maitai-python 1.1.8b0__tar.gz → 1.1.14__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.8b0 → maitai_python-1.1.14}/PKG-INFO +1 -1
  2. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai/_evaluator.py +27 -5
  3. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai/_inference.py +14 -10
  4. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai/_maitai.py +25 -6
  5. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai/_maitai_async.py +27 -9
  6. maitai_python-1.1.14/maitai/_maitai_client.py +32 -0
  7. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai/_utils.py +7 -5
  8. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai/tools/__init__.py +8 -5
  9. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_common/processes/io_thread.py +9 -12
  10. maitai_python-1.1.14/maitai_common/utils/proto_utils.py +19 -0
  11. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_common/version.py +1 -1
  12. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/chat/__init__.py +28 -1
  13. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/sentinel/__init__.py +14 -0
  14. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_python.egg-info/PKG-INFO +1 -1
  15. maitai_python-1.1.8b0/maitai/_maitai_client.py +0 -58
  16. maitai_python-1.1.8b0/maitai_common/utils/proto_utils.py +0 -14
  17. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/README.md +0 -0
  18. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai/__init__.py +0 -0
  19. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai/_azure.py +0 -0
  20. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai/_config.py +0 -0
  21. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai/_config_listener_thread.py +0 -0
  22. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai/_context.py +0 -0
  23. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai/_types.py +0 -0
  24. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_common/__init__.py +0 -0
  25. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_common/config/__init__.py +0 -0
  26. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_common/config/config_service.py +0 -0
  27. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_common/processes/__init__.py +0 -0
  28. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_common/processes/websocket_listener_thread.py +0 -0
  29. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_common/utils/__init__.py +0 -0
  30. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_common/utils/types.py +0 -0
  31. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/__init__.py +0 -0
  32. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/application/__init__.py +0 -0
  33. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/backtest/__init__.py +0 -0
  34. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/company/__init__.py +0 -0
  35. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/config/__init__.py +0 -0
  36. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/embedding/__init__.py +0 -0
  37. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/event/__init__.py +0 -0
  38. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/inference/__init__.py +0 -0
  39. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/key/__init__.py +0 -0
  40. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/metric/__init__.py +0 -0
  41. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/model/__init__.py +0 -0
  42. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/notification/__init__.py +0 -0
  43. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/sandbox/__init__.py +0 -0
  44. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_gen/session/__init__.py +0 -0
  45. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_python.egg-info/SOURCES.txt +0 -0
  46. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_python.egg-info/dependency_links.txt +0 -0
  47. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_python.egg-info/requires.txt +0 -0
  48. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/maitai_python.egg-info/top_level.txt +0 -0
  49. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/setup.cfg +0 -0
  50. {maitai_python-1.1.8b0 → maitai_python-1.1.14}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: maitai-python
3
- Version: 1.1.8b0
3
+ Version: 1.1.14
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -10,7 +10,7 @@ from maitai._config import config
10
10
  from maitai._maitai_client import MaitaiClient
11
11
  from maitai._utils import __version__ as version, chat_completion_chunk_to_response
12
12
  from maitai_common.utils.types import EvaluateCallback
13
- from maitai_gen.chat import ChatCompletionChunk, ChatCompletionParams, ChatCompletionResponse, EvaluateRequest, EvaluateResponse, EvaluationContentType
13
+ from maitai_gen.chat import ChatCompletionChunk, ChatCompletionParams, ChatCompletionRequest, ChatCompletionResponse, EvaluateRequest, EvaluateResponse, EvaluationContentType
14
14
  from maitai_gen.metric import RequestTimingMetric
15
15
 
16
16
 
@@ -30,7 +30,7 @@ class Evaluator(MaitaiClient):
30
30
 
31
31
  @classmethod
32
32
  async def evaluate_async(cls, session_id, reference_id, intent, content, content_type=None, application_id=None, application_ref_name=None, callback=None, completion_params: ChatCompletionParams = None,
33
- chat_completion_response: ChatCompletionResponse = None, chat_completion_chunk: ChatCompletionChunk = None, timing: RequestTimingMetric = None):
33
+ chat_completion_response: ChatCompletionResponse = None, chat_completion_chunk: ChatCompletionChunk = None, timing: RequestTimingMetric = None, metadata: dict = {}):
34
34
  if content_type is None:
35
35
  content_type = _get_content_type(content)
36
36
  if content_type is None:
@@ -39,7 +39,18 @@ class Evaluator(MaitaiClient):
39
39
  raise Exception('application_id or application_ref_name must be provided')
40
40
  eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id, reference_id, intent, content_type, content)
41
41
  if completion_params is not None:
