AIMLAPIChatGenerator

AIMLAPIChatGenerator

AIMLAPIChatGenerator는 AIMLAPI를 통해 AI 모델로 채팅 완성(chat completion)을 가능하게 해줘요.

파이프라인에서 가장 흔한 위치: ChatPromptBuilder 뒤 필수 init 변수: api_key — AIMLAPI API 키. AIMLAPI_API_KEY 환경 변수로 설정 가능 필수 run 변수: messages — ChatMessage 객체 목록 출력 변수: replies — ChatMessage 객체 목록 API reference: AIMLAPI GitHub link: https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/aimlapi Package name: aimlapi-haystack

출처: 문서

본문

Overview

AIMLAPIChatGenerator는 AIMLAPI를 통해 다양한 제공자의 모델에 접근할 수 있게 해줘요. AIMLAPI는 여러 프로바이더의 모델을 위한 통합 API 게이트웨이죠. 하나의 일관된 인터페이스로 한 파이프라인 안에서 서로 다른 모델을 사용할 수 있어요. 기본 모델은 openai/gpt-5-chat-latest입니다.

AIMLAPI는 모든 프로바이더에 단일 API 키를 사용해요. 여러 자격 증명을 관리하지 않고도 서로 다른 모델을 전환하거나 조합할 수 있죠.

사용 가능한 모델 전체 목록은 AIMLAPI 문서에서 확인하세요.

이 컴포넌트는 ChatMessage 객체 목록이 있어야 동작해요. ChatMessage는 메시지, 역할(누가 메시지를 만들었는지 — user, assistant, system, tool 등), 그리고 선택적 메타데이터를 담는 데이터 클래스입니다.

기본 모델에 유효한 어떤 채팅 완성 파라미터든 generation_kwargs 파라미터로 초기화 때와 run() 메서드 모두에 직접 전달할 수 있어요.

Authentication

AIMLAPIChatGenerator는 작동하려면 AIMLAPI API 키가 필요해요. 키는 다음에 설정할 수 있습니다:

  • Secret API를 쓴 api_key init 파라미터
  • AIMLAPI_API_KEY 환경 변수(권장)

Structured Output

AIMLAPIChatGenerator는 호환 모델에 대해 구조화된 출력 생성을 지원해요. 예측 가능한 포맷으로 응답을 받을 수 있죠. generation_kwargs의 response_format 파라미터로 Pydantic 모델이나 JSON 스키마를 사용해 출력 구조를 정의할 수 있어요.

텍스트에서 구조화된 데이터를 추출하거나 특정 형식에 맞는 응답을 생성해야 할 때 유용합니다.

from pydantic import BaseModel
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator

class CityInfo(BaseModel):
    city_name: str
    country: str
    population: int
    famous_for: str

client = AIMLAPIChatGenerator(
    model="openai/gpt-4o-2024-08-06", generation_kwargs={"response_format": CityInfo})
response = client.run(
    messages=[
        ChatMessage.from_user(
            "Berlin is the capital and largest city of Germany with a population of "
            "approximately 3.7 million. It's famous for its history, culture, and nightlife."
        )
    ])
print(response["replies"][0].text)
# >> {"city_name":"Berlin","country":"Germany","population":3700000,
# >> "famous_for":"history, culture, and nightlife"}

Model Compatibility 구조화된 출력 지원은 기본 모델에 따라 달라져요. OpenAI 모델은 gpt-4o-2024-08-06부터 Pydantic 모델과 JSON 스키마를 지원합니다. 어떤 모델이 이 기능을 지원하는지 자세한 내용은 해당 모델 프로바이더 문서를 참고하세요.

Tool Support

AIMLAPIChatGenerator는 tools 파라미터로 함수 호출(function calling)을 지원하며, 유연한 도구 설정을 받아들여요:

  • Tool 객체 목록: 개별 도구를 목록으로 전달
  • 단일 Toolset: Toolset 전체를 직접 전달
  • 혼합 도구와 Toolset: 여러 Toolset을 단독 도구와 한 목록에 결합

덕분에 관련 도구를 논리적 그룹으로 정리하면서 필요에 따라 단독 도구도 포함할 수 있어요.

from haystack.tools import Tool, Toolset
from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator

# 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 = AIMLAPIChatGenerator(
    tools=[math_toolset, weather_tool, news_tool]  # Mix of Toolset and Tool objects
)

도구 작업에 대한 자세한 내용은 Tool과 Toolset 문서를 참고하세요.

Streaming

AIMLAPIChatGenerator는 LLM의 토큰을 출력에서 직접 스트리밍하는 것을 지원해요. 그러려면 streaming_callback init 파라미터에 함수를 전달하세요.

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

