ChatVertexAI 통합

ChatVertexAI 통합

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

출처: 문서

본문

Gemini Enterprise Agent Platform은 Google Cloud에서 사용 가능한 모든 기반 모델을 노출하는 서비스로, gemini-2.5-pro, gemini-2.5-flash 등을 제공해요. 또한 Anthropic의 Claude 같은 일부 비-Google 모델도 제공해요.

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

**This library will be deprecated**

This library will be replaced by the ChatGoogle library. New implementations should use the ChatGoogle library instead and existing implementations should consider migrating.

개요

통합 세부 정보

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

모델 기능

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

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

logprobs가 지원되지만 Gemini는 그 사용이 상당히 제한돼요.

설정

LangChain.js는 Node.js 환경에서 실행하는지 웹 환경에서 실행하는지에 따라 두 가지 다른 인증 방법을 지원해요. 또한 두 패키지 중 하나를 사용해 Gemini Enterprise Agent Platform Express Mode에서 사용하는 인증 방법도 지원해요.

ChatVertexAI 모델에 접근하려면 GCP(Google Cloud Platform) 계정에서 Gemini Enterprise Agent Platform을 설정하고 자격 증명 파일을 저장한 뒤 @langchain/google-vertexai 통합 패키지를 설치해야 해요. Node.js에서 이 패키지는 인증에 @langchain/google-gauth를 사용해요 (별도로 설치할 필요는 없어요).

자격 증명

GCP 계정으로 이동해 자격 증명 파일을 생성하세요. 완료되면 GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 설정하세요:

export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/credentials.json"

로컬 머신에서 gcloud auth application-default login을 실행해 Application Default Credentials를 사용할 수도 있어요.

웹 환경에서 실행한다면 @langchain/google-vertexai-web 패키지(인증에 @langchain/google-webauth 사용)를 설치하세요. GOOGLE_WEB_CREDENTIALS에 서비스 계정 JSON을 설정하세요:

export GOOGLE_WEB_CREDENTIALS='{"type":"service_account","project_id":"YOUR_PROJECT-12345",...}'

GOOGLE_VERTEX_AI_WEB_CREDENTIALS도 지원되지만 더 이상 사용되지 않아요.

Gemini Enterprise Agent Platform Express Mode를 사용한다면 @langchain/google-vertexai 또는 @langchain/google-vertexai-web 패키지 중 하나를 설치할 수 있어요. 그런 다음 Express Mode API 키 페이지로 이동해 GOOGLE_API_KEY 환경 변수에 API 키를 설정할 수 있어요:

export GOOGLE_API_KEY="api_key_value"

모델 호출의 자동 추적(tracing)을 원한다면 아래 주석을 해제해 LangSmith API 키를 설정할 수도 있어요:

# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"

설치

LangChain Gemini Enterprise Agent Platform 채팅 통합은 @langchain/google-vertexai 패키지에 있어요:

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

또는 Vercel Edge function 같은 웹 환경에서 사용한다면:

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

인스턴스 생성

이제 모델 객체를 생성하고 채팅 완성을 생성할 수 있어요:

import { ChatVertexAI } from "@langchain/google-vertexai"
// Uncomment the following line if you're running in a web environment:
// import { ChatVertexAI } from "@langchain/google-vertexai-web"

const llm = new ChatVertexAI({
    model: "gemini-2.5-flash",
    temperature: 0,
    maxRetries: 2,
    // For web, authOptions.credentials
    // authOptions: { ... }
    // other params...
})

호출

const aiMsg = await llm.invoke([
    [
        "system",
        "You are a helpful assistant that translates English to French. Translate the user sentence.",
    ],
    ["human", "I love programming."],
])
aiMsg
AIMessageChunk {
  "content": "J'adore programmer. \n",
  "additional_kwargs": {},
  "response_metadata": {},
  "tool_calls": [],
  "tool_call_chunks": [],
  "invalid_tool_calls": [],
  "usage_metadata": {
    "input_tokens": 20,
    "output_tokens": 7,
    "total_tokens": 27
  }
}
console.log(aiMsg.content)
J'adore programmer.

Google 검색 검색(retrieval)으로 tool calling

모델을 Google 검색 도구와 함께 호출할 수 있으며, 이 도구로 실제 세계 정보에 콘텐츠 생성을 기반(grounding)하여 환각을 줄일 수 있어요.

