-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathrequests.py
More file actions
538 lines (464 loc) · 17.8 KB
/
requests.py
File metadata and controls
538 lines (464 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
"""Models for REST API requests."""
from typing import Optional, Self
from enum import Enum
from pydantic import BaseModel, model_validator, field_validator, Field
from llama_stack_client.types.agents.turn_create_params import Document
from log import get_logger
from utils import suid
from constants import MEDIA_TYPE_JSON, MEDIA_TYPE_TEXT
logger = get_logger(__name__)
class Attachment(BaseModel):
"""Model representing an attachment that can be send from the UI as part of query.
A list of attachments can be an optional part of 'query' request.
Attributes:
attachment_type: The attachment type, like "log", "configuration" etc.
content_type: The content type as defined in MIME standard
content: The actual attachment content
YAML attachments with **kind** and **metadata/name** attributes will
be handled as resources with the specified name:
```
kind: Pod
metadata:
name: private-reg
```
"""
attachment_type: str = Field(
description="The attachment type, like 'log', 'configuration' etc.",
examples=["log"],
)
content_type: str = Field(
description="The content type as defined in MIME standard",
examples=["text/plain"],
)
content: str = Field(
description="The actual attachment content",
examples=["warning: quota exceeded"],
)
# provides examples for /docs endpoint
model_config = {
"extra": "forbid",
"json_schema_extra": {
"examples": [
{
"attachment_type": "log",
"content_type": "text/plain",
"content": "this is attachment",
},
{
"attachment_type": "configuration",
"content_type": "application/yaml",
"content": "kind: Pod\n metadata:\n name: private-reg",
},
{
"attachment_type": "configuration",
"content_type": "application/yaml",
"content": "foo: bar",
},
]
},
}
class QueryRequest(BaseModel):
"""Model representing a request for the LLM (Language Model).
Attributes:
query: The query string.
conversation_id: The optional conversation ID (UUID).
provider: The optional provider.
model: The optional model.
system_prompt: The optional system prompt.
attachments: The optional attachments.
no_tools: Whether to bypass all tools and MCP servers (default: False).
media_type: The optional media type for response format (application/json or text/plain).
Example:
```python
query_request = QueryRequest(query="Tell me about Kubernetes")
```
"""
query: str = Field(
description="The query string",
examples=["What is Kubernetes?"],
)
conversation_id: Optional[str] = Field(
None,
description="The optional conversation ID (UUID)",
examples=["c5260aec-4d82-4370-9fdf-05cf908b3f16"],
)
provider: Optional[str] = Field(
None,
description="The optional provider",
examples=["openai", "watsonx"],
)
model: Optional[str] = Field(
None,
description="The optional model",
examples=["gpt4mini"],
)
system_prompt: Optional[str] = Field(
None,
description="The optional system prompt.",
examples=["You are OpenShift assistant.", "You are Ansible assistant."],
)
attachments: Optional[list[Attachment]] = Field(
None,
description="The optional list of attachments.",
examples=[
{
"attachment_type": "log",
"content_type": "text/plain",
"content": "this is attachment",
},
{
"attachment_type": "configuration",
"content_type": "application/yaml",
"content": "kind: Pod\n metadata:\n name: private-reg",
},
{
"attachment_type": "configuration",
"content_type": "application/yaml",
"content": "foo: bar",
},
],
)
no_tools: Optional[bool] = Field(
False,
description="Whether to bypass all tools and MCP servers",
examples=[True, False],
)
media_type: Optional[str] = Field(
None,
description="Media type for the response format",
examples=[MEDIA_TYPE_JSON, MEDIA_TYPE_TEXT],
)
# provides examples for /docs endpoint
model_config = {
"extra": "forbid",
"json_schema_extra": {
"examples": [
{
"query": "write a deployment yaml for the mongodb image",
"conversation_id": "123e4567-e89b-12d3-a456-426614174000",
"provider": "openai",
"model": "model-name",
"system_prompt": "You are a helpful assistant",
"no_tools": False,
"attachments": [
{
"attachment_type": "log",
"content_type": "text/plain",
"content": "this is attachment",
},
{
"attachment_type": "configuration",
"content_type": "application/yaml",
"content": "kind: Pod\n metadata:\n name: private-reg",
},
{
"attachment_type": "configuration",
"content_type": "application/yaml",
"content": "foo: bar",
},
],
}
]
},
}
@field_validator("conversation_id")
@classmethod
def check_uuid(cls, value: str | None) -> str | None:
"""Check if conversation ID has the proper format."""
if value and not suid.check_suid(value):
raise ValueError(f"Improper conversation ID '{value}'")
return value
def get_documents(self) -> list[Document]:
"""Return the list of documents from the attachments."""
if not self.attachments:
return []
return [
Document(content=att.content, mime_type=att.content_type)
for att in self.attachments # pylint: disable=not-an-iterable
]
@model_validator(mode="after")
def validate_provider_and_model(self) -> Self:
"""Perform validation on the provider and model."""
if self.model and not self.provider:
raise ValueError("Provider must be specified if model is specified")
if self.provider and not self.model:
raise ValueError("Model must be specified if provider is specified")
return self
@model_validator(mode="after")
def validate_media_type(self) -> Self:
"""Validate media_type field."""
if self.media_type and self.media_type not in [
MEDIA_TYPE_JSON,
MEDIA_TYPE_TEXT,
]:
raise ValueError(
f"media_type must be either '{MEDIA_TYPE_JSON}' or '{MEDIA_TYPE_TEXT}'"
)
return self
class FeedbackCategory(str, Enum):
"""Enum representing predefined feedback categories for AI responses.
These categories help provide structured feedback about AI inference quality
when users provide negative feedback (thumbs down). Multiple categories can
be selected to provide comprehensive feedback about response issues.
"""
INCORRECT = "incorrect" # "The answer provided is completely wrong"
NOT_RELEVANT = "not_relevant" # "This answer doesn't address my question at all"
INCOMPLETE = "incomplete" # "The answer only covers part of what I asked about"
OUTDATED_INFORMATION = "outdated_information" # "This information is from several years ago and no longer accurate" # pylint: disable=line-too-long
UNSAFE = "unsafe" # "This response could be harmful or dangerous if followed"
OTHER = "other" # "The response has issues not covered by other categories"
class FeedbackRequest(BaseModel):
"""Model representing a feedback request.
Attributes:
conversation_id: The required conversation ID (UUID).
user_question: The required user question.
llm_response: The required LLM response.
sentiment: The optional sentiment.
user_feedback: The optional user feedback.
categories: The optional list of feedback categories (multi-select for negative feedback).
Example:
```python
feedback_request = FeedbackRequest(
conversation_id="12345678-abcd-0000-0123-456789abcdef",
user_question="what are you doing?",
user_feedback="This response is not helpful",
llm_response="I don't know",
sentiment=-1,
categories=[FeedbackCategory.INCORRECT, FeedbackCategory.INCOMPLETE]
)
```
"""
conversation_id: str = Field(
description="The required conversation ID (UUID)",
examples=["c5260aec-4d82-4370-9fdf-05cf908b3f16"],
)
user_question: str = Field(
description="User question (the query string)",
examples=["What is Kubernetes?"],
)
llm_response: str = Field(
description="Response from LLM",
examples=[
"Kubernetes is an open-source container orchestration system for automating ..."
],
)
sentiment: Optional[int] = Field(
None,
description="User sentiment, if provided must be -1 or 1",
examples=[-1, 1],
)
# Optional user feedback limited to 1-4096 characters to prevent abuse.
user_feedback: Optional[str] = Field(
default=None,
max_length=4096,
description="Feedback on the LLM response.",
examples=["I'm not satisfied with the response because it is too vague."],
)
# Optional list of predefined feedback categories for negative feedback
categories: Optional[list[FeedbackCategory]] = Field(
default=None,
description=(
"List of feedback categories that describe issues with the LLM response "
"(for negative feedback)."
),
examples=[["incorrect", "incomplete"]],
)
# provides examples for /docs endpoint
model_config = {
"extra": "forbid",
"json_schema_extra": {
"examples": [
{
"conversation_id": "12345678-abcd-0000-0123-456789abcdef",
"user_question": "foo",
"llm_response": "bar",
"user_feedback": "Not satisfied with the response quality.",
"sentiment": -1,
},
{
"conversation_id": "12345678-abcd-0000-0123-456789abcdef",
"user_question": "What is the capital of France?",
"llm_response": "The capital of France is Berlin.",
"sentiment": -1,
"categories": ["incorrect"],
},
{
"conversation_id": "12345678-abcd-0000-0123-456789abcdef",
"user_question": "How do I deploy a web app?",
"llm_response": "Use Docker.",
"user_feedback": (
"This response is too general and doesn't provide specific steps."
),
"sentiment": -1,
"categories": ["incomplete", "not_relevant"],
},
]
},
}
@field_validator("conversation_id")
@classmethod
def check_uuid(cls, value: str) -> str:
"""Check if conversation ID has the proper format."""
if not suid.check_suid(value):
raise ValueError(f"Improper conversation ID {value}")
return value
@field_validator("sentiment")
@classmethod
def check_sentiment(cls, value: Optional[int]) -> Optional[int]:
"""Check if sentiment value is as expected."""
if value not in {-1, 1, None}:
raise ValueError(
f"Improper sentiment value of {value}, needs to be -1 or 1"
)
return value
@field_validator("categories")
@classmethod
def validate_categories(
cls, value: Optional[list[FeedbackCategory]]
) -> Optional[list[FeedbackCategory]]:
"""Validate feedback categories list."""
if value is None:
return value
if len(value) == 0:
return None # Convert empty list to None for consistency
unique_categories = list(dict.fromkeys(value)) # don't lose ordering
return unique_categories
@model_validator(mode="after")
def check_feedback_provided(self) -> Self:
"""Ensure that at least one form of feedback is provided."""
if (
self.sentiment is None
and (self.user_feedback is None or self.user_feedback == "")
and self.categories is None
):
raise ValueError(
"At least one form of feedback must be provided: "
"'sentiment', 'user_feedback', or 'categories'"
)
return self
class FeedbackStatusUpdateRequest(BaseModel):
"""Model representing a feedback status update request.
Attributes:
status: Value of the desired feedback enabled state.
Example:
```python
feedback_request = FeedbackRequest(
status=false
)
```
"""
status: bool = Field(
False,
description="Desired state of feedback enablement, must be False or True",
examples=[True, False],
)
# Reject unknown fields
model_config = {"extra": "forbid"}
def get_value(self) -> bool:
"""Return the value of the status attribute."""
return self.status
class CreateResponseRequest(BaseModel):
"""Model representing an OpenAI-compatible request for the Responses API.
This model follows the OpenAI API specification for the /v1/responses endpoint,
allowing clients to send requests in OpenAI format while maintaining internal
compatibility with Lightspeed's existing RAG and LLM integration.
Attributes:
model: The model to use for the response generation.
input: The input text or array of texts to process.
instructions: Optional instructions to guide the response generation.
temperature: Optional temperature for controlling randomness (0.0 to 2.0).
max_output_tokens: Optional maximum number of tokens in the response.
Example:
```python
request = CreateResponseRequest(
model="gpt-4",
input="What is Kubernetes?"
)
```
"""
model: str = Field(
description="The model to use for response generation",
examples=["gpt-4", "gpt-3.5-turbo"],
min_length=1,
)
input: str | list[str] = Field(
description="The input text or array of texts to process",
examples=["What is Kubernetes?", ["Explain containers", "How do they work?"]],
)
instructions: Optional[str] = Field(
None,
description="Optional instructions to guide the response generation",
examples=["You are a helpful DevOps assistant"],
)
temperature: Optional[float] = Field(
None,
description="Temperature for controlling randomness (0.0 to 2.0)",
examples=[0.7, 1.0],
ge=0.0,
le=2.0,
)
max_output_tokens: Optional[int] = Field(
None,
description="Maximum number of tokens in the response",
examples=[1000, 2000],
gt=0,
)
model_config = {
"extra": "forbid",
"json_schema_extra": {
"examples": [
{
"model": "gpt-4",
"input": "What is Kubernetes?",
},
{
"model": "gpt-3.5-turbo",
"input": "Explain Docker containers",
"instructions": "You are a helpful DevOps assistant",
"temperature": 0.7,
"max_output_tokens": 1000,
},
{
"model": "gpt-4",
"input": ["What is Kubernetes?", "How does it work?"],
"temperature": 0.5,
},
]
},
}
@field_validator("input")
@classmethod
def validate_input(cls, value: str | list[str]) -> str | list[str]:
"""Validate that input is not empty."""
if isinstance(value, str):
if not value.strip():
raise ValueError("Input string cannot be empty")
elif isinstance(value, list):
if not value:
raise ValueError("Input array cannot be empty")
for item in value:
if not isinstance(item, str) or not item.strip():
raise ValueError(
"All items in input array must be non-empty strings"
)
return value
class ConversationUpdateRequest(BaseModel):
"""Model representing a request to update a conversation topic summary.
Attributes:
topic_summary: The new topic summary for the conversation.
Example:
```python
update_request = ConversationUpdateRequest(
topic_summary="Discussion about machine learning algorithms"
)
```
"""
topic_summary: str = Field(
...,
description="The new topic summary for the conversation",
examples=["Discussion about machine learning algorithms"],
min_length=1,
max_length=1000,
)
# Reject unknown fields
model_config = {"extra": "forbid"}