maitai-python 1.1.21b2__tar.gz → 1.1.22__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.
Files changed (50) hide show
  1. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/PKG-INFO +1 -1
  2. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/_maitai.py +114 -49
  3. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/_maitai_async.py +114 -48
  4. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/_types.py +1 -5
  5. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_common/config/config_service.py +2 -1
  6. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_common/processes/websocket_listener_thread.py +10 -7
  7. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_common/version.py +1 -1
  8. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/billing/__init__.py +8 -0
  9. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/chat/__init__.py +4 -4
  10. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/config/__init__.py +1 -0
  11. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_python.egg-info/PKG-INFO +1 -1
  12. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/README.md +0 -0
  13. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/__init__.py +0 -0
  14. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/_azure.py +0 -0
  15. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/_config.py +0 -0
  16. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/_config_listener_thread.py +0 -0
  17. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/_context.py +0 -0
  18. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/_evaluator.py +0 -0
  19. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/_inference.py +0 -0
  20. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/_maitai_client.py +0 -0
  21. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/_utils.py +0 -0
  22. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai/tools/__init__.py +0 -0
  23. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_common/__init__.py +0 -0
  24. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_common/config/__init__.py +0 -0
  25. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_common/processes/__init__.py +0 -0
  26. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_common/processes/io_thread.py +0 -0
  27. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_common/utils/__init__.py +0 -0
  28. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_common/utils/proto_utils.py +0 -0
  29. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_common/utils/types.py +0 -0
  30. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/__init__.py +0 -0
  31. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/application/__init__.py +0 -0
  32. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/backtest/__init__.py +0 -0
  33. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/company/__init__.py +0 -0
  34. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/embedding/__init__.py +0 -0
  35. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/event/__init__.py +0 -0
  36. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/inference/__init__.py +0 -0
  37. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/key/__init__.py +0 -0
  38. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/metric/__init__.py +0 -0
  39. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/model/__init__.py +0 -0
  40. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/notification/__init__.py +0 -0
  41. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/rates/__init__.py +0 -0
  42. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/sandbox/__init__.py +0 -0
  43. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/sentinel/__init__.py +0 -0
  44. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_gen/session/__init__.py +0 -0
  45. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_python.egg-info/SOURCES.txt +0 -0
  46. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_python.egg-info/dependency_links.txt +0 -0
  47. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_python.egg-info/requires.txt +0 -0
  48. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/maitai_python.egg-info/top_level.txt +0 -0
  49. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/setup.cfg +0 -0
  50. {maitai_python-1.1.21b2 → maitai_python-1.1.22}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: maitai-python
3
- Version: 1.1.21b2
3
+ Version: 1.1.22
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -93,16 +93,22 @@ class Chat:
93
93
 
94
94
 
95
95
  class Completions:
96
- def __init__(self, client: Optional[openai.Client] = None, client_params: Optional[ClientParams] = None):
96
+ def __init__(
97
+ self,
98
+ client: Optional[openai.Client] = None,
99
+ client_params: Optional[ClientParams] = None,
100
+ ):
97
101
  self._client = client
98
102
  self._client_params = client_params or ClientParams()
99
103
 
