AzureOpenAIChatGenerator — Azure OpenAI 채팅 생성
AzureOpenAIChatGenerator — Azure OpenAI 채팅 생성
이 컴포넌트는 Azure 서비스를 통해 OpenAI의 대규모 언어 모델(LLM)을 이용해 채팅 완성(chat completion)을 만들 수 있게 해 줘요. Azure에 배포된 OpenAI 모델을 Haystack 파이프라인에서 호출하는 한 조각이라고 보시면 돼요.
개요 (Overview)
AzureOpenAIChatGenerator는 Azure 서비스를 통해 배포된 OpenAI 모델을 지원해요. 지원되는 모델 목록은 Azure 문서에서 확인할 수 있어요. 이 컴포넌트에서 기본으로 사용하는 모델은 gpt-4.1-mini예요.
Azure 컴포넌트를 쓰려면 Azure OpenAI API 키와 Azure OpenAI 엔드포인트가 필요해요. 이에 대한 자세한 내용은 Azure 문서에서 확인할 수 있어요.
컴포넌트는 기본적으로 AZURE_OPENAI_API_KEY와 AZURE_OPENAI_AD_TOKEN 환경 변수를 사용해요. 아니면 초기화할 때 api_key와 azure_ad_token을 직접 넘길 수도 있어요.
client = AzureOpenAIChatGenerator(
azure_endpoint="<Your Azure endpoint e.g. `https://your-company.azure.openai.com/>",
api_key=Secret.from_token("<your-api-key>"),
azure_deployment="<a model name>",
)
참고 초기화 파라미터 대신 환경 변수를 사용하는 걸 권장해요.
파이프라인을 수정하지 않고 환경 간에 azure_endpoint와 api_version을 바꾸고 싶다면, 런타임에 환경 변수로부터 값을 가져오는 Secret을 넘기면 돼요.
from haystack.components.generators.chat import AzureOpenAIChatGenerator
from haystack.utils import Secret
client = AzureOpenAIChatGenerator(
azure_endpoint=Secret.from_env_var("AZURE_OPENAI_ENDPOINT"),
api_version=Secret.from_env_var("AZURE_OPENAI_API_VERSION"),
)
그리고 이 컴포넌트는 ChatMessage 객체의 리스트를 받아서 동작해요. ChatMessage는 메시지와 역할(누가 만들었는지 — user, assistant, system, tool 등), 선택적 메타데이터를 담는 데이터 클래스예요. 문자열을 넘기면 역할이 user인 ChatMessage 하나를 담은 리스트로 변환돼요. 사용 예시는 사용법 섹션을 보면 돼요.
openai.ChatCompletion.create 메서드에서 쓸 수 있는 채팅 완성 파라미터는 대부분 generation_kwargs 파라미터로 그대로 전달할 수 있어요. 초기화할 때도, run() 메서드를 호출할 때도 둘 다 가능하죠. 지원되는 파라미터에 대한 자세한 내용은 Azure 문서를 참고하세요.
이 컴포넌트의 모델은 azure_deployment 초기화 파라미터로 지정할 수도 있어요.
구조화된 출력 (Structured Output)
AzureOpenAIChatGenerator는 구조화된 출력 생성을 지원해요. 미리 정해진 형식의 응답을 받을 수 있다는 뜻이에요. generation_kwargs의 response_format 파라미터에 Pydantic 모델이나 JSON 스키마를 지정해서 출력 구조를 정의할 수 있어요.
텍스트에서 구조화된 데이터를 뽑아내야 하거나, 특정 형식을 맞춘 응답이 필요할 때 특히 유용해요.
from pydantic import BaseModel
from haystack.components.generators.chat import AzureOpenAIChatGenerator
from haystack.dataclasses import ChatMessage
class NobelPrizeInfo(BaseModel):
recipient_name: str
award_year: int
category: str
achievement_description: str
nationality: str
client = AzureOpenAIChatGenerator(
azure_endpoint="<Your Azure endpoint>",
azure_deployment="gpt-4o",
generation_kwargs={"response_format": NobelPrizeInfo},
)
response = client.run(
messages=[
ChatMessage.from_user(
"In 2021, American scientist David Julius received the Nobel Prize in"
" Physiology or Medicine for his groundbreaking discoveries on how the human body"
" senses temperature and touch.",
),
],
)
print(response["replies"][0].text)
# {"recipient_name":"David Julius","award_year":2021,"category":"Physiology or Medicine",
# "achievement_description":"David Julius was awarded for his transformative findings
# regarding the molecular mechanisms underlying the human body's sense of temperature
# and touch. Through innovative experiments, he identified specific receptors responsible
# for detecting heat and mechanical stimuli, ranging from gentle touch to pain-inducing
# pressure.","nationality":"American"}
참고 — 모델 호환성과 한계
- Pydantic 모델과 JSON 스키마는 GPT-4o부터 최신 모델에서 지원돼요.
- 이전 모델은
{"type": "json_object"}형태의 기본 JSON 모드만 지원해요. 자세한 내용은 OpenAI JSON mode 문서를 확인하세요.- 스트리밍 제한: 구조화된 출력을 스트리밍할 때는
response_format에 Pydantic 모델 대신 JSON 스키마를 꼭 넘겨야 해요.- 전체 정보는 Azure OpenAI Structured Outputs 문서를 참고하세요.
스트리밍 (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")])
참고 스트리밍은 단일 응답일 때만 동작해요. 공급자가 여러 후보를 지원한다면
n=1로 설정하세요.
StreamingChunk가 어떻게 동작하는지, 커스텀 콜백을 어떻게 작성하는지 더 알고 싶다면 Streaming Support 문서를 참고하세요.
기본적으로는 print_streaming_chunk를 쓰는 걸 권장해요. 커스텀 콜백은 특별한 전송 방식(예: SSE/WebSocket)이나 커스텀 UI 포맷이 필요할 때만 작성하면 돼요.
사용법 (Usage)
단독 사용 (On its own)
기본 사용법:
from haystack.dataclasses import ChatMessage
from haystack.components.generators.chat import AzureOpenAIChatGenerator
client = AzureOpenAIChatGenerator()
response = client.run(
[ChatMessage.from_user("What's Natural Language Processing? Be brief.")],
)
print(response)
스트리밍으로 사용:
from haystack.dataclasses import ChatMessage
from haystack.components.generators.chat import AzureOpenAIChatGenerator
client = AzureOpenAIChatGenerator(
streaming_callback=lambda chunk: print(chunk.content, end="", flush=True),
)
response = client.run(
[ChatMessage.from_user("What's Natural Language Processing? Be brief.")],
)
print(response)
멀티모달 입력으로 사용:
from haystack.dataclasses import ChatMessage, ImageContent
from haystack.components.generators.chat import AzureOpenAIChatGenerator
llm = AzureOpenAIChatGenerator(
azure_endpoint="<Your Azure endpoint>",
azure_deployment="gpt-4o-mini",
)
image = ImageContent.from_file_path("apple.jpg", detail="low")
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)
# Fresh red apple on straw.
파이프라인에서 사용 (In a pipeline)
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.chat import AzureOpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack import Pipeline
# no parameter init, we don't use any runtime template variables
prompt_builder = ChatPromptBuilder()
llm = AzureOpenAIChatGenerator()
pipe = Pipeline()
pipe.add_component("prompt_builder", prompt_builder)
pipe.add_component("llm", llm)
pipe.connect("prompt_builder.prompt", "llm.messages")
location = "Berlin"
messages = [
ChatMessage.from_system(
"Always respond in German even if some input data is in other languages.",
),
ChatMessage.from_user("Tell me about {{location}}"),
]
pipe.run(
data={
"prompt_builder": {
"template_variables": {"location": location},
"template": messages,
},
},
)