Skip to main content
使用 langchain-google-genai 包中的 GoogleGenerativeAIEmbeddings 类连接 Google 生成式 AI 嵌入服务。 本文将帮助您使用 LangChain 快速上手 Google 生成式 AI 嵌入模型(如 Gemini)。有关 GoogleGenerativeAIEmbeddings 功能和配置选项的详细文档,请参阅 API 参考

概述

集成详情

设置

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

凭证

要使用 Google 生成式 AI 模型,您必须拥有 API 密钥。您可以在 Google AI Studio 中创建一个。请参阅 Google 文档 获取说明。 获得密钥后,将其设置为环境变量 GOOGLE_API_KEY
import getpass
import os

if not os.getenv("GOOGLE_API_KEY"):
    os.environ["GOOGLE_API_KEY"] = getpass.getpass("Enter your Google API key: ")
要启用模型调用的自动追踪,请设置您的 LangSmith API 密钥:
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")

安装

pip install -qU  langchain-google-genai

使用方法

from langchain_google_genai import GoogleGenerativeAIEmbeddings

embeddings = GoogleGenerativeAIEmbeddings(model="models/gemini-embedding-001")
vector = embeddings.embed_query("hello, world!")
vector[:5]
[-0.024917153641581535,
 0.012005362659692764,
 -0.003886754624545574,
 -0.05774897709488869,
 0.0020742062479257584]

批量处理

您也可以一次嵌入多个字符串以加快处理速度:
vectors = embeddings.embed_documents(
    [
        "Today is Monday",
        "Today is Tuesday",
        "Today is April Fools day",
    ]
)
len(vectors), len(vectors[0])
(3, 3072)

索引与检索

嵌入模型通常用于检索增强生成(RAG)流程,既用于数据索引,也用于后续检索。有关更详细的说明,请参阅我们的 RAG 教程 以下展示了如何使用上面初始化的 embeddings 对象进行索引和检索。在此示例中,我们将在 InMemoryVectorStore 中索引并检索一个示例文档。
# Create a vector store with a sample text
from langchain_core.vectorstores import InMemoryVectorStore

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

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

# Use the vectorstore as a retriever
retriever = vectorstore.as_retriever()

# Retrieve the most similar text
retrieved_documents = retriever.invoke("What is LangChain?")

# show the retrieved document's content
retrieved_documents[0].page_content
'LangChain is the framework for building context-aware reasoning applications'

任务类型

GoogleGenerativeAIEmbeddings 可选支持 task_type,目前必须为以下之一:
  • SEMANTIC_SIMILARITY:用于生成针对文本相似度评估优化的嵌入。
  • CLASSIFICATION:用于生成针对按预设标签分类文本优化的嵌入。
  • CLUSTERING:用于生成针对基于相似度聚类文本优化的嵌入。
  • RETRIEVAL_DOCUMENTRETRIEVAL_QUERYQUESTION_ANSWERINGFACT_VERIFICATION:用于生成针对文档搜索或信息检索优化的嵌入。
  • CODE_RETRIEVAL_QUERY:用于根据自然语言查询检索代码块,例如排序数组或反转链表。代码块的嵌入使用 RETRIEVAL_DOCUMENT 计算。
默认情况下,embed_documents 方法使用 RETRIEVAL_DOCUMENTembed_query 方法使用 RETRIEVAL_QUERY。如果您提供了任务类型,我们将对所有方法使用该类型。
pip install -qU  matplotlib scikit-learn
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from sklearn.metrics.pairwise import cosine_similarity

query_embeddings = GoogleGenerativeAIEmbeddings(
    model="models/gemini-embedding-001", task_type="RETRIEVAL_QUERY"
)
doc_embeddings = GoogleGenerativeAIEmbeddings(
    model="models/gemini-embedding-001", 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 is 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("---")
Document 1
Cosine similarity with query: 0.7892893360164779
---
Document 2
Cosine similarity with query: 0.5438283285204146
---

API 参考

有关 GoogleGenerativeAIEmbeddings 功能和配置选项的详细文档,请参阅 API 参考

其他配置

您可以将以下参数传递给 ChatGoogleGenerativeAI 以自定义 SDK 的行为:
  • client_options:传递给 Google API 客户端的客户端选项,例如自定义 client_options["api_endpoint"]
  • transport:要使用的传输方法,例如 restgrpcgrpc_asyncio