100
- @required_args(["intent", "application", "messages"],
101
- ["intent", "application_ref_name", "messages"],
102
- ["intent", "application", "messages", "model"],
103
- ["intent", "application_ref_name", "messages", "model"],
104
- ["intent", "application", "messages", "model", "stream"],
105
- ["intent", "application_ref_name", "messages", "model", "stream"])
104
+ @required_args(
105
+ ["intent", "application", "messages"],
106
+ ["intent", "application_ref_name", "messages"],
107
+ ["intent", "application", "messages", "model"],
108
+ ["intent", "application_ref_name", "messages", "model"],
109
+ ["intent", "application", "messages", "model", "stream"],
110
+ ["intent", "application_ref_name", "messages", "model", "stream"],
111
+ )
106
112
  def create(
107
113
  self,
108
114
  *,
@@ -112,37 +118,56 @@ class Completions:
112
118
  reference_id: Union[str, int, None] = None,
113
119
  intent: str = None,
114
120
  action_type: str = None, # DEPRECATED
115
- application_ref_name: str = None, # DEPRECATED
121
+ application_ref_name: str = None, # DEPRECATED
116
122
  application: str = None,
117
123
  callback: Optional[EvaluateCallback] = None,
118
124
  server_side_inference: bool = None,
119
125
  evaluation_enabled: bool = None,
120
126
  apply_corrections: bool = None,
121
127
  context_retrieval_enabled: bool = None,
122
- context_query: str = '',
128
+ context_query: str = "",
123
129
  return_request: bool = False,
124
130
  fallback_model: str = None,
125
131
  assistant: bool = False,
126
132
  metadata: dict = {},
133
+ safe_mode: bool = None,
127
134
  # OpenAI Arguments
128
135
  messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
129
136
  model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
130
137
  frequency_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
131
- function_call: Union[openai_chat_types.completion_create_params.FunctionCall, openai.NotGiven] = openai.NOT_GIVEN,
132
- functions: Union[Iterable[openai_chat_types.completion_create_params.Function], openai.NotGiven] = openai.NOT_GIVEN,
138
+ function_call: Union[
139
+ openai_chat_types.completion_create_params.FunctionCall, openai.NotGiven
140
+ ] = openai.NOT_GIVEN,
141
+ functions: Union[
142
+ Iterable[openai_chat_types.completion_create_params.Function],
143
+ openai.NotGiven,
144
+ ] = openai.NOT_GIVEN,
133
145
  logit_bias: Union[Optional[Dict[str, int]], openai.NotGiven] = openai.NOT_GIVEN,
134
146
  logprobs: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
135
147
  max_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
136
148
  n: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
137
149
  presence_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
138
- response_format: Union[openai_chat_types.completion_create_params.ResponseFormat, openai.NotGiven] = openai.NOT_GIVEN,
150
+ response_format: Union[
151
+ openai_chat_types.completion_create_params.ResponseFormat, openai.NotGiven
152
+ ] = openai.NOT_GIVEN,
139
153
  seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
140
- stop: Union[Union[Optional[str], List[str]], openai.NotGiven] = openai.NOT_GIVEN,
154
+ stop: Union[
155
+ Union[Optional[str], List[str]], openai.NotGiven
156
+ ] = openai.NOT_GIVEN,
141
157
  stream: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
142
- stream_options: Union[Optional[openai_chat_types.ChatCompletionStreamOptionsParam], openai.NotGiven] = openai.NOT_GIVEN,
158
+ stream_options: Union[
159
+ Optional[openai_chat_types.ChatCompletionStreamOptionsParam],
160
+ openai.NotGiven,
161
+ ] = openai.NOT_GIVEN,
143
162
  temperature: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
144
- tool_choice: Union[openai_chat_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven] = openai.NOT_GIVEN,
145
- tools: Union[Tools, Iterable[Union[openai_chat_types.ChatCompletionToolParam, ToolFunction]], openai.NotGiven] = openai.NOT_GIVEN,
163
+ tool_choice: Union[
164
+ openai_chat_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven
165
+ ] = openai.NOT_GIVEN,
166
+ tools: Union[
167
+ Tools,
168
+ Iterable[Union[openai_chat_types.ChatCompletionToolParam, ToolFunction]],
169
+ openai.NotGiven,
170
+ ] = openai.NOT_GIVEN,
146
171
  top_logprobs: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
147
172
  top_p: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
148
173
  user: Union[str, openai.NotGiven] = openai.NOT_GIVEN,
@@ -164,20 +189,30 @@ class Completions:
164
189
  raise ValueError("evaluations must be enabled to apply_corrections")
165
190
  if assistant is True:
166
191
  user_msgs = [True for msg in messages if msg["role"] == "user"]
167
- assistant_messages = [True for msg in messages if msg["role"] == "assistant"]
192
+ assistant_messages = [
193
+ True for msg in messages if msg["role"] == "assistant"
194
+ ]
168
195
  if len(user_msgs) != 1:
169
- raise ValueError("When assistant = True, exactly 1 user message is required")
196
+ raise ValueError(
197
+ "When assistant = True, exactly 1 user message is required"
198
+ )
170
199
  if len(assistant_messages) > 0:
171
- raise ValueError("When assistant = True, no assistant messages are allowed")
200
+ raise ValueError(
201
+ "When assistant = True, no assistant messages are allowed"
202
+ )
172
203
  if not session_id:
173
204
  session_id = str(uuid.uuid4())
174
205
  if not intent and action_type:
175
206
  intent = action_type
176
207
  if not application_ref_name and application:
177
208
  application_ref_name = application
178
- maitai_config = config.get_application_action_config(application_ref_name, intent)
209
+ maitai_config = config.get_application_action_config(
210
+ application_ref_name, intent
211
+ )
179
212
  if server_side_inference is None:
180
- server_side_inference = maitai_config.inference_location == InferenceLocations.SERVER
213
+ server_side_inference = (
214
+ maitai_config.inference_location == InferenceLocations.SERVER
215
+ )
181
216
  if evaluation_enabled is None:
182
217
  evaluation_enabled = maitai_config.evaluation_enabled
183
218
  if apply_corrections is None:
@@ -186,10 +221,12 @@ class Completions:
186
221
  model = maitai_config.model
187
222
  if temperature == openai.NOT_GIVEN:
188
223
  temperature = maitai_config.temperature
224
+ if safe_mode is None:
225
+ safe_mode = maitai_config.safe_mode
189
226
  if stream == openai.NOT_GIVEN:
190
- stream = maitai_config.streaming
227
+ stream = False
191
228
  if response_format == openai.NOT_GIVEN:
192
- response_format = {"type": maitai_config.response_format}
229
+ response_format = {"type": "text"}
193
230
  if stop == openai.NOT_GIVEN and maitai_config.stop is not None:
194
231
  stop = maitai_config.stop
195
232
  if logprobs == openai.NOT_GIVEN:
@@ -253,19 +290,24 @@ class Completions:
253
290
  assistant=assistant,
254
291
  auth_keys=config.auth_keys,
255
292
  metadata=metadata,
293
+ safe_mode=safe_mode,
256
294
  )
