maitai-python 1.1.21b1__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.21b1 → maitai_python-1.1.22}/PKG-INFO +2 -2
  2. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/README.md +1 -1
  3. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/_context.py +6 -5
  4. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/_inference.py +2 -5
  5. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/_maitai.py +117 -50
  6. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/_maitai_async.py +117 -48
  7. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/_types.py +1 -5
  8. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_common/config/config_service.py +2 -1
  9. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_common/processes/websocket_listener_thread.py +10 -7
  10. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_common/version.py +1 -1
  11. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/billing/__init__.py +8 -0
  12. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/chat/__init__.py +4 -4
  13. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/config/__init__.py +1 -0
  14. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_python.egg-info/PKG-INFO +2 -2
  15. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/__init__.py +0 -0
  16. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/_azure.py +0 -0
  17. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/_config.py +0 -0
  18. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/_config_listener_thread.py +0 -0
  19. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/_evaluator.py +0 -0
  20. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/_maitai_client.py +0 -0
  21. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/_utils.py +0 -0
  22. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai/tools/__init__.py +0 -0
  23. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_common/__init__.py +0 -0
  24. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_common/config/__init__.py +0 -0
  25. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_common/processes/__init__.py +0 -0
  26. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_common/processes/io_thread.py +0 -0
  27. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_common/utils/__init__.py +0 -0
  28. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_common/utils/proto_utils.py +0 -0
  29. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_common/utils/types.py +0 -0
  30. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/__init__.py +0 -0
  31. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/application/__init__.py +0 -0
  32. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/backtest/__init__.py +0 -0
  33. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/company/__init__.py +0 -0
  34. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/embedding/__init__.py +0 -0
  35. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/event/__init__.py +0 -0
  36. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/inference/__init__.py +0 -0
  37. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/key/__init__.py +0 -0
  38. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/metric/__init__.py +0 -0
  39. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/model/__init__.py +0 -0
  40. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/notification/__init__.py +0 -0
  41. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/rates/__init__.py +0 -0
  42. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/sandbox/__init__.py +0 -0
  43. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/sentinel/__init__.py +0 -0
  44. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_gen/session/__init__.py +0 -0
  45. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_python.egg-info/SOURCES.txt +0 -0
  46. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_python.egg-info/dependency_links.txt +0 -0
  47. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_python.egg-info/requires.txt +0 -0
  48. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/maitai_python.egg-info/top_level.txt +0 -0
  49. {maitai_python-1.1.21b1 → maitai_python-1.1.22}/setup.cfg +0 -0
  50. {maitai_python-1.1.21b1 → 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.21b1
3
+ Version: 1.1.22
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -46,7 +46,7 @@ response = maitai.chat.completions.create(
46
46
  model="llama3-70b-8192", ## Remove this line to set model in Portal
47
47
  session_id="YOUR_SESSION_ID",
48
48
  intent="CONVERSATION",
49
- application_ref_name="YOUR_APPLICATION_REF_NAME",
49
+ application="YOUR_APPLICATION_NAME",
50
50
  )
51
51
  ```
52
52
 
@@ -27,7 +27,7 @@ response = maitai.chat.completions.create(
27
27
  model="llama3-70b-8192", ## Remove this line to set model in Portal
28
28
  session_id="YOUR_SESSION_ID",
29
29
  intent="CONVERSATION",
30
- application_ref_name="YOUR_APPLICATION_REF_NAME",
30
+ application="YOUR_APPLICATION_NAME",
31
31
  )
32
32
  ```
33
33
 
@@ -4,14 +4,15 @@ import requests
4
4
  from betterproto import Casing
5
5
 
6
6
  from maitai._config import config
7
- from maitai._utils import __version__ as version, required_args
7
+ from maitai._utils import __version__ as version
8
+ from maitai._utils import required_args
8
9
  from maitai_gen.application import ApplicationContext
9
10
 
10
11
 
11
12
  class ContextManager:
12
- @required_args(["application_ref_name", "reference", "context_body"],
13
- ["application_ref_name", "reference", "file_path"])
14
- def update(self, *, application_ref_name: str, reference: str, context_body: str = '', file_path: str = ''):
13
+ @required_args(["application", "reference", "context_body"],
14
+ ["application", "reference", "file_path"])
15
+ def update(self, *, application: str, reference: str, context_body: str = '', file_path: str = ''):
15
16
  if not reference:
16
17
  raise ValueError("Reference is required")
17
18
  if context_body and file_path:
@@ -37,7 +38,7 @@ class ContextManager:
37
38
  'x-client-version': version,
38
39
  }
