本库支持访问多种 Google 模型,包括 Gemini 系列模型及其 Nano Banana 图像生成模型。你可以通过 Google 的 Google AI API(有时也称为生成式 AI API 或 AI Studio API)或通过 Google Cloud Platform 的 Vertex AI 服务来访问这些模型。
这将帮助你开始使用 ChatGoogle 聊天模型 。有关所有 ChatGoogle 功能和配置的详细文档,请前往 API 参考 。
集成详情
模型功能
有关如何使用特定功能的指南,请参阅下表标题中的链接。
请注意,虽然支持对数概率,但 Gemini 对其使用有相当严格的限制。
通过 AI Studio 获取凭据(API 密钥)
要通过 Google AI Studio(有时称为生成式 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 快速模式获取凭据(API 密钥)
Vertex AI 还支持快速模式 ,允许你使用 API 密钥进行身份验证。你可以从 Google Cloud 控制台 获取 Vertex AI API 密钥。
获得 API 密钥后,你可以将其设置为环境变量:
export GOOGLE_API_KEY = "your-api-key"
使用 Vertex AI 快速模式 时,你还需要在实例化模型时将平台类型指定为 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 快速模式
要使用带有 API 密钥的 Vertex AI(快速模式),你必须显式设置 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,它们将在 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 特有的“专用工具”(如代码执行和接地)。
标准工具
你可以使用使用 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 提供了几个用于代码执行和接地的内置工具。
你不能在同一个请求中混合使用这些“专用工具”(代码执行、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 搜索进行接地
你可以使用 googleSearch 工具通过 Google 搜索来接地响应。这对于有关时事或特定事实的问题很有用。
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 检索进行接地
你也可以使用特定的 URL 来接地响应。
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) ;
使用数据存储进行接地
如果你使用的是 Vertex AI(platformType: "gcp"),你可以使用 Vertex AI Search 数据存储来接地响应。
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 的历史记录开头与 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 ) ; // 单声道
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 参考 。
将这些文档连接 到 Claude、VSCode 等,通过 MCP 获取实时答案。