跳到主要内容

ChatVertexAI

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

这将帮助您开始使用 ChatVertexAI 聊天模型。有关所有 ChatVertexAI 功能和配置的详细文档,请访问 API 参考

概述

集成详情

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

模型功能

请查看下表标题中的链接,以获取有关如何使用特定功能的指南。

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

请注意,虽然支持 logprobs,但 Gemini 对它们的使用有相当严格的限制。

设置

LangChain.js 支持两种不同的身份验证方法,具体取决于您是在 Node.js 环境还是 Web 环境中运行。它还支持 Vertex AI Express Mode 使用的身份验证方法,可以使用任一软件包。

要访问 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 Mode,您可以安装 @langchain/google-vertexai@langchain/google-vertexai-web 包。然后,您可以转到 Express Mode API 密钥页面,并在 GOOGLE_API_KEY 环境变量中设置您的 API 密钥

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 function)中使用

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.

使用 Google 搜索检索进行工具调用

可以使用 Google 搜索工具调用模型,您可以使用该工具对齐内容生成与真实世界信息,并减少幻觉。

gemini-2.0-flash-exp 当前不支持对齐。

您可以选择使用 Google 搜索或自定义数据存储进行对齐。以下是两者的示例

Google 搜索检索

使用 Google 搜索的对齐示例

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.

使用数据存储的 Google 搜索检索

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

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


此页内容是否有帮助?


您也可以留下详细的反馈 在 GitHub 上.