maitai-python 1.2.26__py3-none-any.whl → 1.2.28__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.
- maitai/chat/__init__.py +0 -0
- maitai/chat/_completions.py +512 -0
- maitai/chat/_completions_async.py +520 -0
- maitai/transcriptions/__init__.py +0 -0
- maitai/transcriptions/_transcriptions.py +290 -0
- maitai/transcriptions/_transcriptions_async.py +289 -0
- maitai_common/version.py +1 -1
- {maitai_python-1.2.26.dist-info → maitai_python-1.2.28.dist-info}/METADATA +1 -1
- {maitai_python-1.2.26.dist-info → maitai_python-1.2.28.dist-info}/RECORD +11 -5
- {maitai_python-1.2.26.dist-info → maitai_python-1.2.28.dist-info}/WHEEL +0 -0
- {maitai_python-1.2.26.dist-info → maitai_python-1.2.28.dist-info}/top_level.txt +0 -0
maitai/chat/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import time
|
|
3
|
+
import uuid
|
|
4
|
+
import warnings
|
|
5
|
+
from typing import Dict, Iterable, List, Optional, Union
|
|
6
|
+
|
|
7
|
+
import groq
|
|
8
|
+
import httpx
|
|
9
|
+
import openai
|
|
10
|
+
import openai.types as openai_types
|
|
11
|
+
import openai.types.chat as openai_chat_types
|
|
12
|
+
|
|
13
|
+
from maitai._config import config
|
|
14
|
+
from maitai._evaluator import Evaluator
|
|
15
|
+
from maitai._inference import Inference
|
|
16
|
+
from maitai._types import (
|
|
17
|
+
Body,
|
|
18
|
+
EvaluateCallback,
|
|
19
|
+
FallbackConfig,
|
|
20
|
+
Headers,
|
|
21
|
+
MaitaiChunk,
|
|
22
|
+
MaitaiCompletion,
|
|
23
|
+
Query,
|
|
24
|
+
ToolFunction,
|
|
25
|
+
)
|
|
26
|
+
from maitai._utils import (
|
|
27
|
+
convert_open_ai_chat_completion_chunk,
|
|
28
|
+
convert_openai_chat_completion,
|
|
29
|
+
convert_params_to_groq,
|
|
30
|
+
get_chat_completion_params,
|
|
31
|
+
required_args,
|
|
32
|
+
type_to_response_format_param,
|
|
33
|
+
)
|
|
34
|
+
from maitai.exceptions import (
|
|
35
|
+
InferenceException,
|
|
36
|
+
InferenceWarning,
|
|
37
|
+
MaitaiConnectionError,
|
|
38
|
+
)
|
|
39
|
+
from maitai.models.chat import ChatCompletionParams, ClientParams, EvaluationContentType
|
|
40
|
+
from maitai.models.config import InferenceLocations
|
|
41
|
+
from maitai.models.inference import InferenceStreamResponse
|
|
42
|
+
from maitai.models.metric import RequestTimingMetric
|
|
43
|
+
from maitai.tools import Tools
|
|
44
|
+
|
|
45
|
+
logger = logging.getLogger("maitai")
|
|
46
|
+
|
|
47
|
+
DEFAULT_MAX_RETRIES = 2
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Completions:
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
openai_client: Optional[openai.Client] = None,
|
|
54
|
+
groq_client: Optional[groq.Groq] = None,
|
|
55
|
+
client_params: Optional[ClientParams] = None,
|
|
56
|
+
):
|
|
57
|
+
self._openai_client = openai_client
|
|
58
|
+
self._groq_client = groq_client
|
|
59
|
+
self._client_params = client_params or ClientParams()
|
|
60
|
+
self.evaluator = Evaluator()
|
|
61
|
+
self.inference = Inference()
|
|
62
|
+
|
|
63
|
+
@required_args(
|
|
64
|
+
["intent", "application", "messages"],
|
|
65
|
+
["intent", "application_ref_name", "messages"],
|
|
66
|
+
["intent", "application", "messages", "model"],
|
|
67
|
+
["intent", "application_ref_name", "messages", "model"],
|
|
68
|
+
["intent", "application", "messages", "model", "stream"],
|
|
69
|
+
["intent", "application_ref_name", "messages", "model", "stream"],
|
|
70
|
+
)
|
|
71
|
+
def create(
|
|
72
|
+
self,
|
|
73
|
+
*,
|
|
74
|
+
# Maitai Arguments
|
|
75
|
+
user_id: str = "",
|
|
76
|
+
session_id: Union[str, int] = "",
|
|
77
|
+
reference_id: Union[str, int, None] = None,
|
|
78
|
+
intent: str = "",
|
|
79
|
+
application: str = "",
|
|
80
|
+
callback: Optional[EvaluateCallback] = None,
|
|
81
|
+
server_side_inference: Optional[bool] = None,
|
|
82
|
+
evaluation_enabled: Optional[bool] = None,
|
|
83
|
+
apply_corrections: Optional[bool] = None,
|
|
84
|
+
metadata: dict = {},
|
|
85
|
+
safe_mode: Optional[bool] = None,
|
|
86
|
+
fallback_config: Union[FallbackConfig, dict, None] = None,
|
|
87
|
+
return_request: bool = False,
|
|
88
|
+
# OpenAI Arguments
|
|
89
|
+
messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
|
|
90
|
+
model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
|
|
91
|
+
frequency_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
92
|
+
function_call: Union[
|
|
93
|
+
openai_chat_types.completion_create_params.FunctionCall, openai.NotGiven
|
|
94
|
+
] = openai.NOT_GIVEN,
|
|
95
|
+
functions: Union[
|
|
96
|
+
Iterable[openai_chat_types.completion_create_params.Function],
|
|
97
|
+
openai.NotGiven,
|
|
98
|
+
] = openai.NOT_GIVEN,
|
|
99
|
+
logit_bias: Union[Optional[Dict[str, int]], openai.NotGiven] = openai.NOT_GIVEN,
|
|
100
|
+
logprobs: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
|
|
101
|
+
max_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
102
|
+
max_completion_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
103
|
+
n: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
104
|
+
presence_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
105
|
+
reasoning_effort: Union[str, openai.NotGiven, None] = openai.NOT_GIVEN,
|
|
106
|
+
response_format: Union[
|
|
107
|
+
openai_chat_types.completion_create_params.ResponseFormat, openai.NotGiven
|
|
108
|
+
] = openai.NOT_GIVEN,
|
|
109
|
+
seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
110
|
+
stop: Union[
|
|
111
|
+
Union[Optional[str], List[str]], openai.NotGiven
|
|
112
|
+
] = openai.NOT_GIVEN,
|
|
113
|
+
stream: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
|
|
114
|
+
stream_options: Union[
|
|
115
|
+
Optional[openai_chat_types.ChatCompletionStreamOptionsParam],
|
|
116
|
+
openai.NotGiven,
|
|
117
|
+
] = openai.NOT_GIVEN,
|
|
118
|
+
temperature: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
119
|
+
tool_choice: Union[
|
|
120
|
+
openai_chat_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven
|
|
121
|
+
] = openai.NOT_GIVEN,
|
|
122
|
+
tools: Union[
|
|
123
|
+
Tools,
|
|
124
|
+
Iterable[Union[openai_chat_types.ChatCompletionToolParam, ToolFunction]],
|
|
125
|
+
openai.NotGiven,
|
|
126
|
+
] = openai.NOT_GIVEN,
|
|
127
|
+
top_logprobs: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
128
|
+
top_p: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
129
|
+
user: Union[str, openai.NotGiven] = openai.NOT_GIVEN,
|
|
130
|
+
extra_headers: Union[
|
|
131
|
+
None, Headers, Dict[str, str], openai.NotGiven
|
|
132
|
+
] = openai.NOT_GIVEN,
|
|
133
|
+
extra_query: Optional[Query] = None,
|
|
134
|
+
extra_body: Optional[Body] = None,
|
|
135
|
+
timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NOT_GIVEN,
|
|
136
|
+
parallel_tool_calls: Union[bool, openai.NotGiven] = openai.NOT_GIVEN,
|
|
137
|
+
) -> Union[MaitaiCompletion, Iterable[MaitaiChunk]]:
|
|
138
|
+
retry_args = locals()
|
|
139
|
+
timing = RequestTimingMetric(
|
|
140
|
+
time_request_start=time.time(),
|
|
141
|
+
)
|
|
142
|
+
if not config.api_key:
|
|
143
|
+
raise ValueError("Maitai API Key has not been set")
|
|
144
|
+
if server_side_inference is False and apply_corrections is True:
|
|
145
|
+
raise ValueError("server_side_inference must be true to apply_corrections")
|
|
146
|
+
if apply_corrections is True and evaluation_enabled is False:
|
|
147
|
+
raise ValueError("evaluations must be enabled to apply_corrections")
|
|
148
|
+
if not session_id:
|
|
149
|
+
session_id = str(uuid.uuid4())
|
|
150
|
+
maitai_config = config.get_application_action_config(application, intent)
|
|
151
|
+
if server_side_inference is None:
|
|
152
|
+
server_side_inference = (
|
|
153
|
+
maitai_config.inference_location == InferenceLocations.SERVER
|
|
154
|
+
)
|
|
155
|
+
if evaluation_enabled is None:
|
|
156
|
+
evaluation_enabled = maitai_config.evaluation_enabled
|
|
157
|
+
if apply_corrections is None:
|
|
158
|
+
apply_corrections = maitai_config.apply_corrections
|
|
159
|
+
if model == openai.NOT_GIVEN:
|
|
160
|
+
model = maitai_config.model
|
|
161
|
+
if temperature == openai.NOT_GIVEN:
|
|
162
|
+
temperature = maitai_config.temperature
|
|
163
|
+
if safe_mode is None:
|
|
164
|
+
safe_mode = maitai_config.safe_mode
|
|
165
|
+
if stream == openai.NOT_GIVEN:
|
|
166
|
+
stream = False
|
|
167
|
+
if response_format == openai.NOT_GIVEN:
|
|
168
|
+
response_format = {"type": "text"}
|
|
169
|
+
if stop == openai.NOT_GIVEN and maitai_config.stop is not None:
|
|
170
|
+
stop = maitai_config.stop
|
|
171
|
+
if logprobs == openai.NOT_GIVEN:
|
|
172
|
+
logprobs = maitai_config.logprobs
|
|
173
|
+
if max_tokens == openai.NOT_GIVEN and maitai_config.max_tokens is not None:
|
|
174
|
+
max_tokens = maitai_config.max_tokens
|
|
175
|
+
if max_completion_tokens and max_completion_tokens != openai.NOT_GIVEN:
|
|
176
|
+
max_tokens = max_completion_tokens
|
|
177
|
+
if n == openai.NOT_GIVEN and maitai_config.n:
|
|
178
|
+
n = maitai_config.n
|
|
179
|
+
if frequency_penalty == openai.NOT_GIVEN:
|
|
180
|
+
frequency_penalty = maitai_config.frequency_penalty
|
|
181
|
+
if presence_penalty == openai.NOT_GIVEN:
|
|
182
|
+
presence_penalty = maitai_config.presence_penalty
|
|
183
|
+
if timeout == openai.NOT_GIVEN and maitai_config.timeout > 0:
|
|
184
|
+
timeout = maitai_config.timeout
|
|
185
|
+
if fallback_config is None and maitai_config.fallback_config:
|
|
186
|
+
fallback_config = {
|
|
187
|
+
"model": maitai_config.fallback_config.model,
|
|
188
|
+
"strategy": maitai_config.fallback_config.strategy,
|
|
189
|
+
"timeout": maitai_config.fallback_config.timeout,
|
|
190
|
+
}
|
|
191
|
+
completion_params = get_chat_completion_params(
|
|
192
|
+
messages=messages,
|
|
193
|
+
model=model,
|
|
194
|
+
frequency_penalty=frequency_penalty,
|
|
195
|
+
logit_bias=logit_bias,
|
|
196
|
+
logprobs=logprobs,
|
|
197
|
+
max_tokens=max_tokens,
|
|
198
|
+
n=n,
|
|
199
|
+
presence_penalty=presence_penalty,
|
|
200
|
+
response_format=response_format,
|
|
201
|
+
seed=seed,
|
|
202
|
+
stop=stop,
|
|
203
|
+
stream=stream,
|
|
204
|
+
stream_options=stream_options,
|
|
205
|
+
temperature=temperature,
|
|
206
|
+
tool_choice=tool_choice,
|
|
207
|
+
tools=tools,
|
|
208
|
+
top_logprobs=top_logprobs,
|
|
209
|
+
top_p=top_p,
|
|
210
|
+
user=user,
|
|
211
|
+
parallel_tool_calls=parallel_tool_calls,
|
|
212
|
+
extra_headers=extra_headers,
|
|
213
|
+
reasoning_effort=reasoning_effort,
|
|
214
|
+
)
|
|
215
|
+
if server_side_inference:
|
|
216
|
+
response_timeout = None
|
|
217
|
+
if isinstance(timeout, float) or isinstance(timeout, int):
|
|
218
|
+
response_timeout = timeout
|
|
219
|
+
request_dict = {
|
|
220
|
+
"application_ref_name": application,
|
|
221
|
+
"session_id": session_id,
|
|
222
|
+
"reference_id": reference_id,
|
|
223
|
+
"action_type": intent,
|
|
224
|
+
"apply_corrections": apply_corrections,
|
|
225
|
+
"evaluation_enabled": evaluation_enabled,
|
|
226
|
+
"params": completion_params,
|
|
227
|
+
"return_evaluation": True if callback else False,
|
|
228
|
+
"user_id": user_id,
|
|
229
|
+
"auth_keys": config.auth_keys.model_dump(),
|
|
230
|
+
"metadata": metadata,
|
|
231
|
+
"safe_mode": safe_mode,
|
|
232
|
+
"return_request": return_request,
|
|
233
|
+
"fallback_config": fallback_config,
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if self._client_params is not None:
|
|
237
|
+
request_dict["client_params"] = self._client_params.model_dump()
|
|
238
|
+
|
|
239
|
+
try:
|
|
240
|
+
timing.time_pre_request = time.time()
|
|
241
|
+
response = self.inference.infer(
|
|
242
|
+
request_dict, callback, response_timeout
|
|
243
|
+
)
|
|
244
|
+
if stream:
|
|
245
|
+
if "self" in retry_args:
|
|
246
|
+
del retry_args["self"]
|
|
247
|
+
retry_args["server_side_inference"] = False
|
|
248
|
+
retry_args["model"] = model
|
|
249
|
+
return self._process_inference_stream(
|
|
250
|
+
response,
|
|
251
|
+
retry_args,
|
|
252
|
+
timing,
|
|
253
|
+
includes_usage=(
|
|
254
|
+
stream_options.get("include_usage", False)
|
|
255
|
+
if stream_options and stream_options != openai.NOT_GIVEN
|
|
256
|
+
else False
|
|
257
|
+
),
|
|
258
|
+
)
|
|
259
|
+
# ChatCompletion only
|
|
260
|
+
for resp in response:
|
|
261
|
+
if resp.warning:
|
|
262
|
+
warnings.warn(resp.warning, InferenceWarning)
|
|
263
|
+
if resp.error:
|
|
264
|
+
if "Unknown error occurred" in resp.error:
|
|
265
|
+
raise MaitaiConnectionError(resp.error)
|
|
266
|
+
raise InferenceException(resp.error)
|
|
267
|
+
timing.request_id = resp.chat_completion_response.request_id
|
|
268
|
+
timing.time_request_end = time.time()
|
|
269
|
+
self.inference.store_request_timing_data(timing)
|
|
270
|
+
completion = MaitaiCompletion.model_validate(
|
|
271
|
+
resp.chat_completion_response.model_dump()
|
|
272
|
+
)
|
|
273
|
+
completion.set_response_format(response_format)
|
|
274
|
+
return completion
|
|
275
|
+
raise InferenceException("No data received")
|
|
276
|
+
except MaitaiConnectionError as e:
|
|
277
|
+
fallback_model = (
|
|
278
|
+
fallback_config.get("model") if fallback_config else None
|
|
279
|
+
)
|
|
280
|
+
if "gpt" not in model and fallback_model and "gpt" in fallback_model:
|
|
281
|
+
model = fallback_model
|
|
282
|
+
if "gpt" not in model:
|
|
283
|
+
raise e
|
|
284
|
+
if safe_mode:
|
|
285
|
+
raise e
|
|
286
|
+
logger.warning("Maitai issue, retrying on client side")
|
|
287
|
+
server_side_inference = False
|
|
288
|
+
if not server_side_inference:
|
|
289
|
+
groq_model = False
|
|
290
|
+
if "groq:" in model or "maitai:" in model or "llama" in model:
|
|
291
|
+
groq_model = True
|
|
292
|
+
model = model.replace("groq:", "").replace("maitai:", "")
|
|
293
|
+
if "openai:" in model:
|
|
294
|
+
model = model.replace("openai:", "")
|
|
295
|
+
local_params = {
|
|
296
|
+
"messages": messages,
|
|
297
|
+
"model": model,
|
|
298
|
+
"frequency_penalty": frequency_penalty,
|
|
299
|
+
"function_call": function_call,
|
|
300
|
+
"functions": functions,
|
|
301
|
+
"logit_bias": logit_bias,
|
|
302
|
+
"logprobs": logprobs,
|
|
303
|
+
"max_tokens": max_tokens,
|
|
304
|
+
"n": n,
|
|
305
|
+
"presence_penalty": presence_penalty,
|
|
306
|
+
"reasoning_effort": reasoning_effort,
|
|
307
|
+
"response_format": response_format,
|
|
308
|
+
"seed": seed,
|
|
309
|
+
"stop": stop,
|
|
310
|
+
"stream": stream,
|
|
311
|
+
"stream_options": stream_options,
|
|
312
|
+
"temperature": temperature,
|
|
313
|
+
"tool_choice": tool_choice,
|
|
314
|
+
"tools": tools,
|
|
315
|
+
"top_logprobs": top_logprobs,
|
|
316
|
+
"top_p": top_p,
|
|
317
|
+
"user": user,
|
|
318
|
+
"extra_headers": extra_headers,
|
|
319
|
+
"extra_query": extra_query,
|
|
320
|
+
"extra_body": extra_body,
|
|
321
|
+
"timeout": timeout,
|
|
322
|
+
"parallel_tool_calls": parallel_tool_calls,
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if groq_model:
|
|
326
|
+
if self._groq_client is None:
|
|
327
|
+
if (
|
|
328
|
+
not config.auth_keys.groq_api_key
|
|
329
|
+
or not config.auth_keys.groq_api_key.key_value
|
|
330
|
+
):
|
|
331
|
+
raise ValueError(
|
|
332
|
+
"Groq API key is required for Groq models but was not provided"
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
self._groq_client = groq.Groq(
|
|
336
|
+
api_key=config.auth_keys.groq_api_key.key_value,
|
|
337
|
+
)
|
|
338
|
+
client_to_use = self._groq_client
|
|
339
|
+
local_params = convert_params_to_groq(local_params)
|
|
340
|
+
else:
|
|
341
|
+
if self._openai_client is None:
|
|
342
|
+
self._openai_client = openai.OpenAI(
|
|
343
|
+
api_key=config.auth_keys.openai_api_key.key_value,
|
|
344
|
+
default_headers=self._client_params.default_headers or None,
|
|
345
|
+
default_query=self._client_params.default_query or None,
|
|
346
|
+
base_url=self._client_params.base_url or None,
|
|
347
|
+
)
|
|
348
|
+
client_to_use = self._openai_client
|
|
349
|
+
|
|
350
|
+
if hasattr(response_format, "model_json_schema"):
|
|
351
|
+
response_format = {
|
|
352
|
+
"type": "json_schema",
|
|
353
|
+
"json_schema": type_to_response_format_param(response_format),
|
|
354
|
+
}
|
|
355
|
+
if isinstance(tools, Tools):
|
|
356
|
+
tools = tools.get_tool_definitions()
|
|
357
|
+
|
|
358
|
+
response = client_to_use.chat.completions.create(**local_params)
|
|
359
|
+
if stream:
|
|
360
|
+
return self._process_openai_stream(
|
|
361
|
+
session_id,
|
|
362
|
+
reference_id,
|
|
363
|
+
intent,
|
|
364
|
+
application,
|
|
365
|
+
messages,
|
|
366
|
+
response,
|
|
367
|
+
evaluation_enabled,
|
|
368
|
+
completion_params,
|
|
369
|
+
timing,
|
|
370
|
+
callback,
|
|
371
|
+
metadata,
|
|
372
|
+
)
|
|
373
|
+
else:
|
|
374
|
+
timing.time_request_end = time.time()
|
|
375
|
+
maitai_completion = convert_openai_chat_completion(response)
|
|
376
|
+
full_conv = messages + [
|
|
377
|
+
{
|
|
378
|
+
"role": "assistant",
|
|
379
|
+
"content": maitai_completion.choices[0].message.content,
|
|
380
|
+
}
|
|
381
|
+
]
|
|
382
|
+
if evaluation_enabled:
|
|
383
|
+
self.evaluator.evaluate(
|
|
384
|
+
session_id=session_id,
|
|
385
|
+
reference_id=reference_id,
|
|
386
|
+
intent=intent,
|
|
387
|
+
content_type=EvaluationContentType.MESSAGE,
|
|
388
|
+
content=full_conv,
|
|
389
|
+
application_ref_name=application,
|
|
390
|
+
callback=callback,
|
|
391
|
+
chat_completion_response=maitai_completion,
|
|
392
|
+
completion_params=completion_params,
|
|
393
|
+
timing=timing,
|
|
394
|
+
metadata=metadata,
|
|
395
|
+
)
|
|
396
|
+
else:
|
|
397
|
+
self.inference.store_chat_response(
|
|
398
|
+
session_id=session_id,
|
|
399
|
+
reference_id=reference_id,
|
|
400
|
+
intent=intent,
|
|
401
|
+
application_ref_name=application,
|
|
402
|
+
chat_completion_response=maitai_completion,
|
|
403
|
+
completion_params=completion_params,
|
|
404
|
+
final_chunk=None,
|
|
405
|
+
content="",
|
|
406
|
+
timing=timing,
|
|
407
|
+
metadata=metadata,
|
|
408
|
+
)
|
|
409
|
+
completion = MaitaiCompletion.model_validate(
|
|
410
|
+
maitai_completion.model_dump()
|
|
411
|
+
)
|
|
412
|
+
completion.set_response_format(response_format)
|
|
413
|
+
return completion
|
|
414
|
+
|
|
415
|
+
def _process_openai_stream(
|
|
416
|
+
self,
|
|
417
|
+
session_id: Union[str, int],
|
|
418
|
+
reference_id: Union[str, int, None],
|
|
419
|
+
intent: str,
|
|
420
|
+
application: str,
|
|
421
|
+
messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
|
|
422
|
+
stream: openai.Stream[openai_chat_types.ChatCompletionChunk],
|
|
423
|
+
evaluation_enabled: bool,
|
|
424
|
+
chat_completion_params: ChatCompletionParams,
|
|
425
|
+
timing: RequestTimingMetric,
|
|
426
|
+
callback: Optional[EvaluateCallback] = None,
|
|
427
|
+
metadata: dict = {},
|
|
428
|
+
) -> Iterable[MaitaiChunk]:
|
|
429
|
+
full_body = ""
|
|
430
|
+
last_chunk = None
|
|
431
|
+
for chunk in stream:
|
|
432
|
+
if last_chunk is None:
|
|
433
|
+
timing.time_first_chunk = time.time()
|
|
434
|
+
maitai_chunk = convert_open_ai_chat_completion_chunk(chunk)
|
|
435
|
+
if maitai_chunk.choices:
|
|
436
|
+
last_chunk = maitai_chunk
|
|
437
|
+
content = maitai_chunk.choices[0].delta.content
|
|
438
|
+
if content is not None:
|
|
439
|
+
full_body += content
|
|
440
|
+
if maitai_chunk.usage and last_chunk is not None and not last_chunk.usage:
|
|
441
|
+
last_chunk.usage = maitai_chunk.usage
|
|
442
|
+
yield MaitaiChunk.model_validate(maitai_chunk.model_dump())
|
|
443
|
+
timing.time_request_end = time.time()
|
|
444
|
+
if last_chunk is None:
|
|
445
|
+
return
|
|
446
|
+
if evaluation_enabled:
|
|
447
|
+
full_conv = messages + [{"role": "assistant", "content": full_body}]
|
|
448
|
+
self.evaluator.evaluate(
|
|
449
|
+
session_id=session_id,
|
|
450
|
+
reference_id=reference_id,
|
|
451
|
+
intent=intent,
|
|
452
|
+
content_type=EvaluationContentType.MESSAGE,
|
|
453
|
+
content=full_conv,
|
|
454
|
+
application_ref_name=application,
|
|
455
|
+
callback=callback,
|
|
456
|
+
chat_completion_chunk=last_chunk,
|
|
457
|
+
completion_params=chat_completion_params,
|
|
458
|
+
timing=timing,
|
|
459
|
+
metadata=metadata,
|
|
460
|
+
)
|
|
461
|
+
else:
|
|
462
|
+
self.inference.store_chat_response(
|
|
463
|
+
session_id=session_id,
|
|
464
|
+
reference_id=reference_id,
|
|
465
|
+
intent=intent,
|
|
466
|
+
application_ref_name=application,
|
|
467
|
+
completion_params=chat_completion_params,
|
|
468
|
+
final_chunk=last_chunk,
|
|
469
|
+
content=full_body,
|
|
470
|
+
chat_completion_response=None,
|
|
471
|
+
timing=timing,
|
|
472
|
+
metadata=metadata,
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
def _process_inference_stream(
|
|
476
|
+
self,
|
|
477
|
+
stream: Iterable[InferenceStreamResponse],
|
|
478
|
+
retry_args: dict,
|
|
479
|
+
timing: RequestTimingMetric,
|
|
480
|
+
includes_usage: bool = False,
|
|
481
|
+
) -> Iterable[MaitaiChunk]:
|
|
482
|
+
first = True
|
|
483
|
+
try:
|
|
484
|
+
for infer_resp in stream:
|
|
485
|
+
if infer_resp.warning:
|
|
486
|
+
warnings.warn(infer_resp.warning, InferenceWarning)
|
|
487
|
+
if infer_resp.error:
|
|
488
|
+
raise InferenceException(infer_resp.error)
|
|
489
|
+
chunk = infer_resp.chat_completion_chunk
|
|
490
|
+
if chunk is not None:
|
|
491
|
+
if first:
|
|
492
|
+
timing.time_first_chunk = time.time()
|
|
493
|
+
timing.request_id = chunk.request_id
|
|
494
|
+
first = False
|
|
495
|
+
yield MaitaiChunk.model_validate(chunk.model_dump())
|
|
496
|
+
if chunk.choices and chunk.choices[0].finish_reason:
|
|
497
|
+
timing.time_request_end = time.time()
|
|
498
|
+
self.inference.store_request_timing_data(timing)
|
|
499
|
+
if chunk.choices and chunk.choices[0].finish_reason:
|
|
500
|
+
return
|
|
501
|
+
except MaitaiConnectionError as e:
|
|
502
|
+
if "gpt" not in retry_args.get("model", "") and "gpt" in (
|
|
503
|
+
retry_args.get("fallback_model", "") or ""
|
|
504
|
+
):
|
|
505
|
+
retry_args["model"] = retry_args["fallback_model"]
|
|
506
|
+
if "gpt" in retry_args.get("model", ""):
|
|
507
|
+
retry_args["model"] = retry_args["model"].replace("openai:", "")
|
|
508
|
+
response = self.create(**retry_args)
|
|
509
|
+
for resp in response:
|
|
510
|
+
yield resp
|
|
511
|
+
else:
|
|
512
|
+
raise e
|