Grounding은 현재 gemini-2.0-flash-exp에서 지원되지 않아요.

Google Search를 사용해 기반을 두거나 커스텀 데이터 저장소를 사용해 기반을 둘 수 있어요. 두 가지 예시는 다음과 같아요:

Google 검색 검색

Google Search를 사용하는 Grounding 예시:

import { ChatVertexAI } from "@langchain/google-vertexai"

const searchRetrievalTool = {
  googleSearchRetrieval: {
    dynamicRetrievalConfig: {
      mode: "MODE_DYNAMIC", // Use Dynamic Retrieval
      dynamicThreshold: 0.7, // Default for Dynamic Retrieval threshold
    },
  },
};

const searchRetrievalModel = new ChatVertexAI({
  model: "gemini-2.5-pro",
  temperature: 0,
  maxRetries: 0,
}).bindTools([searchRetrievalTool]);

const searchRetrievalResult = await searchRetrievalModel.invoke("Who won the 2024 NBA Finals?");

console.log(searchRetrievalResult.content);
The Boston Celtics won the 2024 NBA Finals, defeating the Dallas Mavericks 4-1 in the series to claim their 18th NBA championship. This victory marked their first title since 2008 and established them as the team with the most NBA championships, surpassing the Los Angeles Lakers' 17 titles.

데이터 저장소로 Google 검색 검색

먼저 데이터 저장소를 설정하세요 (예제 데이터 저장소의 스키마):

ID 날짜 팀 1 스코어 팀 2
3001 2023-09-07 Argentina 1 - 0 Ecuador
3002 2023-09-12 Venezuela 1 - 0 Paraguay
3003 2023-09-12 Chile 0 - 0 Colombia
3004 2023-09-12 Peru 0 - 1 Brazil
3005 2024-10-15 Argentina 6 - 0 Bolivia

그런 다음 아래 예제에서 이 데이터 저장소를 사용하세요:

(projectIddatastoreId에는 자신의 변수를 사용해야 함에 유의하세요)

import { ChatVertexAI } from "@langchain/google-vertexai";

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 searchRetrievalModelWithDataset = new ChatVertexAI({
  model: "gemini-2.5-pro",
  temperature: 0,
  maxRetries: 0,
}).bindTools([searchRetrievalToolWithDataset]);

const searchRetrievalModelResult = await searchRetrievalModelWithDataset.invoke(
  "What is the score of Argentina vs Bolivia football game?"
);

console.log(searchRetrievalModelResult.content);
Argentina won against Bolivia with a score of 6-0 on October 15, 2024.

이제 제공한 데이터 저장소의 데이터에 기반(grounded)을 둔 결과를 얻을 수 있어요.

컨텍스트 캐싱

Gemini Enterprise Agent Platform은 컨텍스트 캐싱 기능을 제공하며, 여러 API 요청에 걸쳐 긴 메시지 콘텐츠 블록을 저장하고 재사용해 비용을 최적화하는 데 도움을 줘요. 긴 대화 히스토리나 상호작용에서 자주 나타나는 메시지 세그먼트가 있을 때 특히 유용해요.

이 기능을 사용하려면 먼저 공식 가이드를 따라 컨텍스트 캐시를 만드세요.

캐시를 만든 뒤 다음과 같이 런타임 매개변수로 그 ID를 전달할 수 있어요:

import { ChatVertexAI } from "@langchain/google-vertexai";

const modelWithCachedContent = new ChatVertexAI({
  model: "gemini-2.5-pro-002",
  location: "us-east5",
});

await modelWithCachedContent.invoke("What is in the content?", {
  cachedContent:
    "projects/PROJECT_NUMBER/locations/LOCATION/cachedContents/CACHE_ID",
});

이 필드를 모델 인스턴스에 직접 바인딩할 수도 있어요:

const modelWithBoundCachedContent = new ChatVertexAI({
  model: "gemini-2.5-pro-002",
  location: "us-east5",
}).bind({
  cachedContent:
    "projects/PROJECT_NUMBER/locations/LOCATION/cachedContents/CACHE_ID",
});

현재 모든 모델이 컨텍스트 캐싱을 지원하는 것은 아니라는 점에 유의하세요.


API 레퍼런스

모든 ChatVertexAI 기능과 구성에 대한 자세한 문서는 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_vertex_ai.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).

더 알아보기