CometAPIChatGenerator

CometAPIChatGenerator

CometAPIChatGenerator는 Comet API를 통해 500개 이상의 AI 모델에 접근하게 해줘요. Comet API는 OpenAI, Anthropic, Google, xAI, DeepSeek 등 여러 제공 업체의 모델을 위한 통합 API 게이트웨이입니다. 단일 파이프라인에서 일관된 인터페이스로 서로 다른 제공 업체의 여러 모델을 사용할 수 있어요.

출처: 문서

본문

Comet API는 모든 제공 업체에 단일 API 키를 사용하므로, 여러 자격 증명을 관리할 필요 없이 모델을 전환하거나 결합할 수 있습니다.

Comet API가 지원하는 모델 범위:

  • OpenAI 모델: gpt-5-mini(기본), gpt-4o, gpt-4o-mini 등
  • Anthropic 모델: claude-sonnet-4-5, claude-opus-4-5-20251101 등
  • Google 모델: gemini-2.5-pro, gemini-2.5-flash 등
  • xAI 모델: grok-4.3 등
  • DeepSeek 모델: deepseek-chat 등

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

이 컴포넌트는 ChatMessage 객체 리스트를 필요로 해요. ChatMessage는 메시지, 역할(누가 생성했는지 — user, assistant, system, tool 등), 그리고 선택적 메타데이터를 담는 데이터 클래스입니다.

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

Authentication

CometAPIChatGenerator는 작동에 Comet API 키가 필요합니다. 다음 위치에서 설정할 수 있어요:

  • api_key init 파라미터(Secret API 사용)
  • COMET_API_KEY 환경 변수(권장)

Structured Output

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

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

from pydantic import BaseModel
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.cometapi import CometAPIChatGenerator


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


client = CometAPIChatGenerator(
    model="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"}

모델 호환성: 구조화된 출력 지원은 기본 모델에 따라 달라져요. gpt-4o-2024-08-06부터 시작하는 OpenAI 모델은 Pydantic 모델과 JSON 스키마를 지원합니다. 어떤 모델이 이 기능을 지원하는지에 대한 자세한 내용은 각 모델 제공 업체 문서를 참고하세요.

Tool Support

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

  • Tool 객체 리스트 — 개별 도구를 리스트로 전달
  • 단일 Toolset — Toolset 전체를 직접 전달
  • 혼합 Tool 및 Toolset — 여러 Toolset을 독립 도구와 함께 하나의 리스트로 결합

이로써 관련 도구를 논리적 그룹으로 정리하면서, 필요하면 독립 도구도 포함할 수 있어요.

from haystack.tools import Tool, Toolset
from haystack_integrations.components.generators.cometapi import CometAPIChatGenerator

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

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

Streaming

CometAPIChatGenerator는 LLM 토큰을 출력으로 직접 스트리밍하는 것을 지원합니다. 이렇게 하려면 streaming_callback init 파라미터에 함수를 전달하세요.

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

from haystack.components.generators.utils import print_streaming_chunk
from haystack_integrations.components.generators.cometapi import CometAPIChatGenerator

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

CometAPIChatGenerator를 사용하려면 cometapi-haystack 패키지를 설치하세요:

pip install cometapi-haystack

On its own

from haystack.components.generators.utils import print_streaming_chunk
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.cometapi import CometAPIChatGenerator

client = CometAPIChatGenerator(
    model="gpt-4o-mini", 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 the interaction between computers and humans through
# >> natural language...')], _name=None, _meta={'model': 'gpt-4o-mini-2024-07-18',
# >> 'index': 0, 'finish_reason': 'stop', 'usage': {'completion_tokens': 59,
# >> 'prompt_tokens': 15, 'total_tokens': 74}})]}

멀티모달 입력 포함:

from haystack.dataclasses import ChatMessage, ImageContent
from haystack_integrations.components.generators.cometapi import CometAPIChatGenerator

# Use a multimodal model like GPT-4o
llm = CometAPIChatGenerator(model="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.cometapi import CometAPIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack import Pipeline
from haystack.utils import Secret

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

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. \n\nDie Stadt hat eine bewegte
# >> Vergangenheit, die stark von der Teilung zwischen Ost- und Westberlin während
# >> des Kalten Krieges geprägt war. Die Berliner Mauer, die von 1961 bis 1989 die
# >> Stadt teilte, ist heute ein Symbol für die Wiedervereinigung und die Freiheit.')],
# >> _name=None, _meta={'model': 'gpt-5-mini-2025-08-07', 'index': 0,
# >> 'finish_reason': 'stop', 'usage': {'completion_tokens': 260,
# >> 'prompt_tokens': 29, 'total_tokens': 289}})]}

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

from haystack.components.builders import ChatPromptBuilder
from haystack_integrations.components.generators.cometapi import CometAPIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack import Pipeline

# Create a pipeline that uses different models for different tasks
prompt_builder = ChatPromptBuilder()
# Use Claude for complex reasoning
claude_llm = CometAPIChatGenerator(model="claude-sonnet-4-5")
# Use GPT-4o-mini for simple tasks
gpt_llm = CometAPIChatGenerator(model="gpt-4o-mini")

pipe = Pipeline()
pipe.add_component("prompt_builder", prompt_builder)
pipe.add_component("claude", claude_llm)
pipe.add_component("gpt", gpt_llm)

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

messages = [ChatMessage.from_user("Explain quantum computing in simple terms.")]
result = pipe.run(data={"prompt_builder": {"template": messages}})

print("Claude:", result["claude"]["replies"][0].text)
print("GPT-4o-mini:", result["gpt"]["replies"][0].text)

With an Agent

도구 호출을 위해 generator와 도구를 Agent에 전달하면, Agent가 전체 도구 호출 루프를 관리합니다:

from haystack.components.agents import Agent
from haystack.dataclasses import ChatMessage
from haystack.tools import Tool
from haystack_integrations.components.generators.cometapi import CometAPIChatGenerator


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=CometAPIChatGenerator(), 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)