from haystack.components.generators.utils import print_streaming_chunk
from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator

# Configure the generator with a streaming callback
component = AIMLAPIChatGenerator(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

AIMLAPIChatGenerator를 쓰려면 aimlapi-haystack 패키지를 설치하세요:

pip install aimlapi-haystack

On its own

from haystack.components.generators.utils import print_streaming_chunk
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator

client = AIMLAPIChatGenerator(
    model="openai/gpt-5-chat-latest", streaming_callback=print_streaming_chunk)
response = client.run(
    [ChatMessage.from_user("What's Natural Language Processing? Be brief.")])
# >> Natural Language Processing (NLP) is a field of artificial intelligence that
# >> focuses on the interaction between computers and humans through natural language.
# >> It involves enabling machines to understand, interpret, and generate human
# >> language in a meaningful way, facilitating tasks such as language translation,
# >> sentiment analysis, and text summarization.
print(response)
# >> {'replies': [ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>, _content=
# >> [TextContent(text='Natural Language Processing (NLP) is a field of artificial
# >> intelligence that focuses on enabling computers to understand, interpret, and
# >> generate human language in a meaningful and useful way.')], _name=None,
# >> _meta={'model': 'openai/gpt-5-chat-latest', 'index': 0,
# >> 'finish_reason': 'stop', 'usage': {'completion_tokens': 36,
# >> 'prompt_tokens': 15, 'total_tokens': 51}})]}

멀티모달 입력으로:

from haystack.dataclasses import ChatMessage, ImageContent
from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator

# Use a multimodal model
llm = AIMLAPIChatGenerator(model="openai/gpt-4o")
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)
# >> Red apple on straw.

In a Pipeline

from haystack.components.builders import ChatPromptBuilder
from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack import Pipeline

# No parameter init, we don't use any runtime template variables
prompt_builder = ChatPromptBuilder()
llm = AIMLAPIChatGenerator()

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,
        }
    })
# >> {'llm': {'replies': [ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>,
# >> _content=[TextContent(text='Berlin ist die Hauptstadt Deutschlands und eine der
# >> bedeutendsten Städte Europas. Es ist bekannt für ihre reiche Geschichte,
# >> kulturelle Vielfalt und kreative Scene.')],
# >> _name=None, _meta={'model': 'openai/gpt-5-chat-latest', 'index': 0,
# >> 'finish_reason': 'stop', 'usage': {'completion_tokens': 120,
# >> 'prompt_tokens': 29, 'total_tokens': 149}})]}

한 파이프라인에서 여러 모델 사용하기:

from haystack.components.builders import ChatPromptBuilder
from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack import Pipeline

# Create a pipeline that uses different models for different tasks
prompt_builder = ChatPromptBuilder()

# Use one model for complex reasoning
reasoning_llm = AIMLAPIChatGenerator(model="anthropic/claude-3-5-sonnet")
# Use another model for simple tasks
simple_llm = AIMLAPIChatGenerator(model="openai/gpt-5-chat-latest")

pipe = Pipeline()
pipe.add_component("prompt_builder", prompt_builder)
pipe.add_component("reasoning", reasoning_llm)
pipe.add_component("simple", simple_llm)

# Feed the same prompt to both models
pipe.connect("prompt_builder.prompt", "reasoning.messages")
pipe.connect("prompt_builder.prompt", "simple.messages")

messages = [ChatMessage.from_user("Explain quantum computing in simple terms.")]
result = pipe.run(data={"prompt_builder": {"template": messages}})
print("Reasoning model:", result["reasoning"]["replies"][0].text)
print("Simple model:", result["simple"]["replies"][0].text)

With an Agent

도구 호출을 위해 생성기와 도구를 Agent에 전달하면, Agent가 전체 도구 호출 루프를 관리해요:

from haystack.components.agents import Agent
from haystack.dataclasses import ChatMessage
from haystack.tools import Tool
from haystack_integrations.components.generators.aimlapi import AIMLAPIChatGenerator

def weather(city: str) -> str:
    """Get weather for a given city."""
    return f"The weather in {city} is sunny and 32°C"

tool = Tool(
    name="weather",
    description="Get weather for a given city",
    parameters={
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"],
    },
    function=weather,
)

agent = Agent(chat_generator=AIMLAPIChatGenerator(), tools=[tool])
result = agent.run(
    messages=[ChatMessage.from_user("What's the weather like in Paris?")])
print(result["last_message"].text)
# >> The weather in Paris is sunny and 32°C.

더 알아보기 (Learn more)