الأساسيات باستخدام "بحث Google"

تتيح ميزة "تحديد المصدر من خلال بحث Search" ربط نموذج Gemini بمحتوى على الويب في الوقت الفعلي، وهي تعمل بجميع اللغات المتاحة. يتيح ذلك لـ Gemini تقديم إجابات أكثر دقة والإشارة إلى مصادر يمكن التحقّق منها بعد تاريخ آخر تحديث للبيانات.

تساعدك ميزة "تحديد المصدر" في إنشاء تطبيقات يمكنها إجراء ما يلي:

  • زيادة الدقة الوقائعية: تقليل حالات الهلوسة في النموذج من خلال الاستناد في الردود إلى معلومات واقعية
  • الوصول إلى المعلومات في الوقت الفعلي: الإجابة عن الأسئلة حول الأحداث والمواضيع الحديثة
  • تقديم الاقتباسات: تعزيز ثقة المستخدمين من خلال عرض مصادر ادعاءات النموذج

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input="Who won the euro 2024?",
    tools=[{"type": "google_search"}]
)

print(interaction.output_text)

JavaScript

import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: "gemini-3.8-flash",
    input: "Who won the euro 2024?",
    tools: [{ type: "google_search" }]
});

console.log(interaction.output_text);

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("Who won the euro 2024?"))
        .tools(Arrays.asList(GoogleSearch.builder().build()))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

انتقال

package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    resp, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(
            interactions.CreateModelInteraction{
                Model: interactions.Model("gemini-3.8-flash"),
                Input: interactions.NewInteractionsInput("Who won the euro 2024?"),
                Tools: []interactions.Tool{
                    interactions.NewTool(interactions.GoogleSearch{}),
                },
            },
        ),
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(resp.Interaction.GetOutputText())
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3.8-flash",
    "input": "Who won the euro 2024?",
    "tools": [{"type": "google_search"}]
  }'

آلية عمل ميزة "تحديد المصدر من خلال بحث Google"

عند تفعيل أداة google_search، يعالج النموذج تلقائيًا سير العمل بالكامل للبحث عن المعلومات ومعالجتها والاقتباس منها.

grounding-overview

  1. طلب المستخدِم: يرسل تطبيقك طلب مستخدِم إلى Gemini API مع تفعيل أداة google_search.
  2. تحليل الطلب: يحلّل النموذج الطلب ويحدّد ما إذا كان بإمكان "بحث Google" تحسين الإجابة.
  3. بحث Google: إذا لزم الأمر، ينشئ النموذج تلقائيًا طلب بحث واحدًا أو أكثر ويُنفّذها.
  4. معالجة نتائج البحث: يعالج النموذج نتائج البحث ويُركّب المعلومات ويُنشئ ردًا.
  5. الرد المستند إلى نتائج البحث: تعرض واجهة برمجة التطبيقات ردًا نهائيًا سهل الاستخدام يستند إلى نتائج البحث. يتضمّن هذا الرد إجابة نصية من النموذج مع annotations مضمّنة تحتوي على الاقتباسات، بالإضافة إلى خطوات google_search_call وgoogle_search_result التي تتضمّن طلبات البحث واقتراحات البحث.

فهم الرد المستند إلى نتائج البحث

عندما يستند الرد بنجاح إلى نتائج البحث، يتضمّن الناتج النصي للنموذج annotations مضمّنة مباشرةً في كتلة المحتوى النصي. تقدّم هذه الشروح التوضيحية معلومات الاقتباس التي تربط أجزاء من الرد بمصادرها.

{
  "steps": [
    {
      "type": "thought",
      "summary": [
        {
          "type": "text",
          "text": "The user is asking for the winner of Euro 2024. I need to search for the result of the Euro 2024 final."
        }
      ],
      "signature": "CoMDAXLI2nynRYojJIy6B1Jh9os2crpWLfB0..."
    },
    {
      "type": "google_search_call",
      "arguments": {
        "queries": ["UEFA Euro 2024 winner"]
      }
    },
    {
      "type": "google_search_result",
      "call_id": "search_001",
      "result": [
        {
          "search_suggestions": "<!-- HTML and CSS for the search widget -->"
        }
      ]
    },
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "Spain won Euro 2024, defeating England 2-1 in the final. This victory marks Spain's record fourth European Championship title.",
          "annotations": [
            {
              "type": "url_citation",
              "url": "https://www.aljazeera.com/sports/euro-2024-final",
              "title": "aljazeera.com",
              "start_index": 0,
              "end_index": 56
            },
            {
              "type": "url_citation",
              "url": "https://www.uefa.com/euro2024/news/spain-wins-euro-2024",
              "title": "uefa.com",
              "start_index": 57,
              "end_index": 124
            }
          ]
        }
      ]
    }
  ]
}

