maitai-python 1.2.18b0__tar.gz → 1.2.19__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 (36) hide show
  1. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/PKG-INFO +1 -1
  2. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/_config.py +1 -0
  3. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/_config_listener.py +11 -12
  4. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/_evaluator.py +6 -3
  5. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/_inference.py +21 -11
  6. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/_maitai.py +14 -3
  7. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/_maitai_async.py +14 -3
  8. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/_types.py +10 -7
  9. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/models/chat.py +6 -2
  10. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/models/key.py +2 -0
  11. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai_common/version.py +1 -1
  12. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai_python.egg-info/PKG-INFO +1 -1
  13. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/README.md +0 -0
  14. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/__init__.py +0 -0
  15. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/_context.py +0 -0
  16. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/_maitai_client.py +0 -0
  17. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/_pydantic.py +0 -0
  18. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/_utils.py +0 -0
  19. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/exceptions.py +0 -0
  20. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/models/__init__.py +0 -0
  21. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/models/application.py +0 -0
  22. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/models/config.py +0 -0
  23. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/models/event.py +0 -0
  24. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/models/inference.py +0 -0
  25. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/models/metric.py +0 -0
  26. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/models/sentinel.py +0 -0
  27. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai/tools/__init__.py +0 -0
  28. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai_common/__init__.py +0 -0
  29. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai_common/config/__init__.py +0 -0
  30. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai_common/config/config_service.py +0 -0
  31. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai_python.egg-info/SOURCES.txt +0 -0
  32. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai_python.egg-info/dependency_links.txt +0 -0
  33. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai_python.egg-info/requires.txt +0 -0
  34. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/maitai_python.egg-info/top_level.txt +0 -0
  35. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/setup.cfg +0 -0
  36. {maitai_python-1.2.18b0 → maitai_python-1.2.19}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: maitai-python
3
- Version: 1.2.18b0
3
+ Version: 1.2.19
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -30,6 +30,7 @@ class Config(MaitaiClient):
30
30
  anthropic_api_key=Key(id=-1, key_value=os.environ.get("ANTHROPIC_API_KEY")),
31
31
  cerebras_api_key=Key(id=-1, key_value=os.environ.get("CEREBRAS_API_KEY")),
32
32
  sambanova_api_key=Key(id=-1, key_value=os.environ.get("SAMBANOVA_API_KEY")),
33
+ gemini_api_key=Key(id=-1, key_value=os.environ.get("GEMINI_API_KEY")),
33
34
  )
34
35
  self.refresh_interval = 30 * 60 # 30 minutes in seconds
35
36
 
@@ -9,6 +9,8 @@ from maitai.models.application import Application
9
9
 
10
10
  logging.getLogger("websocket").setLevel(logging.FATAL)
11
11
 
12
+ logger = logging.getLogger("maitai")
13
+
12
14
 
13
15
  class ConfigListener:
14
16
  def __init__(self, config, path, type, key=None):
@@ -20,7 +22,6 @@ class ConfigListener:
20
22
  self.ws = None
21
23
  self.ws_thread = None
22
24
  self.running = False
23
- self.logger = logging.getLogger("maitai")
24
25
 
25
26
  def on_message(self, ws, message):
26
27
  event = json.loads(message)
@@ -29,9 +30,7 @@ class ConfigListener:
29
30
  if application_json:
30
31
  try:
31
32
  application = Application.model_validate(application_json)
32
- self.logger.info(
33
- "Maitai config listener: received configuration change"
34
- )
33
+ logger.info("Maitai config listener: received configuration change")
35
34
  self.config.store_application_metadata([application])
36
35
  except Exception as e:
37
36
  if os.environ.get("MAITAI_ENV") in [
@@ -39,7 +38,7 @@ class ConfigListener:
39
38
  "staging",
40
39
  "prod",
41
40
  ]:
42
- self.logger.error(
41
+ logger.error(
43
42
  "Maitai config listener: error refreshing applications",
44
43
  exc_info=e,
45
44
  )
@@ -49,15 +48,15 @@ class ConfigListener:
49
48
 
50
49
  def on_error(self, ws, error):
51
50
  if not isinstance(error, (AttributeError, ConnectionError)):
52
- self.logger.error("Maitai config listener: websocket error", exc_info=error)
51
+ logger.error("Maitai config listener: websocket error", exc_info=error)
53
52
 
54
53
  def on_close(self, ws, close_status_code, close_msg):
55
- self.logger.info(
54
+ logger.info(
56
55
  f"Maitai config listener: websocket connection closed: {close_status_code} {close_msg}"
57
56
  )
58
57
 
59
58
  def on_open(self, ws):
60
- self.logger.info("Maitai config listener: websocket connection established")
59
+ logger.info("Maitai config listener: websocket connection established")
61
60
 
62
61
  def _websocket_thread(self):
63
62
  """Run the websocket client in a thread with automatic reconnection."""
@@ -84,19 +83,19 @@ class ConfigListener:
84
83
  retry_count += 1
85
84
  # Exponential backoff with max of 2 seconds
86
85
  retry_delay = min(reconnect_delay * (2**retry_count), 2)
87
- self.logger.info(
86
+ logger.info(
88
87
  f"Maitai config listener: websocket reconnecting in {retry_delay} seconds..."
89
88
  )
90
89
  threading.Event().wait(retry_delay)
91
90
  except Exception as e:
92
- self.logger.error(
91
+ logger.error(
93
92
  "Maitai config listener error in websocket thread", exc_info=e
94
93
  )
95
94
  if self.running:
96
95
  retry_count += 1
97
96
  # Exponential backoff with max of 2 seconds
98
97
  retry_delay = min(reconnect_delay * (2**retry_count), 2)
99
- self.logger.info(
98
+ logger.info(
100
99
  f"Maitai config listener: websocket reconnecting in {retry_delay} seconds..."
101
100
  )
102
101
  threading.Event().wait(retry_delay)
@@ -137,7 +136,7 @@ class ConfigListener:
137
136
  try:
138
137
  self.ws.close()
139
138
  except Exception as e:
140
- self.logger.debug(
139
+ logger.debug(
141
140
  "Maitai config listener: error closing websocket", exc_info=e
142
141
  )
143
142
 
@@ -1,4 +1,5 @@
1
1
  import asyncio
2
+ import logging
2
3
  import traceback
3
4
  from typing import Iterable, Optional
4
5
 
@@ -17,6 +18,8 @@ from maitai.models.chat import (
17
18
  )
18
19
  from maitai.models.metric import RequestTimingMetric
19
20
 
21
+ logger = logging.getLogger("maitai")
22
+
20
23
 
21
24
  def _get_content_type(content, partial=None):
22
25
  if partial is not None:
@@ -230,7 +233,7 @@ class Evaluator(MaitaiClient):
230
233
  response = client.post(url, headers=headers, json=eval_request)
231
234
  if response.status_code != 200:
232
235
  error_text = response.text
233
- print(
236
+ logger.error(
234
237
  f"Failed to send evaluation request. Status code: {response.status_code}. Error: {error_text}"
235
238
  )
236
239
  self.log_error(config.api_key, error_text, url)
@@ -265,7 +268,7 @@ class Evaluator(MaitaiClient):
265
268
  response = await client.post(url, headers=headers, json=eval_request)
266
269
  if response.status_code != 200:
267
270
  error_text = response.text
268
- print(
271
+ logger.error(
269
272
  f"Failed to send evaluation request. Status code: {response.status_code}. Error: {error_text}"
270
273
  )
271
274
  await self.log_error_async(config.api_key, error_text, url)
@@ -302,7 +305,7 @@ class Evaluator(MaitaiClient):
302
305
  "POST", url, headers=headers, json=eval_request
303
306
  ) as response:
304
307
  if response.status_code != 200:
305
- print(
308
+ logger.error(
306
309
  f"Failed to send stream correction request. Status code: {response.status_code}. Error: {response.text}"
307
310
  )
308
311
  self.log_error(config.api_key, response.text, url)
@@ -1,4 +1,5 @@
1
1
  import asyncio
2
+ import inspect
2
3
  import json
3
4
  import traceback
4
5
  from typing import AsyncIterable, Iterable, Optional
@@ -114,7 +115,6 @@ class Inference(MaitaiClient):
114
115
  except MaitaiConnectionError as e:
115
116
  raise
116
117
  except Exception as e:
117
- print(e)
118
118
  exception = MaitaiConnectionError(
119
119
  f"Failed to send inference request. Error: {e}"
120
120
  )
@@ -133,7 +133,12 @@ class Inference(MaitaiClient):
133
133
  await async_chunk_queue.put(chunk)
134
134
  if chunk.evaluate_response and evaluation_callback:
135
135
  try:
136
- evaluation_callback(chunk.evaluate_response)
136
+ if inspect.iscoroutinefunction(evaluation_callback):
137
+ asyncio.create_task(
138
+ evaluation_callback(chunk.evaluate_response)
139
+ )
140
+ else:
141
+ evaluation_callback(chunk.evaluate_response)
137
142
  except:
138
143
  traceback.print_exc()
139
144
  except Exception as e:
@@ -154,18 +159,23 @@ class Inference(MaitaiClient):
154
159
 
155
160
  try:
156
161
  client = await self.get_async_client()
162
+ # Using a context manager here but properly handling exit even on exceptions
157
163
  async with client.stream(
158
164
  "POST", url, headers=headers, json=request_dict, timeout=timeout
159
165
  ) as response:
160
- async for line in response.aiter_lines():
161
- if line:
162
- build_exception(response, line)
163
- inference_response: InferenceStreamResponse = (
164
- InferenceStreamResponse.model_validate_json(line)
165
- )
166
- if inference_response.keep_alive:
167
- continue
168
- yield inference_response
166
+ try:
167
+ async for line in response.aiter_lines():
168
+ if line:
169
+ build_exception(response, line)
170
+ inference_response: InferenceStreamResponse = (
171
+ InferenceStreamResponse.model_validate_json(line)
172
+ )
173
+ if inference_response.keep_alive:
174
+ continue
175
+ yield inference_response
176
+ except Exception as e:
177
+ # Let the context manager properly close the stream before re-raising
178
+ raise e
169
179
  except TimeoutError as e:
170
180
  raise
171
181
  except BadRequestError as e:
@@ -1,3 +1,4 @@
1
+ import logging
1
2
  import os
2
3
  import time
3
4
  import traceback
@@ -47,6 +48,8 @@ from maitai.models.key import Key
47
48
  from maitai.models.metric import RequestTimingMetric
48
49
  from maitai.tools import Tools
49
50
 
51
+ logger = logging.getLogger(__name__)
52
+
50
53
  DEFAULT_MAX_RETRIES = 2
51
54
 
52
55
 
@@ -62,6 +65,7 @@ class Maitai:
62
65
  cerebras_api_key: Optional[str] = None,
63
66
  azure_api_key: Optional[str] = None,
64
67
  sambanova_api_key: Optional[str] = None,
68
+ gemini_api_key: Optional[str] = None,
65
69
  azure_deployment: Optional[str] = None,
66
70
  azure_api_version: Optional[str] = None,
67
71
  azure_endpoint: Optional[str] = None,
@@ -85,7 +89,7 @@ class Maitai:
85
89
  )
86
90
  if api_key:
87
91
  raise ValueError(
88
- "api_key is deprecated. Use provider specific keys instead. Supported variables: openai_api_key, groq_api_key, anthropic_api_key, cerebras_api_key, azure_api_key, sambanova_api_key"
92
+ "api_key is deprecated. Use provider specific keys instead. Supported variables: openai_api_key, groq_api_key, anthropic_api_key, cerebras_api_key, azure_api_key, sambanova_api_key, gemini_api_key"
89
93
  )
90
94
  if openai_api_key:
91
95
  if not config.auth_keys.openai_api_key:
@@ -129,6 +133,13 @@ class Maitai:
129
133
  )
130
134
  else:
131
135
  config.auth_keys.sambanova_api_key.key_value = sambanova_api_key
136
+ if gemini_api_key:
137
+ if not config.auth_keys.gemini_api_key:
138
+ config.auth_keys.gemini_api_key = Key(
139
+ key_value=gemini_api_key,
140
+ )
141
+ else:
142
+ config.auth_keys.gemini_api_key.key_value = gemini_api_key
132
143
  self._client = None
133
144
  azure_params = None
134
145
  if azure_api_key:
@@ -456,7 +467,7 @@ class Completions:
456
467
  if safe_mode:
457
468
  raise e
458
469
  traceback.print_exc()
459
- print("Maitai issue, retrying on client side")
470
+ logger.warning("Maitai issue, retrying on client side")
460
471
  server_side_inference = False
461
472
  if not server_side_inference:
462
473
  if "openai:" in model:
@@ -656,7 +667,7 @@ class Completions:
656
667
  ):
657
668
  retry_args["model"] = retry_args["fallback_model"]
658
669
  if "gpt" in retry_args.get("model", ""):
659
- print("Maitai issue, retrying on client side")
670
+ logger.warning("Maitai issue, retrying on client side")
660
671
  retry_args["model"] = retry_args["model"].replace("openai:", "")
661
672
  response = self.create(**retry_args)
662
673
  for resp in response:
@@ -1,4 +1,5 @@
1
1
  import asyncio
2
+ import logging
2
3
  import os
3
4
  import time
4
5
  import uuid
@@ -47,6 +48,8 @@ from maitai.models.key import Key
47
48
  from maitai.models.metric import RequestTimingMetric
48
49
  from maitai.tools import Tools
49
50
 
51
+ logger = logging.getLogger("maitai")
52
+
50
53
  DEFAULT_MAX_RETRIES = 2
51
54
 
52
55
 
@@ -61,6 +64,7 @@ class MaitaiAsync:
61
64
  anthropic_api_key: Optional[str] = None,
62
65
  cerebras_api_key: Optional[str] = None,
63
66
  sambanova_api_key: Optional[str] = None,
67
+ gemini_api_key: Optional[str] = None,
64
68
  azure_api_key: Optional[str] = None,
65
69
  azure_deployment: Optional[str] = None,
66
70
  azure_api_version: Optional[str] = None,
@@ -85,7 +89,7 @@ class MaitaiAsync:
85
89
  )
86
90
  if api_key:
87
91
  raise ValueError(
88
- "api_key is deprecated. Use provider specific keys instead. Supported variables: openai_api_key, groq_api_key, anthropic_api_key, cerebras_api_key, azure_api_key, sambanova_api_key"
92
+ "api_key is deprecated. Use provider specific keys instead. Supported variables: openai_api_key, groq_api_key, anthropic_api_key, cerebras_api_key, azure_api_key, sambanova_api_key, gemini_api_key"
89
93
  )
90
94
  if openai_api_key:
91
95
  if not config.auth_keys.openai_api_key:
@@ -124,6 +128,13 @@ class MaitaiAsync:
124
128
  )
125
129
  else:
126
130
  config.auth_keys.sambanova_api_key.key_value = sambanova_api_key
131
+ if gemini_api_key:
132
+ if not config.auth_keys.gemini_api_key:
133
+ config.auth_keys.gemini_api_key = Key(
134
+ key_value=gemini_api_key,
135
+ )
136
+ else:
137
+ config.auth_keys.gemini_api_key.key_value = gemini_api_key
127
138
  self._client = None
128
139
  if azure_api_key:
129
140
  azure_params = AzureParams(
@@ -455,7 +466,7 @@ class AsyncCompletions:
455
466
  raise e
456
467
  if safe_mode:
457
468
  raise e
458
- print("Maitai issue, retrying on client side")
469
+ logger.warning("Maitai issue, retrying on client side")
459
470
  server_side_inference = False
460
471
  if not server_side_inference:
461
472
  if "openai:" in model:
@@ -657,7 +668,7 @@ class AsyncCompletions:
657
668
  retry_args["model"] = retry_args["fallback_model"]
658
669
  if "gpt" in retry_args.get("model", ""):
659
670
  retry_args["model"] = retry_args["model"].replace("openai:", "")
660
- print("Maitai issue, retrying on client side")
671
+ logger.warning("Maitai issue, retrying on client side")
661
672
  response = await self.create(**retry_args)
662
673
  async for resp in response:
663
674
  yield resp
@@ -1,13 +1,9 @@
1
1
  import asyncio
2
2
  import json
3
+ import logging
3
4
  import queue
4
5
  from typing import Any, Callable, Mapping, Optional, Protocol, TypedDict, Union
5
6
 
6
- try:
7
- from typing import override
8
- except ImportError:
9
- from typing_extensions import override
10
-
11
7
  import openai.types.chat as openai_chat_types
12
8
  from pydantic import BaseModel
13
9
  from typing_extensions import Literal, runtime_checkable
@@ -16,6 +12,13 @@ import maitai.models.chat as chat_types
16
12
  from maitai.models.chat import *
17
13
  from maitai.models.chat import ChatCompletionResponse, Tool
18
14
 
15
+ logger = logging.getLogger("maitai")
16
+
17
+ try:
18
+ from typing import override
19
+ except ImportError:
20
+ from typing_extensions import override
21
+
19
22
 
20
23
  class Omit:
21
24
  def __bool__(self) -> Literal[False]:
@@ -129,7 +132,7 @@ class QueueIterable:
129
132
  raise item
130
133
  return item
131
134
  except queue.Empty:
132
- print("Queue timed out")
135
+ logger.warning("Maitai issue, queue timed out")
133
136
  self.done = True
134
137
  raise TimeoutError
135
138
  raise StopIteration
@@ -153,7 +156,7 @@ class QueueIterable:
153
156
  return item
154
157
 
155
158
  except asyncio.TimeoutError:
156
- print("Queue timed out")
159
+ logger.warning("Maitai issue, queue timed out")
157
160
  self.done = True
158
161
  raise StopAsyncIteration
159
162
 
@@ -5,6 +5,7 @@ from enum import Enum, IntEnum
5
5
  from typing import Any, Dict, List, Optional, Union
6
6
 
7
7
  from pydantic import BaseModel, ConfigDict, Field
8
+ from typing_extensions import Literal
8
9
 
9
10
  from maitai.models import application as application_types
10
11
  from maitai.models import config, key, metric, sentinel
@@ -16,6 +17,7 @@ class EvaluationProvider(Enum):
16
17
  CEREBRAS = 2
17
18
  MAITAI = 3
18
19
  SAMBANOVA = 4
20
+ GEMINI = 5
19
21
 
20
22
 
21
23
  class AzureParams(BaseModel):
@@ -39,6 +41,7 @@ class ChatCompletionAuth(BaseModel):
39
41
  cerebras_api_key: Optional[str] = ""
40
42
  azure_api_key: Optional[str] = ""
41
43
  sambanova_api_key: Optional[str] = ""
44
+ gemini_api_key: Optional[str] = ""
42
45
 
43
46
 
44
47
  class Property(BaseModel):
@@ -174,6 +177,7 @@ class ChatCompletionRequest(BaseModel):
174
177
  safe_mode: Optional[bool] = Field(default=False)
175
178
  preserve_model_alias: Optional[bool] = False
176
179
  fallback_config: Optional[config.FallbackConfig] = None
180
+ request_type: Literal["PROD", "RERUN", "SYNTHETIC"] = "PROD"
177
181
 
178
182
 
179
183
  class FunctionCall(BaseModel):
@@ -266,7 +270,7 @@ class EvaluateResponse(BaseModel):
266
270
  class ChatCompletionResponse(BaseModel):
267
271
  id: Optional[Union[int, str]] = None
268
272
  object: str = "chat.completion"
269
- created: float = Field(default_factory=time.time)
273
+ created: Union[int, float] = Field(default_factory=lambda: int(time.time()))
270
274
  model: str = None
271
275
  system_fingerprint: Optional[str] = None
272
276
  choices: List[ChatCompletionChoice] = Field(default_factory=list)
@@ -317,7 +321,7 @@ class ChunkChoice(BaseModel):
317
321
  class ChatCompletionChunk(BaseModel):
318
322
  id: str = ""
319
323
  choices: List[ChunkChoice] = Field(default_factory=list)
320
- created: float = Field(default_factory=time.time)
324
+ created: int = Field(default_factory=lambda: int(time.time()))
321
325
  model: str = ""
322
326
  object: str = ""
323
327
  system_fingerprint: Optional[str] = ""
@@ -23,6 +23,7 @@ class KeyIdMap(BaseModel):
23
23
  cerebras_api_key: Optional[int] = 0
24
24
  azure_api_key: Optional[int] = 0
25
25
  sambanova_api_key: Optional[int] = 0
26
+ gemini_api_key: Optional[int] = 0
26
27
 
27
28
 
28
29
  class KeyMap(BaseModel):
@@ -32,6 +33,7 @@ class KeyMap(BaseModel):
32
33
  cerebras_api_key: Optional[Key] = None
33
34
  azure_api_key: Optional[Key] = None
34
35
  sambanova_api_key: Optional[Key] = None
36
+ gemini_api_key: Optional[Key] = None
35
37
 
36
38
 
37
39
  Key.model_rebuild()
@@ -1,3 +1,3 @@
1
- version = "1.2.18b0"
1
+ version = "1.2.19"
2
2
  if __name__ == "__main__":
3
3
  print(version)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: maitai-python
3
- Version: 1.2.18b0
3
+ Version: 1.2.19
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai