maitai-python 1.2.25__py3-none-any.whl → 1.2.26__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
maitai/_maitai.py CHANGED
@@ -1,56 +1,18 @@
1
1
  import logging
2
2
  import os
3
- import time
4
- import traceback
5
- import uuid
6
- import warnings
7
- from typing import Dict, Iterable, List, Mapping, Optional, Union
3
+ from typing import Mapping, Optional, Union
8
4
 
9
5
  import groq
10
6
  import httpx
11
7
  import openai
12
- import openai.types as openai_types
13
- import openai.types.chat as openai_chat_types
14
8
 
15
9
  from maitai._config import config
16
- from maitai._evaluator import Evaluator
17
- from maitai._inference import Inference
18
- from maitai._types import (
19
- Body,
20
- EvaluateCallback,
21
- FallbackConfig,
22
- Headers,
23
- MaitaiChunk,
24
- MaitaiCompletion,
25
- Query,
26
- ToolFunction,
27
- )
28
- from maitai._utils import (
29
- convert_open_ai_chat_completion_chunk,
30
- convert_openai_chat_completion,
31
- convert_params_to_groq,
32
- get_chat_completion_params,
33
- required_args,
34
- type_to_response_format_param,
35
- )
36
- from maitai.exceptions import (
37
- InferenceException,
38
- InferenceWarning,
39
- MaitaiConnectionError,
40
- )
41
- from maitai.models.chat import (
42
- AzureParams,
43
- ChatCompletionParams,
44
- ClientParams,
45
- EvaluationContentType,
46
- )
47
- from maitai.models.config import InferenceLocations
48
- from maitai.models.inference import InferenceStreamResponse
10
+ from maitai.chat._completions import Completions
11
+ from maitai.models.chat import AzureParams, ClientParams
49
12
  from maitai.models.key import Key
50
- from maitai.models.metric import RequestTimingMetric
51
- from maitai.tools import Tools
13
+ from maitai.transcriptions._transcriptions import Transcriptions
52
14
 
53
- logger = logging.getLogger(__name__)
15
+ logger = logging.getLogger("maitai")
54
16
 
55
17
  DEFAULT_MAX_RETRIES = 2
56
18
 
@@ -159,7 +121,7 @@ class Maitai:
159
121
  deployment=azure_deployment,
160
122
  api_version=azure_api_version,
161
123
  )