42
- eval_request.chat_completion_request = cls.create_inference_request(application_ref_name, session_id, reference_id, intent, False, True, completion_params, callback, False, '')
42
+ eval_request.chat_completion_request = ChatCompletionRequest(
43
+ application_ref_name=application_ref_name,
44
+ session_id=session_id,
45
+ reference_id=reference_id,
46
+ action_type=intent,
47
+ apply_corrections=False,
48
+ evaluation_enabled=True,
49
+ params=completion_params,
50
+ return_evaluation=True if callback else False,
51
+ auth_keys=config.auth_keys,
52
+ metadata=metadata,
53
+ )
43
54
  if chat_completion_chunk is not None:
44
55
  chat_completion_response = chat_completion_chunk_to_response(chat_completion_chunk, content)
45
56
  eval_request.chat_completion_response = chat_completion_response
@@ -48,7 +59,7 @@ class Evaluator(MaitaiClient):
48
59
 
49
60
  @classmethod
50
61
  def evaluate(cls, session_id, reference_id, intent, content, content_type=None, application_id=None, application_ref_name=None, callback=None, partial=None, completion_params: ChatCompletionParams = None,
51
- chat_completion_response: ChatCompletionResponse = None, chat_completion_chunk: ChatCompletionChunk = None, timing: RequestTimingMetric = None):
62
+ chat_completion_response: ChatCompletionResponse = None, chat_completion_chunk: ChatCompletionChunk = None, timing: RequestTimingMetric = None, metadata: dict = {}):
52
63
  if content_type is None:
53
64
  content_type = _get_content_type(content, partial)
54
65
  if content_type is None:
@@ -57,7 +68,18 @@ class Evaluator(MaitaiClient):
57
68
  raise Exception('application_id or application_ref_name must be provided')
58
69
  eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id, reference_id, intent, content_type, content, partial=partial)
59
70
  if completion_params is not None:
60
- eval_request.chat_completion_request = cls.create_inference_request(application_ref_name, session_id, reference_id, intent, False, True, completion_params, callback, False, None)
71
+ eval_request.chat_completion_request = ChatCompletionRequest(
72
+ application_ref_name=application_ref_name,
73
+ session_id=session_id,
74
+ reference_id=reference_id,
75
+ action_type=intent,
76
+ apply_corrections=False,
77
+ evaluation_enabled=True,
78
+ params=completion_params,
79
+ return_evaluation=True if callback else False,
80
+ auth_keys=config.auth_keys,
81
+ metadata=metadata,
82
+ )
61
83
  if chat_completion_chunk is not None:
62
84
  chat_completion_response = chat_completion_chunk_to_response(chat_completion_chunk, content)
63
85
  eval_request.chat_completion_response = chat_completion_response
@@ -51,18 +51,22 @@ class Inference(MaitaiClient):
51
51
  return QueueIterable(q, timeout=timeout)
52
52
 
53
53
  @classmethod
54
- def create_chat_storage_request(cls, session_id, reference_id, intent, application_ref_name, completion_params: ChatCompletionParams, chat_completion_response: Optional[ChatCompletionResponse],
55
- final_chunk: Optional[ChatCompletionChunk], content: str, timing: RequestTimingMetric):
56
- inference_request = cls.create_inference_request(application_ref_name, session_id, reference_id, intent, False, False, completion_params, None, False, '')
54
+ def store_chat_response(cls, session_id, reference_id, intent, application_ref_name, completion_params: ChatCompletionParams, chat_completion_response: Optional[ChatCompletionResponse],
55
+ final_chunk: Optional[ChatCompletionChunk], content: str, timing: RequestTimingMetric, metadata: dict):
56
+ inference_request = ChatCompletionRequest(
57
+ application_ref_name=application_ref_name,
58
+ session_id=session_id,
59
+ reference_id=reference_id,
60
+ action_type=intent,
61
+ apply_corrections=False,
62
+ evaluation_enabled=False,
63
+ params=completion_params,
64
+ auth_keys=config.auth_keys,
65
+ metadata=metadata,
66
+ )
57
67
  if final_chunk:
58
68
  chat_completion_response = chat_completion_chunk_to_response(final_chunk, content)
59
-
60
- return ChatStorageRequest(chat_completion_request=inference_request, chat_completion_response=chat_completion_response, timing_metrics=timing)
61
-
62
- @classmethod
63
- def store_chat_response(cls, session_id, reference_id, intent, application_ref_name, completion_params: ChatCompletionParams, chat_completion_response: Optional[ChatCompletionResponse],
64
- final_chunk: Optional[ChatCompletionChunk], content: str, timing: RequestTimingMetric):
65
- chat_storage_request = cls.create_chat_storage_request(session_id, reference_id, intent, application_ref_name, completion_params, chat_completion_response, final_chunk, content, timing)
69
+ chat_storage_request = ChatStorageRequest(chat_completion_request=inference_request, chat_completion_response=chat_completion_response, timing_metrics=timing)
66
70
  cls.run_async(cls.send_storage_request_async(chat_storage_request))
