> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# ChatGoogleGenerativeAI 集成

> 使用 LangChain Python 与 ChatGoogleGenerativeAI 聊天模型集成。

通过 **Gemini Developer API** 或 **Vertex AI** 访问 Google 的生成式 AI 模型，包括 Gemini 系列。Gemini Developer API 提供快速设置和 API 密钥，适合个人开发者。Vertex AI 提供企业级功能并与 Google Cloud Platform 集成。

有关最新模型、模型 ID、其功能、上下文窗口等的信息，请前往 [Google AI 文档](https://ai.google.dev/gemini-api/docs)。

<Note>
  **Vertex AI 整合与兼容性**

  自 `langchain-google-genai` 4.0.0 起，此包使用整合后的 [`google-genai`](https://googleapis.github.io/python-genai/) SDK，而非旧的 [`google-ai-generativelanguage`](https://googleapis.dev/python/generativelanguage/latest/) SDK。

  此次迁移带来了通过 Gemini Developer API 和 Vertex AI 中的 Gemini API 对 Gemini 模型的支持，取代了 `langchain-google-vertexai` 中的某些类，例如 `ChatVertexAI`。

  阅读 [完整公告和迁移指南](https://github.com/langchain-ai/langchain-google/discussions/1422)。
</Note>

<Tip>
  **API 参考**

  有关所有功能和配置选项的详细文档，请前往 [`ChatGoogleGenerativeAI`](https://reference.langchain.com/python/langchain-google-genai/chat_models/ChatGoogleGenerativeAI) API 参考。
</Tip>

## 概述

### 集成详情

| 类                                                                                                                            | 包                                                                                          | 可序列化 | [JS 支持](https://js.langchain.com/docs/integrations/chat/google_generative_ai) |                                                下载量                                                |                                                版本                                               |
| :--------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------- | :--: | :---------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------: |
| [`ChatGoogleGenerativeAI`](https://reference.langchain.com/python/langchain-google-genai/chat_models/ChatGoogleGenerativeAI) | [`langchain-google-genai`](https://reference.langchain.com/python/langchain-google-genai/) | beta |                                       ✅                                       | ![PyPI - 下载量](https://img.shields.io/pypi/dm/langchain-google-genai?style=flat-square\&label=%20) | ![PyPI - 版本](https://img.shields.io/pypi/v/langchain-google-genai?style=flat-square\&label=%20) |

### 模型功能

| [工具调用](/oss/python/langchain/tools) | [结构化输出](/oss/python/langchain/structured-output) | [图像输入](/oss/python/langchain/messages#multimodal) | 音频输入 | 视频输入 | [令牌级流式传输](/oss/python/langchain/streaming/) | 原生异步 | [令牌用量](/oss/python/langchain/models#token-usage) | [Logprobs](/oss/python/langchain/models#log-probabilities) |
| :---------------------------------: | :----------------------------------------------: | :-----------------------------------------------: | :--: | :--: | :-----------------------------------------: | :--: | :----------------------------------------------: | :--------------------------------------------------------: |
|                  ✅                  |                         ✅                        |                         ✅                         |   ✅  |   ✅  |                      ✅                      |   ✅  |                         ✅                        |                             ⚠️                             |

## 设置

要访问 Google AI 模型，您需要创建一个 Google 账户，获取 Google AI API 密钥，并安装 `langchain-google-genai` 集成包。

### 安装

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -U langchain-google-genai
```

### 凭证

此集成支持两个后端：**Gemini Developer API** 和 **Vertex AI**。后端根据您的配置自动选择。

#### 后端选择

后端确定方式如下：

1. 如果设置了 `GOOGLE_GENAI_USE_VERTEXAI` 环境变量，则使用该值
2. 如果提供了 `credentials` 参数，则使用 Vertex AI
3. 如果提供了 `project` 参数，则使用 Vertex AI
4. 否则，使用 Gemini Developer API

您也可以显式设置 `vertexai=True` 或 `vertexai=False` 以覆盖自动检测。

<Tabs>
  <Tab title="Gemini Developer API">
    **使用 API 密钥快速设置**

    推荐给个人开发者/新用户。

    前往 [Google AI Studio](https://ai.google.dev/gemini-api/docs/api-key) 生成 API 密钥：

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import getpass
    import os

    if "GOOGLE_API_KEY" not in os.environ:
        os.environ["GOOGLE_API_KEY"] = getpass.getpass("Enter your Google AI API key: ")
    ```

    集成首先检查 `GOOGLE_API_KEY`，然后将 `GEMINI_API_KEY` 作为后备。
  </Tab>

  <Tab title="Vertex AI (使用 API 密钥)">
    **使用 API 密钥认证的 Vertex AI**

    您可以使用带 API 密钥认证的 Vertex AI 进行更简单的设置：

    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    export GEMINI_API_KEY='your-api-key'
    export GOOGLE_GENAI_USE_VERTEXAI=true
    export GOOGLE_CLOUD_PROJECT='your-project-id'
    ```

    或者编程方式：

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langchain_google_genai import ChatGoogleGenerativeAI

    llm = ChatGoogleGenerativeAI(
        model="gemini-2.5-flash",
        api_key="your-api-key", # [!code highlight]
        project="your-project-id", # [!code highlight]
        vertexai=True, # [!code highlight]
    )
    ```
  </Tab>

  <Tab title="Vertex AI (使用凭证)">
    **使用服务账号或 ADC 的 Vertex AI**

    设置 [Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials)：

    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    gcloud auth application-default login
    ```

    设置您的 Google Cloud 项目：

    ```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    export GOOGLE_CLOUD_PROJECT='your-project-id'
    # 可选：设置区域（默认为 us-central1）
    export GOOGLE_CLOUD_LOCATION='us-central1'
    ```

    或使用服务账号凭证：

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from google.oauth2 import service_account
    from langchain_google_genai import ChatGoogleGenerativeAI

    credentials = service_account.Credentials.from_service_account_file(
        "path/to/service-account.json",
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )

    llm = ChatGoogleGenerativeAI(
        model="gemini-2.5-flash",
        credentials=credentials, # [!code highlight]
        project="your-project-id", # [!code highlight]
    )
    ```
  </Tab>
</Tabs>

#### 环境变量

| 变量                          | 用途                               | 后端                                 |
| --------------------------- | -------------------------------- | ---------------------------------- |
| `GOOGLE_API_KEY`            | API 密钥（主要）                       | 两者（参见 `GOOGLE_GENAI_USE_VERTEXAI`） |
| `GEMINI_API_KEY`            | API 密钥（后备）                       | 两者（参见 `GOOGLE_GENAI_USE_VERTEXAI`） |
| `GOOGLE_GENAI_USE_VERTEXAI` | 强制 Vertex AI 后端 (`true`/`false`) | Vertex AI                          |
| `GOOGLE_CLOUD_PROJECT`      | GCP 项目 ID                        | Vertex AI                          |
| `GOOGLE_CLOUD_LOCATION`     | GCP 区域（默认：`us-central1`）         | Vertex AI                          |

要为您的模型调用启用自动追踪，请设置您的 [LangSmith](/langsmith/home) API 密钥：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

## 实例化

现在我们可以实例化我们的模型对象并生成响应：

<Tabs>
  <Tab title="Gemini Developer API">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langchain_google_genai import ChatGoogleGenerativeAI

    model = ChatGoogleGenerativeAI(
        model="gemini-3.1-pro-preview",
        temperature=1.0,  # Gemini 3.0+ 默认为 1.0
        max_tokens=None,
        timeout=None,
        max_retries=2,
        # other params...
    )
    ```
  </Tab>

  <Tab title="Vertex AI">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langchain_google_genai import ChatGoogleGenerativeAI

    model = ChatGoogleGenerativeAI(
        model="gemini-3.1-pro-preview",
        project="your-project-id", # [!code highlight]
        location="us-central1",  # 可选，默认为 us-central1 [!code highlight]
        temperature=1.0,  # Gemini 3.0+ 默认为 1.0
        max_tokens=None,
        timeout=None,
        max_retries=2,
        # other params...
    )
    ```

    提供 `project` 会自动选择 Vertex AI 后端，除非您显式设置 `vertexai=False`。
  </Tab>
</Tabs>

<Note>
  **Gemini 3.0+ 模型的 Temperature**

  如果未显式设置 `temperature` 且模型为 Gemini 3.0 或更高版本，它将自动设置为 `1.0`，而不是 Google GenAI API 最佳实践中的默认值 `0.7`。在 Gemini 3.0+ 中使用 `0.7` 可能导致无限循环、推理性能下降以及复杂任务失败。
</Note>

有关可用模型参数的完整列表，请参阅 [`ChatGoogleGenerativeAI`](https://reference.langchain.com/python/langchain-google-genai/chat_models/ChatGoogleGenerativeAI) API 参考。

### 代理配置

如果您需要使用代理，请在初始化之前设置这些环境变量：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export HTTPS_PROXY='http://username:password@proxy_uri:port'
export SSL_CERT_FILE='path/to/cert.pem'  # 可选：自定义 SSL 证书
```

对于 SOCKS5 代理或高级代理配置，请使用 `client_args` 参数：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
model = ChatGoogleGenerativeAI(
    model="gemini-3.1-pro-preview",
    client_args={"proxy": "socks5://user:pass@host:port"},
)
```

## 调用

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
messages = [
    (
        "system",
        "You are a helpful assistant that translates English to French. Translate the user sentence.",
    ),
    ("human", "I love programming."),
]
ai_msg = model.invoke(messages)
ai_msg
```

<CodeGroup>
  ```plaintext Gemini 3 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  AIMessage(content=[{'type': 'text', 'text': "J'adore la programmation.", 'extras': {'signature': 'EpoWCpc...'}}], additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'model_name': 'gemini-3.1-pro-preview', 'safety_ratings': [], 'model_provider': 'google_genai'}, id='lc_run--fb732b64-1ab4-4a28-b93b-dcfb2a164a3d-0', usage_metadata={'input_tokens': 21, 'output_tokens': 779, 'total_tokens': 800, 'input_token_details': {'cache_read': 0}, 'output_token_details': {'reasoning': 772}})
  ```

  ```plaintext Gemini 2.5 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  AIMessage(content="J'adore la programmation.", additional_kwargs={}, response_metadata={'prompt_feedback': {'block_reason': 0, 'safety_ratings': []}, 'finish_reason': 'STOP', 'model_name': 'gemini-2.5-flash', 'safety_ratings': []}, id='run-3b28d4b8-8a62-4e6c-ad4e-b53e6e825749-0', usage_metadata={'input_tokens': 20, 'output_tokens': 7, 'total_tokens': 27, 'input_token_details': {'cache_read': 0}})
  ```
</CodeGroup>

<Note>
  **消息内容形状**

  Gemini 3 系列模型返回内容块列表以捕获 [思维签名](#thought-signatures)。使用 `.text` 获取字符串内容：

  ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  response.content  # -> [{"type": "text", "text": "Hello!", "extras": {"signature": "EpQFCp..."}}]
  response.text     # -> "Hello!"
  ```

  Gemini 2.5 及更早版本为 `.content` 返回纯字符串。
</Note>

## 多模态使用

Gemini 模型接受多模态输入（文本、图像、音频、视频、PDF），部分模型可以生成多模态输出。

### 支持的输入方法

| 方法                               | [图像](#image-input) | [视频](#video-input) | [音频](#audio-input) | [PDF](#pdf-input) |
| -------------------------------- | :----------------: | :----------------: | :----------------: | :---------------: |
| [文件上传](#file-upload) (Files API) |          ✅         |          ✅         |          ✅         |         ✅         |
| Base64 内联数据                      |          ✅         |          ✅         |          ✅         |         ✅         |
| HTTP/HTTPS URLs\*                |          ✅         |          ✅         |          ✅         |         ✅         |
| GCS URIs (`gs://...`)            |          ✅         |          ✅         |          ✅         |         ✅         |

\*YouTube URL 在预览中支持用于视频输入。

### 文件上传

您可以将文件上传到 Google 服务器并通过 URI 引用它们。这适用于 PDF、图像、视频和音频文件。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import time
from google import genai
from langchain.messages import HumanMessage
from langchain_google_genai import ChatGoogleGenerativeAI

client = genai.Client()
model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

# Upload file to Google's servers
myfile = client.files.upload(file="/path/to/your/file.pdf")
while myfile.state.name == "PROCESSING":
    time.sleep(2)
    myfile = client.files.get(name=myfile.name)

# Reference by file_id in FileContentBlock
message = HumanMessage(
    content=[
        {"type": "text", "text": "What is in the document?"},
        {
            "type": "file",
            "file_id": myfile.uri,  # or myfile.name
            "mime_type": "application/pdf",
        },
    ]
)
response = model.invoke([message])
```

上传后，您可以在下面的任何媒体特定部分中使用 `file_id` 模式引用该文件。

### 图像输入

使用带有列表内容格式的 [`HumanMessage`](https://reference.langchain.com/python/langchain-core/messages/human/HumanMessage) 提供图像输入和文本。

<CodeGroup>
  ```python Image URL theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Describe the image at the URL."},
          {
              "type": "image",
              "url": "https://picsum.photos/seed/picsum/200/300",
          },
      ]
  )
  response = model.invoke([message])
  ```

  ```python Chat Completions image_url format theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Describe the image at the URL."},
          {"type": "image_url", "image_url": "https://picsum.photos/seed/picsum/200/300"},
      ]
  )
  response = model.invoke([message])
  ```

  ```python Base64 encoded theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import base64
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  image_bytes = open("path/to/your/image.jpg", "rb").read()
  image_base64 = base64.b64encode(image_bytes).decode("utf-8")
  mime_type = "image/jpeg"

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Describe the local image."},
          {
              "type": "image",
              "base64": image_base64,
              "mime_type": mime_type,
          },
      ]
  )
  response = model.invoke([message])
  ```

  ```python Uploaded file theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import time
  from google import genai
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  client = genai.Client()
  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  # Upload and wait for processing
  myfile = client.files.upload(file="/path/to/image.jpg")
  while myfile.state.name == "PROCESSING":
      time.sleep(2)
      myfile = client.files.get(name=myfile.name)

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Describe this image."},
          {
              "type": "file",
              "file_id": myfile.uri,
              "mime_type": "image/jpeg",
          },
      ]
  )
  response = model.invoke([message])
  ```
</CodeGroup>

其他支持的图像格式：

* Google Cloud Storage URI (`gs://...`)。确保服务账号具有访问权限。

### PDF 输入

提供 PDF 文件输入和文本。

<CodeGroup>
  ```python URL theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Describe the document in a sentence."},
          {
              "type": "image_url",  # (PDFs are treated as images)
              "image_url": "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
          },
      ]
  )
  response = model.invoke([message])
  ```

  ```python Base64 encoded theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import base64
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  pdf_bytes = open("path/to/your/document.pdf", "rb").read()
  pdf_base64 = base64.b64encode(pdf_bytes).decode("utf-8")
  mime_type = "application/pdf"

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Describe the document in a sentence."},
          {
              "type": "file",
              "base64": pdf_base64,
              "mime_type": mime_type,
          },
      ]
  )
  response = model.invoke([message])
  ```

  ```python Uploaded file theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import time
  from google import genai
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  client = genai.Client()
  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  # Upload and wait for processing
  myfile = client.files.upload(file="/path/to/document.pdf")
  while myfile.state.name == "PROCESSING":
      time.sleep(2)
      myfile = client.files.get(name=myfile.name)

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Describe the document in a sentence."},
          {
              "type": "file",
              "file_id": myfile.uri,
              "mime_type": "application/pdf",
          },
      ]
  )
  response = model.invoke([message])
  ```
</CodeGroup>

### 音频输入

提供音频文件输入和文本。

<CodeGroup>
  ```python URL theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Summarize this audio in a sentence."},
          {
              "type": "image_url",
              "image_url": "https://example.com/audio.mp3",
          },
      ]
  )
  response = model.invoke([message])
  ```

  ```python Base64 encoded theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import base64
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  audio_bytes = open("path/to/your/audio.mp3", "rb").read()
  audio_base64 = base64.b64encode(audio_bytes).decode("utf-8")
  mime_type = "audio/mpeg"

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Summarize this audio in a sentence."},
          {
              "type": "audio",
              "base64": audio_base64,
              "mime_type": mime_type,
          },
      ]
  )
  response = model.invoke([message])
  ```

  ```python Uploaded file theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import time
  from google import genai
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  client = genai.Client()
  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  # Upload and wait for processing
  myfile = client.files.upload(file="/path/to/audio.mp3")
  while myfile.state.name == "PROCESSING":
      time.sleep(2)
      myfile = client.files.get(name=myfile.name)

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Summarize this audio in a sentence."},
          {
              "type": "file",
              "file_id": myfile.uri,
              "mime_type": "audio/mpeg",
          },
      ]
  )
  response = model.invoke([message])
  ```
</CodeGroup>

### 视频输入

提供视频文件输入和文本。

<CodeGroup>
  ```python Base64 encoded theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import base64
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  video_bytes = open("path/to/your/video.mp4", "rb").read()
  video_base64 = base64.b64encode(video_bytes).decode("utf-8")
  mime_type = "video/mp4"

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Describe what's in this video in a sentence."},
          {
              "type": "video",
              "base64": video_base64,
              "mime_type": mime_type,
          },
      ]
  )
  response = model.invoke([message])
  ```

  ```python Uploaded file theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import time
  from google import genai
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  client = genai.Client()
  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  # Upload and wait for processing
  myfile = client.files.upload(file="/path/to/video.mp4")
  while myfile.state.name == "PROCESSING":
      time.sleep(2)
      myfile = client.files.get(name=myfile.name)

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Summarize the video in 3 sentences."},
          {
              "type": "file",
              "file_id": myfile.uri,
              "mime_type": "video/mp4",
          },
      ]
  )
  response = model.invoke([message])
  ```

  ```python YouTube URL theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  message = HumanMessage(
      content=[
          {"type": "text", "text": "Summarize the video in 3 sentences."},
          {
              "type": "video",
              "url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
              "mime_type": "video/mp4",
          },
      ]
  )
  response = model.invoke([message])
  ```
</CodeGroup>

<Note>
  **YouTube 视频输入（预览）**

  * 仅支持公开视频（不支持私密或未列出的视频）
  * 免费层：每天最多 8 小时的 YouTube 视频
</Note>

### 图像生成

某些模型可以内联生成文本和图像。详见 [Gemini API 文档](https://ai.google.dev/gemini-api/docs/image-generation)。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import base64
from IPython.display import Image, display
from langchain.messages import AIMessage
from langchain_google_genai import ChatGoogleGenerativeAI

model = ChatGoogleGenerativeAI(model="gemini-2.5-flash-image") # [!code highlight]

response = model.invoke("Generate a photorealistic image of a cuddly cat wearing a hat.")

def _get_image_base64(response: AIMessage) -> None:
    image_block = next(
        block
        for block in response.content
        if isinstance(block, dict) and block.get("image_url")
    )
    return image_block["image_url"].get("url").split(",")[-1]

image_base64 = _get_image_base64(response)
display(Image(data=base64.b64decode(image_base64), width=300))
```

使用 `image_config` 控制图像尺寸和质量（见 [`genai.types.ImageConfig`](https://googleapis.github.io/python-genai/genai.html#genai.types.ImageConfig)）。可以在实例化时设置（适用于所有调用）或在调用时设置（每次调用覆盖）：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import ChatGoogleGenerativeAI

# Set at instantiation (applies to all calls)
model = ChatGoogleGenerativeAI(
    model="gemini-2.5-flash-image",
    image_config={"aspect_ratio": "16:9"}, # [!code highlight]
)

# Or override per call
response = model.invoke(
    "Generate a photorealistic image of a cuddly cat wearing a hat.",
    image_config={"aspect_ratio": "1:1"}, # [!code highlight]
)
```

默认情况下，图像生成模型可能会同时返回文本和图像（例如 *"Ok! Here's an image of a..."*）。

您可以通过设置 `response_modalities` 参数请求模型仅返回图像：

<CodeGroup>
  ```python Instantiation theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI, Modality

  model = ChatGoogleGenerativeAI(
      model="gemini-2.5-flash-image",
      response_modalities=[Modality.IMAGE],  # [!code highlight]
  )

  # All invocations will return only images
  response = model.invoke("Generate a photorealistic image of a cuddly cat wearing a hat.")
  ```

  ```python Invocation theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI, Modality

  model = ChatGoogleGenerativeAI(model="gemini-2.5-flash-image")

  # Only this invocation will return images; others may return text+images
  response = model.invoke(
      "Generate a photorealistic image of a cuddly cat wearing a hat.",
      response_modalities=[Modality.IMAGE], # [!code highlight]
  )
  ```
</CodeGroup>

### 音频生成

某些模型可以生成音频文件。详见 [Gemini API 文档](https://ai.google.dev/gemini-api/docs/speech-generation)。

<Warning>
  **Vertex AI 限制**

  音频生成模型目前在 Vertex AI 上处于有限预览阶段，可能需要白名单访问。如果在 `vertexai=True` 时使用 TTS 模型遇到 `INVALID_ARGUMENT` 错误，您的 GCP 项目可能需要加入白名单。

  更多详细信息，请参阅此 [Google AI 论坛讨论](https://discuss.ai.google.dev/t/request-allowlist-access-for-audio-output-in-gemini-2-5-pro-flash-tts-vertex-ai/108067)。
</Warning>

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import ChatGoogleGenerativeAI

model = ChatGoogleGenerativeAI(model="gemini-2.5-flash-preview-tts") # [!code highlight]

response = model.invoke("Please say The quick brown fox jumps over the lazy dog")

# Base64 encoded binary data of the audio
wav_data = response.additional_kwargs.get("audio")
with open("output.wav", "wb") as f:
    f.write(wav_data)
```

## 工具调用

您可以为模型配备可调用的工具。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.tools import tool
from langchain.messages import HumanMessage
from langchain_google_genai import ChatGoogleGenerativeAI


# Define the tool
@tool(description="Get the current weather in a given location")
def get_weather(location: str) -> str:
    return "It's sunny."


# Initialize and bind (potentially multiple) tools to the model
model_with_tools = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview").bind_tools([get_weather])

# Step 1: Model generates tool calls
messages = [HumanMessage("What's the weather in Boston?")]
ai_msg = model_with_tools.invoke(messages)
messages.append(ai_msg)

# Check the tool calls in the response
print(ai_msg.tool_calls)

# Step 2: Execute tools and collect results
for tool_call in ai_msg.tool_calls:
    # Execute the tool with the generated arguments
    tool_result = get_weather.invoke(tool_call)
    messages.append(tool_result)

# Step 3: Pass results back to model for final response
final_response = model_with_tools.invoke(messages)
final_response
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[{'name': 'get_weather', 'args': {'location': 'Boston'}, 'id': '879b4233-901b-4bbb-af56-3771ca8d3a75', 'type': 'tool_call'}]
```

## 结构化输出

强制模型以特定结构响应。更多信息请参见 [Gemini API 文档](https://ai.google.dev/gemini-api/docs/structured-output)。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import ChatGoogleGenerativeAI
from pydantic import BaseModel
from typing import Literal


class Feedback(BaseModel):
    sentiment: Literal["positive", "neutral", "negative"]
    summary: str


model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")
structured_model = model.with_structured_output(
    schema=Feedback.model_json_schema(), method="json_schema"
)

response = structured_model.invoke("The new UI is great!")
response["sentiment"]  # "positive"
response["summary"]  # "The user expresses positive..."
```

对于流式结构化输出，合并字典而不是使用 `+=`：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
stream = structured_model.stream("The interface is intuitive and beautiful!")
full = next(stream)
for chunk in stream:
    full.update(chunk)  # Merge dictionaries
print(full)  # Complete structured response
# -> {'sentiment': 'positive', 'summary': 'The user praises...'}
```

### 结构化输出方法

支持两种结构化输出方法：

* **`method="json_schema"`（默认）**：使用 Gemini 的原生结构化输出。推荐用于更好的可靠性，因为它直接约束模型的生成过程，而不是依赖后处理工具调用。
* **`method="function_calling"`**：使用工具调用来提取结构化数据。

### 将结构化输出与 Google 搜索结合

当使用 `with_structured_output(method="function_calling")` 时，不要在同一个调用中传递其他工具（如 Google 搜索）。

要在单个调用中获得结构化输出 **和** 搜索 grounding，请使用 `.bind()` 配合 `response_mime_type` 和 `response_schema`，而不是 `with_structured_output`：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import ChatGoogleGenerativeAI
from pydantic import BaseModel


class MatchResult(BaseModel):
    winner: str
    final_match_score: str
    scorers: list[str]


llm = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

llm_with_search = llm.bind(
    tools=[{"google_search": {}}],
    response_mime_type="application/json",
    response_schema=MatchResult.model_json_schema(),
)

response = llm_with_search.invoke(
    "Search for details of the latest Euro championship final match."
)
```

这使用 Gemini 的原生 JSON schema 模式来结构化输出，同时允许像 Google 搜索这样的工具进行 grounding——全部在一个 LLM 调用中完成。

## 令牌用量跟踪

从响应元数据中访问令牌用量信息。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import ChatGoogleGenerativeAI

model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

result = model.invoke("Explain the concept of prompt engineering in one sentence.")

print(result.content)
print("\nUsage Metadata:")
print(result.usage_metadata)
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Prompt engineering is the art and science of crafting effective text prompts to elicit desired and accurate responses from large language models.

Usage Metadata:
{'input_tokens': 10, 'output_tokens': 24, 'total_tokens': 34, 'input_token_details': {'cache_read': 0}}
```

## 思考支持

某些 Gemini 模型支持可配置的思考深度。参数取决于模型版本：

| 模型系列       | 参数                | 值                                                   |
| ---------- | ----------------- | --------------------------------------------------- |
| Gemini 3+  | `thinking_level`  | `"minimal"`, `"low"`, `"medium"`, `"high"` (Pro 默认) |
| Gemini 2.5 | `thinking_budget` | `0` (关闭), `-1` (动态), 或正整数 (令牌限制)                    |

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import ChatGoogleGenerativeAI

# Gemini 3+: use thinking_level
llm = ChatGoogleGenerativeAI(
    model="gemini-3.1-pro-preview",
    thinking_level="low",  # [!code highlight]
)

response = llm.invoke("How many O's are in Google?")
```

### Gemini 2.5 模型：`thinking_budget`

对于 Gemini 2.5 模型，请使用 `thinking_budget`（整数令牌计数）代替：

* 设置为 `0` 以禁用思考（如果支持）
* 设置为 `-1` 进行动态思考（由模型决定）
* 设置为正整数以限制令牌用量

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import ChatGoogleGenerativeAI

llm = ChatGoogleGenerativeAI(
    model="gemini-2.5-flash",
    thinking_budget=1024,  # [!code highlight]
)
```

<Warning>
  并非所有模型都允许禁用思考。详见 [Gemini 模型文档](https://ai.google.dev/gemini-api/docs/models)。
</Warning>

### 查看模型思考过程

要查看思考模型的推理，请设置 `include_thoughts=True`：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import ChatGoogleGenerativeAI

llm = ChatGoogleGenerativeAI(
    model="gemini-3.1-pro-preview",
    include_thoughts=True,  # [!code highlight]
)

response = llm.invoke("How many O's are in Google? How did you verify your answer?")
reasoning_tokens = response.usage_metadata["output_token_details"]["reasoning"]

print("Response:", response.content)
print("Reasoning tokens used:", reasoning_tokens)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Response: [{'type': 'thinking', 'thinking': '**Analyzing and Cou...'}, {'type': 'text', 'text': 'There a...', 'extras': {'signature': 'EroR...'}}]
Reasoning tokens used: 672
```

有关思考的更多信息，请参见 [Gemini API 文档](https://ai.google.dev/gemini-api/docs/thinking)。

### 思考签名

[思考签名](https://ai.google.dev/gemini-api/docs/thinking) 是模型推理的加密表示。它们使 Gemini 能够在多轮对话中保持思维上下文，因为 API 是无状态的。

<Note>
  如果不随工具调用响应传递思考签名，Gemini 3 可能会引发 4xx 错误。升级到 `langchain-google-genai >= 3.1.0` 以确保正确处理此问题。
</Note>

签名出现在 `AIMessage` 响应中：

* **文本块**：内容块内的 `extras.signature`
* **工具调用**：`additional_kwargs["__gemini_function_call_thought_signatures__"]`

对于多轮对话，请将完整的 `AIMessage` 传回模型以保留签名。当您把 `AIMessage` 追加到您的消息列表中时（如上 [工具调用](#tool-calling) 示例所示），这会自动发生。

<Warning>
  **不要手动重建消息。** 如果您创建新的 `AIMessage` 而不是传递原始对象，签名将会丢失，API 可能会拒绝请求。
</Warning>

## 内置工具

Google Gemini 支持各种内置工具，可以按常规方式绑定到模型。

### Google 搜索

详见 [Gemini 文档](https://ai.google.dev/gemini-api/docs/grounding/search-suggestions)。

<CodeGroup>
  ```python Bind to model theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  model_with_search = model.bind_tools([{"google_search": {}}]) # [!code highlight]
  response = model_with_search.invoke("When is the next total solar eclipse in US?")

  response.content_blocks
  ```

  ```python Use on invocation theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  response = model.invoke(
      "When is the next total solar eclipse in US?",
      tools=[{"google_search": {}}], # [!code highlight]
  )

  response.content_blocks
  ```
</CodeGroup>

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[{'type': 'text',
  'text': 'The next total solar eclipse visible in the contiguous United States will occur on...',
  'annotations': [{'type': 'citation',
    'id': 'abc123',
    'url': '<url for source 1>',
    'title': '<source 1 title>',
    'start_index': 0,
    'end_index': 99,
    'cited_text': 'The next total solar eclipse...',
    'extras': {'google_ai_metadata': {'web_search_queries': ['next total solar eclipse in US'],
       'grounding_chunk_index': 0,
       'confidence_scores': []}}},
   ...
```

### Google 地图

某些模型支持使用 Google 地图进行 grounding。地图 grounding 将 Gemini 的生成能力与 Google 地图当前的、事实性的位置数据连接起来。这使得能够提供准确、地理位置特定响应的定位感知应用程序。详见 [Gemini 文档](https://ai.google.dev/gemini-api/docs/maps-grounding)。

<CodeGroup>
  ```python Bind to model theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-2.5-pro")

  model_with_maps = model.bind_tools([{"google_maps": {}}]) # [!code highlight]
  response = model_with_maps.invoke(
      "What are some good Italian restaurants near the Eiffel Tower in Paris?"
  )
  ```

  ```python Use on invocation theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-2.5-pro")

  response = model.invoke(
      "What are some good Italian restaurants near the Eiffel Tower in Paris?",
      tools=[{"google_maps": {}}], # [!code highlight]
  )
  ```
</CodeGroup>

响应将包含来自 Google 地图的位置信息的 grounding 元数据。

您可以使用 `tool_config` 配合 `lat_lng` 提供特定的位置上下文。当您希望相对于特定地理点 grounding 查询时，这很有用。

<CodeGroup>
  ```python Bind to model theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-2.5-pro")

  # Provide location context (latitude and longitude)
  model_with_maps = model.bind_tools(
      [{"google_maps": {}}], # [!code highlight]
      tool_config={
          "retrieval_config": {  # Eiffel Tower
              "lat_lng": { # [!code highlight]
                  "latitude": 48.858844, # [!code highlight]
                  "longitude": 2.294351, # [!code highlight]
              } # [!code highlight]
          }
      },
  )

  response = model_with_maps.invoke(
      "What Italian restaurants are within a 5 minute walk from here?"
  )
  ```

  ```python Use on invocation theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-2.5-pro")

  response = model.invoke(
      "What Italian restaurants are within a 5 minute walk from here?",
      tools=[{"google_maps": {}}], # [!code highlight]
      tool_config={
          "retrieval_config": {  # Eiffel Tower
              "lat_lng": { # [!code highlight]
                  "latitude": 48.858844, # [!code highlight]
                  "longitude": 2.294351, # [!code highlight]
              } # [!code highlight]
          }
      },
  )
  ```
</CodeGroup>

### URL 上下文

URL 上下文工具使模型能够访问和分析您在提示中提供的 URL 的内容。这对于总结网页、从多个来源提取数据或回答关于在线内容的问题等任务非常有用。详见 [Gemini 文档](https://ai.google.dev/gemini-api/docs/url-context) 了解细节和限制。

<CodeGroup>
  ```python Bind to model theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-2.5-flash")

  model_with_url_context = model.bind_tools([{"url_context": {}}]) # [!code highlight]
  response = model_with_url_context.invoke(
      "Summarize the content at https://docs.langchain.com"
  )
  ```

  ```python Use on invocation theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-2.5-flash")

  response = model.invoke(
      "Summarize the content at https://docs.langchain.com",
      tools=[{"url_context": {}}], # [!code highlight]
  )
  ```
</CodeGroup>

### 代码执行

详见 [Gemini 文档](https://ai.google.dev/gemini-api/docs/code-execution?lang=python)。

<CodeGroup>
  ```python Bind to model theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  model_with_code_interpreter = model.bind_tools([{"code_execution": {}}]) # [!code highlight]
  response = model_with_code_interpreter.invoke("Use Python to calculate 3^3.")

  response.content_blocks
  ```

  ```python Use on invocation theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

  response = model.invoke(
      "Use Python to calculate 3^3.",
      tools=[{"code_execution": {}}], # [!code highlight]
  )

  response.content_blocks
  ```
</CodeGroup>

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[{'type': 'server_tool_call',
  'name': 'code_interpreter',
  'args': {'code': 'print(3**3)', 'language': <Language.PYTHON: 1>},
  'id': '...'},
 {'type': 'server_tool_result',
  'tool_call_id': '',
  'status': 'success',
  'output': '27\n',
  'extras': {'block_type': 'code_execution_result',
   'outcome': <Outcome.OUTCOME_OK: 1>}},
 {'type': 'text', 'text': 'The calculation of 3 to the power of 3 is 27.'}]
```

### 计算机使用

Gemini 2.5 Computer Use 模型 (`gemini-2.5-computer-use-preview-10-2025`) 可以与浏览器环境交互以自动化 Web 任务，如点击、键入和滚动。

<Warning>
  **预览模型限制**

  Computer Use 模型处于预览阶段，可能会产生意外行为。始终监督自动化任务，避免用于敏感数据或关键操作。详见 [Gemini API 文档](https://ai.google.dev/gemini-api/docs/computer-use) 了解安全最佳实践。
</Warning>

<CodeGroup>
  ```python Bind to model theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-2.5-computer-use-preview-10-2025") # [!code highlight]
  model_with_computer = model.bind_tools([{"computer_use": {}}]) # [!code highlight]

  response = model_with_computer.invoke("Please navigate to example.com")

  response.content_blocks
  ```

  ```python Use on invocation theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain_google_genai import ChatGoogleGenerativeAI

  model = ChatGoogleGenerativeAI(model="gemini-2.5-computer-use-preview-10-2025") # [!code highlight]

  response = model.invoke(
      "Please navigate to example.com",
      tools=[{"computer_use": {}}], # [!code highlight]
  )

  response.content_blocks
  ```
</CodeGroup>

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[{'type': 'tool_call',
  'id': '08a8b175-16ab-4861-8965-b736d5d4dd7e',
  'name': 'open_web_browser',
  'args': {}}]
```

您可以配置环境并排除特定的 UI 操作：

```python Advanced configuration theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import ChatGoogleGenerativeAI, Environment

model = ChatGoogleGenerativeAI(model="gemini-2.5-computer-use-preview-10-2025") # [!code highlight]

# Specify the environment (browser is default)
model_with_computer = model.bind_tools(
    [{"computer_use": {"environment": Environment.ENVIRONMENT_BROWSER}}] # [!code highlight]
)

# Exclude specific UI actions
model_with_computer = model.bind_tools(
    [
        {
            "computer_use": {
                "environment": Environment.ENVIRONMENT_BROWSER,
                "excludedPredefinedFunctions": [ # [!code highlight]
                    "drag_and_drop", # [!code highlight]
                    "key_combination", # [!code highlight]
                ], # [!code highlight]
            }
        }
    ]
)

response = model_with_computer.invoke("Search for Python tutorials")
```

模型返回 UI 操作的函数调用（如 `click_at`, `type_text_at`, `scroll`），带有标准化坐标。您需要在浏览器自动化框架中实现这些实际操作的实际执行。

## 安全设置

Gemini 模型具有默认的安全设置，可以覆盖。如果您收到大量 `'Safety Warnings'`，可以尝试调整模型的安全设置属性。例如，要关闭危险内容的阻止，您可以按以下方式构建 LLM：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import (
    ChatGoogleGenerativeAI,
    HarmBlockThreshold,
    HarmCategory,
)

llm = ChatGoogleGenerativeAI(
        model="gemini-3.1-pro-preview",
        safety_settings={
        HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
    },
)
```

有关可用类别和阈值的枚举，请参见 Google 的 [安全设置类型](https://ai.google.dev/api/python/google/generativeai/types/SafetySettingDict)。

## 上下文缓存

上下文缓存允许您存储和重用内容（例如 PDF、图像）以加快处理速度。`cached_content` 参数接受通过 Google Generative AI API 创建的缓存名称。

<Accordion title="单文件示例">
  此示例缓存单个文件并对其进行查询。

  ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import time
  from google import genai
  from google.genai import types
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  client = genai.Client()

  # Upload file
  file = client.files.upload(file="path/to/your/file")
  while file.state.name == "PROCESSING":
      time.sleep(2)
      file = client.files.get(name=file.name)

  # Create cache
  model = "gemini-3.1-pro-preview"
  cache = client.caches.create(
      model=model,
      config=types.CreateCachedContentConfig(
          display_name="Cached Content",
          system_instruction=(
              "You are an expert content analyzer, and your job is to answer "
              "the user's query based on the file you have access to."
          ),
          contents=[file],
          ttl="300s",
      ),
  )

  # Query with LangChain
  llm = ChatGoogleGenerativeAI(
      model=model,
      cached_content=cache.name,
  )
  message = HumanMessage(content="Summarize the main points of the content.")
  llm.invoke([message])
  ```
</Accordion>

<Accordion title="多文件示例">
  此示例使用 `Part` 缓存两个文件并一起查询它们。

  ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  import time
  from google import genai
  from google.genai.types import CreateCachedContentConfig, Content, Part
  from langchain.messages import HumanMessage
  from langchain_google_genai import ChatGoogleGenerativeAI

  client = genai.Client()

  # Upload files
  file_1 = client.files.upload(file="./file1")
  while file_1.state.name == "PROCESSING":
      time.sleep(2)
      file_1 = client.files.get(name=file_1.name)

  file_2 = client.files.upload(file="./file2")
  while file_2.state.name == "PROCESSING":
      time.sleep(2)
      file_2 = client.files.get(name=file_2.name)

  # Create cache with multiple files
  contents = [
      Content(
          role="user",
          parts=[
              Part.from_uri(file_uri=file_1.uri, mime_type=file_1.mime_type),
              Part.from_uri(file_uri=file_2.uri, mime_type=file_2.mime_type),
          ],
      )
  ]
  model = "gemini-3.1-pro-preview"
  cache = client.caches.create(
      model=model,
      config=CreateCachedContentConfig(
          display_name="Cached Contents",
          system_instruction=(
              "You are an expert content analyzer, and your job is to answer "
              "the user's query based on the files you have access to."
          ),
          contents=contents,
          ttl="300s",
      ),
  )

  # Query with LangChain
  llm = ChatGoogleGenerativeAI(
      model=model,
      cached_content=cache.name,
  )
  message = HumanMessage(
      content="Provide a summary of the key information across both files."
  )
  llm.invoke([message])
  ```
</Accordion>

有关更多信息，请参见 Gemini API 文档上的 [上下文缓存](https://ai.google.dev/gemini-api/docs/caching?lang=python)。

## 响应元数据

从模型响应中访问响应元数据。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import ChatGoogleGenerativeAI

llm = ChatGoogleGenerativeAI(model="gemini-3.1-pro-preview")

response = llm.invoke("Hello!")
response.response_metadata
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{'prompt_feedback': {'block_reason': 0, 'safety_ratings': []},
 'finish_reason': 'STOP',
 'model_name': 'gemini-3.1-pro-preview',
 'safety_ratings': [],
 'model_provider': 'google_genai'}
```

***

## API 参考

有关所有功能和配置选项的详细文档，请前往 [`ChatGoogleGenerativeAI`](https://reference.langchain.com/python/langchain-google-genai/chat_models/ChatGoogleGenerativeAI) API 参考。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\python\integrations\chat\google_generative_ai.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
