maitai-python 1.2.1__py3-none-any.whl → 1.2.3__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/_config.py CHANGED
@@ -9,84 +9,15 @@ from requests.adapters import HTTPAdapter
9
9
  from urllib3 import Retry
10
10
 
11
11
  from maitai._config_listener_thread import ConfigListenerThread
12
- from maitai._utils import __version__ as version
12
+ from maitai._maitai_client import MaitaiClient
13
13
  from maitai_common.config import config_service
14
14
  from maitai_gen.application import Application
15
15
  from maitai_gen.config import Config as ActionConfig
16
16
  from maitai_gen.key import Key, KeyMap
17
17
 
18
18
 
19
- def _get_aws_instance_metadata(url, timeout=2):
20
- try:
21
- token_url = "http://169.254.169.254/latest/api/token"
22
- token_headers = {"X-aws-ec2-metadata-token-ttl-seconds": "21600"}
23
- token_response = requests.put(token_url, headers=token_headers, timeout=timeout)
19
+ class Config(MaitaiClient):
24
20
 
25
- if token_response.status_code == 200:
26
- token = token_response.text
27
- headers = {"X-aws-ec2-metadata-token": token}
28
- else:
29
- headers = None
30
-
31
- response = requests.get(url, headers=headers, timeout=timeout)
32
- response.raise_for_status()
33
- return response.text
34
- except requests.RequestException:
35
- return None
36
-
37
-
38
- def _get_gcp_instance_metadata(url, timeout=2):
39
- try:
40
- headers = {"Metadata-Flavor": "Google"}
41
- response = requests.get(url, headers=headers, timeout=timeout)
42
- response.raise_for_status()
43
- return response.text
44
- except requests.RequestException:
45
- return None
46
-
47
-
48
- def _get_azure_instance_metadata(timeout=2):
49
- try:
50
- headers = {"Metadata": "true"}
51
- url = "http://169.254.169.254/metadata/instance/compute?api-version=2021-02-01"
52
- response = requests.get(url, headers=headers, timeout=timeout)
53
- response.raise_for_status()
54
- data = response.json()
55
- return data.get("location")
56
- except requests.RequestException:
57
- return None
58
-
59
-
60
- def _determine_maitai_host():
61
- if maitai_host := os.environ.get("MAITAI_HOST"):
62
- return maitai_host.rstrip("/")
63
-
64
- if (
65
- _get_aws_instance_metadata(
66
- "http://169.254.169.254/latest/meta-data/placement/region"
67
- )
68
- == "us-west-2"
69
- ):
70
- return "https://api.aws.us-west-2.trymaitai.ai"
71
-
72
- gcp_zone = _get_gcp_instance_metadata(
73
- "http://metadata.google.internal/computeMetadata/v1/instance/zone"
74
- )
75
- if gcp_zone:
76
- if "us-west1" in gcp_zone:
77
- return "https://api.gcp.us-west1.trymaitai.ai"
78
- elif "us-central1" in gcp_zone:
79
- return "https://api.gcp.us-central1.trymaitai.ai"
80
-
81
- azure_region = _get_azure_instance_metadata()
82
- if azure_region == "westus2":
83
- return "https://api.azure.westus2.trymaitai.ai"
84
-
85
- return "https://api.trymaitai.ai"
86
-
87
-
88
- class Config:
89
- maitai_host = _determine_maitai_host()
90
21
  maitai_ws = os.environ.get(
91
22
  "MAITAI_WS", "wss://09hidyy627.execute-api.us-west-2.amazonaws.com/production"
92
23
  )
@@ -136,15 +67,28 @@ class Config:
136
67
  def api_key(self, value):
137
68
  self._api_key = value
138
69
 
139
- def initialize(self, api_key, retry=0):
70
+ def initialize(self, api_key, retry=0, use_async=False):
140
71
  if self.initialized and self.api_key == api_key:
141
72
  return
142
73
  self.api_key = api_key
143
74
  self.initialized = True
144
75
  try:
145
- self.refresh_applications()
76
+ # Call init_sdk and process the response
77
+ response_json = self.init_sdk(
78
+ api_key, self.maitai_host, use_async=use_async
79
+ )
80
+
81
+ applications = [
82
+ Application().from_dict(app_json)
83
+ for app_json in response_json["applications"]
84
+ ]
85
+ self._company_id = response_json.get("company_id")
86
+ if not self._company_id:
87
+ raise Exception("Company ID not found in response")
88
+
89
+ self.store_application_metadata(applications)
146
90
  self._initialize_websocket()
147
- self._start_refresh_timer()
91
+ self._start_refresh_timer(use_async=use_async)
148
92
  except Exception as e:
149
93
  try:
150
94
  self._load_config_from_file()
@@ -155,27 +99,27 @@ class Config:
155
99
  t = threading.Timer(
156
100
  interval=2**retry,
157
101
  function=self.initialize,
158
- args=(api_key, retry + 1),
102
+ args=(api_key, retry + 1, use_async),
159
103
  )
160
104
  t.daemon = True
161
105
  t.start()
162
106
 
163
- def _start_refresh_timer(self):
107
+ def _start_refresh_timer(self, use_async=False):
164
108
  if self.refresh_timer:
165
109
  self.refresh_timer.cancel()
166
110
  self.refresh_timer = threading.Timer(
167
- self.refresh_interval, self._refresh_and_reschedule
111
+ self.refresh_interval, self._refresh_and_reschedule, args=(use_async,)
168
112
  )
169
113
  self.refresh_timer.daemon = True
170
114
  self.refresh_timer.start()
171
115
 
172
- def _refresh_and_reschedule(self):
116
+ def _refresh_and_reschedule(self, use_async=False):
173
117
  try:
174
- self.refresh_applications()
118
+ self.refresh_applications(use_async=use_async)
175
119
  except Exception as e:
176
120
  pass
177
121
  finally:
178
- self._start_refresh_timer()
122
+ self._start_refresh_timer(use_async=use_async)
179
123
 
180
124
  def get_application(self, application_ref_name: str) -> Application:
181
125
  return self._applications.get(application_ref_name)
@@ -187,29 +131,6 @@ class Config:
187
131
  action_type, config_service.get_default_config()
188
132
  )
189
133
 
190
- def refresh_applications(self):
191
- host = self.maitai_host
192
- url = f"{host}/config/init_sdk"
193
- headers = {
194
- "Content-Type": "application/json",
195
- "x-api-key": self.api_key,
196
- "x-client-version": version,
197
- }
198
-
199
- response = self._session.get(url, headers=headers, timeout=15)
200
- self._session.close()
201
- if response.status_code != 200:
202
- raise Exception(f"Failed to initialize Maitai client: {response.text}")
203
- response_json = response.json()
204
- applications = [
205
- Application().from_dict(app_json)
206
- for app_json in response_json["applications"]
207
- ]
208
- self._company_id = response_json.get("company_id")
209
- if not self._company_id:
210
- raise Exception("Company ID not found in response")
211
- return self.store_application_metadata(applications)
212
-
213
134
  def store_application_metadata(self, applications: List[Application]):
214
135
  for application in applications:
215
136
  self._applications[application.application_ref_name] = application
maitai/_evaluator.py CHANGED
@@ -238,17 +238,16 @@ class Evaluator(MaitaiClient):
238
238
  async with session.post(
239
239
  url, headers=headers, data=json.dumps(eval_request)
240
240
  ) as response:
241
- print("received", response.status)
242
241
  if response.status != 200:
243
242
  error_text = await response.text()
244
- cls.log_error(error_text, url)
243
+ cls.log_error(config.api_key, error_text, url)
245
244
  print(
246
245
  f"Failed to send evaluation request. Status code: {response.status}. Error: {error_text}"
247
246
  )
248
247
  return None
249
248
  return await response.read()
250
249
  except Exception as e:
251
- await cls.increment_error(str(e), url)
250
+ await cls.increment_error(config.api_key, str(e), url)
252
251
 
253
252
  result = await send_request()
254
253
  if result is not None:
@@ -281,7 +280,7 @@ class Evaluator(MaitaiClient):
281
280
  print(
282
281
  f"Failed to send stream correction request. Status code: {response.status_code}. Error: {response.text}"
283
282
  )
284
- cls.log_error(response.text, url)
283
+ cls.log_error(config.api_key, response.text, url)
285
284
  return
286
285
  try:
287
286
  for line in response.iter_lines():
maitai/_inference.py CHANGED
@@ -1,4 +1,3 @@
1
- import asyncio
2
1
  import json
3
2
  import traceback
4
3
  from typing import AsyncIterable, Iterable, Optional
@@ -7,8 +6,6 @@ import aiohttp
7
6
  import requests
8
7
  from aiohttp import ClientTimeout
9
8
  from betterproto import Casing
10
- from requests.adapters import HTTPAdapter
11
- from urllib3.util.retry import Retry
12
9
 
13
10
  from maitai._config import config
14
11
  from maitai._maitai_client import MaitaiClient
@@ -36,9 +33,6 @@ class InferenceWarning(Warning):
36
33
 
37
34
 
38
35
  class Inference(MaitaiClient):
39
- _session = None
40
- _async_session = None
41
-
42
36
  def __init__(self):
43
37
  super().__init__()
44
38
 
@@ -143,7 +137,7 @@ class Inference(MaitaiClient):
143
137
  if not inference_response.keep_alive:
144
138
  yield inference_response
145
139
  except requests.exceptions.RequestException as e:
146
- cls.log_error(str(e), url)
140
+ cls.log_error(config.api_key, str(e), url)
147
141
  raise MaitaiConnectionError(f"Failed to send inference request. Error: {e}")
148
142
 
149
143
  @classmethod
@@ -165,7 +159,12 @@ class Inference(MaitaiClient):
165
159
  try:
166
160
  if cls._async_session is None:
167
161
  cls._async_session = aiohttp.ClientSession(
168
- connector=aiohttp.TCPConnector(ssl=False, limit=100),
162
+ connector=aiohttp.TCPConnector(
163
+ ssl=False,
164
+ limit=100,
165
+ keepalive_timeout=300,
166
+ force_close=False,
167
+ ),
169
168
  timeout=ClientTimeout(timeout) if timeout else None,
170
169
  )
171
170
 
@@ -174,7 +173,7 @@ class Inference(MaitaiClient):
174
173
  ) as response:
175
174
  if response.status != 200:
176
175
  error_text = await response.text()
177
- cls.log_error(error_text, url)
176
+ cls.log_error(config.api_key, error_text, url)
178
177
  exception = MaitaiConnectionError(
179
178
  f"Failed to send inference request. Status code: {response.status}. Error: {error_text}"
180
179
  )
@@ -209,7 +208,7 @@ class Inference(MaitaiClient):
209
208
  exception = MaitaiConnectionError(
210
209
  f"Failed to send inference request: {str(e)}"
211
210
  )
212
- await cls.increment_error(str(e), url)
211
+ await cls.increment_error(config.api_key, str(e), url)
213
212
  if chunk_queue:
214
213
  chunk_queue.put(exception)
215
214
  if async_chunk_queue:
@@ -234,7 +233,7 @@ class Inference(MaitaiClient):
234
233
  data=json.dumps(storage_request),
235
234
  )
236
235
  except Exception as e:
237
- await cls.increment_error(str(e), url)
236
+ await cls.increment_error(config.api_key, str(e), url)
238
237
 
239
238
  @classmethod
240
239
  def store_request_timing_data(cls, metric: RequestTimingMetric):
@@ -259,23 +258,6 @@ class Inference(MaitaiClient):
259
258
  except:
260
259
  pass
261
260
 
262
- @classmethod
263
- def get_session(cls):
264
- if cls._session is None:
265
- cls._session = requests.Session()
266
- retries = Retry(
267
- total=3, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504]
268
- )
269
- cls._session.mount(
270
- "http://",
271
- HTTPAdapter(max_retries=retries, pool_connections=10, pool_maxsize=100),
272
- )
273
- cls._session.mount(
274
- "https://",
275
- HTTPAdapter(max_retries=retries, pool_connections=10, pool_maxsize=100),
276
- )
277
- return cls._session
278
-
279
261
  @classmethod
280
262
  async def send_inference_request_async_fresh_session(
281
263
  cls,
@@ -302,7 +284,7 @@ class Inference(MaitaiClient):
302
284
  ) as response:
303
285
  if response.status != 200:
304
286
  error_text = await response.text()
305
- cls.log_error(error_text, url)
287
+ cls.log_error(config.api_key, error_text, url)
306
288
  exception = MaitaiConnectionError(
307
289
  f"Failed to send inference request. Status code: {response.status}. Error: {error_text}"
308
290
  )
@@ -340,33 +322,8 @@ class Inference(MaitaiClient):
340
322
  exception = MaitaiConnectionError(
341
323
  f"Failed to send inference request: {str(e)}"
342
324
  )
343
- await cls.increment_error(str(e), url)
325
+ await cls.increment_error(config.api_key, str(e), url)
344
326
  if chunk_queue:
345
327
  chunk_queue.put(exception)
346
328
  if async_chunk_queue:
347
329
  await async_chunk_queue.put(exception)
348
-
349
- @classmethod
350
- def close_session(cls):
351
- if cls._session:
352
- cls._session.close()
353
- cls._session = None
354
-
355
- @classmethod
356
- async def close_async_session(cls):
357
- if cls._async_session:
358
- await cls._async_session.close()
359
- cls._async_session = None
360
-
361
- def __del__(self):
362
- self.close_session()
363
- self.run_async(self.close_async_session())
364
-
365
-
366
- import atexit
367
-
368
-
369
- @atexit.register
370
- def cleanup():
371
- asyncio.run(Inference.close_async_session())
372
- Inference.close_session()
maitai/_maitai.py CHANGED
@@ -20,6 +20,7 @@ from maitai._inference import (
20
20
  from maitai._types import (
21
21
  Body,
22
22
  EvaluateCallback,
23
+ FallbackConfig,
23
24
  Headers,
24
25
  MaitaiChunk,
25
26
  MaitaiCompletion,
@@ -65,7 +66,7 @@ class Maitai:
65
66
  if not maitai_api_key:
66
67
  maitai_api_key = os.environ.get("MAITAI_API_KEY")
67
68
  if maitai_api_key:
68
- config.initialize(maitai_api_key)
69
+ config.initialize(maitai_api_key, use_async=False)
69
70
  else:
70
71
  raise ValueError(
71
72
  "MAITAI_API_KEY has not been set. Either set via environment variable or pass it directly into the client."
@@ -155,6 +156,7 @@ class Completions:
155
156
  assistant: bool = False,
156
157
  metadata: dict = {},
157
158
  safe_mode: bool = None,
159
+ fallback_config: FallbackConfig = None,
158
160
  # OpenAI Arguments
159
161
  messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
160
162
  model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
@@ -270,8 +272,25 @@ class Completions:
270
272
  timeout = maitai_config.timeout
271
273
  if context_retrieval_enabled is None:
272
274
  context_retrieval_enabled = maitai_config.context_retrieval_enabled
273
- if fallback_model is None and maitai_config.fallback_model:
274
- fallback_model = maitai_config.fallback_model
275
+ if fallback_model:
276
+ warnings.warn(
277
+ "fallback_model is deprecated. Use fallback_config instead.",
278
+ DeprecationWarning,
279
+ )
280
+ if fallback_config is None and maitai_config.fallback_config:
281
+ fallback_config = {
282
+ "model": maitai_config.fallback_config.model,
283
+ "strategy": maitai_config.fallback_config.strategy,
284
+ "timeout": maitai_config.fallback_config.timeout,
285
+ }
286
+ if fallback_config is None and fallback_model:
287
+ fallback_config = {
288
+ "model": fallback_model,
289
+ "strategy": "reactive",
290
+ "timeout": None,
291
+ }
292
+ if fallback_config and "model" in fallback_config:
293
+ fallback_model = fallback_config["model"]
275
294
  completion_params = get_chat_completion_params(
276
295
  messages=messages,
277
296
  model=model,
@@ -317,6 +336,7 @@ class Completions:
317
336
  "auth_keys": config.auth_keys.to_dict(),
318
337
  "metadata": metadata,
319
338
  "safe_mode": safe_mode,
339
+ "fallback_config": fallback_config,
320
340
  }
321
341
 
322
342
  if self._client_params is not None:
@@ -556,8 +576,8 @@ def _process_inference_stream(
556
576
  ):
557
577
  return
558
578
  except MaitaiConnectionError as e:
559
- if "gpt" not in retry_args.get("model", "") and "gpt" in retry_args.get(
560
- "fallback_model", ""
579
+ if "gpt" not in retry_args.get("model", "") and "gpt" in (
580
+ retry_args.get("fallback_model", "") or ""
561
581
  ):
562
582
  retry_args["model"] = retry_args["fallback_model"]
563
583
  if "gpt" in retry_args.get("model", ""):
maitai/_maitai_async.py CHANGED
@@ -20,6 +20,7 @@ from maitai._inference import (
20
20
  from maitai._types import (
21
21
  Body,
22
22
  EvaluateCallback,
23
+ FallbackConfig,
23
24
  Headers,
24
25
  MaitaiChunk,
25
26
  MaitaiCompletion,
@@ -65,12 +66,11 @@ class MaitaiAsync:
65
66
  if not maitai_api_key:
66
67
  maitai_api_key = os.environ.get("MAITAI_API_KEY")
67
68
  if maitai_api_key:
68
- config.initialize(maitai_api_key)
69
+ config.initialize(maitai_api_key, use_async=True)
69
70
  else:
70
71
  raise ValueError(
71
72
  "MAITAI_API_KEY has not been set. Either set via environment variable or pass it directly into the client."
72
73
  )
73
-
74
74
  if api_key:
75
75
  if not openai_api_key:
76
76
  openai_api_key = api_key
@@ -156,6 +156,7 @@ class AsyncCompletions:
156
156
  assistant: bool = False,
157
157
  metadata: dict = {},
158
158
  safe_mode: bool = None,
159
+ fallback_config: FallbackConfig = None,
159
160
  # OpenAI Arguments
160
161
  messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
161
162
  model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
@@ -271,8 +272,25 @@ class AsyncCompletions:
271
272
  timeout = maitai_config.timeout
272
273
  if context_retrieval_enabled is None:
273
274
  context_retrieval_enabled = maitai_config.context_retrieval_enabled
274
- if fallback_model is None and maitai_config.fallback_model:
275
- fallback_model = maitai_config.fallback_model
275
+ if fallback_model is not None:
276
+ warnings.warn(
277
+ "fallback_model is deprecated. Use fallback_config instead.",
278
+ DeprecationWarning,
279
+ )
280
+ if fallback_config is None and maitai_config.fallback_config:
281
+ fallback_config = {
282
+ "model": maitai_config.fallback_config.model,
283
+ "strategy": maitai_config.fallback_config.strategy,
284
+ "timeout": maitai_config.fallback_config.timeout,
285
+ }
286
+ if fallback_config is None and fallback_model:
287
+ fallback_config = {
288
+ "model": fallback_model,
289
+ "strategy": "reactive",
290
+ "timeout": None,
291
+ }
292
+ if fallback_config and "model" in fallback_config:
293
+ fallback_model = fallback_config["model"]
276
294
  completion_params = get_chat_completion_params(
277
295
  messages=messages,
278
296
  model=model,
@@ -558,8 +576,8 @@ async def _process_inference_stream_async(
558
576
  ):
559
577
  return
560
578
  except MaitaiConnectionError as e:
561
- if "gpt" not in retry_args.get("model", "") and "gpt" in retry_args.get(
562
- "fallback_model", ""
579
+ if "gpt" not in retry_args.get("model", "") and "gpt" in (
580
+ retry_args.get("fallback_model", "") or ""
563
581
  ):
564
582
  retry_args["model"] = retry_args["fallback_model"]
565
583
  if "gpt" in retry_args.get("model", ""):
maitai/_maitai_client.py CHANGED
@@ -1,17 +1,139 @@
1
1
  import asyncio
2
+ import atexit
2
3
  import json
4
+ import os
3
5
  import threading
4
6
 
5
7
  import aiohttp
8
+ import requests
9
+ from requests.adapters import HTTPAdapter
10
+ from urllib3.util.retry import Retry
6
11
 
7
- from maitai._config import config
8
12
  from maitai_common.version import version
9
13
 
10
14
 
15
+ def _get_aws_instance_metadata(url, timeout=2):
16
+ try:
17
+ token_url = "http://169.254.169.254/latest/api/token"
18
+ token_headers = {"X-aws-ec2-metadata-token-ttl-seconds": "21600"}
19
+ token_response = requests.put(token_url, headers=token_headers, timeout=timeout)
20
+
21
+ if token_response.status_code == 200:
22
+ token = token_response.text
23
+ headers = {"X-aws-ec2-metadata-token": token}
24
+ else:
25
+ headers = None
26
+
27
+ response = requests.get(url, headers=headers, timeout=timeout)
28
+ response.raise_for_status()
29
+ return response.text
30
+ except requests.RequestException:
31
+ return None
32
+
33
+
34
+ def _get_gcp_instance_metadata(url, timeout=2):
35
+ try:
36
+ headers = {"Metadata-Flavor": "Google"}
37
+ response = requests.get(url, headers=headers, timeout=timeout)
38
+ response.raise_for_status()
39
+ return response.text
40
+ except requests.RequestException:
41
+ return None
42
+
43
+
44
+ def _get_azure_instance_metadata(timeout=2):
45
+ try:
46
+ headers = {"Metadata": "true"}
47
+ url = "http://169.254.169.254/metadata/instance/compute?api-version=2021-02-01"
48
+ response = requests.get(url, headers=headers, timeout=timeout)
49
+ response.raise_for_status()
50
+ data = response.json()
51
+ return data.get("location")
52
+ except requests.RequestException:
53
+ return None
54
+
55
+
56
+ def _determine_maitai_host():
57
+ if maitai_host := os.environ.get("MAITAI_HOST"):
58
+ return maitai_host.rstrip("/")
59
+
60
+ if (
61
+ _get_aws_instance_metadata(
62
+ "http://169.254.169.254/latest/meta-data/placement/region"
63
+ )
64
+ == "us-west-2"
65
+ ):
66
+ return "https://api.aws.us-west-2.trymaitai.ai"
67
+
68
+ gcp_zone = _get_gcp_instance_metadata(
69
+ "http://metadata.google.internal/computeMetadata/v1/instance/zone"
70
+ )
71
+ if gcp_zone:
72
+ if "us-west1" in gcp_zone:
73
+ return "https://api.gcp.us-west1.trymaitai.ai"
74
+ elif "us-central1" in gcp_zone:
75
+ return "https://api.gcp.us-central1.trymaitai.ai"
76
+
77
+ azure_region = _get_azure_instance_metadata()
78
+ if azure_region == "westus2":
79
+ return "https://api.azure.westus2.trymaitai.ai"
80
+
81
+ return "https://api.trymaitai.ai"
82
+
83
+
11
84
  class MaitaiClient:
85
+ _session = None
86
+ _async_session = None
87
+ maitai_host = _determine_maitai_host()
88
+ _loop = asyncio.new_event_loop()
89
+ _thr = threading.Thread(
90
+ target=_loop.run_forever, name="Maitai Async Runner", daemon=True
91
+ )
12
92
 
13
93
  def __init__(self):
14
94
  super().__init__()
95
+ atexit.register(self.cleanup)
96
+
97
+ def cleanup(self):
98
+ self.run_async_with_result(self.close_async_session())
99
+ self.close_session()
100
+ if self._loop.is_running():
101
+ self._loop.call_soon_threadsafe(self._loop.stop)
102
+ if self._thr.is_alive():
103
+ self._thr.join()
104
+
105
+ @classmethod
106
+ def get_session(cls):
107
+ if cls._session is None:
108
+ cls._session = requests.Session()
109
+ retries = Retry(
110
+ total=3, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504]
111
+ )
112
+ cls._session.mount(
113
+ "http://",
114
+ HTTPAdapter(max_retries=retries, pool_connections=10, pool_maxsize=100),
115
+ )
116
+ cls._session.mount(
117
+ "https://",
118
+ HTTPAdapter(max_retries=retries, pool_connections=10, pool_maxsize=100),
119
+ )
120
+ return cls._session
121
+
122
+ @classmethod
123
+ def close_session(cls):
124
+ if cls._session:
125
+ cls._session.close()
126
+ cls._session = None
127
+
128
+ @classmethod
129
+ async def close_async_session(cls):
130
+ if cls._async_session:
131
+ await cls._async_session.close()
132
+ cls._async_session = None
133
+
134
+ def __del__(self):
135
+ self.close_session()
136
+ self.run_async_with_result(self.close_async_session())
15
137
 
16
138
  @classmethod
17
139
  def run_async(cls, coro):
@@ -38,16 +160,23 @@ class MaitaiClient:
38
160
  threading.Thread(target=run).start()
39
161
 
40
162
  @classmethod
41
- def log_error(cls, error: str, path: str):
42
- cls.run_async(cls.increment_error(error, path))
163
+ def run_async_with_result(cls, coro):
164
+ if not cls._thr.is_alive():
165
+ cls._thr.start()
166
+ future = asyncio.run_coroutine_threadsafe(coro, cls._loop)
167
+ return future.result()
43
168
 
44
169
  @classmethod
45
- async def increment_error(cls, error: str, path: str):
46
- host = config.maitai_host
170
+ def log_error(cls, api_key: str, error: str, path: str):
171
+ cls.run_async_with_result(cls.increment_error(api_key, error, path))
172
+
173
+ @classmethod
174
+ async def increment_error(cls, api_key: str, error: str, path: str):
175
+ host = cls.maitai_host
47
176
  url = f"{host}/metrics/increment/python_sdk_error"
48
177
  headers = {
49
178
  "Content-Type": "application/json",
50
- "x-api-key": config.api_key,
179
+ "x-api-key": api_key,
51
180
  "x-client-version": version,
52
181
  }
53
182
  labels = {
@@ -62,3 +191,42 @@ class MaitaiClient:
62
191
  return await session.put(url, headers=headers, data=json.dumps(labels))
63
192
  except:
64
193
  pass
194
+
195
+ @classmethod
196
+ def init_sdk(cls, api_key: str, host: str, use_async: bool = False):
197
+ """Initialize the SDK by making a request to /config/init_sdk"""
198
+ url = f"{host}/config/init_sdk"
199
+ headers = {
200
+ "Content-Type": "application/json",
201
+ "x-api-key": api_key,
202
+ "x-client-version": version,
203
+ }
204
+
205
+ if use_async:
206
+ if cls._async_session is None:
207
+
208
+ async def init_async():
209
+ cls._async_session = aiohttp.ClientSession(
210
+ connector=aiohttp.TCPConnector(
211
+ ssl=False,
212
+ limit=100,
213
+ keepalive_timeout=300, # 5 minutes keepalive
214
+ force_close=False,
215
+ )
216
+ )
217
+ async with cls._async_session.get(
218
+ url, headers=headers, timeout=15
219
+ ) as response:
220
+ if response.status != 200:
221
+ raise Exception(
222
+ f"Failed to initialize Maitai client: {await response.text()}"
223
+ )
224
+ return await response.json()
225
+
226
+ return cls.run_async_with_result(init_async())
227
+ else:
228
+ session = cls.get_session()
229
+ response = session.get(url, headers=headers, timeout=15)
230
+ if response.status_code != 200:
231
+ raise Exception(f"Failed to initialize Maitai client: {response.text}")
232
+ return response.json()
maitai/_types.py CHANGED
@@ -1,7 +1,7 @@
1
1
  import asyncio
2
2
  import json
3
3
  import queue
4
- from typing import Any, Callable, Mapping, Optional, Protocol, Union
4
+ from typing import Any, Callable, Mapping, Optional, Protocol, TypedDict, Union
5
5
 
6
6
  import openai.types.chat as openai_chat_types
7
7
  from betterproto import Casing
@@ -185,3 +185,9 @@ class QueueIterable:
185
185
 
186
186
 
187
187
  EvaluateCallback = Callable[[EvaluateResponse], None]
188
+
189
+
190
+ class FallbackConfig(TypedDict):
191
+ model: Optional[str]
192
+ strategy: Literal["reactive", "first_response", "timeout"]
193
+ timeout: Optional[float]
maitai_common/version.py CHANGED
@@ -1,3 +1,3 @@
1
- version = "1.2.1"
1
+ version = "1.2.3"
2
2
  if __name__ == "__main__":
3
3
  print(version)
@@ -18,6 +18,7 @@ from betterproto.grpc.grpclib_server import ServiceBase
18
18
 
19
19
  from .. import (
20
20
  application as _application__,
21
+ config as _config__,
21
22
  key as _key__,
22
23
  metric as _metric__,
23
24
  sentinel as _sentinel__,
@@ -73,6 +74,7 @@ class ChatCompletionRequest(betterproto.Message):
73
74
  25, betterproto.TYPE_STRING, betterproto.TYPE_STRING
74
75
  )
75
76
  safe_mode: bool = betterproto.bool_field(26)
77
+ fallback_config: "_config__.FallbackConfig" = betterproto.message_field(27)
76
78
 
77
79
 
78
80
  @dataclass(eq=False, repr=False)
@@ -17,6 +17,13 @@ class InferenceLocations(betterproto.Enum):
17
17
  SERVER = 1
18
18
 
19
19
 
20
+ @dataclass(eq=False, repr=False)
21
+ class FallbackConfig(betterproto.Message):
22
+ model: str = betterproto.string_field(1)
23
+ strategy: str = betterproto.string_field(2)
24
+ timeout: float = betterproto.double_field(3)
25
+
26
+
20
27
  @dataclass(eq=False, repr=False)
21
28
  class Config(betterproto.Message):
22
29
  inference_location: "InferenceLocations" = betterproto.enum_field(1)
@@ -40,6 +47,7 @@ class Config(betterproto.Message):
40
47
  feedback: List[str] = betterproto.string_field(22)
41
48
  generating_sentinels: bool = betterproto.bool_field(23)
42
49
  sentinel_regeneration_enabled: bool = betterproto.bool_field(24)
50
+ fallback_config: "FallbackConfig" = betterproto.message_field(25)
43
51
 
44
52
 
45
53
  @dataclass(eq=False, repr=False)
@@ -14,6 +14,7 @@ import betterproto
14
14
  from .. import (
15
15
  application as _application__,
16
16
  chat as _chat__,
17
+ config as _config__,
17
18
  sentinel as _sentinel__,
18
19
  )
19
20
 
@@ -49,3 +50,21 @@ class TestSet(betterproto.Message):
49
50
  6, betterproto.TYPE_STRING, betterproto.TYPE_STRING
50
51
  )
51
52
  date_created: int = betterproto.int64_field(7)
53
+ description: str = betterproto.string_field(8)
54
+
55
+
56
+ @dataclass(eq=False, repr=False)
57
+ class TestRun(betterproto.Message):
58
+ id: int = betterproto.int64_field(1)
59
+ test_set_id: int = betterproto.int64_field(2)
60
+ company_id: int = betterproto.int64_field(3)
61
+ application_id: int = betterproto.int64_field(4)
62
+ application_action_id: int = betterproto.int64_field(5)
63
+ date_created: int = betterproto.int64_field(6)
64
+ date_completed: int = betterproto.int64_field(7)
65
+ description: str = betterproto.string_field(8)
66
+ status: str = betterproto.string_field(9)
67
+ config: "_config__.Config" = betterproto.message_field(10)
68
+ meta: Dict[str, str] = betterproto.map_field(
69
+ 11, betterproto.TYPE_STRING, betterproto.TYPE_STRING
70
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: maitai-python
3
- Version: 1.2.1
3
+ Version: 1.2.3
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -1,18 +1,18 @@
1
1
  maitai/__init__.py,sha256=HjnRas9JQpcCPOh9m1ABfexl6BV69tRcJzArdQpCWkQ,593
2
2
  maitai/_azure.py,sha256=ZQXVzmU2QPJ41wQUxqFkyeAKAJ6HrMoQKDbi3lyUJVc,8513
3
- maitai/_config.py,sha256=n1RV9Udg5_EGNLCvVm8WR_RAmNeI2LCXkIWDXme727I,10104
3
+ maitai/_config.py,sha256=IkpwORKXpO2rDRJ6JHmuGWb29g9IR9Cc2Tl3VrDuMH8,7603
4
4
  maitai/_config_listener_thread.py,sha256=VaftjUXrP8oe6yg0TXUlIZW2vGw7bTk8p_95o4dSVgo,902
5
5
  maitai/_context.py,sha256=WmCLGd7BK1ViImd7uDTsjly7ECcugioZhGjxXwETHfI,2401
6
- maitai/_evaluator.py,sha256=qbwj--FCvNnRz-LTpuenMYf-2eGZRMrPqxepSerKWUo,10355
7
- maitai/_inference.py,sha256=uINtF7KUFGfLDZ4wQ8rI45czfl7qYU4GcrGVv0nFaEc,13624
8
- maitai/_maitai.py,sha256=AWnwbLviZd2SLXR6fR_UABenJsKg5Gh6fwfVba8HO0w,23588
9
- maitai/_maitai_async.py,sha256=8PZC3BFrNBg8gNjtufdDycybMzBGhUIXdVdQkAXhVO0,23728
10
- maitai/_maitai_client.py,sha256=NrICbHWhfx-u6pdXSUCjKRlPYmJO9nWb4hgnr3vf1y8,1981
11
- maitai/_types.py,sha256=JEF0kGlnAdT-GDF927FfpH85FTz2dmaFp1FJg04WOos,6273
6
+ maitai/_evaluator.py,sha256=x2XSKv6h90VcYBnqb1BRcPOrX7O3gQ4hShZCJzXfO9Y,10344
7
+ maitai/_inference.py,sha256=4cijo8J7LDLOZFxD9jPeF9KMUmPk8xG-NaT8cGYaITs,12597
8
+ maitai/_maitai.py,sha256=waXLGOFDMsrFnd2_UQLBP4b8S7dDSSnip_ZcDVRULZI,24429
9
+ maitai/_maitai_async.py,sha256=IxPSyztMmGdQ6GMkhrW6NaS_FqPWcswmcDZ3UQY3tGE,24527
10
+ maitai/_maitai_client.py,sha256=s3eZAu4HmJauZMVIxi5X5ZeW-ZChKDKK4h3LHJ3PHVs,7744
11
+ maitai/_types.py,sha256=uIYm1YQv6ZmGZ4GG6p6xrCjfVGq8VSxkehLgRqtr1Rw,6436
12
12
  maitai/_utils.py,sha256=3JN5MClGZNkcmn-hWgi8fNV2n-Ytlek37H3S6TEHzuk,11276
13
13
  maitai/tools/__init__.py,sha256=TxJ-g4A0eIzoIMD60ctIPVppCWcdcuZWms3hPGrqkSs,4043
14
14
  maitai_common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
- maitai_common/version.py,sha256=VPkIDQwPJjvm-Jr51LgdnqtVODDJ34WFe1Pwmxqo3rY,64
15
+ maitai_common/version.py,sha256=QSJ-4aASsA2wj3ikoXX7HbVXcGp--f-vKFG3Q61Ybqs,64
16
16
  maitai_common/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
17
  maitai_common/config/config_service.py,sha256=U8hU0F9juZtrZwIayOM_OBShxynUS8gu5K0F40KvcA0,940
18
18
  maitai_common/processes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -23,11 +23,11 @@ maitai_gen/model.py,sha256=o44eE5ZO9KRTPJETMA9aCGO5CL4PKd06Ih57Zy76wJA,910
23
23
  maitai_gen/application/__init__.py,sha256=PY7Q6Lxr7YfyhmFe_xnbGlz14tGoBEbpYA6EBEAI7M0,2430
24
24
  maitai_gen/backtest/__init__.py,sha256=_9B-q5F1YTPOgGLBTRZCdFnv54SizjfK0bFCaDi6UzM,467
25
25
  maitai_gen/billing/__init__.py,sha256=yP9k5pCuI8mehQDHqVrBDWldVsLZ7-LlwpRorESdsN4,2664
26
- maitai_gen/chat/__init__.py,sha256=ZHz3G8NLoKVyFkmsh-_wyCZ4eTJqSB6Pg6lw2jB693c,22225
26
+ maitai_gen/chat/__init__.py,sha256=DqsoSJE2wDMXVhTrKRip3j8hCAcde8uxJZOMsbkgYl0,22330
27
27
  maitai_gen/company/__init__.py,sha256=Jj03m8QlVsGLr0VQA-T5yxjbC1R3cx0gthUwgtbtGuc,739
28
- maitai_gen/config/__init__.py,sha256=vNW0hWIuYwDZNKwnPwSIYkwHmPIe5HA1IPfisQQ_Img,2008
28
+ maitai_gen/config/__init__.py,sha256=k9tdqH1uhV-cYkZn1FtP4rzMxmKJRGJzxaToWFbTY1g,2298
29
29
  maitai_gen/embedding/__init__.py,sha256=py5vAEdXFatL7daub1YSnruIRV-im0heWSa5hjaSljM,941
30
- maitai_gen/evaluation/__init__.py,sha256=CjB_Vnokmfawg-wte9YLB-e4OR8A6QI1B1ftZc7Pe_A,1777
30
+ maitai_gen/evaluation/__init__.py,sha256=HdrDNEPlV3lrvw14VyoeLnY_u8jfGDcocSv2XD9RyY4,2558
31
31
  maitai_gen/event/__init__.py,sha256=puOhfH-KQu_fL-yPJPjceDhwy3VbzP0oTtQs-RHeTE4,670
32
32
  maitai_gen/finetuning/__init__.py,sha256=e0kdoBdKjXXgufokcEr5WOjEFuqRE1JUCj3FJ0SroHA,3301
33
33
  maitai_gen/inference/__init__.py,sha256=KUWiTng5KeibART4NZ91JuN6fR4u7hmxcx8BjhCde78,741
@@ -38,7 +38,7 @@ maitai_gen/rates/__init__.py,sha256=Aho7HzMKRfjQz10tMJCoRVttq_cGlYh2DxxpSyTQAzU,
38
38
  maitai_gen/sandbox/__init__.py,sha256=IZ4hf76V1aZrYk5S-4p7z38e-op_s341utVG2domE_g,1549
39
39
  maitai_gen/sentinel/__init__.py,sha256=3yR28usTBIAC-M_uxEUFgqXo2PWylEKEPYmWX_dp7Cs,2513
40
40
  maitai_gen/session/__init__.py,sha256=kCJweCFagUqGkzktucaWLti9HSLaO5AML8Jewl89yM0,1242
41
- maitai_python-1.2.1.dist-info/METADATA,sha256=Dd_xqvZboo7rlydtTiYqgFi_8pDcoXYxQgGxPrbtWIk,1494
42
- maitai_python-1.2.1.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
43
- maitai_python-1.2.1.dist-info/top_level.txt,sha256=-5U1krxnwlqB-AY7nEe29ZcNvwByNc-SnBe-mph-QjI,32
44
- maitai_python-1.2.1.dist-info/RECORD,,
41
+ maitai_python-1.2.3.dist-info/METADATA,sha256=tsbN1vJ3VaftPiieaNxH9PwM8WGF8OyU9vmiM7nZAc8,1494
42
+ maitai_python-1.2.3.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
43
+ maitai_python-1.2.3.dist-info/top_level.txt,sha256=-5U1krxnwlqB-AY7nEe29ZcNvwByNc-SnBe-mph-QjI,32
44
+ maitai_python-1.2.3.dist-info/RECORD,,