الحقول الرئيسية في الرد:

  • google_search_call : يحتوي على queries البحث التي نفّذها النموذج.
  • google_search_result : يحتوي على search_suggestions، وهي مقتطف HTML لعرض اقتراحات البحث في واجهة المستخدم. يتم تفصيل متطلبات الاستخدام الكاملة في بنود الخدمة.
  • text مع annotations : الإجابة المُركّبة من النموذج مع الاقتباسات المضمّنة يربط كل شرح توضيحي url_citation جزءًا من النص (محدّدًا من خلال start_index وend_index) بعنوان URL للمصدر. هذا هو المفتاح لإنشاء اقتباسات مضمّنة.

يمكن أيضًا استخدام ميزة "تحديد المصدر من خلال بحث Google" مع أداة سياق عنوان URL لتحديد مصدر الردود في كلّ من بيانات الويب العلنية وعناوين URL المحدّدة التي تقدّمها.

الإشارة إلى المصادر باستخدام الاقتباسات المضمّنة

تعرض واجهة برمجة التطبيقات شروحًا توضيحية مضمّنة من نوع url_citation في كتلة المحتوى النصي، ما يمنحك تحكّمًا كاملاً في طريقة عرض المصادر في واجهة المستخدم. يتضمّن كل شرح توضيحي start_index وend_index لتحديد جزء النص الذي يشير إليه. إليك كيفية استخراجها وعرضها.

Python

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
                if content_block.annotations:
                    print("\nCitations:")
                    for annotation in content_block.annotations:
                        if annotation.type == "url_citation":
                            cited_text = content_block.text[annotation.start_index:annotation.end_index]
                            print(f"  [{annotation.title}]({annotation.url})")
                            print(f"    Cited text: \"{cited_text}\"")

JavaScript

for (const step of interaction.steps) {
  if (step.type === 'model_output') {
    for (const contentBlock of step.content) {
      if (contentBlock.type === 'text') {
        console.log(contentBlock.text);
        if (contentBlock.annotations) {
          console.log("\nCitations:");
          for (const annotation of contentBlock.annotations) {
            if (annotation.type === 'url_citation') {
              const citedText = contentBlock.text.slice(annotation.startIndex, annotation.endIndex);
              console.log(`  [${annotation.title}](${annotation.url})`);
              console.log(`    Cited text: "${citedText}"`);
            }
          }
        }
      }
    }
  }
}

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Annotation;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.URLCitation;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.of("Who won the euro 2024?"))
        .tools(Arrays.asList(GoogleSearch.builder().build()))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            TextContent textContent = (TextContent) contentBlock;
            String text = textContent.text().orElse("");
            System.out.println(text);
            if (textContent.annotations().isPresent()
                && !textContent.annotations().get().isEmpty()) {
              System.out.println("\nCitations:");
              for (Annotation annotation : textContent.annotations().get()) {
                if (annotation instanceof URLCitation) {
                  URLCitation citation = (URLCitation) annotation;
                  int start = citation.startIndex().orElse(0);
                  int end = citation.endIndex().orElse(0);
                  String citedText =
                      (start >= 0 && end <= text.length() && start <= end)
                          ? text.substring(start, end)
                          : "";
                  System.out.printf(
                      "  [%s](%s)%n", citation.title().orElse(""), citation.url().orElse(""));
                  System.out.printf("    Cited text: \"%s\"%n", citedText);
                }
              }
            }
          }
        }
      }
    }
  }
}

انتقال

