openrouter-haystack 2.0.0__tar.gz → 3.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/CHANGELOG.md +23 -0
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/PKG-INFO +2 -2
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/pyproject.toml +2 -3
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/src/haystack_integrations/components/generators/openrouter/chat/chat_generator.py +53 -298
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/tests/test_openrouter_chat_generator.py +46 -283
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/tests/test_openrouter_chat_generator_async.py +6 -183
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/.gitignore +0 -0
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/LICENSE.txt +0 -0
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/README.md +0 -0
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/examples/openrouter_with_structured_outputs.py +0 -0
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/examples/openrouter_with_tools_example.py +0 -0
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/pydoc/config_docusaurus.yml +0 -0
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/src/haystack_integrations/components/generators/openrouter/__init__.py +0 -0
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/src/haystack_integrations/components/generators/openrouter/chat/__init__.py +0 -0
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/src/haystack_integrations/components/generators/py.typed +0 -0
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/tests/__init__.py +0 -0
- {openrouter_haystack-2.0.0 → openrouter_haystack-3.0.0}/tests/conftest.py +0 -0
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [integrations/openrouter-v2.1.0] - 2026-11-19
|
|
4
|
+
|
|
5
|
+
### 🐛 Bug Fixes
|
|
6
|
+
|
|
7
|
+
- OpenRouter - respect an empty runtime tools list (#4223)
|
|
8
|
+
|
|
9
|
+
### 🚜 Refactor
|
|
10
|
+
|
|
11
|
+
- Simplify `OpenRouterChatGenerator` (#4287)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
## [integrations/openrouter-v2.0.0] - 2026-10-16
|
|
15
|
+
|
|
16
|
+
### 🧪 Testing
|
|
17
|
+
|
|
18
|
+
- Test compatible integrations with Python 3.15; update pyproject (#4104)
|
|
19
|
+
|
|
20
|
+
### 🧹 Chores
|
|
21
|
+
|
|
22
|
+
- Replace ToolInvoker with Agent in tests, examples and docstrings (#4108)
|
|
23
|
+
- [**breaking**] Drop Python 3.10 support (#4105)
|
|
24
|
+
|
|
25
|
+
|
|
3
26
|
## [integrations/openrouter-v1.3.0] - 2026-10-07
|
|
4
27
|
|
|
5
28
|
### 🚀 Features
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: openrouter-haystack
|
|
3
|
-
Version:
|
|
3
|
+
Version: 3.0.0
|
|
4
4
|
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/openrouter#readme
|
|
5
5
|
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
6
6
|
Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/openrouter
|
|
@@ -18,7 +18,7 @@ Classifier: Programming Language :: Python :: 3.15
|
|
|
18
18
|
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
19
19
|
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
20
20
|
Requires-Python: >=3.11
|
|
21
|
-
Requires-Dist: haystack-ai>=
|
|
21
|
+
Requires-Dist: haystack-ai>=3.5.0
|
|
22
22
|
Description-Content-Type: text/markdown
|
|
23
23
|
|
|
24
24
|
# openrouter-haystack
|
|
@@ -23,7 +23,7 @@ classifiers = [
|
|
|
23
23
|
"Programming Language :: Python :: Implementation :: CPython",
|
|
24
24
|
"Programming Language :: Python :: Implementation :: PyPy",
|
|
25
25
|
]
|
|
26
|
-
dependencies = ["haystack-ai>=
|
|
26
|
+
dependencies = ["haystack-ai>=3.5.0"]
|
|
27
27
|
|
|
28
28
|
[project.urls]
|
|
29
29
|
Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/openrouter#readme"
|
|
@@ -56,8 +56,7 @@ dependencies = [
|
|
|
56
56
|
"pytest-cov",
|
|
57
57
|
"pytest-rerunfailures",
|
|
58
58
|
"mypy",
|
|
59
|
-
"pip"
|
|
60
|
-
"pytz"
|
|
59
|
+
"pip"
|
|
61
60
|
]
|
|
62
61
|
|
|
63
62
|
[tool.hatch.envs.test.scripts]
|
|
@@ -4,21 +4,14 @@
|
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
6
|
import inspect
|
|
7
|
-
import json
|
|
8
7
|
from dataclasses import replace
|
|
9
8
|
from typing import Any
|
|
10
9
|
|
|
11
|
-
from haystack import component
|
|
10
|
+
from haystack import component
|
|
12
11
|
from haystack.components.generators.chat import OpenAIChatGenerator
|
|
13
12
|
from haystack.components.generators.chat.openai import (
|
|
14
|
-
_check_finish_reason,
|
|
15
13
|
_convert_chat_completion_chunk_to_streaming_chunk,
|
|
16
14
|
)
|
|
17
|
-
from haystack.components.generators.utils import (
|
|
18
|
-
_convert_streaming_chunks_to_chat_message,
|
|
19
|
-
_normalize_messages,
|
|
20
|
-
_serialize_object,
|
|
21
|
-
)
|
|
22
15
|
from haystack.dataclasses import (
|
|
23
16
|
ChatMessage,
|
|
24
17
|
ComponentInfo,
|
|
@@ -26,18 +19,13 @@ from haystack.dataclasses import (
|
|
|
26
19
|
StreamingCallbackT,
|
|
27
20
|
StreamingChunk,
|
|
28
21
|
SyncStreamingCallbackT,
|
|
29
|
-
ToolCall,
|
|
30
|
-
select_streaming_callback,
|
|
31
22
|
)
|
|
32
|
-
from haystack.tools import ToolsType
|
|
33
|
-
from haystack.utils import serialize_callable
|
|
23
|
+
from haystack.tools import ToolsType
|
|
34
24
|
from haystack.utils.auth import Secret
|
|
35
25
|
from openai import AsyncStream, Stream
|
|
36
26
|
from openai.types.chat import ChatCompletion, ChatCompletionChunk, ParsedChatCompletion
|
|
37
27
|
from openai.types.chat.chat_completion import Choice
|
|
38
28
|
|
|
39
|
-
logger = logging.getLogger(__name__)
|
|
40
|
-
|
|
41
29
|
|
|
42
30
|
def _extract_reasoning(message: Any) -> ReasoningContent | None:
|
|
43
31
|
"""Extract reasoning content from an OpenRouter API response message."""
|
|
@@ -77,44 +65,6 @@ def _extract_reasoning(message: Any) -> ReasoningContent | None:
|
|
|
77
65
|
return ReasoningContent(reasoning_text=reasoning_text, extra=extra)
|
|
78
66
|
|
|
79
67
|
|
|
80
|
-
def _convert_openrouter_completion_to_chat_message(
|
|
81
|
-
completion: ChatCompletion | ParsedChatCompletion, choice: Choice
|
|
82
|
-
) -> ChatMessage:
|
|
83
|
-
"""Convert an OpenRouter chat completion to a ChatMessage, including reasoning content."""
|
|
84
|
-
message = choice.message
|
|
85
|
-
text = message.content
|
|
86
|
-
tool_calls = []
|
|
87
|
-
if message.tool_calls:
|
|
88
|
-
for tc in message.tool_calls:
|
|
89
|
-
func = getattr(tc, "function", None)
|
|
90
|
-
if func is None:
|
|
91
|
-
continue
|
|
92
|
-
try:
|
|
93
|
-
arguments = json.loads(func.arguments)
|
|
94
|
-
tool_calls.append(ToolCall(id=tc.id, tool_name=func.name, arguments=arguments))
|
|
95
|
-
except json.JSONDecodeError:
|
|
96
|
-
logger.warning(
|
|
97
|
-
"OpenRouter returned a malformed JSON string for tool call arguments. "
|
|
98
|
-
"Tool call ID: {_id}, Tool name: {_name}, Arguments: {_arguments}",
|
|
99
|
-
_id=tc.id,
|
|
100
|
-
_name=func.name,
|
|
101
|
-
_arguments=func.arguments,
|
|
102
|
-
)
|
|
103
|
-
|
|
104
|
-
logprobs = _serialize_object(choice.logprobs) if choice.logprobs else None
|
|
105
|
-
meta = {
|
|
106
|
-
"model": completion.model,
|
|
107
|
-
"index": choice.index,
|
|
108
|
-
"finish_reason": choice.finish_reason,
|
|
109
|
-
"usage": _serialize_object(completion.usage),
|
|
110
|
-
}
|
|
111
|
-
if logprobs:
|
|
112
|
-
meta["logprobs"] = logprobs
|
|
113
|
-
|
|
114
|
-
reasoning = _extract_reasoning(message)
|
|
115
|
-
return ChatMessage.from_assistant(text=text, tool_calls=tool_calls, meta=meta, reasoning=reasoning)
|
|
116
|
-
|
|
117
|
-
|
|
118
68
|
def _convert_openrouter_chunk_to_streaming_chunks(
|
|
119
69
|
chunk: ChatCompletionChunk, previous_chunks: list[StreamingChunk], component_info: ComponentInfo
|
|
120
70
|
) -> list[StreamingChunk]:
|
|
@@ -202,22 +152,6 @@ def _merge_reasoning_details(details: list[dict[str, Any]]) -> list[dict[str, An
|
|
|
202
152
|
return list(merged.values())
|
|
203
153
|
|
|
204
154
|
|
|
205
|
-
def _convert_openrouter_streaming_chunks_to_chat_message(chunks: list[StreamingChunk]) -> ChatMessage:
|
|
206
|
-
"""Connect OpenRouter streaming chunks into a single ChatMessage, keeping the merged `reasoning_details`."""
|
|
207
|
-
message = _convert_streaming_chunks_to_chat_message(chunks=chunks)
|
|
208
|
-
# the core helper only joins the reasoning text, but OpenRouter expects the details back in multi-turn conversations
|
|
209
|
-
details = [d for c in chunks if c.reasoning for d in c.reasoning.extra.get("reasoning_details", [])]
|
|
210
|
-
if not details:
|
|
211
|
-
return message
|
|
212
|
-
reasoning = ReasoningContent(
|
|
213
|
-
reasoning_text=message.reasoning.reasoning_text if message.reasoning else "",
|
|
214
|
-
extra={"reasoning_details": _merge_reasoning_details(details)},
|
|
215
|
-
)
|
|
216
|
-
return ChatMessage.from_assistant(
|
|
217
|
-
text=message.text, tool_calls=message.tool_calls, meta=message.meta, reasoning=reasoning
|
|
218
|
-
)
|
|
219
|
-
|
|
220
|
-
|
|
221
155
|
@component
|
|
222
156
|
class OpenRouterChatGenerator(OpenAIChatGenerator):
|
|
223
157
|
"""
|
|
@@ -256,7 +190,7 @@ class OpenRouterChatGenerator(OpenAIChatGenerator):
|
|
|
256
190
|
messages = [ChatMessage.from_user("What's Natural Language Processing?")]
|
|
257
191
|
|
|
258
192
|
client = OpenRouterChatGenerator(
|
|
259
|
-
model="deepseek/deepseek-r1",
|
|
193
|
+
model="deepseek/deepseek-r1-0528",
|
|
260
194
|
generation_kwargs={"reasoning": {"effort": "high"}},
|
|
261
195
|
)
|
|
262
196
|
response = client.run(messages)
|
|
@@ -269,7 +203,7 @@ class OpenRouterChatGenerator(OpenAIChatGenerator):
|
|
|
269
203
|
self,
|
|
270
204
|
*,
|
|
271
205
|
api_key: Secret = Secret.from_env_var("OPENROUTER_API_KEY"),
|
|
272
|
-
model: str = "openai/gpt-
|
|
206
|
+
model: str = "openai/gpt-6.1-terra",
|
|
273
207
|
streaming_callback: StreamingCallbackT | None = None,
|
|
274
208
|
api_base_url: str | None = "https://openrouter.ai/api/v1",
|
|
275
209
|
generation_kwargs: dict[str, Any] | None = None,
|
|
@@ -347,100 +281,58 @@ class OpenRouterChatGenerator(OpenAIChatGenerator):
|
|
|
347
281
|
:returns:
|
|
348
282
|
The serialized component as a dictionary.
|
|
349
283
|
"""
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
# the __init__)
|
|
355
|
-
# it would be hard to maintain the compatibility as superclass changes
|
|
356
|
-
return default_to_dict(
|
|
357
|
-
self,
|
|
358
|
-
model=self.model,
|
|
359
|
-
streaming_callback=callback_name,
|
|
360
|
-
api_base_url=self.api_base_url,
|
|
361
|
-
generation_kwargs=self.generation_kwargs,
|
|
362
|
-
api_key=self.api_key.to_dict(),
|
|
363
|
-
tools=serialize_tools_or_toolset(self.tools),
|
|
364
|
-
extra_headers=self.extra_headers,
|
|
365
|
-
timeout=self.timeout,
|
|
366
|
-
max_retries=self.max_retries,
|
|
367
|
-
http_client_kwargs=self.http_client_kwargs,
|
|
368
|
-
)
|
|
369
|
-
|
|
370
|
-
def _prepare_api_call(
|
|
371
|
-
self,
|
|
372
|
-
*,
|
|
373
|
-
messages: list[ChatMessage],
|
|
374
|
-
streaming_callback: StreamingCallbackT | None = None,
|
|
375
|
-
generation_kwargs: dict[str, Any] | None = None,
|
|
376
|
-
tools: ToolsType | None = None,
|
|
377
|
-
tools_strict: bool | None = None,
|
|
378
|
-
) -> dict[str, Any]:
|
|
379
|
-
# update generation kwargs by merging with the generation kwargs passed to the run method
|
|
380
|
-
generation_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})}
|
|
381
|
-
extra_headers = {**(self.extra_headers or {})}
|
|
382
|
-
|
|
383
|
-
is_streaming = streaming_callback is not None
|
|
384
|
-
num_responses = generation_kwargs.pop("n", 1)
|
|
385
|
-
|
|
386
|
-
if is_streaming and num_responses > 1:
|
|
387
|
-
msg = "Cannot stream multiple responses, please set n=1."
|
|
388
|
-
raise ValueError(msg)
|
|
389
|
-
response_format = generation_kwargs.pop("response_format", None)
|
|
390
|
-
|
|
391
|
-
# adapt ChatMessage(s) to the format expected by the OpenAI API
|
|
392
|
-
openai_formatted_messages = [message.to_openai_dict_format() for message in messages]
|
|
393
|
-
|
|
394
|
-
# OpenRouter expects reasoning_details to be sent back in multi-turn conversations, but
|
|
395
|
-
# to_openai_dict_format() strips reasoning, so we re-inject it into the formatted message dicts.
|
|
396
|
-
for i, chat_msg in enumerate(messages):
|
|
397
|
-
if chat_msg.reasoning and chat_msg.reasoning.extra.get("reasoning_details"):
|
|
398
|
-
openai_formatted_messages[i]["reasoning_details"] = chat_msg.reasoning.extra["reasoning_details"]
|
|
399
|
-
|
|
400
|
-
flattened_tools = flatten_tools_or_toolsets(tools or self.tools)
|
|
401
|
-
tools_strict = tools_strict if tools_strict is not None else self.tools_strict
|
|
402
|
-
_check_duplicate_tool_names(flattened_tools)
|
|
403
|
-
|
|
404
|
-
openai_tools = {}
|
|
405
|
-
if flattened_tools:
|
|
406
|
-
tool_definitions = []
|
|
407
|
-
for t in flattened_tools:
|
|
408
|
-
function_spec = {**t.tool_spec}
|
|
409
|
-
if tools_strict:
|
|
410
|
-
function_spec["strict"] = True
|
|
411
|
-
function_spec["parameters"]["additionalProperties"] = False
|
|
412
|
-
tool_definitions.append({"type": "function", "function": function_spec})
|
|
413
|
-
openai_tools = {"tools": tool_definitions}
|
|
414
|
-
|
|
415
|
-
base_args = {
|
|
416
|
-
"model": self.model,
|
|
417
|
-
"messages": openai_formatted_messages,
|
|
418
|
-
"n": num_responses,
|
|
419
|
-
**openai_tools,
|
|
420
|
-
"extra_headers": {**extra_headers},
|
|
421
|
-
"extra_body": {**generation_kwargs},
|
|
284
|
+
data = super(OpenRouterChatGenerator, self).to_dict() # noqa: UP008
|
|
285
|
+
init_parameters = inspect.signature(type(self).__init__).parameters
|
|
286
|
+
data["init_parameters"] = {
|
|
287
|
+
key: value for key, value in data["init_parameters"].items() if key in init_parameters
|
|
422
288
|
}
|
|
289
|
+
data["init_parameters"]["extra_headers"] = self.extra_headers
|
|
290
|
+
return data
|
|
291
|
+
|
|
292
|
+
def _adapt_generation_kwargs(self, generation_kwargs: dict[str, Any]) -> dict[str, Any]:
|
|
293
|
+
"""Send OpenRouter generation parameters in the request body with custom headers."""
|
|
294
|
+
return {"extra_body": dict(generation_kwargs), "extra_headers": dict(self.extra_headers or {})}
|
|
295
|
+
|
|
296
|
+
def _convert_message_to_api_format(self, message: ChatMessage) -> dict[str, Any]:
|
|
297
|
+
"""Preserve reasoning details when sending messages back to OpenRouter."""
|
|
298
|
+
formatted = super(OpenRouterChatGenerator, self)._convert_message_to_api_format(message) # noqa: UP008
|
|
299
|
+
if message.reasoning and message.reasoning.extra.get("reasoning_details"):
|
|
300
|
+
formatted["reasoning_details"] = message.reasoning.extra["reasoning_details"]
|
|
301
|
+
return formatted
|
|
302
|
+
|
|
303
|
+
def _convert_chat_completion_to_chat_message(
|
|
304
|
+
self, completion: ChatCompletion | ParsedChatCompletion, choice: Choice
|
|
305
|
+
) -> ChatMessage:
|
|
306
|
+
"""Convert a completion while preserving OpenRouter reasoning content and details."""
|
|
307
|
+
message = super(OpenRouterChatGenerator, self)._convert_chat_completion_to_chat_message( # noqa: UP008
|
|
308
|
+
completion=completion, choice=choice
|
|
309
|
+
)
|
|
310
|
+
reasoning = _extract_reasoning(choice.message)
|
|
311
|
+
if reasoning is None:
|
|
312
|
+
return message
|
|
313
|
+
return ChatMessage.from_assistant(
|
|
314
|
+
text=message.text, tool_calls=message.tool_calls, meta=message.meta, reasoning=reasoning
|
|
315
|
+
)
|
|
423
316
|
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
final_args["response_format"] = response_format
|
|
439
|
-
return final_args
|
|
317
|
+
def _convert_streaming_chunks_to_chat_message(self, chunks: list[StreamingChunk]) -> ChatMessage:
|
|
318
|
+
"""Connect OpenRouter streaming chunks into a single ChatMessage, keeping the merged `reasoning_details`."""
|
|
319
|
+
message = super(OpenRouterChatGenerator, self)._convert_streaming_chunks_to_chat_message(chunks=chunks) # noqa: UP008
|
|
320
|
+
# OpenRouter needs reasoning details back in multi-turn conversations; core only joins the text.
|
|
321
|
+
details = [d for c in chunks if c.reasoning for d in c.reasoning.extra.get("reasoning_details", [])]
|
|
322
|
+
if not details:
|
|
323
|
+
return message
|
|
324
|
+
reasoning = ReasoningContent(
|
|
325
|
+
reasoning_text=message.reasoning.reasoning_text if message.reasoning else "",
|
|
326
|
+
extra={"reasoning_details": _merge_reasoning_details(details)},
|
|
327
|
+
)
|
|
328
|
+
return ChatMessage.from_assistant(
|
|
329
|
+
text=message.text, tool_calls=message.tool_calls, meta=message.meta, reasoning=reasoning
|
|
330
|
+
)
|
|
440
331
|
|
|
441
332
|
def _handle_stream_response(
|
|
442
333
|
self, chat_completion: Stream[ChatCompletionChunk], callback: SyncStreamingCallbackT
|
|
443
334
|
) -> list[ChatMessage]:
|
|
335
|
+
"""Handle OpenRouter streams that can emit multiple chunks per API delta."""
|
|
444
336
|
component_info = ComponentInfo.from_component(self)
|
|
445
337
|
chunks: list[StreamingChunk] = []
|
|
446
338
|
for chunk in chat_completion:
|
|
@@ -450,11 +342,12 @@ class OpenRouterChatGenerator(OpenAIChatGenerator):
|
|
|
450
342
|
):
|
|
451
343
|
chunks.append(streaming_chunk)
|
|
452
344
|
callback(streaming_chunk)
|
|
453
|
-
return [
|
|
345
|
+
return [self._convert_streaming_chunks_to_chat_message(chunks=chunks)]
|
|
454
346
|
|
|
455
347
|
async def _handle_async_stream_response(
|
|
456
348
|
self, chat_completion: AsyncStream[ChatCompletionChunk], callback: StreamingCallbackT
|
|
457
349
|
) -> list[ChatMessage]:
|
|
350
|
+
"""Handle async OpenRouter streams that can emit multiple chunks per API delta."""
|
|
458
351
|
component_info = ComponentInfo.from_component(self)
|
|
459
352
|
chunks: list[StreamingChunk] = []
|
|
460
353
|
try:
|
|
@@ -472,142 +365,4 @@ class OpenRouterChatGenerator(OpenAIChatGenerator):
|
|
|
472
365
|
# shield the close so the stream is released even though the task is being cancelled
|
|
473
366
|
await asyncio.shield(chat_completion.close())
|
|
474
367
|
raise
|
|
475
|
-
return [
|
|
476
|
-
|
|
477
|
-
@component.output_types(replies=list[ChatMessage])
|
|
478
|
-
def run(
|
|
479
|
-
self,
|
|
480
|
-
messages: list[ChatMessage] | str,
|
|
481
|
-
streaming_callback: StreamingCallbackT | None = None,
|
|
482
|
-
generation_kwargs: dict[str, Any] | None = None,
|
|
483
|
-
*,
|
|
484
|
-
tools: ToolsType | None = None,
|
|
485
|
-
tools_strict: bool | None = None,
|
|
486
|
-
) -> dict[str, list[ChatMessage]]:
|
|
487
|
-
"""
|
|
488
|
-
Invokes chat completion on the OpenRouter API.
|
|
489
|
-
|
|
490
|
-
:param messages:
|
|
491
|
-
A list of ChatMessage instances representing the input messages.
|
|
492
|
-
If a string is provided, it is converted to a list containing a ChatMessage with user role.
|
|
493
|
-
:param streaming_callback:
|
|
494
|
-
A callback function that is called when a new token is received from the stream.
|
|
495
|
-
:param generation_kwargs:
|
|
496
|
-
Additional keyword arguments for text generation. These are merged per key with the
|
|
497
|
-
`generation_kwargs` passed at initialization: keys provided here take precedence, keys set only
|
|
498
|
-
at initialization are kept.
|
|
499
|
-
For details on OpenRouter API parameters, see
|
|
500
|
-
[OpenRouter docs](https://openrouter.ai/docs/quickstart).
|
|
501
|
-
:param tools: A list of Tool and/or Toolset objects, or a single Toolset for which the model can prepare calls.
|
|
502
|
-
If set, it will override the `tools` parameter provided during initialization.
|
|
503
|
-
:param tools_strict:
|
|
504
|
-
Whether to enable strict schema adherence for tool calls.
|
|
505
|
-
|
|
506
|
-
:returns:
|
|
507
|
-
A dictionary with the following key:
|
|
508
|
-
- `replies`: A list containing the generated responses as ChatMessage instances.
|
|
509
|
-
"""
|
|
510
|
-
messages = _normalize_messages(messages)
|
|
511
|
-
self.warm_up()
|
|
512
|
-
|
|
513
|
-
if len(messages) == 0:
|
|
514
|
-
return {"replies": []}
|
|
515
|
-
|
|
516
|
-
streaming_callback = select_streaming_callback(
|
|
517
|
-
init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=False
|
|
518
|
-
)
|
|
519
|
-
|
|
520
|
-
api_args = self._prepare_api_call(
|
|
521
|
-
messages=messages,
|
|
522
|
-
streaming_callback=streaming_callback,
|
|
523
|
-
generation_kwargs=generation_kwargs,
|
|
524
|
-
tools=tools,
|
|
525
|
-
tools_strict=tools_strict,
|
|
526
|
-
)
|
|
527
|
-
openai_endpoint = api_args.pop("openai_endpoint")
|
|
528
|
-
# with haystack-ai >= 3.0 the client is Optional and built by warm_up above
|
|
529
|
-
chat_completion = getattr(self.client.chat.completions, openai_endpoint)(**api_args) # type: ignore[union-attr]
|
|
530
|
-
|
|
531
|
-
if streaming_callback is not None:
|
|
532
|
-
completions = self._handle_stream_response(chat_completion, streaming_callback)
|
|
533
|
-
else:
|
|
534
|
-
assert isinstance(chat_completion, ChatCompletion), "Unexpected response type for non-streaming request."
|
|
535
|
-
completions = [
|
|
536
|
-
_convert_openrouter_completion_to_chat_message(chat_completion, choice)
|
|
537
|
-
for choice in chat_completion.choices
|
|
538
|
-
]
|
|
539
|
-
|
|
540
|
-
for message in completions:
|
|
541
|
-
_check_finish_reason(message.meta)
|
|
542
|
-
|
|
543
|
-
return {"replies": completions}
|
|
544
|
-
|
|
545
|
-
@component.output_types(replies=list[ChatMessage])
|
|
546
|
-
async def run_async(
|
|
547
|
-
self,
|
|
548
|
-
messages: list[ChatMessage] | str,
|
|
549
|
-
streaming_callback: StreamingCallbackT | None = None,
|
|
550
|
-
generation_kwargs: dict[str, Any] | None = None,
|
|
551
|
-
*,
|
|
552
|
-
tools: ToolsType | None = None,
|
|
553
|
-
tools_strict: bool | None = None,
|
|
554
|
-
) -> dict[str, list[ChatMessage]]:
|
|
555
|
-
"""
|
|
556
|
-
Asynchronously invokes chat completion on the OpenRouter API.
|
|
557
|
-
|
|
558
|
-
:param messages:
|
|
559
|
-
A list of ChatMessage instances representing the input messages.
|
|
560
|
-
If a string is provided, it is converted to a list containing a ChatMessage with user role.
|
|
561
|
-
:param streaming_callback:
|
|
562
|
-
A callback function that is called when a new token is received from the stream.
|
|
563
|
-
Must be a coroutine.
|
|
564
|
-
:param generation_kwargs:
|
|
565
|
-
Additional keyword arguments for text generation. These are merged per key with the
|
|
566
|
-
`generation_kwargs` passed at initialization: keys provided here take precedence, keys set only
|
|
567
|
-
at initialization are kept.
|
|
568
|
-
:param tools: A list of Tool and/or Toolset objects, or a single Toolset.
|
|
569
|
-
:param tools_strict:
|
|
570
|
-
Whether to enable strict schema adherence for tool calls.
|
|
571
|
-
|
|
572
|
-
:returns:
|
|
573
|
-
A dictionary with the following key:
|
|
574
|
-
- `replies`: A list containing the generated responses as ChatMessage instances.
|
|
575
|
-
"""
|
|
576
|
-
messages = _normalize_messages(messages)
|
|
577
|
-
if hasattr(self, "warm_up_async"):
|
|
578
|
-
# haystack-ai >= 3.0 initializes the async client on the running event loop
|
|
579
|
-
await self.warm_up_async()
|
|
580
|
-
else:
|
|
581
|
-
self.warm_up()
|
|
582
|
-
|
|
583
|
-
if len(messages) == 0:
|
|
584
|
-
return {"replies": []}
|
|
585
|
-
|
|
586
|
-
streaming_callback = select_streaming_callback(
|
|
587
|
-
init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=True
|
|
588
|
-
)
|
|
589
|
-
|
|
590
|
-
api_args = self._prepare_api_call(
|
|
591
|
-
messages=messages,
|
|
592
|
-
streaming_callback=streaming_callback,
|
|
593
|
-
generation_kwargs=generation_kwargs,
|
|
594
|
-
tools=tools,
|
|
595
|
-
tools_strict=tools_strict,
|
|
596
|
-
)
|
|
597
|
-
openai_endpoint = api_args.pop("openai_endpoint")
|
|
598
|
-
# with haystack-ai >= 3.0 the client is Optional and built by warm_up above
|
|
599
|
-
chat_completion = await getattr(self.async_client.chat.completions, openai_endpoint)(**api_args) # type: ignore[union-attr]
|
|
600
|
-
|
|
601
|
-
if streaming_callback is not None:
|
|
602
|
-
completions = await self._handle_async_stream_response(chat_completion, streaming_callback)
|
|
603
|
-
else:
|
|
604
|
-
assert isinstance(chat_completion, ChatCompletion), "Unexpected response type for non-streaming request."
|
|
605
|
-
completions = [
|
|
606
|
-
_convert_openrouter_completion_to_chat_message(chat_completion, choice)
|
|
607
|
-
for choice in chat_completion.choices
|
|
608
|
-
]
|
|
609
|
-
|
|
610
|
-
for message in completions:
|
|
611
|
-
_check_finish_reason(message.meta)
|
|
612
|
-
|
|
613
|
-
return {"replies": completions}
|
|
368
|
+
return [self._convert_streaming_chunks_to_chat_message(chunks=chunks)]
|