39
40
  response = requests.put(url, headers=headers, data=json.dumps({
40
- 'application_ref_name': application_ref_name,
41
+ 'application_ref_name': application,
41
42
  'context': context.to_pydict(casing=Casing.SNAKE),
42
43
  }))
43
44
 
@@ -1,4 +1,3 @@
1
- import time
2
1
  import traceback
3
2
  from typing import AsyncIterable, Iterable, Optional
4
3
 
@@ -9,8 +8,7 @@ from betterproto import Casing
9
8
 
10
9
  from maitai._config import config
11
10
  from maitai._maitai_client import MaitaiClient
12
- from maitai._utils import __version__ as version
13
- from maitai._utils import chat_completion_chunk_to_response
11
+ from maitai._utils import __version__ as version, chat_completion_chunk_to_response
14
12
  from maitai_common.utils.types import AsyncChunkQueue, ChunkQueue, EvaluateCallback, QueueIterable
15
13
  from maitai_gen.chat import ChatCompletionChunk, ChatCompletionParams, ChatCompletionRequest, ChatCompletionResponse, ChatStorageRequest
16
14
  from maitai_gen.inference import InferenceStreamResponse
@@ -82,7 +80,6 @@ class Inference(MaitaiClient):
82
80
  'x-client-version': version,
83
81
  }
84
82
  try:
85
- print("REQUETS SEND TIME", time.time())
86
83
  response = requests.post(url, headers=headers, data=chat_request.to_json(casing=Casing.SNAKE), stream=True, timeout=timeout or 120)
87
84
  if response.status_code != 200:
88
85
  cls.log_error(response.text, url)
@@ -115,7 +112,6 @@ class Inference(MaitaiClient):
115
112
  }
116
113
  try:
117
114
  async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False), timeout=ClientTimeout(timeout or 120)) as session:
118
- print("REQUETS SEND TIME", time.time())
119
115
  async with session.post(url, headers=headers, data=chat_request.to_json(casing=Casing.SNAKE)) as response:
120
116
  if response.status != 200:
121
117
  error_text = await response.text()
@@ -166,6 +162,7 @@ class Inference(MaitaiClient):
166
162
  return await session.put(url, headers=headers, data=chat_storage_request.to_json(casing=Casing.SNAKE))
167
163
  except Exception as e:
168
164
  await cls.increment_error(str(e), url)
165
+ pass
169
166
 
170
167
  @classmethod
171
168
  def store_request_timing_data(cls, metric: RequestTimingMetric):
@@ -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(["action_type", "application_ref_name", "messages"],
101
- ["intent", "application_ref_name", "messages"],
102
- ["action_type", "application_ref_name", "messages", "model"],
103
- ["intent", "application_ref_name", "messages", "model"],
104
- ["action_type", "application_ref_name", "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,36 +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,
121
+ application_ref_name: str = None, # DEPRECATED
122
+ application: str = None,
116
123
  callback: Optional[EvaluateCallback] = None,
117
124
  server_side_inference: bool = None,
118
125
  evaluation_enabled: bool = None,
119
126
  apply_corrections: bool = None,
120
127
  context_retrieval_enabled: bool = None,
121
- context_query: str = '',
128
+ context_query: str = "",
122
129
  return_request: bool = False,
123
130
  fallback_model: str = None,
124
131
  assistant: bool = False,
125
132
  metadata: dict = {},
133
+ safe_mode: bool = None,
126
134
  # OpenAI Arguments
127
135
  messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
128
136
  model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
129
137
  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,
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,
132
145
  logit_bias: Union[Optional[Dict[str, int]], openai.NotGiven] = openai.NOT_GIVEN,
133
146
  logprobs: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
134
147
  max_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
135
148
  n: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
136
149
  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,
150
+ response_format: Union[
151
+ openai_chat_types.completion_create_params.ResponseFormat, openai.NotGiven
152
+ ] = openai.NOT_GIVEN,
138
153
  seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
139
- 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,
140
157
  stream: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
141
- 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,
142
162
  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,
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,
145
171
  top_logprobs: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
146
172
  top_p: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
147
173
  user: Union[str, openai.NotGiven] = openai.NOT_GIVEN,
@@ -151,7 +177,6 @@ class Completions:
151
177
  timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NOT_GIVEN,
152
178
  parallel_tool_calls: Union[bool, openai.NotGiven] = openai.NOT_GIVEN,
153
179
  ) -> Union[MaitaiCompletion, Iterable[MaitaiChunk]]:
154
- print("ENTER TIME", time.time())
155
180
  retry_args = locals()
156
181
  timing = RequestTimingMetric(
157
182
  time_request_start=time.time(),
@@ -164,18 +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
- maitai_config = config.get_application_action_config(application_ref_name, intent)
207
+ if not application_ref_name and application:
208
+ application_ref_name = application
209
+ maitai_config = config.get_application_action_config(
210
+ application_ref_name, intent
211
+ )
177
212
  if server_side_inference is None:
178
- server_side_inference = maitai_config.inference_location == InferenceLocations.SERVER
213
+ server_side_inference = (
214
+ maitai_config.inference_location == InferenceLocations.SERVER
215
+ )
179
216
  if evaluation_enabled is None:
180
217
  evaluation_enabled = maitai_config.evaluation_enabled
181
218
  if apply_corrections is None:
@@ -184,10 +221,12 @@ class Completions:
184
221
  model = maitai_config.model
185
222
  if temperature == openai.NOT_GIVEN:
186
223
  temperature = maitai_config.temperature
224
+ if safe_mode is None:
225
+ safe_mode = maitai_config.safe_mode
187
226
  if stream == openai.NOT_GIVEN:
188
- stream = maitai_config.streaming
227
+ stream = False
189
228
  if response_format == openai.NOT_GIVEN:
190
- response_format = {"type": maitai_config.response_format}
229
+ response_format = {"type": "text"}
191
230
  if stop == openai.NOT_GIVEN and maitai_config.stop is not None:
192
231
  stop = maitai_config.stop
193
232
  if logprobs == openai.NOT_GIVEN:
@@ -251,19 +290,24 @@ class Completions:
251
290
  assistant=assistant,
252
291
  auth_keys=config.auth_keys,
253
292
  metadata=metadata,
293
+ safe_mode=safe_mode,
254
294
  )
255
295
  if self._client_params is not None:
256
296
  chat_request.client_params = self._client_params
257
297
  try:
258
298
  timing.time_pre_request = time.time()
259
- response = maitai.Inference.infer(chat_request, callback, response_timeout)
299
+ response = maitai.Inference.infer(
300
+ chat_request, callback, response_timeout
301
+ )
260
302
  if stream:
261
- if 'self' in retry_args:
262
- del retry_args['self']
263
- retry_args['server_side_inference'] = False
264
- retry_args['model'] = model
265
- retry_args['fallback_model'] = fallback_model
266
- 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
+ )
267
311
  # ChatCompletion only
268
312
  for resp in response:
269
313
  if resp.warning:
@@ -316,16 +360,31 @@ class Completions:
316
360
  extra_body=extra_body,
317
361
  timeout=timeout,
318
362
  parallel_tool_calls=parallel_tool_calls,
319
-
320
363
  )
321
364
  if stream:
322
- 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
+ )
323
378
  else:
324
379
  timing.time_request_end = time.time()
325
380
  maitai_completion = convert_openai_chat_completion(response)
326
381
  proto_messages = openai_messages_to_proto(messages)
327
382
  proto_messages.append(
328
- 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
+ )
329
388
  if evaluation_enabled:
330
389
  maitai.Evaluator.evaluate(
331
390
  session_id=session_id,
@@ -356,18 +415,19 @@ class Completions:
356
415
  return MaitaiCompletion(maitai_completion)
357
416
 
358
417
 
359
- def _process_openai_stream(session_id: Union[str, int],
360
- reference_id: Union[str, int, None],
361
- intent: str,
362
- application_ref_name: str,
363
- messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
364
- stream: openai.Stream[openai_chat_types.ChatCompletionChunk],
365
- evaluation_enabled: bool,
366
- chat_completion_params: ChatCompletionParams,
367
- timing: RequestTimingMetric,
368
- callback: Optional[EvaluateCallback] = None,
369
- metadata: dict = {},
370
- ) -> 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]:
371
431
  full_body = ""
372
432
  proto_messages = openai_messages_to_proto(messages)
373
433
  last_chunk = None
@@ -414,7 +474,12 @@ def _process_openai_stream(session_id: Union[str, int],
414
474
  )
415
475
 
416
476
 
417
- 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]:
418
483
  first = True
419
484
  try:
420
485
  for infer_resp in stream:
@@ -434,9 +499,11 @@ def _process_inference_stream(stream: Iterable[InferenceStreamResponse], retry_a
434
499
  maitai.Inference.store_request_timing_data(timing)
435
500
  return
436
501
  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', ''):
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", ""):
440
507
  print("Maitai issue, retrying on client side")
441
508
  response = retry_func(**retry_args)
442
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(["action_type", "application_ref_name", "messages"],
101
- ["intent", "application_ref_name", "messages"],
102
- ["action_type", "application_ref_name", "messages", "model"],
103
- ["intent", "application_ref_name", "messages", "model"],
104
- ["action_type", "application_ref_name", "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,8 @@ 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,
120
+ application_ref_name: str = None, # DEPRECATED
121
+ application: str = None,
116
122
  callback: Optional[EvaluateCallback] = None,
117
123
  server_side_inference: bool = None,
118
124
  evaluation_enabled: bool = None,
@@ -122,25 +128,45 @@ class AsyncCompletions:
122
128
  fallback_model: str = None,
123
129
  assistant: bool = False,
124
130
  metadata: dict = {},
131
+ safe_mode: bool = None,
125
132
  # OpenAI Arguments
126
133
  messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
127
134
  model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
128
135
  frequency_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
129
- function_call: Union[openai_chat_types.completion_create_params.FunctionCall, openai.NotGiven] = openai.NOT_GIVEN,
130
- 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,
131
143
  logit_bias: Union[Optional[Dict[str, int]], openai.NotGiven] = openai.NOT_GIVEN,
132
144
  logprobs: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
133
145
  max_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
134
146
  n: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
135
147
  presence_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
136
- 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,
137
151
  seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
138
- 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,
139
155
  stream: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
140
- 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,
141
160
  temperature: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
142
- tool_choice: Union[openai_chat_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven] = openai.NOT_GIVEN,
143
- 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,
144
170
  top_p: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
145
171
  user: Union[str, openai.NotGiven] = openai.NOT_GIVEN,
146
172
  extra_headers: Optional[Headers] = None,
@@ -161,18 +187,30 @@ class AsyncCompletions:
161
187
  raise ValueError("evaluations must be enabled to apply_corrections")
162
188
  if assistant is True:
163
189
  user_msgs = [True for msg in messages if msg["role"] == "user"]
164
- 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
+ ]
165
193
  if len(user_msgs) != 1:
166
- 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
+ )
167
197
  if len(assistant_messages) > 0:
168
- raise ValueError("When assistant = True, no assistant messages are allowed")
198
+ raise ValueError(
199
+ "When assistant = True, no assistant messages are allowed"
200
+ )
169
201
  if not session_id:
170
202
  session_id = str(uuid.uuid4())
171
203
  if action_type and not intent:
172
204
  intent = action_type
173
- maitai_config = config.get_application_action_config(application_ref_name, intent)
205
+ if not application_ref_name and application:
206
+ application_ref_name = application
207
+ maitai_config = config.get_application_action_config(
208
+ application_ref_name, intent
209
+ )
174
210
  if server_side_inference is None:
175
- server_side_inference = maitai_config.inference_location == InferenceLocations.SERVER
211
+ server_side_inference = (
212
+ maitai_config.inference_location == InferenceLocations.SERVER
213
+ )
176
214
  if evaluation_enabled is None:
177
215
  evaluation_enabled = maitai_config.evaluation_enabled
178
216
  if apply_corrections is None:
@@ -181,10 +219,12 @@ class AsyncCompletions:
181
219
  model = maitai_config.model
182
220
  if temperature == openai.NOT_GIVEN:
183
221
  temperature = maitai_config.temperature
222
+ if safe_mode is None:
223
+ safe_mode = maitai_config.safe_mode
184
224
  if stream == openai.NOT_GIVEN:
185
- stream = maitai_config.streaming
225
+ stream = False
186
226
  if response_format == openai.NOT_GIVEN:
187
- response_format = {"type": maitai_config.response_format}
227
+ response_format = {"type": "text"}
188
228
  if stop == openai.NOT_GIVEN and maitai_config.stop is not None:
189
229
  stop = maitai_config.stop
190
230
  if logprobs == openai.NOT_GIVEN:
@@ -247,19 +287,24 @@ class AsyncCompletions:
247
287
  assistant=assistant,
248
288
  auth_keys=config.auth_keys,
249
289
  metadata=metadata,
290
+ safe_mode=safe_mode,
250
291
  )
