llama-stack-haystack 1.0.0__py3-none-any.whl

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,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)
File without changes
@@ -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,8 @@
1
+ haystack_integrations/components/generators/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ haystack_integrations/components/generators/llama_stack/__init__.py,sha256=Zx6ZeC2pqN_CYjjRLXO7gQmPlq-n1FNlC_tIKAH6OL0,96
3
+ haystack_integrations/components/generators/llama_stack/chat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ haystack_integrations/components/generators/llama_stack/chat/chat_generator.py,sha256=9SQf0tIVndZYJxoAWfTZiIyDQwGyY5e_tLuL6Frl9n8,8561
5
+ llama_stack_haystack-1.0.0.dist-info/METADATA,sha256=kNex2HYwhCKzeekzOMNc_AiTzwh80svUdHceneWlH8w,1735
6
+ llama_stack_haystack-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
+ llama_stack_haystack-1.0.0.dist-info/licenses/LICENSE.txt,sha256=B05uMshqTA74s-0ltyHKI6yoPfJ3zYgQbvcXfDVGFf8,10280
8
+ llama_stack_haystack-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.