本库支持访问多种 Google 模型,包括 Gemini 模型系列及其 Nano Banana 图像生成模型。您可以通过 Google 的 Google AI API(有时也称为 Generative AI API 或 AI Studio API)或通过 Google Cloud Platform 的 Vertex AI 服务访问这些模型。
这将帮助您开始使用 ChatGoogle 聊天模型。有关所有 ChatGoogle 功能和配置的详细文档,请前往 API 参考。
集成详情
模型功能
请参见下表标题中的链接,了解如何使用特定功能的指南。
请注意,虽然支持 logprobs,但 Gemini 对其使用有相当严格的限制。
通过 AI Studio 获取凭证(API 密钥)
要通过 Google AI Studio(有时称为 Generative AI API)使用模型,您需要一个 API 密钥。您可以从 Google AI Studio 获取。
获取 API 密钥后,您可以将其设置为环境变量:
export GOOGLE_API_KEY="your-api-key"
或者,您可以直接将其传递给模型构造函数:
import { ChatGoogle } from "@langchain/google";
const llm = new ChatGoogle({
apiKey: "your-api-key",
model: "gemini-2.5-flash",
});
通过 Vertex AI Express Mode 获取凭证(API 密钥)
Vertex AI 还支持 Express Mode,允许您使用 API 密钥进行身份验证。您可以从 Google Cloud Console 获取 Vertex AI API 密钥。
获取 API 密钥后,您可以将其设置为环境变量:
export GOOGLE_API_KEY="your-api-key"
当使用 Vertex AI Express Mode 时,您还需要在实例化模型时指定平台类型为 gcp。
const llm = new ChatGoogle({
model: "gemini-2.5-flash",
platformType: "gcp",
// apiKey: "...", // 如果设置了 GOOGLE_API_KEY,则为可选
});
通过 Vertex AI 获取凭证(OAuth 应用程序默认凭证 / ADC)
对于 Google Cloud 上的生产环境,建议使用 应用程序默认凭证 (ADC)。这在 Node.js 环境中受支持。
如果您在本地机器上运行,可以通过安装 Google Cloud SDK 并运行以下命令来设置 ADC:
gcloud auth application-default login
或者,您可以将 GOOGLE_APPLICATION_CREDENTIALS 环境变量设置为服务账号密钥文件的路径:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-key.json"
通过 Vertex AI 获取凭证(OAuth 保存的凭证)
如果您在 Web 环境中运行或想直接提供凭证,可以使用 GOOGLE_CLOUD_CREDENTIALS 环境变量。这应包含服务账号密钥文件的内容(而不是路径)。
export GOOGLE_CLOUD_CREDENTIALS='{"type":"service_account","project_id":"your-project-id",...}'
您也可以使用 credentials 参数直接在代码中提供这些凭证。
const llm = new ChatGoogle({
model: "gemini-2.5-flash",
platformType: "gcp",
credentials: {
type: "service_account",
project_id: "your-project-id",
private_key_id: "your-private-key-id",
private_key: "your-private-key",
client_email: "your-service-account-email",
client_id: "your-client-id",
auth_uri: "https://accounts.google.com/o/oauth2/auth",
token_uri: "https://oauth2.googleapis.com/token",
auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",
client_x509_cert_url: "your-cert-url",
}
});
如果您想获得模型调用的自动跟踪,还可以通过取消注释以下内容来设置您的 LangSmith API 密钥:
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
LangChain ChatGoogle 集成位于 @langchain/google 包中:
npm install @langchain/google @langchain/core
实例化
导入路径取决于您是在 Node.js 环境还是 Web/Edge 环境中运行。
import { ChatGoogle } from "@langchain/google/node";
模型将根据您的配置自动确定是使用 Google AI API 还是 Vertex AI:
- 如果您提供
apiKey(或设置 GOOGLE_API_KEY),则默认使用 Google AI。
- 如果您提供
credentials(或在 Node 中设置 GOOGLE_APPLICATION_CREDENTIALS / GOOGLE_CLOUD_CREDENTIALS),则默认使用 Vertex AI。
Google AI (AI Studio)
const llm = new ChatGoogle({
model: "gemini-2.5-flash",
maxRetries: 2,
// apiKey: "...", // 如果设置了 GOOGLE_API_KEY,则为可选
});
Vertex AI
const llm = new ChatGoogle({
model: "gemini-2.5-flash",
// credentials: { ... }, // 如果使用 ADC 或 GOOGLE_CLOUD_CREDENTIALS,则为可选
});
Vertex AI Express Mode
要使用带 API 密钥的 Vertex AI(Express Mode),您必须显式设置 platformType。
const llm = new ChatGoogle({
model: "gemini-2.5-flash",
platformType: "gcp",
// apiKey: "...", // 如果设置了 GOOGLE_API_KEY,则为可选
});
模型配置最佳实践
虽然 ChatGoogle 支持标准模型参数,如 temperature、topP 和 topK,但使用 Gemini 模型的最佳实践是将这些参数保留为其默认值。模型围绕这些默认值进行了高度调整。
如果您想控制模型的“随机性”或“创造性”,建议在提示或系统提示中使用特定指令(例如,“要有创造性”、“给出简洁的事实性答案”),而不是调整温度。
import { HumanMessage, SystemMessage } from "@langchain/core/messages";
const aiMsg = await llm.invoke([
new SystemMessage(
"You are a helpful assistant that translates English to French. Translate the user sentence."
),
new HumanMessage("I love programming."),
]);
响应元数据
AIMessage 响应包含有关生成的元数据,包括令牌使用情况和对数概率。
令牌使用情况
usage_metadata 属性允许您检查令牌计数。
const res = await llm.invoke("Hello, how are you?");
console.log(res.usage_metadata);
{ input_tokens: 6, output_tokens: 7, total_tokens: 13 }
Logprobs
如果您在模型配置中启用 logprobs,它们将在 response_metadata 中可用。
const llmWithLogprobs = new ChatGoogle({
model: "gemini-2.5-flash",
logprobs: 2, // 要返回的顶级候选数量
});
const resWithLogprobs = await llmWithLogprobs.invoke("Hello");
console.log(resWithLogprobs.response_metadata.logprobs_result);
安全设置
默认情况下,当前版本的 Gemini 安全设置是关闭的。
如果您想为各种类别启用安全设置,可以使用模型的 safetySettings 属性。
import { ChatGoogle } from "@langchain/google";
const llm = new ChatGoogle({
model: "gemini-2.5-flash",
safetySettings: [
{
category: "HARM_CATEGORY_HARASSMENT",
threshold: "BLOCK_LOW_AND_ABOVE",
},
],
});
结构化输出
您可以使用 withStructuredOutput 方法从模型获取结构化 JSON 输出。
import { ChatGoogle } from "@langchain/google";
import { z } from "zod";
const llm = new ChatGoogle("gemini-2.5-flash");
const schema = z.object({
people: z.array(z.object({
name: z.string().describe("The name of the person"),
age: z.number().describe("The age of the person"),
})),
});
const structuredLlm = llm.withStructuredOutput(schema);
const res = await structuredLlm.invoke("John is 25 and Jane is 30.");
console.log(res);
{
"people": [
{ "name": "John", "age": 25 },
{ "name": "Jane", "age": 30 }
]
}
工具调用
ChatGoogle 支持标准 LangChain 工具调用 以及 Gemini 特定的“专业工具”(如代码执行和 Grounding)。
标准工具
您可以使用使用 Zod 模式定义的 LangChain 标准工具。
import { ChatGoogle } from "@langchain/google";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
const weatherTool = tool((input) => {
return "It is sunny and 75 degrees.";
}, {
name: "get_weather",
description: "Get the weather for a location",
schema: z.object({
location: z.string(),
}),
});
const llm = new ChatGoogle("gemini-2.5-flash")
.bindTools([weatherTool]);
const res = await llm.invoke("What is the weather in SF?");
console.log(res.tool_calls);
专业工具
Gemini 提供了多个用于代码执行和 Grounding 的内置工具。
您不能在同一请求中混合使用这些“专业工具”(代码执行、Google 搜索等)和标准 LangChain 工具(如上面的天气工具)。
代码执行
Gemini 模型支持代码执行,允许模型生成并运行 Python 代码来解决复杂问题。
import { ChatGoogle } from "@langchain/google";
const llm = new ChatGoogle("gemini-2.5-flash")
.bindTools([
{
codeExecution: {},
},
]);
const res = await llm.invoke("Calculate the 100th Fibonacci number.");
console.log(res.contentBlocks);
使用 Google Search 进行 Grounding
您可以使用 googleSearch 工具通过 Google 搜索来 grounding 响应。这对于有关当前事件或特定事实的问题很有用。
googleSearchRetrieval 工具是为了向后兼容而保留的,但推荐使用 googleSearch。
import { ChatGoogle } from "@langchain/google";
const llm = new ChatGoogle("gemini-2.5-flash")
.bindTools([
{
googleSearch: {},
},
]);
const res = await llm.invoke("Who won the latest World Series?");
console.log(res.text);
使用 URL 检索进行 Grounding
您还可以使用特定 URL 来 grounding 响应。
import { ChatGoogle } from "@langchain/google";
const llm = new ChatGoogle("gemini-2.5-flash")
.bindTools([
{
urlContext: {},
},
]);
const prompt = "Summarize this page: https://js.langchain.com/";
const res = await llm.invoke(prompt);
console.log(res.text);
使用数据存储进行 Grounding
如果您使用的是 Vertex AI (platformType: "gcp"),则可以使用 Vertex AI Search 数据存储来 grounding 响应。
import { ChatGoogle } from "@langchain/google";
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 llm = new ChatGoogle({
model: "gemini-2.5-pro",
platformType: "gcp",
}).bindTools([searchRetrievalToolWithDataset]);
const res = await llm.invoke(
"What is the score of Argentina vs Bolivia football game?"
);
console.log(res.text);
上下文缓存
默认情况下,Gemini 模型会进行隐式上下文缓存。如果您发送给 Gemini 的历史记录开头与其缓存中的上下文完全匹配,它将减少该请求的令牌成本。
您还可以显式地将一些内容传递给模型一次,缓存输入令牌,然后在后续请求中引用缓存的令牌以降低成本和延迟。LangChain 不支持创建此显式缓存,但如果您已创建缓存,可以在调用中引用它。
import { ChatGoogle } from "@langchain/google";
const llm = new ChatGoogle("gemini-2.5-pro");
// 将缓存名称传递给模型
const res = await llm.invoke("Summarize this document", {
cachedContent: "projects/123/locations/us-central1/cachedContents/456",
});
多模态请求
ChatGoogle 模型支持多模态请求,允许您发送图像、音频和视频以及文本。您可以使用消息中的 contentBlocks 字段以结构化方式提供这些输入。
import { ChatGoogle } from "@langchain/google";
import { HumanMessage } from "@langchain/core/messages";
import * as fs from "fs";
const llm = new ChatGoogle("gemini-2.5-flash");
const image = fs.readFileSync("./hotdog.jpg").toString("base64");
const res = await llm.invoke([
new HumanMessage({
contentBlocks: [
{
type: "text",
text: "What is in this image?",
},
{
type: "image",
mimeType: "image/jpeg",
data: image,
},
],
}),
]);
console.log(res.text);
const audio = fs.readFileSync("./speech.wav").toString("base64");
const res = await llm.invoke([
new HumanMessage({
contentBlocks: [
{
type: "text",
text: "Summarize this audio.",
},
{
type: "audio",
mimeType: "audio/wav",
data: audio,
},
],
}),
]);
console.log(res.text);
const video = fs.readFileSync("./movie.mp4").toString("base64");
const res = await llm.invoke([
new HumanMessage({
contentBlocks: [
{
type: "text",
text: "Describe the video.",
},
{
type: "video",
mimeType: "video/mp4",
data: video,
},
],
}),
]);
console.log(res.text);
推理 / 思考
Google 的 Gemini 2.5 和 Gemini 3 模型支持“思考”或“推理”步骤。即使您没有显式配置,这些模型也可能执行推理,但库仅在您显式设置推理/思考量时才返回推理摘要(思考块)。
本库提供模型之间的兼容性,允许您使用统一参数:
-
maxReasoningTokens(或 thinkingBudget):指定用于推理的最大令牌数。
0:关闭推理(如果支持)。
-1:使用模型的默认值。
> 0:设置特定的令牌预算。
-
reasoningEffort(或 thinkingLevel):设置相对努力程度。
- 值:
"minimal"、"low"、"medium"、"high"。
import { ChatGoogle } from "@langchain/google";
const llm = new ChatGoogle({
model: "gemini-3.1-pro-preview",
reasoningEffort: "high",
});
const res = await llm.invoke("What is the square root of 144?");
// 推理步骤在 contentBlocks 中可用
const reasoningBlocks = res.contentBlocks.filter((block) => block.type === "reasoning");
reasoningBlocks.forEach((block) => {
if (block.type === "reasoning") {
console.log("Thought:", block.reasoning);
}
});
console.log("Answer:", res.text);
思考块还包括一个 reasoningContentBlock 字段。这包含基于 Gemini 发送的底层部分的 ContentBlock。虽然这通常是一个文本块,但对于像 Nano Banana Pro 这样的多模态模型,它可能是图像或其他媒体块。
使用 Nano Banana 和 Nano Banana Pro 生成图像
要生成图像,您需要使用支持此功能的模型(例如 gemini-2.5-flash-image),并将 responseModalities 配置为包含 “IMAGE”。
import { ChatGoogle } from "@langchain/google";
import * as fs from "fs";
const llm = new ChatGoogle({
model: "gemini-2.5-flash-image",
responseModalities: ["IMAGE", "TEXT"],
});
const res = await llm.invoke(
"I would like to see a drawing of a house with the sun shining overhead. Drawn in crayon."
);
// 生成的图像在消息的 contentBlocks 中返回
for (const [index, block] of res.contentBlocks.entries()) {
if (block.type === "file" && block.data) {
const base64Data = block.data;
// 根据 MIME 类型确定正确的文件扩展名
const mimeType = (block.mimeType || "image/png").split(";")[0];
const extension = mimeType.split("/")[1] || "png";
const filename = `generated_image_${index}.${extension}`;
// 将图像保存到文件
fs.writeFileSync(filename, Buffer.from(base64Data, "base64"));
console.log(`[Saved image to ${filename}]`);
} else if (block.type === "text") {
console.log(block.text);
}
}
语音生成 (TTS)
一些 Gemini 模型支持生成语音(音频输出)。要启用此功能,请将 responseModalities 配置为包含 “AUDIO” 并提供 speechConfig。
speechConfig 可以是 完整的 Gemini 语音配置对象,但在大多数情况下,您只需提供一个包含预构建语音名称的字符串。
许多模型以原始 PCM 格式 (audio/L16) 返回音频,这需要 WAV 头才能被大多数媒体播放器播放。
import { ChatGoogle } from "@langchain/google";
import * as fs from "fs";
const llm = new ChatGoogle({
model: "gemini-2.5-flash-preview-tts",
responseModalities: ["AUDIO", "TEXT"],
speechConfig: "Zubenelgenubi", // 预构建语音名称
});
const res = await llm.invoke("Say cheerfully: Have a wonderful day!");
// 向原始 PCM 数据添加 WAV 头的函数
function addWavHeader(pcmData: Buffer, sampleRate = 24000) {
const header = Buffer.alloc(44);
header.write("RIFF", 0);
header.writeUInt32LE(36 + pcmData.length, 4);
header.write("WAVE", 8);
header.write("fmt ", 12);
header.writeUInt32LE(16, 16);
header.writeUInt16LE(1, 20); // PCM
header.writeUInt16LE(1, 22); // Mono
header.writeUInt32LE(sampleRate, 24);
header.writeUInt32LE(sampleRate * 2, 28); // 字节率(16 位单声道)
header.writeUInt16LE(2, 32); // 块对齐
header.writeUInt16LE(16, 34); // 每样本位数
header.write("data", 36);
header.writeUInt32LE(pcmData.length, 40);
return Buffer.concat([header, pcmData]);
}
// 生成的音频在 contentBlocks 中返回
for (const [index, block] of res.contentBlocks.entries()) {
if (block.type === "file" && block.data) {
let audioBuffer = Buffer.from(block.data, "base64");
let filename = `generated_audio_${index}.wav`;
if (block.mimeType?.startsWith("audio/L16")) {
audioBuffer = addWavHeader(audioBuffer);
} else if (block.mimeType) {
// 忽略 mimeType 中的参数,例如 "; rate=24000"
const mimeType = block.mimeType.split(";")[0];
const extension = mimeType.split("/")[1] || "wav";
filename = `generated_audio_${index}.${extension}`;
}
// 将音频保存到文件
fs.writeFileSync(filename, audioBuffer);
console.log(`[Saved audio to ${filename}]`);
} else if (block.type === "text") {
console.log(block.text);
}
}
多说话人 TTS
您还可以为单个请求配置多个说话人。这对于让 Gemini 朗读脚本很有用。此简化的 speechConfig 要求您为每个预定义的 name(代表语音)分配一个 speaker,然后在脚本中使用该说话人。
const multiSpeakerLlm = new ChatGoogle({
model: "gemini-2.5-flash-preview-tts",
responseModalities: ["AUDIO"],
speechConfig: [
{ speaker: "Joe", name: "Kore" },
{ speaker: "Jane", name: "Puck" },
],
});
const res = await multiSpeakerLlm.invoke(`
Joe: How's it going today, Jane?
Jane: Not too bad, how about you?
`);
API 参考
有关所有 ChatGoogle 功能和配置的详细文档,请前往 API 参考。