由 deepset 维护
集成:OpenRouter
使用 OpenRouter API 进行文本生成模型。
目录
概述
OpenRouterChatGenerator 允许您调用 OpenRouter 上提供的任何 LLM,包括
- OpenAI 变体,如
openai/gpt-4o - Anthropic 的
claude-3.5-sonnet - 社区托管的开源模型(Llama 2、Mixtral 等)
有关通过 OpenRouter API 可用的模型的更多信息,请参阅 OpenRouter 文档。
除了基本的聊天补全外,该组件还公开了 OpenRouter 特有的功能
- 提供商/模型路由 – 使用
generation_kwargs参数选择备用模型或提供商顺序。 - 额外的 HTTP 标头 – 通过
extra_headers添加归属或跟踪标头。
为了跟上本指南的步伐,您需要一个 OpenRouter API 密钥。将其添加为环境变量 OPENROUTER_API_KEY。
安装
pip install openrouter-haystack
使用
您可以将 OpenRouterChatGenerator 单独使用,在 pipeline 中使用,或与 Agent 组件 一起使用。
以下是将其用作独立组件的示例
import os
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.openrouter import OpenRouterChatGenerator
os.environ["OPENROUTER_API_KEY"] = "YOUR_OPENROUTER_API_KEY"
client = OpenRouterChatGenerator() # defaults to openai/gpt-4o-mini
response = client.run(
[ChatMessage.from_user("What are Agentic Pipelines? Be brief.")]
)
print(response["replies"])
{'replies': [ChatMessage(_role=<ChatRole.ASSISTANT: 'assistant'>, _content=[TextContent(text='The capital of Vietnam is Hanoi.')], _name=None, _meta={'model': 'openai/gpt-4o-mini', 'index': 0, 'finish_reason': 'stop', 'usage': {'completion_tokens': 8, 'prompt_tokens': 13, 'total_tokens': 21, 'completion_tokens_details': CompletionTokensDetails(accepted_prediction_tokens=None, audio_tokens=None, reasoning_tokens=0, rejected_prediction_tokens=None), 'prompt_tokens_details': PromptTokensDetails(audio_tokens=None, cached_tokens=0)}})]}
如果您传递流式回调,OpenRouterChatGenerator 还支持流式响应
import os
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.openrouter import OpenRouterChatGenerator
os.environ["OPENROUTER_API_KEY"] = "YOUR_OPENROUTER_API_KEY"
def show(chunk): # simple streaming callback
print(chunk.content, end="", flush=True)
client = OpenRouterChatGenerator(
model="openrouter/auto", # let OpenRouter pick a model
streaming_callback=show,
generation_kwargs={
"provider": {"sort": "throughput"}, # pick the fastest provider
}
)
response = client.run([ChatMessage.from_user("Summarize RAG in two lines.")])
print (response)
许可证
openrouter-haystack 在 Apache-2.0 许可证下分发。