162
- self._openai_client = openai.AzureOpenAI(
124
+ self._openai_client = openai.AzureOpenAI( # type: ignore
163
125
  azure_endpoint=azure_endpoint,
164
126
  azure_deployment=azure_deployment,
165
127
  api_key=azure_api_key,
@@ -188,529 +150,47 @@ class Maitai:
188
150
  _strict_response_validation=_strict_response_validation,
189
151
  )
190
152
  if groq_api_key or config.auth_keys.groq_api_key:
153
+
191
154
  self._groq_client = groq.Groq(
192
- api_key=groq_api_key or config.auth_keys.groq_api_key.key_value,
155
+ api_key=groq_api_key
156
+ or (
157
+ config.auth_keys.groq_api_key.key_value
158
+ if config.auth_keys.groq_api_key
159
+ else None
160
+ ),
193
161
  )
194
162
 
195
163
  client_params = None
196
164
  if base_url or default_headers or default_query:
197
- client_params = ClientParams(
198
- base_url=base_url or "",
199
- default_headers=default_headers or {},
200
- default_query=default_query or {},
201
- azure_params=azure_params,
202
- )
165
+ client_param_dict = {}
166
+ if base_url:
167
+ client_param_dict["base_url"] = base_url
168
+ if default_headers:
169
+ client_param_dict["default_headers"] = default_headers
170
+ if default_query:
171
+ client_param_dict["default_query"] = default_query
172
+ if azure_params:
173
+ client_param_dict["azure_params"] = azure_params
174
+ client_params = ClientParams(**client_param_dict)
203
175
  self.chat = Chat(self._openai_client, self._groq_client, client_params)
176
+ self.audio = Audio(self._openai_client, self._groq_client, client_params)
204
177
 
205
178
 
206
179
  class Chat:
207
180
  def __init__(
208
- self, openai_client=None, groq_client=None, client_params: ClientParams = None
181
+ self,
182
+ openai_client=None,
183
+ groq_client=None,
184
+ client_params: Optional[ClientParams] = None,
209
185
  ):
210
186
  self.completions = Completions(openai_client, groq_client, client_params)
211
187
 
212
188
 
213
- class Completions:
189
+ class Audio:
214
190
  def __init__(
215
191
  self,
216
- openai_client: Optional[openai.Client] = None,
217
- groq_client: Optional[groq.Groq] = None,
192
+ openai_client=None,
193
+ groq_client=None,
218
194
  client_params: Optional[ClientParams] = None,
219
195
  ):
220
- self._openai_client = openai_client
221
- self._groq_client = groq_client
222
- self._client_params = client_params or ClientParams()
223
- self.evaluator = Evaluator()
224
- self.inference = Inference()
225
-
226
- @required_args(
227
- ["intent", "application", "messages"],
228
- ["intent", "application_ref_name", "messages"],
229
- ["intent", "application", "messages", "model"],
230
- ["intent", "application_ref_name", "messages", "model"],
231
- ["intent", "application", "messages", "model", "stream"],
232
- ["intent", "application_ref_name", "messages", "model", "stream"],
233
- )
234
- def create(
235
- self,
236
- *,
237
- # Maitai Arguments
238
- user_id: str = "",
239
- session_id: Union[str, int] = None,
240
- reference_id: Union[str, int, None] = None,
241
- intent: str = None,
242
- action_type: str = None, # DEPRECATED
243
- application_ref_name: str = None, # DEPRECATED
244
- application: str = None,
245
- callback: Optional[EvaluateCallback] = None,
246
- server_side_inference: bool = None,
247
- evaluation_enabled: bool = None,
248
- apply_corrections: bool = None,
249
- context_retrieval_enabled: bool = None,
250
- context_query: str = "",
251
- return_request: bool = False,
252
- fallback_model: str = None,
253
- assistant: bool = False,
254
- metadata: dict = {},
255
- safe_mode: bool = None,
256
- fallback_config: FallbackConfig = None,
257
- # OpenAI Arguments
258
- messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
259
- model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
260
- frequency_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
261
- function_call: Union[
262
- openai_chat_types.completion_create_params.FunctionCall, openai.NotGiven
263
- ] = openai.NOT_GIVEN,
264
- functions: Union[
265
- Iterable[openai_chat_types.completion_create_params.Function],
266
- openai.NotGiven,
267
- ] = openai.NOT_GIVEN,
268
- logit_bias: Union[Optional[Dict[str, int]], openai.NotGiven] = openai.NOT_GIVEN,
269
- logprobs: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
270
- max_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
271
- max_completion_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
272
- n: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
273
- presence_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
274
- reasoning_effort: Optional[str] = openai.NOT_GIVEN,
275
- response_format: Union[
276
- openai_chat_types.completion_create_params.ResponseFormat, openai.NotGiven
277
- ] = openai.NOT_GIVEN,
278
- seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
279
- stop: Union[
280
- Union[Optional[str], List[str]], openai.NotGiven
281
- ] = openai.NOT_GIVEN,
282
- stream: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
283
- stream_options: Union[
284
- Optional[openai_chat_types.ChatCompletionStreamOptionsParam],
285
- openai.NotGiven,
286
- ] = openai.NOT_GIVEN,
287
- temperature: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
288
- tool_choice: Union[
289
- openai_chat_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven
290
- ] = openai.NOT_GIVEN,
291
- tools: Union[
292
- Tools,
293
- Iterable[Union[openai_chat_types.ChatCompletionToolParam, ToolFunction]],
294
- openai.NotGiven,
295
- ] = openai.NOT_GIVEN,
296
- top_logprobs: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
297
- top_p: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
298
- user: Union[str, openai.NotGiven] = openai.NOT_GIVEN,
299
- extra_headers: Optional[Headers] = None,
300
- extra_query: Optional[Query] = None,
301
- extra_body: Optional[Body] = None,
302
- timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NOT_GIVEN,
303
- parallel_tool_calls: Union[bool, openai.NotGiven] = openai.NOT_GIVEN,
304
- ) -> Union[MaitaiCompletion, Iterable[MaitaiChunk]]:
305
- retry_args = locals()
306
- timing = RequestTimingMetric(
307
- time_request_start=time.time(),
308
- )
309
- if not config.api_key:
310
- raise ValueError("Maitai API Key has not been set")
311
- if server_side_inference is False and apply_corrections is True:
312
- raise ValueError("server_side_inference must be true to apply_corrections")
313
- if apply_corrections is True and evaluation_enabled is False:
314
- raise ValueError("evaluations must be enabled to apply_corrections")
315
- if assistant is True:
316
- user_msgs = [True for msg in messages if msg["role"] == "user"]
317
- assistant_messages = [
318
- True for msg in messages if msg["role"] == "assistant"
319
- ]
320
- if len(user_msgs) != 1:
321
- raise ValueError(
322
- "When assistant = True, exactly 1 user message is required"
323
- )
324
- if len(assistant_messages) > 0:
325
- raise ValueError(
326
- "When assistant = True, no assistant messages are allowed"
327
- )
328
- if not session_id:
329
- session_id = str(uuid.uuid4())
330
- if not intent and action_type:
331
- intent = action_type
332
- if not application_ref_name and application:
333
- application_ref_name = application
334
- maitai_config = config.get_application_action_config(
335
- application_ref_name, intent
336
- )
337
- if server_side_inference is None:
338
- server_side_inference = (
339
- maitai_config.inference_location == InferenceLocations.SERVER
340
- )
341
- if evaluation_enabled is None:
342
- evaluation_enabled = maitai_config.evaluation_enabled
343
- if apply_corrections is None:
344
- apply_corrections = maitai_config.apply_corrections
345
- if model == openai.NOT_GIVEN:
346
- model = maitai_config.model
347
- if temperature == openai.NOT_GIVEN:
348
- temperature = maitai_config.temperature
349
- if safe_mode is None:
350
- safe_mode = maitai_config.safe_mode
351
- if stream == openai.NOT_GIVEN:
352
- stream = False
353
- if response_format == openai.NOT_GIVEN:
354
- response_format = {"type": "text"}
355
- if stop == openai.NOT_GIVEN and maitai_config.stop is not None:
356
- stop = maitai_config.stop
357
- if logprobs == openai.NOT_GIVEN:
358
- logprobs = maitai_config.logprobs
359
- if max_tokens == openai.NOT_GIVEN and maitai_config.max_tokens is not None:
360
- max_tokens = maitai_config.max_tokens
361
- if max_completion_tokens and max_completion_tokens != openai.NOT_GIVEN:
362
- max_tokens = max_completion_tokens
363
- if n == openai.NOT_GIVEN and maitai_config.n:
364
- n = maitai_config.n
365
- if frequency_penalty == openai.NOT_GIVEN:
366
- frequency_penalty = maitai_config.frequency_penalty
367
- if presence_penalty == openai.NOT_GIVEN:
368
- presence_penalty = maitai_config.presence_penalty
369
- if timeout == openai.NOT_GIVEN and maitai_config.timeout > 0:
370
- timeout = maitai_config.timeout
371
- if context_retrieval_enabled is None:
372
- context_retrieval_enabled = maitai_config.context_retrieval_enabled
373
- if fallback_model:
374
- warnings.warn(
375
- "fallback_model is deprecated. Use fallback_config instead.",
376
- DeprecationWarning,
377
- )
378
- if fallback_config is None and maitai_config.fallback_config:
379
- fallback_config = {
380
- "model": maitai_config.fallback_config.model,
381
- "strategy": maitai_config.fallback_config.strategy,
382
- "timeout": maitai_config.fallback_config.timeout,
383
- }
384
- if fallback_config is None and fallback_model:
385
- fallback_config = {
386
- "model": fallback_model,
387
- "strategy": "reactive",
388
- "timeout": None,
389
- }
390
- if fallback_config and "model" in fallback_config:
391
- fallback_model = fallback_config["model"]
392
- completion_params = get_chat_completion_params(
393
- messages=messages,
394
- model=model,
395
- frequency_penalty=frequency_penalty,
396
- logit_bias=logit_bias,
397
- logprobs=logprobs,
398
- max_tokens=max_tokens,
399
- n=n,
400
- presence_penalty=presence_penalty,
401
- response_format=response_format,
402
- seed=seed,
403
- stop=stop,
404
- stream=stream,
405
- stream_options=stream_options,
406
- temperature=temperature,
407
- tool_choice=tool_choice,
408
- tools=tools,
409
- top_logprobs=top_logprobs,
410
- top_p=top_p,
411
- user=user,
412
- parallel_tool_calls=parallel_tool_calls,
413
- extra_headers=extra_headers,
414
- reasoning_effort=reasoning_effort,
415
- )
416
- if server_side_inference:
417
- response_timeout = None
418
- if isinstance(timeout, float) or isinstance(timeout, int):
419
- response_timeout = timeout
420
- request_dict = {
421
- "application_ref_name": application_ref_name,
422
- "session_id": session_id,
423
- "reference_id": reference_id,
424
- "action_type": intent,
425
- "apply_corrections": apply_corrections,
426
- "evaluation_enabled": evaluation_enabled,
427
- "params": completion_params,
428
- "return_evaluation": True if callback else False,
429
- "context_retrieval_enabled": context_retrieval_enabled,
430
- "context_query": context_query,
431
- "return_request": return_request,
432
- "fallback_model": fallback_model,
433
- "user_id": user_id,
434
- "assistant": assistant,
435
- "auth_keys": config.auth_keys.model_dump(),
436
- "metadata": metadata,
437
- "safe_mode": safe_mode,
438
- "fallback_config": fallback_config,
439
- }
440
-
441
- if self._client_params is not None:
442
- request_dict["client_params"] = self._client_params.model_dump()
443
-
444
- try:
445
- timing.time_pre_request = time.time()
446
- response = self.inference.infer(
447
- request_dict, callback, response_timeout
448
- )
449
- if stream:
450
- if "self" in retry_args:
451
- del retry_args["self"]
452
- retry_args["server_side_inference"] = False
453
- retry_args["model"] = model
454
- retry_args["fallback_model"] = fallback_model
455
- return self._process_inference_stream(
456
- response,
457
- retry_args,
458
- timing,
459
- includes_usage=(
460
- stream_options.get("include_usage", False)
461
- if stream_options and stream_options != openai.NOT_GIVEN
462
- else False
463
- ),
464
- )
465
- # ChatCompletion only
466
- for resp in response:
467
- if resp.warning:
468
- warnings.warn(resp.warning, InferenceWarning)
469
- if resp.error:
470
- if "Unknown error occurred" in resp.error:
471
- raise MaitaiConnectionError(resp.error)
472
- raise InferenceException(resp.error)
473
- timing.request_id = resp.chat_completion_response.request_id
474
- timing.time_request_end = time.time()
475
- self.inference.store_request_timing_data(timing)
476
- completion = MaitaiCompletion.model_validate(
477
- resp.chat_completion_response.model_dump()
478
- )
479
- completion.set_response_format(response_format)
480
- return completion
481
- raise InferenceException("No data received")
482
- except MaitaiConnectionError as e:
483
- if "gpt" not in model and fallback_model and "gpt" in fallback_model:
484
- model = fallback_model
485
- if "gpt" not in model:
486
- raise e
487
- if safe_mode:
488
- raise e
489
- traceback.print_exc()
490
- logger.warning("Maitai issue, retrying on client side")
491
- server_side_inference = False
492
- if not server_side_inference:
493
- groq_model = False
494
- if "groq:" in model or "maitai:" in model or "llama" in model:
495
- groq_model = True
496
- model = model.replace("groq:", "").replace("maitai:", "")
497
- if "openai:" in model:
498
- model = model.replace("openai:", "")
499
-
500
- local_params = {
501
- "messages": messages,
502
- "model": model,
503
- "frequency_penalty": frequency_penalty,
504
- "function_call": function_call,
505
- "functions": functions,
506
- "logit_bias": logit_bias,
507
- "logprobs": logprobs,
508
- "max_tokens": max_tokens,
509
- "n": n,
510
- "presence_penalty": presence_penalty,
511
- "reasoning_effort": reasoning_effort,
512
- "response_format": response_format,
513
- "seed": seed,
514
- "stop": stop,
515
- "stream": stream,
516
- "stream_options": stream_options,
517
- "temperature": temperature,
518
- "tool_choice": tool_choice,
519
- "tools": tools,
520
- "top_logprobs": top_logprobs,
521
- "top_p": top_p,
522
- "user": user,
523
- "extra_headers": extra_headers,
524
- "extra_query": extra_query,
525
- "extra_body": extra_body,
526
- "timeout": timeout,
527
- "parallel_tool_calls": parallel_tool_calls,
528
- }
529
-
530
- if groq_model:
531
- if self._groq_client is None:
532
- if (
533
- not config.auth_keys.groq_api_key
534
- or not config.auth_keys.groq_api_key.key_value
535
- ):
536
- raise ValueError(
537
- "Groq API key is required for Groq models but was not provided"
538
- )
539
-
540
- self._groq_client = groq.Groq(
541
- api_key=config.auth_keys.groq_api_key.key_value,
542
- )
543
- client_to_use = self._groq_client
544
- local_params = convert_params_to_groq(local_params)
545
- else:
546
- if self._openai_client is None:
547
- self._openai_client = openai.OpenAI(
548
- api_key=config.auth_keys.openai_api_key.key_value,
549
- default_headers=self._client_params.default_headers or None,
550
- default_query=self._client_params.default_query or None,
551
- base_url=self._client_params.base_url or None,
552
- )
553
- client_to_use = self._openai_client
554
-
555
- if hasattr(response_format, "model_json_schema"):
556
- response_format = {
557
- "type": "json_schema",
558
- "json_schema": type_to_response_format_param(response_format),
559
- }
560
- if isinstance(tools, Tools):
561
- tools = tools.get_tool_definitions()
562
-
563
- response = client_to_use.chat.completions.create(**local_params)
564
- if stream:
565
- return self._process_openai_stream(
566
- session_id,
567
- reference_id,
568
- intent,
569
- application_ref_name,
570
- messages,
571
- response,
572
- evaluation_enabled,
573
- completion_params,
574
- timing,
575
- callback,
576
- metadata,
577
- )
578
- else:
579
- timing.time_request_end = time.time()
580
- maitai_completion = convert_openai_chat_completion(response)
581
- full_conv = messages + [
582
- {
583
- "role": "assistant",
584
- "content": maitai_completion.choices[0].message.content,
585
- }
586
- ]
587
- if evaluation_enabled:
588
- self.evaluator.evaluate(
589
- session_id=session_id,
590
- reference_id=reference_id,
591
- intent=intent,
592
- content_type=EvaluationContentType.MESSAGE,
593
- content=full_conv,
594
- application_ref_name=application_ref_name,
595
- callback=callback,
596
- chat_completion_response=maitai_completion,
597
- completion_params=completion_params,
598
- timing=timing,
599
- metadata=metadata,
600
- )
601
- else:
602
- self.inference.store_chat_response(
603
- session_id=session_id,
604
- reference_id=reference_id,
605
- intent=intent,
606
- application_ref_name=application_ref_name,
607
- chat_completion_response=maitai_completion,
608
- completion_params=completion_params,
609
- final_chunk=None,
610
- content="",
611
- timing=timing,
612
- metadata=metadata,
613
- )
614
- completion = MaitaiCompletion.model_validate(
615
- maitai_completion.model_dump()
616
- )
617
- completion.set_response_format(response_format)
618
- return completion
619
-
620
- def _process_openai_stream(
621
- self,
622
- session_id: Union[str, int],
623
- reference_id: Union[str, int, None],
624
- intent: str,
625
- application_ref_name: str,
626
- messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
627
- stream: openai.Stream[openai_chat_types.ChatCompletionChunk],
628
- evaluation_enabled: bool,
629
- chat_completion_params: ChatCompletionParams,
630
- timing: RequestTimingMetric,
631
- callback: Optional[EvaluateCallback] = None,
632
- metadata: dict = {},
633
- ) -> Iterable[MaitaiChunk]:
634
- full_body = ""
635
- last_chunk = None
636
- for chunk in stream:
637
- if last_chunk is None:
638
- timing.time_first_chunk = time.time()
639
- maitai_chunk = convert_open_ai_chat_completion_chunk(chunk)
640
- if maitai_chunk.choices:
641
- last_chunk = maitai_chunk
642
- content = maitai_chunk.choices[0].delta.content
643
- if content is not None:
644
- full_body += content
645
- if maitai_chunk.usage and last_chunk is not None and not last_chunk.usage:
646
- last_chunk.usage = maitai_chunk.usage
647
- yield MaitaiChunk.model_validate(maitai_chunk.model_dump())
648
- timing.time_request_end = time.time()
649
- if evaluation_enabled:
650
- full_conv = messages + [{"role": "assistant", "content": full_body}]
651
- self.evaluator.evaluate(
652
- session_id=session_id,
653
- reference_id=reference_id,
654
- intent=intent,
655
- content_type=EvaluationContentType.MESSAGE,
656
- content=full_conv,
657
- application_ref_name=application_ref_name,
658
- callback=callback,
659
- chat_completion_chunk=last_chunk,
660
- completion_params=chat_completion_params,
661
- timing=timing,
662
- metadata=metadata,
663
- )
664
- else:
665
- self.inference.store_chat_response(
666
- session_id=session_id,
667
- reference_id=reference_id,
668
- intent=intent,
669
- application_ref_name=application_ref_name,
670
- completion_params=chat_completion_params,
671
- final_chunk=last_chunk,
672
- content=full_body,
673
- chat_completion_response=None,
674
- timing=timing,
675
- metadata=metadata,
676
- )
677
-
678
- def _process_inference_stream(
679
- self,
680
- stream: Iterable[InferenceStreamResponse],
681
- retry_args: dict,
682
- timing: RequestTimingMetric,
683
- includes_usage: bool = False,
684
- ) -> Iterable[MaitaiChunk]:
685
- first = True
686
- try:
687
- for infer_resp in stream:
688
- if infer_resp.warning:
689
- warnings.warn(infer_resp.warning, InferenceWarning)
690
- if infer_resp.error:
691
- raise InferenceException(infer_resp.error)
692
- chunk = infer_resp.chat_completion_chunk
693
- if chunk is not None:
694
- if first:
695
- timing.time_first_chunk = time.time()
696
- timing.request_id = chunk.request_id
697
- first = False
698
- yield MaitaiChunk.model_validate(chunk.model_dump())
699
- if chunk.choices and chunk.choices[0].finish_reason:
700
- timing.time_request_end = time.time()
701
- self.inference.store_request_timing_data(timing)
702
- if chunk.choices and chunk.choices[0].finish_reason:
703
- return
704
- except MaitaiConnectionError as e:
705
- if "gpt" not in retry_args.get("model", "") and "gpt" in (
706
- retry_args.get("fallback_model", "") or ""
707
- ):
708
- retry_args["model"] = retry_args["fallback_model"]
709
- if "gpt" in retry_args.get("model", ""):
710
- logger.warning("Maitai issue, retrying on client side")
711
- retry_args["model"] = retry_args["model"].replace("openai:", "")
712
- response = self.create(**retry_args)
713
- for resp in response:
714
- yield resp
715
- else:
716
- raise e
196
+ self.transcriptions = Transcriptions(openai_client)