GoogleAIGeminiChatGenerator — Google Gemini 채팅 생성

GoogleAIGeminiChatGenerator — Google Gemini 채팅 생성

이 컴포넌트는 Google Gemini 모델을 이용해 채팅 완성(chat completion)을 만들 수 있게 해 줘요. Haystack 파이프라인에서 Gemini 모델과 대화를 주고받는 한 조각이라고 보시면 돼요.

출처: 공식 문서 — GoogleAIGeminiChatGenerator

⚠️ 지원 중단 공지

이 통합은 2025년 8월 이후 지원이 중단되는 구버전 google-generativeai SDK를 사용해요.

새로운 GoogleGenAIChatGenerator 통합으로 전환하는 걸 권장합니다.

GoogleAIGeminiChatGeneratorgemini-2.5-pro-exp-03-25, gemini-2.0-flash, gemini-1.5-pro, gemini-1.5-flash 모델을 지원해요.

사용 가능한 모델은 https://ai.google.dev/gemini-api/docs/models/gemini 에서 확인할 수 있어요.

파라미터 개요 (Parameters Overview)

GoogleAIGeminiChatGenerator는 인증에 Google Studio API 키를 사용해요. 이 키는 api_key 파라미터에 직접 쓰거나, GOOGLE_API_KEY 환경 변수(권장)로 설정할 수 있어요.

API 키를 얻으려면 Google AI Studio 웹사이트를 방문하세요.

스트리밍 (Streaming)

이 Generator는 LLM의 토큰을 출력에 바로 스트리밍하는 스트리밍을 지원해요. streaming_callback 초기화 파라미터에 함수를 넘기면 됩니다.

사용법 (Usage)

GoogleAIGeminiChatGenerator를 쓰려면 google-ai-haystack 패키지를 설치해야 해요.

pip install google-ai-haystack

단독 사용 (On its own)

기본 사용법:

import os
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.google_ai import (
    GoogleAIGeminiChatGenerator,
)

os.environ["GOOGLE_API_KEY"] = "<MY_API_KEY>"
gemini_chat = GoogleAIGeminiChatGenerator()

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"], ChatMessage.from_user("Who's the main actor?")]
res = gemini_chat.run(messages)

print(res["replies"][0].text)
# >> Tim Robbins

Gemini와 대화할 때 함수 호출(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)

도구를 설정하려면 GoogleAIGeminiChatGenerator 인스턴스를 새로 만들어요.

import os
from haystack_integrations.components.generators.google_ai import (
    GoogleAIGeminiChatGenerator,
)

os.environ["GOOGLE_API_KEY"] = "<MY_API_KEY>"

gemini_chat = GoogleAIGeminiChatGenerator(model="gemini-2.0-flash", 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에 넘길 수도 있어요. 에이전트가 모델의 도구 호출을 준비하고, 실행하고, 최종 답변이 준비될 때까지 결과를 다시 넣어주는 일을 알아서 처리해 줘요.

import os
from haystack.components.agents import Agent
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.google_ai import (
    GoogleAIGeminiChatGenerator,
)

os.environ["GOOGLE_API_KEY"] = "<MY_API_KEY>"

agent = Agent(
    chat_generator=GoogleAIGeminiChatGenerator(model="gemini-2.0-flash"),
    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)

import os
from haystack.components.builders import ChatPromptBuilder
from haystack.dataclasses import ChatMessage
from haystack import Pipeline
from haystack_integrations.components.generators.google_ai import (
    GoogleAIGeminiChatGenerator,
)

# no parameter init, we don't use any runtime template variables
prompt_builder = ChatPromptBuilder()

os.environ["GOOGLE_API_KEY"] = "<MY_API_KEY>"
gemini_chat = GoogleAIGeminiChatGenerator()

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.