ChatGoogle 통합

ChatGoogle 통합

LangChain JavaScript로 ChatGoogle 채팅 모델과 통합하는 방법을 안내할게요.

출처: 문서

본문

이 라이브러리는 Gemini 계열 모델과 그들의 Nano Banana 이미지 생성 모델을 포함해 다양한 Google 모델에 대한 접근을 지원해요. 이러한 모델에 Google의 Google AI API(때로는 Generative AI API 또는 AI Studio API라고도 함) 또는 Google Cloud Platform의 Gemini Enterprise Agent Platform 서비스를 통해 접근할 수 있어요.

이 문서는 ChatGoogle 채팅 모델을 시작하는 데 도움을 줘요. 모든 ChatGoogle 기능과 구성에 대한 자세한 문서는 API 레퍼런스를 참고하세요.

`@langchain/google` is the recommended package for all new Google Gemini integrations. It replaces the older [`@langchain/google-genai`](/oss/javascript/integrations/chat/google_generative_ai) and [`@langchain/google-vertexai`](/oss/javascript/integrations/chat/google_vertex_ai) packages. See [legacy packages](/oss/javascript/integrations/providers/google#legacy-packages) for migration details.

개요

통합 세부 정보

클래스 패키지 Serializable PY 지원 Downloads Version
ChatGoogle @langchain/google NPM - Downloads NPM - Version

모델 기능

아래 표 헤더의 링크에서 특정 기능을 사용하는 방법에 대한 가이드를 확인할 수 있어요.

Tool calling Structured output Image input Audio input Video input Token-level streaming Token usage Logprobs

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: ***
  model: "gemini-3.7-flash",
});

Gemini Enterprise Agent Platform Express Mode를 통한 자격 증명 (API 키)

Gemini Enterprise Agent Platform은 API 키를 사용한 인증을 허용하는 Express Mode도 지원해요. Google Cloud 콘솔에서 Gemini Enterprise Agent Platform API 키를 받을 수 있어요.

API 키를 받았다면 환경 변수로 설정할 수 있어요:

export GOOGLE_API_KEY="your-api-key"

Gemini Enterprise Agent Platform Express Mode를 사용할 때는 모델을 인스턴스화할 때 플랫폼 유형을 gcp로 지정해야 해요.

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

Gemini Enterprise Agent Platform을 통한 자격 증명 (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"

Gemini Enterprise Agent Platform을 통한 자격 증명 (OAuth 저장 자격 증명)

웹 환경에서 실행하거나 자격 증명을 직접 제공하려면 GOOGLE_CLOUD_CREDENTIALS 환경 변수를 사용할 수 있어요. 이 변수는 서비스 계정 키 파일의 내용을 담아야 해요 (경로가 아니라).

export GOOGLE_CLOUD_CREDENTIALS='{"type":"service_account","project_id":"your-project-id",...}'

코드에서 credentials 매개변수를 사용해 이러한 자격 증명을 직접 제공할 수도 있어요.

const llm = new ChatGoogle({
  model: "gemini-3.7-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 패키지에 있어요:

```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}} npm install @langchain/google @langchain/core ```
yarn add @langchain/google @langchain/core
pnpm add @langchain/google @langchain/core

인스턴스 생성

임포트 경로는 Node.js 환경에서 실행하는지 웹/엣지 환경에서 실행하는지에 따라 달라져요.

```typescript Node.js theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}} import { ChatGoogle } from "@langchain/google/node"; ```
import { ChatGoogle } from "@langchain/google";

모델은 구성에 따라 Google AI API 또는 Gemini Enterprise Agent Platform을 사용할지 자동으로 결정해요:

  • apiKey를 제공하면(또는 GOOGLE_API_KEY를 설정하면) 기본적으로 Google AI를 사용해요.
  • credentials를 제공하면(또는 Node에서 GOOGLE_APPLICATION_CREDENTIALS/GOOGLE_CLOUD_CREDENTIALS를 설정하면) 기본적으로 Gemini Enterprise Agent Platform을 사용해요.

Google AI (AI Studio)

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

Gemini Enterprise Agent Platform

const llm = new ChatGoogle({
  model: "gemini-3.7-flash",
  // credentials: { ... }, // Optional if using ADC or GOOGLE_CLOUD_CREDENTIALS
});

Gemini Enterprise Agent Platform Express Mode

Gemini Enterprise Agent Platform을 API 키로 사용하려면(Express Mode) platformType을 명시적으로 설정해야 해요.

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

모델 구성 모범 사례

ChatGoogletemperature, topP, topK 같은 표준 모델 매개변수를 지원하지만, 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 응답에는 토큰 사용량 및 로그 확률(log probabilities)을 포함한 생성에 대한 메타데이터가 담겨 있어요.

토큰 사용량

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-3.7-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-3.7-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-3.7-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 }
  ]
}

Tool calling

ChatGoogle은 표준 LangChain tool calling과 Gemini 특화 "Specialty Tools"(Code Execution 및 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-3.7-flash")
  .bindTools([weatherTool]);

const res = await llm.invoke("What is the weather in SF?");
console.log(res.tool_calls);

Specialty Tools

Gemini는 코드 실행과 grounding을 위한 여러 내장 도구를 제공해요.

You cannot mix these "Specialty Tools" (Code Execution, Google Search, etc.) with standard LangChain tools (like the weather tool above) in the same request.

코드 실행

Gemini 모델은 코드 실행을 지원하며, 모델이 Python 코드를 생성하고 실행해 복잡한 문제를 해결할 수 있게 해줘요.

import { ChatGoogle } from "@langchain/google";

const llm = new ChatGoogle("gemini-3.7-flash")
  .bindTools([
    {
      codeExecution: {},
    },
  ]);

const res = await llm.invoke("Calculate the 100th Fibonacci number.");
console.log(res.contentBlocks);

Google Search로 grounding

googleSearch 도구를 사용해 응답을 Google Search에 기반(grounding)시킬 수 있어요. 최신 이벤트나 특정 사실에 대한 질문에 유용해요.

The `googleSearchRetrieval` tool is maintained for backwards compatibility, but `googleSearch` is preferred.
import { ChatGoogle } from "@langchain/google";

const llm = new ChatGoogle("gemini-3.7-flash")
  .bindTools([
    {
      googleSearch: {},
    },
  ]);

const res = await llm.invoke("Who won the latest World Series?");
console.log(res.text);

URL 검색으로 grounding

특정 URL을 사용해 응답을 기반시킬 수도 있어요.

import { ChatGoogle } from "@langchain/google";

const llm = new ChatGoogle("gemini-3.7-flash")
  .bindTools([
    {
      urlContext: {},
    },
  ]);

const prompt = "Summarize this page: https://js.langchain.com/";
const res = await llm.invoke(prompt);
console.log(res.text);

데이터 저장소로 grounding

Gemini Enterprise Agent Platform을 사용한다면(platformType: "gcp") Agent 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-3.1-pro-preview",
  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-3.1-pro-preview");

// 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-3.7-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 모델은 "thinking" 또는 "reasoning" 단계를 지원해요. 이러한 모델은 명시적으로 구성하지 않아도 추론을 수행할 수 있지만, 라이브러리는 추론할 양을 명시적으로 설정한 경우에만 추론 요약(thought blocks)을 반환해요.

이 라이브러리는 모델 간 호환성을 제공하여 통합된 매개변수를 사용할 수 있게 해줘요:

  • 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?");

// 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);
Thought blocks also include a `reasoningContentBlock` field. This contains the `ContentBlock` based on the underlying part sent by Gemini. While this is typically a text block, for multimodal models like Nano Banana Pro, it could be an image or other media block.

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는 음성을 나타내는 각 미리 정의된 namespeaker를 할당한 다음 대본에서 그 화자를 사용해야 해요.

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 레퍼런스를 참고하세요.


[Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers. [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/chat/google.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).

더 알아보기