AzureOpenAIResponsesChatGenerator
AzureOpenAIResponsesChatGenerator
Azure 서비스를 통해 OpenAI의 Responses API로 채팅 완성을 가능하게 하며 추론(reasoning) 모델을 지원하는 컴포넌트예요.
파이프라인에서 가장 흔한 위치: ChatPromptBuilder 뒤
필수 init 변수: api_key(AZURE_OPENAI_API_KEY 환경 변수로 설정 가능. 또는 Azure AD 토큰용 콜러블), azure_endpoint(배포된 모델의 엔드포인트. AZURE_OPENAI_ENDPOINT 환경 변수로 설정 가능)
필수 run 변수: messages — 채팅을 나타내는 ChatMessage 객체 목록 또는 평문 문자열
출력 변수: replies — 생성된 응답을 담은 ChatMessage 객체 목록
API reference: Generators
GitHub link: https://github.com/deepset-ai/haystack/blob/main/haystack/components/generators/chat/azure_responses.py
Package name: haystack-ai
출처: 문서
본문
Overview
AzureOpenAIResponsesChatGenerator는 Azure OpenAI 서비스를 통해 OpenAI의 Responses API를 사용해요. Azure에 배포된 gpt-5 및 o-시리즈 모델(o1, o3-mini 같은 추론 모델)을 지원합니다. 기본 모델은 gpt-5-mini예요.
Responses API는 추론이 가능한 모델을 위해 설계되었으며, 추론 요약, 이전 응답 ID를 이용한 다중 턴 대화, 구조화된 출력 같은 기능을 지원해요. 이 컴포넌트는 Azure 인프라를 통해 이러한 기능에 접근할 수 있게 해줍니다.
컴포넌트는 ChatMessage 객체 목록이 있어야 동작해요. ChatMessage는 메시지, 역할(누가 메시지를 만들었는지 — user, assistant, system), 선택적 메타데이터를 담는 데이터 클래스입니다. 문자열이 전달되면 user 역할의 ChatMessage 하나를 담은 목록으로 변환됩니다. 예시는 usage 섹션을 참고하세요.
OpenAI Responses API에 유효한 어떤 파라미터든 generation_kwargs 파라미터로 AzureOpenAIResponsesChatGenerator에 직접 전달할 수 있어요. 초기화 때와 run() 메서드 모두에 가능합니다. 지원 파라미터에 대한 자세한 내용은 Azure OpenAI 문서를 참고하세요.
이 컴포넌트의 모델은 azure_deployment init 파라미터로 지정하며, Azure 배포 이름과 일치해야 해요.
Authentication
Azure 컴포넌트를 쓰려면 Azure OpenAI API 키와 Azure OpenAI 엔드포인트가 필요합니다. 자세한 내용은 Azure 문서에서 확인할 수 있어요.
컴포넌트는 기본적으로 AZURE_OPENAI_API_KEY와 AZURE_OPENAI_ENDPOINT 환경 변수를 사용합니다. 또는 Secret을 사용해 초기화 때 전달할 수 있어요:
from haystack.components.generators.chat import AzureOpenAIResponsesChatGenerator
from haystack.utils import Secret
client = AzureOpenAIResponsesChatGenerator(
azure_endpoint="https://your-resource.azure.openai.com/",
api_key=Secret.from_token("<your-api-key>"),
azure_deployment="gpt-5-mini",
)
Azure Active Directory 인증의 경우 토큰을 반환하는 콜러블을 전달할 수 있어요:
from haystack.components.generators.chat import AzureOpenAIResponsesChatGenerator
def get_azure_ad_token():
# Your Azure AD token retrieval logic
return "your-azure-ad-token"
client = AzureOpenAIResponsesChatGenerator(
azure_endpoint="https://your-resource.azure.openai.com/",
api_key=get_azure_ad_token,
azure_deployment="gpt-5-mini",
)
Reasoning Support
Responses API의 핵심 기능 중 하나는 추론 모델 지원이에요. generation_kwargs의 reasoning 파라미터로 추론 동작을 설정할 수 있습니다:
from haystack.components.generators.chat import AzureOpenAIResponsesChatGenerator
from haystack.dataclasses import ChatMessage
client = AzureOpenAIResponsesChatGenerator(
azure_endpoint="https://your-resource.azure.openai.com/",
generation_kwargs={"reasoning": {"effort": "medium", "summary": "auto"}},
)
messages = [
ChatMessage.from_user(
"What's the most efficient sorting algorithm for nearly sorted data?",
),
]
response = client.run(messages)
print(response)
reasoning 파라미터가 받는 값:
effort: 추론 노력 수준 —"low","medium","high"summary: 추론 요약 생성 방식 —"auto"또는"generate_summary": True/False
note OpenAI는 실제 추론 토큰을 반환하지 않지만, 활성화하면 요약을 볼 수 있어요. 자세한 내용은 OpenAI Reasoning 문서를 참고하세요.
Multi-turn Conversations
Responses API는 previous_response_id를 사용한 다중 턴 대화를 지원해요. 이전 턴의 응답 ID를 전달해 대화 컨텍스트를 유지할 수 있습니다:
from haystack.components.generators.chat import AzureOpenAIResponsesChatGenerator
from haystack.dataclasses import ChatMessage
client = AzureOpenAIResponsesChatGenerator(
azure_endpoint="https://your-resource.azure.openai.com/",
)
# First turn
messages = [ChatMessage.from_user("What's quantum computing?")]
response = client.run(messages)
response_id = response["replies"][0].meta.get("id")
# Second turn - reference previous response
messages = [ChatMessage.from_user("Can you explain that in simpler terms?")]
response = client.run(messages, generation_kwargs={"previous_response_id": response_id})
Structured Output
AzureOpenAIResponsesChatGenerator는 generation_kwargs의 text_format와 text 파라미터로 구조화된 출력 생성을 지원해요:
text_format: Pydantic 모델을 전달해 구조를 정의text: JSON 스키마를 직접 전달
Pydantic 모델 사용하기:
from pydantic import BaseModel
from haystack.components.generators.chat import AzureOpenAIResponsesChatGenerator
from haystack.dataclasses import ChatMessage
class ProductInfo(BaseModel):
name: str
price: float
category: str
in_stock: bool
client = AzureOpenAIResponsesChatGenerator(
azure_endpoint="https://your-resource.azure.openai.com/",
azure_deployment="gpt-4o",
generation_kwargs={"text_format": ProductInfo},
)
response = client.run(
messages=[
ChatMessage.from_user(
"Extract product info: 'Wireless Mouse, $29.99, Electronics, Available in stock'",
),
],
)
print(response["replies"][0].text)
JSON 스키마 사용하기:
from haystack.components.generators.chat import AzureOpenAIResponsesChatGenerator
from haystack.dataclasses import ChatMessage
json_schema = {
"format": {
"type": "json_schema",
"name": "ProductInfo",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"price": {"type": "number"},
"category": {"type": "string"},
"in_stock": {"type": "boolean"},
},
"required": ["name", "price", "category", "in_stock"],
"additionalProperties": False,
},
},
}
client = AzureOpenAIResponsesChatGenerator(
azure_endpoint="https://your-resource.azure.openai.com/",
azure_deployment="gpt-4o",
generation_kwargs={"text": json_schema},
)
response = client.run(
messages=[
ChatMessage.from_user(
"Extract product info: 'Wireless Mouse, $29.99, Electronics, Available in stock'",
),
],
)
print(response["replies"][0].text)
Model Compatibility and Limitations
- 최신 모델(GPT-4o부터)은 Pydantic 모델과 JSON 스키마를 모두 지원해요.
text_format와text를 모두 제공하면text_format이 우선하며text로 전달된 JSON 스키마는 무시됩니다.- 구조화된 출력을 쓸 때는 스트리밍을 지원하지 않아요.
- 이전 모델은
{"type": "json_object"}를 통한 기본 JSON 모드만 지원합니다. 자세한 내용은 OpenAI JSON mode 문서를 참고하세요. - 완전한 정보는 Azure OpenAI Structured Outputs 문서를 확인하세요.
Tool Support
AzureOpenAIResponsesChatGenerator는 tools 파라미터로 함수 호출을 지원해요. 유연한 도구 설정을 받아들입니다:
- Haystack Tool 객체와 Toolset: Haystack
Tool객체나Toolset객체 전달, 둘을 섞은 목록 포함 - OpenAI/MCP 도구 정의: 미리 정의된 OpenAI 또는 MCP 도구 정의를 딕셔너리로 전달
한 호출에서 Haystack 도구와 OpenAI/MCP 도구를 섞을 수 없다는 점을 기억하세요 — 둘 중 하나의 형식을 선택해야 해요.
from haystack.tools import Tool
from haystack.components.generators.chat import AzureOpenAIResponsesChatGenerator
from haystack.dataclasses import ChatMessage
def get_weather(city: str) -> str:
"""Get weather information for a city."""
return f"Weather in {city}: Sunny, 22°C"
weather_tool = Tool(
name="get_weather",
description="Get current weather for a city",
function=get_weather,
parameters={"type": "object", "properties": {"city": {"type": "string"}}},
)
generator = AzureOpenAIResponsesChatGenerator(
azure_endpoint="https://your-resource.azure.openai.com/",
tools=[weather_tool],
)
messages = [ChatMessage.from_user("What's the weather in Paris?")]
response = generator.run(messages)
tools_strict 파라미터로 엄격한 스키마 준수를 제어할 수 있어요. True(기본값은 False)로 설정하면 모델이 도구 스키마를 정확히 따릅니다. Responses API는 이 파라미터와 무관한 자체적인 엄격성 강제 메커니즘을 갖고 있다는 점을 기억하세요.
도구 작업에 대한 자세한 내용은 Tool과 Toolset 문서를 참고하세요.
Streaming
생성되는 대로 출력을 스트리밍할 수 있어요. streaming_callback에 콜백을 넘기면 됩니다. 내장 print_streaming_chunk를 쓰면 텍스트 토큰과 도구 이벤트(도구 호출·도구 결과)를 출력할 수 있어요.
from haystack.components.generators.utils import print_streaming_chunk
# Configure any `ChatGenerator` with a streaming callback
component = SomeChatGenerator(streaming_callback=print_streaming_chunk)
# Pass a list of messages:
# from haystack.dataclasses import ChatMessage
# component.run([ChatMessage.from_user("Your question here")])
info 스트리밍은 단일 응답에서만 동작해요. 프로바이더가 여러 후보를 지원한다면
n=1로 설정하세요.
StreamingChunk가 어떻게 동작하는지, 사용자 정의 콜백을 어떻게 작성하는지는 Streaming Support 문서를 참고하세요.
기본적으로 print_streaming_chunk를 우선 쓰는 걸 권장해요. 특정 전송(예: SSE/WebSocket)이나 사용자 정의 UI 포맷이 필요할 때만 직접 콜백을 작성하세요.
Usage
On its own
추론과 스트리밍을 사용해 AzureOpenAIResponsesChatGenerator를 독립적으로 쓰는 예시입니다:
from haystack.dataclasses import ChatMessage
from haystack.components.generators.chat import AzureOpenAIResponsesChatGenerator
from haystack.components.generators.utils import print_streaming_chunk
client = AzureOpenAIResponsesChatGenerator(
azure_endpoint="https://your-resource.azure.openai.com/",
streaming_callback=print_streaming_chunk,
generation_kwargs={"reasoning": {"effort": "high", "summary": "auto"}},
)
response = client.run(
[
ChatMessage.from_user(
"Solve this logic puzzle: If all roses are flowers and some flowers fade quickly, can we conclude that some roses fade quickly?",
),
],
)
print(response["replies"][0].reasoning) # Access reasoning summary if available
In a pipeline
이 예시는 ChatPromptBuilder로 동적 프롬프트를 만들고, 추론을 활성화한 AzureOpenAIResponsesChatGenerator로 복잡한 주제의 설명을 생성하는 파이프라인을 보여줘요:
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.chat import AzureOpenAIResponsesChatGenerator
from haystack.dataclasses import ChatMessage
from haystack import Pipeline
prompt_builder = ChatPromptBuilder()
llm = AzureOpenAIResponsesChatGenerator(
azure_endpoint="https://your-resource.azure.openai.com/",
generation_kwargs={"reasoning": {"effort": "low", "summary": "auto"}},
)
pipe = Pipeline()
pipe.add_component("prompt_builder", prompt_builder)
pipe.add_component("llm", llm)
pipe.connect("prompt_builder.prompt", "llm.messages")
topic = "quantum computing"
messages = [
ChatMessage.from_system(
"You are a helpful assistant that explains complex topics clearly.",
),
ChatMessage.from_user("Explain {{topic}} in simple terms"),
]
result = pipe.run(
data={
"prompt_builder": {
"template_variables": {"topic": topic},
"template": messages,
},
},
)
print(result)
더 알아보기 (Learn more)
- Chat Generators — 채팅 생성기 개요
- Tool, Toolset — 도구 사용
- Choosing the Right Generator — 스트리밍 지원