以编程方式使用文档

此库支持访问 Google 的多种模型,包括 Gemini 系列模型及其 Nano Banana 图像生成模型。您可以通过以下方式访问这些 模型:通过 Google 的 Google AI API(有时也称为 生成式 AI API 或 AI Studio API)或通过 Google Cloud Platform Vertex AI service.

这将帮助您开始使用 ChatGoogle 聊天模型. 有关所有 ChatGoogle 功能和配置的详细文档,请前往 API 参考.

概述

集成详情

可序列化PY 支持下载量版本
ChatGoogle@langchain/google!NPM - 下载量!NPM - 版本

模型功能

请参阅下面表头中的链接,了解如何使用特定功能。

工具调用结构化输出图像输入音频输入视频输入Token 级流式输出Token 使用量Logprobs

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

设置

通过 AI Studio 获取凭证(API 密钥)

要通过 Google AI Studio(有时也称为生成式 AI API)使用模型,您需要一个 API 密钥。您可以从以下位置获取一个: Google AI Studio.

获取 API 密钥后,您可以将其设置为环境变量:

或者您可以直接将其传递给模型构造函数:

const llm = new ChatGoogle({
  apiKey: "your-api-key",
  model: "gemini-2.5-flash",
});

通过 Vertex AI Express Mode 获取凭证(API 密钥)

Vertex AI 还支持 Express Mode, ,允许您使用 API 密钥进行身份验证。您可以从以下位置获取 Vertex AI API 密钥: Google Cloud Console.

获得API密钥后,您可以将其设置为环境变量:

使用 Vertex AI Express Mode时,您还需要指定平台 类型为 gcp 在实例化模型时。

const llm = new ChatGoogle({
  model: "gemini-2.5-flash",
  platformType: "gcp",
  // apiKey: "...", // Optional if GOOGLE_API_KEY is set
});

Credentials through Vertex AI (OAuth Application Default Credentials / ADC)

对于Google Cloud上的生产环境,建议使用 应用默认凭据(ADC). Node.js环境支持此功能。

如果在本地机器上运行,您可以通过安装 Google Cloud SDK 并运行以下命令来设置ADC:

gcloud auth application-default login

或者,您可以将 GOOGLE_APPLICATION_CREDENTIALS 环境 变量设置为服务账号密钥文件的路径:

通过Vertex AI的凭据(保存的OAuth凭据)

如果在Web环境中运行或想直接提供凭据, 可以使用 GOOGLE_CLOUD_CREDENTIALS 环境变量。这应该包含 您的服务账号密钥文件的 **内容** (而不是路径)。

您也可以使用 credentials parameter.

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 package:

npm install @langchain/google @langchain/core
yarn add @langchain/google @langchain/core
pnpm add @langchain/google @langchain/core

实例化

The import path differs depending on whether you are running in a Node.js environment or a Web/Edge environment.

模型会自动根据您的配置决定是使用Google AI API还是Vertex AI: - 如果您提供 apiKey (或设置 GOOGLE_API_KEY),它默认为Google AI。 - 如果您提供 credentials (或设置 GOOGLE_APPLICATION_CREDENTIALS / GOOGLE_CLOUD_CREDENTIALS 在Node中),它默认为Vertex AI。

Google AI(AI Studio)

const llm = new ChatGoogle({
  model: "gemini-2.5-flash",
  maxRetries: 2,
  // apiKey: "...", // Optional if GOOGLE_API_KEY is set
});

Vertex AI

const llm = new ChatGoogle({
  model: "gemini-2.5-flash",
  // credentials: { ... }, // Optional if using ADC or 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: "...", // Optional if GOOGLE_API_KEY is set
});

模型配置最佳实践

虽然 ChatGoogle 支持 temperature, topP等标准模型参数,但 topK, Gemini模型的最佳实践是保持这些参数的默认值。这些模型围绕这些默认值进行了高度调优。

如果您想控制模型的"随机性"或"创造性",建议 在提示词或系统提示词中使用特定指令(例如"要有创意"、 "给出简洁的事实回答"),而不是调整温度。

调用

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."),
]);
console.log(aiMsg.text);
J'adore programmer.

响应元数据

AIMessage 响应包含有关生成的元数据,包括 token 使用量和日志概率。

Token 使用量

usage_metadata 属性允许您检查 token 计数。

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, // Number of top candidates to return
});

const resWithLogprobs = await llmWithLogprobs.invoke("Hello");

console.log(resWithLogprobs.response_metadata.logprobs_result);

安全设置

默认情况下,当前版本的 Gemini 安全设置处于关闭状态。

如果您想为各种类别启用安全设置,可以使用 的 safetySettings 模型属性。

const llm = new ChatGoogle({
  model: "gemini-2.5-flash",
  safetySettings: [
    {
      category: "HARM_CATEGORY_HARASSMENT",
      threshold: "BLOCK_LOW_AND_ABOVE",
    },
  ],
});

结构化输出

您可以使用 withStructuredOutput 方法从模型获取结构化的JSON输出。

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 工具调用 as 以及 Gemini 特定的"专业工具"(如代码执行和接地)。

标准工具

您可以使用使用 Zod schema 定义的标准 LangChain 工具。

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 提供了多个用于代码执行和接地的内置工具。

代码执行

Gemini 模型支持代码执行,允许模型生成和运行 Python 代码来解决复杂问题。

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 搜索来接地响应。 这对于有关时事或具体事实的问题很有用。

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 来接地响应。

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 数据存储来接地响应。

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 缓存中的上下文完全匹配,它将降低该请求的 token 成本。 its cache, it will reduce the token cost for that request.

您还可以显式地将某些内容传递给模型一次,然后缓存输入 令牌,然后引用缓存的令牌用于后续请求以降低成本 和延迟。LangChain 不支持创建此显式缓存,但 如果您已创建缓存,则可以在调用中引用它。

const llm = new ChatGoogle("gemini-2.5-pro");

// Pass the cache name to the model
const res = await llm.invoke("Summarize this document", {
  cachedContent: "projects/123/locations/us-central1/cachedContents/456",
});

多模态请求

ChatGoogle 模型支持多模态请求,允许您发送图像、 音频和视频以及文本。您可以使用 contentBlocks 字段在您的 消息中以结构化方式提供这些输入。

图像

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);

Reasoning / Thinking

Google 的 Gemini 2.5 和 Gemini 3 模型支持"思考"或"推理"步骤。 这些模型即使您没有显式配置也可能会执行推理, 但该库仅在您 explicitly set a value for how much to reason/think.

该库提供模型之间的兼容性,允许您使用统一参数:

  • - maxReasoningTokens (or thinkingBudget):指定用于推理的最大令牌数。
  • - 0:关闭推理(如果支持)。
  • - -1:使用模型的默认设置。
  • - > 0:设置特定的令牌预算。
  • - reasoningEffort (or thinkingLevel):设置相对努力程度。
  • - Values: "minimal", "low", "medium", "high".
const llm = new ChatGoogle({
  model: "gemini-3.1-pro-preview",
  reasoningEffort: "high",
});

const res = await llm.invoke("What is the square root of 144?");

// The reasoning steps are available in the 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);

使用 Nano Banana 和 Nano Banana Pro 进行图像生成

要生成图像,您需要使用支持它的模型(例如 gemini-2.5-flash-image)并配置 responseModalities to 包含"IMAGE"。

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."
);

// Generated images are returned in the contentBlocks of the message
for (const [index, block] of res.contentBlocks.entries()) {
  if (block.type === "file" && block.data) {
    const base64Data = block.data;
    // Determine the correct file extension from the MIME type
    const mimeType = (block.mimeType || "image/png").split(";")[0];
    const extension = mimeType.split("/")[1] || "png";
    const filename = `generated_image_${index}.${extension}`;

    // Save the image to a file
    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 头才能被大多数媒体播放器播放。

const llm = new ChatGoogle({
  model: "gemini-2.5-flash-preview-tts",
  responseModalities: ["AUDIO", "TEXT"],
  speechConfig: "Zubenelgenubi", // Prebuilt voice name
});

const res = await llm.invoke("Say cheerfully: Have a wonderful day!");

// Function to add a WAV header to raw PCM data
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); // Byte rate (16-bit mono)
  header.writeUInt16LE(2, 32); // Block align
  header.writeUInt16LE(16, 34); // Bits per sample
  header.write("data", 36);
  header.writeUInt32LE(pcmData.length, 40);
  return Buffer.concat([header, pcmData]);
}

// Generated audio is returned in the 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) {
      // Ignore parameters in the mimeType, such as "; rate=24000"
      const mimeType = block.mimeType.split(";")[0];
      const extension = mimeType.split("/")[1] || "wav";
      filename = `generated_audio_${index}.${extension}`;
    }

    // Save the audio to a file
    fs.writeFileSync(filename, audioBuffer);
    console.log(`[Saved audio to ${filename}]`);
  } else if (block.type === "text") {
    console.log(block.text);
  }
}

多说话者 TTS

您也可以为单个请求配置多个说话者。这对于让 Gemini 朗读脚本很有用。简化的 speechConfig 需要您分配 a speaker 给每个预定义的 name 表示语音,然后使用该 说话者在脚本中。

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