VertexAIGeminiChatGenerator — Google Vertex AI Gemini 채팅 생성
VertexAIGeminiChatGenerator — Google Vertex AI Gemini 채팅 생성
VertexAIGeminiChatGenerator는 Google Gemini 모델을 이용해 채팅 완성(chat completion)을 만들 수 있게 해 주는 컴포넌트예요. Google Cloud의 Vertex AI 환경에서 Gemini 모델과 대화를 주고받는 한 조각이라고 보시면 돼요.
⚠️ 지원 중단 공지
이 통합은 2025년 8월 이후 지원이 중단되는 구버전
google-generativeaiSDK를 사용해요.새로운 GoogleGenAIChatGenerator 통합으로 전환하는 걸 권장합니다.
VertexAIGeminiGenerator는 gemini-1.5-pro, gemini-1.5-flash / gemini-2.0-flash 모델을 지원해요. 참고로 Google은 gemini-1.5-pro에서 gemini-2.0-flash로 업그레이드하길 권장하고 있어요.
사용 가능한 모델은 https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models 에서 확인할 수 있어요.
파라미터 개요 (Parameters Overview)
VertexAIGeminiChatGenerator는 인증에 Google Cloud 애플리케이션 기본 자격 증명(Application Default Credentials, ADC)을 사용해요. ADC 설정 방법에 대한 자세한 내용은 공식 문서를 참고하세요.
Google Vertex AI 엔드포인트 사용이 승인된 프로젝트에 접근 권한이 있는 계정을 쓰는 것이 중요하다는 점을 꼭 기억하세요.
프로젝트 ID는 GCP 리소스 관리자에서 찾거나, 터미널에서 gcloud projects list를 실행해서 찾을 수 있어요. gcloud CLI에 대한 자세한 내용은 공식 문서를 참고하세요.
스트리밍 (Streaming)
이 Generator는 LLM의 토큰을 출력에 바로 스트리밍하는 스트리밍을 지원해요. streaming_callback 초기화 파라미터에 함수를 넘기면 됩니다.
사용법 (Usage)
VertexAIGeminiChatGenerator를 쓰려면 google-vertex-haystack 패키지를 설치해야 해요.
pip install google-vertex-haystack
단독 사용 (On its own)
기본 사용법:
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.google_vertex import (
VertexAIGeminiChatGenerator,
)
gemini_chat = VertexAIGeminiChatGenerator()
messages = [ChatMessage.from_user("Tell me the name of a movie")]
res = gemini_chat.run(messages)
print(res["replies"][0].text)
# >> The Shawshank Redemption
messages += [res["replies"][0], ChatMessage.from_user("Who's the main actor?")]
res = gemini_chat.run(messages)
print(res["replies"][0].text)
# >> Tim Robbins
Gemini Pro와 대화할 때 함수 호출(function call)도 쉽게 쓸 수 있어요. 먼저 함수를 로컬에서 정의하고 Tool로 변환합니다.
from typing import Annotated
from haystack.tools import create_tool_from_function
# example function to get the current weather
def get_current_weather(
location: Annotated[
str,
"The city for which to get the weather, e.g. 'San Francisco'",
] = "Munich",
unit: Annotated[str, "The unit for the temperature, e.g. 'celsius'"] = "celsius",
) -> str:
return f"The weather in {location} is sunny. The temperature is 20 {unit}."
tool = create_tool_from_function(get_current_weather)
도구를 설정하려면 VertexAIGeminiChatGenerator 인스턴스를 새로 만들어요.
from haystack_integrations.components.generators.google_vertex import (
VertexAIGeminiChatGenerator,
)
gemini_chat = VertexAIGeminiChatGenerator(model="gemini-2.0-flash-exp", tools=[tool])
그리고 질문을 던지면 돼요. 모델이 도구 호출을 준비하고, 코드가 Tool.invoke로 그 호출을 실행하며, 결과가 다시 모델로 돌아가 최종 답변이 완성돼요.
from haystack.dataclasses import ChatMessage
messages = [ChatMessage.from_user("What is the temperature in celsius in Berlin?")]
replies = gemini_chat.run(messages=messages)["replies"]
print(replies[0].tool_calls)
# >> [ToolCall(tool_name='get_current_weather',
# >> arguments={'unit': 'celsius', 'location': 'Berlin'}, id=None)]
tool_messages = []
for tool_call in replies[0].tool_calls:
result = tool.invoke(**tool_call.arguments)
tool_messages.append(ChatMessage.from_tool(tool_result=result, origin=tool_call))
messages = messages + replies + tool_messages
final_replies = gemini_chat.run(messages=messages)["replies"]
print(final_replies[0].text)
# >> The temperature in Berlin is 20 degrees Celsius.
에이전트와 함께 사용 (With an Agent)
도구 호출 루프를 직접 돌리는 대신, 생성기(generator)와 도구들을 Agent에 넘길 수도 있어요. 에이전트가 모델의 도구 호출을 준비하고, 실행하고, 최종 답변이 준비될 때까지 결과를 다시 넣어주는 일을 알아서 처리해 줘요.
from haystack.components.agents import Agent
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.google_vertex import (
VertexAIGeminiChatGenerator,
)
agent = Agent(
chat_generator=VertexAIGeminiChatGenerator(model="gemini-2.0-flash-exp"),
tools=[tool],
)
result = agent.run(
messages=[ChatMessage.from_user("What is the temperature in celsius in Berlin?")]
)
print(result["last_message"].text)
# >> The temperature in Berlin is 20 degrees Celsius.
파이프라인에서 사용 (In a pipeline)
from haystack.components.builders import ChatPromptBuilder
from haystack.dataclasses import ChatMessage
from haystack import Pipeline
from haystack_integrations.components.generators.google_vertex import (
VertexAIGeminiChatGenerator,
)
# no parameter init, we don't use any runtime template variables
prompt_builder = ChatPromptBuilder()
gemini_chat = VertexAIGeminiChatGenerator()
pipe = Pipeline()
pipe.add_component("prompt_builder", prompt_builder)
pipe.add_component("gemini", gemini_chat)
pipe.connect("prompt_builder.prompt", "gemini.messages")
location = "Rome"
messages = [ChatMessage.from_user("Tell me briefly about {{location}} history")]
res = pipe.run(
data={
"prompt_builder": {
"template_variables": {"location": location},
"template": messages,
}
}
)
print(res)
# >> - **753 B.C.:** Traditional date of the founding of Rome by Romulus and Remus.
# >> - **509 B.C.:** Establishment of the Roman Republic, replacing the Etruscan monarchy.
# >> - **492-264 B.C.:** Series of wars against neighboring tribes, resulting in the expansion of the Roman Republic's territory.
# >> - **264-146 B.C.:** Three Punic Wars against Carthage, resulting in the destruction of Carthage and the Roman Republic becoming the dominant power in the Mediterranean.
# >> - **133-73 B.C.:** Series of civil wars and slave revolts, leading to the rise of Julius Caesar.
# >> - **49 B.C.:** Julius Caesar crosses the Rubicon River, starting the Roman Civil War.
# >> - **44 B.C.:** Julius Caesar is assassinated, leading to the Second Triumvirate of Octavian, Mark Antony, and Lepidus.
# >> - **31 B.C.:** Battle of Actium, where Octavian defeats Mark Antony and Cleopatra, becoming the sole ruler of Rome.
# >> - **27 B.C.:** The Roman Republic is transformed into the Roman Empire, with Octavian becoming the first Roman emperor, known as Augustus.
# >> - **1st century A.D.:** The Roman Empire reaches its greatest extent, stretching from Britain to Egypt.
# >> - **3rd century A.D.:** The Roman Empire begins to decline, facing internal instability, invasions by Germanic tribes, and the rise of Christianity.
# >> - **476 A.D.:** The last Western Roman emperor, Romulus Augustulus, is overthrown by the Germanic leader Odoacer, marking the end of the Roman Empire in the West.