Google Vertex 是一项服务,可访问 Google Cloud 中所有可用的基础模型,如 gemini-2.5-pro, gemini-2.5-flash等。 它还提供一些非 Google 模型,例如 Anthropic 的 Claude.
这将帮助您开始使用 ChatVertexAI 聊天模型。有关所有 ChatVertexAI 功能和配置的详细文档,请访问 API 参考.
概述
集成详情
| 类 | 包 | 可序列化 | PY 支持 | 下载 | 版本 |
|---|---|---|---|---|---|
ChatVertexAI | @langchain/google-vertexai | ✅ | ✅ | !NPM - 下载量 | !NPM - 版本 |
模型特性
请参阅下方表格标题中的链接,了解如何使用特定功能。
| 工具调用 | 结构化输出 | 图像输入 | 音频输入 | 视频输入 | Token 级流式输出 | Token 使用量 | 对数概率 |
|---|---|---|---|---|---|---|---|
| ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
请注意,虽然支持对数概率,但 Gemini 对其使用有相当严格的限制。
设置
LangChain.js 支持两种不同的身份验证方法,基于是否 您正在 Node.js 环境还是 Web 环境中运行。它还支持 使用任一包的 Vertex AI Express Mode 身份验证方法。
要访问 ChatVertexAI 模型,您需要在 Google Cloud Platform (GCP) 账户中设置 Google VertexAI,保存凭据文件,并安装 @langchain/google-vertexai 集成包。在 Node.js 上,该包使用 @langchain/google-gauth 进行身份验证(您无需单独安装)。
凭据
前往您的 GCP 账户 并生成凭据文件。完成后设置 GOOGLE_APPLICATION_CREDENTIALS 环境变量:
或者,在本地机器上可以运行 gcloud auth application-default login 以使用应用默认凭据。
如果在 Web 环境中运行,请安装 @langchain/google-vertexai-web 包(使用 @langchain/google-webauth 用于身份验证)。设置服务账户 JSON 在 GOOGLE_WEB_CREDENTIALS:
GOOGLE_VERTEX_AI_WEB_CREDENTIALS 也支持,但已弃用。
如果您使用的是 Vertex AI 快速模式,您可以安装 @langchain/google-vertexai or @langchain/google-vertexai-web package. 然后您可以前往 快速模式 API 密钥页面并在 GOOGLE_API_KEY 环境变量中设置您的 API 密钥:
如果您想获取模型调用的自动追踪,您还可以设置您的 LangSmith API 密钥,方法是取消下方注释:
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
安装
LangChain ChatVertexAI 集成位于 @langchain/google-vertexai package:
npm install @langchain/google-vertexai @langchain/core
yarn add @langchain/google-vertexai @langchain/core
pnpm add @langchain/google-vertexai @langchain/core
或者,如果在 Web 环境(如 Vercel Edge 函数:
npm install @langchain/google-vertexai-web @langchain/core
yarn add @langchain/google-vertexai-web @langchain/core
pnpm add @langchain/google-vertexai-web @langchain/core
实例化
现在我们可以实例化模型对象并生成聊天补全:
// Uncomment the following line if you're running in a web environment:
// import { ChatVertexAI } from "@langchain/google-vertexai-web"
const llm = new ChatVertexAI({
model: "gemini-2.5-flash",
temperature: 0,
maxRetries: 2,
// For web, authOptions.credentials
// authOptions: { ... }
// other params...
})
调用
const aiMsg = await llm.invoke([
[
"system",
"You are a helpful assistant that translates English to French. Translate the user sentence.",
],
["human", "I love programming."],
])
aiMsg
AIMessageChunk {
"content": "J'adore programmer. \n",
"additional_kwargs": {},
"response_metadata": {},
"tool_calls": [],
"tool_call_chunks": [],
"invalid_tool_calls": [],
"usage_metadata": {
"input_tokens": 20,
"output_tokens": 7,
"total_tokens": 27
}
}
console.log(aiMsg.content)
J'adore programmer.
使用 Google 搜索检索的工具调用
可以使用 Google 搜索工具调用模型,您可以用它来 锚定 通过真实世界信息进行内容生成并减少幻觉。
当前不支持 gemini-2.0-flash-exp.
您可以选择使用 Google 搜索锚定或使用自定义数据存储。以下是两种方式的示例:
Google 搜索检索
使用 Google 搜索的锚定示例:
const searchRetrievalTool = {
googleSearchRetrieval: {
dynamicRetrievalConfig: {
mode: "MODE_DYNAMIC", // Use Dynamic Retrieval
dynamicThreshold: 0.7, // Default for Dynamic Retrieval threshold
},
},
};
const searchRetrievalModel = new ChatVertexAI({
model: "gemini-2.5-pro",
temperature: 0,
maxRetries: 0,
}).bindTools([searchRetrievalTool]);
const searchRetrievalResult = await searchRetrievalModel.invoke("Who won the 2024 NBA Finals?");
console.log(searchRetrievalResult.content);
The Boston Celtics won the 2024 NBA Finals, defeating the Dallas Mavericks 4-1 in the series to claim their 18th NBA championship. This victory marked their first title since 2008 and established them as the team with the most NBA championships, surpassing the Los Angeles Lakers' 17 titles.
带数据存储的 Google 搜索检索
首先,设置您的数据存储(这是示例数据存储的架构):
| ID | Date | Team 1 | Score | Team 2 |
|---|---|---|---|---|
| 3001 | 2023-09-07 | Argentina | 1 - 0 | Ecuador |
| 3002 | 2023-09-12 | Venezuela | 1 - 0 | Paraguay |
| 3003 | 2023-09-12 | Chile | 0 - 0 | Colombia |
| 3004 | 2023-09-12 | Peru | 0 - 1 | Brazil |
| 3005 | 2024-10-15 | Argentina | 6 - 0 | Bolivia |
然后,在下方提供的示例中使用此数据存储:
(请注意,您必须使用自己的变量作为 projectId 和 datastoreId)
const projectId = "YOUR_PROJECT_ID";
const datastoreId = "YOUR_DATASTORE_ID";
const searchRetrievalToolWithDataset = {
retrieval: {
vertexAiSearch: {
datastore: `projects/${projectId}/locations/global/collections/default_collection/dataStores/${datastoreId}`,
},
disableAttribution: false,
},
};
const searchRetrievalModelWithDataset = new ChatVertexAI({
model: "gemini-2.5-pro",
temperature: 0,
maxRetries: 0,
}).bindTools([searchRetrievalToolWithDataset]);
const searchRetrievalModelResult = await searchRetrievalModelWithDataset.invoke(
"What is the score of Argentina vs Bolivia football game?"
);
console.log(searchRetrievalModelResult.content);
Argentina won against Bolivia with a score of 6-0 on October 15, 2024.
现在您应该会获得基于所提供数据存储中的数据的锚定结果。
上下文缓存
Vertex AI 提供上下文缓存功能,通过存储和重用跨多个 API 请求的大量消息内容来帮助优化成本。当您有冗长的对话历史记录或在交互中频繁出现的消息段落时,这尤其有用。
要使用此功能,请先按照 此官方指南.
创建缓存后,您可以通过以下方式将其 ID 作为运行时参数传递:
const modelWithCachedContent = new ChatVertexAI({
model: "gemini-2.5-pro-002",
location: "us-east5",
});
await modelWithCachedContent.invoke("What is in the content?", {
cachedContent:
"projects/PROJECT_NUMBER/locations/LOCATION/cachedContents/CACHE_ID",
});
您还可以将此字段直接绑定到模型实例:
const modelWithBoundCachedContent = new ChatVertexAI({
model: "gemini-2.5-pro-002",
location: "us-east5",
}).bind({
cachedContent:
"projects/PROJECT_NUMBER/locations/LOCATION/cachedContents/CACHE_ID",
});
请注意,并非所有模型当前都支持上下文缓存。
API 参考
所有功能的详细文档 ChatVertexAI 和配置,请参阅 API 参考文档.