AmazonBedrockChatGenerator — Amazon Bedrock 채팅 생성

AmazonBedrockChatGenerator — Amazon Bedrock 채팅 생성

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

출처: 공식 문서 — AmazonBedrockChatGenerator

Amazon Bedrock은 주요 AI 스타트업과 Amazon의 우수한 파운데이션 모델들을 하나의 통합 API로 제공하는 완전 관리형 서비스예요. 여러 파운데이션 모델 중에서 사용 사례에 가장 잘 맞는 모델을 고를 수 있죠.

AmazonBedrockChatGenerator는 Amazon, Anthropic, Cohere, Meta, Mistral 등의 채팅 모델을 단 하나의 컴포넌트로 사용할 수 있게 해 줘요.

개요 (Overview)

이 컴포넌트는 인증에 AWS를 사용해요. IAM을 통해 AWS CLI로 인증할 수 있어요. IAM 아이덴티티 기반 정책을 설정하는 방법에 대한 자세한 내용은 공식 문서를 참고하세요.

참고 — AWS CLI 사용하기

AWS 서비스를 관리하려면 AWS CLI를 쓰는 것이 더 간편해요. AWS CLI를 쓰면 boto3 자격 증명을 빠르게 구성할 수 있어요. 이렇게 하면 Haystack에서 Amazon Bedrock Generator를 초기화할 때 자세한 인증 파라미터를 일일이 넘길 필요가 없어져요.

텍스트 생성을 위해 이 컴포넌트를 쓰려면 모델 이름과 함께 AmazonBedrockChatGenerator를 초기화하면 돼요. AWS 자격 증명(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION)은 환경 변수로 설정하거나, 위에서 설명한 방식으로 구성하거나, Secret 인자로 전달하면 돼요. 설정한 리전이 Amazon Bedrock을 지원하는지 꼭 확인하세요.

도구 지원 (Tool Support)

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

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

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

from haystack.tools import Tool, Toolset
from haystack_integrations.components.generators.amazon_bedrock import (
    AmazonBedrockChatGenerator,
)

# 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 = AmazonBedrockChatGenerator(
    model="global.anthropic.claude-sonnet-4-6",
    tools=[math_toolset, weather_tool, news_tool],  # Mix of Toolset and Tool objects
)

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

스트리밍 (Streaming)

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

프롬프트 캐싱 (Prompt Caching)

AmazonBedrockChatGenerator는 추론 응답 지연 시간과 입력 토큰 비용을 줄이기 위해 프롬프트 캐싱을 지원해요.

Bedrock의 프롬프트 캐싱은 선택된 모델에서 사용할 수 있어요. 입력이 모델별 최소 토큰 임계값을 넘기만 하면, 요청 안에 캐시 지점(cache point)을 정의할 수 있게 해 줘요.

요청 하나에는 최대 4개의 캐시 지점을 넣을 수 있어요.

메시지 캐싱 (Caching messages)

이 생성기는 ChatMessagemeta 필드를 통해 캐시 지점을 제어할 수 있게 해 줘요.

예를 들어 여러 요청에 걸쳐 재사용할 긴 사용자 메시지를 캐시하려면 다음과 같이 합니다.

from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.amazon_bedrock import (
    AmazonBedrockChatGenerator,
)

msg = ChatMessage.from_user(
    "long message...",
    meta={"cachePoint": {"type": "default", "ttl": "5m"}},
)

generator = AmazonBedrockChatGenerator(
    model="global.anthropic.claude-sonnet-4-6",
)

result = generator.run(messages=[msg])

캐시 지점이 성공적으로 기록되면, 캐시된 입력 토큰 수는 다음 위치에서 확인할 수 있어요.

result["replies"][0].meta["usage"]["cache_write_input_tokens"]

도구 캐싱 (Caching tools)

tools_cachepoint_config 초기화 파라미터를 사용하면 도구 정의도 캐시할 수 있어요. 이 값을 지정하면, 모델로 보내는 모든 도구가 최소 토큰 임계값을 넘고 선택한 모델이 프롬프트 캐싱을 지원할 때 캐시돼요.

from haystack_integrations.components.generators.amazon_bedrock import (
    AmazonBedrockChatGenerator,
)

# define or load your tools

generator = AmazonBedrockChatGenerator(
    model="global.anthropic.claude-sonnet-4-6",
    tools=my_tools,
    tools_cachepoint_config={"type": "default", "ttl": "5m"},
)

# send a request to the Language Model

Amazon Bedrock에서 프롬프트 캐싱이 어떻게 동작하는지 더 자세한 내용은 공식 문서를 참고하세요.

사용법 (Usage)

Haystack에서 Amazon Bedrock을 쓰려면 amazon-bedrock-haystack 패키지를 설치해야 해요.

pip install amazon-bedrock-haystack

단독 사용 (On its own)

기본 사용법:

from haystack_integrations.components.generators.amazon_bedrock import (
    AmazonBedrockChatGenerator,
)
from haystack.dataclasses import ChatMessage

generator = AmazonBedrockChatGenerator(model="global.anthropic.claude-sonnet-4-6")
messages = [
    ChatMessage.from_system(
        "You are a helpful assistant that answers question in Spanish only",
    ),
    ChatMessage.from_user("What's Natural Language Processing? Be brief."),
]

response = generator.run(messages)
print(response)

멀티모달 입력으로 사용:

from haystack.dataclasses import ChatMessage, ImageContent
from haystack_integrations.components.generators.amazon_bedrock import (
    AmazonBedrockChatGenerator,
)

llm = AmazonBedrockChatGenerator(model="global.anthropic.claude-sonnet-4-6")

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 mat.

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

RAG 파이프라인에서 사용:

from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.amazon_bedrock import (
    AmazonBedrockChatGenerator,
)

pipe = Pipeline()
pipe.add_component("prompt_builder", ChatPromptBuilder())
pipe.add_component(
    "llm", AmazonBedrockChatGenerator(model="global.anthropic.claude-sonnet-4-6")
)
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)