maitai-python 1.2.9__tar.gz → 1.2.10__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 (39) hide show
  1. {maitai_python-1.2.9 → maitai_python-1.2.10}/PKG-INFO +2 -4
  2. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/__init__.py +0 -2
  3. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/_config.py +16 -22
  4. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/_config_listener_thread.py +1 -1
  5. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/_context.py +13 -13
  6. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/_evaluator.py +90 -65
  7. maitai_python-1.2.10/maitai/_inference.py +328 -0
  8. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/_maitai.py +119 -111
  9. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/_maitai_async.py +128 -113
  10. maitai_python-1.2.10/maitai/_maitai_client.py +187 -0
  11. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/models/application.py +1 -0
  12. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/models/chat.py +5 -2
  13. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/models/config.py +4 -0
  14. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/models/key.py +2 -2
  15. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai_common/processes/websocket_listener_thread.py +36 -27
  16. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai_common/version.py +1 -1
  17. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai_python.egg-info/PKG-INFO +2 -4
  18. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai_python.egg-info/requires.txt +1 -3
  19. {maitai_python-1.2.9 → maitai_python-1.2.10}/setup.py +1 -3
  20. maitai_python-1.2.9/maitai/_inference.py +0 -330
  21. maitai_python-1.2.9/maitai/_maitai_client.py +0 -238
  22. {maitai_python-1.2.9 → maitai_python-1.2.10}/README.md +0 -0
  23. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/_pydantic.py +0 -0
  24. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/_types.py +0 -0
  25. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/_utils.py +0 -0
  26. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/models/__init__.py +0 -0
  27. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/models/event.py +0 -0
  28. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/models/inference.py +0 -0
  29. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/models/metric.py +0 -0
  30. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai/tools/__init__.py +0 -0
  31. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai_common/__init__.py +0 -0
  32. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai_common/config/__init__.py +0 -0
  33. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai_common/config/config_service.py +0 -0
  34. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai_common/processes/__init__.py +0 -0
  35. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai_common/processes/io_thread.py +0 -0
  36. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai_python.egg-info/SOURCES.txt +0 -0
  37. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai_python.egg-info/dependency_links.txt +0 -0
  38. {maitai_python-1.2.9 → maitai_python-1.2.10}/maitai_python.egg-info/top_level.txt +0 -0
  39. {maitai_python-1.2.9 → maitai_python-1.2.10}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: maitai-python
3
- Version: 1.2.9
3
+ Version: 1.2.10
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -9,10 +9,8 @@ License: MIT
9
9
  Classifier: Programming Language :: Python :: 3
10
10
  Classifier: License :: OSI Approved :: MIT License
11
11
  Description-Content-Type: text/markdown
12
- Requires-Dist: requests
13
12
  Requires-Dist: openai>=1.34.0
14
- Requires-Dist: httpx
15
- Requires-Dist: aiohttp
13
+ Requires-Dist: httpx[http2]
16
14
  Requires-Dist: websocket-client
17
15
  Requires-Dist: pyhumps
18
16
  Requires-Dist: pydantic>=2.0.0
@@ -1,6 +1,4 @@
1
1
  from maitai._context import ContextManager
2
- from maitai._evaluator import Evaluator as Evaluator # noqa
3
- from maitai._inference import Inference as Inference # noqa
4
2
  from maitai._maitai import Chat, Maitai
5
3
  from maitai._maitai_async import MaitaiAsync
6
4
 
@@ -3,10 +3,6 @@ import os
3
3
  import threading
4
4
  from typing import List
5
5
 
6
- import requests
7
- from requests.adapters import HTTPAdapter
8
- from urllib3 import Retry
9
-
10
6
  from maitai._config_listener_thread import ConfigListenerThread
11
7
  from maitai._maitai_client import MaitaiClient
12
8
  from maitai.models.application import Application
@@ -24,15 +20,7 @@ class Config(MaitaiClient):
24
20
  refresh_timer = None
25
21
 
26
22
  def __init__(self):
27
- retry_strategy = Retry(total=3, backoff_factor=1)
28
- adapter = HTTPAdapter(max_retries=retry_strategy)
29
-
30
- self._session = requests.Session()
31
- self._session.mount("http://", adapter)
32
- self._session.mount("https://", adapter)
33
-
34
23
  self._api_key = None
35
- self._applications: dict[str, Application] = {}
36
24
  self._company_id = None
37
25
  self.websocket_listener_thread = None
38
26
  self.config_listener_thread = None
@@ -43,8 +31,9 @@ class Config(MaitaiClient):
43
31
  groq_api_key=Key(id=-1, key_value=os.environ.get("GROQ_API_KEY")),
44
32
  anthropic_api_key=Key(id=-1, key_value=os.environ.get("ANTHROPIC_API_KEY")),
45
33
  cerebras_api_key=Key(id=-1, key_value=os.environ.get("CEREBRAS_API_KEY")),
34
+ sambanova_api_key=Key(id=-1, key_value=os.environ.get("SAMBANOVA_API_KEY")),
46
35
  )
47
- self.refresh_interval = 30 * 60 # 1 hour in seconds
36
+ self.refresh_interval = 30 * 60 # 30 minutes in seconds
48
37
 
49
38
  @property
50
39
  def api_key(self):
@@ -97,16 +86,18 @@ class Config(MaitaiClient):
97
86
  try:
98
87
  self._load_config_from_file()
99
88
  except Exception:
100
- raise e
89
+ raise e from None
101
90
  self.initialized = False
102
91
  if retry < 5:
103
- t = threading.Timer(
92
+ if self.refresh_timer:
93
+ self.refresh_timer.cancel()
94
+ self.refresh_timer = threading.Timer(
104
95
  interval=2**retry,
105
96
  function=self.initialize,
106
97
  args=(api_key, retry + 1, use_async),
107
98
  )
108
- t.daemon = True
109
- t.start()
99
+ self.refresh_timer.daemon = True
100
+ self.refresh_timer.start()
110
101
 
111
102
  def _start_refresh_timer(self, use_async=False):
112
103
  if self.refresh_timer:
@@ -125,9 +116,6 @@ class Config(MaitaiClient):
125
116
  finally:
126
117
  self._start_refresh_timer(use_async=use_async)
127
118
 
128
- def get_application(self, application_ref_name: str) -> Application:
129
- return self._applications.get(application_ref_name)
130
-
131
119
  def get_application_action_config(
132
120
  self, application_ref_name: str, action_type: str
133
121
  ) -> ActionConfig:
@@ -137,7 +125,6 @@ class Config(MaitaiClient):
137
125
 
138
126
  def store_application_metadata(self, applications: List[Application]):
139
127
  for application in applications:
140
- self._applications[application.application_ref_name] = application
141
128
  for action_type in application.action_types:
142
129
  if (
143
130
  application.application_ref_name
@@ -184,11 +171,18 @@ class Config(MaitaiClient):
184
171
  def cleanup(self):
185
172
  if self.config_listener_thread:
186
173
  self.config_listener_thread.terminate()
174
+ try:
175
+ self.config_listener_thread.join(
176
+ timeout=1.0
177
+ ) # Give thread time to cleanup
178
+ except Exception:
179
+ pass # If join fails, continue with cleanup
187
180
  self.config_listener_thread = None
181
+
188
182
  if self.refresh_timer:
189
183
  self.refresh_timer.cancel()
190
184
  self.refresh_timer = None
191
- self.initialized = False # Reset initialization state
185
+ self.initialized = False
192
186
 
193
187
 
194
188
  config = Config()
@@ -6,7 +6,7 @@ from maitai_common.processes.websocket_listener_thread import WebsocketListenerT
6
6
 
7
7
  class ConfigListenerThread(WebsocketListenerThread):
8
8
  def __init__(self, config, path, type, key=None):
9
- super(ConfigListenerThread, self).__init__(path, type, key, interval=600)
9
+ super(ConfigListenerThread, self).__init__(path, type, key, interval=60)
10
10
  self.config = config
11
11
 
12
12
  def on_message(self, ws, message):
@@ -1,14 +1,11 @@
1
- import json
2
-
3
- import requests
4
-
5
1
  from maitai._config import config
2
+ from maitai._maitai_client import MaitaiClient
6
3
  from maitai._utils import __version__ as version
7
4
  from maitai._utils import required_args
8
5
  from maitai.models.application import ApplicationContext
9
6
 
10
7
 
11
- class ContextManager:
8
+ class ContextManager(MaitaiClient):
12
9
  @required_args(
13
10
  ["application", "reference", "context_body"],
14
11
  ["application", "reference", "file_path"],
@@ -49,15 +46,15 @@ class ContextManager:
49
46
  "x-api-key": config.api_key,
50
47
  "x-client-version": version,
51
48
  }
52
- response = requests.put(
49
+
50
+ client = self.get_client()
51
+ response = client.put(
53
52
  url,
54
53
  headers=headers,
55
- data=json.dumps(
56
- {
57
- "application_ref_name": application,
58
- "context": context.model_dump(),
59
- }
60
- ),
54
+ json={
55
+ "application_ref_name": application,
56
+ "context": context.model_dump(),
57
+ },
61
58
  )
62
59
 
63
60
  if response.status_code != 200:
@@ -70,9 +67,12 @@ class ContextManager:
70
67
  "x-api-key": config.api_key,
71
68
  "x-client-version": version,
72
69
  }
70
+
71
+ client = self.get_client()
73
72
  with open(file_path, "rb") as file:
74
73
  files = {"file": file}
75
- response = requests.post(url, headers=headers, files=files)
74
+ response = client.post(url, headers=headers, files=files)
75
+
76
76
  if response.status_code != 200:
77
77
  raise RuntimeError(f"Error uploading context: {response.text}")
78
78
  return response.json()
@@ -1,10 +1,6 @@
1
1
  import asyncio
2
- import json
3
2
  import traceback
4
- from typing import Iterable
5
-
6
- import aiohttp
7
- import requests
3
+ from typing import Iterable, Optional
8
4
 
9
5
  from maitai._config import config
10
6
  from maitai._maitai_client import MaitaiClient
@@ -36,9 +32,8 @@ class Evaluator(MaitaiClient):
36
32
  def __init__(self):
37
33
  super().__init__()
38
34
 
39
- @classmethod
40
35
  async def evaluate_async(
41
- cls,
36
+ self,
42
37
  session_id,
43
38
  reference_id,
44
39
  intent,
@@ -59,7 +54,7 @@ class Evaluator(MaitaiClient):
59
54
  raise Exception("Unable to automatically determine content_type")
60
55
  if application_id is None and application_ref_name is None:
61
56
  raise Exception("application_id or application_ref_name must be provided")
62
- eval_request = cls.create_eval_request(
57
+ eval_request = self.create_eval_request(
63
58
  application_id,
64
59
  application_ref_name,
65
60
  session_id,
@@ -91,13 +86,15 @@ class Evaluator(MaitaiClient):
91
86
  else None
92
87
  )
93
88
  eval_request["timing_metrics"] = timing.model_dump() if timing else None
94
- await asyncio.create_task(
95
- cls.send_evaluation_request_async(eval_request, callback)
96
- )
89
+ if callback is not None:
90
+ asyncio.create_task(
91
+ self.send_evaluation_request_async(eval_request, callback)
92
+ )
93
+ else:
94
+ return self.send_evaluation_request(eval_request)
97
95
 
98
- @classmethod
99
96
  def evaluate(
100
- cls,
97
+ self,
101
98
  session_id,
102
99
  reference_id,
103
100
  intent,
@@ -119,7 +116,7 @@ class Evaluator(MaitaiClient):
119
116
  raise Exception("Unable to automatically determine content_type")
120
117
  if application_id is None and application_ref_name is None:
121
118
  raise Exception("application_id or application_ref_name must be provided")
122
- eval_request: EvaluateRequest = cls.create_eval_request(
119
+ eval_request: EvaluateRequest = self.create_eval_request(
123
120
  application_id,
124
121
  application_ref_name,
125
122
  session_id,
@@ -150,12 +147,13 @@ class Evaluator(MaitaiClient):
150
147
  chat_completion_response.model_dump()
151
148
  )
152
149
  eval_request["timing_metrics"] = timing.model_dump() if timing else None
150
+ if callback is not None:
151
+ self.executor.submit(self.send_evaluation_request, eval_request, callback)
152
+ else:
153
+ return self.send_evaluation_request(eval_request)
153
154
 
154
- cls.run_async(cls.send_evaluation_request_async(eval_request, callback))
155
-
156
- @classmethod
157
155
  def stream_correction(
158
- cls,
156
+ self,
159
157
  session_id,
160
158
  reference_id,
161
159
  intent,
@@ -166,7 +164,7 @@ class Evaluator(MaitaiClient):
166
164
  fault_description,
167
165
  sentinel_id,
168
166
  ):
169
- eval_request: EvaluateRequest = cls.create_eval_request(
167
+ eval_request: EvaluateRequest = self.create_eval_request(
170
168
  None,
171
169
  application_ref_name,
172
170
  session_id,
@@ -178,11 +176,10 @@ class Evaluator(MaitaiClient):
178
176
  fault_description=fault_description,
179
177
  )
180
178
  eval_request["sentinel_id"] = sentinel_id
181
- return cls.send_stream_correction_request(eval_request)
179
+ return self.send_stream_correction_request(eval_request)
182
180
 
183
- @classmethod
184
181
  def create_eval_request(
185
- cls,
182
+ self,
186
183
  application_id,
187
184
  application_ref_name,
188
185
  session_id,
@@ -217,39 +214,67 @@ class Evaluator(MaitaiClient):
217
214
 
218
215
  return eval_request
219
216
 
220
- @classmethod
217
+ def send_evaluation_request(
218
+ self, eval_request: dict, callback: Optional[EvaluateCallback] = None
219
+ ):
220
+ path = "request" if callback else "submit"
221
+ host = config.maitai_host
222
+ url = f"{host}/evaluation/{path}"
223
+ headers = {
224
+ "Content-Type": "application/json",
225
+ "x-api-key": config.api_key,
226
+ "x-client-version": version,
227
+ }
228
+ try:
229
+ client = self.get_client()
230
+ response = client.post(url, headers=headers, json=eval_request)
231
+ if response.status_code != 200:
232
+ error_text = response.text
233
+ print(
234
+ f"Failed to send evaluation request. Status code: {response.status_code}. Error: {error_text}"
235
+ )
236
+ self.log_error(config.api_key, error_text, url)
237
+ result = response.content
238
+ except Exception as e:
239
+ self.log_error(config.api_key, traceback.format_exc(), url)
240
+ return None
241
+ if result is not None:
242
+ eval_result = EvaluateResponse.model_validate_json(result)
243
+ if callback is not None:
244
+ try:
245
+ callback(eval_result)
246
+ except:
247
+ traceback.print_exc()
248
+ else:
249
+ return eval_result
250
+
221
251
  async def send_evaluation_request_async(
222
- cls, eval_request: dict, callback: EvaluateCallback = None
252
+ self, eval_request: dict, callback: Optional[EvaluateCallback] = None
223
253
  ):
224
254
  path = "request" if callback else "submit"
225
255
  host = config.maitai_host
226
256
  url = f"{host}/evaluation/{path}"
257
+ headers = {
258
+ "Content-Type": "application/json",
259
+ "x-api-key": config.api_key,
260
+ "x-client-version": version,
261
+ }
227
262
 
228
- async def send_request():
229
- headers = {
230
- "Content-Type": "application/json",
231
- "x-api-key": config.api_key,
232
- "x-client-version": version,
233
- }
234
- try:
235
- async with aiohttp.ClientSession(
236
- connector=aiohttp.TCPConnector(ssl=False)
237
- ) as session:
238
- async with session.post(
239
- url, headers=headers, data=json.dumps(eval_request)
240
- ) as response:
241
- if response.status != 200:
242
- error_text = await response.text()
243
- cls.log_error(config.api_key, error_text, url)
244
- print(
245
- f"Failed to send evaluation request. Status code: {response.status}. Error: {error_text}"
246
- )
247
- return None
248
- return await response.read()
249
- except Exception as e:
250
- await cls.increment_error(config.api_key, traceback.format_exc(), url)
263
+ try:
264
+ client = await self.get_async_client()
265
+ response = await client.post(url, headers=headers, json=eval_request)
266
+ if response.status_code != 200:
267
+ error_text = response.text
268
+ print(
269
+ f"Failed to send evaluation request. Status code: {response.status_code}. Error: {error_text}"
270
+ )
271
+ await self.log_error_async(config.api_key, error_text, url)
272
+ return None
273
+ result = response.content
274
+ except Exception as e:
275
+ await self.log_error_async(config.api_key, traceback.format_exc(), url)
276
+ return None
251
277
 
252
- result = await send_request()
253
278
  if result is not None:
254
279
  eval_result = EvaluateResponse.model_validate_json(result)
255
280
  if callback is not None:
@@ -260,9 +285,8 @@ class Evaluator(MaitaiClient):
260
285
  else:
261
286
  return eval_result
262
287
 
263
- @classmethod
264
288
  def send_stream_correction_request(
265
- cls, eval_request: dict
289
+ self, eval_request: dict
266
290
  ) -> Iterable[ChatCompletionChunk]:
267
291
  def consume_stream():
268
292
  host = config.maitai_host
@@ -273,21 +297,22 @@ class Evaluator(MaitaiClient):
273
297
  "x-client-version": version,
274
298
  }
275
299
 
276
- response = requests.post(
277
- url, headers=headers, data=json.dumps(eval_request), stream=True
278
- )
279
- if response.status_code != 200:
280
- print(
281
- f"Failed to send stream correction request. Status code: {response.status_code}. Error: {response.text}"
282
- )
283
- cls.log_error(config.api_key, response.text, url)
284
- return
285
- try:
286
- for line in response.iter_lines():
287
- if line:
288
- yield line
289
- finally:
290
- response.close()
300
+ client = self.get_client()
301
+ with client.stream(
302
+ "POST", url, headers=headers, json=eval_request
303
+ ) as response:
304
+ if response.status_code != 200:
305
+ print(
306
+ f"Failed to send stream correction request. Status code: {response.status_code}. Error: {response.text}"
307
+ )
308
+ self.log_error(config.api_key, response.text, url)
309
+ return
310
+ try:
311
+ for line in response.iter_lines():
312
+ if line:
313
+ yield line
314
+ finally:
315
+ pass # No need to close response as context manager handles it
291
316
 
292
317
  for resp in consume_stream():
293
318
  inference_response: ChatCompletionChunk = (