cometapi-haystack 2.0.1__tar.gz → 2.1.1__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.
- {cometapi_haystack-2.0.1 → cometapi_haystack-2.1.1}/CHANGELOG.md +14 -0
- {cometapi_haystack-2.0.1 → cometapi_haystack-2.1.1}/PKG-INFO +3 -2
- cometapi_haystack-2.1.1/pydoc/config_docusaurus.yml +13 -0
- {cometapi_haystack-2.0.1 → cometapi_haystack-2.1.1}/pyproject.toml +16 -9
- cometapi_haystack-2.1.1/src/haystack_integrations/components/generators/cometapi/chat/chat_generator.py +92 -0
- cometapi_haystack-2.1.1/tests/conftest.py +11 -0
- {cometapi_haystack-2.0.1 → cometapi_haystack-2.1.1}/tests/test_cometapi_chat_generator.py +32 -51
- {cometapi_haystack-2.0.1 → cometapi_haystack-2.1.1}/tests/test_cometapi_chat_generator_async.py +5 -2
- cometapi_haystack-2.0.1/pydoc/config_docusaurus.yml +0 -28
- cometapi_haystack-2.0.1/src/haystack_integrations/components/generators/cometapi/chat/chat_generator.py +0 -193
- {cometapi_haystack-2.0.1 → cometapi_haystack-2.1.1}/.gitignore +0 -0
- {cometapi_haystack-2.0.1 → cometapi_haystack-2.1.1}/LICENSE.txt +0 -0
- {cometapi_haystack-2.0.1 → cometapi_haystack-2.1.1}/README.md +0 -0
- {cometapi_haystack-2.0.1 → cometapi_haystack-2.1.1}/src/haystack_integrations/components/generators/cometapi/__init__.py +0 -0
- {cometapi_haystack-2.0.1 → cometapi_haystack-2.1.1}/src/haystack_integrations/components/generators/py.typed +0 -0
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [integrations/cometapi-v2.1.0] - 2026-01-28
|
|
4
|
+
|
|
5
|
+
### 🧹 Chores
|
|
6
|
+
|
|
7
|
+
- CometAPI - upgrade to Haystack 2.23 and remove special delta handling (#2786)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
## [integrations/cometapi-v2.0.1] - 2026-01-19
|
|
11
|
+
|
|
12
|
+
### 🐛 Bug Fixes
|
|
13
|
+
|
|
14
|
+
- `CometAPIChatGenerator` - handle `delta` set to `None` (#2759)
|
|
15
|
+
|
|
16
|
+
|
|
3
17
|
## [integrations/cometapi-v2.0.0] - 2026-01-09
|
|
4
18
|
|
|
5
19
|
### 🧹 Chores
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: cometapi-haystack
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.1.1
|
|
4
4
|
Summary: Use Comet API with Haystack to build AI applications with 500+ AI models.
|
|
5
5
|
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/cometapi#readme
|
|
6
6
|
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
@@ -15,10 +15,11 @@ Classifier: Programming Language :: Python :: 3.10
|
|
|
15
15
|
Classifier: Programming Language :: Python :: 3.11
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.12
|
|
17
17
|
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
19
|
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
19
20
|
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
20
21
|
Requires-Python: >=3.10
|
|
21
|
-
Requires-Dist: haystack-ai>=2.
|
|
22
|
+
Requires-Dist: haystack-ai>=2.23.0
|
|
22
23
|
Description-Content-Type: text/markdown
|
|
23
24
|
|
|
24
25
|
# cometapi-haystack
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
loaders:
|
|
2
|
+
- modules:
|
|
3
|
+
- haystack_integrations.components.generators.cometapi.chat.chat_generator
|
|
4
|
+
search_path: [../src]
|
|
5
|
+
processors:
|
|
6
|
+
- type: filter
|
|
7
|
+
documented_only: true
|
|
8
|
+
skip_empty_modules: true
|
|
9
|
+
renderer:
|
|
10
|
+
description: Comet API integration for Haystack
|
|
11
|
+
id: integrations-cometapi
|
|
12
|
+
filename: cometapi.md
|
|
13
|
+
title: Comet API
|
|
@@ -22,10 +22,11 @@ classifiers = [
|
|
|
22
22
|
"Programming Language :: Python :: 3.11",
|
|
23
23
|
"Programming Language :: Python :: 3.12",
|
|
24
24
|
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Programming Language :: Python :: 3.14",
|
|
25
26
|
"Programming Language :: Python :: Implementation :: CPython",
|
|
26
27
|
"Programming Language :: Python :: Implementation :: PyPy",
|
|
27
28
|
]
|
|
28
|
-
dependencies = ["haystack-ai>=2.
|
|
29
|
+
dependencies = ["haystack-ai>=2.23.0"]
|
|
29
30
|
|
|
30
31
|
[project.urls]
|
|
31
32
|
Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/cometapi#readme"
|
|
@@ -48,7 +49,7 @@ installer = "uv"
|
|
|
48
49
|
dependencies = ["haystack-pydoc-tools", "ruff"]
|
|
49
50
|
|
|
50
51
|
[tool.hatch.envs.default.scripts]
|
|
51
|
-
docs = ["pydoc
|
|
52
|
+
docs = ["haystack-pydoc pydoc/config_docusaurus.yml"]
|
|
52
53
|
fmt = "ruff check --fix {args}; ruff format {args}"
|
|
53
54
|
fmt-check = "ruff check {args} && ruff format --check {args}"
|
|
54
55
|
|
|
@@ -67,7 +68,8 @@ dependencies = [
|
|
|
67
68
|
unit = 'pytest -m "not integration" {args:tests}'
|
|
68
69
|
integration = 'pytest -m "integration" {args:tests}'
|
|
69
70
|
all = 'pytest {args:tests}'
|
|
70
|
-
cov-retry = '
|
|
71
|
+
unit-cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x -m "not integration" {args:tests}'
|
|
72
|
+
integration-cov-append-retry = 'pytest --cov=haystack_integrations --cov-append --reruns 3 --reruns-delay 30 -x -m "integration" {args:tests}'
|
|
71
73
|
|
|
72
74
|
types = "mypy -p haystack_integrations.components.generators.cometapi {args}"
|
|
73
75
|
|
|
@@ -77,11 +79,6 @@ non_interactive = true
|
|
|
77
79
|
check_untyped_defs = true
|
|
78
80
|
disallow_incomplete_defs = true
|
|
79
81
|
|
|
80
|
-
[[tool.mypy.overrides]]
|
|
81
|
-
module = [
|
|
82
|
-
"jsonref.*", # jsonref does not provide types
|
|
83
|
-
]
|
|
84
|
-
ignore_missing_imports = true
|
|
85
82
|
|
|
86
83
|
[tool.ruff]
|
|
87
84
|
line-length = 120
|
|
@@ -89,9 +86,17 @@ line-length = 120
|
|
|
89
86
|
[tool.ruff.lint]
|
|
90
87
|
select = [
|
|
91
88
|
"A",
|
|
89
|
+
"ANN",
|
|
92
90
|
"ARG",
|
|
93
91
|
"B",
|
|
94
92
|
"C",
|
|
93
|
+
"D102", # Missing docstring in public method
|
|
94
|
+
"D103", # Missing docstring in public function
|
|
95
|
+
"D205", # 1 blank line required between summary line and description
|
|
96
|
+
"D209", # Closing triple quotes go to new line
|
|
97
|
+
"D213", # summary lines must be positioned on the second physical line of the docstring
|
|
98
|
+
"D417", # Missing argument descriptions in the docstring
|
|
99
|
+
"D419", # Docstring is empty
|
|
95
100
|
"DTZ",
|
|
96
101
|
"E",
|
|
97
102
|
"EM",
|
|
@@ -115,6 +120,7 @@ select = [
|
|
|
115
120
|
"YTT",
|
|
116
121
|
]
|
|
117
122
|
ignore = [
|
|
123
|
+
"ANN401", # Allow Any - used legitimately for dynamic types and SDK boundaries
|
|
118
124
|
# Allow non-abstract empty methods in abstract base classes
|
|
119
125
|
"B027",
|
|
120
126
|
# Allow boolean positional values in function calls, like `dict.get(... True)`
|
|
@@ -145,13 +151,14 @@ ban-relative-imports = "parents"
|
|
|
145
151
|
|
|
146
152
|
[tool.ruff.lint.per-file-ignores]
|
|
147
153
|
# Tests can use magic values, assertions, and relative imports
|
|
148
|
-
"tests/**/*" = ["PLR2004", "S101", "TID252"]
|
|
154
|
+
"tests/**/*" = ["PLR2004", "S101", "TID252", "D", "ANN"]
|
|
149
155
|
# Examples can use print statements
|
|
150
156
|
"examples/**/*" = ["T201"]
|
|
151
157
|
|
|
152
158
|
[tool.coverage.run]
|
|
153
159
|
source = ["haystack_integrations"]
|
|
154
160
|
branch = true
|
|
161
|
+
relative_files = true
|
|
155
162
|
parallel = true
|
|
156
163
|
|
|
157
164
|
[tool.coverage.report]
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from haystack import component, default_to_dict
|
|
4
|
+
from haystack.components.generators.chat import OpenAIChatGenerator
|
|
5
|
+
from haystack.dataclasses import (
|
|
6
|
+
StreamingCallbackT,
|
|
7
|
+
)
|
|
8
|
+
from haystack.tools import (
|
|
9
|
+
Tool,
|
|
10
|
+
Toolset,
|
|
11
|
+
serialize_tools_or_toolset,
|
|
12
|
+
)
|
|
13
|
+
from haystack.utils import Secret, serialize_callable
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@component
|
|
17
|
+
class CometAPIChatGenerator(OpenAIChatGenerator):
|
|
18
|
+
"""
|
|
19
|
+
A chat generator that uses the CometAPI for generating chat responses.
|
|
20
|
+
|
|
21
|
+
This class extends Haystack's OpenAIChatGenerator to specifically interact with the CometAPI.
|
|
22
|
+
It sets the `api_base_url` to the CometAPI endpoint and allows for all the
|
|
23
|
+
standard configurations available in the OpenAIChatGenerator.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
*,
|
|
29
|
+
api_key: Secret = Secret.from_env_var("COMET_API_KEY"),
|
|
30
|
+
model: str = "gpt-5-mini",
|
|
31
|
+
streaming_callback: StreamingCallbackT | None = None,
|
|
32
|
+
generation_kwargs: dict[str, Any] | None = None,
|
|
33
|
+
timeout: int | None = None,
|
|
34
|
+
max_retries: int | None = None,
|
|
35
|
+
tools: list[Tool | Toolset] | Toolset | None = None,
|
|
36
|
+
tools_strict: bool = False,
|
|
37
|
+
http_client_kwargs: dict[str, Any] | None = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
"""
|
|
40
|
+
Creates a `CometAPIChatGenerator` instance.
|
|
41
|
+
|
|
42
|
+
:param api_key: The API key for authenticating with the CometAPI.
|
|
43
|
+
:param model: The name of the model to use for chat generation (e.g., `"gpt-5-mini"`, `"grok-3-mini"`).
|
|
44
|
+
:param streaming_callback: An optional callable invoked with each chunk of a streaming response.
|
|
45
|
+
:param generation_kwargs: Optional keyword arguments passed to the underlying generation API call.
|
|
46
|
+
:param timeout: The maximum time in seconds to wait for a response from the API.
|
|
47
|
+
:param max_retries: The maximum number of times to retry a failed API request.
|
|
48
|
+
:param tools: An optional list of tools the model can use.
|
|
49
|
+
:param tools_strict: If `True`, the model is forced to use one of the provided tools.
|
|
50
|
+
:param http_client_kwargs: Optional keyword arguments passed to the HTTP client.
|
|
51
|
+
"""
|
|
52
|
+
api_base_url = "https://api.cometapi.com/v1"
|
|
53
|
+
|
|
54
|
+
# the @component decorator recreates the class, so the zero-argument form of super() cannot be used
|
|
55
|
+
super(CometAPIChatGenerator, self).__init__( # noqa: UP008
|
|
56
|
+
api_key=api_key,
|
|
57
|
+
model=model,
|
|
58
|
+
api_base_url=api_base_url,
|
|
59
|
+
streaming_callback=streaming_callback,
|
|
60
|
+
generation_kwargs=generation_kwargs,
|
|
61
|
+
timeout=timeout,
|
|
62
|
+
max_retries=max_retries,
|
|
63
|
+
tools=tools,
|
|
64
|
+
tools_strict=tools_strict,
|
|
65
|
+
http_client_kwargs=http_client_kwargs,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
def to_dict(self) -> dict[str, Any]:
|
|
69
|
+
"""
|
|
70
|
+
Serialize this component to a dictionary.
|
|
71
|
+
|
|
72
|
+
:returns:
|
|
73
|
+
The serialized component as a dictionary.
|
|
74
|
+
"""
|
|
75
|
+
callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None
|
|
76
|
+
|
|
77
|
+
# if we didn't implement the to_dict method here then the to_dict method of the superclass would be used
|
|
78
|
+
# which would serialize some fields that we don't want to serialize (e.g. the ones we don't have in
|
|
79
|
+
# the __init__)
|
|
80
|
+
# it would be hard to maintain the compatibility as superclass changes
|
|
81
|
+
return default_to_dict(
|
|
82
|
+
self,
|
|
83
|
+
api_key=self.api_key.to_dict(),
|
|
84
|
+
model=self.model,
|
|
85
|
+
streaming_callback=callback_name,
|
|
86
|
+
generation_kwargs=self.generation_kwargs,
|
|
87
|
+
timeout=self.timeout,
|
|
88
|
+
max_retries=self.max_retries,
|
|
89
|
+
tools=serialize_tools_or_toolset(self.tools),
|
|
90
|
+
tools_strict=self.tools_strict,
|
|
91
|
+
http_client_kwargs=self.http_client_kwargs,
|
|
92
|
+
)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@pytest.fixture(autouse=True)
|
|
5
|
+
def allow_deserialization_of_test_modules(monkeypatch):
|
|
6
|
+
"""
|
|
7
|
+
haystack-ai >= 3.0 refuses to deserialize classes and callables from modules outside its
|
|
8
|
+
trusted-module allowlist. Tools and callbacks defined in the test modules live outside that
|
|
9
|
+
allowlist, so trust them explicitly; haystack-ai 2.x ignores this environment variable.
|
|
10
|
+
"""
|
|
11
|
+
monkeypatch.setenv("HAYSTACK_DESERIALIZATION_ALLOWLIST", "tests,test_*")
|
|
@@ -7,7 +7,11 @@ import pytest
|
|
|
7
7
|
import pytz
|
|
8
8
|
from haystack import Pipeline
|
|
9
9
|
from haystack.components.generators.utils import print_streaming_chunk
|
|
10
|
-
|
|
10
|
+
|
|
11
|
+
try:
|
|
12
|
+
from haystack.components.tools import ToolInvoker
|
|
13
|
+
except ImportError: # ToolInvoker was removed in Haystack 3.0
|
|
14
|
+
ToolInvoker = None
|
|
11
15
|
from haystack.dataclasses import ChatMessage, ChatRole, StreamingChunk, ToolCall
|
|
12
16
|
from haystack.tools import Tool
|
|
13
17
|
from haystack.utils.auth import Secret
|
|
@@ -88,16 +92,24 @@ class TestCometAPIChatGenerator:
|
|
|
88
92
|
def test_init_default(self, monkeypatch):
|
|
89
93
|
monkeypatch.setenv("COMET_API_KEY", "test-api-key")
|
|
90
94
|
component = CometAPIChatGenerator()
|
|
91
|
-
assert component.
|
|
95
|
+
assert component.api_key.resolve_value() == "test-api-key"
|
|
92
96
|
assert component.model == "gpt-5-mini"
|
|
93
97
|
assert component.api_base_url == "https://api.cometapi.com/v1"
|
|
94
98
|
assert component.streaming_callback is None
|
|
95
99
|
assert not component.generation_kwargs
|
|
96
100
|
|
|
101
|
+
def test_warm_up(self, monkeypatch):
|
|
102
|
+
monkeypatch.setenv("COMET_API_KEY", "test-api-key")
|
|
103
|
+
component = CometAPIChatGenerator()
|
|
104
|
+
component.warm_up() # with haystack-ai >= 3.0 the client is created during warm-up
|
|
105
|
+
assert component.client.api_key == "test-api-key"
|
|
106
|
+
|
|
97
107
|
def test_init_fail_wo_api_key(self, monkeypatch):
|
|
98
108
|
monkeypatch.delenv("COMET_API_KEY", raising=False)
|
|
99
109
|
with pytest.raises(ValueError, match=r"None of the .* environment variables are set"):
|
|
100
|
-
|
|
110
|
+
# haystack-ai 2.x raises at init; haystack-ai >= 3.0 raises when the client is created in warm_up
|
|
111
|
+
component = CometAPIChatGenerator()
|
|
112
|
+
component.warm_up()
|
|
101
113
|
|
|
102
114
|
def test_init_with_parameters(self):
|
|
103
115
|
component = CometAPIChatGenerator(
|
|
@@ -106,7 +118,7 @@ class TestCometAPIChatGenerator:
|
|
|
106
118
|
streaming_callback=print_streaming_chunk,
|
|
107
119
|
generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"},
|
|
108
120
|
)
|
|
109
|
-
assert component.
|
|
121
|
+
assert component.api_key.resolve_value() == "test-api-key"
|
|
110
122
|
assert component.model == "gpt-5-mini"
|
|
111
123
|
assert component.streaming_callback is print_streaming_chunk
|
|
112
124
|
assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"}
|
|
@@ -125,7 +137,6 @@ class TestCometAPIChatGenerator:
|
|
|
125
137
|
"api_key": {"env_vars": ["COMET_API_KEY"], "strict": True, "type": "env_var"},
|
|
126
138
|
"model": "gpt-5-mini",
|
|
127
139
|
"streaming_callback": None,
|
|
128
|
-
"api_base_url": "https://api.cometapi.com/v1",
|
|
129
140
|
"generation_kwargs": {},
|
|
130
141
|
"timeout": None,
|
|
131
142
|
"max_retries": None,
|
|
@@ -158,7 +169,6 @@ class TestCometAPIChatGenerator:
|
|
|
158
169
|
expected_params = {
|
|
159
170
|
"api_key": {"env_vars": ["ENV_VAR"], "strict": True, "type": "env_var"},
|
|
160
171
|
"model": "gpt-5-mini",
|
|
161
|
-
"api_base_url": "https://api.cometapi.com/v1",
|
|
162
172
|
"streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
|
|
163
173
|
"generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"},
|
|
164
174
|
"timeout": 10,
|
|
@@ -196,22 +206,6 @@ class TestCometAPIChatGenerator:
|
|
|
196
206
|
assert component.timeout == 10
|
|
197
207
|
assert component.max_retries == 10
|
|
198
208
|
|
|
199
|
-
def test_from_dict_fail_wo_env_var(self, monkeypatch):
|
|
200
|
-
monkeypatch.delenv("COMET_API_KEY", raising=False)
|
|
201
|
-
data = {
|
|
202
|
-
"type": ("haystack_integrations.components.generators.cometapi.chat.chat_generator.CometAPIChatGenerator"),
|
|
203
|
-
"init_parameters": {
|
|
204
|
-
"api_key": {"env_vars": ["COMET_API_KEY"], "strict": True, "type": "env_var"},
|
|
205
|
-
"model": "gpt-5-mini",
|
|
206
|
-
"streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
|
|
207
|
-
"generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"},
|
|
208
|
-
"timeout": 10,
|
|
209
|
-
"max_retries": 10,
|
|
210
|
-
},
|
|
211
|
-
}
|
|
212
|
-
with pytest.raises(ValueError, match=r"None of the .* environment variables are set"):
|
|
213
|
-
CometAPIChatGenerator.from_dict(data)
|
|
214
|
-
|
|
215
209
|
def test_run(self, chat_messages, mock_chat_completion, monkeypatch):
|
|
216
210
|
monkeypatch.setenv("COMET_API_KEY", "fake-api-key")
|
|
217
211
|
component = CometAPIChatGenerator()
|
|
@@ -392,6 +386,7 @@ class TestCometAPIChatGenerator:
|
|
|
392
386
|
reason="Export an env var called COMET_API_KEY containing the OpenAI API key to run this test.",
|
|
393
387
|
)
|
|
394
388
|
@pytest.mark.integration
|
|
389
|
+
@pytest.mark.skipif(ToolInvoker is None, reason="ToolInvoker is not available in the installed haystack-ai version")
|
|
395
390
|
def test_pipeline_with_cometapi_chat_generator(self, tools):
|
|
396
391
|
"""
|
|
397
392
|
Test that the CometAPIChatGenerator component can be used in a pipeline
|
|
@@ -445,6 +440,11 @@ class TestCometAPIChatGenerator:
|
|
|
445
440
|
|
|
446
441
|
# Get pipeline dictionary and verify its structure
|
|
447
442
|
pipeline_dict = pipeline.to_dict()
|
|
443
|
+
|
|
444
|
+
# the Tool serialization format is owned by haystack-ai and varies across its versions; the
|
|
445
|
+
# dumps/loads round-trip below covers the tools, so exclude them from the pinned-dict comparison
|
|
446
|
+
tools_entries = pipeline_dict["components"]["generator"]["init_parameters"].pop("tools")
|
|
447
|
+
assert len(tools_entries) == 1
|
|
448
448
|
expected_dict = {
|
|
449
449
|
"metadata": {},
|
|
450
450
|
"max_runs_per_component": 100,
|
|
@@ -456,23 +456,10 @@ class TestCometAPIChatGenerator:
|
|
|
456
456
|
"init_parameters": {
|
|
457
457
|
"model": "gpt-5-mini",
|
|
458
458
|
"streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
|
|
459
|
-
"api_base_url": "https://api.cometapi.com/v1",
|
|
460
|
-
"organization": None,
|
|
461
459
|
"generation_kwargs": {"temperature": 0.7},
|
|
462
460
|
"api_key": {"type": "env_var", "env_vars": ["COMET_API_KEY"], "strict": True},
|
|
463
461
|
"timeout": None,
|
|
464
462
|
"max_retries": None,
|
|
465
|
-
"tools": [
|
|
466
|
-
{
|
|
467
|
-
"type": "haystack.tools.tool.Tool",
|
|
468
|
-
"data": {
|
|
469
|
-
"name": "weather",
|
|
470
|
-
"description": "useful to determine the weather in a given location",
|
|
471
|
-
"parameters": {"city": {"type": "string"}},
|
|
472
|
-
"function": "test_cometapi_chat_generator.weather",
|
|
473
|
-
},
|
|
474
|
-
}
|
|
475
|
-
],
|
|
476
463
|
"tools_strict": False,
|
|
477
464
|
"http_client_kwargs": None,
|
|
478
465
|
},
|
|
@@ -485,25 +472,15 @@ class TestCometAPIChatGenerator:
|
|
|
485
472
|
if not hasattr(pipeline, "_connection_type_validation"):
|
|
486
473
|
expected_dict.pop("connection_type_validation")
|
|
487
474
|
|
|
488
|
-
# add outputs_to_string, inputs_from_state and outputs_to_state tool parameters for compatibility with
|
|
489
|
-
# haystack-ai>=2.12.0
|
|
490
|
-
if hasattr(tool, "outputs_to_string"):
|
|
491
|
-
expected_dict["components"]["generator"]["init_parameters"]["tools"][0]["data"]["outputs_to_string"] = (
|
|
492
|
-
tool.outputs_to_string
|
|
493
|
-
)
|
|
494
|
-
if hasattr(tool, "inputs_from_state"):
|
|
495
|
-
expected_dict["components"]["generator"]["init_parameters"]["tools"][0]["data"]["inputs_from_state"] = (
|
|
496
|
-
tool.inputs_from_state
|
|
497
|
-
)
|
|
498
|
-
if hasattr(tool, "outputs_to_state"):
|
|
499
|
-
expected_dict["components"]["generator"]["init_parameters"]["tools"][0]["data"]["outputs_to_state"] = (
|
|
500
|
-
tool.outputs_to_state
|
|
501
|
-
)
|
|
502
|
-
|
|
503
475
|
assert pipeline_dict == expected_dict
|
|
504
476
|
|
|
477
|
+
# Test YAML serialization/deserialization
|
|
478
|
+
pipeline_yaml = pipeline.dumps()
|
|
479
|
+
new_pipeline = Pipeline.loads(pipeline_yaml)
|
|
480
|
+
assert new_pipeline == pipeline
|
|
481
|
+
|
|
505
482
|
# Verify the loaded pipeline's generator has the same configuration
|
|
506
|
-
loaded_generator =
|
|
483
|
+
loaded_generator = new_pipeline.get_component("generator")
|
|
507
484
|
assert loaded_generator.model == generator.model
|
|
508
485
|
assert loaded_generator.generation_kwargs == generator.generation_kwargs
|
|
509
486
|
assert loaded_generator.streaming_callback == generator.streaming_callback
|
|
@@ -847,6 +824,9 @@ class TestChatCompletionChunkConversion:
|
|
|
847
824
|
if not isinstance(usage["prompt_tokens_details"], dict):
|
|
848
825
|
usage["prompt_tokens_details"] = asdict(usage["prompt_tokens_details"])
|
|
849
826
|
|
|
827
|
+
# Normalize usage details since cache_write_tokens is not always present in the response
|
|
828
|
+
usage["prompt_tokens_details"].setdefault("cache_write_tokens", None)
|
|
829
|
+
|
|
850
830
|
assert usage == {
|
|
851
831
|
"completion_tokens": 42,
|
|
852
832
|
"prompt_tokens": 55,
|
|
@@ -859,6 +839,7 @@ class TestChatCompletionChunkConversion:
|
|
|
859
839
|
},
|
|
860
840
|
"prompt_tokens_details": {
|
|
861
841
|
"audio_tokens": None,
|
|
842
|
+
"cache_write_tokens": None,
|
|
862
843
|
"cached_tokens": 0,
|
|
863
844
|
},
|
|
864
845
|
}
|
{cometapi_haystack-2.0.1 → cometapi_haystack-2.1.1}/tests/test_cometapi_chat_generator_async.py
RENAMED
|
@@ -83,14 +83,17 @@ def mock_async_chat_completion():
|
|
|
83
83
|
|
|
84
84
|
|
|
85
85
|
class TestCometAPIChatGeneratorAsync:
|
|
86
|
-
|
|
86
|
+
@pytest.mark.asyncio
|
|
87
|
+
async def test_warm_up_async(self, monkeypatch):
|
|
87
88
|
monkeypatch.setenv("COMET_API_KEY", "test-api-key")
|
|
88
89
|
component = CometAPIChatGenerator()
|
|
90
|
+
if hasattr(component, "warm_up_async"):
|
|
91
|
+
# haystack-ai >= 3.0 creates the async client during async warm-up
|
|
92
|
+
await component.warm_up_async()
|
|
89
93
|
|
|
90
94
|
assert isinstance(component.async_client, AsyncOpenAI)
|
|
91
95
|
assert component.async_client.api_key == "test-api-key"
|
|
92
96
|
assert component.async_client.base_url == "https://api.cometapi.com/v1/"
|
|
93
|
-
assert not component.generation_kwargs
|
|
94
97
|
|
|
95
98
|
@pytest.mark.asyncio
|
|
96
99
|
async def test_run_async(self, chat_messages, mock_async_chat_completion, monkeypatch):
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
loaders:
|
|
2
|
-
- ignore_when_discovered:
|
|
3
|
-
- __init__
|
|
4
|
-
modules:
|
|
5
|
-
- haystack_integrations.components.generators.cometapi.chat.chat_generator
|
|
6
|
-
search_path:
|
|
7
|
-
- ../src
|
|
8
|
-
type: haystack_pydoc_tools.loaders.CustomPythonLoader
|
|
9
|
-
processors:
|
|
10
|
-
- do_not_filter_modules: false
|
|
11
|
-
documented_only: true
|
|
12
|
-
expression: null
|
|
13
|
-
skip_empty_modules: true
|
|
14
|
-
type: filter
|
|
15
|
-
- type: smart
|
|
16
|
-
- type: crossref
|
|
17
|
-
renderer:
|
|
18
|
-
description: Comet API integration for Haystack
|
|
19
|
-
id: integrations-cometapi
|
|
20
|
-
markdown:
|
|
21
|
-
add_member_class_prefix: false
|
|
22
|
-
add_method_class_prefix: true
|
|
23
|
-
classdef_code_block: false
|
|
24
|
-
descriptive_class_title: false
|
|
25
|
-
descriptive_module_title: true
|
|
26
|
-
filename: cometapi.md
|
|
27
|
-
title: Comet API
|
|
28
|
-
type: haystack_pydoc_tools.renderers.DocusaurusRenderer
|
|
@@ -1,193 +0,0 @@
|
|
|
1
|
-
from datetime import datetime
|
|
2
|
-
from typing import Any
|
|
3
|
-
|
|
4
|
-
from haystack.components.generators.chat import OpenAIChatGenerator
|
|
5
|
-
from haystack.components.generators.chat import openai as openai_module
|
|
6
|
-
from haystack.components.generators.utils import _serialize_object
|
|
7
|
-
from haystack.dataclasses import (
|
|
8
|
-
ComponentInfo,
|
|
9
|
-
FinishReason,
|
|
10
|
-
StreamingCallbackT,
|
|
11
|
-
StreamingChunk,
|
|
12
|
-
ToolCallDelta,
|
|
13
|
-
)
|
|
14
|
-
from haystack.tools import (
|
|
15
|
-
Tool,
|
|
16
|
-
Toolset,
|
|
17
|
-
)
|
|
18
|
-
from haystack.utils import Secret
|
|
19
|
-
from openai.types.chat import ChatCompletionChunk
|
|
20
|
-
from openai.types.chat.chat_completion_chunk import Choice as ChunkChoice
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
# TODO: remove the following function and the monkey patch after haystack-ai==2.23.0, that ships this fix in the base
|
|
24
|
-
# class
|
|
25
|
-
def _convert_chat_completion_chunk_to_streaming_chunk(
|
|
26
|
-
chunk: ChatCompletionChunk, previous_chunks: list[StreamingChunk], component_info: ComponentInfo | None = None
|
|
27
|
-
) -> StreamingChunk:
|
|
28
|
-
"""
|
|
29
|
-
Converts the streaming response chunk from the OpenAI API to a StreamingChunk.
|
|
30
|
-
|
|
31
|
-
:param chunk: The chunk returned by the OpenAI API.
|
|
32
|
-
:param previous_chunks: A list of previously received StreamingChunks.
|
|
33
|
-
:param component_info: An optional `ComponentInfo` object containing information about the component that
|
|
34
|
-
generated the chunk, such as the component name and type.
|
|
35
|
-
|
|
36
|
-
:returns:
|
|
37
|
-
A StreamingChunk object representing the content of the chunk from the OpenAI API.
|
|
38
|
-
"""
|
|
39
|
-
finish_reason_mapping: dict[str, FinishReason] = {
|
|
40
|
-
"stop": "stop",
|
|
41
|
-
"length": "length",
|
|
42
|
-
"content_filter": "content_filter",
|
|
43
|
-
"tool_calls": "tool_calls",
|
|
44
|
-
"function_call": "tool_calls",
|
|
45
|
-
}
|
|
46
|
-
# On very first chunk so len(previous_chunks) == 0, the Choices field only provides role info (e.g. "assistant")
|
|
47
|
-
# Choices is empty if include_usage is set to True where the usage information is returned.
|
|
48
|
-
if len(chunk.choices) == 0:
|
|
49
|
-
return StreamingChunk(
|
|
50
|
-
content="",
|
|
51
|
-
component_info=component_info,
|
|
52
|
-
# Index is None since it's only set to an int when a content block is present
|
|
53
|
-
index=None,
|
|
54
|
-
finish_reason=None,
|
|
55
|
-
meta={
|
|
56
|
-
"model": chunk.model,
|
|
57
|
-
"received_at": datetime.now().isoformat(), # noqa: DTZ005
|
|
58
|
-
"usage": _serialize_object(chunk.usage),
|
|
59
|
-
},
|
|
60
|
-
)
|
|
61
|
-
|
|
62
|
-
choice: ChunkChoice = chunk.choices[0]
|
|
63
|
-
|
|
64
|
-
# create a list of ToolCallDelta objects from the tool calls
|
|
65
|
-
if choice.delta and choice.delta.tool_calls:
|
|
66
|
-
tool_calls_deltas = []
|
|
67
|
-
for tool_call in choice.delta.tool_calls:
|
|
68
|
-
function = tool_call.function
|
|
69
|
-
tool_calls_deltas.append(
|
|
70
|
-
ToolCallDelta(
|
|
71
|
-
index=tool_call.index,
|
|
72
|
-
id=tool_call.id,
|
|
73
|
-
tool_name=function.name if function else None,
|
|
74
|
-
arguments=function.arguments if function and function.arguments else None,
|
|
75
|
-
)
|
|
76
|
-
)
|
|
77
|
-
chunk_message = StreamingChunk(
|
|
78
|
-
content=choice.delta.content or "",
|
|
79
|
-
component_info=component_info,
|
|
80
|
-
# We adopt the first tool_calls_deltas.index as the overall index of the chunk.
|
|
81
|
-
index=tool_calls_deltas[0].index,
|
|
82
|
-
tool_calls=tool_calls_deltas,
|
|
83
|
-
start=tool_calls_deltas[0].tool_name is not None,
|
|
84
|
-
finish_reason=finish_reason_mapping.get(choice.finish_reason) if choice.finish_reason else None,
|
|
85
|
-
meta={
|
|
86
|
-
"model": chunk.model,
|
|
87
|
-
"index": choice.index,
|
|
88
|
-
"tool_calls": choice.delta.tool_calls,
|
|
89
|
-
"finish_reason": choice.finish_reason,
|
|
90
|
-
"received_at": datetime.now().isoformat(), # noqa: DTZ005
|
|
91
|
-
"usage": _serialize_object(chunk.usage),
|
|
92
|
-
},
|
|
93
|
-
)
|
|
94
|
-
return chunk_message
|
|
95
|
-
|
|
96
|
-
# On very first chunk the choice field only provides role info (e.g. "assistant") so we set index to None
|
|
97
|
-
# We set all chunks missing the content field to index of None. E.g. can happen if chunk only contains finish
|
|
98
|
-
# reason.
|
|
99
|
-
if choice.delta and (choice.delta.content is None or choice.delta.role is not None):
|
|
100
|
-
resolved_index = None
|
|
101
|
-
else:
|
|
102
|
-
# We set the index to be 0 since if text content is being streamed then no tool calls are being streamed
|
|
103
|
-
# NOTE: We may need to revisit this if OpenAI allows planning/thinking content before tool calls like
|
|
104
|
-
# Anthropic Claude
|
|
105
|
-
resolved_index = 0
|
|
106
|
-
|
|
107
|
-
# Initialize meta dictionary
|
|
108
|
-
meta = {
|
|
109
|
-
"model": chunk.model,
|
|
110
|
-
"index": choice.index,
|
|
111
|
-
"tool_calls": choice.delta.tool_calls if choice.delta and choice.delta.tool_calls else None,
|
|
112
|
-
"finish_reason": choice.finish_reason,
|
|
113
|
-
"received_at": datetime.now().isoformat(), # noqa: DTZ005
|
|
114
|
-
"usage": _serialize_object(chunk.usage),
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
# check if logprobs are present
|
|
118
|
-
# logprobs are returned only for text content
|
|
119
|
-
logprobs = _serialize_object(choice.logprobs) if choice.logprobs else None
|
|
120
|
-
if logprobs:
|
|
121
|
-
meta["logprobs"] = logprobs
|
|
122
|
-
|
|
123
|
-
content = ""
|
|
124
|
-
if choice.delta and choice.delta.content:
|
|
125
|
-
content = choice.delta.content
|
|
126
|
-
|
|
127
|
-
chunk_message = StreamingChunk(
|
|
128
|
-
content=content,
|
|
129
|
-
component_info=component_info,
|
|
130
|
-
index=resolved_index,
|
|
131
|
-
# The first chunk is always a start message chunk that only contains role information, so if we reach here
|
|
132
|
-
# and previous_chunks is length 1 then this is the start of text content.
|
|
133
|
-
start=len(previous_chunks) == 1,
|
|
134
|
-
finish_reason=finish_reason_mapping.get(choice.finish_reason) if choice.finish_reason else None,
|
|
135
|
-
meta=meta,
|
|
136
|
-
)
|
|
137
|
-
return chunk_message
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
# monkey patch the OpenAIChatGenerator to use our own _convert_chat_completion_chunk_to_streaming_chunk
|
|
141
|
-
openai_module._convert_chat_completion_chunk_to_streaming_chunk = _convert_chat_completion_chunk_to_streaming_chunk
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
class CometAPIChatGenerator(OpenAIChatGenerator):
|
|
145
|
-
"""
|
|
146
|
-
A chat generator that uses the CometAPI for generating chat responses.
|
|
147
|
-
|
|
148
|
-
This class extends Haystack's OpenAIChatGenerator to specifically interact with the CometAPI.
|
|
149
|
-
It sets the `api_base_url` to the CometAPI endpoint and allows for all the
|
|
150
|
-
standard configurations available in the OpenAIChatGenerator.
|
|
151
|
-
|
|
152
|
-
:param api_key: The API key for authenticating with the CometAPI. Defaults to
|
|
153
|
-
loading from the "COMET_API_KEY" environment variable.
|
|
154
|
-
:param model: The name of the model to use for chat generation (e.g., "gpt-5-mini", "grok-3-mini").
|
|
155
|
-
Defaults to "gpt-5-mini".
|
|
156
|
-
:param streaming_callback: An optional callable that will be called with each chunk of
|
|
157
|
-
a streaming response.
|
|
158
|
-
:param generation_kwargs: Optional keyword arguments to pass to the underlying generation
|
|
159
|
-
API call.
|
|
160
|
-
:param timeout: The maximum time in seconds to wait for a response from the API.
|
|
161
|
-
:param max_retries: The maximum number of times to retry a failed API request.
|
|
162
|
-
:param tools: An optional list of tool definitions that the model can use.
|
|
163
|
-
:param tools_strict: If True, the model is forced to use one of the provided tools if a tool call is made.
|
|
164
|
-
:param http_client_kwargs: Optional keyword arguments to pass to the HTTP client.
|
|
165
|
-
"""
|
|
166
|
-
|
|
167
|
-
def __init__(
|
|
168
|
-
self,
|
|
169
|
-
*,
|
|
170
|
-
api_key: Secret = Secret.from_env_var("COMET_API_KEY"),
|
|
171
|
-
model: str = "gpt-5-mini",
|
|
172
|
-
streaming_callback: StreamingCallbackT | None = None,
|
|
173
|
-
generation_kwargs: dict[str, Any] | None = None,
|
|
174
|
-
timeout: int | None = None,
|
|
175
|
-
max_retries: int | None = None,
|
|
176
|
-
tools: list[Tool | Toolset] | Toolset | None = None,
|
|
177
|
-
tools_strict: bool = False,
|
|
178
|
-
http_client_kwargs: dict[str, Any] | None = None,
|
|
179
|
-
):
|
|
180
|
-
api_base_url = "https://api.cometapi.com/v1"
|
|
181
|
-
|
|
182
|
-
super().__init__(
|
|
183
|
-
api_key=api_key,
|
|
184
|
-
model=model,
|
|
185
|
-
api_base_url=api_base_url,
|
|
186
|
-
streaming_callback=streaming_callback,
|
|
187
|
-
generation_kwargs=generation_kwargs,
|
|
188
|
-
timeout=timeout,
|
|
189
|
-
max_retries=max_retries,
|
|
190
|
-
tools=tools,
|
|
191
|
-
tools_strict=tools_strict,
|
|
192
|
-
http_client_kwargs=http_client_kwargs,
|
|
193
|
-
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|