AnthropicFoundryChatGenerator

AnthropicFoundryChatGenerator

Azure Foundry를 통해 제공되는 Anthropic 모델로 채팅 완성을 가능하게 하는 컴포넌트예요.

파이프라인에서 가장 흔한 위치: ChatPromptBuilder 뒤 필수 init 변수: api_key(Azure Foundry API 키. ANTHROPIC_FOUNDRY_API_KEY 환경 변수로 설정 가능. 또는 azure_ad_token_provider 콜러블 전달 가능), resource(Azure Foundry 리소스 이름. ANTHROPIC_FOUNDRY_RESOURCE 환경 변수로 설정 가능. 또는 전체 endpoint URL 전달 가능) 필수 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

AnthropicFoundryChatGenerator는 Azure Foundry 배포를 통해 Anthropic의 Claude 모델을 호출할 수 있게 해줘요. AnthropicChatGenerator의 얇은 서브클래스로, 요청·응답 형태는 Anthropic Messages API와 일치하지만 트래픽은 api.anthropic.com 대신 여러분의 Azure 리소스를 통해 흐릅니다.

조직이 모델 호스팅(비용, 네트워킹, 규정 준수)을 Azure로 표준화하면서도 Claude를 쓰고 싶을 때 이 생성기를 사용하세요. Azure가 필요 없다면 AnthropicChatGenerator를 권장해요.

기본 모델은 claude-sonnet-4-5입니다. 동작이 확인된 다른 모델로는 claude-opus-4-6, claude-sonnet-4-6, claude-opus-4-5, claude-opus-4-1, claude-haiku-4-5가 있어요. 이 목록은 완전하지 않으며, 실제 카탈로그는 Foundry 리소스에 배포된 것에 따라 달라집니다. 모델 선택 가이드는 Anthropic 모델 개요를 참고하세요.

Parameters

AnthropicFoundryChatGenerator가 Azure와 통신하려면 두 가지가 필요해요: 자격 증명과 엔드포인트.

자격 증명(Credentials). 다음 중 하나를 선택하세요:

  • ANTHROPIC_FOUNDRY_API_KEY 환경 변수(권장).
  • Haystack Secret API를 쓰는 api_key init 파라미터: Secret.from_token("your-api-key-here").
  • azure_ad_token_provider로 전달하는 콜러블 — 필요할 때마다 새 Azure AD 토큰을 반환하죠. 정적 키가 적절하지 않은 Entra ID / 관리형 ID 설정에 쓰세요.

엔드포인트(Endpoint). 다음 중 하나를 선택하세요:

  • resource init 파라미터(또는 ANTHROPIC_FOUNDRY_RESOURCE 환경 변수) — 짧은 Foundry 리소스 이름으로, URL을 만드는 데 쓰입니다.
  • endpoint init 파라미터 — 전체 URL로, 사용자 정의 도메인이나 비표준 경로에 유용해요.

설정한 뒤에는 Anthropic Messages API가 지원하는 어떤 텍스트 생성 파라미터든 generation_kwargs를 통해 init 때나 호출마다 전달할 수 있어요. 일반적인 키로는 system, max_tokens, temperature, top_p, top_k, stop_sequences, metadata, extra_headers가 있습니다. timeout와 max_retries를 조정해 클라이언트 측 탄력성을 제어할 수도 있어요.

컴포넌트는 ChatMessage 객체 목록을 받습니다. ChatMessage는 메시지, 역할(user, assistant, system, tool), 선택적 메타데이터를 담는 데이터 클래스예요. 텍스트 입력만 지원됩니다.

Tool Support

AnthropicFoundryChatGenerator는 tools 파라미터로 함수 호출을 지원하며, 다음을 받아들여요:

  • Tool 객체 목록: 개별 도구를 목록으로 전달.
  • 단일 Toolset: Toolset 전체를 직접 전달.
  • 혼합 도구와 Toolset: 여러 Toolset을 단독 도구와 한 목록에 결합.
from haystack.tools import Tool, Toolset
from haystack_integrations.components.generators.anthropic import (
    AnthropicFoundryChatGenerator,
)

weather_tool = Tool(
    name="weather", description="Get weather info", parameters=..., function=...)
math_toolset = Toolset([add_tool, subtract_tool, multiply_tool])

generator = AnthropicFoundryChatGenerator(
    resource="my-resource",
    tools=[math_toolset, weather_tool],
)

run()에 전달된 도구는 init 때 설정한 도구를 덮어써요. 자세한 내용은 Tool과 Toolset 문서를 참고하세요.

Streaming

생성되는 대로 출력을 스트리밍할 수 있어요. streaming_callback에 콜백을 넘기면 됩니다. 내장 print_streaming_chunk는 텍스트 토큰과 도구 이벤트를 표준 출력에 출력해요.

from haystack.components.generators.utils import print_streaming_chunk
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.anthropic import (
    AnthropicFoundryChatGenerator,
)

generator = AnthropicFoundryChatGenerator(
    resource="my-resource",
    streaming_callback=print_streaming_chunk,
)
generator.run([ChatMessage.from_user("Your question here")])

info 스트리밍은 단일 응답에서만 동작해요. 프로바이더가 여러 후보를 지원한다면 n=1로 설정하세요.

StreamingChunk가 어떻게 동작하는지, 사용자 정의 콜백을 어떻게 작성하는지는 Streaming Support를 참고하세요. 특정 전송(SSE나 WebSocket 같은)이나 사용자 정의 UI 포맷이 필요하지 않다면 print_streaming_chunk를 우선 쓰세요.

Async

run_async는 run을 그대로 반영하며 자동으로 연결돼요. async 파이프라인이나 웹 핸들러 안에서 유용합니다.

import asyncio
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.anthropic import (
    AnthropicFoundryChatGenerator,
)

async def main():
    generator = AnthropicFoundryChatGenerator(resource="my-resource")
    result = await generator.run_async([ChatMessage.from_user("Hello!")])
    print(result["replies"][0].text)

asyncio.run(main())

Usage

AnthropicFoundryChatGenerator를 쓰려면 anthropic-haystack 패키지를 설치하세요:

pip install anthropic-haystack

On its own

from haystack.dataclasses import ChatMessage
from haystack.utils import Secret
from haystack_integrations.components.generators.anthropic import (
    AnthropicFoundryChatGenerator,
)

generator = AnthropicFoundryChatGenerator(
    model="claude-sonnet-4-5",
    api_key=Secret.from_env_var("ANTHROPIC_FOUNDRY_API_KEY"),
    resource="my-resource",
)
response = generator.run([ChatMessage.from_user("What's Natural Language Processing?")])
print(response)

In a pipeline

from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.anthropic import (
    AnthropicFoundryChatGenerator,
)

pipe = Pipeline()
pipe.add_component("prompt_builder", ChatPromptBuilder())
pipe.add_component(
    "llm",
    AnthropicFoundryChatGenerator(resource="my-resource"),
)
pipe.connect("prompt_builder", "llm")

country = "Germany"
messages = [
    ChatMessage.from_system(
        "You are an assistant giving out valuable information to language learners.",
    ),
    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)