257
295
  if self._client_params is not None:
258
296
  chat_request.client_params = self._client_params
259
297
  try:
260
298
  timing.time_pre_request = time.time()
261
- response = maitai.Inference.infer(chat_request, callback, response_timeout)
299
+ response = maitai.Inference.infer(
300
+ chat_request, callback, response_timeout
301
+ )
262
302
  if stream:
263
- if 'self' in retry_args:
264
- del retry_args['self']
265
- retry_args['server_side_inference'] = False
266
- retry_args['model'] = model
267
- retry_args['fallback_model'] = fallback_model
268
- return _process_inference_stream(response, retry_args, self.create, timing)
303
+ if "self" in retry_args:
304
+ del retry_args["self"]
305
+ retry_args["server_side_inference"] = False
306
+ retry_args["model"] = model
307
+ retry_args["fallback_model"] = fallback_model
308
+ return _process_inference_stream(
309
+ response, retry_args, self.create, timing
310
+ )
269
311
  # ChatCompletion only
270
312
  for resp in response:
271
313
  if resp.warning:
@@ -318,16 +360,31 @@ class Completions:
318
360
  extra_body=extra_body,
319
361
  timeout=timeout,
320
362
  parallel_tool_calls=parallel_tool_calls,
321
-
322
363
  )
323
364
  if stream:
324
- return _process_openai_stream(session_id, reference_id, intent, application_ref_name, messages, response, evaluation_enabled, completion_params, timing, callback, metadata)
365
+ return _process_openai_stream(
366
+ session_id,
367
+ reference_id,
368
+ intent,
369
+ application_ref_name,
370
+ messages,
371
+ response,
372
+ evaluation_enabled,
373
+ completion_params,
374
+ timing,
375
+ callback,
376
+ metadata,
377
+ )
325
378
  else:
326
379
  timing.time_request_end = time.time()
327
380
  maitai_completion = convert_openai_chat_completion(response)
328
381
  proto_messages = openai_messages_to_proto(messages)
329
382
  proto_messages.append(
330
- ChatMessage(role="assistant", content=maitai_completion.choices[0].message.content))
383
+ ChatMessage(
384
+ role="assistant",
385
+ content=maitai_completion.choices[0].message.content,
386
+ )
387
+ )
331
388
  if evaluation_enabled:
332
389
  maitai.Evaluator.evaluate(
333
390
  session_id=session_id,
@@ -358,18 +415,19 @@ class Completions:
358
415
  return MaitaiCompletion(maitai_completion)
359
416
 
360
417
 
361
- def _process_openai_stream(session_id: Union[str, int],
362
- reference_id: Union[str, int, None],
363
- intent: str,
364
- application_ref_name: str,
365
- messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
366
- stream: openai.Stream[openai_chat_types.ChatCompletionChunk],
367
- evaluation_enabled: bool,
368
- chat_completion_params: ChatCompletionParams,
369
- timing: RequestTimingMetric,
370
- callback: Optional[EvaluateCallback] = None,
371
- metadata: dict = {},
372
- ) -> Iterable[MaitaiChunk]:
418
+ def _process_openai_stream(
419
+ session_id: Union[str, int],
420
+ reference_id: Union[str, int, None],
421
+ intent: str,
422
+ application_ref_name: str,
423
+ messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
424
+ stream: openai.Stream[openai_chat_types.ChatCompletionChunk],
425
+ evaluation_enabled: bool,
426
+ chat_completion_params: ChatCompletionParams,
427
+ timing: RequestTimingMetric,
428
+ callback: Optional[EvaluateCallback] = None,
429
+ metadata: dict = {},
430
+ ) -> Iterable[MaitaiChunk]:
373
431
  full_body = ""
374
432
  proto_messages = openai_messages_to_proto(messages)
375
433
  last_chunk = None
@@ -416,7 +474,12 @@ def _process_openai_stream(session_id: Union[str, int],
416
474
  )
417
475
 
418
476
 
419
- def _process_inference_stream(stream: Iterable[InferenceStreamResponse], retry_args: dict, retry_func, timing: RequestTimingMetric) -> Iterable[MaitaiChunk]:
477
+ def _process_inference_stream(
478
+ stream: Iterable[InferenceStreamResponse],
479
+ retry_args: dict,
480
+ retry_func,
481
+ timing: RequestTimingMetric,
482
+ ) -> Iterable[MaitaiChunk]:
420
483
  first = True
421
484
  try:
422
485
  for infer_resp in stream:
@@ -436,9 +499,11 @@ def _process_inference_stream(stream: Iterable[InferenceStreamResponse], retry_a
436
499
  maitai.Inference.store_request_timing_data(timing)
437
500
  return
438
501
  except MaitaiConnectionError as e:
439
- if 'gpt' not in retry_args.get('model', '') and 'gpt' in retry_args.get('fallback_model', ''):
440
- retry_args['model'] = retry_args['fallback_model']
441
- if 'gpt' in retry_args.get('model', ''):
502
+ if "gpt" not in retry_args.get("model", "") and "gpt" in retry_args.get(
503
+ "fallback_model", ""
504
+ ):
505
+ retry_args["model"] = retry_args["fallback_model"]
506
+ if "gpt" in retry_args.get("model", ""):
442
507
  print("Maitai issue, retrying on client side")
443
508
  response = retry_func(**retry_args)
444
509
  for resp in response:
@@ -45,7 +45,6 @@ class MaitaiAsync:
45
45
  default_query: Optional[Mapping[str, object]] = None,
46
46
  http_client: Optional[httpx.Client] = None,
47
47
  _strict_response_validation: bool = False,
48
-
49
48
  ):
50
49
  if maitai_api_key:
51
50
  config.initialize(maitai_api_key)
@@ -93,16 +92,22 @@ class AsyncChat:
93
92
 
94
93
 
95
94
  class AsyncCompletions:
96
- def __init__(self, client: Optional[openai.AsyncClient] = None, client_params: Optional[ClientParams] = None):
95
+ def __init__(
96
+ self,
97
+ client: Optional[openai.AsyncClient] = None,
98
+ client_params: Optional[ClientParams] = None,
99
+ ):
97
100
  self._client = client
98
101
  self._client_params = client_params or ClientParams()
99
102
 
100
- @required_args(["intent", "application", "messages"],
101
- ["intent", "application_ref_name", "messages"],
102
- ["intent", "application", "messages", "model"],
103
- ["intent", "application_ref_name", "messages", "model"],
104
- ["intent", "application", "messages", "model", "stream"],
105
- ["intent", "application_ref_name", "messages", "model", "stream"])
103
+ @required_args(
104
+ ["intent", "application", "messages"],
105
+ ["intent", "application_ref_name", "messages"],
106
+ ["intent", "application", "messages", "model"],
107
+ ["intent", "application_ref_name", "messages", "model"],
108
+ ["intent", "application", "messages", "model", "stream"],
109
+ ["intent", "application_ref_name", "messages", "model", "stream"],
110
+ )
106
111
  async def create(
107
112
  self,
108
113
  *,
@@ -112,7 +117,7 @@ class AsyncCompletions:
112
117
  reference_id: Union[str, int, None] = None,
113
118
  intent: str = None,
114
119
  action_type: str = None, # DEPRECATED
115
- application_ref_name: str = None, # DEPRECATED
120
+ application_ref_name: str = None, # DEPRECATED
116
121
  application: str = None,
117
122
  callback: Optional[EvaluateCallback] = None,
118
123
  server_side_inference: bool = None,
@@ -123,25 +128,45 @@ class AsyncCompletions:
123
128
  fallback_model: str = None,
124
129
  assistant: bool = False,
125
130
  metadata: dict = {},
131
+ safe_mode: bool = None,
126
132
  # OpenAI Arguments
127
133
  messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
128
134
  model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
129
135
  frequency_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
130
- function_call: Union[openai_chat_types.completion_create_params.FunctionCall, openai.NotGiven] = openai.NOT_GIVEN,
131
- functions: Union[Iterable[openai_chat_types.completion_create_params.Function], openai.NotGiven] = openai.NOT_GIVEN,
136
+ function_call: Union[
137
+ openai_chat_types.completion_create_params.FunctionCall, openai.NotGiven
138
+ ] = openai.NOT_GIVEN,
139
+ functions: Union[
140
+ Iterable[openai_chat_types.completion_create_params.Function],
141
+ openai.NotGiven,
142
+ ] = openai.NOT_GIVEN,
132
143
  logit_bias: Union[Optional[Dict[str, int]], openai.NotGiven] = openai.NOT_GIVEN,
133
144
  logprobs: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
134
145
  max_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
135
146
  n: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
136
147
  presence_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
137
- response_format: Union[openai_chat_types.completion_create_params.ResponseFormat, openai.NotGiven] = openai.NOT_GIVEN,
148
+ response_format: Union[
149
+ openai_chat_types.completion_create_params.ResponseFormat, openai.NotGiven
150
+ ] = openai.NOT_GIVEN,
138
151
  seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
139
- stop: Union[Union[Optional[str], List[str]], openai.NotGiven] = openai.NOT_GIVEN,
152
+ stop: Union[
153
+ Union[Optional[str], List[str]], openai.NotGiven
154
+ ] = openai.NOT_GIVEN,
140
155
  stream: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
141
- stream_options: Union[Optional[openai_chat_types.ChatCompletionStreamOptionsParam], openai.NotGiven] = openai.NOT_GIVEN,
156
+ stream_options: Union[
157
+ Optional[openai_chat_types.ChatCompletionStreamOptionsParam],
158
+ openai.NotGiven,
159
+ ] = openai.NOT_GIVEN,
142
160
  temperature: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
143
- tool_choice: Union[openai_chat_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven] = openai.NOT_GIVEN,
144
- tools: Union[Tools, Iterable[Union[openai_chat_types.ChatCompletionToolParam, ToolFunction]], openai.NotGiven] = openai.NOT_GIVEN, top_logprobs: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
161
+ tool_choice: Union[
162
+ openai_chat_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven
163
+ ] = openai.NOT_GIVEN,
164
+ tools: Union[
165
+ Tools,
166
+ Iterable[Union[openai_chat_types.ChatCompletionToolParam, ToolFunction]],
167
+ openai.NotGiven,
168
+ ] = openai.NOT_GIVEN,
169
+ top_logprobs: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
145
170
  top_p: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
146
171
  user: Union[str, openai.NotGiven] = openai.NOT_GIVEN,
147
172
  extra_headers: Optional[Headers] = None,
@@ -162,20 +187,30 @@ class AsyncCompletions:
162
187
  raise ValueError("evaluations must be enabled to apply_corrections")
163
188
  if assistant is True:
164
189
  user_msgs = [True for msg in messages if msg["role"] == "user"]
165
- assistant_messages = [True for msg in messages if msg["role"] == "assistant"]
190
+ assistant_messages = [
191
+ True for msg in messages if msg["role"] == "assistant"
192
+ ]
166
193
  if len(user_msgs) != 1:
167
- raise ValueError("When assistant = True, exactly 1 user message is required")
194
+ raise ValueError(
195
+ "When assistant = True, exactly 1 user message is required"
196
+ )
168
197
  if len(assistant_messages) > 0:
169
- raise ValueError("When assistant = True, no assistant messages are allowed")
198
+ raise ValueError(
199
+ "When assistant = True, no assistant messages are allowed"
200
+ )
170
201
  if not session_id:
171
202
  session_id = str(uuid.uuid4())
172
203
  if action_type and not intent:
173
204
  intent = action_type
174
205
  if not application_ref_name and application:
175
206
  application_ref_name = application
176
- maitai_config = config.get_application_action_config(application_ref_name, intent)
207
+ maitai_config = config.get_application_action_config(
208
+ application_ref_name, intent
209
+ )
177
210
  if server_side_inference is None:
178
- server_side_inference = maitai_config.inference_location == InferenceLocations.SERVER
211
+ server_side_inference = (
212
+ maitai_config.inference_location == InferenceLocations.SERVER
213
+ )
179
214
  if evaluation_enabled is None:
180
215
  evaluation_enabled = maitai_config.evaluation_enabled
181
216
  if apply_corrections is None:
@@ -184,10 +219,12 @@ class AsyncCompletions:
184
219
  model = maitai_config.model
185
220
  if temperature == openai.NOT_GIVEN:
186
221
  temperature = maitai_config.temperature
222
+ if safe_mode is None:
223
+ safe_mode = maitai_config.safe_mode
187
224
  if stream == openai.NOT_GIVEN:
188
- stream = maitai_config.streaming
225
+ stream = False
189
226
  if response_format == openai.NOT_GIVEN:
190
- response_format = {"type": maitai_config.response_format}
227
+ response_format = {"type": "text"}
191
228
  if stop == openai.NOT_GIVEN and maitai_config.stop is not None:
192
229
  stop = maitai_config.stop
193
230
  if logprobs == openai.NOT_GIVEN:
@@ -250,19 +287,24 @@ class AsyncCompletions:
250
287
  assistant=assistant,
251
288
  auth_keys=config.auth_keys,
252
289
  metadata=metadata,
290
+ safe_mode=safe_mode,
253
291
  )
254
292
  if self._client_params is not None:
255
293
  chat_request.client_params = self._client_params
256
294
  try:
257
295
  timing.time_pre_request = time.time()
258
- response = await maitai.Inference.infer_async(chat_request, callback, response_timeout)
296
+ response = await maitai.Inference.infer_async(
297
+ chat_request, callback, response_timeout
298
+ )
259
299
  if stream:
260
- if 'self' in retry_args:
261
- del retry_args['self']
262
- retry_args['server_side_inference'] = False
263
- retry_args['model'] = model
264
- retry_args['fallback_model'] = fallback_model
265
- return _process_inference_stream_async(response, retry_args, self.create, timing)
300
+ if "self" in retry_args:
301
+ del retry_args["self"]
302
+ retry_args["server_side_inference"] = False
303
+ retry_args["model"] = model
304
+ retry_args["fallback_model"] = fallback_model
305
+ return _process_inference_stream_async(
306
+ response, retry_args, self.create, timing
307
+ )
266
308
  # ChatCompletion only
267
309
  async for resp in response:
268
310
  if resp.warning:
@@ -317,13 +359,29 @@ class AsyncCompletions:
317
359
  parallel_tool_calls=parallel_tool_calls,
318
360
  )