67
71
 
68
72
  @classmethod
@@ -122,6 +122,7 @@ class Completions:
122
122
  return_request: bool = False,
123
123
  fallback_model: str = None,
124
124
  assistant: bool = False,
125
+ metadata: dict = {},
125
126
  # OpenAI Arguments
126
127
  messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
127
128
  model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
@@ -148,6 +149,7 @@ class Completions:
148
149
  extra_query: Optional[Query] = None,
149
150
  extra_body: Optional[Body] = None,
150
151
  timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NOT_GIVEN,
152
+ parallel_tool_calls: Union[bool, openai.NotGiven] = openai.NOT_GIVEN,
151
153
  ) -> Union[MaitaiCompletion, Iterable[MaitaiChunk]]:
152
154
  retry_args = locals()
153
155
  timing = RequestTimingMetric(
@@ -159,6 +161,13 @@ class Completions:
159
161
  raise ValueError("server_side_inference must be true to apply_corrections")
160
162
  if apply_corrections is True and evaluation_enabled is False:
161
163
  raise ValueError("evaluations must be enabled to apply_corrections")
164
+ if assistant is True:
165
+ user_msgs = [True for msg in messages if msg["role"] == "user"]
166
+ assistant_messages = [True for msg in messages if msg["role"] == "assistant"]
167
+ if len(user_msgs) != 1:
168
+ raise ValueError("When assistant = True, exactly 1 user message is required")
169
+ if len(assistant_messages) > 0:
170
+ raise ValueError("When assistant = True, no assistant messages are allowed")
162
171
  if not session_id:
163
172
  session_id = str(uuid.uuid4())
164
173
  if not intent and action_type:
@@ -218,28 +227,32 @@ class Completions:
218
227
  top_logprobs=top_logprobs,
219
228
  top_p=top_p,
220
229
  user=user,
230
+ parallel_tool_calls=parallel_tool_calls,
221
231
  )
222
232
  if server_side_inference:
223
233
  response_timeout = None
224
234
  if isinstance(timeout, float) or isinstance(timeout, int):
225
235
  response_timeout = timeout
226
- chat_request: ChatCompletionRequest = maitai.Inference.create_inference_request(
236
+ chat_request: ChatCompletionRequest = ChatCompletionRequest(
227
237
  application_ref_name=application_ref_name,
228
238
  session_id=session_id,
229
239
  reference_id=reference_id,
230
- intent=intent,
240
+ action_type=intent,
231
241
  apply_corrections=apply_corrections,
232
242
  evaluation_enabled=evaluation_enabled,
233
- completion_params=completion_params,
234
- callback=callback,
243
+ params=completion_params,
244
+ return_evaluation=True if callback else False,
235
245
  context_retrieval_enabled=context_retrieval_enabled,
236
246
  context_query=context_query,
237
247
  return_request=return_request,
238
248
  fallback_model=fallback_model,
239
249
  user_id=user_id,
240
250
  assistant=assistant,
241
- client_params=self._client_params,
251
+ auth_keys=config.auth_keys,
252
+ metadata=metadata,
242
253
  )
254
+ if self._client_params is not None:
255
+ chat_request.client_params = self._client_params
243
256
  try:
244
257
  timing.time_pre_request = time.time()
245
258
  response = maitai.Inference.infer(chat_request, callback, response_timeout)
@@ -301,10 +314,11 @@ class Completions:
301
314
  extra_query=extra_query,
302
315
  extra_body=extra_body,
303
316
  timeout=timeout,
317
+ parallel_tool_calls=parallel_tool_calls,
304
318
 
305
319
  )
306
320
  if stream:
307
- return _process_openai_stream(session_id, reference_id, intent, application_ref_name, messages, response, evaluation_enabled, completion_params, timing, callback)
321
+ return _process_openai_stream(session_id, reference_id, intent, application_ref_name, messages, response, evaluation_enabled, completion_params, timing, callback, metadata)
308
322
  else:
309
323
  timing.time_request_end = time.time()
310
324
  maitai_completion = convert_openai_chat_completion(response)
@@ -323,6 +337,7 @@ class Completions:
323
337
  chat_completion_response=maitai_completion,
324
338
  completion_params=completion_params,
325
339
  timing=timing,
340
+ metadata=metadata,
326
341
  )
327
342
  else:
328
343
  maitai.Inference.store_chat_response(
@@ -335,6 +350,7 @@ class Completions:
335
350
  final_chunk=None,
336
351
  content="",
337
352
  timing=timing,
353
+ metadata=metadata,
338
354
  )
339
355
  return MaitaiCompletion(maitai_completion)
340
356
 
