# URL 上下文

URL 上下文工具允许您以 URL 的形式为模型提供附加上下文。通过在请求中包含 URL，模型将访问这些页面中的内容（只要它不是列表中列出的 URL 类型） [限制部分](/docs/url-context#limitations)）以告知并加强其响应。

URL 上下文工具对于以下任务非常有用：

* **提取数据**：从多个 URL 中提取特定信息，例如价格、名称或主要发现。

* **比较文档**：分析多个报告、文章或 PDF 以识别差异并跟踪趋势。

* **合成和创建内容**：组合来自多个源 URL 的信息以生成准确的摘要、博客文章或报告。

* **分析代码和文档**：指向 GitHub 存储库或技术文档来解释代码、生成设置说明或回答问题。

## 比较两个页面  {% class="hide-from-toc" #get-started %}

以下示例显示如何比较来自不同网站的两个食谱。

{% tabs %}
{% tab label="Python" %}
```python
# This will only work for SDK newer than 2.0.0
from google import genai

client = genai.Client()

url1 = "https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592"
url2 = "https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/"

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=f"Compare the ingredients and cooking times from the recipes at {url1} and {url2}",
    tools=[{"type": "url_context"}]
)

# Print the model's text response and its source annotations
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("\nSources:")
                    for annotation in content_block.annotations:
                        if annotation.type == "url_citation":
                            print(f" - {annotation.title}: {annotation.url}")
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

async function main() {
  const interaction = await client.interactions.create({
    model: "gemini-4-hydrogen",
    input: "Compare the ingredients and cooking times from the recipes at https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592 and https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/",
    tools: [{ type: "url_context" }]
  });

  // Print the model's text response and its source annotations
  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("\nSources:");
            for (const annotation of contentBlock.annotations) {
              if (annotation.type === 'url_citation') {
                console.log(` - ${annotation.title}: ${annotation.url}`);
              }
            }
          }
        }
      }
    }
  }
}

await main();
```
{% /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)
    }

    url1 := "https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592"
    url2 := "https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/"

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-4-hydrogen"),
            Input: interactions.NewInteractionsInput(
                fmt.Sprintf("Compare the ingredients and cooking times from the recipes at %s and %s", url1, url2),
            ),
            Tools: []interactions.Tool{
                interactions.NewTool(interactions.URLContext{}),
            },
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    // Print the model's text response and its source annotations
    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                    if len(contentBlock.TextContent.Annotations) > 0 {
                        fmt.Println("\nSources:")
                        for _, annotation := range contentBlock.TextContent.Annotations {
                            if annotation.URLCitation != nil {
                                fmt.Printf("  - %s: %s\n", annotation.URLCitation.GetTitle(), annotation.URLCitation.GetURL())
                            }
                        }
                    }
                }
            }
        }
    }
}
```
{% /tab %}

{% tab label="REST" %}
```shell
# Specifies the API revision to avoid breaking changes when they become default
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": "Compare the ingredients and cooking times from the recipes at https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592 and https://www.allrecipes.com/recipe/21151/simple-whole-roast-chicken/",
    "tools": [{"type": "url_context"}]
}'
```
{% /tab %}
{% /tabs %}

## 它是如何运作的  {% #how-it-works %}

URL 上下文工具使用两步检索过程来平衡速度、成本和对新数据的访问。当您提供 URL 时，该工具首先尝试从内部索引缓存中获取内容。这充当高度优化的缓存。如果索引中没有可用的 URL（例如，如果它是一个非常新的页面），该工具会自动回退以执行实时获取。这会直接访问 URL 以实时检索其内容。

## 与其他工具结合  {% #code-examples-with-search %}

您可以将 URL 上下文工具与其他工具结合起来创建更强大的工作流程。

[Gemini 3型号](/docs/url-context#supported-models) 支持将内置工具（如 URL 上下文）与自定义工具（函数调用）相结合。了解更多信息 [工具组合](/docs/tool-combination) 页。

### 事实依据带搜索  {% #grounding-with-search %}

当 URL 上下文和 [使用 Google 搜索提供事实依据](/docs/google-search) 启用后，模型可以使用其搜索功能在线查找相关信息，然后使用 URL 上下文工具更深入地了解它找到的页面。对于需要对特定页面进行广泛搜索和深入分析的提示，此方法非常有效。

{% tabs %}
{% tab label="Python" %}
```python
# This will only work for SDK newer than 2.0.0
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Give me three day events schedule based on {{'YOUR_URL'}}. Also let me know what needs to taken care of considering weather and commute.",
    tools=[
        {"type": "url_context"},
        {"type": "google_search"}
    ]
)

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)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
// This will only work for SDK newer than 2.0.0
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

async function main() {
  const interaction = await client.interactions.create({
    model: "gemini-4-hydrogen",
    input: "Give me three day events schedule based on {{'YOUR_URL'}}. Also let me know what needs to taken care of considering weather and commute.",
    tools: [
      { type: "url_context" },
      { type: "google_search" }
    ]
  });

  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);
      }
    }
  }
}