319
361
  if stream:
320
- return _process_async_openai_stream(session_id, reference_id, intent, application_ref_name, messages, response, evaluation_enabled, completion_params, timing, callback, metadata)
362
+ return _process_async_openai_stream(
363
+ session_id,
364
+ reference_id,
365
+ intent,
366
+ application_ref_name,
367
+ messages,
368
+ response,
369
+ evaluation_enabled,
370
+ completion_params,
371
+ timing,
372
+ callback,
373
+ metadata,
374
+ )
321
375
  else:
322
376
  timing.time_request_end = time.time()
323
377
  maitai_completion = convert_openai_chat_completion(response)
324
378
  proto_messages = openai_messages_to_proto(messages)
325
379
  proto_messages.append(
326
- ChatMessage(role="assistant", content=maitai_completion.choices[0].message.content))
380
+ ChatMessage(
381
+ role="assistant",
382
+ content=maitai_completion.choices[0].message.content,
383
+ )
384
+ )
327
385
  if evaluation_enabled:
328
386
  await maitai.Evaluator.evaluate_async(
329
387
  session_id=session_id,
@@ -354,18 +412,19 @@ class AsyncCompletions:
354
412
  return MaitaiCompletion(maitai_completion)
355
413
 
356
414
 
357
- async def _process_async_openai_stream(session_id: Union[str, int],
358
- reference_id: Union[str, int, None],
359
- intent: str,
360
- application_ref_name: str,
361
- messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
362
- stream: openai.AsyncStream[openai_chat_types.ChatCompletionChunk],
363
- evaluation_enabled: bool,
364
- chat_completion_params: ChatCompletionParams,
365
- timing: RequestTimingMetric,
366
- callback: Optional[EvaluateCallback] = None,
367
- metadata: dict = {}
368
- ) -> AsyncIterable[MaitaiChunk]:
415
+ async def _process_async_openai_stream(
416
+ session_id: Union[str, int],
417
+ reference_id: Union[str, int, None],
418
+ intent: str,
419
+ application_ref_name: str,
420
+ messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
421
+ stream: openai.AsyncStream[openai_chat_types.ChatCompletionChunk],
422
+ evaluation_enabled: bool,
423
+ chat_completion_params: ChatCompletionParams,
424
+ timing: RequestTimingMetric,
425
+ callback: Optional[EvaluateCallback] = None,
426
+ metadata: dict = {},
427
+ ) -> AsyncIterable[MaitaiChunk]:
369
428
  full_body = ""
370
429
  proto_messages = openai_messages_to_proto(messages)
371
430
  last_chunk = None
@@ -414,7 +473,12 @@ async def _process_async_openai_stream(session_id: Union[str, int],
414
473
  )
415
474
 
416
475
 
417
- async def _process_inference_stream_async(stream: AsyncIterable[InferenceStreamResponse], retry_args: dict, retry_func, timing: RequestTimingMetric) -> AsyncIterable[MaitaiChunk]:
476
+ async def _process_inference_stream_async(
477
+ stream: AsyncIterable[InferenceStreamResponse],
478
+ retry_args: dict,
479
+ retry_func,
480
+ timing: RequestTimingMetric,
481
+ ) -> AsyncIterable[MaitaiChunk]:
418
482
  first = True
419
483
  try:
420
484
  async for infer_resp in stream:
@@ -434,9 +498,11 @@ async def _process_inference_stream_async(stream: AsyncIterable[InferenceStreamR
434
498
  maitai.Inference.store_request_timing_data(timing)
435
499
  return
436
500
  except MaitaiConnectionError as e:
437
- if 'gpt' not in retry_args.get('model', '') and 'gpt' in retry_args.get('fallback_model', ''):
438
- retry_args['model'] = retry_args['fallback_model']
439
- if 'gpt' in retry_args.get('model', ''):
501
+ if "gpt" not in retry_args.get("model", "") and "gpt" in retry_args.get(
502
+ "fallback_model", ""
503
+ ):
504
+ retry_args["model"] = retry_args["fallback_model"]
505
+ if "gpt" in retry_args.get("model", ""):
440
506
  print("Maitai issue, retrying on client side")
441
507
  response = retry_func(**retry_args)
442
508
  for resp in response:
@@ -5,7 +5,7 @@ import openai.types.chat as openai_chat_types
5
5
  from betterproto import Casing
6
6
  from typing_extensions import Literal, runtime_checkable
7
7
 
8
- from maitai_gen.chat import ChatCompletionChunk, ChatCompletionRequest, ChatCompletionResponse, EvaluateRequest, EvaluateResponse, Tool
8
+ from maitai_gen.chat import ChatCompletionChunk, ChatCompletionRequest, ChatCompletionResponse, Tool
9
9
 
10
10
 
11
11
  class Omit:
@@ -22,8 +22,6 @@ class MaitaiChunk(ChatCompletionChunk):
22
22
  def __init__(self, chat_completion_chunk: ChatCompletionChunk = None):
23
23
  super().__init__()
24
24
  if chat_completion_chunk is not None:
25
- if chat_completion_chunk.evaluate_response is not None:
26
- self.evaluate_response = EvaluateResponse(evaluation_request=EvaluateRequest())
27
25
  self.from_pydict(chat_completion_chunk.to_pydict())
28
26
 
29
27
  def model_dump_json(self):
@@ -53,8 +51,6 @@ class MaitaiCompletion(ChatCompletionResponse):
53
51
  def __init__(self, chat_completion_response: ChatCompletionResponse = None):
54
52
  super().__init__()
55
53
  if chat_completion_response is not None:
56
- if chat_completion_response.evaluate_response is not None:
57
- self.evaluate_response = EvaluateResponse(evaluation_request=EvaluateRequest())
58
54
  if chat_completion_response.chat_completion_request is not None:
59
55
  self.chat_completion_request = ChatCompletionRequest()
60
56
  self.from_pydict(chat_completion_response.to_pydict())
@@ -8,7 +8,7 @@ def get_default_config() -> Config:
8
8
  inference_location=InferenceLocations.SERVER,
9
9
  evaluation_enabled=True,
10
10
  apply_corrections=False,
11
- model='gpt-4o',
11
+ model="gpt-4o",
12
12
  temperature=1,
13
13
  streaming=False,
14
14
  response_format="text",
@@ -21,6 +21,7 @@ def get_default_config() -> Config:
21
21
  timeout=0,
22
22
  context_retrieval_enabled=False,
23
23
  fallback_model=None,
24
+ safe_mode=False,
24
25
  )
25
26
 
26
27
 
@@ -1,3 +1,4 @@
1
+ import logging
1
2
  import threading
2
3
  import time
3
4
 
@@ -5,15 +6,17 @@ import websocket
5
6
 
6
7
  from maitai_common.processes.io_thread import IOThread
7
8
 
9
+ logging.getLogger("websocket").setLevel(logging.WARNING)
10
+
8
11
 
9
12
  class WebsocketListenerThread(IOThread):
10
13
  def __init__(self, path, type, key=None):
11
14
  super(WebsocketListenerThread, self).__init__(interval=60)
12
- self.child_name = f'{self.__class__.__name__}'
15
+ self.child_name = f"{self.__class__.__name__}"
13
16
  self.messages = []
14
- self.ws_url = f'{path}?type={type}'
17
+ self.ws_url = f"{path}?type={type}"
15
18
  if key:
16
- self.ws_url += f'&key={key}'
19
+ self.ws_url += f"&key={key}"
17
20
  self.ws = None
18
21
  self.ws_threads = []
19
22
  self.closing_ws = False # Add a shutdown flag
@@ -28,10 +31,12 @@ class WebsocketListenerThread(IOThread):
28
31
  on_message=self.on_message,
29
32
  on_close=self.on_close,
30
33
  on_error=self.on_error,
31
- on_open=self.on_open
34
+ on_open=self.on_open,
32
35
  )
33
36
  # Starting a new thread to handle the WebSocket connection
34
- ws_thread = threading.Thread(target=self.ws.run_forever, name="WebsocketThread")
37
+ ws_thread = threading.Thread(
38
+ target=self.ws.run_forever, name="WebsocketThread"
39
+ )
35
40
  ws_thread.start()
36
41
  self.retry_backoff = 1
37
42
  tmp = [ws_thread]
@@ -44,7 +49,6 @@ class WebsocketListenerThread(IOThread):
44
49
  self.messages.append(message)
45
50
 
46
51
  def on_close(self, ws, _, __):
47
- print("Maitai config websocket closed. Reconnecting...")
48
52
  self.connect_to_websocket()
49
53
 
50
54
  def on_open(self, ws):
@@ -55,7 +59,6 @@ class WebsocketListenerThread(IOThread):
55
59
  self.ws.close()
56
60
 
57
61
  def on_error(self, ws, error):
58
- print(f"Maitai config websocket error: {error}. Reconnecting...")
59
62
  time.sleep(self.retry_backoff)
60
63
  self.retry_backoff *= 2
61
64
  self.connect_to_websocket()
@@ -1,3 +1,3 @@
1
- version = "1.1.21b2"
1
+ version = "1.1.22"
2
2
  if __name__ == "__main__":
3
3
  print(version)
@@ -21,3 +21,11 @@ class PaymentMethod(betterproto.Message):
21
21
  7, betterproto.TYPE_STRING, betterproto.TYPE_STRING
22
22
  )