@@ -349,6 +365,7 @@ def _process_openai_stream(session_id: Union[str, int],
349
365
  chat_completion_params: ChatCompletionParams,
350
366
  timing: RequestTimingMetric,
351
367
  callback: Optional[EvaluateCallback] = None,
368
+ metadata: dict = {},
352
369
  ) -> Iterable[MaitaiChunk]:
353
370
  full_body = ""
354
371
  proto_messages = openai_messages_to_proto(messages)
@@ -379,6 +396,7 @@ def _process_openai_stream(session_id: Union[str, int],
379
396
  chat_completion_chunk=last_chunk,
380
397
  completion_params=chat_completion_params,
381
398
  timing=timing,
399
+ metadata=metadata,
382
400
  )
383
401
  else:
384
402
  maitai.Inference.store_chat_response(
@@ -391,6 +409,7 @@ def _process_openai_stream(session_id: Union[str, int],
391
409
  content=full_body,
392
410
  chat_completion_response=None,
393
411
  timing=timing,
412
+ metadata=metadata,
394
413
  )
395
414
 
396
415
 
@@ -118,6 +118,7 @@ class AsyncCompletions:
118
118
  context_query: str = None,
119
119
  fallback_model: str = None,
120
120
  assistant: bool = False,
121
+ metadata: dict = {},
121
122
  # OpenAI Arguments
122
123
  messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
123
124
  model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
@@ -143,6 +144,7 @@ class AsyncCompletions:
143
144
  extra_query: Optional[Query] = None,
144
145
  extra_body: Optional[Body] = None,
145
146
  timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NOT_GIVEN,
147
+ parallel_tool_calls: Union[bool, openai.NotGiven] = openai.NOT_GIVEN,
146
148
  ) -> Union[MaitaiCompletion, AsyncIterable[MaitaiChunk]]:
147
149
  retry_args = locals()
148
150
  timing = RequestTimingMetric(
@@ -154,6 +156,13 @@ class AsyncCompletions:
154
156
  raise ValueError("server_side_inference must be true to apply_corrections")
155
157
  if apply_corrections is True and evaluation_enabled is False:
156
158
  raise ValueError("evaluations must be enabled to apply_corrections")
159
+ if assistant is True:
160
+ user_msgs = [True for msg in messages if msg["role"] == "user"]
161
+ assistant_messages = [True for msg in messages if msg["role"] == "assistant"]
162
+ if len(user_msgs) != 1:
163
+ raise ValueError("When assistant = True, exactly 1 user message is required")
164
+ if len(assistant_messages) > 0:
165
+ raise ValueError("When assistant = True, no assistant messages are allowed")
157
166
  if not session_id:
158
167
  session_id = str(uuid.uuid4())
159
168
  if action_type and not intent:
@@ -213,28 +222,31 @@ class AsyncCompletions:
213
222
  top_logprobs=top_logprobs,
214
223
  top_p=top_p,
215
224
  user=user,
225
+ parallel_tool_calls=parallel_tool_calls,
216
226
  )
217
227
  if server_side_inference:
218
228
  response_timeout = None
219
229
  if isinstance(timeout, float) or isinstance(timeout, int):
220
230
  response_timeout = timeout
221
- chat_request: ChatCompletionRequest = maitai.Inference.create_inference_request(
231
+ chat_request: ChatCompletionRequest = ChatCompletionRequest(
222
232
  application_ref_name=application_ref_name,
223
233
  session_id=session_id,
224
234
  reference_id=reference_id,
225
- intent=intent,
235
+ action_type=intent,
226
236
  apply_corrections=apply_corrections,
227
237
  evaluation_enabled=evaluation_enabled,
228
- completion_params=completion_params,
229
- callback=callback,
238
+ params=completion_params,
239
+ return_evaluation=True if callback else False,
230
240
  context_retrieval_enabled=context_retrieval_enabled,
231
241
  context_query=context_query,
232
- return_request=False,
233
242
  fallback_model=fallback_model,
234
243
  user_id=user_id,
235
244
  assistant=assistant,
236
- client_params=self._client_params,
245
+ auth_keys=config.auth_keys,
246
+ metadata=metadata,
237
247
  )
248
+ if self._client_params is not None:
249
+ chat_request.client_params = self._client_params
238
250
  try:
239
251
  timing.time_pre_request = time.time()
240
252
  response = await maitai.Inference.infer_async(chat_request, callback, response_timeout)
@@ -296,10 +308,10 @@ class AsyncCompletions:
296
308
  extra_query=extra_query,
297
309
  extra_body=extra_body,
298
310
  timeout=timeout,
299
-
311
+ parallel_tool_calls=parallel_tool_calls,
300
312
  )
301
313
  if stream:
302
- return _process_async_openai_stream(session_id, reference_id, intent, application_ref_name, messages, response, evaluation_enabled, completion_params, timing, callback)
314
+ return _process_async_openai_stream(session_id, reference_id, intent, application_ref_name, messages, response, evaluation_enabled, completion_params, timing, callback, metadata)
303
315
  else:
