llama-stack-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.
@@ -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
File without changes
@@ -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,45 @@
1
+ Metadata-Version: 2.4
2
+ Name: llama-stack-haystack
3
+ Version: 1.0.0
4
+ Summary: Use Llama Stack framework for text generation
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/llama-stack#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/llama-stack
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: Implementation :: CPython
19
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: haystack-ai>=2.14
22
+ Requires-Dist: llama-stack
23
+ Description-Content-Type: text/markdown
24
+
25
+ # llama-stack-haystack
26
+
27
+ [![PyPI - Version](https://img.shields.io/pypi/v/llama-stack-haystack.svg)](https://pypi.org/project/llama-stack-haystack)
28
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/llama-haystack.svg)](https://pypi.org/project/llama-stack-haystack)
29
+
30
+ -----
31
+
32
+ **Table of Contents**
33
+
34
+ - [Installation](#installation)
35
+ - [License](#license)
36
+
37
+ ## Installation
38
+
39
+ ```console
40
+ pip install llama-stack-haystack
41
+ ```
42
+
43
+ ## License
44
+
45
+ `llama-stack-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
@@ -0,0 +1,21 @@
1
+ # llama-stack-haystack
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/llama-stack-haystack.svg)](https://pypi.org/project/llama-stack-haystack)
4
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/llama-haystack.svg)](https://pypi.org/project/llama-stack-haystack)
5
+
6
+ -----
7
+
8
+ **Table of Contents**
9
+
10
+ - [Installation](#installation)
11
+ - [License](#license)
12
+
13
+ ## Installation
14
+
15
+ ```console
16
+ pip install llama-stack-haystack
17
+ ```
18
+
19
+ ## License
20
+
21
+ `llama-stack-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
@@ -0,0 +1,49 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ # This example demonstrates how to use the LlamaStackChatGenerator component
6
+ # with tools.
7
+ # To run this example, you will need to
8
+ # set up Llama Stack Server through an inference provider and have a model available.
9
+ # For a quick start on how to setup server with Ollama, see [Llama Stack docs](https://llama-stack.readthedocs.io/en/latest/getting_started/index.html).
10
+
11
+ from haystack.components.tools import ToolInvoker
12
+ from haystack.dataclasses import ChatMessage
13
+ from haystack.tools import Tool
14
+
15
+ from .components.generators.llama_stack.chat.chat_generator import LlamaStackChatGenerator
16
+
17
+
18
+ # Define a tool that models can call
19
+ def weather(city: str):
20
+ """Return mock weather info for the given city."""
21
+ return f"The weather in {city} is sunny and 32°C"
22
+
23
+
24
+ tool_parameters = {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
25
+
26
+ weather_tool = Tool(
27
+ name="weather",
28
+ description="Useful for getting the weather in a specific city",
29
+ parameters=tool_parameters,
30
+ function=weather,
31
+ )
32
+
33
+ # Create a tool invoker with the weather tool
34
+ tool_invoker = ToolInvoker(tools=[weather_tool])
35
+
36
+ client = LlamaStackChatGenerator(
37
+ model="llama3.2:3b", # model name varies depending on the inference provider used for the Llama Stack Server.
38
+ api_base_url="http://localhost:8321/v1/openai/v1",
39
+ )
40
+ messages = [ChatMessage.from_user("What's the weather in Tokyo?")]
41
+
42
+ response = client.run(messages=messages, tools=[weather_tool])["replies"]
43
+
44
+ print(f"assistant messages: {response[0]}\n") # noqa: T201
45
+
46
+ # If the assistant message contains a tool call, run the tool invoker
47
+ if response[0].tool_calls:
48
+ tool_messages = tool_invoker.run(messages=response)["tool_messages"]
49
+ print(f"tool messages: {tool_messages}") # noqa: T201
@@ -0,0 +1,29 @@
1
+ loaders:
2
+ - type: haystack_pydoc_tools.loaders.CustomPythonLoader
3
+ search_path: [../src]
4
+ modules: [
5
+ "haystack_integrations.components.generators.llama_stack.chat.chat_generator",
6
+ ]
7
+ ignore_when_discovered: ["__init__"]
8
+ processors:
9
+ - type: filter
10
+ expression:
11
+ documented_only: true
12
+ do_not_filter_modules: false
13
+ skip_empty_modules: true
14
+ - type: smart
15
+ - type: crossref
16
+ renderer:
17
+ type: haystack_pydoc_tools.renderers.ReadmeIntegrationRenderer
18
+ excerpt: Llama Stack integration for Haystack
19
+ category_slug: integrations-api
20
+ title: Llama Stack
21
+ slug: integrations-llama-stack
22
+ order: 200
23
+ markdown:
24
+ descriptive_class_title: false
25
+ classdef_code_block: false
26
+ descriptive_module_title: true
27
+ add_method_class_prefix: true
28
+ add_member_class_prefix: false
29
+ filename: _readme_llama_stack.md
@@ -0,0 +1,156 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "llama-stack-haystack"
7
+ dynamic = ["version"]
8
+ description = 'Use Llama Stack framework for text generation'
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ keywords = []
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", # python 3.9 is not supported by llama-stack
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: Implementation :: CPython",
23
+ "Programming Language :: Python :: Implementation :: PyPy",
24
+ ]
25
+ dependencies = ["haystack-ai>=2.14", "llama-stack"]
26
+
27
+ [project.urls]
28
+ Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/llama-stack#readme"
29
+ Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
30
+ Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/llama-stack"
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["src/haystack_integrations"]
34
+
35
+ [tool.hatch.version]
36
+ source = "vcs"
37
+ tag-pattern = 'integrations\/llama_stack-v(?P<version>.*)'
38
+
39
+ [tool.hatch.version.raw-options]
40
+ root = "../.."
41
+ git_describe_command = 'git describe --tags --match="integrations/llama_stack-v[0-9]*"'
42
+
43
+ [tool.hatch.envs.default]
44
+ installer = "uv"
45
+ dependencies = ["haystack-pydoc-tools", "ruff"]
46
+ [tool.hatch.envs.default.scripts]
47
+ docs = ["pydoc-markdown pydoc/config.yml"]
48
+ fmt = "ruff check --fix {args} && ruff format {args}"
49
+ fmt-check = "ruff check {args} && ruff format --check {args}"
50
+
51
+ [tool.hatch.envs.test]
52
+ dependencies = [
53
+ "pytest",
54
+ "pytest-asyncio",
55
+ "pytest-cov",
56
+ "pytest-rerunfailures",
57
+ "mypy",
58
+ "pip",
59
+ "pytz"
60
+ ]
61
+
62
+ [tool.hatch.envs.test.scripts]
63
+ unit = 'pytest -m "not integration" {args:tests}'
64
+ integration = 'pytest -m "integration" {args:tests}'
65
+ all = 'pytest {args:tests}'
66
+ cov-retry = 'all --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x'
67
+
68
+ types = "mypy -p haystack_integrations.components.generators.llama_stack {args}"
69
+
70
+ [tool.mypy]
71
+ install_types = true
72
+ non_interactive = true
73
+ check_untyped_defs = true
74
+ disallow_incomplete_defs = true
75
+
76
+
77
+ [tool.ruff]
78
+ target-version = "py38"
79
+ line-length = 120
80
+
81
+ [tool.ruff.lint]
82
+ select = [
83
+ "A",
84
+ "ARG",
85
+ "B",
86
+ "C",
87
+ "DTZ",
88
+ "E",
89
+ "EM",
90
+ "F",
91
+ "I",
92
+ "ICN",
93
+ "ISC",
94
+ "N",
95
+ "PLC",
96
+ "PLE",
97
+ "PLR",
98
+ "PLW",
99
+ "Q",
100
+ "RUF",
101
+ "S",
102
+ "T",
103
+ "TID",
104
+ "UP",
105
+ "W",
106
+ "YTT",
107
+ ]
108
+ ignore = [
109
+ # Allow non-abstract empty methods in abstract base classes
110
+ "B027",
111
+ # Ignore checks for possible passwords
112
+ "S105",
113
+ "S106",
114
+ "S107",
115
+ # Ignore complexity
116
+ "C901",
117
+ "PLR0911",
118
+ "PLR0912",
119
+ "PLR0913",
120
+ "PLR0915",
121
+ # Misc
122
+ "B008",
123
+ "S101",
124
+ ]
125
+ unfixable = [
126
+ # Don't touch unused imports
127
+ "F401",
128
+ ]
129
+
130
+ [tool.ruff.lint.isort]
131
+ known-first-party = ["haystack_integrations"]
132
+
133
+ [tool.ruff.lint.flake8-tidy-imports]
134
+ ban-relative-imports = "parents"
135
+
136
+ [tool.ruff.lint.per-file-ignores]
137
+ # Tests can use magic values, assertions, and relative imports
138
+ "tests/**/*" = ["PLR2004", "S101", "TID252", "E501", "F841"]
139
+
140
+ [tool.coverage.run]
141
+ source = ["haystack_integrations"]
142
+ branch = true
143
+ parallel = false
144
+
145
+
146
+ [tool.coverage.report]
147
+ omit = ["*/tests/*", "*/__init__.py"]
148
+ show_missing = true
149
+ exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
150
+
151
+ [tool.pytest.ini_options]
152
+ addopts = "--strict-markers"
153
+ markers = [
154
+ "integration: integration tests",
155
+ ]
156
+ log_cli = true
@@ -0,0 +1,3 @@
1
+ from .chat.chat_generator import LlamaStackChatGenerator
2
+
3
+ __all__ = ["LlamaStackChatGenerator"]
@@ -0,0 +1,168 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any, Dict, List, Optional, Union
6
+
7
+ from haystack import component, default_from_dict, default_to_dict, logging
8
+ from haystack.components.generators.chat import OpenAIChatGenerator
9
+ from haystack.dataclasses import StreamingCallbackT
10
+ from haystack.tools import Tool, Toolset, deserialize_tools_or_toolset_inplace, serialize_tools_or_toolset
11
+ from haystack.utils import deserialize_callable, serialize_callable
12
+ from haystack.utils.auth import Secret
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ @component
18
+ class LlamaStackChatGenerator(OpenAIChatGenerator):
19
+ """
20
+ Enables text generation using Llama Stack framework.
21
+ Llama Stack Server supports multiple inference providers, including Ollama, Together,
22
+ and vLLM and other cloud providers.
23
+ For a complete list of inference providers, see [Llama Stack docs](https://llama-stack.readthedocs.io/en/latest/providers/inference/index.html).
24
+
25
+ Users can pass any text generation parameters valid for the OpenAI chat completion API
26
+ directly to this component using the `generation_kwargs`
27
+ parameter in `__init__` or the `generation_kwargs` parameter in `run` method.
28
+
29
+ This component uses the `ChatMessage` format for structuring both input and output,
30
+ ensuring coherent and contextually relevant responses in chat-based text generation scenarios.
31
+ Details on the `ChatMessage` format can be found in the
32
+ [Haystack docs](https://docs.haystack.deepset.ai/docs/chatmessage)
33
+
34
+ Usage example:
35
+ You need to setup Llama Stack Server before running this example and have a model available. For a quick start on
36
+ how to setup server with Ollama, see [Llama Stack docs](https://llama-stack.readthedocs.io/en/latest/getting_started/index.html).
37
+
38
+ ```python
39
+ from haystack_integrations.components.generators.llama_stack import LlamaStackChatGenerator
40
+ from haystack.dataclasses import ChatMessage
41
+
42
+ messages = [ChatMessage.from_user("What's Natural Language Processing?")]
43
+
44
+ client = LlamaStackChatGenerator(model="llama3.2:3b")
45
+ response = client.run(messages)
46
+ print(response)
47
+
48
+ >>{'replies': [ChatMessage(_content=[TextContent(text='Natural Language Processing (NLP)
49
+ is a branch of artificial intelligence
50
+ >>that focuses on enabling computers to understand, interpret, and generate human language in a way that is
51
+ >>meaningful and useful.')], _role=<ChatRole.ASSISTANT: 'assistant'>, _name=None,
52
+ >>_meta={'model': 'llama3.2:3b', 'index': 0, 'finish_reason': 'stop',
53
+ >>'usage': {'prompt_tokens': 15, 'completion_tokens': 36, 'total_tokens': 51}})]}
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ *,
59
+ model: str,
60
+ api_base_url: str = "http://localhost:8321/v1/openai/v1",
61
+ organization: Optional[str] = None,
62
+ streaming_callback: Optional[StreamingCallbackT] = None,
63
+ generation_kwargs: Optional[Dict[str, Any]] = None,
64
+ timeout: Optional[int] = None,
65
+ tools: Optional[Union[List[Tool], Toolset]] = None,
66
+ tools_strict: bool = False,
67
+ max_retries: Optional[int] = None,
68
+ http_client_kwargs: Optional[Dict[str, Any]] = None,
69
+ ):
70
+ """
71
+ Creates an instance of LlamaStackChatGenerator. To use this chat generator,
72
+ you need to setup Llama Stack Server with an inference provider and have a model available.
73
+
74
+ :param model:
75
+ The name of the model to use for chat completion.
76
+ This depends on the inference provider used for the Llama Stack Server.
77
+ :param streaming_callback:
78
+ A callback function that is called when a new token is received from the stream.
79
+ The callback function accepts StreamingChunk as an argument.
80
+ :param api_base_url:
81
+ The Llama Stack API base url. If not specified, the localhost is used with the default port 8321.
82
+ :param organization: Your organization ID, defaults to `None`.
83
+ :param generation_kwargs:
84
+ Other parameters to use for the model. These parameters are all sent directly to
85
+ the Llama Stack endpoint. See [Llama Stack API docs](https://llama-stack.readthedocs.io/) for more details.
86
+ Some of the supported parameters:
87
+ - `max_tokens`: The maximum number of tokens the output text can have.
88
+ - `temperature`: What sampling temperature to use. Higher values mean the model will take more risks.
89
+ Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer.
90
+ - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model
91
+ considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens
92
+ comprising the top 10% probability mass are considered.
93
+ - `stream`: Whether to stream back partial progress. If set, tokens will be sent as data-only server-sent
94
+ events as they become available, with the stream terminated by a data: [DONE] message.
95
+ - `safe_prompt`: Whether to inject a safety prompt before all conversations.
96
+ - `random_seed`: The seed to use for random sampling.
97
+ :param timeout:
98
+ Timeout for client calls using OpenAI API. If not set, it defaults to either the
99
+ `OPENAI_TIMEOUT` environment variable, or 30 seconds.
100
+ :param tools:
101
+ A list of tools or a Toolset for which the model can prepare calls. This parameter can accept either a
102
+ list of `Tool` objects or a `Toolset` instance.
103
+ :param tools_strict:
104
+ Whether to enable strict schema adherence for tool calls. If set to `True`, the model will follow exactly
105
+ the schema provided in the `parameters` field of the tool definition, but this may increase latency.
106
+ :param max_retries:
107
+ Maximum number of retries to contact OpenAI after an internal error.
108
+ If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5.
109
+ :param http_client_kwargs:
110
+ A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`.
111
+ For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client).
112
+
113
+ """
114
+
115
+ # Use placeholder key for a Llama Stack server running locally
116
+ api_key = Secret.from_token("placeholder-api-key")
117
+
118
+ super(LlamaStackChatGenerator, self).__init__( # noqa: UP008
119
+ model=model,
120
+ api_key=api_key,
121
+ streaming_callback=streaming_callback,
122
+ api_base_url=api_base_url,
123
+ organization=organization,
124
+ generation_kwargs=generation_kwargs,
125
+ timeout=timeout,
126
+ tools=tools,
127
+ tools_strict=tools_strict,
128
+ max_retries=max_retries,
129
+ http_client_kwargs=http_client_kwargs,
130
+ )
131
+
132
+ def to_dict(self) -> Dict[str, Any]:
133
+ """
134
+ Serialize this component to a dictionary.
135
+
136
+ :returns:
137
+ The serialized component as a dictionary.
138
+ """
139
+ callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None
140
+ return default_to_dict(
141
+ self,
142
+ model=self.model,
143
+ streaming_callback=callback_name,
144
+ api_base_url=self.api_base_url,
145
+ organization=self.organization,
146
+ generation_kwargs=self.generation_kwargs,
147
+ timeout=self.timeout,
148
+ max_retries=self.max_retries,
149
+ tools=serialize_tools_or_toolset(self.tools),
150
+ tools_strict=self.tools_strict,
151
+ http_client_kwargs=self.http_client_kwargs,
152
+ )
153
+
154
+ @classmethod
155
+ def from_dict(cls, data: Dict[str, Any]) -> "LlamaStackChatGenerator":
156
+ """
157
+ Deserialize this component from a dictionary.
158
+
159
+ :param data: The dictionary representation of this component.
160
+ :returns:
161
+ The deserialized component instance.
162
+ """
163
+ deserialize_tools_or_toolset_inplace(data["init_parameters"], key="tools")
164
+ init_params = data.get("init_parameters", {})
165
+ serialized_callback_handler = init_params.get("streaming_callback")
166
+ if serialized_callback_handler:
167
+ data["init_parameters"]["streaming_callback"] = deserialize_callable(serialized_callback_handler)
168
+ return default_from_dict(cls, data)
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2024-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,300 @@
1
+ from datetime import datetime
2
+ from unittest.mock import patch
3
+
4
+ import pytest
5
+ import pytz
6
+ from haystack.components.generators.utils import print_streaming_chunk
7
+ from haystack.dataclasses import ChatMessage, ChatRole, StreamingChunk, ToolCall
8
+ from haystack.tools import Tool
9
+ from openai.types.chat import ChatCompletion, ChatCompletionMessage
10
+ from openai.types.chat.chat_completion import Choice
11
+
12
+ from haystack_integrations.components.generators.llama_stack.chat.chat_generator import LlamaStackChatGenerator
13
+
14
+
15
+ @pytest.fixture
16
+ def chat_messages():
17
+ return [
18
+ ChatMessage.from_system("You are a helpful assistant"),
19
+ ChatMessage.from_user("What's the capital of France"),
20
+ ]
21
+
22
+
23
+ def weather(city: str):
24
+ """Get weather for a given city."""
25
+ return f"The weather in {city} is sunny and 32°C"
26
+
27
+
28
+ @pytest.fixture
29
+ def tools():
30
+ tool_parameters = {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
31
+ tool = Tool(
32
+ name="weather",
33
+ description="useful to determine the weather in a given location",
34
+ parameters=tool_parameters,
35
+ function=weather,
36
+ )
37
+
38
+ return [tool]
39
+
40
+
41
+ @pytest.fixture
42
+ def mock_chat_completion():
43
+ """
44
+ Mock the OpenAI API completion response and reuse it for tests
45
+ """
46
+ with patch("openai.resources.chat.completions.Completions.create") as mock_chat_completion_create:
47
+ completion = ChatCompletion(
48
+ id="foo",
49
+ model="llama3.2:3b",
50
+ object="chat.completion",
51
+ choices=[
52
+ Choice(
53
+ finish_reason="stop",
54
+ logprobs=None,
55
+ index=0,
56
+ message=ChatCompletionMessage(content="Hello world!", role="assistant"),
57
+ )
58
+ ],
59
+ created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()),
60
+ usage={"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97},
61
+ )
62
+
63
+ mock_chat_completion_create.return_value = completion
64
+ yield mock_chat_completion_create
65
+
66
+
67
+ class TestLlamaStackChatGenerator:
68
+ def test_init_default(self):
69
+ component = LlamaStackChatGenerator(model="llama3.2:3b")
70
+ assert component.model == "llama3.2:3b"
71
+ assert component.api_base_url == "http://localhost:8321/v1/openai/v1"
72
+ assert component.streaming_callback is None
73
+ assert not component.generation_kwargs
74
+
75
+ def test_init_with_parameters(self):
76
+ component = LlamaStackChatGenerator(
77
+ model="llama3.2:3b",
78
+ streaming_callback=print_streaming_chunk,
79
+ api_base_url="test-base-url",
80
+ generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"},
81
+ )
82
+ assert component.model == "llama3.2:3b"
83
+ assert component.streaming_callback is print_streaming_chunk
84
+ assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"}
85
+
86
+ def test_to_dict_default(
87
+ self,
88
+ ):
89
+ component = LlamaStackChatGenerator(model="llama3.2:3b")
90
+ data = component.to_dict()
91
+
92
+ assert (
93
+ data["type"]
94
+ == "haystack_integrations.components.generators.llama_stack.chat.chat_generator.LlamaStackChatGenerator"
95
+ )
96
+
97
+ expected_params = {
98
+ "model": "llama3.2:3b",
99
+ "streaming_callback": None,
100
+ "api_base_url": "http://localhost:8321/v1/openai/v1",
101
+ "generation_kwargs": {},
102
+ "timeout": None,
103
+ "max_retries": None,
104
+ "tools": None,
105
+ "http_client_kwargs": None,
106
+ "tools_strict": False,
107
+ }
108
+
109
+ for key, value in expected_params.items():
110
+ assert data["init_parameters"][key] == value
111
+
112
+ def test_to_dict_with_parameters(
113
+ self,
114
+ ):
115
+ component = LlamaStackChatGenerator(
116
+ model="llama3.2:3b",
117
+ streaming_callback=print_streaming_chunk,
118
+ api_base_url="test-base-url",
119
+ generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"},
120
+ timeout=10,
121
+ max_retries=10,
122
+ tools=None,
123
+ http_client_kwargs={"proxy": "http://localhost:8080"},
124
+ tools_strict=True,
125
+ )
126
+ data = component.to_dict()
127
+
128
+ assert (
129
+ data["type"]
130
+ == "haystack_integrations.components.generators.llama_stack.chat.chat_generator.LlamaStackChatGenerator"
131
+ )
132
+
133
+ expected_params = {
134
+ "model": "llama3.2:3b",
135
+ "api_base_url": "test-base-url",
136
+ "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
137
+ "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"},
138
+ "timeout": 10,
139
+ "max_retries": 10,
140
+ "tools": None,
141
+ "http_client_kwargs": {"proxy": "http://localhost:8080"},
142
+ "tools_strict": True,
143
+ }
144
+
145
+ for key, value in expected_params.items():
146
+ assert data["init_parameters"][key] == value
147
+
148
+ def test_from_dict(
149
+ self,
150
+ ):
151
+ data = {
152
+ "type": (
153
+ "haystack_integrations.components.generators.llama_stack.chat.chat_generator.LlamaStackChatGenerator"
154
+ ),
155
+ "init_parameters": {
156
+ "model": "llama3.2:3b",
157
+ "api_base_url": "test-base-url",
158
+ "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
159
+ "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"},
160
+ "timeout": 10,
161
+ "max_retries": 10,
162
+ "tools": None,
163
+ "http_client_kwargs": {"proxy": "http://localhost:8080"},
164
+ "tools_strict": False,
165
+ },
166
+ }
167
+ component = LlamaStackChatGenerator.from_dict(data)
168
+ assert component.model == "llama3.2:3b"
169
+ assert component.streaming_callback is print_streaming_chunk
170
+ assert component.api_base_url == "test-base-url"
171
+ assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"}
172
+ assert component.http_client_kwargs == {"proxy": "http://localhost:8080"}
173
+ assert component.tools is None
174
+ assert component.timeout == 10
175
+ assert component.max_retries == 10
176
+ assert not component.tools_strict
177
+
178
+ def test_run(self, chat_messages, mock_chat_completion): # noqa: ARG002
179
+ component = LlamaStackChatGenerator(model="llama3.2:3b")
180
+ response = component.run(chat_messages)
181
+
182
+ # check that the component returns the correct ChatMessage response
183
+ assert isinstance(response, dict)
184
+ assert "replies" in response
185
+ assert isinstance(response["replies"], list)
186
+ assert len(response["replies"]) == 1
187
+ assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
188
+
189
+ def test_run_with_params(self, chat_messages, mock_chat_completion):
190
+ component = LlamaStackChatGenerator(
191
+ model="llama3.2:3b",
192
+ generation_kwargs={"max_tokens": 10, "temperature": 0.5},
193
+ )
194
+ response = component.run(chat_messages)
195
+
196
+ # check that the component calls the OpenAI API with the correct parameters
197
+ # for LlamaStack
198
+ _, kwargs = mock_chat_completion.call_args
199
+ assert kwargs["max_tokens"] == 10
200
+ assert kwargs["temperature"] == 0.5
201
+ # check that the component returns the correct response
202
+ assert isinstance(response, dict)
203
+ assert "replies" in response
204
+ assert isinstance(response["replies"], list)
205
+ assert len(response["replies"]) == 1
206
+ assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
207
+
208
+ @pytest.mark.integration
209
+ def test_live_run(self):
210
+ chat_messages = [ChatMessage.from_user("What's the capital of France")]
211
+ component = LlamaStackChatGenerator(model="llama3.2:3b")
212
+ results = component.run(chat_messages)
213
+ assert len(results["replies"]) == 1
214
+ message: ChatMessage = results["replies"][0]
215
+ assert "Paris" in message.text
216
+ assert "llama3.2:3b" in message.meta["model"]
217
+ assert message.meta["finish_reason"] == "stop"
218
+
219
+ @pytest.mark.integration
220
+ def test_live_run_streaming(self):
221
+ class Callback:
222
+ def __init__(self):
223
+ self.responses = ""
224
+ self.counter = 0
225
+
226
+ def __call__(self, chunk: StreamingChunk) -> None:
227
+ self.counter += 1
228
+ self.responses += chunk.content if chunk.content else ""
229
+
230
+ callback = Callback()
231
+ component = LlamaStackChatGenerator(model="llama3.2:3b", streaming_callback=callback)
232
+ results = component.run([ChatMessage.from_user("What's the capital of France?")])
233
+
234
+ assert len(results["replies"]) == 1
235
+ message: ChatMessage = results["replies"][0]
236
+ assert "Paris" in message.text
237
+
238
+ assert "llama3.2:3b" in message.meta["model"]
239
+ assert message.meta["finish_reason"] == "stop"
240
+
241
+ assert callback.counter > 1
242
+ assert "Paris" in callback.responses
243
+
244
+ @pytest.mark.integration
245
+ def test_live_run_with_tools(self, tools):
246
+ chat_messages = [ChatMessage.from_user("What's the weather like in Paris?")]
247
+ component = LlamaStackChatGenerator(model="llama3.2:3b", tools=tools)
248
+ results = component.run(chat_messages)
249
+ assert len(results["replies"]) == 1
250
+ message = results["replies"][0]
251
+ assert message.text == ""
252
+
253
+ assert message.tool_calls
254
+ tool_call = message.tool_call
255
+ assert isinstance(tool_call, ToolCall)
256
+ assert tool_call.tool_name == "weather"
257
+ assert tool_call.arguments == {"city": "Paris"}
258
+ assert message.meta["finish_reason"] == "tool_calls"
259
+
260
+ @pytest.mark.integration
261
+ def test_live_run_with_tools_and_response(self, tools):
262
+ """
263
+ Integration test that the LlamaStackChatGenerator component can run with tools and get a response.
264
+ """
265
+ initial_messages = [ChatMessage.from_user("What's the weather like in Paris?")]
266
+ component = LlamaStackChatGenerator(model="llama3.2:3b", tools=tools)
267
+ results = component.run(messages=initial_messages, generation_kwargs={"tool_choice": "auto"})
268
+
269
+ assert len(results["replies"]) > 0, "No replies received"
270
+
271
+ # Find the message with tool calls
272
+ tool_message = None
273
+ for message in results["replies"]:
274
+ if message.tool_call:
275
+ tool_message = message
276
+ break
277
+
278
+ assert tool_message is not None, "No message with tool call found"
279
+ assert isinstance(tool_message, ChatMessage), "Tool message is not a ChatMessage instance"
280
+ assert ChatMessage.is_from(tool_message, ChatRole.ASSISTANT), "Tool message is not from the assistant"
281
+
282
+ tool_call = tool_message.tool_call
283
+ assert tool_call.id, "Tool call does not contain value for 'id' key"
284
+ assert tool_call.tool_name == "weather"
285
+ assert tool_call.arguments == {"city": "Paris"}
286
+ assert tool_message.meta["finish_reason"] == "tool_calls"
287
+
288
+ new_messages = [
289
+ initial_messages[0],
290
+ tool_message,
291
+ ChatMessage.from_tool(tool_result="22° C", origin=tool_call),
292
+ ]
293
+ # Pass the tool result to the model to get the final response
294
+ results = component.run(new_messages)
295
+
296
+ assert len(results["replies"]) == 1
297
+ final_message = results["replies"][0]
298
+ assert not final_message.tool_call
299
+ assert len(final_message.text) > 0
300
+ assert "paris" in final_message.text.lower()