23
23
  is_default: bool = betterproto.bool_field(8)
24
+
25
+
26
+ @dataclass(eq=False, repr=False)
27
+ class ModelCost(betterproto.Message):
28
+ provider: str = betterproto.string_field(1)
29
+ model: str = betterproto.string_field(2)
30
+ prompt_cpm: float = betterproto.double_field(3)
31
+ completion_cpm: float = betterproto.double_field(4)
@@ -77,6 +77,7 @@ class ChatCompletionRequest(betterproto.Message):
77
77
  metadata: Dict[str, str] = betterproto.map_field(
78
78
  25, betterproto.TYPE_STRING, betterproto.TYPE_STRING
79
79
  )
80
+ safe_mode: bool = betterproto.bool_field(26)
80
81
 
81
82
 
82
83
  @dataclass(eq=False, repr=False)
@@ -364,9 +365,10 @@ class EvaluateResult(betterproto.Message):
364
365
  )
365
366
  sentinel_id: int = betterproto.int64_field(6)
366
367
  eval_time: int = betterproto.int64_field(7)
367
- sentinel: "_sentinel__.Sentinel" = betterproto.message_field(8)
368
368
  date_created: int = betterproto.int64_field(9)
369
369
  usage: "ChatCompletionUsage" = betterproto.message_field(10)