package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    resp, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(
            interactions.CreateModelInteraction{
                Model: interactions.Model("gemini-3.8-flash"),
                Input: interactions.NewInteractionsInput("Who won the euro 2024?"),
                Tools: []interactions.Tool{
                    interactions.NewTool(interactions.GoogleSearch{}),
                },
            },
        ),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range resp.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, content := range step.ModelOutputStep.Content {
                if content.TextContent != nil {
                    text := content.TextContent.Text
                    fmt.Println(text)
                    if len(content.TextContent.Annotations) > 0 {
                        fmt.Println("\nCitations:")
                        for _, annotation := range content.TextContent.Annotations {
                            if annotation.URLCitation != nil {
                                c := annotation.URLCitation
                                start := 0
                                if c.StartIndex != nil {
                                    start = *c.StartIndex
                                }
                                end := 0
                                if c.EndIndex != nil {
                                    end = *c.EndIndex
                                }
                                citedText := ""
                                if start >= 0 && end <= len(text) && start <= end {
                                    citedText = text[start:end]
                                }
                                title := ""
                                if c.Title != nil {
                                    title = *c.Title
                                }
                                url := ""
                                if c.URL != nil {
                                    url = *c.URL
                                }
                                fmt.Printf("  [%s](%s)\n", title, url)
                                fmt.Printf("    Cited text: %q\n", citedText)
                            }
                        }
                    }
                }
            }
        }
    }
}

سيعرض الناتج النص متبوعًا بالاقتباسات:

Spain won Euro 2024, defeating England 2-1 in the final. This victory marks Spain's record fourth European Championship title.

Citations:
  [aljazeera.com](https://www.aljazeera.com/sports/euro-2024-final)
    Cited text: "Spain won Euro 2024, defeating England 2-1 in the final."
  [uefa.com](https://www.uefa.com/euro2024/news/spain-wins-euro-2024)
    Cited text: "This victory marks Spain's record fourth European Championship title."

الأسعار

عند استخدام ميزة "تحديد المصدر من خلال بحث Google" مع Gemini 3 والنماذج الأحدث، يتم تحصيل رسوم من مشروعك مقابل كل استعلام بحث يقرّر النموذج تنفيذه. يتضمّن نموذج الفوترة هذا لكل استعلام 5,000 طلب بحث مجاني شهريًا تتم مشاركتها بين جميع نماذج Gemini 3 والنماذج الأحدث، ثم تبلغ التكلفة 14 دولارًا أمريكيًا لكل 1,000 طلب بحث.

على سبيل المثال، إذا قرّر النموذج تنفيذ طلبات بحث متعددة للردّ على طلب واحد (مثل البحث عن "UEFA Euro 2024 winner" و"Spain vs England Euro 2024 final score" ضمن طلب بيانات من واجهة برمجة التطبيقات نفسه)، يتم احتساب ذلك على أنّه استخدامان قابلان للفوترة للأداة لهذا الطلب. لأغراض الفوترة، نتجاهل طلبات البحث الفارغة على الويب عند احتساب الطلبات الفريدة.

عند استخدام ميزة "تحديد المصدر من خلال البحث" مع Gemini 2.5 أو النماذج الأقدم، يتم تحصيل رسوم من مشروعك لكل طلب.

للحصول على معلومات مفصّلة عن الأسعار، يُرجى الاطّلاع على صفحة أسعار Gemini API.

النماذج المتوافقة

يمكنك الاطّلاع على الإمكانات الكاملة في صفحة نظرة عامة على النموذج.

الطراز تحديد المصدر من خلال "بحث Search"
Gemini 4 Argon ✔️
Gemini 3.8 Flash ✔️
Gemini 3.6 Flash ✔️
Gemini 3.5 Flash-Lite ✔️
Gemini 3.1 Flash Image Preview ✔️
Gemini 3.1 Pro Preview ✔️
Gemini 3 Pro Image Preview ✔️
Gemini 3 Flash Preview ✔️
Gemini 2.5 Pro ✔️
Gemini 2.5 Flash ✔️
Gemini 2.5 Flash-Lite ✔️
Gemini 2.0 Flash ✔️

مجموعات الأدوات المتوافقة

يمكنك استخدام ميزة "تحديد المصدر من خلال بحث Google" مع أدوات أخرى، مثل تنفيذ التعليمات البرمجية، و سياق عنوان URL، و ميزة "تحديد المصدر من خلال خرائط Google" (المتوفرة في Gemini 3.5 Flash-Lite والنماذج الأحدث) لتعزيز حالات الاستخدام الأكثر تعقيدًا. تتيح نماذج Gemini 3 أيضًا دمج هذه الأدوات المضمّنة مع الأدوات المخصّصة (استدعاء الدوال). مزيد من المعلومات في صفحة مجموعات الأدوات

الخطوات التالية