openrouter-haystack 1.3.0__tar.gz → 2.1.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-1.3.0 → openrouter_haystack-2.1.0}/CHANGELOG.md +39 -0
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/PKG-INFO +4 -4
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/examples/openrouter_with_tools_example.py +6 -12
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/pyproject.toml +4 -5
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/src/haystack_integrations/components/generators/openrouter/chat/chat_generator.py +51 -296
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/tests/test_openrouter_chat_generator.py +21 -259
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/tests/test_openrouter_chat_generator_async.py +5 -182
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/.gitignore +0 -0
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/LICENSE.txt +0 -0
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/README.md +0 -0
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/examples/openrouter_with_structured_outputs.py +0 -0
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/pydoc/config_docusaurus.yml +0 -0
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/src/haystack_integrations/components/generators/openrouter/__init__.py +0 -0
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/src/haystack_integrations/components/generators/openrouter/chat/__init__.py +0 -0
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/src/haystack_integrations/components/generators/py.typed +0 -0
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/tests/__init__.py +0 -0
- {openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/tests/conftest.py +0 -0
|
@@ -1,5 +1,44 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [integrations/openrouter-v2.0.0] - 2026-10-16
|
|
4
|
+
|
|
5
|
+
### 🧪 Testing
|
|
6
|
+
|
|
7
|
+
- Test compatible integrations with Python 3.15; update pyproject (#4104)
|
|
8
|
+
|
|
9
|
+
### 🧹 Chores
|
|
10
|
+
|
|
11
|
+
- Replace ToolInvoker with Agent in tests, examples and docstrings (#4108)
|
|
12
|
+
- [**breaking**] Drop Python 3.10 support (#4105)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
## [integrations/openrouter-v1.3.0] - 2026-10-07
|
|
16
|
+
|
|
17
|
+
### 🚀 Features
|
|
18
|
+
|
|
19
|
+
- *(openrouter)* Add reasoning support for streaming responses (#4063)
|
|
20
|
+
|
|
21
|
+
### 🐛 Bug Fixes
|
|
22
|
+
|
|
23
|
+
- Fix new issues raised by ruff 0.16.0 (#3670)
|
|
24
|
+
- Standardize license files (#3771)
|
|
25
|
+
|
|
26
|
+
### 🧪 Testing
|
|
27
|
+
|
|
28
|
+
- Fix tests for integrations that inherit from the OpenAIChatGenerator (#3583)
|
|
29
|
+
- Make OpenRouter tests declare max_tokens + refactor (#3730)
|
|
30
|
+
- Fix tests for openai>=3.0.0 (#3801)
|
|
31
|
+
|
|
32
|
+
### ⚙️ CI
|
|
33
|
+
|
|
34
|
+
- Improve changelog generation; fix existing changelogs (#3883)
|
|
35
|
+
|
|
36
|
+
### 🧹 Chores
|
|
37
|
+
|
|
38
|
+
- Re-standardize READMEs (#3768)
|
|
39
|
+
- Clarify how generation_kwargs passed in run are handled (#3805)
|
|
40
|
+
|
|
41
|
+
|
|
3
42
|
## [integrations/openrouter-v1.2.0] - 2026-07-06
|
|
4
43
|
|
|
5
44
|
### 🐛 Bug Fixes
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: openrouter-haystack
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 2.1.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
|
|
@@ -10,15 +10,15 @@ License-File: LICENSE.txt
|
|
|
10
10
|
Classifier: Development Status :: 4 - Beta
|
|
11
11
|
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
12
|
Classifier: Programming Language :: Python
|
|
13
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
14
13
|
Classifier: Programming Language :: Python :: 3.11
|
|
15
14
|
Classifier: Programming Language :: Python :: 3.12
|
|
16
15
|
Classifier: Programming Language :: Python :: 3.13
|
|
17
16
|
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
18
18
|
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
19
19
|
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
20
|
-
Requires-Python: >=3.
|
|
21
|
-
Requires-Dist: haystack-ai>=
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: haystack-ai>=3.5.0
|
|
22
22
|
Description-Content-Type: text/markdown
|
|
23
23
|
|
|
24
24
|
# openrouter-haystack
|
{openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/examples/openrouter_with_tools_example.py
RENAMED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
# To run this example, you will need to
|
|
8
8
|
# set `OPENROUTER_API_KEY` environment variable
|
|
9
9
|
|
|
10
|
-
from haystack.components.
|
|
10
|
+
from haystack.components.agents import Agent
|
|
11
11
|
from haystack.dataclasses import ChatMessage
|
|
12
12
|
from haystack.tools import Tool
|
|
13
13
|
|
|
@@ -29,9 +29,6 @@ weather_tool = Tool(
|
|
|
29
29
|
function=weather,
|
|
30
30
|
)
|
|
31
31
|
|
|
32
|
-
# Create a tool invoker with the weather tool
|
|
33
|
-
tool_invoker = ToolInvoker(tools=[weather_tool])
|
|
34
|
-
|
|
35
32
|
# We can setup model routing by setting the `model` parameter to `openrouter/auto`
|
|
36
33
|
# and providing a list of models to route to.
|
|
37
34
|
client = OpenRouterChatGenerator(
|
|
@@ -40,13 +37,10 @@ client = OpenRouterChatGenerator(
|
|
|
40
37
|
"models": ["openai/gpt-4o-mini", "anthropic/claude-3-haiku"],
|
|
41
38
|
},
|
|
42
39
|
)
|
|
43
|
-
messages = [ChatMessage.from_user("What's the weather in Tokyo?")]
|
|
44
|
-
|
|
45
|
-
response = client.run(messages=messages, tools=[weather_tool])["replies"]
|
|
46
40
|
|
|
47
|
-
|
|
41
|
+
# The Agent calls the tool and feeds the result back to the model
|
|
42
|
+
agent = Agent(chat_generator=client, tools=[weather_tool])
|
|
43
|
+
result = agent.run(messages=[ChatMessage.from_user("What's the weather in Tokyo?")])
|
|
48
44
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
tool_messages = tool_invoker.run(messages=response)["tool_messages"]
|
|
52
|
-
print(f"tool messages: {tool_messages}")
|
|
45
|
+
print(f"messages: {result['messages']}\n")
|
|
46
|
+
print(f"assistant final answer: {result['last_message'].text}")
|
|
@@ -7,7 +7,7 @@ name = "openrouter-haystack"
|
|
|
7
7
|
dynamic = ["version"]
|
|
8
8
|
description = ''
|
|
9
9
|
readme = "README.md"
|
|
10
|
-
requires-python = ">=3.
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
11
|
license = "Apache-2.0"
|
|
12
12
|
keywords = []
|
|
13
13
|
authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }]
|
|
@@ -15,15 +15,15 @@ classifiers = [
|
|
|
15
15
|
"License :: OSI Approved :: Apache Software License",
|
|
16
16
|
"Development Status :: 4 - Beta",
|
|
17
17
|
"Programming Language :: Python",
|
|
18
|
-
"Programming Language :: Python :: 3.10",
|
|
19
18
|
"Programming Language :: Python :: 3.11",
|
|
20
19
|
"Programming Language :: Python :: 3.12",
|
|
21
20
|
"Programming Language :: Python :: 3.13",
|
|
22
21
|
"Programming Language :: Python :: 3.14",
|
|
22
|
+
"Programming Language :: Python :: 3.15",
|
|
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
|
"""
|
|
@@ -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)]
|
{openrouter_haystack-1.3.0 → openrouter_haystack-2.1.0}/tests/test_openrouter_chat_generator.py
RENAMED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
1
5
|
import json
|
|
2
6
|
import os
|
|
3
|
-
from datetime import datetime
|
|
4
7
|
from types import SimpleNamespace
|
|
5
|
-
from unittest.mock import Mock
|
|
8
|
+
from unittest.mock import Mock
|
|
6
9
|
|
|
7
10
|
import pytest
|
|
8
|
-
import pytz
|
|
9
11
|
from haystack import Pipeline
|
|
10
12
|
from haystack.components.generators.utils import print_streaming_chunk
|
|
11
13
|
from haystack.dataclasses import ChatMessage, ChatRole, ReasoningContent, StreamingChunk, ToolCall
|
|
@@ -21,7 +23,6 @@ from pydantic import BaseModel
|
|
|
21
23
|
|
|
22
24
|
from haystack_integrations.components.generators.openrouter.chat.chat_generator import (
|
|
23
25
|
OpenRouterChatGenerator,
|
|
24
|
-
_convert_openrouter_completion_to_chat_message,
|
|
25
26
|
_extract_reasoning,
|
|
26
27
|
_merge_reasoning_details,
|
|
27
28
|
)
|
|
@@ -43,11 +44,6 @@ class CalendarEvent(BaseModel):
|
|
|
43
44
|
event_location: str
|
|
44
45
|
|
|
45
46
|
|
|
46
|
-
@pytest.fixture
|
|
47
|
-
def calendar_event_model():
|
|
48
|
-
return CalendarEvent
|
|
49
|
-
|
|
50
|
-
|
|
51
47
|
class CollectorCallback:
|
|
52
48
|
"""
|
|
53
49
|
Callback to collect streaming chunks for testing purposes.
|
|
@@ -86,32 +82,6 @@ def tools():
|
|
|
86
82
|
return [tool]
|
|
87
83
|
|
|
88
84
|
|
|
89
|
-
@pytest.fixture
|
|
90
|
-
def mock_chat_completion():
|
|
91
|
-
"""
|
|
92
|
-
Mock the OpenAI API completion response and reuse it for tests
|
|
93
|
-
"""
|
|
94
|
-
with patch("openai.resources.chat.completions.Completions.create") as mock_chat_completion_create:
|
|
95
|
-
completion = ChatCompletion(
|
|
96
|
-
id="foo",
|
|
97
|
-
model="openai/gpt-5-mini",
|
|
98
|
-
object="chat.completion",
|
|
99
|
-
choices=[
|
|
100
|
-
Choice(
|
|
101
|
-
finish_reason="stop",
|
|
102
|
-
logprobs=None,
|
|
103
|
-
index=0,
|
|
104
|
-
message=ChatCompletionMessage(content="Hello world!", role="assistant"),
|
|
105
|
-
)
|
|
106
|
-
],
|
|
107
|
-
created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()),
|
|
108
|
-
usage={"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97},
|
|
109
|
-
)
|
|
110
|
-
|
|
111
|
-
mock_chat_completion_create.return_value = completion
|
|
112
|
-
yield mock_chat_completion_create
|
|
113
|
-
|
|
114
|
-
|
|
115
85
|
class TestOpenRouterChatGeneratorUnit:
|
|
116
86
|
def test_init_default(self, monkeypatch):
|
|
117
87
|
monkeypatch.setenv("OPENROUTER_API_KEY", "test-api-key")
|
|
@@ -122,19 +92,6 @@ class TestOpenRouterChatGeneratorUnit:
|
|
|
122
92
|
assert component.streaming_callback is None
|
|
123
93
|
assert not component.generation_kwargs
|
|
124
94
|
|
|
125
|
-
def test_warm_up(self, monkeypatch):
|
|
126
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "test-api-key")
|
|
127
|
-
component = OpenRouterChatGenerator()
|
|
128
|
-
component.warm_up() # with haystack-ai >= 3.0 the client is created during warm-up
|
|
129
|
-
assert component.client.api_key == "test-api-key"
|
|
130
|
-
|
|
131
|
-
def test_init_fail_wo_api_key(self, monkeypatch):
|
|
132
|
-
monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)
|
|
133
|
-
with pytest.raises(ValueError, match=r"None of the .* environment variables are set"):
|
|
134
|
-
# haystack-ai 2.x raises at init; haystack-ai >= 3.0 raises when the client is created in warm_up
|
|
135
|
-
component = OpenRouterChatGenerator()
|
|
136
|
-
component.warm_up()
|
|
137
|
-
|
|
138
95
|
def test_init_with_parameters(self):
|
|
139
96
|
component = OpenRouterChatGenerator(
|
|
140
97
|
api_key=Secret.from_token("test-api-key"),
|
|
@@ -242,70 +199,15 @@ class TestOpenRouterChatGeneratorUnit:
|
|
|
242
199
|
assert component.timeout == 10
|
|
243
200
|
assert component.max_retries == 10
|
|
244
201
|
|
|
245
|
-
def
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
assert isinstance(response, dict)
|
|
252
|
-
assert "replies" in response
|
|
253
|
-
assert isinstance(response["replies"], list)
|
|
254
|
-
assert len(response["replies"]) == 1
|
|
255
|
-
assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
|
|
256
|
-
|
|
257
|
-
def test_run_with_params(self, chat_messages, mock_chat_completion, monkeypatch):
|
|
258
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
259
|
-
component = OpenRouterChatGenerator(generation_kwargs={"max_tokens": 10, "temperature": 0.5})
|
|
260
|
-
response = component.run(chat_messages)
|
|
261
|
-
|
|
262
|
-
# check that the component calls the OpenAI API with the correct parameters
|
|
263
|
-
# for OpenRouter, these are passed in the extra_body parameter
|
|
264
|
-
_, kwargs = mock_chat_completion.call_args
|
|
265
|
-
assert kwargs["extra_body"]["max_tokens"] == 10
|
|
266
|
-
assert kwargs["extra_body"]["temperature"] == 0.5
|
|
267
|
-
# check that the component returns the correct response
|
|
268
|
-
assert isinstance(response, dict)
|
|
269
|
-
assert "replies" in response
|
|
270
|
-
assert isinstance(response["replies"], list)
|
|
271
|
-
assert len(response["replies"]) == 1
|
|
272
|
-
assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
|
|
273
|
-
|
|
274
|
-
def test_run_with_generation_kwargs(self, chat_messages, mock_chat_completion, monkeypatch):
|
|
275
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
276
|
-
component = OpenRouterChatGenerator(generation_kwargs={"max_tokens": 10, "temperature": 0.5})
|
|
277
|
-
component.run(chat_messages, generation_kwargs={"temperature": 0.9})
|
|
278
|
-
|
|
279
|
-
_, kwargs = mock_chat_completion.call_args
|
|
280
|
-
assert kwargs["extra_body"]["max_tokens"] == 10
|
|
281
|
-
assert kwargs["extra_body"]["temperature"] == 0.9
|
|
282
|
-
|
|
283
|
-
def test_prepare_api_call_with_tools_strict(self, chat_messages, tools, monkeypatch):
|
|
284
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
285
|
-
component = OpenRouterChatGenerator(tools=tools)
|
|
286
|
-
api_args = component._prepare_api_call(messages=chat_messages, tools_strict=True)
|
|
287
|
-
|
|
288
|
-
assert api_args["tools"][0]["type"] == "function"
|
|
289
|
-
function_spec = api_args["tools"][0]["function"]
|
|
290
|
-
assert function_spec["name"] == "weather"
|
|
291
|
-
assert function_spec["strict"] is True
|
|
292
|
-
assert function_spec["parameters"]["additionalProperties"] is False
|
|
293
|
-
|
|
294
|
-
def test_prepare_api_call_raises_when_streaming_with_multiple_responses(self, chat_messages, monkeypatch):
|
|
295
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
296
|
-
component = OpenRouterChatGenerator(generation_kwargs={"n": 2})
|
|
297
|
-
with pytest.raises(ValueError, match="Cannot stream multiple responses"):
|
|
298
|
-
component._prepare_api_call(messages=chat_messages, streaming_callback=print_streaming_chunk)
|
|
299
|
-
|
|
300
|
-
def test_prepare_api_call_with_response_format_and_streaming(self, chat_messages, monkeypatch):
|
|
301
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
302
|
-
response_format = {"type": "json_schema", "json_schema": {"name": "Foo", "schema": {"type": "object"}}}
|
|
303
|
-
component = OpenRouterChatGenerator(generation_kwargs={"response_format": response_format})
|
|
304
|
-
api_args = component._prepare_api_call(messages=chat_messages, streaming_callback=print_streaming_chunk)
|
|
202
|
+
def test_prepare_api_call_with_generation_kwargs(self, chat_messages):
|
|
203
|
+
component = OpenRouterChatGenerator(
|
|
204
|
+
generation_kwargs={"max_tokens": 10, "temperature": 0.5},
|
|
205
|
+
extra_headers={"HTTP-Referer": "https://example.com", "X-Title": "Test application"},
|
|
206
|
+
)
|
|
207
|
+
kwargs = component._prepare_api_call(messages=chat_messages, generation_kwargs={"temperature": 0.9})
|
|
305
208
|
|
|
306
|
-
assert
|
|
307
|
-
assert
|
|
308
|
-
assert api_args["response_format"] == response_format
|
|
209
|
+
assert kwargs["extra_body"] == {"max_tokens": 10, "temperature": 0.9}
|
|
210
|
+
assert kwargs["extra_headers"] == {"HTTP-Referer": "https://example.com", "X-Title": "Test application"}
|
|
309
211
|
|
|
310
212
|
def test_serde_in_pipeline(self, monkeypatch):
|
|
311
213
|
monkeypatch.setenv("OPENROUTER_API_KEY", "test-key")
|
|
@@ -531,7 +433,7 @@ class TestOpenRouterChatGeneratorIntegration:
|
|
|
531
433
|
assert "france" in msg["country"].lower(), f"Expected 'France' in country field, got: {msg['country']}"
|
|
532
434
|
assert message.meta["finish_reason"] == "stop"
|
|
533
435
|
|
|
534
|
-
def test_live_run_with_response_format_pydantic_model(self
|
|
436
|
+
def test_live_run_with_response_format_pydantic_model(self):
|
|
535
437
|
# Use a more explicit prompt that emphasizes JSON structure requirement
|
|
536
438
|
chat_messages = [
|
|
537
439
|
ChatMessage.from_user(
|
|
@@ -541,7 +443,7 @@ class TestOpenRouterChatGeneratorIntegration:
|
|
|
541
443
|
)
|
|
542
444
|
]
|
|
543
445
|
component = OpenRouterChatGenerator(
|
|
544
|
-
model="openai/gpt-5-mini", generation_kwargs={"response_format":
|
|
446
|
+
model="openai/gpt-5-mini", generation_kwargs={"response_format": CalendarEvent, "max_tokens": 1000}
|
|
545
447
|
)
|
|
546
448
|
results = component.run(chat_messages)
|
|
547
449
|
assert len(results["replies"]) == 1
|
|
@@ -1043,11 +945,11 @@ class TestReasoningSupport:
|
|
|
1043
945
|
),
|
|
1044
946
|
)
|
|
1045
947
|
],
|
|
1046
|
-
created=
|
|
948
|
+
created=1750162525,
|
|
1047
949
|
usage={"prompt_tokens": 30, "completion_tokens": 20, "total_tokens": 50},
|
|
1048
950
|
)
|
|
1049
951
|
|
|
1050
|
-
result =
|
|
952
|
+
result = OpenRouterChatGenerator()._convert_chat_completion_to_chat_message(completion, completion.choices[0])
|
|
1051
953
|
assert result.text is None
|
|
1052
954
|
assert result.reasoning is not None
|
|
1053
955
|
assert result.reasoning.reasoning_text == "I need to check the weather."
|
|
@@ -1074,11 +976,11 @@ class TestReasoningSupport:
|
|
|
1074
976
|
),
|
|
1075
977
|
)
|
|
1076
978
|
],
|
|
1077
|
-
created=
|
|
979
|
+
created=1750162525,
|
|
1078
980
|
usage={"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97},
|
|
1079
981
|
)
|
|
1080
982
|
|
|
1081
|
-
result =
|
|
983
|
+
result = OpenRouterChatGenerator()._convert_chat_completion_to_chat_message(completion, completion.choices[0])
|
|
1082
984
|
assert result.text == "The answer is 42."
|
|
1083
985
|
assert result.reasoning is not None
|
|
1084
986
|
assert result.reasoning.reasoning_text == "Let me think about this..."
|
|
@@ -1101,89 +1003,14 @@ class TestReasoningSupport:
|
|
|
1101
1003
|
message=ChatCompletionMessage(content="Hello!", role="assistant"),
|
|
1102
1004
|
)
|
|
1103
1005
|
],
|
|
1104
|
-
created=
|
|
1006
|
+
created=1750162525,
|
|
1105
1007
|
usage={"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
|
|
1106
1008
|
)
|
|
1107
1009
|
|
|
1108
|
-
result =
|
|
1010
|
+
result = OpenRouterChatGenerator()._convert_chat_completion_to_chat_message(completion, completion.choices[0])
|
|
1109
1011
|
assert result.text == "Hello!"
|
|
1110
1012
|
assert result.reasoning is None
|
|
1111
1013
|
|
|
1112
|
-
def test_run_with_reasoning(self, monkeypatch):
|
|
1113
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
1114
|
-
|
|
1115
|
-
with patch("openai.resources.chat.completions.Completions.create") as mock_create:
|
|
1116
|
-
completion = ChatCompletion(
|
|
1117
|
-
id="test-run-reasoning",
|
|
1118
|
-
model="deepseek/deepseek-r1",
|
|
1119
|
-
object="chat.completion",
|
|
1120
|
-
choices=[
|
|
1121
|
-
Choice(
|
|
1122
|
-
finish_reason="stop",
|
|
1123
|
-
logprobs=None,
|
|
1124
|
-
index=0,
|
|
1125
|
-
message=ChatCompletionMessage(
|
|
1126
|
-
content="Paris is the capital of France.",
|
|
1127
|
-
role="assistant",
|
|
1128
|
-
reasoning="The user asked about capitals. France's capital is Paris.",
|
|
1129
|
-
reasoning_details=[
|
|
1130
|
-
{
|
|
1131
|
-
"type": "reasoning.text",
|
|
1132
|
-
"text": "The user asked about capitals. France's capital is Paris.",
|
|
1133
|
-
}
|
|
1134
|
-
],
|
|
1135
|
-
),
|
|
1136
|
-
)
|
|
1137
|
-
],
|
|
1138
|
-
created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()),
|
|
1139
|
-
usage={"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97},
|
|
1140
|
-
)
|
|
1141
|
-
mock_create.return_value = completion
|
|
1142
|
-
|
|
1143
|
-
component = OpenRouterChatGenerator(
|
|
1144
|
-
model="deepseek/deepseek-r1",
|
|
1145
|
-
generation_kwargs={"reasoning": {"effort": "high"}},
|
|
1146
|
-
)
|
|
1147
|
-
response = component.run([ChatMessage.from_user("What's the capital of France?")])
|
|
1148
|
-
|
|
1149
|
-
assert len(response["replies"]) == 1
|
|
1150
|
-
reply = response["replies"][0]
|
|
1151
|
-
assert reply.text == "Paris is the capital of France."
|
|
1152
|
-
assert reply.reasoning is not None
|
|
1153
|
-
assert "capitals" in reply.reasoning.reasoning_text
|
|
1154
|
-
assert reply.reasoning.extra["reasoning_details"][0]["type"] == "reasoning.text"
|
|
1155
|
-
|
|
1156
|
-
def test_run_with_string_input(self, monkeypatch):
|
|
1157
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
1158
|
-
|
|
1159
|
-
with patch("openai.resources.chat.completions.Completions.create") as mock_create:
|
|
1160
|
-
completion = ChatCompletion(
|
|
1161
|
-
id="test-string-input",
|
|
1162
|
-
model="openai/gpt-5-mini",
|
|
1163
|
-
object="chat.completion",
|
|
1164
|
-
choices=[
|
|
1165
|
-
Choice(
|
|
1166
|
-
finish_reason="stop",
|
|
1167
|
-
logprobs=None,
|
|
1168
|
-
index=0,
|
|
1169
|
-
message=ChatCompletionMessage(content="Paris.", role="assistant"),
|
|
1170
|
-
)
|
|
1171
|
-
],
|
|
1172
|
-
created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()),
|
|
1173
|
-
usage={"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
|
|
1174
|
-
)
|
|
1175
|
-
mock_create.return_value = completion
|
|
1176
|
-
|
|
1177
|
-
component = OpenRouterChatGenerator()
|
|
1178
|
-
response = component.run("What's the capital of France?")
|
|
1179
|
-
|
|
1180
|
-
# the backend should receive exactly one user message
|
|
1181
|
-
_, kwargs = mock_create.call_args
|
|
1182
|
-
assert kwargs["messages"] == [{"role": "user", "content": "What's the capital of France?"}]
|
|
1183
|
-
|
|
1184
|
-
assert len(response["replies"]) == 1
|
|
1185
|
-
assert response["replies"][0].text == "Paris."
|
|
1186
|
-
|
|
1187
1014
|
def test_handle_stream_response_with_reasoning(self):
|
|
1188
1015
|
# mirrors OpenRouter's stream shape: `role` on every chunk, reasoning in both `reasoning` and
|
|
1189
1016
|
# `reasoning_details`, and the signature arriving in a separate final fragment
|
|
@@ -1402,68 +1229,3 @@ class TestReasoningSupport:
|
|
|
1402
1229
|
assert formatted[1]["reasoning_details"] == [{"type": "reasoning.text", "text": "Step by step analysis..."}]
|
|
1403
1230
|
assert "reasoning_details" not in formatted[0]
|
|
1404
1231
|
assert "reasoning_details" not in formatted[2]
|
|
1405
|
-
|
|
1406
|
-
def test_run_empty_messages(self, monkeypatch):
|
|
1407
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
1408
|
-
component = OpenRouterChatGenerator()
|
|
1409
|
-
response = component.run([])
|
|
1410
|
-
assert response == {"replies": []}
|
|
1411
|
-
|
|
1412
|
-
def test_convert_completion_with_logprobs(self):
|
|
1413
|
-
completion = ChatCompletion(
|
|
1414
|
-
id="test-logprobs",
|
|
1415
|
-
model="openai/gpt-5-mini",
|
|
1416
|
-
object="chat.completion",
|
|
1417
|
-
choices=[
|
|
1418
|
-
Choice(
|
|
1419
|
-
finish_reason="stop",
|
|
1420
|
-
logprobs={
|
|
1421
|
-
"content": [
|
|
1422
|
-
{"token": "Hello", "logprob": -0.5, "top_logprobs": [], "bytes": [72, 101, 108, 108, 111]}
|
|
1423
|
-
]
|
|
1424
|
-
},
|
|
1425
|
-
index=0,
|
|
1426
|
-
message=ChatCompletionMessage(content="Hello!", role="assistant"),
|
|
1427
|
-
)
|
|
1428
|
-
],
|
|
1429
|
-
created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()),
|
|
1430
|
-
usage={"prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10},
|
|
1431
|
-
)
|
|
1432
|
-
result = _convert_openrouter_completion_to_chat_message(completion, completion.choices[0])
|
|
1433
|
-
assert result.text == "Hello!"
|
|
1434
|
-
assert "logprobs" in result.meta
|
|
1435
|
-
|
|
1436
|
-
def test_convert_completion_malformed_tool_call_json(self):
|
|
1437
|
-
completion = ChatCompletion(
|
|
1438
|
-
id="test-bad-json",
|
|
1439
|
-
model="openai/gpt-5-mini",
|
|
1440
|
-
object="chat.completion",
|
|
1441
|
-
choices=[
|
|
1442
|
-
Choice(
|
|
1443
|
-
finish_reason="tool_calls",
|
|
1444
|
-
logprobs=None,
|
|
1445
|
-
index=0,
|
|
1446
|
-
message=ChatCompletionMessage(
|
|
1447
|
-
content=None,
|
|
1448
|
-
role="assistant",
|
|
1449
|
-
tool_calls=[
|
|
1450
|
-
{
|
|
1451
|
-
"id": "call_bad",
|
|
1452
|
-
"type": "function",
|
|
1453
|
-
"function": {"name": "weather", "arguments": "{invalid json}"},
|
|
1454
|
-
},
|
|
1455
|
-
{
|
|
1456
|
-
"id": "call_good",
|
|
1457
|
-
"type": "function",
|
|
1458
|
-
"function": {"name": "weather", "arguments": '{"city": "Paris"}'},
|
|
1459
|
-
},
|
|
1460
|
-
],
|
|
1461
|
-
),
|
|
1462
|
-
)
|
|
1463
|
-
],
|
|
1464
|
-
created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()),
|
|
1465
|
-
usage={"prompt_tokens": 10, "completion_tokens": 15, "total_tokens": 25},
|
|
1466
|
-
)
|
|
1467
|
-
result = _convert_openrouter_completion_to_chat_message(completion, completion.choices[0])
|
|
1468
|
-
assert len(result.tool_calls) == 1
|
|
1469
|
-
assert result.tool_calls[0].id == "call_good"
|
|
@@ -1,18 +1,18 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
1
5
|
import os
|
|
2
|
-
from datetime import datetime
|
|
3
6
|
from unittest.mock import AsyncMock, patch
|
|
4
7
|
|
|
5
8
|
import pytest
|
|
6
|
-
import pytz
|
|
7
9
|
from haystack.dataclasses import (
|
|
8
10
|
ChatMessage,
|
|
9
11
|
ChatRole,
|
|
10
12
|
StreamingChunk,
|
|
11
13
|
)
|
|
12
14
|
from haystack.tools import Tool, Toolset
|
|
13
|
-
from openai import
|
|
14
|
-
from openai.types.chat import ChatCompletion, ChatCompletionChunk, ChatCompletionMessage
|
|
15
|
-
from openai.types.chat.chat_completion import Choice
|
|
15
|
+
from openai.types.chat import ChatCompletionChunk
|
|
16
16
|
from openai.types.chat.chat_completion_chunk import Choice as ChoiceChunk
|
|
17
17
|
from openai.types.chat.chat_completion_chunk import ChoiceDelta
|
|
18
18
|
|
|
@@ -21,14 +21,6 @@ from haystack_integrations.components.generators.openrouter.chat.chat_generator
|
|
|
21
21
|
)
|
|
22
22
|
|
|
23
23
|
|
|
24
|
-
@pytest.fixture
|
|
25
|
-
def chat_messages():
|
|
26
|
-
return [
|
|
27
|
-
ChatMessage.from_system("You are a helpful assistant"),
|
|
28
|
-
ChatMessage.from_user("What's the capital of France"),
|
|
29
|
-
]
|
|
30
|
-
|
|
31
|
-
|
|
32
24
|
def weather(city: str):
|
|
33
25
|
"""Get weather for a given city."""
|
|
34
26
|
return f"The weather in {city} is sunny and 32°C"
|
|
@@ -51,137 +43,8 @@ def tools():
|
|
|
51
43
|
return [tool]
|
|
52
44
|
|
|
53
45
|
|
|
54
|
-
@pytest.fixture
|
|
55
|
-
def mock_async_chat_completion():
|
|
56
|
-
"""
|
|
57
|
-
Mock the Async OpenAI API completion response and reuse it for async tests
|
|
58
|
-
"""
|
|
59
|
-
with patch(
|
|
60
|
-
"openai.resources.chat.completions.AsyncCompletions.create",
|
|
61
|
-
new_callable=AsyncMock,
|
|
62
|
-
) as mock_chat_completion_create:
|
|
63
|
-
completion = ChatCompletion(
|
|
64
|
-
id="foo",
|
|
65
|
-
model="openai/gpt-5-mini",
|
|
66
|
-
object="chat.completion",
|
|
67
|
-
choices=[
|
|
68
|
-
Choice(
|
|
69
|
-
finish_reason="stop",
|
|
70
|
-
logprobs=None,
|
|
71
|
-
index=0,
|
|
72
|
-
message=ChatCompletionMessage(content="Hello world!", role="assistant"),
|
|
73
|
-
)
|
|
74
|
-
],
|
|
75
|
-
created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()),
|
|
76
|
-
usage={
|
|
77
|
-
"prompt_tokens": 57,
|
|
78
|
-
"completion_tokens": 40,
|
|
79
|
-
"total_tokens": 97,
|
|
80
|
-
},
|
|
81
|
-
)
|
|
82
|
-
# For async mocks, the return value should be awaitable
|
|
83
|
-
mock_chat_completion_create.return_value = completion
|
|
84
|
-
yield mock_chat_completion_create
|
|
85
|
-
|
|
86
|
-
|
|
87
46
|
@pytest.mark.asyncio
|
|
88
47
|
class TestOpenRouterChatGeneratorAsyncUnit:
|
|
89
|
-
async def test_warm_up_async(self, monkeypatch):
|
|
90
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "test-api-key")
|
|
91
|
-
component = OpenRouterChatGenerator()
|
|
92
|
-
if hasattr(component, "warm_up_async"):
|
|
93
|
-
# haystack-ai >= 3.0 creates the async client during async warm-up
|
|
94
|
-
await component.warm_up_async()
|
|
95
|
-
|
|
96
|
-
assert isinstance(component.async_client, AsyncOpenAI)
|
|
97
|
-
assert component.async_client.api_key == "test-api-key"
|
|
98
|
-
assert component.async_client.base_url == "https://openrouter.ai/api/v1/"
|
|
99
|
-
|
|
100
|
-
async def test_run_async(self, chat_messages, mock_async_chat_completion, monkeypatch): # noqa: ARG002
|
|
101
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
102
|
-
component = OpenRouterChatGenerator()
|
|
103
|
-
response = await component.run_async(chat_messages)
|
|
104
|
-
|
|
105
|
-
# check that the component returns the correct ChatMessage response
|
|
106
|
-
assert isinstance(response, dict)
|
|
107
|
-
assert "replies" in response
|
|
108
|
-
assert isinstance(response["replies"], list)
|
|
109
|
-
assert len(response["replies"]) == 1
|
|
110
|
-
assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
|
|
111
|
-
|
|
112
|
-
async def test_run_async_with_params(self, chat_messages, mock_async_chat_completion, monkeypatch):
|
|
113
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
114
|
-
component = OpenRouterChatGenerator(generation_kwargs={"max_tokens": 10, "temperature": 0.5})
|
|
115
|
-
response = await component.run_async(chat_messages)
|
|
116
|
-
|
|
117
|
-
# check that the component calls the OpenAI API with the correct parameters
|
|
118
|
-
_, kwargs = mock_async_chat_completion.call_args
|
|
119
|
-
assert kwargs["extra_body"]["max_tokens"] == 10
|
|
120
|
-
assert kwargs["extra_body"]["temperature"] == 0.5
|
|
121
|
-
|
|
122
|
-
# check that the component returns the correct response
|
|
123
|
-
assert isinstance(response, dict)
|
|
124
|
-
assert "replies" in response
|
|
125
|
-
assert isinstance(response["replies"], list)
|
|
126
|
-
assert len(response["replies"]) == 1
|
|
127
|
-
assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
|
|
128
|
-
|
|
129
|
-
async def test_run_async_with_generation_kwargs(self, chat_messages, mock_async_chat_completion, monkeypatch):
|
|
130
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
131
|
-
component = OpenRouterChatGenerator(generation_kwargs={"max_tokens": 10, "temperature": 0.5})
|
|
132
|
-
await component.run_async(chat_messages, generation_kwargs={"temperature": 0.9})
|
|
133
|
-
|
|
134
|
-
_, kwargs = mock_async_chat_completion.call_args
|
|
135
|
-
assert kwargs["extra_body"]["max_tokens"] == 10
|
|
136
|
-
assert kwargs["extra_body"]["temperature"] == 0.9
|
|
137
|
-
|
|
138
|
-
async def test_run_async_with_reasoning(self, monkeypatch):
|
|
139
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
140
|
-
|
|
141
|
-
with patch(
|
|
142
|
-
"openai.resources.chat.completions.AsyncCompletions.create",
|
|
143
|
-
new_callable=AsyncMock,
|
|
144
|
-
) as mock_create:
|
|
145
|
-
completion = ChatCompletion(
|
|
146
|
-
id="test-async-reasoning",
|
|
147
|
-
model="deepseek/deepseek-r1",
|
|
148
|
-
object="chat.completion",
|
|
149
|
-
choices=[
|
|
150
|
-
Choice(
|
|
151
|
-
finish_reason="stop",
|
|
152
|
-
logprobs=None,
|
|
153
|
-
index=0,
|
|
154
|
-
message=ChatCompletionMessage(
|
|
155
|
-
content="Paris is the capital of France.",
|
|
156
|
-
role="assistant",
|
|
157
|
-
reasoning="The user asked about capitals. France's capital is Paris.",
|
|
158
|
-
reasoning_details=[
|
|
159
|
-
{
|
|
160
|
-
"type": "reasoning.text",
|
|
161
|
-
"text": "The user asked about capitals. France's capital is Paris.",
|
|
162
|
-
}
|
|
163
|
-
],
|
|
164
|
-
),
|
|
165
|
-
)
|
|
166
|
-
],
|
|
167
|
-
created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()),
|
|
168
|
-
usage={"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97},
|
|
169
|
-
)
|
|
170
|
-
mock_create.return_value = completion
|
|
171
|
-
|
|
172
|
-
component = OpenRouterChatGenerator(
|
|
173
|
-
model="deepseek/deepseek-r1",
|
|
174
|
-
generation_kwargs={"reasoning": {"effort": "high"}},
|
|
175
|
-
)
|
|
176
|
-
response = await component.run_async([ChatMessage.from_user("What's the capital of France?")])
|
|
177
|
-
|
|
178
|
-
assert len(response["replies"]) == 1
|
|
179
|
-
reply = response["replies"][0]
|
|
180
|
-
assert reply.text == "Paris is the capital of France."
|
|
181
|
-
assert reply.reasoning is not None
|
|
182
|
-
assert "capitals" in reply.reasoning.reasoning_text
|
|
183
|
-
assert reply.reasoning.extra["reasoning_details"][0]["type"] == "reasoning.text"
|
|
184
|
-
|
|
185
48
|
async def test_run_async_streaming_with_reasoning(self, monkeypatch):
|
|
186
49
|
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
187
50
|
|
|
@@ -243,46 +106,6 @@ class TestOpenRouterChatGeneratorAsyncUnit:
|
|
|
243
106
|
]
|
|
244
107
|
assert reply.meta["finish_reason"] == "stop"
|
|
245
108
|
|
|
246
|
-
async def test_run_async_empty_messages(self, monkeypatch):
|
|
247
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
248
|
-
component = OpenRouterChatGenerator()
|
|
249
|
-
response = await component.run_async([])
|
|
250
|
-
assert response == {"replies": []}
|
|
251
|
-
|
|
252
|
-
async def test_run_async_with_string_input(self, monkeypatch):
|
|
253
|
-
monkeypatch.setenv("OPENROUTER_API_KEY", "fake-api-key")
|
|
254
|
-
|
|
255
|
-
with patch(
|
|
256
|
-
"openai.resources.chat.completions.AsyncCompletions.create",
|
|
257
|
-
new_callable=AsyncMock,
|
|
258
|
-
) as mock_create:
|
|
259
|
-
completion = ChatCompletion(
|
|
260
|
-
id="test-async-string-input",
|
|
261
|
-
model="openai/gpt-5-mini",
|
|
262
|
-
object="chat.completion",
|
|
263
|
-
choices=[
|
|
264
|
-
Choice(
|
|
265
|
-
finish_reason="stop",
|
|
266
|
-
logprobs=None,
|
|
267
|
-
index=0,
|
|
268
|
-
message=ChatCompletionMessage(content="Paris.", role="assistant"),
|
|
269
|
-
)
|
|
270
|
-
],
|
|
271
|
-
created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()),
|
|
272
|
-
usage={"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
|
|
273
|
-
)
|
|
274
|
-
mock_create.return_value = completion
|
|
275
|
-
|
|
276
|
-
component = OpenRouterChatGenerator()
|
|
277
|
-
response = await component.run_async("What's the capital of France?")
|
|
278
|
-
|
|
279
|
-
# the backend should receive exactly one user message
|
|
280
|
-
_, kwargs = mock_create.call_args
|
|
281
|
-
assert kwargs["messages"] == [{"role": "user", "content": "What's the capital of France?"}]
|
|
282
|
-
|
|
283
|
-
assert len(response["replies"]) == 1
|
|
284
|
-
assert response["replies"][0].text == "Paris."
|
|
285
|
-
|
|
286
109
|
|
|
287
110
|
@pytest.mark.skipif(
|
|
288
111
|
not os.environ.get("OPENROUTER_API_KEY", None),
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|