SPB Git

Repository Public

google-search.md 13.8 KB 332 lines markdown

1Grounding with Google Search connects the Gemini model to real-time web content2and works with all available languages. This allows3Gemini to provide more accurate answers and cite verifiable sources beyond its4knowledge cutoff.56Grounding helps you build applications that can:78- **Increase factual accuracy:** Reduce model hallucinations by basing responses on real-world information.9- **Access real-time information:** Answer questions about recent events and topics.10- **Provide citations:** Build user trust by showing the sources for the11  model's claims.1213### Python1415    from google import genai1617    client = genai.Client()1819    interaction = client.interactions.create(20        model="gemini-3.8-flash",21        input="Who won the euro 2024?",22        tools=[{"type": "google_search"}]23    )2425    print(interaction.output_text)2627### JavaScript2829    import { GoogleGenAI } from "@google/genai";3031    const client = new GoogleGenAI({});3233    const interaction = await client.interactions.create({34        model: "gemini-3.8-flash",35        input: "Who won the euro 2024?",36        tools: [{ type: "google_search" }]37    });3839    console.log(interaction.output_text);4041### Java4243    import com.google.genai.Client;44    import com.google.genai.gaos.models.interactions.CreateModelInteraction;45    import com.google.genai.gaos.models.interactions.GoogleSearch;46    import com.google.genai.gaos.models.interactions.Interaction;47    import com.google.genai.gaos.models.interactions.InteractionsInput;48    import com.google.genai.gaos.models.interactions.Model;49    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;50    import java.util.Arrays;5152    Client client = new Client();5354    CreateModelInteraction params =55        CreateModelInteraction.builder()56            .model(Model.of("gemini-3.8-flash"))57            .input(InteractionsInput.of("Who won the euro 2024?"))58            .tools(Arrays.asList(GoogleSearch.builder().build()))59            .build();6061    Interaction interaction =62        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();6364    System.out.println(interaction.outputText().orElse(""));6566### REST6768    curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \69      -H "x-goog-api-key: $GEMINI_API_KEY" \70      -H "Content-Type: application/json" \71      -d '{72        "model": "gemini-3.8-flash",73        "input": "Who won the euro 2024?",74        "tools": [{"type": "google_search"}]75      }'7677## How grounding with Google Search works7879When you enable the `google_search` tool, the model handles the entire workflow80of searching, processing, and citing information automatically.8182![grounding-overview](https://ai.google.dev/static/gemini-api/docs/images/google-search-tool-overview.png)83841. **User Prompt:** Your application sends a user's prompt to the Gemini API with the `google_search` tool enabled.852. **Prompt Analysis:** The model analyzes the prompt and determines if a Google Search can improve the answer.863. **Google Search:** If needed, the model automatically generates one or multiple search queries and executes them.874. **Search Results Processing:** The model processes the search results, synthesizes the information, and formulates a response.885. **Grounded Response:** The API returns a final, user-friendly response that is grounded in the search results. This response includes the model's text answer with inline `annotations` containing the citations, as well as `google_search_call` and `google_search_result` steps with the search queries and search suggestions.8990## Understanding the grounding response9192When a response is successfully grounded, the model's text output includes93inline `annotations` directly on the text content block. These annotations94provide citation information linking parts of the response to their sources.9596    {97      "steps": [98        {99          "type": "thought",100          "summary": [101            {102              "type": "text",103              "text": "The user is asking for the winner of Euro 2024. I need to search for the result of the Euro 2024 final."104            }105          ],106          "signature": "CoMDAXLI2nynRYojJIy6B1Jh9os2crpWLfB0..."107        },108        {109          "type": "google_search_call",110          "arguments": {111            "queries": ["UEFA Euro 2024 winner"]112          }113        },114        {115          "type": "google_search_result",116          "call_id": "search_001",117          "result": [118            {119              "search_suggestions": "<!-- HTML and CSS for the search widget -->"120            }121          ]122        },123        {124          "type": "model_output",125          "content": [126            {127              "type": "text",128              "text": "Spain won Euro 2024, defeating England 2-1 in the final. This victory marks Spain's record fourth European Championship title.",129              "annotations": [130                {131                  "type": "url_citation",132                  "url": "https://www.aljazeera.com/sports/euro-2024-final",133                  "title": "aljazeera.com",134                  "start_index": 0,135                  "end_index": 56136                },137                {138                  "type": "url_citation",139                  "url": "https://www.uefa.com/euro2024/news/spain-wins-euro-2024",140                  "title": "uefa.com",141                  "start_index": 57,142                  "end_index": 124143                }144              ]145            }146          ]147        }148      ]149    }150151The key fields in the response:152153- `google_search_call` : Contains the search `queries` the model executed.154- `google_search_result` : Contains `search_suggestions`, an HTML snippet for rendering search suggestions in your UI. Full usage requirements are detailed in the [Terms of Service](https://ai.google.dev/gemini-api/terms#grounding-with-google-search).155- `text` with `annotations` : The model's synthesized answer with inline citations. Each `url_citation` annotation links a text segment (defined by `start_index` and `end_index`) to a source URL. This is the key to building inline citations.156157Grounding with Google Search can also be used in combination with the [URL158context tool](https://ai.google.dev/gemini-api/docs/url-context) to ground responses in159both public web data and the specific URLs you provide.160161## Attributing sources with inline citations162163The API returns inline `url_citation` annotations on the text content block,164giving you complete control over how you display sources in your user interface.165Each annotation includes `start_index` and `end_index` to identify which part166of the text it cites. Here's how to extract and display them.167168### Python169170    for step in interaction.steps:171        if step.type == "model_output":172            for content_block in step.content:173                if content_block.type == "text":174                    print(content_block.text)175                    if content_block.annotations:176                        print("\nCitations:")177                        for annotation in content_block.annotations:178                            if annotation.type == "url_citation":179                                cited_text = content_block.text[annotation.start_index:annotation.end_index]180                                print(f"  [{annotation.title}]({annotation.url})")181                                print(f"    Cited text: \"{cited_text}\"")182183### JavaScript184185    for (const step of interaction.steps) {186      if (step.type === 'model_output') {187        for (const contentBlock of step.content) {188          if (contentBlock.type === 'text') {189            console.log(contentBlock.text);190            if (contentBlock.annotations) {191              console.log("\nCitations:");192              for (const annotation of contentBlock.annotations) {193                if (annotation.type === 'url_citation') {194                  const citedText = contentBlock.text.slice(annotation.startIndex, annotation.endIndex);195                  console.log(`  [${annotation.title}](${annotation.url})`);196                  console.log(`    Cited text: "${citedText}"`);197                }198              }199            }200          }201        }202      }203    }204205### Java206207    import com.google.genai.Client;208    import com.google.genai.gaos.models.interactions.Annotation;209    import com.google.genai.gaos.models.interactions.Content;210    import com.google.genai.gaos.models.interactions.CreateModelInteraction;211    import com.google.genai.gaos.models.interactions.GoogleSearch;212    import com.google.genai.gaos.models.interactions.Interaction;213    import com.google.genai.gaos.models.interactions.InteractionsInput;214    import com.google.genai.gaos.models.interactions.Model;215    import com.google.genai.gaos.models.interactions.ModelOutputStep;216    import com.google.genai.gaos.models.interactions.Step;217    import com.google.genai.gaos.models.interactions.TextContent;218    import com.google.genai.gaos.models.interactions.URLCitation;219    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;220    import java.util.Arrays;221222    Client client = new Client();223224    CreateModelInteraction params =225        CreateModelInteraction.builder()226            .model(Model.of("gemini-3.8-flash"))227            .input(InteractionsInput.of("Who won the euro 2024?"))228            .tools(Arrays.asList(GoogleSearch.builder().build()))229            .build();230231    Interaction interaction =232        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();233234    if (interaction.steps().isPresent()) {235      for (Step step : interaction.steps().get()) {236        if (step instanceof ModelOutputStep) {237          ModelOutputStep outputStep = (ModelOutputStep) step;238          if (outputStep.content().isPresent()) {239            for (Content contentBlock : outputStep.content().get()) {240              if (contentBlock instanceof TextContent) {241                TextContent textContent = (TextContent) contentBlock;242                String text = textContent.text().orElse("");243                System.out.println(text);244                if (textContent.annotations().isPresent()245                    && !textContent.annotations().get().isEmpty()) {246                  System.out.println("\nCitations:");247                  for (Annotation annotation : textContent.annotations().get()) {248                    if (annotation instanceof URLCitation) {249                      URLCitation citation = (URLCitation) annotation;250                      int start = citation.startIndex().orElse(0);251                      int end = citation.endIndex().orElse(0);252                      String citedText =253                          (start >= 0 && end <= text.length() && start <= end)254                              ? text.substring(start, end)255                              : "";256                      System.out.printf(257                          "  [%s](%s)%n", citation.title().orElse(""), citation.url().orElse(""));258                      System.out.printf("    Cited text: \"%s\"%n", citedText);259                    }260                  }261                }262              }263            }264          }265        }266      }267    }268269The output will show the text followed by its citations:270271    Spain won Euro 2024, defeating England 2-1 in the final. This victory marks Spain's record fourth European Championship title.272273    Citations:274      [aljazeera.com](https://www.aljazeera.com/sports/euro-2024-final)275        Cited text: "Spain won Euro 2024, defeating England 2-1 in the final."276      [uefa.com](https://www.uefa.com/euro2024/news/spain-wins-euro-2024)277        Cited text: "This victory marks Spain's record fourth European Championship title."278279## Pricing280281When you use Grounding with Google Search with Gemini 3, your project is billed282for each search query that the model decides to execute. If the model decides to283execute multiple search queries to answer a single prompt (for example,284searching for `"UEFA Euro 2024 winner"` and `"Spain vs England Euro 2024 final285score"` within the same API call), this counts as two billable uses of the tool286for that request. For billing purposes, we ignore the empty web search queries287when counting unique queries. This billing model only applies to Gemini 3288models; when you use search grounding with Gemini 2.5 or older models, your289project is billed per prompt.290291For detailed pricing information, see the [Gemini API pricing292page](https://ai.google.dev/gemini-api/docs/pricing).293294## Supported models295296You can find full capabilities on the [model297overview](https://ai.google.dev/gemini-api/docs/models) page.298299| Model | Grounding with Google Search |300|---|---|301| Gemini 3.8 Flash | ✔️ |302| Gemini 3.7 Flash | ✔️ |303| Gemini 3.6 Flash | ✔️ |304| Gemini 3.5 Flash-Lite | ✔️ |305| Gemini 3.5 Flash | ✔️ |306| Gemini 3.1 Flash Image Preview | ✔️ |307| Gemini 3.1 Pro Preview | ✔️ |308| Gemini 3 Pro Image Preview | ✔️ |309| Gemini 3 Flash Preview | ✔️ |310| Gemini 2.5 Pro | ✔️ |311| Gemini 2.5 Flash | ✔️ |312| Gemini 2.5 Flash-Lite | ✔️ |313| Gemini 2.0 Flash | ✔️ |314315> [!NOTE]316> **Note:** Older models use a `google_search_retrieval` tool. For all current models, use the `google_search` tool as shown in the examples.317318## Supported tool combinations319320You can use Grounding with Google Search with other tools like321[code execution](https://ai.google.dev/gemini-api/docs/code-execution),322[URL context](https://ai.google.dev/gemini-api/docs/url-context), and323[Grounding with Google Maps](https://ai.google.dev/gemini-api/docs/maps-grounding) (supported on324Gemini 3.5 Flash and later models) to power more complex use cases. Gemini 3325models also support combining these built-in tools with custom tools (function326calling). Learn more on the327[tool combinations](https://ai.google.dev/gemini-api/docs/tool-combination) page.328329## What's next330331- Learn about other available tools, like [Function Calling](https://ai.google.dev/gemini-api/docs/function-calling).332- Learn how to augment prompts with specific URLs using the [URL context tool](https://ai.google.dev/gemini-api/docs/url-context).
Files main
Menu

Theme