lightspeed-stack 0.1.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,201 @@
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,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
models/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Pydantic models."""
models/config.py ADDED
@@ -0,0 +1,161 @@
1
+ """Model with service configuration."""
2
+
3
+ from typing import Optional
4
+
5
+ from pydantic import BaseModel, model_validator, FilePath, AnyHttpUrl
6
+ from typing_extensions import Self
7
+
8
+ import constants
9
+
10
+ from utils import checks
11
+
12
+
13
+ class TLSConfiguration(BaseModel):
14
+ """TLS configuration."""
15
+
16
+ tls_certificate_path: Optional[FilePath] = None
17
+ tls_key_path: Optional[FilePath] = None
18
+ tls_key_password: Optional[FilePath] = None
19
+
20
+ @model_validator(mode="after")
21
+ def check_tls_configuration(self) -> Self:
22
+ """Check TLS configuration."""
23
+ return self
24
+
25
+
26
+ class ServiceConfiguration(BaseModel):
27
+ """Service configuration."""
28
+
29
+ host: str = "localhost"
30
+ port: int = 8080
31
+ auth_enabled: bool = False
32
+ workers: int = 1
33
+ color_log: bool = True
34
+ access_log: bool = True
35
+ tls_config: TLSConfiguration = TLSConfiguration()
36
+
37
+ @model_validator(mode="after")
38
+ def check_service_configuration(self) -> Self:
39
+ """Check service configuration."""
40
+ if self.port <= 0:
41
+ raise ValueError("Port value should not be negative")
42
+ if self.port > 65535:
43
+ raise ValueError("Port value should be less than 65536")
44
+ if self.workers < 1:
45
+ raise ValueError("Workers must be set to at least 1")
46
+ return self
47
+
48
+
49
+ class ModelContextProtocolServer(BaseModel):
50
+ """model context protocol server configuration."""
51
+
52
+ name: str
53
+ provider_id: str = "model-context-protocol"
54
+ url: str
55
+
56
+
57
+ class LLamaStackConfiguration(BaseModel):
58
+ """Llama stack configuration."""
59
+
60
+ url: Optional[str] = None
61
+ api_key: Optional[str] = None
62
+ use_as_library_client: Optional[bool] = None
63
+ library_client_config_path: Optional[str] = None
64
+
65
+ @model_validator(mode="after")
66
+ def check_llama_stack_model(self) -> Self:
67
+ """Check Llama stack configuration."""
68
+ if self.url is None:
69
+ if self.use_as_library_client is None:
70
+ raise ValueError(
71
+ "LLama stack URL is not specified and library client mode is not specified"
72
+ )
73
+ if self.use_as_library_client is False:
74
+ raise ValueError(
75
+ "LLama stack URL is not specified and library client mode is not enabled"
76
+ )
77
+ if self.use_as_library_client is None:
78
+ self.use_as_library_client = False
79
+ if self.use_as_library_client:
80
+ if self.library_client_config_path is None:
81
+ # pylint: disable=line-too-long
82
+ raise ValueError(
83
+ "LLama stack library client mode is enabled but a configuration file path is not specified" # noqa: C0301
84
+ )
85
+ return self
86
+
87
+
88
+ class UserDataCollection(BaseModel):
89
+ """User data collection configuration."""
90
+
91
+ feedback_disabled: bool = True
92
+ feedback_storage: Optional[str] = None
93
+ transcripts_disabled: bool = True
94
+ transcripts_storage: Optional[str] = None
95
+
96
+ @model_validator(mode="after")
97
+ def check_storage_location_is_set_when_needed(self) -> Self:
98
+ """Check that storage_location is set when enabled."""
99
+ if not self.feedback_disabled and self.feedback_storage is None:
100
+ raise ValueError("feedback_storage is required when feedback is enabled")
101
+ if not self.transcripts_disabled and self.transcripts_storage is None:
102
+ raise ValueError(
103
+ "transcripts_storage is required when transcripts is enabled"
104
+ )
105
+ return self
106
+
107
+
108
+ class AuthenticationConfiguration(BaseModel):
109
+ """Authentication configuration."""
110
+
111
+ module: str = constants.DEFAULT_AUTHENTICATION_MODULE
112
+ skip_tls_verification: bool = False
113
+ k8s_cluster_api: Optional[AnyHttpUrl] = None
114
+ k8s_ca_cert_path: Optional[FilePath] = None
115
+
116
+ @model_validator(mode="after")
117
+ def check_authentication_model(self) -> Self:
118
+ """Validate YAML containing authentication configuration section."""
119
+ if self.module not in constants.SUPPORTED_AUTHENTICATION_MODULES:
120
+ supported_modules = ", ".join(constants.SUPPORTED_AUTHENTICATION_MODULES)
121
+ raise ValueError(
122
+ f"Unsupported authentication module '{self.module}'. "
123
+ f"Supported modules: {supported_modules}"
124
+ )
125
+ return self
126
+
127
+
128
+ class Customization(BaseModel):
129
+ """Service customization."""
130
+
131
+ system_prompt_path: Optional[FilePath] = None
132
+ system_prompt: Optional[str] = None
133
+
134
+ @model_validator(mode="after")
135
+ def check_authentication_model(self) -> Self:
136
+ """Load system prompt from file."""
137
+ if self.system_prompt_path is not None:
138
+ checks.file_check(self.system_prompt_path, "system prompt")
139
+ self.system_prompt = checks.get_attribute_from_file(
140
+ dict(self), "system_prompt_path"
141
+ )
142
+ return self
143
+
144
+
145
+ class Configuration(BaseModel):
146
+ """Global service configuration."""
147
+
148
+ name: str
149
+ service: ServiceConfiguration
150
+ llama_stack: LLamaStackConfiguration
151
+ user_data_collection: UserDataCollection
152
+ mcp_servers: list[ModelContextProtocolServer] = []
153
+ authentication: Optional[AuthenticationConfiguration] = (
154
+ AuthenticationConfiguration()
155
+ )
156
+ customization: Optional[Customization] = None
157
+
158
+ def dump(self, filename: str = "configuration.json") -> None:
159
+ """Dump actual configuration into JSON file."""
160
+ with open(filename, "w", encoding="utf-8") as fout:
161
+ fout.write(self.model_dump_json(indent=4))
models/requests.py ADDED
@@ -0,0 +1,208 @@
1
+ """Model for service requests."""
2
+
3
+ from typing import Optional, Self
4
+
5
+ from pydantic import BaseModel, model_validator, field_validator, Field
6
+ from llama_stack_client.types.agents.turn_create_params import Document
7
+
8
+ from utils import suid
9
+
10
+
11
+ class Attachment(BaseModel):
12
+ """Model representing an attachment that can be send from UI as part of query.
13
+
14
+ List of attachments can be optional part of 'query' request.
15
+
16
+ Attributes:
17
+ attachment_type: The attachment type, like "log", "configuration" etc.
18
+ content_type: The content type as defined in MIME standard
19
+ content: The actual attachment content
20
+
21
+ YAML attachments with **kind** and **metadata/name** attributes will
22
+ be handled as resources with specified name:
23
+ ```
24
+ kind: Pod
25
+ metadata:
26
+ name: private-reg
27
+ ```
28
+ """
29
+
30
+ attachment_type: str
31
+ content_type: str
32
+ content: str
33
+
34
+ # provides examples for /docs endpoint
35
+ model_config = {
36
+ "json_schema_extra": {
37
+ "examples": [
38
+ {
39
+ "attachment_type": "log",
40
+ "content_type": "text/plain",
41
+ "content": "this is attachment",
42
+ },
43
+ {
44
+ "attachment_type": "configuration",
45
+ "content_type": "application/yaml",
46
+ "content": "kind: Pod\n metadata:\n name: private-reg",
47
+ },
48
+ {
49
+ "attachment_type": "configuration",
50
+ "content_type": "application/yaml",
51
+ "content": "foo: bar",
52
+ },
53
+ ]
54
+ }
55
+ }
56
+
57
+
58
+ # TODO(lucasagomes): add media_type when needed, current implementation
59
+ # does not support streaming response, so this is not used
60
+ class QueryRequest(BaseModel):
61
+ """Model representing a request for the LLM (Language Model).
62
+
63
+ Attributes:
64
+ query: The query string.
65
+ conversation_id: The optional conversation ID (UUID).
66
+ provider: The optional provider.
67
+ model: The optional model.
68
+ system_prompt: The optional system prompt.
69
+ attachments: The optional attachments.
70
+
71
+ Example:
72
+ ```python
73
+ query_request = QueryRequest(query="Tell me about Kubernetes")
74
+ ```
75
+ """
76
+
77
+ query: str
78
+ conversation_id: Optional[str] = None
79
+ provider: Optional[str] = None
80
+ model: Optional[str] = None
81
+ system_prompt: Optional[str] = None
82
+ attachments: Optional[list[Attachment]] = None
83
+
84
+ # provides examples for /docs endpoint
85
+ model_config = {
86
+ "extra": "forbid",
87
+ "json_schema_extra": {
88
+ "examples": [
89
+ {
90
+ "query": "write a deployment yaml for the mongodb image",
91
+ "conversation_id": "123e4567-e89b-12d3-a456-426614174000",
92
+ "provider": "openai",
93
+ "model": "model-name",
94
+ "system_prompt": "You are a helpful assistant",
95
+ "attachments": [
96
+ {
97
+ "attachment_type": "log",
98
+ "content_type": "text/plain",
99
+ "content": "this is attachment",
100
+ },
101
+ {
102
+ "attachment_type": "configuration",
103
+ "content_type": "application/yaml",
104
+ "content": "kind: Pod\n metadata:\n name: private-reg",
105
+ },
106
+ {
107
+ "attachment_type": "configuration",
108
+ "content_type": "application/yaml",
109
+ "content": "foo: bar",
110
+ },
111
+ ],
112
+ }
113
+ ]
114
+ },
115
+ }
116
+
117
+ def get_documents(self) -> list[Document]:
118
+ """Return the list of documents from the attachments."""
119
+ if not self.attachments:
120
+ return []
121
+ return [
122
+ Document(content=att.content, mime_type=att.content_type)
123
+ for att in self.attachments # pylint: disable=not-an-iterable
124
+ ]
125
+
126
+ @model_validator(mode="after")
127
+ def validate_provider_and_model(self) -> Self:
128
+ """Perform validation on the provider and model."""
129
+ if self.model and not self.provider:
130
+ raise ValueError("Provider must be specified if model is specified")
131
+ if self.provider and not self.model:
132
+ raise ValueError("Model must be specified if provider is specified")
133
+ return self
134
+
135
+
136
+ class FeedbackRequest(BaseModel):
137
+ """Model representing a feedback request.
138
+
139
+ Attributes:
140
+ conversation_id: The required conversation ID (UUID).
141
+ user_question: The required user question.
142
+ llm_response: The required LLM response.
143
+ sentiment: The optional sentiment.
144
+ user_feedback: The optional user feedback.
145
+
146
+ Example:
147
+ ```python
148
+ feedback_request = FeedbackRequest(
149
+ conversation_id="12345678-abcd-0000-0123-456789abcdef",
150
+ user_question="what are you doing?",
151
+ user_feedback="Great service!",
152
+ llm_response="I don't know",
153
+ sentiment=-1,
154
+ )
155
+ ```
156
+ """
157
+
158
+ conversation_id: str
159
+ user_question: str
160
+ llm_response: str
161
+ sentiment: Optional[int] = None
162
+ # Optional user feedback limited to 1–4096 characters to prevent abuse.
163
+ user_feedback: Optional[str] = Field(
164
+ default=None,
165
+ max_length=4096,
166
+ description="Feedback on the LLM response.",
167
+ examples=["I'm not satisfied with the response because it is too vague."],
168
+ )
169
+
170
+ # provides examples for /docs endpoint
171
+ model_config = {
172
+ "json_schema_extra": {
173
+ "examples": [
174
+ {
175
+ "conversation_id": "12345678-abcd-0000-0123-456789abcdef",
176
+ "user_question": "foo",
177
+ "llm_response": "bar",
178
+ "user_feedback": "Great service!",
179
+ "sentiment": 1,
180
+ }
181
+ ]
182
+ }
183
+ }
184
+
185
+ @field_validator("conversation_id")
186
+ @classmethod
187
+ def check_uuid(cls, value: str) -> str:
188
+ """Check if conversation ID has the proper format."""
189
+ if not suid.check_suid(value):
190
+ raise ValueError(f"Improper conversation ID {value}")
191
+ return value
192
+
193
+ @field_validator("sentiment")
194
+ @classmethod
195
+ def check_sentiment(cls, value: Optional[int]) -> Optional[int]:
196
+ """Check if sentiment value is as expected."""
197
+ if value not in {-1, 1, None}:
198
+ raise ValueError(
199
+ f"Improper sentiment value of {value}, needs to be -1 or 1"
200
+ )
201
+ return value
202
+
203
+ @model_validator(mode="after")
204
+ def check_sentiment_or_user_feedback_set(self) -> Self:
205
+ """Ensure that either 'sentiment' or 'user_feedback' is set."""
206
+ if self.sentiment is None and self.user_feedback is None:
207
+ raise ValueError("Either 'sentiment' or 'user_feedback' must be set")
208
+ return self