370
+ sentinel_name: str = betterproto.string_field(11)
371
+ severity: int = betterproto.int64_field(12)
370
372
 
371
373
 
372
374
  @dataclass(eq=False, repr=False)
@@ -376,11 +378,9 @@ class EvaluateResponse(betterproto.Message):
376
378
  request_id: int = betterproto.int64_field(3)
377
379
  evaluation_results: List["EvaluateResult"] = betterproto.message_field(4)
378
380
  evaluation_request_id: str = betterproto.string_field(5)
379
- evaluation_request: Optional["EvaluateRequest"] = betterproto.message_field(
380
- 6, optional=True, group="_evaluation_request"
381
- )
382
381
  evaluate_summary: str = betterproto.string_field(7)
383
382
  evaluation_time: int = betterproto.int64_field(8)
383
+ reference_id: str = betterproto.string_field(9)
384
384
 
385
385
 
386
386
  @dataclass(eq=False, repr=False)
@@ -42,6 +42,7 @@ class Config(betterproto.Message):
42
42
  intent_stability: Optional[str] = betterproto.string_field(
43
43
  20, optional=True, group="_intent_stability"
44
44
  )
45
+ safe_mode: bool = betterproto.bool_field(21)
45
46
 
46
47
 
47
48
  @dataclass(eq=False, repr=False)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: maitai-python
3
- Version: 1.1.21b2
3
+ Version: 1.1.22
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai