litellm-haystack 1.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.
- litellm_haystack-1.0.0/.gitignore +146 -0
- litellm_haystack-1.0.0/LICENSE.txt +73 -0
- litellm_haystack-1.0.0/PKG-INFO +40 -0
- litellm_haystack-1.0.0/README.md +15 -0
- litellm_haystack-1.0.0/pydoc/config_docusaurus.yml +13 -0
- litellm_haystack-1.0.0/pyproject.toml +105 -0
- litellm_haystack-1.0.0/src/haystack_integrations/components/generators/litellm/__init__.py +7 -0
- litellm_haystack-1.0.0/src/haystack_integrations/components/generators/litellm/chat/__init__.py +3 -0
- litellm_haystack-1.0.0/src/haystack_integrations/components/generators/litellm/chat/chat_generator.py +371 -0
- litellm_haystack-1.0.0/src/haystack_integrations/components/generators/py.typed +0 -0
- litellm_haystack-1.0.0/tests/__init__.py +0 -0
- litellm_haystack-1.0.0/tests/test_litellm_chat_generator.py +518 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
pip-wheel-metadata/
|
|
24
|
+
share/python-wheels/
|
|
25
|
+
*.egg-info/
|
|
26
|
+
.installed.cfg
|
|
27
|
+
*.egg
|
|
28
|
+
MANIFEST
|
|
29
|
+
|
|
30
|
+
# PyInstaller
|
|
31
|
+
# Usually these files are written by a python script from a template
|
|
32
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
33
|
+
*.manifest
|
|
34
|
+
*.spec
|
|
35
|
+
|
|
36
|
+
# Installer logs
|
|
37
|
+
pip-log.txt
|
|
38
|
+
pip-delete-this-directory.txt
|
|
39
|
+
|
|
40
|
+
# Unit test / coverage reports
|
|
41
|
+
htmlcov/
|
|
42
|
+
.tox/
|
|
43
|
+
.nox/
|
|
44
|
+
.coverage
|
|
45
|
+
.coverage.*
|
|
46
|
+
.cache
|
|
47
|
+
nosetests.xml
|
|
48
|
+
coverage.xml
|
|
49
|
+
*.cover
|
|
50
|
+
*.py,cover
|
|
51
|
+
.hypothesis/
|
|
52
|
+
.pytest_cache/
|
|
53
|
+
volumes/
|
|
54
|
+
|
|
55
|
+
# Translations
|
|
56
|
+
*.mo
|
|
57
|
+
*.pot
|
|
58
|
+
|
|
59
|
+
# Django stuff:
|
|
60
|
+
*.log
|
|
61
|
+
local_settings.py
|
|
62
|
+
db.sqlite3
|
|
63
|
+
db.sqlite3-journal
|
|
64
|
+
|
|
65
|
+
# Flask stuff:
|
|
66
|
+
instance/
|
|
67
|
+
.webassets-cache
|
|
68
|
+
|
|
69
|
+
# Scrapy stuff:
|
|
70
|
+
.scrapy
|
|
71
|
+
|
|
72
|
+
# Sphinx documentation
|
|
73
|
+
docs/_build/
|
|
74
|
+
|
|
75
|
+
# PyBuilder
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
.python-version
|
|
87
|
+
|
|
88
|
+
# pipenv
|
|
89
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
90
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
91
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
92
|
+
# install all needed dependencies.
|
|
93
|
+
#Pipfile.lock
|
|
94
|
+
|
|
95
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
|
96
|
+
__pypackages__/
|
|
97
|
+
|
|
98
|
+
# Celery stuff
|
|
99
|
+
celerybeat-schedule
|
|
100
|
+
celerybeat.pid
|
|
101
|
+
|
|
102
|
+
# SageMath parsed files
|
|
103
|
+
*.sage.py
|
|
104
|
+
|
|
105
|
+
# Environments
|
|
106
|
+
.env
|
|
107
|
+
.venv
|
|
108
|
+
env/
|
|
109
|
+
venv/
|
|
110
|
+
ENV/
|
|
111
|
+
env.bak/
|
|
112
|
+
venv.bak/
|
|
113
|
+
|
|
114
|
+
# Spyder project settings
|
|
115
|
+
.spyderproject
|
|
116
|
+
.spyproject
|
|
117
|
+
|
|
118
|
+
# Rope project settings
|
|
119
|
+
.ropeproject
|
|
120
|
+
|
|
121
|
+
# mkdocs documentation
|
|
122
|
+
/site
|
|
123
|
+
|
|
124
|
+
# mypy
|
|
125
|
+
.mypy_cache/
|
|
126
|
+
.dmypy.json
|
|
127
|
+
dmypy.json
|
|
128
|
+
|
|
129
|
+
# Pyre type checker
|
|
130
|
+
.pyre/
|
|
131
|
+
|
|
132
|
+
# IDEs
|
|
133
|
+
.vscode
|
|
134
|
+
|
|
135
|
+
# Docs generation artifacts
|
|
136
|
+
_readme_*.md
|
|
137
|
+
.idea
|
|
138
|
+
|
|
139
|
+
# macOS
|
|
140
|
+
.DS_Store
|
|
141
|
+
|
|
142
|
+
# http cache (requests-cache)
|
|
143
|
+
**/http_cache.sqlite
|
|
144
|
+
|
|
145
|
+
# ruff
|
|
146
|
+
.ruff_cache
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
10
|
+
|
|
11
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
12
|
+
|
|
13
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
14
|
+
|
|
15
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
16
|
+
|
|
17
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
18
|
+
|
|
19
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
20
|
+
|
|
21
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
22
|
+
|
|
23
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
24
|
+
|
|
25
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
26
|
+
|
|
27
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
28
|
+
|
|
29
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
30
|
+
|
|
31
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
32
|
+
|
|
33
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
34
|
+
|
|
35
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
36
|
+
|
|
37
|
+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
38
|
+
|
|
39
|
+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
40
|
+
|
|
41
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
42
|
+
|
|
43
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
56
|
+
|
|
57
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
58
|
+
|
|
59
|
+
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
|
60
|
+
|
|
61
|
+
Copyright [yyyy] [name of copyright owner]
|
|
62
|
+
|
|
63
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
64
|
+
you may not use this file except in compliance with the License.
|
|
65
|
+
You may obtain a copy of the License at
|
|
66
|
+
|
|
67
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
68
|
+
|
|
69
|
+
Unless required by applicable law or agreed to in writing, software
|
|
70
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
71
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
72
|
+
See the License for the specific language governing permissions and
|
|
73
|
+
limitations under the License.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: litellm-haystack
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: An integration of LiteLLM AI gateway into the Haystack framework, routing to 100+ LLM providers.
|
|
5
|
+
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/litellm#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
7
|
+
Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/litellm
|
|
8
|
+
Author-email: deepset GmbH <info@deepset.ai>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE.txt
|
|
11
|
+
Keywords: ai-gateway,haystack,litellm,llm
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Programming Language :: Python
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Requires-Dist: haystack-ai>=2.24.1
|
|
23
|
+
Requires-Dist: litellm!=1.82.7,!=1.82.8,<2.0,>=1.60.0
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# litellm-haystack
|
|
27
|
+
|
|
28
|
+
[](https://pypi.org/project/litellm-haystack)
|
|
29
|
+
[](https://pypi.org/project/litellm-haystack)
|
|
30
|
+
|
|
31
|
+
- [Integration page](https://haystack.deepset.ai/integrations/litellm)
|
|
32
|
+
- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/litellm/CHANGELOG.md)
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## Contributing
|
|
37
|
+
|
|
38
|
+
Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
|
|
39
|
+
|
|
40
|
+
To run integration tests locally, you need to export the `OPENAI_API_KEY` environment variable.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# litellm-haystack
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/litellm-haystack)
|
|
4
|
+
[](https://pypi.org/project/litellm-haystack)
|
|
5
|
+
|
|
6
|
+
- [Integration page](https://haystack.deepset.ai/integrations/litellm)
|
|
7
|
+
- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/litellm/CHANGELOG.md)
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Contributing
|
|
12
|
+
|
|
13
|
+
Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
|
|
14
|
+
|
|
15
|
+
To run integration tests locally, you need to export the `OPENAI_API_KEY` environment variable.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
loaders:
|
|
2
|
+
- modules:
|
|
3
|
+
- haystack_integrations.components.generators.litellm.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: LiteLLM integration for Haystack
|
|
11
|
+
id: integrations-litellm
|
|
12
|
+
filename: litellm.md
|
|
13
|
+
title: LiteLLM
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling", "hatch-vcs"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "litellm-haystack"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "An integration of LiteLLM AI gateway into the Haystack framework, routing to 100+ LLM providers."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
keywords = ["haystack", "litellm", "llm", "ai-gateway"]
|
|
13
|
+
authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"License :: OSI Approved :: Apache Software License",
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Programming Language :: Python",
|
|
18
|
+
"Programming Language :: Python :: 3.10",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Programming Language :: Python :: 3.14",
|
|
23
|
+
"Programming Language :: Python :: Implementation :: CPython",
|
|
24
|
+
]
|
|
25
|
+
# litellm 1.82.7 and 1.82.8 were malicious releases and are excluded.
|
|
26
|
+
dependencies = ["haystack-ai>=2.24.1", "litellm>=1.60.0,<2.0,!=1.82.7,!=1.82.8"]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/litellm#readme"
|
|
30
|
+
Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
|
|
31
|
+
Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/litellm"
|
|
32
|
+
|
|
33
|
+
[tool.hatch.build.targets.wheel]
|
|
34
|
+
packages = ["src/haystack_integrations"]
|
|
35
|
+
|
|
36
|
+
[tool.hatch.version]
|
|
37
|
+
source = "vcs"
|
|
38
|
+
tag-pattern = 'integrations\/litellm-v(?P<version>.*)'
|
|
39
|
+
|
|
40
|
+
[tool.hatch.version.raw-options]
|
|
41
|
+
root = "../.."
|
|
42
|
+
git_describe_command = 'git describe --tags --match="integrations/litellm-v[0-9]*"'
|
|
43
|
+
|
|
44
|
+
[tool.hatch.envs.default]
|
|
45
|
+
installer = "uv"
|
|
46
|
+
dependencies = ["haystack-pydoc-tools", "ruff"]
|
|
47
|
+
|
|
48
|
+
[tool.hatch.envs.default.scripts]
|
|
49
|
+
docs = ["haystack-pydoc pydoc/config_docusaurus.yml"]
|
|
50
|
+
fmt = "ruff check --fix {args}; ruff format {args}"
|
|
51
|
+
fmt-check = "ruff check {args} && ruff format --check {args}"
|
|
52
|
+
|
|
53
|
+
[tool.hatch.envs.test]
|
|
54
|
+
dependencies = [
|
|
55
|
+
"pytest",
|
|
56
|
+
"pytest-asyncio",
|
|
57
|
+
"pytest-cov",
|
|
58
|
+
"pytest-rerunfailures",
|
|
59
|
+
"mypy",
|
|
60
|
+
"pip",
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
[tool.hatch.envs.test.scripts]
|
|
64
|
+
unit = 'pytest -m "not integration" {args:tests}'
|
|
65
|
+
integration = 'pytest -m "integration" {args:tests}'
|
|
66
|
+
all = 'pytest {args:tests}'
|
|
67
|
+
unit-cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x -m "not integration" {args:tests}'
|
|
68
|
+
integration-cov-append-retry = 'pytest --cov=haystack_integrations --cov-append --reruns 3 --reruns-delay 30 -x -m "integration" {args:tests}'
|
|
69
|
+
types = "mypy -p haystack_integrations.components.generators.litellm {args}"
|
|
70
|
+
|
|
71
|
+
[tool.mypy]
|
|
72
|
+
install_types = true
|
|
73
|
+
non_interactive = true
|
|
74
|
+
check_untyped_defs = true
|
|
75
|
+
disallow_incomplete_defs = true
|
|
76
|
+
|
|
77
|
+
[tool.ruff]
|
|
78
|
+
line-length = 120
|
|
79
|
+
|
|
80
|
+
[tool.ruff.lint]
|
|
81
|
+
select = ["A", "B", "E", "F", "I", "N", "Q", "RUF", "S", "T", "UP", "W"]
|
|
82
|
+
ignore = ["T201", "B027", "S105", "S106", "S107"]
|
|
83
|
+
|
|
84
|
+
[tool.ruff.lint.isort]
|
|
85
|
+
known-first-party = ["haystack_integrations"]
|
|
86
|
+
|
|
87
|
+
[tool.ruff.lint.per-file-ignores]
|
|
88
|
+
"tests/**/*" = ["S101", "D", "ANN"]
|
|
89
|
+
|
|
90
|
+
[tool.coverage.run]
|
|
91
|
+
source = ["haystack_integrations"]
|
|
92
|
+
branch = true
|
|
93
|
+
relative_files = true
|
|
94
|
+
parallel = true
|
|
95
|
+
|
|
96
|
+
[tool.coverage.report]
|
|
97
|
+
omit = ["*/tests/*", "*/__init__.py"]
|
|
98
|
+
show_missing = true
|
|
99
|
+
exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
|
|
100
|
+
|
|
101
|
+
[tool.pytest.ini_options]
|
|
102
|
+
addopts = "--strict-markers"
|
|
103
|
+
asyncio_default_fixture_loop_scope = "class"
|
|
104
|
+
asyncio_mode = "auto"
|
|
105
|
+
markers = ["unit: unit tests", "integration: integration tests", "asyncio: mark a test as an asyncio coroutine"]
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2025-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from haystack import component, default_from_dict, default_to_dict, logging
|
|
9
|
+
from haystack.components.generators.utils import _convert_streaming_chunks_to_chat_message
|
|
10
|
+
from haystack.dataclasses import ChatMessage, ToolCall
|
|
11
|
+
from haystack.dataclasses.streaming_chunk import (
|
|
12
|
+
AsyncStreamingCallbackT,
|
|
13
|
+
ComponentInfo,
|
|
14
|
+
FinishReason,
|
|
15
|
+
StreamingCallbackT,
|
|
16
|
+
StreamingChunk,
|
|
17
|
+
SyncStreamingCallbackT,
|
|
18
|
+
ToolCallDelta,
|
|
19
|
+
select_streaming_callback,
|
|
20
|
+
)
|
|
21
|
+
from haystack.tools import (
|
|
22
|
+
ToolsType,
|
|
23
|
+
_check_duplicate_tool_names,
|
|
24
|
+
deserialize_tools_or_toolset_inplace,
|
|
25
|
+
flatten_tools_or_toolsets,
|
|
26
|
+
serialize_tools_or_toolset,
|
|
27
|
+
)
|
|
28
|
+
from haystack.utils.auth import Secret, deserialize_secrets_inplace
|
|
29
|
+
from haystack.utils.callable_serialization import deserialize_callable, serialize_callable
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@component
|
|
35
|
+
class LiteLLMChatGenerator:
|
|
36
|
+
"""Completes chats using any of 100+ LLM providers via LiteLLM.
|
|
37
|
+
|
|
38
|
+
LiteLLM routes to OpenAI, Anthropic, Google, AWS Bedrock, Azure, Cohere,
|
|
39
|
+
Mistral, Groq, and many more through a single unified interface.
|
|
40
|
+
|
|
41
|
+
Model names use LiteLLM format: ``provider/model-name``, e.g.
|
|
42
|
+
``anthropic/claude-sonnet-4-20250514``, ``openai/gpt-4o``,
|
|
43
|
+
``bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0``.
|
|
44
|
+
|
|
45
|
+
See https://docs.litellm.ai/docs/providers for the full list.
|
|
46
|
+
|
|
47
|
+
Usage example:
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from haystack_integrations.components.generators.litellm import LiteLLMChatGenerator
|
|
51
|
+
from haystack.dataclasses import ChatMessage
|
|
52
|
+
|
|
53
|
+
generator = LiteLLMChatGenerator(
|
|
54
|
+
model="anthropic/claude-sonnet-4-20250514",
|
|
55
|
+
generation_kwargs={"max_tokens": 1024, "temperature": 0.7},
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
messages = [
|
|
59
|
+
ChatMessage.from_system("You are a helpful assistant"),
|
|
60
|
+
ChatMessage.from_user("What's Natural Language Processing?"),
|
|
61
|
+
]
|
|
62
|
+
result = generator.run(messages=messages)
|
|
63
|
+
print(result["replies"][0].text)
|
|
64
|
+
```
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
*,
|
|
70
|
+
api_key: Secret | None = None,
|
|
71
|
+
model: str = "openai/gpt-4o",
|
|
72
|
+
streaming_callback: StreamingCallbackT | None = None,
|
|
73
|
+
api_base_url: str | None = None,
|
|
74
|
+
generation_kwargs: dict[str, Any] | None = None,
|
|
75
|
+
tools: ToolsType | None = None,
|
|
76
|
+
) -> None:
|
|
77
|
+
"""Create a LiteLLMChatGenerator instance.
|
|
78
|
+
|
|
79
|
+
:param api_key:
|
|
80
|
+
The API key for the provider. Optional: when not set, LiteLLM resolves
|
|
81
|
+
credentials itself from the provider's standard environment variable
|
|
82
|
+
(e.g. ``ANTHROPIC_API_KEY``, ``OPENAI_API_KEY``). Pass a ``Secret`` only
|
|
83
|
+
when you want Haystack to manage and serialize the key explicitly.
|
|
84
|
+
:param model:
|
|
85
|
+
The model name in LiteLLM format (provider/model-name).
|
|
86
|
+
:param streaming_callback:
|
|
87
|
+
A callback function invoked with each new StreamingChunk.
|
|
88
|
+
:param api_base_url:
|
|
89
|
+
Custom API base URL (e.g. for a self-hosted LiteLLM proxy).
|
|
90
|
+
:param generation_kwargs:
|
|
91
|
+
Additional parameters passed to litellm.completion().
|
|
92
|
+
See https://docs.litellm.ai/docs/completion/input for details.
|
|
93
|
+
:param tools:
|
|
94
|
+
A list of Tool / Toolset objects the model can prepare calls for.
|
|
95
|
+
"""
|
|
96
|
+
self.model = model
|
|
97
|
+
self.api_key = api_key
|
|
98
|
+
self.streaming_callback = streaming_callback
|
|
99
|
+
self.api_base_url = api_base_url
|
|
100
|
+
self.generation_kwargs = generation_kwargs or {}
|
|
101
|
+
self.tools = tools
|
|
102
|
+
|
|
103
|
+
def _build_litellm_kwargs(
|
|
104
|
+
self,
|
|
105
|
+
messages: list[ChatMessage],
|
|
106
|
+
streaming_callback: StreamingCallbackT | None,
|
|
107
|
+
generation_kwargs: dict[str, Any] | None,
|
|
108
|
+
tools: ToolsType | None,
|
|
109
|
+
) -> dict[str, Any]:
|
|
110
|
+
merged_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})}
|
|
111
|
+
openai_messages = [m.to_openai_dict_format() for m in messages]
|
|
112
|
+
|
|
113
|
+
extra: dict[str, Any] = {}
|
|
114
|
+
if self.api_key:
|
|
115
|
+
extra["api_key"] = self.api_key.resolve_value()
|
|
116
|
+
if self.api_base_url:
|
|
117
|
+
extra["api_base"] = self.api_base_url
|
|
118
|
+
|
|
119
|
+
flattened_tools = flatten_tools_or_toolsets(tools or self.tools)
|
|
120
|
+
_check_duplicate_tool_names(flattened_tools)
|
|
121
|
+
tool_defs = None
|
|
122
|
+
if flattened_tools:
|
|
123
|
+
tool_defs = [{"type": "function", "function": t.tool_spec} for t in flattened_tools]
|
|
124
|
+
|
|
125
|
+
# User-supplied generation_kwargs go first so the framework-controlled keys below
|
|
126
|
+
# (model, messages, stream, tools, drop_params, credentials) always take precedence
|
|
127
|
+
# and can't be silently overridden.
|
|
128
|
+
return {
|
|
129
|
+
**merged_kwargs,
|
|
130
|
+
"model": self.model,
|
|
131
|
+
"messages": openai_messages,
|
|
132
|
+
"stream": streaming_callback is not None,
|
|
133
|
+
"tools": tool_defs,
|
|
134
|
+
"drop_params": True,
|
|
135
|
+
**extra,
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
@component.output_types(replies=list[ChatMessage])
|
|
139
|
+
def run(
|
|
140
|
+
self,
|
|
141
|
+
messages: list[ChatMessage],
|
|
142
|
+
streaming_callback: StreamingCallbackT | None = None,
|
|
143
|
+
generation_kwargs: dict[str, Any] | None = None,
|
|
144
|
+
*,
|
|
145
|
+
tools: ToolsType | None = None,
|
|
146
|
+
) -> dict[str, list[ChatMessage]]:
|
|
147
|
+
"""Invoke chat completion via LiteLLM.
|
|
148
|
+
|
|
149
|
+
:param messages: Input messages as ChatMessage instances.
|
|
150
|
+
:param streaming_callback: Override the streaming callback for this call.
|
|
151
|
+
:param generation_kwargs: Override generation parameters for this call.
|
|
152
|
+
:param tools: Override tools for this call.
|
|
153
|
+
:returns: A dict with key ``replies`` containing ChatMessage instances.
|
|
154
|
+
"""
|
|
155
|
+
if not messages:
|
|
156
|
+
return {"replies": []}
|
|
157
|
+
|
|
158
|
+
import litellm
|
|
159
|
+
|
|
160
|
+
streaming_callback = select_streaming_callback(
|
|
161
|
+
init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=False
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
kwargs = self._build_litellm_kwargs(messages, streaming_callback, generation_kwargs, tools)
|
|
165
|
+
response = litellm.completion(**kwargs)
|
|
166
|
+
|
|
167
|
+
if streaming_callback is not None:
|
|
168
|
+
return {"replies": self._handle_streaming(response, streaming_callback)}
|
|
169
|
+
|
|
170
|
+
completions = [_build_chat_message(response, choice) for choice in response.choices]
|
|
171
|
+
return {"replies": completions}
|
|
172
|
+
|
|
173
|
+
@component.output_types(replies=list[ChatMessage])
|
|
174
|
+
async def run_async(
|
|
175
|
+
self,
|
|
176
|
+
messages: list[ChatMessage],
|
|
177
|
+
streaming_callback: StreamingCallbackT | None = None,
|
|
178
|
+
generation_kwargs: dict[str, Any] | None = None,
|
|
179
|
+
*,
|
|
180
|
+
tools: ToolsType | None = None,
|
|
181
|
+
) -> dict[str, list[ChatMessage]]:
|
|
182
|
+
"""Async version of run()."""
|
|
183
|
+
if not messages:
|
|
184
|
+
return {"replies": []}
|
|
185
|
+
|
|
186
|
+
import litellm
|
|
187
|
+
|
|
188
|
+
streaming_callback = select_streaming_callback(
|
|
189
|
+
init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=True
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
kwargs = self._build_litellm_kwargs(messages, streaming_callback, generation_kwargs, tools)
|
|
193
|
+
response = await litellm.acompletion(**kwargs)
|
|
194
|
+
|
|
195
|
+
if streaming_callback is not None:
|
|
196
|
+
return {"replies": await self._ahandle_streaming(response, streaming_callback)}
|
|
197
|
+
|
|
198
|
+
completions = [_build_chat_message(response, choice) for choice in response.choices]
|
|
199
|
+
return {"replies": completions}
|
|
200
|
+
|
|
201
|
+
def _handle_streaming(self, stream_response: Any, callback: SyncStreamingCallbackT) -> list[ChatMessage]:
|
|
202
|
+
component_info = ComponentInfo.from_component(self)
|
|
203
|
+
chunks: list[StreamingChunk] = []
|
|
204
|
+
for chunk in stream_response:
|
|
205
|
+
stream_chunk = _convert_litellm_chunk_to_streaming_chunk(chunk, chunks, component_info)
|
|
206
|
+
chunks.append(stream_chunk)
|
|
207
|
+
callback(stream_chunk)
|
|
208
|
+
return [_convert_streaming_chunks_to_chat_message(chunks=chunks)]
|
|
209
|
+
|
|
210
|
+
async def _ahandle_streaming(self, stream_response: Any, callback: AsyncStreamingCallbackT) -> list[ChatMessage]:
|
|
211
|
+
component_info = ComponentInfo.from_component(self)
|
|
212
|
+
chunks: list[StreamingChunk] = []
|
|
213
|
+
async for chunk in stream_response:
|
|
214
|
+
stream_chunk = _convert_litellm_chunk_to_streaming_chunk(chunk, chunks, component_info)
|
|
215
|
+
chunks.append(stream_chunk)
|
|
216
|
+
await callback(stream_chunk)
|
|
217
|
+
return [_convert_streaming_chunks_to_chat_message(chunks=chunks)]
|
|
218
|
+
|
|
219
|
+
def to_dict(self) -> dict[str, Any]:
|
|
220
|
+
"""Serialize this component to a dictionary."""
|
|
221
|
+
callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None
|
|
222
|
+
return default_to_dict(
|
|
223
|
+
self,
|
|
224
|
+
model=self.model,
|
|
225
|
+
api_key=self.api_key.to_dict() if self.api_key else None,
|
|
226
|
+
streaming_callback=callback_name,
|
|
227
|
+
api_base_url=self.api_base_url,
|
|
228
|
+
generation_kwargs=self.generation_kwargs,
|
|
229
|
+
tools=serialize_tools_or_toolset(self.tools),
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
@classmethod
|
|
233
|
+
def from_dict(cls, data: dict[str, Any]) -> "LiteLLMChatGenerator":
|
|
234
|
+
"""Deserialize a component from a dictionary."""
|
|
235
|
+
deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"])
|
|
236
|
+
deserialize_tools_or_toolset_inplace(data["init_parameters"], key="tools")
|
|
237
|
+
if data["init_parameters"].get("streaming_callback"):
|
|
238
|
+
data["init_parameters"]["streaming_callback"] = deserialize_callable(
|
|
239
|
+
data["init_parameters"]["streaming_callback"]
|
|
240
|
+
)
|
|
241
|
+
return default_from_dict(cls, data)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
# LiteLLM normalizes provider finish reasons to OpenAI's vocabulary, but we still map
|
|
245
|
+
# explicitly so the value matches Haystack's FinishReason literal.
|
|
246
|
+
_FINISH_REASON_MAPPING: dict[str, FinishReason] = {
|
|
247
|
+
"stop": "stop",
|
|
248
|
+
"length": "length",
|
|
249
|
+
"content_filter": "content_filter",
|
|
250
|
+
"tool_calls": "tool_calls",
|
|
251
|
+
"function_call": "tool_calls",
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _extract_usage(obj: Any) -> dict[str, int]:
|
|
256
|
+
"""Pull token usage off a litellm response or chunk, tolerating its absence."""
|
|
257
|
+
usage = getattr(obj, "usage", None)
|
|
258
|
+
if not usage:
|
|
259
|
+
return {}
|
|
260
|
+
return {
|
|
261
|
+
"prompt_tokens": getattr(usage, "prompt_tokens", 0),
|
|
262
|
+
"completion_tokens": getattr(usage, "completion_tokens", 0),
|
|
263
|
+
"total_tokens": getattr(usage, "total_tokens", 0),
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _build_chat_message(response: Any, choice: Any) -> ChatMessage:
|
|
268
|
+
"""Convert a single litellm choice into a haystack ChatMessage."""
|
|
269
|
+
message = choice.message
|
|
270
|
+
|
|
271
|
+
# Keep content as-is (None for tool-only replies) so we don't attach an empty text block,
|
|
272
|
+
# matching both Haystack's OpenAI generator and our own streaming aggregation.
|
|
273
|
+
text = message.content
|
|
274
|
+
|
|
275
|
+
tool_calls = []
|
|
276
|
+
if getattr(message, "tool_calls", None):
|
|
277
|
+
for tc in message.tool_calls:
|
|
278
|
+
arguments = tc.function.arguments
|
|
279
|
+
if isinstance(arguments, str):
|
|
280
|
+
try:
|
|
281
|
+
arguments = json.loads(arguments)
|
|
282
|
+
except json.JSONDecodeError:
|
|
283
|
+
logger.warning(
|
|
284
|
+
"The LLM provider returned a malformed JSON string for tool call arguments. This tool "
|
|
285
|
+
"call will be skipped. Tool call ID: {_id}, Tool name: {_name}, Arguments: {_arguments}",
|
|
286
|
+
_id=tc.id,
|
|
287
|
+
_name=tc.function.name,
|
|
288
|
+
_arguments=arguments,
|
|
289
|
+
)
|
|
290
|
+
continue
|
|
291
|
+
tool_calls.append(ToolCall(tool_name=tc.function.name, arguments=arguments, id=tc.id))
|
|
292
|
+
|
|
293
|
+
meta: dict[str, Any] = {
|
|
294
|
+
"model": response.model,
|
|
295
|
+
"index": choice.index,
|
|
296
|
+
"finish_reason": choice.finish_reason,
|
|
297
|
+
"usage": _extract_usage(response),
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
return ChatMessage.from_assistant(text=text, tool_calls=tool_calls, meta=meta)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _convert_litellm_chunk_to_streaming_chunk(
|
|
304
|
+
chunk: Any, previous_chunks: list[StreamingChunk], component_info: ComponentInfo
|
|
305
|
+
) -> StreamingChunk:
|
|
306
|
+
"""Convert a single litellm streaming chunk into a Haystack ``StreamingChunk``.
|
|
307
|
+
|
|
308
|
+
The structured fields (``tool_calls``, ``finish_reason``, ``index``) are populated so that
|
|
309
|
+
``_convert_streaming_chunks_to_chat_message`` can reconstruct tool calls and metadata; it reads
|
|
310
|
+
those fields, not ``meta``. LiteLLM returns OpenAI-compatible chunks, but unlike the OpenAI SDK
|
|
311
|
+
its chunk objects don't always expose a ``usage`` attribute, so it is accessed defensively.
|
|
312
|
+
"""
|
|
313
|
+
usage = _extract_usage(chunk) or None
|
|
314
|
+
|
|
315
|
+
# Final usage-only chunk: no choices, just aggregate token counts.
|
|
316
|
+
if not chunk.choices:
|
|
317
|
+
return StreamingChunk(
|
|
318
|
+
content="",
|
|
319
|
+
component_info=component_info,
|
|
320
|
+
index=None,
|
|
321
|
+
finish_reason=None,
|
|
322
|
+
meta={"model": chunk.model, "usage": usage},
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
choice = chunk.choices[0]
|
|
326
|
+
delta = choice.delta
|
|
327
|
+
finish_reason = _FINISH_REASON_MAPPING.get(choice.finish_reason) if choice.finish_reason else None
|
|
328
|
+
meta: dict[str, Any] = {
|
|
329
|
+
"model": chunk.model,
|
|
330
|
+
"index": choice.index,
|
|
331
|
+
"finish_reason": choice.finish_reason,
|
|
332
|
+
"usage": usage,
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
tool_calls = getattr(delta, "tool_calls", None) if delta else None
|
|
336
|
+
if tool_calls:
|
|
337
|
+
tool_call_deltas = []
|
|
338
|
+
for tc in tool_calls:
|
|
339
|
+
function = tc.function
|
|
340
|
+
tool_call_deltas.append(
|
|
341
|
+
ToolCallDelta(
|
|
342
|
+
index=tc.index,
|
|
343
|
+
id=tc.id,
|
|
344
|
+
tool_name=function.name if function else None,
|
|
345
|
+
arguments=function.arguments if function and function.arguments else None,
|
|
346
|
+
)
|
|
347
|
+
)
|
|
348
|
+
return StreamingChunk(
|
|
349
|
+
content=(delta.content or "") if delta else "",
|
|
350
|
+
component_info=component_info,
|
|
351
|
+
# ToolCallDelta requires an index; adopt the first one as the chunk index.
|
|
352
|
+
index=tool_call_deltas[0].index,
|
|
353
|
+
tool_calls=tool_call_deltas,
|
|
354
|
+
start=tool_call_deltas[0].tool_name is not None,
|
|
355
|
+
finish_reason=finish_reason,
|
|
356
|
+
meta=meta,
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
content = (delta.content or "") if delta else ""
|
|
360
|
+
# The opening chunk only carries role info (no content), so it isn't a content block.
|
|
361
|
+
role = getattr(delta, "role", None) if delta else None
|
|
362
|
+
resolved_index = None if (delta is None or delta.content is None or role is not None) else 0
|
|
363
|
+
|
|
364
|
+
return StreamingChunk(
|
|
365
|
+
content=content,
|
|
366
|
+
component_info=component_info,
|
|
367
|
+
index=resolved_index,
|
|
368
|
+
start=len(previous_chunks) == 1,
|
|
369
|
+
finish_reason=finish_reason,
|
|
370
|
+
meta=meta,
|
|
371
|
+
)
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2025-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import types
|
|
8
|
+
from types import SimpleNamespace
|
|
9
|
+
from unittest import mock
|
|
10
|
+
from unittest.mock import MagicMock
|
|
11
|
+
|
|
12
|
+
import pytest
|
|
13
|
+
from haystack.dataclasses import ChatMessage, StreamingChunk
|
|
14
|
+
from haystack.tools import Tool
|
|
15
|
+
from haystack.utils.auth import Secret
|
|
16
|
+
|
|
17
|
+
from haystack_integrations.components.generators.litellm import LiteLLMChatGenerator
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _make_mock_response(content="Hello!", model="openai/gpt-4o", tool_calls=None):
|
|
21
|
+
"""Build a mock litellm ModelResponse."""
|
|
22
|
+
msg = MagicMock()
|
|
23
|
+
msg.content = content
|
|
24
|
+
msg.role = "assistant"
|
|
25
|
+
msg.tool_calls = tool_calls
|
|
26
|
+
|
|
27
|
+
choice = MagicMock()
|
|
28
|
+
choice.message = msg
|
|
29
|
+
choice.index = 0
|
|
30
|
+
choice.finish_reason = "stop"
|
|
31
|
+
|
|
32
|
+
usage = MagicMock()
|
|
33
|
+
usage.prompt_tokens = 10
|
|
34
|
+
usage.completion_tokens = 5
|
|
35
|
+
usage.total_tokens = 15
|
|
36
|
+
|
|
37
|
+
resp = MagicMock()
|
|
38
|
+
resp.choices = [choice]
|
|
39
|
+
resp.usage = usage
|
|
40
|
+
resp.model = model
|
|
41
|
+
return resp
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _delta(content=None, role=None, tool_calls=None):
|
|
45
|
+
"""Build a litellm-like streaming delta with explicit attributes.
|
|
46
|
+
|
|
47
|
+
We use SimpleNamespace rather than MagicMock so that unset attributes behave
|
|
48
|
+
like a real litellm delta (absent/None) instead of returning truthy mocks.
|
|
49
|
+
"""
|
|
50
|
+
return SimpleNamespace(content=content, role=role, tool_calls=tool_calls)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _stream_chunk(choices, model="openai/gpt-4o", usage=None):
|
|
54
|
+
return SimpleNamespace(choices=choices, model=model, usage=usage)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _stream_choice(delta, finish_reason=None, index=0):
|
|
58
|
+
return SimpleNamespace(delta=delta, finish_reason=finish_reason, index=index)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _make_mock_stream_chunks(content="Hello!", usage=None):
|
|
62
|
+
"""Build mock streaming chunks for a plain text completion."""
|
|
63
|
+
chunks = [_stream_chunk([_stream_choice(_delta(role="assistant", content=None))])]
|
|
64
|
+
for char in content:
|
|
65
|
+
chunks.append(_stream_chunk([_stream_choice(_delta(content=char))]))
|
|
66
|
+
# Final content chunk carrying the finish reason.
|
|
67
|
+
chunks.append(_stream_chunk([_stream_choice(_delta(content=None), finish_reason="stop")]))
|
|
68
|
+
if usage is not None:
|
|
69
|
+
# Providers commonly send a trailing usage-only chunk with empty choices.
|
|
70
|
+
chunks.append(_stream_chunk([], usage=usage))
|
|
71
|
+
return chunks
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _tool_call_chunk_delta(index, call_id=None, name=None, arguments=None):
|
|
75
|
+
function = SimpleNamespace(name=name, arguments=arguments)
|
|
76
|
+
return SimpleNamespace(index=index, id=call_id, function=function)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class TestLiteLLMChatGeneratorInit:
|
|
80
|
+
def test_default_init(self):
|
|
81
|
+
gen = LiteLLMChatGenerator()
|
|
82
|
+
assert gen.model == "openai/gpt-4o"
|
|
83
|
+
assert gen.api_key is None
|
|
84
|
+
assert gen.streaming_callback is None
|
|
85
|
+
assert gen.api_base_url is None
|
|
86
|
+
assert gen.generation_kwargs == {}
|
|
87
|
+
|
|
88
|
+
def test_init_with_params(self):
|
|
89
|
+
gen = LiteLLMChatGenerator(
|
|
90
|
+
model="anthropic/claude-sonnet-4-20250514",
|
|
91
|
+
api_key=Secret.from_token("sk-test"),
|
|
92
|
+
api_base_url="https://proxy.local",
|
|
93
|
+
generation_kwargs={"temperature": 0.5, "max_tokens": 100},
|
|
94
|
+
)
|
|
95
|
+
assert gen.model == "anthropic/claude-sonnet-4-20250514"
|
|
96
|
+
assert gen.api_key.resolve_value() == "sk-test"
|
|
97
|
+
assert gen.api_base_url == "https://proxy.local"
|
|
98
|
+
assert gen.generation_kwargs["temperature"] == 0.5
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class TestSerialization:
|
|
102
|
+
def test_to_dict(self):
|
|
103
|
+
gen = LiteLLMChatGenerator(
|
|
104
|
+
model="openai/gpt-4o",
|
|
105
|
+
generation_kwargs={"temperature": 0.7},
|
|
106
|
+
)
|
|
107
|
+
d = gen.to_dict()
|
|
108
|
+
assert d["init_parameters"]["model"] == "openai/gpt-4o"
|
|
109
|
+
assert d["init_parameters"]["generation_kwargs"]["temperature"] == 0.7
|
|
110
|
+
|
|
111
|
+
def test_from_dict(self):
|
|
112
|
+
d = {
|
|
113
|
+
"type": "haystack_integrations.components.generators.litellm.chat.chat_generator.LiteLLMChatGenerator",
|
|
114
|
+
"init_parameters": {
|
|
115
|
+
"model": "anthropic/claude-sonnet-4-20250514",
|
|
116
|
+
"api_key": None,
|
|
117
|
+
"streaming_callback": None,
|
|
118
|
+
"api_base_url": None,
|
|
119
|
+
"generation_kwargs": {"max_tokens": 200},
|
|
120
|
+
"tools": None,
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
gen = LiteLLMChatGenerator.from_dict(d)
|
|
124
|
+
assert gen.model == "anthropic/claude-sonnet-4-20250514"
|
|
125
|
+
assert gen.generation_kwargs["max_tokens"] == 200
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@pytest.mark.unit
|
|
129
|
+
class TestRun:
|
|
130
|
+
def test_basic_completion(self):
|
|
131
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o")
|
|
132
|
+
mock_resp = _make_mock_response("The capital is Paris.")
|
|
133
|
+
|
|
134
|
+
fake_litellm = types.ModuleType("litellm")
|
|
135
|
+
fake_litellm.completion = MagicMock(return_value=mock_resp)
|
|
136
|
+
|
|
137
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
138
|
+
messages = [ChatMessage.from_user("What's the capital of France?")]
|
|
139
|
+
result = gen.run(messages=messages)
|
|
140
|
+
|
|
141
|
+
assert len(result["replies"]) == 1
|
|
142
|
+
assert result["replies"][0].text == "The capital is Paris."
|
|
143
|
+
fake_litellm.completion.assert_called_once()
|
|
144
|
+
|
|
145
|
+
def test_drop_params_always_set(self):
|
|
146
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o")
|
|
147
|
+
mock_resp = _make_mock_response()
|
|
148
|
+
|
|
149
|
+
fake_litellm = types.ModuleType("litellm")
|
|
150
|
+
fake_litellm.completion = MagicMock(return_value=mock_resp)
|
|
151
|
+
|
|
152
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
153
|
+
gen.run(messages=[ChatMessage.from_user("hi")])
|
|
154
|
+
call_kwargs = fake_litellm.completion.call_args
|
|
155
|
+
assert call_kwargs.kwargs["drop_params"] is True
|
|
156
|
+
|
|
157
|
+
def test_api_key_forwarded(self):
|
|
158
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o", api_key=Secret.from_token("sk-test123"))
|
|
159
|
+
mock_resp = _make_mock_response()
|
|
160
|
+
|
|
161
|
+
fake_litellm = types.ModuleType("litellm")
|
|
162
|
+
fake_litellm.completion = MagicMock(return_value=mock_resp)
|
|
163
|
+
|
|
164
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
165
|
+
gen.run(messages=[ChatMessage.from_user("hi")])
|
|
166
|
+
call_kwargs = fake_litellm.completion.call_args
|
|
167
|
+
assert call_kwargs.kwargs["api_key"] == "sk-test123"
|
|
168
|
+
|
|
169
|
+
def test_api_key_omitted_when_none(self):
|
|
170
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o")
|
|
171
|
+
mock_resp = _make_mock_response()
|
|
172
|
+
|
|
173
|
+
fake_litellm = types.ModuleType("litellm")
|
|
174
|
+
fake_litellm.completion = MagicMock(return_value=mock_resp)
|
|
175
|
+
|
|
176
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
177
|
+
gen.run(messages=[ChatMessage.from_user("hi")])
|
|
178
|
+
call_kwargs = fake_litellm.completion.call_args
|
|
179
|
+
assert "api_key" not in call_kwargs.kwargs
|
|
180
|
+
|
|
181
|
+
def test_base_url_forwarded(self):
|
|
182
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o", api_base_url="https://proxy.local")
|
|
183
|
+
mock_resp = _make_mock_response()
|
|
184
|
+
|
|
185
|
+
fake_litellm = types.ModuleType("litellm")
|
|
186
|
+
fake_litellm.completion = MagicMock(return_value=mock_resp)
|
|
187
|
+
|
|
188
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
189
|
+
gen.run(messages=[ChatMessage.from_user("hi")])
|
|
190
|
+
call_kwargs = fake_litellm.completion.call_args
|
|
191
|
+
assert call_kwargs.kwargs["api_base"] == "https://proxy.local"
|
|
192
|
+
|
|
193
|
+
def test_generation_kwargs_merged(self):
|
|
194
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o", generation_kwargs={"temperature": 0.5})
|
|
195
|
+
mock_resp = _make_mock_response()
|
|
196
|
+
|
|
197
|
+
fake_litellm = types.ModuleType("litellm")
|
|
198
|
+
fake_litellm.completion = MagicMock(return_value=mock_resp)
|
|
199
|
+
|
|
200
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
201
|
+
gen.run(messages=[ChatMessage.from_user("hi")], generation_kwargs={"max_tokens": 100})
|
|
202
|
+
call_kwargs = fake_litellm.completion.call_args
|
|
203
|
+
assert call_kwargs.kwargs["temperature"] == 0.5
|
|
204
|
+
assert call_kwargs.kwargs["max_tokens"] == 100
|
|
205
|
+
|
|
206
|
+
def test_empty_messages_returns_empty(self):
|
|
207
|
+
gen = LiteLLMChatGenerator()
|
|
208
|
+
result = gen.run(messages=[])
|
|
209
|
+
assert result == {"replies": []}
|
|
210
|
+
|
|
211
|
+
def test_usage_in_meta(self):
|
|
212
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o")
|
|
213
|
+
mock_resp = _make_mock_response()
|
|
214
|
+
|
|
215
|
+
fake_litellm = types.ModuleType("litellm")
|
|
216
|
+
fake_litellm.completion = MagicMock(return_value=mock_resp)
|
|
217
|
+
|
|
218
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
219
|
+
result = gen.run(messages=[ChatMessage.from_user("hi")])
|
|
220
|
+
meta = result["replies"][0].meta
|
|
221
|
+
assert meta["usage"]["prompt_tokens"] == 10
|
|
222
|
+
assert meta["usage"]["completion_tokens"] == 5
|
|
223
|
+
|
|
224
|
+
def test_tool_calls_parsed(self):
|
|
225
|
+
tc = MagicMock()
|
|
226
|
+
tc.id = "call_123"
|
|
227
|
+
tc.function.name = "get_weather"
|
|
228
|
+
tc.function.arguments = '{"city": "Paris"}'
|
|
229
|
+
|
|
230
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o")
|
|
231
|
+
mock_resp = _make_mock_response(content="", tool_calls=[tc])
|
|
232
|
+
|
|
233
|
+
fake_litellm = types.ModuleType("litellm")
|
|
234
|
+
fake_litellm.completion = MagicMock(return_value=mock_resp)
|
|
235
|
+
|
|
236
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
237
|
+
result = gen.run(messages=[ChatMessage.from_user("weather?")])
|
|
238
|
+
reply = result["replies"][0]
|
|
239
|
+
assert reply.tool_calls is not None
|
|
240
|
+
assert len(reply.tool_calls) == 1
|
|
241
|
+
assert reply.tool_calls[0].tool_name == "get_weather"
|
|
242
|
+
assert reply.tool_calls[0].arguments == {"city": "Paris"}
|
|
243
|
+
|
|
244
|
+
def test_streaming_content_accumulated(self):
|
|
245
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o")
|
|
246
|
+
usage = SimpleNamespace(prompt_tokens=10, completion_tokens=5, total_tokens=15)
|
|
247
|
+
chunks = _make_mock_stream_chunks("Hi!", usage=usage)
|
|
248
|
+
|
|
249
|
+
fake_litellm = types.ModuleType("litellm")
|
|
250
|
+
fake_litellm.completion = MagicMock(return_value=iter(chunks))
|
|
251
|
+
|
|
252
|
+
collected = []
|
|
253
|
+
|
|
254
|
+
def callback(chunk: StreamingChunk) -> None:
|
|
255
|
+
collected.append(chunk)
|
|
256
|
+
|
|
257
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
258
|
+
result = gen.run(messages=[ChatMessage.from_user("hi")], streaming_callback=callback)
|
|
259
|
+
assert len(collected) > 0
|
|
260
|
+
assert len(result["replies"]) == 1
|
|
261
|
+
|
|
262
|
+
full_text = "".join(c.content for c in collected)
|
|
263
|
+
assert "Hi!" in full_text
|
|
264
|
+
|
|
265
|
+
# finish_reason and usage must survive aggregation, not just the streamed text.
|
|
266
|
+
reply = result["replies"][0]
|
|
267
|
+
assert reply.text == "Hi!"
|
|
268
|
+
assert reply.meta["finish_reason"] == "stop"
|
|
269
|
+
assert reply.meta["usage"]["prompt_tokens"] == 10
|
|
270
|
+
assert reply.meta["usage"]["total_tokens"] == 15
|
|
271
|
+
|
|
272
|
+
def test_streaming_tool_calls_reconstructed(self):
|
|
273
|
+
# Tool call arguments stream across multiple chunks and must be reassembled.
|
|
274
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o")
|
|
275
|
+
chunks = [
|
|
276
|
+
_stream_chunk([_stream_choice(_delta(role="assistant", content=None))]),
|
|
277
|
+
_stream_chunk(
|
|
278
|
+
[
|
|
279
|
+
_stream_choice(
|
|
280
|
+
_delta(tool_calls=[_tool_call_chunk_delta(index=0, call_id="call_1", name="get_weather")])
|
|
281
|
+
)
|
|
282
|
+
]
|
|
283
|
+
),
|
|
284
|
+
_stream_chunk(
|
|
285
|
+
[_stream_choice(_delta(tool_calls=[_tool_call_chunk_delta(index=0, arguments='{"city": ')]))]
|
|
286
|
+
),
|
|
287
|
+
_stream_chunk([_stream_choice(_delta(tool_calls=[_tool_call_chunk_delta(index=0, arguments='"Paris"}')]))]),
|
|
288
|
+
_stream_chunk([_stream_choice(_delta(content=None), finish_reason="tool_calls")]),
|
|
289
|
+
]
|
|
290
|
+
|
|
291
|
+
fake_litellm = types.ModuleType("litellm")
|
|
292
|
+
fake_litellm.completion = MagicMock(return_value=iter(chunks))
|
|
293
|
+
|
|
294
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
295
|
+
result = gen.run(messages=[ChatMessage.from_user("weather in Paris?")], streaming_callback=lambda _c: None)
|
|
296
|
+
reply = result["replies"][0]
|
|
297
|
+
assert reply.tool_calls is not None
|
|
298
|
+
assert len(reply.tool_calls) == 1
|
|
299
|
+
assert reply.tool_calls[0].id == "call_1"
|
|
300
|
+
assert reply.tool_calls[0].tool_name == "get_weather"
|
|
301
|
+
assert reply.tool_calls[0].arguments == {"city": "Paris"}
|
|
302
|
+
assert reply.meta["finish_reason"] == "tool_calls"
|
|
303
|
+
|
|
304
|
+
def test_generation_kwargs_runtime_overrides_init(self):
|
|
305
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o", generation_kwargs={"temperature": 0.5})
|
|
306
|
+
mock_resp = _make_mock_response()
|
|
307
|
+
fake_litellm = types.ModuleType("litellm")
|
|
308
|
+
fake_litellm.completion = MagicMock(return_value=mock_resp)
|
|
309
|
+
|
|
310
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
311
|
+
gen.run(messages=[ChatMessage.from_user("hi")], generation_kwargs={"temperature": 0.9})
|
|
312
|
+
call_kwargs = fake_litellm.completion.call_args
|
|
313
|
+
assert call_kwargs.kwargs["temperature"] == 0.9
|
|
314
|
+
|
|
315
|
+
def test_none_content_in_response(self):
|
|
316
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o")
|
|
317
|
+
mock_resp = _make_mock_response(content=None)
|
|
318
|
+
fake_litellm = types.ModuleType("litellm")
|
|
319
|
+
fake_litellm.completion = MagicMock(return_value=mock_resp)
|
|
320
|
+
|
|
321
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
322
|
+
result = gen.run(messages=[ChatMessage.from_user("hi")])
|
|
323
|
+
# None content yields no text block (matching the OpenAI generator), not an empty string.
|
|
324
|
+
assert result["replies"][0].text is None
|
|
325
|
+
|
|
326
|
+
def test_malformed_tool_call_arguments_skipped(self):
|
|
327
|
+
tc = MagicMock()
|
|
328
|
+
tc.id = "call_bad"
|
|
329
|
+
tc.function.name = "get_weather"
|
|
330
|
+
tc.function.arguments = "{not valid json"
|
|
331
|
+
|
|
332
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o")
|
|
333
|
+
mock_resp = _make_mock_response(content=None, tool_calls=[tc])
|
|
334
|
+
|
|
335
|
+
fake_litellm = types.ModuleType("litellm")
|
|
336
|
+
fake_litellm.completion = MagicMock(return_value=mock_resp)
|
|
337
|
+
|
|
338
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
339
|
+
result = gen.run(messages=[ChatMessage.from_user("weather?")])
|
|
340
|
+
# A tool call with unparseable arguments is dropped rather than passed through.
|
|
341
|
+
assert not result["replies"][0].tool_calls
|
|
342
|
+
|
|
343
|
+
def test_tools_sent_to_litellm(self):
|
|
344
|
+
def weather(city: str) -> str:
|
|
345
|
+
"""Get weather."""
|
|
346
|
+
return f"Sunny in {city}"
|
|
347
|
+
|
|
348
|
+
tool = Tool(
|
|
349
|
+
function=weather,
|
|
350
|
+
name="weather",
|
|
351
|
+
description="Get weather",
|
|
352
|
+
parameters={"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
|
|
353
|
+
)
|
|
354
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o", tools=[tool])
|
|
355
|
+
mock_resp = _make_mock_response()
|
|
356
|
+
|
|
357
|
+
fake_litellm = types.ModuleType("litellm")
|
|
358
|
+
fake_litellm.completion = MagicMock(return_value=mock_resp)
|
|
359
|
+
|
|
360
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
361
|
+
gen.run(messages=[ChatMessage.from_user("weather in Paris?")])
|
|
362
|
+
call_kwargs = fake_litellm.completion.call_args
|
|
363
|
+
assert call_kwargs.kwargs["tools"] is not None
|
|
364
|
+
assert len(call_kwargs.kwargs["tools"]) == 1
|
|
365
|
+
assert call_kwargs.kwargs["tools"][0]["function"]["name"] == "weather"
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
class TestSerializationRoundTrip:
|
|
369
|
+
def test_round_trip_basic(self):
|
|
370
|
+
gen = LiteLLMChatGenerator(
|
|
371
|
+
model="anthropic/claude-sonnet-4-20250514",
|
|
372
|
+
api_base_url="https://proxy.local",
|
|
373
|
+
generation_kwargs={"temperature": 0.8, "max_tokens": 200},
|
|
374
|
+
)
|
|
375
|
+
restored = LiteLLMChatGenerator.from_dict(gen.to_dict())
|
|
376
|
+
assert restored.model == gen.model
|
|
377
|
+
assert restored.api_base_url == gen.api_base_url
|
|
378
|
+
assert restored.generation_kwargs == gen.generation_kwargs
|
|
379
|
+
|
|
380
|
+
def test_round_trip_with_secret(self):
|
|
381
|
+
gen = LiteLLMChatGenerator(
|
|
382
|
+
model="openai/gpt-4o",
|
|
383
|
+
api_key=Secret.from_env_var("MY_TEST_KEY"),
|
|
384
|
+
)
|
|
385
|
+
d = gen.to_dict()
|
|
386
|
+
assert d["init_parameters"]["api_key"]["type"] == "env_var"
|
|
387
|
+
restored = LiteLLMChatGenerator.from_dict(d)
|
|
388
|
+
assert restored.api_key is not None
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
@pytest.mark.unit
|
|
392
|
+
class TestAsync:
|
|
393
|
+
@pytest.mark.asyncio
|
|
394
|
+
async def test_run_async_basic(self):
|
|
395
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o")
|
|
396
|
+
mock_resp = _make_mock_response("async reply")
|
|
397
|
+
|
|
398
|
+
fake_litellm = types.ModuleType("litellm")
|
|
399
|
+
|
|
400
|
+
async def _acompletion(**_kwargs):
|
|
401
|
+
return mock_resp
|
|
402
|
+
|
|
403
|
+
fake_litellm.acompletion = _acompletion
|
|
404
|
+
|
|
405
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
406
|
+
result = await gen.run_async(messages=[ChatMessage.from_user("hi")])
|
|
407
|
+
assert len(result["replies"]) == 1
|
|
408
|
+
assert result["replies"][0].text == "async reply"
|
|
409
|
+
|
|
410
|
+
@pytest.mark.asyncio
|
|
411
|
+
async def test_run_async_empty_messages(self):
|
|
412
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o")
|
|
413
|
+
result = await gen.run_async(messages=[])
|
|
414
|
+
assert result == {"replies": []}
|
|
415
|
+
|
|
416
|
+
@pytest.mark.asyncio
|
|
417
|
+
async def test_run_async_streaming(self):
|
|
418
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o")
|
|
419
|
+
usage = SimpleNamespace(prompt_tokens=10, completion_tokens=5, total_tokens=15)
|
|
420
|
+
chunks = _make_mock_stream_chunks("Hi!", usage=usage)
|
|
421
|
+
|
|
422
|
+
async def _aiter():
|
|
423
|
+
for chunk in chunks:
|
|
424
|
+
yield chunk
|
|
425
|
+
|
|
426
|
+
fake_litellm = types.ModuleType("litellm")
|
|
427
|
+
|
|
428
|
+
async def _acompletion(**_kwargs):
|
|
429
|
+
return _aiter()
|
|
430
|
+
|
|
431
|
+
fake_litellm.acompletion = _acompletion
|
|
432
|
+
|
|
433
|
+
collected = []
|
|
434
|
+
|
|
435
|
+
async def callback(chunk: StreamingChunk) -> None:
|
|
436
|
+
collected.append(chunk)
|
|
437
|
+
|
|
438
|
+
with mock.patch.dict(sys.modules, {"litellm": fake_litellm}):
|
|
439
|
+
result = await gen.run_async(messages=[ChatMessage.from_user("hi")], streaming_callback=callback)
|
|
440
|
+
assert len(collected) > 0
|
|
441
|
+
reply = result["replies"][0]
|
|
442
|
+
assert reply.text == "Hi!"
|
|
443
|
+
assert reply.meta["finish_reason"] == "stop"
|
|
444
|
+
assert reply.meta["usage"]["total_tokens"] == 15
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _weather_tool():
|
|
448
|
+
def get_weather(city: str) -> str:
|
|
449
|
+
"""Get the weather for a city."""
|
|
450
|
+
return f"Sunny in {city}"
|
|
451
|
+
|
|
452
|
+
return Tool(
|
|
453
|
+
function=get_weather,
|
|
454
|
+
name="get_weather",
|
|
455
|
+
description="Get the current weather for a given city.",
|
|
456
|
+
parameters={"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
@pytest.mark.integration
|
|
461
|
+
@pytest.mark.skipif(not os.environ.get("OPENAI_API_KEY"), reason="OPENAI_API_KEY not set")
|
|
462
|
+
class TestLiveIntegration:
|
|
463
|
+
def test_live_completion(self):
|
|
464
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o-mini", generation_kwargs={"max_tokens": 16})
|
|
465
|
+
result = gen.run(messages=[ChatMessage.from_user("Reply with the single word: OK")])
|
|
466
|
+
assert len(result["replies"]) == 1
|
|
467
|
+
assert result["replies"][0].text
|
|
468
|
+
assert result["replies"][0].meta["usage"]["total_tokens"] > 0
|
|
469
|
+
|
|
470
|
+
def test_live_streaming(self):
|
|
471
|
+
collected = []
|
|
472
|
+
|
|
473
|
+
def callback(chunk: StreamingChunk) -> None:
|
|
474
|
+
collected.append(chunk)
|
|
475
|
+
|
|
476
|
+
gen = LiteLLMChatGenerator(
|
|
477
|
+
model="openai/gpt-4o-mini",
|
|
478
|
+
streaming_callback=callback,
|
|
479
|
+
# Ask OpenAI to emit a trailing usage-only chunk so the no-choices branch is exercised.
|
|
480
|
+
generation_kwargs={"max_tokens": 32, "stream_options": {"include_usage": True}},
|
|
481
|
+
)
|
|
482
|
+
result = gen.run(messages=[ChatMessage.from_user("Count from 1 to 5, comma-separated.")])
|
|
483
|
+
|
|
484
|
+
assert len(collected) > 1 # genuinely streamed in multiple chunks
|
|
485
|
+
reply = result["replies"][0]
|
|
486
|
+
assert reply.text.strip()
|
|
487
|
+
assert reply.meta["finish_reason"] == "stop"
|
|
488
|
+
assert reply.meta["usage"]["total_tokens"] > 0
|
|
489
|
+
|
|
490
|
+
def test_live_tool_call(self):
|
|
491
|
+
gen = LiteLLMChatGenerator(model="openai/gpt-4o-mini", tools=[_weather_tool()])
|
|
492
|
+
result = gen.run(messages=[ChatMessage.from_user("What's the weather in Paris? Use the get_weather tool.")])
|
|
493
|
+
reply = result["replies"][0]
|
|
494
|
+
assert reply.tool_calls, "expected the model to request a tool call"
|
|
495
|
+
assert reply.tool_calls[0].tool_name == "get_weather"
|
|
496
|
+
assert reply.tool_calls[0].arguments.get("city")
|
|
497
|
+
assert reply.meta["finish_reason"] == "tool_calls"
|
|
498
|
+
|
|
499
|
+
def test_live_streaming_tool_call(self):
|
|
500
|
+
collected = []
|
|
501
|
+
|
|
502
|
+
def callback(chunk: StreamingChunk) -> None:
|
|
503
|
+
collected.append(chunk)
|
|
504
|
+
|
|
505
|
+
gen = LiteLLMChatGenerator(
|
|
506
|
+
model="openai/gpt-4o-mini",
|
|
507
|
+
tools=[_weather_tool()],
|
|
508
|
+
streaming_callback=callback,
|
|
509
|
+
)
|
|
510
|
+
result = gen.run(messages=[ChatMessage.from_user("What's the weather in Paris? Use the get_weather tool.")])
|
|
511
|
+
|
|
512
|
+
assert len(collected) > 0
|
|
513
|
+
reply = result["replies"][0]
|
|
514
|
+
# The streamed tool-call deltas must be reassembled into a single parsed ToolCall.
|
|
515
|
+
assert reply.tool_calls, "expected the streamed response to contain a tool call"
|
|
516
|
+
assert reply.tool_calls[0].tool_name == "get_weather"
|
|
517
|
+
assert reply.tool_calls[0].arguments.get("city")
|
|
518
|
+
assert reply.meta["finish_reason"] == "tool_calls"
|