Skip to main content

ChatVertexAI

Google Vertex 是一项服务,提供了 Google Cloud 中可用的所有基础模型,例如 gemini-1.5-progemini-2.0-flash-exp 等。 它还提供了一些非 Google 的模型,例如 Anthropic 的 Claude

这将帮助你快速上手使用 ChatVertexAI 聊天模型。如需了解 ChatVertexAI 所有功能和配置的详细文档,请参阅 API 参考

概览

集成详情

本地可序列化PY 支持包下载量包最新版本
ChatVertexAI@langchain/google-vertexaiNPM - 下载量NPM - 版本

模型功能

有关如何使用特定功能的指南,请参阅下表标题中的链接。

工具调用结构化输出JSON 模式图像输入音频输入视频输入逐令牌流式传输令牌使用情况Logprobs

请注意,虽然支持 logprobs,但 Gemini 对其使用有较为严格的限制。

安装配置

LangChain.js 支持两种不同的认证方式,具体取决于你是在 Node.js 环境还是 Web 环境中运行。 它还支持使用任一包通过 Vertex AI Express 模式使用的认证方法。

要访问 ChatVertexAI 模型,你需要在你的 Google Cloud Platform (GCP) 账户中设置 Google VertexAI,保存凭证文件,并安装 @langchain/google-vertexai 集成包。

凭证

前往你的 GCP 账户 并生成一个凭证文件。完成此操作后,设置 GOOGLE_APPLICATION_CREDENTIALS 环境变量:

export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/credentials.json"

如果在 Web 环境中运行,应将 GOOGLE_VERTEX_AI_WEB_CREDENTIALS 环境变量设为 JSON 格式的字符串对象,并安装 @langchain/google-vertexai-web 包:

GOOGLE_VERTEX_AI_WEB_CREDENTIALS={"type":"service_account","project_id":"YOUR_PROJECT-12345",...}

如果你使用的是 Vertex AI Express 模式,则可以安装 @langchain/google-vertexai@langchain/google-vertexai-web 包。 然后你可以前往 Express 模式 的 API 密钥页面,并将你的 API 密钥设置在 GOOGLE_API_KEY 环境变量中:

export GOOGLE_API_KEY="api_key_value"

如果你想获取模型调用的自动追踪,还可以通过取消注释以下内容来设置你的 LangSmith API 密钥:

# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"

安装

LangChain 的 ChatVertexAI 集成位于 @langchain/google-vertexai 包中:

:::提示 请参阅安装集成包的一般说明部分。 :::

yarn add @langchain/google-vertexai @langchain/core

或者如果在 Web 环境中使用,例如 Vercel Edge 函数

yarn add @langchain/google-vertexai-web @langchain/core

实例化

现在我们可以实例化我们的模型对象并生成聊天补全结果:

import { ChatVertexAI } from "@langchain/google-vertexai";
// 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.0-flash-exp",
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.

使用谷歌搜索检索的工具调用

您可以使用谷歌搜索工具调用模型,从而通过现实世界的信息来支持内容生成并减少幻觉的产生。

目前 gemini-2.0-flash-exp 不支持基础信息支持(Grounding)。

您可以选择使用谷歌搜索进行基础信息支持,或者通过自定义数据存储来实现。以下是两者的示例:

谷歌搜索检索

使用谷歌搜索的示例:

import { ChatVertexAI } from "@langchain/google-vertexai";

const searchRetrievalTool = {
googleSearchRetrieval: {
dynamicRetrievalConfig: {
mode: "MODE_DYNAMIC", // Use Dynamic Retrieval
dynamicThreshold: 0.7, // Default for Dynamic Retrieval threshold
},
},
};

const searchRetrievalModel = new ChatVertexAI({
model: "gemini-1.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.

使用数据存储进行谷歌搜索检索

首先,设置你的数据存储(这是一个示例数据存储的模式):

ID日期球队 1比分球队 2
30012023-09-07阿根廷1 - 0厄瓜多尔
30022023-09-12委内瑞拉1 - 0巴拉圭
30032023-09-12智利0 - 0哥伦比亚
30042023-09-12秘鲁0 - 1巴西
30052024-10-15阿根廷6 - 0玻利维亚

然后,在下面提供的示例中使用此数据存储:

(请注意,你需要为 projectIddatastoreId 使用自己的变量)

import { ChatVertexAI } from "@langchain/google-vertexai";

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-1.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 作为运行时参数传入:

import { ChatVertexAI } from "@langchain/google-vertexai";

const modelWithCachedContent = new ChatVertexAI({
model: "gemini-1.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-1.5-pro-002",
location: "us-east5",
}).bind({
cachedContent:
"projects/PROJECT_NUMBER/locations/LOCATION/cachedContents/CACHE_ID",
});

请注意,并非所有模型当前都支持上下文缓存。

链式调用

我们可以像这样将模型与提示模板进行链式调用

import { ChatPromptTemplate } from "@langchain/core/prompts";

const prompt = ChatPromptTemplate.fromMessages([
[
"system",
"You are a helpful assistant that translates {input_language} to {output_language}.",
],
["human", "{input}"],
]);

const chain = prompt.pipe(llm);
await chain.invoke({
input_language: "English",
output_language: "German",
input: "I love programming.",
});
AIMessageChunk {
"content": "Ich liebe das Programmieren. \n",
"additional_kwargs": {},
"response_metadata": {},
"tool_calls": [],
"tool_call_chunks": [],
"invalid_tool_calls": [],
"usage_metadata": {
"input_tokens": 15,
"output_tokens": 9,
"total_tokens": 24
}
}

API 参考文档

有关 ChatVertexAI 所有功能和配置的详细文档,请访问 API 参考页面: https://api.js.langchain.com/classes/langchain_google_vertexai.ChatVertexAI.html


Was this page helpful?


You can also leave detailed feedback on GitHub.