Skip to main content
此库支持访问各种 Google 模型,包括 Gemini 系列模型及其 Nano Banana 图像生成模型。您可以通过 Google 的 Google AI API(有时也称为 Generative AI API 或 AI Studio API)或通过 Google Cloud Platform Vertex AI 服务访问这些模型。 这将帮助您开始使用 ChatGoogle 聊天模型。有关所有 ChatGoogle 功能和配置的详细文档,请访问 API 参考
@langchain/google 是所有新 Google Gemini 集成的推荐包。 它取代了旧的 @langchain/google-genai@langchain/google-vertexai 包。 请参阅旧版包以获取迁移详细信息。

概览

集成详情

可序列化PY 支持下载量版本
ChatGoogle@langchain/googleNPM - DownloadsNPM - Version

模型功能

请参阅下表标题中的链接,以获取有关如何使用特定功能的指南。 请注意,虽然支持 logprobs,但 Gemini 对它们的使用有相当大的限制。

设置

通过 AI Studio 获取凭证 (API Key)

要通过 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 Key)

Vertex AI 还支持 Express Mode, 它允许您使用 API 密钥进行身份验证。您可以从 Google Cloud 控制台 获取 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: "...", // Optional if GOOGLE_API_KEY is set
});

通过 Vertex AI 获取凭证 (OAuth Application Default Credentials / ADC)

对于 Google Cloud 上的生产环境,建议使用 Application Default Credentials (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 saved credentials)

如果您在 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",
  }
});

追踪 (Tracing)

如果您想自动跟踪模型调用,您还可以通过取消注释以下内容来设置您的 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: "...", // 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 支持标准的模型参数,如 temperaturetopPtopK, 但 Gemini 模型的最佳实践是将这些参数保留为默认值。这些模型是围绕这些默认值进行高度调优的。 如果您想控制模型的“随机性”或“创造力”,建议在提示或系统提示中使用具体指令(例如,“要有创意”、“给出简洁的事实性回答”),而不是调整 temperature。

调用

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

响应元数据

AIMessage 响应包含有关生成的元数据,包括 token 使用情况和对数概率 (log probabilities)。

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

如果您在模型配置中启用了 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 属性。
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 schema 定义的标准 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 搜索进行 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 的历史记录的开头与 Gemini 在其缓存中的上下文完全匹配,它将减少该请求的 token 成本。 您也可以显式地将一些内容传递给模型一次,缓存输入 token,然后在后续请求中引用缓存的 token 以降低成本和延迟。LangChain 不支持创建此显式缓存,但如果您已创建缓存,则可以在调用中引用它。
import { ChatGoogle } from "@langchain/google";

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 字段以结构化方式提供这些输入。

图像

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

推理 / 思考 (Reasoning / Thinking)

Google 的 Gemini 2.5 和 Gemini 3 模型支持“思考”或“推理”步骤。 即使您没有显式配置,这些模型也可能执行推理,但只有当您显式设置推理/思考的值时,该库才会返回推理摘要(思维块)。 此库提供模型之间的兼容性,允许您使用统一的参数:
  • maxReasoningTokens (或 thinkingBudget): 指定用于推理的最大 token 数。
    • 0: 关闭推理(如果支持)。
    • -1: 使用模型的默认值。
    • > 0: 设置特定的 token 预算。
  • 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?");

// 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);
思维块还包含一个 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."
);

// 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 标头才能被大多数媒体播放器播放。
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", // 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 要求您为代表声音的每个预定义 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 参考