304
316
  timing.time_request_end = time.time()
305
317
  maitai_completion = convert_openai_chat_completion(response)
@@ -318,6 +330,7 @@ class AsyncCompletions:
318
330
  chat_completion_response=maitai_completion,
319
331
  completion_params=completion_params,
320
332
  timing=timing,
333
+ metadata=metadata,
321
334
  )
322
335
  else:
323
336
  maitai.Inference.store_chat_response(
@@ -330,6 +343,7 @@ class AsyncCompletions:
330
343
  final_chunk=None,
331
344
  content="",
332
345
  timing=timing,
346
+ metadata=metadata,
333
347
  )
334
348
  return MaitaiCompletion(maitai_completion)
335
349
 
@@ -343,7 +357,9 @@ async def _process_async_openai_stream(session_id: Union[str, int],
343
357
  evaluation_enabled: bool,
344
358
  chat_completion_params: ChatCompletionParams,
345
359
  timing: RequestTimingMetric,
346
- callback: Optional[EvaluateCallback] = None) -> AsyncIterable[MaitaiChunk]:
360
+ callback: Optional[EvaluateCallback] = None,
361
+ metadata: dict = {}
362
+ ) -> AsyncIterable[MaitaiChunk]:
347
363
  full_body = ""
348
364
  proto_messages = openai_messages_to_proto(messages)
349
365
  last_chunk = None
@@ -375,6 +391,7 @@ async def _process_async_openai_stream(session_id: Union[str, int],
375
391
  chat_completion_chunk=last_chunk,
376
392
  completion_params=chat_completion_params,
377
393
  timing=timing,
394
+ metadata=metadata,
378
395
  )
379
396
  else:
