# 使用 Google 搜索提供事实依据

事实依据与 Google 搜索将 Gemini 模型连接到实时 Web 内容，并适用于所有可用语言。这使得 Gemini 能够提供更准确的答案，并引用超出其知识范围的可验证来源。

事实依据帮助您构建能够：

* **提高事实准确性：** 通过基于现实世界信息的响应来减少模型幻觉。

* **获取实时信息：** 回答有关最近事件和主题的问题。

* **提供引用：** 通过显示模型声明的来源来建立用户信任。

{% tabs %}
{% tab label="Python" %}
```python
from google import genai

client = genai.Client()

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

print(interaction.output_text)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

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

console.log(interaction.output_text);
```
{% /tab %}

{% tab label="Java" %}
```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-4-hydrogen"))
        .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(""));
```
{% /tab %}

{% tab label="Go" %}
```go
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-4-hydrogen"),
                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())
}
```
{% /tab %}

{% tab label="REST" %}
```shell
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Api-Revision: 2026-05-20" \
  -d '{
    "model": "gemini-4-hydrogen",
    "input": "Who won the euro 2024?",
    "tools": [{"type": "google_search"}]
  }'
```
{% /tab %}
{% /tabs %}

## 事实依据与 Google 搜索的工作原理  {% #how-it-works %}

当您启用 `google_search` 工具，该模型自动处理搜索、处理和引用信息的整个工作流程。

![](https://www.gstatic.com/cloud-cms/0c893db002557e538dbe4c9afe8f5abf.png)

1. **用户提示：** 您的应用程序将用户提示发送到 Gemini API，其中包含 `google_search` 工具已启用。

1. **提示分析：** 该模型分析提示并确定 Google 搜索是否可以改进答案。

1. **Google 搜索：** 如果需要，该模型会自动生成一个或多个搜索查询并执行它们。

1. **搜索结果处理：** 该模型处理搜索结果、综合信息并制定响应。

1. **提供事实依据响应：** API 返回基于搜索结果的最终用户友好响应。此响应包括模型的内联文本答案 `annotations` 包含引文，以及 `google_search_call` 和 `google_search_result` 搜索查询和搜索建议的步骤。

## 了解事实依据响应  {% #understanding-the-grounding-response %}

当响应成功提供事实依据时，模型的文本输出包括内联 `annotations` 直接在文本内容块上。这些注释提供了将部分响应与其来源链接起来的引用信息。

```json
{
  "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`，用于在 UI 中呈现搜索建议的 HTML 片段。完整的使用要求详见 [服务条款](/docs/terms#grounding-with-google-search).

* `text` 使用 `annotations` ：模型的综合答案以及内嵌引用。每个 `url_citation` 注释链接文本段（定义为 `start_index` 和 `end_index`) 到源 URL。这是建立内联引用的关键。

事实依据与 Google 搜索还可以与 [URL上下文工具](/docs/url-context) 公共网络数据和您提供的特定 URL 中的地面响应。

## 通过内嵌引用来确定来源  {% #attributing-sources-with-inline-citations %}

API 内联返回 `url_citation` 文本内容块上的注释，使您可以完全控制如何在用户界面中显示源。每个注释包括 `start_index` 和 `end_index` 以确定它引用了文本的哪一部分。以下是提取和显示它们的方法。

{% tabs %}
{% tab label="Python" %}
```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}\"")
```
{% /tab %}

{% tab label="JavaScript" %}
```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}"`);
            }
          }
        }
      }
    }
  }
}
```
{% /tab %}

{% tab label="Java" %}
```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-4-hydrogen"))
        .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);
                }
              }
            }
          }
        }
      }
    }
  }
}
```
{% /tab %}

{% tab label="Go" %}
```go
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-4-hydrogen"),
                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)
                            }
                        }
                    }
                }
            }
        }
    }
}
```
{% /tab %}
{% /tabs %}

输出将显示文本及其引用：

```none
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."
```

## 价格  {% #pricing %}

当您将事实依据与 Google 搜索与 Gemini 3 及更新型号一起使用时，您的项目将按 **每个** 模型决定执行的搜索查询。这种按查询计费模型包括所有 Gemini 3 和更新型号之间共享的每月 5,000 免费搜索请求，然后是成本 **$14 每个 1,000 搜索请求**.

例如，如果模型决定执行多个搜索查询来回答单个提示（例如搜索 `"UEFA Euro 2024 winner"` 和 `"Spain vs England Euro 2024 final score"` 在同一个 API 调用中），这算作该请求对该工具的两次计费使用。出于计费目的，我们在计算唯一查询时忽略空的网络搜索查询。

当您将搜索事实依据与 Gemini 2.5 或旧型号一起使用时，您的项目将按提示计费。

有关详细定价信息，请参阅 [Gemini API 定价页面](/docs/pricing).

{% callout type="note" %}
**注意：** 事实依据和 Google 搜索的默认限制为 **1,500 每日请求数 (RPD)** Gemini 3 和 Gemini 开发者 API 付费层中较新型号的每个项目。如果您的申请需要更高的每日限额，请在 [Google AI Studio](https://aistudio.google.com/rate-limit) （选择 **申请更多配额** 旁边的 `generate_content_search_request_paid` 限制）。
{% /callout %}

## 支持的模型  {% #supported-models %}

您可以在以下位置找到完整功能 [型号概览](/docs/models) 页。

| 模型                             | 使用 Google 搜索提供事实依据 |
| ------------------------------ | ------------------ |
| Gemini 4 Carbon                | ✔️                 |
| Gemini 4 Argon                 | ✔️                 |
| Gemini 4 Hydrogen              | ✔️                 |
| 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               | ✔️                 |

{% callout type="note" %}
较旧的型号使用 `google_search_retrieval` 工具。对于所有当前型号，请使用 `google_search` 工具如示例所示。
{% /callout %}

## 支持的工具组合  {% #tool-combination %}

您可以将事实依据与 Google 搜索以及其他工具一起使用，例如 [代码执行](/docs/code-execution), [URL 上下文](/docs/url-context), 和 [使用 Google 地图提供事实依据](/docs/maps-grounding) （在 Gemini 3.5 Flash 及更高版本上受支持）为更复杂的用例提供支持。 Gemini 4 和 Gemini 3 型号还支持将这些内置工具与自定义工具 (函数调用) 相结合。了解更多信息 [工具组合](/docs/tool-combination) 页。

## 后续步骤  {% #whats-next %}

* 了解其他可用工具，例如 [函数调用](/docs/function-calling).
* 了解如何使用特定 URL 来增强提示 [URL上下文工具](/docs/url-context).
