跳到主要内容
Google Vertex 是一项服务,它公开了 Google Cloud 中所有可用的基础模型,例如 gemini-2.5-progemini-2.5-flash 等。它还提供了一些非 Google 模型,例如 Anthropic 的 Claude 这将帮助您开始使用 ChatVertexAI 聊天模型。有关所有 ChatVertexAI 功能和配置的详细文档,请参阅API 参考

概览

集成详情

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

模型功能

有关如何使用特定功能的指南,请参阅下表标题中的链接。
工具调用结构化输出JSON 模式图像输入音频输入视频输入令牌级流式传输Token 用量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 Key 页面,并将您的 API Key 设置在 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 包中
npm install @langchain/google-vertexai @langchain/core
或者如果在 Web 环境中使用,例如 Vercel Edge 函数
npm install @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.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 搜索进行基础的示例
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",
});

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

API 参考

有关所有 ChatVertexAI 功能和配置的详细文档,请参阅API 参考
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.