AnthropicVertexChatGenerator
AnthropicVertexChatGenerator
AnthropicVertex API를 통해 채팅 완성을 가능하게 하는 컴포넌트예요.
파이프라인에서 가장 흔한 위치: ChatPromptBuilder 뒤
필수 init 변수: region(Anthropic 모델이 배포된 리전), project_id(Anthropic 모델이 배포된 GCP 프로젝트 ID)
필수 run 변수: messages — ChatMessage 객체 목록
출력 변수: replies — ChatMessage 객체 목록
API reference: Anthropic
GitHub link: https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/anthropic
Package name: anthropic-haystack
출처: 문서
본문
Overview
AnthropicVertexChatGenerator는 Anthropic Vertex AI API를 통해 Anthropic의 Claude 모델로 텍스트 생성을 가능하게 해줘요.
다양한 Claude 모델(Opus, Sonnet, Haiku 등)이 Vertex AI API 엔드포인트로 접근될 수 있어요. 모델에 대한 자세한 내용은 Anthropic Vertex AI 문서를 참고하세요.
Parameters
AnthropicVertexChatGenerator를 쓰려면 Vertex AI가 활성화된 GCP 프로젝트가 있어야 해요. GCP project_id와 region을 init 파라미터로 전달해야 합니다. 둘 다 None으로 전달하면 컴포넌트는 PROJECT_ID와 REGION 환경 변수로 폴백합니다.
요청 전에 gcloud auth login으로 GCP에 인증해야 할 수 있어요.
컴포넌트를 초기화할 때 model 파라미터로 선호하는 지원 Anthropic 모델을 설정하세요. 또한 원하는 Anthropic 모델이 Vertex AI Model Garden에서 활성화되어 있는지 확인해야 해요.
AnthropicVertexChatGenerator는 텍스트를 생성하려면 프롬프트가 필요하지만, Anthropic Messaging API 메서드에서 사용 가능한 어떤 텍스트 생성 파라미터든 generation_kwargs 파라미터로 이 컴포넌트에 직접 전달할 수 있어요. 초기화 때와 컴포넌트 실행 때 모두 가능합니다. Anthropic API가 지원하는 파라미터에 대한 자세한 내용은 Anthropic 문서를 참고하세요.
마지막으로 컴포넌트는 ChatMessage 객체 목록이 있어야 동작해요. ChatMessage는 메시지, 역할(누가 메시지를 만들었는지 — user, assistant, system, tool 등), 선택적 메타데이터를 담는 데이터 클래스입니다.
현재는 텍스트 입력 모달리티만 지원됩니다.
Streaming
생성되는 대로 출력을 스트리밍할 수 있어요. streaming_callback에 콜백을 넘기면 됩니다. 내장 print_streaming_chunk를 쓰면 텍스트 토큰과 도구 이벤트(도구 호출·도구 결과)를 출력할 수 있어요.
from haystack.components.generators.utils import print_streaming_chunk
# Configure any `Generator` or `ChatGenerator` with a streaming callback
component = SomeGeneratorOrChatGenerator(streaming_callback=print_streaming_chunk)
# If this is a `ChatGenerator`, pass a list of messages:
# from haystack.dataclasses import ChatMessage
# component.run([ChatMessage.from_user("Your question here")])
# If this is a (non-chat) `Generator`, pass a prompt:
# component.run({"prompt": "Your prompt here"})
info 스트리밍은 단일 응답에서만 동작해요. 프로바이더가 여러 후보를 지원한다면
n=1로 설정하세요.
StreamingChunk가 어떻게 동작하는지, 사용자 정의 콜백을 어떻게 작성하는지는 Streaming Support 문서를 참고하세요.
기본적으로 print_streaming_chunk를 우선 쓰는 걸 권장해요. 특정 전송(예: SSE/WebSocket)이나 사용자 정의 UI 포맷이 필요할 때만 직접 콜백을 작성하세요.
Prompt Caching
프롬프트 캐싱은 크고 긴 텍스트 입력을 재사용을 위해 저장하는 Anthropic LLM의 기능이에요. 큰 텍스트 블록을 한 번 보내고, 이후 요청에서 전체 텍스트를 다시 보내지 않고 그것을 참조할 수 있죠.
이 기능은 전체 코드베이스 컨텍스트가 필요한 코딩 어시스턴트나 큰 문서 처리에 특히 유용합니다. 비용을 줄이고 응답 시간을 개선하는 데 도움이 돼요.
프롬프트 캐싱으로 초기화되고 캐시할 메시지를 태깅한 AnthropicVertexChatGenerator 인스턴스 예시입니다:
from haystack_integrations.components.generators.anthropic import (
AnthropicVertexChatGenerator,
)
from haystack.dataclasses import ChatMessage
generation_kwargs = {"extra_headers": {"anthropic-beta": "prompt-caching-2024-07-31"}}
claude_llm = AnthropicVertexChatGenerator(
region="your_region",
project_id="test_id",
generation_kwargs=generation_kwargs,
)
system_message = ChatMessage.from_system(
"Replace with some long text documents, code or instructions",
)
system_message.meta["cache_control"] = {"type": "ephemeral"}
messages = [
system_message,
ChatMessage.from_user("A query about the long text for example"),
]
result = claude_llm.run(messages)
# and now invoke again with
messages = [
system_message,
ChatMessage.from_user("Another query about the long text etc"),
]
result = claude_llm.run(messages)
# and so on, either invoking component directly or in the pipeline
자세한 내용은 Anthropic 문서와 통합 예시를 참고하세요.
Usage
AnthropicVertexChatGenerator를 쓰려면 anthropic-haystack 패키지를 설치하세요:
pip install anthropic-haystack
On its own
from haystack_integrations.components.generators.anthropic import (
AnthropicVertexChatGenerator,
)
from haystack.dataclasses import ChatMessage
messages = [ChatMessage.from_user("What's Natural Language Processing?")]
client = AnthropicVertexChatGenerator(
model="claude-sonnet-4@20250514",
project_id="your-project-id",
region="us-central1",
)
response = client.run(messages)
print(response)
In a pipeline
파이프라인에서 Anthropic 채팅 모델과 함께 AnthropicVertexChatGenerator를 쓸 수도 있어요.
from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.anthropic import (
AnthropicVertexChatGenerator,
)
from haystack.utils import Secret
pipe = Pipeline()
pipe.add_component("prompt_builder", ChatPromptBuilder())
pipe.add_component(
"llm",
AnthropicVertexChatGenerator(project_id="test_id", region="us-central1"),
)
pipe.connect("prompt_builder", "llm")
country = "Germany"
system_message = ChatMessage.from_system(
"You are an assistant giving out valuable information to language learners.",
)
messages = [
system_message,
ChatMessage.from_user("What's the official language of {{ country }}?"),
]
res = pipe.run(
data={
"prompt_builder": {
"template_variables": {"country": country},
"template": messages,
},
},
)
print(res)
더 알아보기 (Learn more)
- AnthropicChatGenerator — Anthropic 채팅 생성기
- Choosing the Right Generator — 스트리밍 지원