SPB Git

Repository Public

google-search.md 11.3 KB 290 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 genai16    from google.genai import types1718    client = genai.Client()1920    grounding_tool = types.Tool(21        google_search=types.GoogleSearch()22    )2324    config = types.GenerateContentConfig(25        tools=[grounding_tool]26    )2728    response = client.models.generate_content(29        model="gemini-3.8-flash",30        contents="Who won the euro 2024?",31        config=config,32    )3334    print(response.text)3536### JavaScript3738    import { GoogleGenAI } from "@google/genai";3940    const ai = new GoogleGenAI({});4142    const groundingTool = {43      googleSearch: {},44    };4546    const config = {47      tools: [groundingTool],48    };4950    const response = await ai.models.generateContent({51      model: "gemini-3.8-flash",52      contents: "Who won the euro 2024?",53      config,54    });5556    console.log(response.text);5758### REST5960    curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \61      -H "x-goog-api-key: $GEMINI_API_KEY" \62      -H "Content-Type: application/json" \63      -X POST \64      -d '{65        "contents": [66          {67            "parts": [68              {"text": "Who won the euro 2024?"}69            ]70          }71        ],72        "tools": [73          {74            "google_search": {}75          }76        ]77      }'7879You can learn more by trying the [Search tool80notebook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Search_Grounding.ipynb).8182## How grounding with Google Search works8384When you enable the `google_search` tool, the model handles the entire workflow85of searching, processing, and citing information automatically.8687![grounding-overview](https://ai.google.dev/static/gemini-api/docs/images/google-search-tool-overview.png)88891. **User Prompt:** Your application sends a user's prompt to the Gemini API with the `google_search` tool enabled.902. **Prompt Analysis:** The model analyzes the prompt and determines if a Google Search can improve the answer.913. **Google Search:** If needed, the model automatically generates one or multiple search queries and executes them.924. **Search Results Processing:** The model processes the search results, synthesizes the information, and formulates a response.935. **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 and `groundingMetadata` with the search queries, web results, and citations.9495## Understanding the grounding response9697When a response is successfully grounded, the response includes a98`groundingMetadata` field. This structured data is essential for verifying99claims and building a rich citation experience in your application.100101    {102      "candidates": [103        {104          "content": {105            "parts": [106              {107                "text": "Spain won Euro 2024, defeating England 2-1 in the final. This victory marks Spain's record fourth European Championship title."108              }109            ],110            "role": "model"111          },112          "groundingMetadata": {113            "webSearchQueries": [114              "UEFA Euro 2024 winner",115              "who won euro 2024"116            ],117            "searchEntryPoint": {118              "renderedContent": "<!-- HTML and CSS for the search widget -->"119            },120            "groundingChunks": [121              {"web": {"uri": "https://vertexaisearch.cloud.google.com.....", "title": "aljazeera.com"}},122              {"web": {"uri": "https://vertexaisearch.cloud.google.com.....", "title": "uefa.com"}}123            ],124            "groundingSupports": [125              {126                "segment": {"startIndex": 0, "endIndex": 85, "text": "Spain won Euro 2024, defeatin..."},127                "groundingChunkIndices": [0]128              },129              {130                "segment": {"startIndex": 86, "endIndex": 210, "text": "This victory marks Spain's..."},131                "groundingChunkIndices": [0, 1]132              }133            ]134          }135        }136      ]137    }138139The Gemini API returns the following information with the `groundingMetadata`:140141- `webSearchQueries` : Array of the search queries used. This is useful for debugging and understanding the model's reasoning process.142- `searchEntryPoint` : Contains the HTML and CSS to render the required Search Suggestions. Full usage requirements are detailed in the [Terms of143  Service](https://ai.google.dev/gemini-api/terms#grounding-with-google-search).144- `groundingChunks` : Array of objects containing the web sources (`uri` and `title`).145- `groundingSupports` : Array of chunks to connect model response `text` to the sources in `groundingChunks`. Each chunk links a text `segment` (defined by `startIndex` and `endIndex`) to one or more `groundingChunkIndices`. This is the key to building inline citations.146147Grounding with Google Search can also be used in combination with the [URL148context tool](https://ai.google.dev/gemini-api/docs/url-context) to ground responses in both public149web data and the specific URLs you provide.150151## Attributing sources with inline citations152153The API returns structured citation data, giving you complete control over how154you display sources in your user interface. You can use the `groundingSupports`155and `groundingChunks` fields to link the model's statements directly to their156sources. Here is a common pattern for processing the metadata to create a157response with inline, clickable citations.158159### Python160161    def add_citations(response):162        text = response.text163        supports = response.candidates[0].grounding_metadata.grounding_supports164        chunks = response.candidates[0].grounding_metadata.grounding_chunks165166        # Sort supports by end_index in descending order to avoid shifting issues when inserting.167        sorted_supports = sorted(supports, key=lambda s: s.segment.end_index, reverse=True)168169        for support in sorted_supports:170            end_index = support.segment.end_index171            if support.grounding_chunk_indices:172                # Create citation string like [1](link1)[2](link2)173                citation_links = []174                for i in support.grounding_chunk_indices:175                    if i < len(chunks):176                        uri = chunks[i].web.uri177                        citation_links.append(f"[{i + 1}]({uri})")178179                citation_string = ", ".join(citation_links)180                text = text[:end_index] + citation_string + text[end_index:]181182        return text183184    # Assuming response with grounding metadata185    text_with_citations = add_citations(response)186    print(text_with_citations)187188### JavaScript189190    function addCitations(response) {191        let text = response.text;192        const supports = response.candidates[0]?.groundingMetadata?.groundingSupports;193        const chunks = response.candidates[0]?.groundingMetadata?.groundingChunks;194195        // Sort supports by end_index in descending order to avoid shifting issues when inserting.196        const sortedSupports = [...supports].sort(197            (a, b) => (b.segment?.endIndex ?? 0) - (a.segment?.endIndex ?? 0),198        );199200        for (const support of sortedSupports) {201            const endIndex = support.segment?.endIndex;202            if (endIndex === undefined || !support.groundingChunkIndices?.length) {203            continue;204            }205206            const citationLinks = support.groundingChunkIndices207            .map(i => {208                const uri = chunks[i]?.web?.uri;209                if (uri) {210                return `[${i + 1}](${uri})`;211                }212                return null;213            })214            .filter(Boolean);215216            if (citationLinks.length > 0) {217            const citationString = citationLinks.join(", ");218            text = text.slice(0, endIndex) + citationString + text.slice(endIndex);219            }220        }221222        return text;223    }224225    const textWithCitations = addCitations(response);226    console.log(textWithCitations);227228The new response with inline citations will look like this:229230    Spain won Euro 2024, defeating England 2-1 in the final.[1](https:/...), [2](https:/...), [4](https:/...), [5](https:/...) This victory marks Spain's record-breaking fourth European Championship title.[5]((https:/...), [2](https:/...), [3](https:/...), [4](https:/...)231232## Pricing233234When you use Grounding with Google Search with Gemini 3, your project is billed235for each search query that the model decides to execute. If the model decides to236execute multiple search queries to answer a single prompt (for example,237searching for `"UEFA Euro 2024 winner"` and `"Spain vs England Euro 2024 final238score"` within the same API call), this counts as two billable uses of the tool239for that request. For billing purposes, we ignore the empty web search queries240when counting unique queries. This billing model only applies to Gemini 3241models; when you use search grounding with Gemini 2.5 or older models, your242project is billed per prompt.243244For detailed pricing information, see the [Gemini API pricing245page](https://ai.google.dev/gemini-api/docs/pricing).246247## Supported models248249You can find full capabilities on the [model250overview](https://ai.google.dev/gemini-api/docs/models) page.251252| Model | Grounding with Google Search |253|---|---|254| Gemini 3.8 Flash | ✔️ |255| Gemini 3.7 Flash | ✔️ |256| Gemini 3.6 Flash | ✔️ |257| Gemini 3.5 Flash-Lite | ✔️ |258| Gemini 3.5 Flash | ✔️ |259| Gemini 3.1 Flash-Lite | ✔️ |260| Gemini 3.1 Flash Image Preview | ✔️ |261| Gemini 3.1 Pro Preview | ✔️ |262| Gemini 3 Pro Image Preview | ✔️ |263| Gemini 3 Flash Preview | ✔️ |264| Gemini 3.1 Flash-Lite Preview | ✔️ |265| Gemini 2.5 Pro | ✔️ |266| Gemini 2.5 Flash | ✔️ |267| Gemini 2.5 Flash-Lite | ✔️ |268| Gemini 2.0 Flash | ✔️ |269270> [!NOTE]271> **Note:** Older models use a `google_search_retrieval` tool. For all current models, use the `google_search` tool as shown in the examples.272273## Supported tool combinations274275You can use Grounding with Google Search with other tools like276[code execution](https://ai.google.dev/gemini-api/docs/code-execution),277[URL context](https://ai.google.dev/gemini-api/docs/url-context), and278[Grounding with Google Maps](https://ai.google.dev/gemini-api/docs/maps-grounding) (supported on279Gemini 3.5 Flash and later models) to power more complex use cases. Gemini 3280models also support combining these built-in tools with custom tools (function281calling). Learn more on the282[tool combinations](https://ai.google.dev/gemini-api/docs/tool-combination) page.283284## What's next285286- Try the [Grounding with Google Search in the Gemini API287  Cookbook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Search_Grounding.ipynb).288- Learn about other available tools, like [Function Calling](https://ai.google.dev/gemini-api/docs/function-calling).289- Learn how to augment prompts with specific URLs using the [URL context290  tool](https://ai.google.dev/gemini-api/docs/url-context).
Files main
Menu

Theme