AnthropicChatGenerator — Anthropic 채팅 생성

AnthropicChatGenerator — Anthropic 채팅 생성

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

출처: 공식 문서 — AnthropicChatGenerator

개요 (Overview)

이 통합은 Anthropic의 chat 모델을 지원해요. claude-3-5-sonnet-20240620, claude-3-opus-20240229, claude-3-haiku-20240307 같은 모델들이죠. 최신 전체 목록은 Anthropic 문서에서 확인할 수 있어요.

파라미터 (Parameters)

AnthropicChatGenerator는 동작하려면 Anthropic API 키가 필요해요. 키는 다음 두 가지 방법으로 제공할 수 있어요.

  • ANTHROPIC_API_KEY 환경 변수 (권장)
  • api_key 초기화 파라미터 + Haystack의 Secret API: Secret.from_token("your-api-key-here")

원하는 Anthropic 모델은 컴포넌트를 초기화할 때 model 파라미터로 정해요.

AnthropicChatGenerator는 텍스트를 만들려면 프롬프트가 필요해요. 그리고 Anthropic Messaging API에서 쓸 수 있는 텍스트 생성 파라미터는 대부분 generation_kwargs 파라미터로 직접 전달할 수 있어요. 초기화할 때도, 컴포넌트를 실행할 때도 가능하죠. Anthropic API가 지원하는 파라미터에 대한 자세한 내용은 Anthropic 문서를 확인하세요.

마지막으로, 이 컴포넌트는 ChatMessage 객체의 리스트를 받아서 동작해요. ChatMessage는 메시지와 역할(누가 만들었는지 — user, assistant, system, tool 등), 선택적 메타데이터를 담는 데이터 클래스예요.

텍스트와 이미지 입력 모두 지원해요.

도구 지원 (Tool Support)

AnthropicChatGeneratortools 파라미터를 통해 함수 호출(function calling)을 지원해요. 이 파라미터는 유연한 도구 구성을 받아들여요.

  • Tool 객체 리스트: 개별 도구를 리스트로 전달
  • 단일 Toolset: Toolset 하나를 통째로 전달
  • Tool과 Toolset 혼합: 여러 Toolset과 단독 도구를 한 리스트에 섞어서 전달

이렇게 하면 관련된 도구들을 논리적인 그룹으로 묶으면서, 필요할 때 단독 도구도 같이 포함할 수 있어요.

from haystack.tools import Tool, Toolset
from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator

# Create individual tools
weather_tool = Tool(
    name="weather", description="Get weather info", parameters=..., function=...
)
news_tool = Tool(
    name="news", description="Get latest news", parameters=..., function=...
)

# Group related tools into a toolset
math_toolset = Toolset([add_tool, subtract_tool, multiply_tool])

# Pass mixed tools and toolsets to the generator
generator = AnthropicChatGenerator(
    tools=[math_toolset, weather_tool, news_tool]  # Mix of Toolset and Tool objects
)

도구를 다루는 더 자세한 내용은 ToolToolset 문서를 참고하세요.

스트리밍 (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"})

참고 스트리밍은 단일 응답일 때만 동작해요. 공급자가 여러 후보를 지원한다면 n=1로 설정하세요.

StreamingChunk가 어떻게 동작하는지, 커스텀 콜백을 어떻게 작성하는지 더 알고 싶다면 Streaming Support 문서를 참고하세요.

기본적으로는 print_streaming_chunk를 쓰는 걸 권장해요. 커스텀 콜백은 특별한 전송 방식(예: SSE/WebSocket)이나 커스텀 UI 포맷이 필요할 때만 작성하면 돼요.

프롬프트 캐싱 (Prompt caching)

프롬프트 캐싱은 Anthropic LLM의 기능으로, 큰 텍스트 입력을 저장해 두고 재사용할 수 있게 해 줘요. 큰 텍스트 블록을 한 번 보내고, 이후 요청에서는 전체 텍스트를 다시 보내지 않고 그 블록을 참조할 수 있는 거예요.

이 기능은 전체 코드베이스 컨텍스트가 필요한 코딩 어시스턴트나, 큰 문서를 처리할 때 특히 유용해요. 비용을 낮추고 응답 시간도 개선해 줘요.

AnthropicChatGenerator 인스턴스를 프롬프트 캐싱으로 초기화하고, 어떤 메시지를 캐시할지 태그를 지정하는 예시예요.

from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.utils import Secret

generation_kwargs = {"extra_headers": {"anthropic-beta": "prompt-caching-2024-07-31"}}

claude_llm = AnthropicChatGenerator(
    api_key=Secret.from_env_var("ANTHROPIC_API_KEY"),
    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)

AnthropicChatGenerator를 쓰려면 anthropic-haystack 패키지를 설치해야 해요.

pip install anthropic-haystack

단독 사용 (On its own)

from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator
from haystack.dataclasses import ChatMessage

generator = AnthropicChatGenerator()
message = ChatMessage.from_user("What's Natural Language Processing? Be brief.")
print(generator.run([message]))

멀티모달 입력으로 사용:

from haystack.dataclasses import ChatMessage, ImageContent
from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator

llm = AnthropicChatGenerator()

image = ImageContent.from_file_path("apple.jpg")
user_message = ChatMessage.from_user(
    content_parts=["What does the image show? Max 5 words.", image],
)

response = llm.run([user_message])["replies"][0].text
print(response)

# Red apple on straw.

파이프라인에서 사용 (In a pipeline)

AnthropicChatGenerator와 Anthropic 채팅 모델을 파이프라인에서도 쓸 수 있어요.

from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator
from haystack.utils import Secret

pipe = Pipeline()
pipe.add_component("prompt_builder", ChatPromptBuilder())
pipe.add_component(
    "llm",
    AnthropicChatGenerator(Secret.from_env_var("ANTHROPIC_API_KEY")),
)
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)