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

# GoogleGenerativeAIEmbeddings 集成

> 使用 LangChain Python 集成 Google Gemini API 嵌入模型。

这将帮助你开始使用 LangChain 的 Google 生成式 AI 嵌入模型。有关 `GoogleGenerativeAIEmbeddings` 功能和配置选项的详细文档，请参阅 [API 参考](https://reference.langchain.com/python/langchain-google-genai/embeddings/GoogleGenerativeAIEmbeddings)。

## 概述

<Note>
  `gemini-embedding-2-preview` 通过 Google GenAI SDK 的 `embed_content()` API 原生支持文本、图像、视频、音频和 PDF 输入。但是，LangChain 的 `Embeddings` 接口（`embed_query` / `embed_documents`）目前仅接受文本输入。LangChain 中的多模态嵌入支持计划在未来版本中实现。对于当前的多模态用例，请直接使用 [Google GenAI SDK](https://ai.google.dev/gemini-api/docs)。
</Note>

### 集成详情

## 设置

要访问 Google Gemini 嵌入模型，你需要创建一个 Google Cloud 项目、启用生成式语言 API、获取 API 密钥，并安装 `langchain-google-genai` 集成包。

### 凭证

前往 [Google AI Studio](https://aistudio.google.com/apikey) 注册并生成 API 密钥。更多详情请参阅 [Gemini API 密钥文档](https://ai.google.dev/gemini-api/docs/api-key)。完成此操作后，设置 `GOOGLE_API_KEY` 环境变量：

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

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

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

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

### 安装

LangChain Google 生成式 AI 集成位于 `langchain-google-genai` 包中：

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

## 实例化

现在我们可以实例化模型对象并生成嵌入：

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

embeddings = GoogleGenerativeAIEmbeddings(model="gemini-embedding-2-preview")
vector = embeddings.embed_query("hello, world!")
vector[:5]
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[-0.024917153641581535,
 0.012005362659692764,
 -0.003886754624545574,
 -0.05774897709488869,
 0.0020742062479257584]
```

### 降低维度

`gemini-embedding-2-preview` 通过 Matryoshka 表示学习 (MRL) 支持灵活的输出维度。你可以降低维度以优化存储和延迟：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
embeddings = GoogleGenerativeAIEmbeddings(
    model="gemini-embedding-2-preview",
    output_dimensionality=768,  # 建议：768、1536 或 3072（默认）
)
vector = embeddings.embed_query("hello, world!")
len(vector)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
768
```

## 批量处理

你也可以一次嵌入多个字符串以提高处理速度：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
vectors = embeddings.embed_documents(
    [
        "Today is Monday",
        "Today is Tuesday",
        "Today is April Fools day",
    ]
)
len(vectors), len(vectors[0])
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
(3, 768)
```

## 索引和检索

嵌入模型通常用于检索增强生成 (RAG) 流程中，既作为索引数据的一部分，也用于后续检索。更多详细说明，请参阅我们的 [RAG 教程](/oss/python/langchain/rag)。

下面，了解如何使用我们上面初始化的 `embeddings` 对象来索引和检索数据。在此示例中，我们将在 `InMemoryVectorStore` 中索引和检索一个示例文档。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 创建一个带有示例文本的向量存储
from langchain_core.vectorstores import InMemoryVectorStore

text = "LangChain is the framework for building context-aware reasoning applications"

vectorstore = InMemoryVectorStore.from_texts(
    [text],
    embedding=embeddings,
)

# 使用向量存储作为检索器
retriever = vectorstore.as_retriever()

# 检索最相似的文本
retrieved_documents = retriever.invoke("What is LangChain?")

# 显示检索到的文档内容
retrieved_documents[0].page_content
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
'LangChain is the framework for building context-aware reasoning applications'
```

## 任务类型

`GoogleGenerativeAIEmbeddings` 可选支持 `task_type`，目前必须是以下之一：

* `SEMANTIC_SIMILARITY`：用于生成针对评估文本相似性进行优化的嵌入。
* `CLASSIFICATION`：用于生成针对根据预设标签对文本进行分类进行优化的嵌入。
* `CLUSTERING`：用于生成针对基于相似性对文本进行聚类进行优化的嵌入。
* `RETRIEVAL_DOCUMENT`、`RETRIEVAL_QUERY`、`QUESTION_ANSWERING` 和 `FACT_VERIFICATION`：用于生成针对文档搜索或信息检索进行优化的嵌入。
* `CODE_RETRIEVAL_QUERY`：用于根据自然语言查询（如对数组排序或反转链表）检索代码块。代码块的嵌入使用 `RETRIEVAL_DOCUMENT` 计算。

默认情况下，我们在 `embed_documents` 方法中使用 `RETRIEVAL_DOCUMENT`，在 `embed_query` 方法中使用 `RETRIEVAL_QUERY`。如果你提供任务类型，我们将在所有方法中使用该类型。

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU matplotlib scikit-learn
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from sklearn.metrics.pairwise import cosine_similarity

query_embeddings = GoogleGenerativeAIEmbeddings(
    model="gemini-embedding-2-preview", task_type="RETRIEVAL_QUERY"
)
doc_embeddings = GoogleGenerativeAIEmbeddings(
    model="gemini-embedding-2-preview", task_type="RETRIEVAL_DOCUMENT"
)

q_embed = query_embeddings.embed_query("What is the capital of France?")
d_embed = doc_embeddings.embed_documents(
    ["The capital of France is Paris.", "Philipp likes to eat pizza."]
)

for i, d in enumerate(d_embed):
    print(f"Document {i + 1}:")
    print(f"Cosine similarity with query: {cosine_similarity([q_embed], [d])[0][0]}")
    print("---")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Document 1:
Cosine similarity with query: 0.7892893360164779
---
Document 2:
Cosine similarity with query: 0.5438283285204146
---
```

## 附加配置

你可以将以下参数传递给 `GoogleGenerativeAIEmbeddings` 以自定义 SDK 的行为：

* `base_url`：API 客户端的自定义基础 URL（例如，自定义端点）
* `output_dimensionality`：降低返回嵌入的维度（例如，`output_dimensionality=256`）
* `request_options`：请求选项字典（例如，`{"timeout": 10}`）
* `additional_headers`：包含在 API 请求中的附加 HTTP 头
* `client_args`：传递给底层 HTTP 客户端的附加参数

***

## API 参考

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

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs)通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/embeddings/google_generative_ai.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
