Skip to main content
Google Vertex 是一项服务,它公开了 Google Cloud 中所有可用的基础模型,例如 gemini-2.5-progemini-2.5-flash 等。 它还提供一些非 Google 模型,例如 Anthropic 的 Claude 这将帮助您开始使用 ChatVertexAI 聊天模型。有关所有 ChatVertexAI 功能和配置的详细文档,请参阅 API 参考
此库将被弃用此库将被 ChatGoogle 库取代。 新实现应使用 ChatGoogle 库, 现有实现应考虑迁移。

概述

集成详情

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

模型特性

有关如何使用特定功能的指南,请参阅下表标题中的链接。 请注意,虽然支持对数概率,但 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 包中:
npm install @langchain/google-vertexai @langchain/core
如果在 Web 环境(如 Vercel Edge 函数)中使用:
npm install @langchain/google-vertexai-web @langchain/core

实例化

现在我们可以实例化模型对象并生成聊天补全:
import { ChatVertexAI } from "@langchain/google-vertexai"
// 如果在 Web 环境中运行,请取消注释以下行:
// import { ChatVertexAI } from "@langchain/google-vertexai-web"

const llm = new ChatVertexAI({
    model: "gemini-2.5-flash",
    temperature: 0,
    maxRetries: 2,
    // 对于 Web 环境,使用 authOptions.credentials
    // authOptions: { ... }
    // 其他参数...
})

调用

const aiMsg = await llm.invoke([
    [
        "system",
        "您是一个将英语翻译成法语的助手。请翻译用户的句子。",
    ],
    ["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", // 使用动态检索
      dynamicThreshold: 0.7, // 动态检索阈值的默认值
    },
  },
};

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日期队伍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-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 作为运行时参数传入,如下所示:
import { ChatVertexAI } from "@langchain/google-vertexai";

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 参考