OpenRouterChatGenerator
此组件支持与托管在 OpenRouter 上的任何模型进行聊天补全。
| pipeline 中的最常见位置 | 在 ChatPromptBuilder 之后 |
| 必需的初始化变量 | “api_key”:OpenRouter API 密钥。可以通过以下方式设置:OPENROUTER_API_KEY 环境变量,或传递给init() 方法。 |
| 强制运行变量 | “messages”:ChatMessage 对象列表 |
| 输出变量 | “replies”:ChatMessage 对象列表 |
| API 参考 | OpenRouter |
| GitHub 链接 | https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/openrouter |
概述
该OpenRouterChatGenerator 使您能够通过向 OpenRouter API 发起聊天补全调用,来使用来自多个提供商(例如openai/gpt-4o, anthropic/claude-3.5-sonnet 等模型)的模型。
此生成器还支持 OpenRouter 特有的功能,例如
- 通过初始化或运行时期间的
generation_kwargs参数进行配置的提供商路由和模型回退。 - 可以通过
extra_headers参数提供的自定义 HTTP 标头。
此组件使用与Haystack其他聊天生成器相同的ChatMessage格式,用于结构化输入和输出。有关更多信息,请参阅ChatMessage文档。
它还完全兼容 Haystack 的 Tools 和 Toolsets,这些工具支持与兼容模型进行函数调用。
初始化
要使用此集成,您必须拥有有效的 OpenRouter 订阅,并有足够的积分和 API 密钥。您可以通过OPENROUTER_API_KEY 环境变量或通过 Secret 提供。
然后,安装 openrouter-haystack 集成。
pip install openrouter-haystack
流式传输
OpenRouterChatGenerator 支持从 LLM 进行 流式传输响应,允许在生成令牌时发出它们。要启用流式传输,请将可调用对象传递给streaming_callback参数。
用法
单独使用
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"])
在 pipeline 中
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)
更新于 5 个月前
