OpenRouterChatGenerator

OpenRouterChatGenerator

OpenRouter에 호스팅된 어떤 모델로든 채팅 완성을 할 수 있게 해 주는 컴포넌트예요.

출처: 문서

본문

OpenRouterChatGenerator는 OpenRouter API로 채팅 완성 호출을 보내서 여러 프로바이더의 모델(openai/gpt-4o, anthropic/claude-sonnet-4.5 등)을 쓸 수 있게 해 줘요.

이 Generator는 OpenRouter 특유의 기능도 지원해요.

  • 초기화 시 또는 실행 시점에 generation_kwargs 파라미터로 설정할 수 있는 프로바이더 라우팅과 모델 폴백(fallback).
  • extra_headers 파라미터로 제공할 수 있는 커스텀 HTTP 헤더.

이 컴포넌트는 구조화된 입력·출력에 다른 Haystack Chat Generator와 같은 ChatMessage 형식을 사용해요. 자세한 내용은 ChatMessage 문서를 참고하세요.

툴 지원

OpenRouterChatGenerator는 tools 파라미터로 함수 호출을 지원하며, 이 파라미터는 유연한 툴 구성을 받아요.

  • Tool 객체 목록: 개별 툴을 목록으로 넘겨요.
  • 단일 Toolset: Toolset 전체를 그대로 넘겨요.
  • Tool과 Toolset 혼합: 여러 Toolset을 독립 툴과 한 목록에 섞어요.

이렇게 하면 관련 툴을 논리적 그룹으로 묶으면서 필요할 때 독립 툴도 함께 넣을 수 있어요.

from haystack.tools import Tool, Toolset
from haystack_integrations.components.generators.openrouter import (
    OpenRouterChatGenerator,
)


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

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

초기화

이 통합을 쓰려면 크레딧이 충분한 활성 OpenRouter 구독과 API 키가 있어야 해요. OPENROUTER_API_KEY 환경 변수나 Secret으로 제공할 수 있어요.

그런 다음 openrouter-haystack 통합을 설치해요.

pip install openrouter-haystack

스트리밍

OpenRouterChatGenerator는 LLM의 스트리밍 응답을 지원해서 토큰이 생성되는 대로 내보낼 수 있어요. 스트리밍을 켜려면 초기화할 때 streaming_callback 파라미터로 콜러블을 넘기면 돼요.

더 알아보기 (Learn more)

단독으로 쓰기

from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.openrouter import (
    OpenRouterChatGenerator,
)


client = OpenRouterChatGenerator()
response = client.run([ChatMessage.from_user("What are Agentic Pipelines? Be brief.")])
print(response["replies"][0].text)

스트리밍과 모델 라우팅 사용:

from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.openrouter import (
    OpenRouterChatGenerator,
)


client = OpenRouterChatGenerator(
    model="openrouter/auto",
    streaming_callback=lambda chunk: print(chunk.content, end="", flush=True),
)

response = client.run([ChatMessage.from_user("What are Agentic Pipelines? Be brief.")])

# check the model used for the response
print("\n\n Model used: ", response["replies"][0].meta["model"])

멀티모달 입력 사용:

from haystack.dataclasses import ChatMessage, ImageContent
from haystack_integrations.components.generators.openrouter import (
    OpenRouterChatGenerator,
)


llm = OpenRouterChatGenerator(model="anthropic/claude-sonnet-4.5")

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.

파이프라인에서 쓰기

from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.openrouter import (
    OpenRouterChatGenerator,
)


prompt_builder = ChatPromptBuilder()
llm = OpenRouterChatGenerator(model="openai/gpt-4o-mini")

pipe = Pipeline()
pipe.add_component("builder", prompt_builder)
pipe.add_component("llm", llm)
pipe.connect("builder.prompt", "llm.messages")

messages = [
    ChatMessage.from_system("Give brief answers."),
    ChatMessage.from_user("Tell me about {{city}}"),
]

response = pipe.run(
    data={"builder": {"template": messages, "template_variables": {"city": "Berlin"}}},
)
print(response)