await main();
```
{% /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)
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-4-hydrogen"),
            Input: interactions.NewInteractionsInput("Give me three day events schedule based on YOUR_URL. Also let me know what needs to taken care of considering weather and commute."),
            Tools: []interactions.Tool{
                interactions.NewTool(interactions.URLContext{}),
                interactions.NewTool(interactions.GoogleSearch{}),
            },
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                }
            }
        }
    }
}
```
{% /tab %}

{% tab label="REST" %}
```shell
# Specifies the API revision to avoid breaking changes when they become default
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": "Give me three day events schedule based on {{'YOUR_URL'}}. Also let me know what needs to taken care of considering weather and commute.",
      "tools": [
          {"type": "url_context"},
          {"type": "google_search"}
      ]
  }'
```
{% /tab %}
{% /tabs %}

## 了解响应  {% #contextual-response %}

当模型使用 URL 上下文工具时，其文本响应包括内联 `url_citation` 文本内容块上的注释。每个注释链接响应文本的一部分（通过 `start_index` 和 `end_index`) 到它派生的源 URL。这是在您的申请中显示引用的主要方式 - 请参阅 [上面的主要例子](/docs/url-context#get-started) 了解如何提取它们。

该响应还包括 `url_context_result` 步骤包含有关每个 URL 检索尝试的元数据（状态、检索到的 URL）。这主要用于调试。

### 安全检查  {% #safety-checks %}

系统对 URL 执行内容审核检查，以确认它们符合安全标准。如果 URL 未通过此检查，则相应的 `url_context_result` 步骤将显示 `status` 的 `"unsafe"`.

### token数  {% #token-count %}

从您在提示中指定的 URL 检索到的内容将计为输入 token 的一部分。您可以在中看到 token 计数 `usage` 交互的对象。下面是一个例子：

```none
'usage': {
  'output_tokens': 45,
  'input_tokens': 27,
  'input_tokens_details': [{'modality': 'TEXT', 'token_count': 27}],
  'thoughts_tokens': 31,
  'tool_use_input_tokens': 10309,
  'tool_use_input_tokens_details': [{'modality': 'TEXT', 'token_count': 10309}],
  'total_tokens': 10412
}
```

每个 token 的价格取决于所使用的型号，请参阅 [定价](/docs/pricing) 页面了解详细信息。

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

| 模型                                                            | URL上下文 |
| ------------------------------------------------------------- | ------ |
| [Gemini 4 Carbon](/docs/models/gemini-4-carbon)               | ✔️     |
| [Gemini 4 Argon](/docs/models/gemini-4-argon)                 | ✔️     |
| [Gemini 4 Hydrogen](/docs/models/gemini-4-hydrogen)           | ✔️     |
| [Gemini 3.8 Flash](/docs/models/gemini-3.8-flash)             | ✔️     |
| [Gemini 3.6 Flash](/docs/models/gemini-3.6-flash)             | ✔️     |
| [Gemini 3.5 Flash-Lite](/docs/models/gemini-3.5-flash-lite)   | ✔️     |
| [Gemini 3.1 Pro Preview](/docs/models/gemini-3.1-pro-preview) | ✔️     |
| [Gemini 3.1 Flash-Lite](/docs/models/gemini-3.1-flash-lite)   | ✔️     |
| [Gemini 3 Flash Preview](/docs/models/gemini-3-flash-preview) | ✔️     |
| [Gemini 2.5 Pro](/docs/models/gemini-2.5-pro)                 | ✔️     |
| [Gemini 2.5 Flash](/docs/models/gemini-2.5-flash)             | ✔️     |
| [Gemini 2.5 Flash-Lite](/docs/models/gemini-2.5-flash-lite)   | ✔️     |

## 最佳实践  {% #best-practices %}

* **提供具体网址**：为了获得最佳结果，请提供您希望模型分析的内容的直接 URL。该模型将仅检索您提供的 URL 中的内容，而不检索嵌套链接中的任何内容。

* **检查可访问性**：验证您提供的网址不会指向需要登录或位于付费专区后面的页面。

* **使用完整的 URL**：提供完整的 URL，包括协议（例如，https://www.google.com 而不仅仅是 google.com）。

## 限制  {% #limitations %}

* 请求限制：该工具每个请求最多可以处理 20 URL。

* URL 内容大小：从单个 URL 检索的内容的最大大小为 34MB。

* 公共可访问性：URL 必须可在网络上公开访问。不支持本地主机地址（例如 localhost、127.0.0.1）、专用网络和隧道服务（例如 ngrok、pinggy）。

### 支持和不支持的内容类型  {% #url-types %}

该工具可以从具有以下内容类型的 URL 中提取内容：

* 文本（文本/html、应用程序/json、文本/纯文本、文本/xml、文本/css、文本/javascript、文本/csv、文本/rtf）

* 图片（图片/png、图片/jpeg、图片/bmp、图片/webp）

* PDF（申请表/pdf）

以下内容类型是 **不** 支持：

* 付费内容

* YouTube 视频（参见 [视频理解](/docs/video-understanding#youtube) 了解如何处理 YouTube URL）

* Google 工作区文件，例如 Google 文档或电子表格

* 视频和音频文件