380
397
  maitai.Inference.store_chat_response(
@@ -387,6 +404,7 @@ async def _process_async_openai_stream(session_id: Union[str, int],
387
404
  content=full_body,
388
405
  chat_completion_response=None,
389
406
  timing=timing,
407
+ metadata=metadata,
390
408
  )
391
409
 
392
410
 
@@ -0,0 +1,32 @@
1
+ import asyncio
2
+ import threading
3
+
4
+
5
+ class MaitaiClient:
6
+
7
+ def __init__(self):
8
+ super().__init__()
9
+
10
+ @classmethod
11
+ def run_async(cls, coro):
12
+ """
13
+ Modified helper method to run coroutine in a background thread if not already in an asyncio loop,
14
+ otherwise just run it. This allows for both asyncio and non-asyncio applications to use this method.
15
+ """
16
+ try:
17
+ loop = asyncio.get_running_loop()
18
+ except RuntimeError: # No running event loop
19
+ loop = None
20
+
21
+ if loop and loop.is_running():
22
+ # We are in an asyncio loop, schedule coroutine execution
23
+ asyncio.create_task(coro, name='maitai')
24
+ else:
25
+ # Not in an asyncio loop, run in a new event loop in a background thread
26
+ def run():
27
+ new_loop = asyncio.new_event_loop()
28
+ asyncio.set_event_loop(new_loop)
29
+ new_loop.run_until_complete(coro)
30
+ new_loop.close()
31
+
32
+ threading.Thread(target=run).start()
@@ -110,7 +110,7 @@ def get_chat_completion_params(*,
110
110
  max_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
111
111
  n: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
112
112
  presence_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
113
- response_format: Union[openai_types.completion_create_params.ResponseFormat, openai.NotGiven] = openai.NOT_GIVEN,
113
+ response_format: Union[openai_types.completion_create_params.ResponseFormat, chat_types.ResponseFormat, openai.NotGiven] = openai.NOT_GIVEN,
114
114
  seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
115
115
  stop: Union[Union[Optional[str], List[str]], openai.NotGiven] = openai.NOT_GIVEN,
116
116
  stream: Optional[bool] = False,
@@ -121,6 +121,7 @@ def get_chat_completion_params(*,
121
121
  top_logprobs: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
122
122
  top_p: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
123
123
  user: Union[str, openai.NotGiven] = openai.NOT_GIVEN,
124
+ parallel_tool_calls: Union[bool, openai.NotGiven] = openai.NOT_GIVEN,
124
125
  ) -> chat_types.ChatCompletionParams:
125
126
  params = chat_types.ChatCompletionParams(
126
127
  messages=openai_messages_to_proto(messages),
@@ -142,6 +143,7 @@ def get_chat_completion_params(*,
142
143
  'frequency_penalty': frequency_penalty,
143
144
  'user': user,
144
145
  'tool_choice': tool_choice,
146
+ 'parallel_tool_calls': parallel_tool_calls,
145
147
  }
146
148
  # Set each parameter that is not marked as NOT_GIVEN
147
149
  for param_name, value in optional_params.items():
@@ -153,16 +155,16 @@ def get_chat_completion_params(*,
153
155
 
154
156
  if response_format != openai.NOT_GIVEN:
155
157
  params.response_format = chat_types.ResponseFormat(type=response_format["type"])
158
+ if response_format.get("json_schema"):
159
+ params.response_format.json_schema = chat_types.JsonSchema().from_dict(response_format["json_schema"])
156
160
 
157
161
  if tools != openai.NOT_GIVEN:
158
162
  params.tools = []
159
163
  if isinstance(tools, Tools):
160
164
  params.tools = tools.get_tool_definitions()
161
- else:
165
+ elif tools:
162
166
  for tool in tools:
163
- if isinstance(tool, Callable) and not isinstance(tool, ToolFunction):
164
- raise TypeError(f"Method passed into tools missing @tool decorator")
165
- if isinstance(tool, ToolFunction):
167
+ if hasattr(tool, "__tool__"):
166
168
  params.tools.append(tool.__tool__)
167
169
  continue
168
170
  function = tool.get("function")
@@ -3,7 +3,6 @@ import json
3
3
  import re
4
4
  from typing import get_type_hints
5
5
 
6
- from maitai._types import ToolFunction
7
6
  from maitai_gen.chat import Function, Tool, ToolCall
8
7
 
9
8
 
@@ -12,7 +11,7 @@ class Tools:
12
11
  self.available_functions = {}
13
12
  self.definitions = []
14
13
  for func in tools:
15
- if not isinstance(func, ToolFunction):
14
+ if not hasattr(func, "__tool__"):
16
15
  raise TypeError(f"Method passed into tools missing @tool decorator")
17
16
  tool_call = func.__tool__
18
17
  self.available_functions[tool_call.function.name] = func
@@ -31,7 +30,10 @@ class Tools:
31
30
  return function_response
32
31
 
33
32
 
34
- def tool(func):
33
+ def tool(func=None, strict=True):
34
+ if func is None:
35
+ return lambda f: tool(f, strict=strict)
36
+
35
37
  function_description = func.__doc__
36
38
  if not function_description:
37
39
  raise ValueError("Missing docstring for tool")
@@ -61,18 +63,19 @@ def tool(func):
61
63
  "type": _parse_type(param_type),
62
64
  "description": param_descriptions.get(param_name, ""),
63
65
  }
64
- if param.default is param.empty:
65
- required.append(param_name)
66
+ required.append(param_name)
66
67
 
67
68
  wrapper.__tool__ = Tool(
68
69
  type="function",
69
70
  function=Function(
70
71
  name=func.__name__,
72
+ strict=strict,
71
73
  description=function_description,
72
74
  parameters={
73
75
  "type": "object",
74
76
  "properties": properties,
75
77
  "required": required,
78
+ "additionalProperties": False,
76
79
  },
77
80
  )
78
81
  )
@@ -1,4 +1,4 @@
1
- import threading
1
+ import asyncio
2
2
  import time
3
3
  import traceback
4
4
  from threading import Thread
@@ -16,17 +16,20 @@ class IOThread(Thread):
16
16
  self.completed_loops = 0
17
17
  self.avg_loop_time = 0
18
18
  self.cleaned = False
19
- self.timer_thread = None
20
19
  self.last_loop_start = -1
21
20
  self.child_name = self.__class__.__name__ if name is None else name
22
21
 
23
22
  def run(self):
24
23
  if not self.initialized:
25
24
  self.initialize()
26
- time.sleep(self.interval)
27
- self.loop()
25
+ asyncio.run(self.main_loop())
28
26
 
29
- def loop(self):
27
+ async def main_loop(self):
28
+ await asyncio.sleep(self.interval)
29
+ while self.run_thread:
30
+ await self.loop()
31
+
32
+ async def loop(self):
30
33
  if self.run_thread:
31
34
  self.last_loop_start = time.time()
32
35
  self.is_running = True
@@ -41,18 +44,12 @@ class IOThread(Thread):
41
44
  self.avg_loop_time = ((self.avg_loop_time * self.completed_loops) * delta) / (self.completed_loops + 1)
42
45
  self.completed_loops += 1
43
46
  next_run = self.interval - delta
44
- self.timer_thread = threading.Timer(0 if next_run < 0 else next_run, self.loop)
45
- self.timer_thread.name = self.child_name
46
- self.timer_thread.start()
47
+ await asyncio.sleep(max(0, next_run))
47
48
  else:
48
- if self.timer_thread is not None:
49
- self.timer_thread.cancel()
50
49
  self.cleaned = True
51
50
 
52
51
  def terminate(self):
53
52
  self.run_thread = False
54
- if self.timer_thread is not None:
55
- self.timer_thread.cancel()
56
53
  self.cleaned = True
57
54
  self.print(f'{self.child_name} cleaned up')
58
55
 
@@ -0,0 +1,19 @@
1
+ from typing import Iterable
2
+
3
+ from openai.types.chat import ChatCompletionMessageParam
4
+
5
+ from maitai_gen.chat import ChatCompletionMessage, ChatMessage
6
+
7
+
8
+ def openai_messages_to_proto(messages: Iterable[ChatCompletionMessageParam]):
9
+ proto_messages: [ChatMessage] = []
10
+ for message in messages:
11
+ if isinstance(message, ChatMessage):
12
+ proto_messages.append(message)
13
+ elif isinstance(message, ChatCompletionMessage):
14
+ proto_messages.append(ChatMessage().from_pydict(message.to_pydict()))
15
+ else:
16
+ proto_messages.append(
17
+ ChatMessage().from_pydict(message)
18
+ )
19
+ return proto_messages
@@ -1,3 +1,3 @@
1
- version = "1.1.8b0"
1
+ version = "1.1.14"
2
2
  if __name__ == "__main__":
3
3
  print(version)
@@ -73,6 +73,9 @@ class ChatCompletionRequest(betterproto.Message):
73
73
  user_id: str = betterproto.string_field(22)
74
74
  assistant: bool = betterproto.bool_field(23)
75
75
  client_params: "ClientParams" = betterproto.message_field(24)
76
+ metadata: Dict[str, str] = betterproto.map_field(
77
+ 25, betterproto.TYPE_STRING, betterproto.TYPE_STRING
78
+ )
76
79
 
77
80
 
78
81
  @dataclass(eq=False, repr=False)
@@ -117,11 +120,15 @@ class ChatCompletionParams(betterproto.Message):
117
120
  user: str = betterproto.string_field(17)
118
121
  tools: List["Tool"] = betterproto.message_field(18)
119
122
  tool_choice: str = betterproto.string_field(19)
123
+ parallel_tool_calls: bool = betterproto.bool_field(20)
120
124
 
121
125
 
122
126
  @dataclass(eq=False, repr=False)
123
127
  class ResponseFormat(betterproto.Message):
124
128
  type: str = betterproto.string_field(1)
129
+ json_schema: Optional["JsonSchema"] = betterproto.message_field(
130
+ 2, optional=True, group="_json_schema"
131
+ )
125
132
 
126
133
 
127
134
  @dataclass(eq=False, repr=False)
@@ -142,6 +149,16 @@ class Function(betterproto.Message):
142
149
  parameters: Dict[str, str] = betterproto.map_field(
143
150
  3, betterproto.TYPE_STRING, betterproto.TYPE_STRING
144
151
  )
152
+ strict: bool = betterproto.bool_field(4)
153
+
154
+
155
+ @dataclass(eq=False, repr=False)
156
+ class JsonSchema(betterproto.Message):
157
+ name: str = betterproto.string_field(1)
158
+ strict: bool = betterproto.bool_field(2)
159
+ schema: Dict[str, str] = betterproto.map_field(
160
+ 3, betterproto.TYPE_STRING, betterproto.TYPE_STRING
161
+ )
145
162
 
146
163
 
147
164
  @dataclass(eq=False, repr=False)
@@ -206,6 +223,7 @@ class ChatCompletionMessage(betterproto.Message):
206
223
  3, optional=True, group="_function_call"
207
224
  )
208
225
  tool_calls: List["ToolCall"] = betterproto.message_field(4)
226
+ refusal: str = betterproto.string_field(5)
209
227
 
210
228
 
211
229
  @dataclass(eq=False, repr=False)
@@ -252,6 +270,7 @@ class ChoiceDelta(betterproto.Message):
252
270
  role: str = betterproto.string_field(2)
253
271
  tool_calls: List["ToolCall"] = betterproto.message_field(3)
254
272
  function_call: "FunctionCall" = betterproto.message_field(4)
273
+ refusal: str = betterproto.string_field(6)
255
274
 
256
275
 
257
276
  @dataclass(eq=False, repr=False)
@@ -271,6 +290,7 @@ class ToolCallFunction(betterproto.Message):
271
290
  @dataclass(eq=False, repr=False)
272
291
  class LogProbs(betterproto.Message):
273
292
  content: List["LogPropsContent"] = betterproto.message_field(1)
293
+ refusal: List["LogPropsContent"] = betterproto.message_field(2)
274
294
 
275
295
 
276
296
  @dataclass(eq=False, repr=False)
@@ -278,7 +298,14 @@ class LogPropsContent(betterproto.Message):
278
298
  token: str = betterproto.string_field(1)
279
299
  logprob: float = betterproto.double_field(2)
280
300
  bytes: List[int] = betterproto.int32_field(3)
281
- top_logprobs: List["LogProbs"] = betterproto.message_field(4)
301
+ top_logprobs: List["TopLogProbs"] = betterproto.message_field(4)
302
+
303
+
304
+ @dataclass(eq=False, repr=False)
305
+ class TopLogProbs(betterproto.Message):
306
+ token: str = betterproto.string_field(1)
307
+ logprob: float = betterproto.double_field(2)
308
+ bytes: List[float] = betterproto.double_field(3)
282
309
 
283
310
 
284
311
  @dataclass(eq=False, repr=False)
@@ -32,6 +32,7 @@ class Sentinel(betterproto.Message):
32
32
  meta: Dict[str, str] = betterproto.map_field(
33
33
  9, betterproto.TYPE_STRING, betterproto.TYPE_STRING
34
34
  )
35
+ sentinel_generation_id: int = betterproto.int64_field(10)
35
36
 
36
37
 
37
38
  @dataclass(eq=False, repr=False)
@@ -53,3 +54,16 @@ class DirectiveBody(betterproto.Message):
53
54
  class SentinelExample(betterproto.Message):
54
55
  example_type: str = betterproto.string_field(1)
55
56
  example_body: str = betterproto.string_field(2)
57
+
58
+
59
+ @dataclass(eq=False, repr=False)
60
+ class SentinelGeneration(betterproto.Message):
61
+ id: int = betterproto.int64_field(1)
62
+ date_created: int = betterproto.int64_field(2)
63
+ company_id: int = betterproto.int64_field(3)
64
+ application_id: int = betterproto.int64_field(4)
65
+ application_action_id: int = betterproto.int64_field(5)
66
+ base_prompt: str = betterproto.string_field(6)
67
+ meta: Dict[str, str] = betterproto.map_field(
68
+ 7, betterproto.TYPE_STRING, betterproto.TYPE_STRING
69
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: maitai-python
3
- Version: 1.1.8b0
3
+ Version: 1.1.14
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -1,58 +0,0 @@
1
- import asyncio
2
- import threading
3
-
4
- from maitai._config import config
5
- from maitai_gen.chat import ChatCompletionParams, ChatCompletionRequest, ClientParams
6
-
7
-
8
- class MaitaiClient:
9
-
10
- def __init__(self):
11
- super().__init__()
12
-
13
- @classmethod
14
- def run_async(cls, coro):
15
- """
16
- Modified helper method to run coroutine in a background thread if not already in an asyncio loop,
17
- otherwise just run it. This allows for both asyncio and non-asyncio applications to use this method.
18
- """
19
- try:
20
- loop = asyncio.get_running_loop()
21
- except RuntimeError: # No running event loop
22
- loop = None
23
-
24
- if loop and loop.is_running():
25
- # We are in an asyncio loop, schedule coroutine execution
26
- asyncio.create_task(coro, name='maitai')
27
- else:
28
- # Not in an asyncio loop, run in a new event loop in a background thread
29
- def run():
30
- new_loop = asyncio.new_event_loop()
31
- asyncio.set_event_loop(new_loop)
32
- new_loop.run_until_complete(coro)
33
- new_loop.close()
34
-
35
- threading.Thread(target=run).start()
36
-
37
- @classmethod
38
- def create_inference_request(cls, application_ref_name, session_id, reference_id, intent, apply_corrections, evaluation_enabled, completion_params: ChatCompletionParams, callback=None,
39
- context_retrieval_enabled=False, context_query=None, return_request=False, fallback_model=None, user_id="", assistant=False, client_params: ClientParams = None):
40
- infer_request: ChatCompletionRequest = ChatCompletionRequest()
41
- infer_request.application_ref_name = application_ref_name
42
- infer_request.reference_id = reference_id
43
- infer_request.session_id = session_id
44
- infer_request.action_type = intent
45
- infer_request.apply_corrections = apply_corrections
46
- infer_request.params = completion_params
47
- infer_request.evaluation_enabled = evaluation_enabled
48
- infer_request.auth_keys = config.auth_keys
49
- infer_request.return_evaluation = True if callback else False
50
- infer_request.context_retrieval_enabled = context_retrieval_enabled
51
- infer_request.context_query = context_query
52
- infer_request.return_request = return_request
53
- infer_request.fallback_model = fallback_model
54
- infer_request.user_id = user_id
55
- infer_request.assistant = assistant
56
- if client_params is not None:
57
- infer_request.client_params = client_params
58
- return infer_request
@@ -1,14 +0,0 @@
1
- from typing import Iterable
2
-
3
- from openai.types.chat import ChatCompletionMessageParam
4
-
5
- from maitai_gen.chat import ChatMessage
6
-
7
-
8
- def openai_messages_to_proto(messages: Iterable[ChatCompletionMessageParam]):
9
- proto_messages: [ChatMessage] = []
10
- for message in messages:
11
- proto_messages.append(
12
- ChatMessage().from_pydict(message)
13
- )
14
- return proto_messages
File without changes