251
292
  if self._client_params is not None:
252
293
  chat_request.client_params = self._client_params
253
294
  try:
254
295
  timing.time_pre_request = time.time()
255
- 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
+ )
256
299
  if stream:
257
- if 'self' in retry_args:
258
- del retry_args['self']
259
- retry_args['server_side_inference'] = False
260
- retry_args['model'] = model
261
- retry_args['fallback_model'] = fallback_model
262
- 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
+ )
263
308
  # ChatCompletion only
264
309
  async for resp in response:
265
310
  if resp.warning:
@@ -314,13 +359,29 @@ class AsyncCompletions:
314
359
  parallel_tool_calls=parallel_tool_calls,
315
360
  )
316
361
  if stream:
317
- 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
+ )
318
375
  else:
319
376
  timing.time_request_end = time.time()
320
377
  maitai_completion = convert_openai_chat_completion(response)
321
378
  proto_messages = openai_messages_to_proto(messages)
322
379
  proto_messages.append(
323
- 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
+ )
324
385
  if evaluation_enabled:
325
386
  await maitai.Evaluator.evaluate_async(
326
387
  session_id=session_id,
@@ -351,18 +412,19 @@ class AsyncCompletions:
351
412
  return MaitaiCompletion(maitai_completion)
352
413
 
353
414
 
354
- async def _process_async_openai_stream(session_id: Union[str, int],
355
- reference_id: Union[str, int, None],
356
- intent: str,
357
- application_ref_name: str,
358
- messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
359
- stream: openai.AsyncStream[openai_chat_types.ChatCompletionChunk],
360
- evaluation_enabled: bool,
361
- chat_completion_params: ChatCompletionParams,
362
- timing: RequestTimingMetric,
363
- callback: Optional[EvaluateCallback] = None,
364
- metadata: dict = {}
365
- ) -> 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]:
366
428
  full_body = ""
367
429
  proto_messages = openai_messages_to_proto(messages)
368
430
  last_chunk = None
@@ -411,7 +473,12 @@ async def _process_async_openai_stream(session_id: Union[str, int],
411
473
  )
412
474
 
413
475
 
414
- 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]:
415
482
  first = True
416
483
  try:
417
484
  async for infer_resp in stream:
@@ -431,9 +498,11 @@ async def _process_inference_stream_async(stream: AsyncIterable[InferenceStreamR
431
498
  maitai.Inference.store_request_timing_data(timing)
432
499
  return
433
500
  except MaitaiConnectionError as e:
434
- if 'gpt' not in retry_args.get('model', '') and 'gpt' in retry_args.get('fallback_model', ''):
435
- retry_args['model'] = retry_args['fallback_model']
436
- 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", ""):
437
506
  print("Maitai issue, retrying on client side")
438
507
  response = retry_func(**retry_args)
439
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.21b1"
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.21b1
3
+ Version: 1.1.22
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -46,7 +46,7 @@ response = maitai.chat.completions.create(
46
46
  model="llama3-70b-8192", ## Remove this line to set model in Portal
47
47
  session_id="YOUR_SESSION_ID",
48
48
  intent="CONVERSATION",
49
- application_ref_name="YOUR_APPLICATION_REF_NAME",
49
+ application="YOUR_APPLICATION_NAME",
50
50
  )
51
51
  ```
52
52