maitai-python 1.2.2__py3-none-any.whl → 1.2.4__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/__init__.py CHANGED
@@ -1,9 +1,6 @@
1
- import os
2
-
3
- from maitai._azure import MaitaiAsyncAzureOpenAIClient, MaitaiAzureOpenAIClient
4
1
  from maitai._context import ContextManager
5
- from maitai._evaluator import Evaluator as Evaluator
6
- from maitai._inference import Inference as Inference
2
+ from maitai._evaluator import Evaluator as Evaluator # noqa
3
+ from maitai._inference import Inference as Inference # noqa
7
4
  from maitai._maitai import Chat, Maitai
8
5
  from maitai._maitai_async import MaitaiAsync
9
6
 
@@ -12,8 +9,7 @@ context = ContextManager()
12
9
  AsyncOpenAI = MaitaiAsync
13
10
  OpenAI = Maitai
14
11
 
15
- AsyncAzureOpenAI = MaitaiAsyncAzureOpenAIClient
16
- AzureOpenAI = MaitaiAzureOpenAIClient
12
+ AsyncMaitai = MaitaiAsync
17
13
 
18
14
 
19
15
  def initialize(api_key):
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
@@ -35,7 +35,12 @@ from maitai._utils import (
35
35
  required_args,
36
36
  )
37
37
  from maitai.tools import Tools
38
- from maitai_gen.chat import ChatCompletionParams, ClientParams, EvaluationContentType
38
+ from maitai_gen.chat import (
39
+ AzureParams,
40
+ ChatCompletionParams,
41
+ ClientParams,
42
+ EvaluationContentType,
43
+ )
39
44
  from maitai_gen.config import InferenceLocations
40
45
  from maitai_gen.inference import InferenceStreamResponse
41
46
  from maitai_gen.metric import RequestTimingMetric
@@ -53,6 +58,10 @@ class Maitai:
53
58
  groq_api_key: Optional[str] = None,
54
59
  anthropic_api_key: Optional[str] = None,
55
60
  cerebras_api_key: Optional[str] = None,
61
+ azure_api_key: Optional[str] = None,
62
+ azure_deployment: Optional[str] = None,
63
+ azure_api_version: Optional[str] = None,
64
+ azure_endpoint: Optional[str] = None,
56
65
  organization: Optional[str] = None,
57
66
  project: Optional[str] = None,
58
67
  base_url: Union[str, httpx.URL, None] = None,
@@ -66,20 +75,15 @@ class Maitai:
66
75
  if not maitai_api_key:
67
76
  maitai_api_key = os.environ.get("MAITAI_API_KEY")
68
77
  if maitai_api_key:
69
- config.initialize(maitai_api_key)
78
+ config.initialize(maitai_api_key, use_async=False)
70
79
  else:
71
80
  raise ValueError(
72
81
  "MAITAI_API_KEY has not been set. Either set via environment variable or pass it directly into the client."
73
82
  )
74
83
  if api_key:
75
- if not openai_api_key:
76
- openai_api_key = api_key
77
- if not groq_api_key:
78
- groq_api_key = api_key
79
- if not anthropic_api_key:
80
- anthropic_api_key = api_key
81
- if not cerebras_api_key:
82
- cerebras_api_key = api_key
84
+ raise ValueError(
85
+ "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"
86
+ )
83
87
  if openai_api_key:
84
88
  config.auth_keys.openai_api_key.key_value = openai_api_key
85
89
  if groq_api_key:
@@ -88,10 +92,34 @@ class Maitai:
88
92
  config.auth_keys.anthropic_api_key.key_value = anthropic_api_key
89
93
  if cerebras_api_key:
90
94
  config.auth_keys.cerebras_api_key.key_value = cerebras_api_key
95
+ if azure_api_key:
96
+ config.auth_keys.azure_api_key.key_value = azure_api_key
91
97
  self._client = None
92
- if api_key or openai_api_key or os.environ.get("OPENAI_API_KEY"):
98
+ azure_params = None
99
+ if azure_api_key:
100
+ azure_params = AzureParams(
101
+ endpoint=azure_endpoint,
102
+ deployment=azure_deployment,
103
+ api_version=azure_api_version,
104
+ )
105
+ self._client = openai.AzureOpenAI(
106
+ azure_endpoint=azure_endpoint,
107
+ azure_deployment=azure_deployment,
108
+ api_key=azure_api_key,
109
+ api_version=azure_api_version,
110
+ organization=organization,
111
+ project=project,
112
+ base_url=base_url,
113
+ timeout=timeout,
114
+ max_retries=max_retries,
115
+ default_headers=default_headers,
116
+ default_query=default_query,
117
+ http_client=http_client,
118
+ _strict_response_validation=_strict_response_validation,
119
+ )
120
+ elif openai_api_key or os.environ.get("OPENAI_API_KEY"):
93
121
  self._client = openai.OpenAI(
94
- api_key=api_key or openai_api_key or os.environ.get("OPENAI_API_KEY"),
122
+ api_key=openai_api_key or os.environ.get("OPENAI_API_KEY"),
95
123
  organization=organization,
96
124
  project=project,
97
125
  base_url=base_url,
@@ -108,6 +136,7 @@ class Maitai:
108
136
  base_url=base_url or "",
109
137
  default_headers=default_headers or {},
110
138
  default_query=default_query or {},
139
+ azure_params=azure_params,
111
140
  )
112
141
  self.chat = Chat(self._client, client_params)
113
142
 
@@ -576,8 +605,8 @@ def _process_inference_stream(
576
605
  ):
577
606
  return
578
607
  except MaitaiConnectionError as e:
579
- if "gpt" not in retry_args.get("model", "") and "gpt" in retry_args.get(
580
- "fallback_model", ""
608
+ if "gpt" not in retry_args.get("model", "") and "gpt" in (
609
+ retry_args.get("fallback_model", "") or ""
581
610
  ):
582
611
  retry_args["model"] = retry_args["fallback_model"]
583
612
  if "gpt" in retry_args.get("model", ""):
maitai/_maitai_async.py CHANGED
@@ -35,7 +35,12 @@ from maitai._utils import (
35
35
  required_args,
36
36
  )
37
37
  from maitai.tools import Tools
38
- from maitai_gen.chat import ChatCompletionParams, ClientParams, EvaluationContentType
38
+ from maitai_gen.chat import (
39
+ AzureParams,
40
+ ChatCompletionParams,
41
+ ClientParams,
42
+ EvaluationContentType,
43
+ )
39
44
  from maitai_gen.config import InferenceLocations
40
45
  from maitai_gen.inference import InferenceStreamResponse
41
46
  from maitai_gen.metric import RequestTimingMetric
@@ -53,6 +58,10 @@ class MaitaiAsync:
53
58
  groq_api_key: Optional[str] = None,
54
59
  anthropic_api_key: Optional[str] = None,
55
60
  cerebras_api_key: Optional[str] = None,
61
+ azure_api_key: Optional[str] = None,
62
+ azure_deployment: Optional[str] = None,
63
+ azure_api_version: Optional[str] = None,
64
+ azure_endpoint: Optional[str] = None,
56
65
  organization: Optional[str] = None,
57
66
  project: Optional[str] = None,
58
67
  base_url: Union[str, httpx.URL, None] = None,
@@ -66,21 +75,15 @@ class MaitaiAsync:
66
75
  if not maitai_api_key:
67
76
  maitai_api_key = os.environ.get("MAITAI_API_KEY")
68
77
  if maitai_api_key:
69
- config.initialize(maitai_api_key)
78
+ config.initialize(maitai_api_key, use_async=True)
70
79
  else:
71
80
  raise ValueError(
72
81
  "MAITAI_API_KEY has not been set. Either set via environment variable or pass it directly into the client."
73
82
  )
74
-
75
83
  if api_key:
76
- if not openai_api_key:
77
- openai_api_key = api_key
78
- if not groq_api_key:
79
- groq_api_key = api_key
80
- if not anthropic_api_key:
81
- anthropic_api_key = api_key
82
- if not cerebras_api_key:
83
- cerebras_api_key = api_key
84
+ raise ValueError(
85
+ "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"
86
+ )
84
87
  if openai_api_key:
85
88
  config.auth_keys.openai_api_key.key_value = openai_api_key
86
89
  if groq_api_key:
@@ -89,10 +92,33 @@ class MaitaiAsync:
89
92
  config.auth_keys.anthropic_api_key.key_value = anthropic_api_key
90
93
  if cerebras_api_key:
91
94
  config.auth_keys.cerebras_api_key.key_value = cerebras_api_key
95
+ if azure_api_key:
96
+ config.auth_keys.azure_api_key.key_value = azure_api_key
92
97
  self._client = None
93
- if api_key or openai_api_key or os.environ.get("OPENAI_API_KEY"):
98
+ if azure_api_key:
99
+ azure_params = AzureParams(
100
+ endpoint=azure_endpoint,
101
+ deployment=azure_deployment,
102
+ api_version=azure_api_version,
103
+ )
104
+ self._client = openai.AsyncAzureOpenAI(
105
+ azure_endpoint=azure_endpoint,
106
+ azure_deployment=azure_deployment,
107
+ api_key=azure_api_key,
108
+ api_version=azure_api_version,
109
+ organization=organization,
110
+ project=project,
111
+ base_url=base_url,
112
+ timeout=timeout,
113
+ max_retries=max_retries,
114
+ default_headers=default_headers,
115
+ default_query=default_query,
116
+ http_client=http_client,
117
+ _strict_response_validation=_strict_response_validation,
118
+ )
119
+ elif openai_api_key or os.environ.get("OPENAI_API_KEY"):
94
120
  self._client = openai.AsyncClient(
95
- api_key=api_key or openai_api_key or os.environ.get("OPENAI_API_KEY"),
121
+ api_key=openai_api_key or os.environ.get("OPENAI_API_KEY"),
96
122
  organization=organization,
97
123
  project=project,
98
124
  base_url=base_url,
@@ -110,6 +136,7 @@ class MaitaiAsync:
110
136
  base_url=base_url or "",
111
137
  default_headers=default_headers or {},
112
138
  default_query=default_query or {},
139
+ azure_params=azure_params,
113
140
  )
114
141
  self.chat = AsyncChat(self._client, client_params)
115
142
 
@@ -577,8 +604,8 @@ async def _process_inference_stream_async(
577
604
  ):
578
605
  return
579
606
  except MaitaiConnectionError as e:
580
- if "gpt" not in retry_args.get("model", "") and "gpt" in retry_args.get(
581
- "fallback_model", ""
607
+ if "gpt" not in retry_args.get("model", "") and "gpt" in (
608
+ retry_args.get("fallback_model", "") or ""
582
609
  ):
583
610
  retry_args["model"] = retry_args["fallback_model"]
584
611
  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_common/version.py CHANGED
@@ -1,3 +1,3 @@
1
- version = "1.2.2"
1
+ version = "1.2.4"
2
2
  if __name__ == "__main__":
3
3
  print(version)
@@ -77,6 +77,13 @@ class ChatCompletionRequest(betterproto.Message):
77
77
  fallback_config: "_config__.FallbackConfig" = betterproto.message_field(27)
78
78
 
79
79
 
80
+ @dataclass(eq=False, repr=False)
81
+ class AzureParams(betterproto.Message):
82
+ endpoint: str = betterproto.string_field(1)
83
+ deployment: str = betterproto.string_field(2)
84
+ api_version: str = betterproto.string_field(3)
85
+
86
+
80
87
  @dataclass(eq=False, repr=False)
81
88
  class ClientParams(betterproto.Message):
82
89
  base_url: str = betterproto.string_field(1)
@@ -86,6 +93,7 @@ class ClientParams(betterproto.Message):
86
93
  default_query: Dict[str, str] = betterproto.map_field(
87
94
  3, betterproto.TYPE_STRING, betterproto.TYPE_STRING
88
95
  )
96
+ azure_params: "AzureParams" = betterproto.message_field(4)
89
97
 
90
98
 
91
99
  @dataclass(eq=False, repr=False)
@@ -95,6 +103,7 @@ class ChatCompletionAuth(betterproto.Message):
95
103
  override_api_key: str = betterproto.string_field(3)
96
104
  anthropic_api_key: str = betterproto.string_field(4)
97
105
  cerebras_api_key: str = betterproto.string_field(5)
106
+ azure_api_key: str = betterproto.string_field(6)
98
107
 
99
108
 
100
109
  @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
+ )
@@ -28,6 +28,7 @@ class KeyIdMap(betterproto.Message):
28
28
  groq_api_key: int = betterproto.int64_field(2)
29
29
  anthropic_api_key: int = betterproto.int64_field(3)
30
30
  cerebras_api_key: int = betterproto.int64_field(4)
31
+ azure_api_key: int = betterproto.int64_field(5)
31
32
 
32
33
 
33
34
  @dataclass(eq=False, repr=False)
@@ -36,3 +37,4 @@ class KeyMap(betterproto.Message):
36
37
  groq_api_key: "Key" = betterproto.message_field(2)
37
38
  anthropic_api_key: "Key" = betterproto.message_field(3)
38
39
  cerebras_api_key: "Key" = betterproto.message_field(4)
40
+ azure_api_key: "Key" = betterproto.message_field(5)
maitai_gen/model.py CHANGED
@@ -1,7 +1,7 @@
1
1
  # This is an automatically generated file, please do not change
2
- # gen by protobuf_to_pydantic[v0.3.0.3](https://github.com/so1n/protobuf_to_pydantic)
3
- # Protobuf Version: 5.29.2
4
- # Pydantic Version: 2.10.4
2
+ # gen by protobuf_to_pydantic[v0.3.0](https://github.com/so1n/protobuf_to_pydantic)
3
+ # Protobuf Version: 5.27.0
4
+ # Pydantic Version: 2.8.2
5
5
  import typing
6
6
 
7
7
  from google.protobuf.message import Message # type: ignore
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: maitai-python
3
- Version: 1.2.2
3
+ Version: 1.2.4
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -1,44 +1,43 @@
1
- maitai/__init__.py,sha256=HjnRas9JQpcCPOh9m1ABfexl6BV69tRcJzArdQpCWkQ,593
2
- maitai/_azure.py,sha256=ZQXVzmU2QPJ41wQUxqFkyeAKAJ6HrMoQKDbi3lyUJVc,8513
3
- maitai/_config.py,sha256=n1RV9Udg5_EGNLCvVm8WR_RAmNeI2LCXkIWDXme727I,10104
1
+ maitai/__init__.py,sha256=1nR3g4MXSM5Xj-HKcDa2pdhQJMqIv-7HzNL8R5J4fEU,458
2
+ maitai/_config.py,sha256=IkpwORKXpO2rDRJ6JHmuGWb29g9IR9Cc2Tl3VrDuMH8,7603
4
3
  maitai/_config_listener_thread.py,sha256=VaftjUXrP8oe6yg0TXUlIZW2vGw7bTk8p_95o4dSVgo,902
5
4
  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=KEMxf0nIPsV8ZEkZfNoNZ6Ae2CPT5iH10-9syXuwdOw,24404
9
- maitai/_maitai_async.py,sha256=YfCo7G5trBNpEmLztDWs6Uk34O1b2nJsA4IkShuuazI,24504
10
- maitai/_maitai_client.py,sha256=NrICbHWhfx-u6pdXSUCjKRlPYmJO9nWb4hgnr3vf1y8,1981
5
+ maitai/_evaluator.py,sha256=x2XSKv6h90VcYBnqb1BRcPOrX7O3gQ4hShZCJzXfO9Y,10344
6
+ maitai/_inference.py,sha256=4cijo8J7LDLOZFxD9jPeF9KMUmPk8xG-NaT8cGYaITs,12597
7
+ maitai/_maitai.py,sha256=5aF0SGbpt3O7Lu-9zHCWdPq133SlyW-uwJ9c6gMlco4,25561
8
+ maitai/_maitai_async.py,sha256=1Wh5KDOYesC-7xAw58iITAI5RRA4DvmCES1lRpboXzI,25636
9
+ maitai/_maitai_client.py,sha256=s3eZAu4HmJauZMVIxi5X5ZeW-ZChKDKK4h3LHJ3PHVs,7744
11
10
  maitai/_types.py,sha256=uIYm1YQv6ZmGZ4GG6p6xrCjfVGq8VSxkehLgRqtr1Rw,6436
12
11
  maitai/_utils.py,sha256=3JN5MClGZNkcmn-hWgi8fNV2n-Ytlek37H3S6TEHzuk,11276
13
12
  maitai/tools/__init__.py,sha256=TxJ-g4A0eIzoIMD60ctIPVppCWcdcuZWms3hPGrqkSs,4043
14
13
  maitai_common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
- maitai_common/version.py,sha256=j2u0CvKX_frZofU-GGJNf9eBuHdU1JppJyw42qkAmUk,64
14
+ maitai_common/version.py,sha256=zwTylIRzKGP6obXkwBrpBIu_zH55DgBVS8mTvJYuyfo,64
16
15
  maitai_common/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
16
  maitai_common/config/config_service.py,sha256=U8hU0F9juZtrZwIayOM_OBShxynUS8gu5K0F40KvcA0,940
18
17
  maitai_common/processes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
18
  maitai_common/processes/io_thread.py,sha256=Pqw-3Pz6rlJvK_6P5ytgGoXP7pymYQzuDhTGaeOSLW8,1995
20
19
  maitai_common/processes/websocket_listener_thread.py,sha256=CaFtcHby8iEnjQNawGkvcKhr7S_pqvavW8gXw0YUjnM,3482
21
20
  maitai_gen/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
- maitai_gen/model.py,sha256=EQoBLRHJ6TahP5vsHZCTFPUnzSHFlww_PkN0I7lEAh8,913
21
+ maitai_gen/model.py,sha256=o44eE5ZO9KRTPJETMA9aCGO5CL4PKd06Ih57Zy76wJA,910
23
22
  maitai_gen/application/__init__.py,sha256=PY7Q6Lxr7YfyhmFe_xnbGlz14tGoBEbpYA6EBEAI7M0,2430
24
23
  maitai_gen/backtest/__init__.py,sha256=_9B-q5F1YTPOgGLBTRZCdFnv54SizjfK0bFCaDi6UzM,467
25
24
  maitai_gen/billing/__init__.py,sha256=yP9k5pCuI8mehQDHqVrBDWldVsLZ7-LlwpRorESdsN4,2664
26
- maitai_gen/chat/__init__.py,sha256=DqsoSJE2wDMXVhTrKRip3j8hCAcde8uxJZOMsbkgYl0,22330
25
+ maitai_gen/chat/__init__.py,sha256=4Vr5O9gLYvCY9LSjZ_TH-WUjgnALVaj5v-b3nCMyEQA,22670
27
26
  maitai_gen/company/__init__.py,sha256=Jj03m8QlVsGLr0VQA-T5yxjbC1R3cx0gthUwgtbtGuc,739
28
27
  maitai_gen/config/__init__.py,sha256=k9tdqH1uhV-cYkZn1FtP4rzMxmKJRGJzxaToWFbTY1g,2298
29
28
  maitai_gen/embedding/__init__.py,sha256=py5vAEdXFatL7daub1YSnruIRV-im0heWSa5hjaSljM,941
30
- maitai_gen/evaluation/__init__.py,sha256=CjB_Vnokmfawg-wte9YLB-e4OR8A6QI1B1ftZc7Pe_A,1777
29
+ maitai_gen/evaluation/__init__.py,sha256=HdrDNEPlV3lrvw14VyoeLnY_u8jfGDcocSv2XD9RyY4,2558
31
30
  maitai_gen/event/__init__.py,sha256=puOhfH-KQu_fL-yPJPjceDhwy3VbzP0oTtQs-RHeTE4,670
32
31
  maitai_gen/finetuning/__init__.py,sha256=e0kdoBdKjXXgufokcEr5WOjEFuqRE1JUCj3FJ0SroHA,3301
33
32
  maitai_gen/inference/__init__.py,sha256=KUWiTng5KeibART4NZ91JuN6fR4u7hmxcx8BjhCde78,741
34
- maitai_gen/key/__init__.py,sha256=lDgA5vvqO0J_XmE8IxAWk640t0karVmi_6ThiMowttc,1338
33
+ maitai_gen/key/__init__.py,sha256=6B924RX6F50vOEUVMuw8Ca1leVraneWquAYppZ9d_eI,1446
35
34
  maitai_gen/metric/__init__.py,sha256=RX1sF74PB2L2lTD7EYfim5BSRmvGVd63L__IgJhZDh0,615
36
35
  maitai_gen/notification/__init__.py,sha256=l4M2OlHvKhnU3ygytk0-voSypDAhjzNch6C7XXVnn6s,1301
37
36
  maitai_gen/rates/__init__.py,sha256=Aho7HzMKRfjQz10tMJCoRVttq_cGlYh2DxxpSyTQAzU,1382
38
37
  maitai_gen/sandbox/__init__.py,sha256=IZ4hf76V1aZrYk5S-4p7z38e-op_s341utVG2domE_g,1549
39
38
  maitai_gen/sentinel/__init__.py,sha256=3yR28usTBIAC-M_uxEUFgqXo2PWylEKEPYmWX_dp7Cs,2513
40
39
  maitai_gen/session/__init__.py,sha256=kCJweCFagUqGkzktucaWLti9HSLaO5AML8Jewl89yM0,1242
41
- maitai_python-1.2.2.dist-info/METADATA,sha256=Nq7FNaAtVVP7C6O8tZDuyDIiYhfhF2Yarrh0NNrJykI,1494
42
- maitai_python-1.2.2.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
43
- maitai_python-1.2.2.dist-info/top_level.txt,sha256=-5U1krxnwlqB-AY7nEe29ZcNvwByNc-SnBe-mph-QjI,32
44
- maitai_python-1.2.2.dist-info/RECORD,,
40
+ maitai_python-1.2.4.dist-info/METADATA,sha256=2Nb36FnHnla5DvNkCLTqrgXXTByso_68lGlamkaPhdg,1494
41
+ maitai_python-1.2.4.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
42
+ maitai_python-1.2.4.dist-info/top_level.txt,sha256=-5U1krxnwlqB-AY7nEe29ZcNvwByNc-SnBe-mph-QjI,32
43
+ maitai_python-1.2.4.dist-info/RECORD,,
maitai/_azure.py DELETED
@@ -1,217 +0,0 @@
1
- from typing import Mapping, Optional, overload, Union
2
-
3
- import httpx
4
- import openai
5
- from openai.lib.azure import AsyncAzureADTokenProvider, AzureADTokenProvider
6
-
7
- from maitai._config import config
8
- from maitai._maitai import Chat
9
- from maitai._maitai_async import AsyncChat
10
-
11
- DEFAULT_MAX_RETRIES = 2
12
-
13
-
14
- class MaitaiAsyncAzureOpenAIClient:
15
- @overload
16
- def __init__(
17
- self,
18
- *,
19
- azure_endpoint: str,
20
- maitai_api_key: Optional[str] = None,
21
- azure_deployment: Optional[str] = None,
22
- api_version: Optional[str] = None,
23
- api_key: Optional[str] = None,
24
- azure_ad_token: Optional[str] = None,
25
- azure_ad_token_provider: Optional[AsyncAzureADTokenProvider] = None,
26
- organization: Optional[str] = None,
27
- project: Optional[str] = None,
28
- timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NotGiven,
29
- max_retries: int = DEFAULT_MAX_RETRIES,
30
- default_headers: Optional[Mapping[str, str]] = None,
31
- default_query: Optional[Mapping[str, object]] = None,
32
- http_client: Optional[httpx.AsyncClient] = None,
33
- _strict_response_validation: bool = False,
34
- ) -> None: ...
35
-
36
- @overload
37
- def __init__(
38
- self,
39
- *,
40
- maitai_api_key: Optional[str] = None,
41
- azure_deployment: Optional[str] = None,
42
- api_version: Optional[str] = None,
43
- api_key: Optional[str] = None,
44
- azure_ad_token: Optional[str] = None,
45
- azure_ad_token_provider: Optional[AsyncAzureADTokenProvider] = None,
46
- organization: Optional[str] = None,
47
- project: Optional[str] = None,
48
- timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NotGiven,
49
- max_retries: int = DEFAULT_MAX_RETRIES,
50
- default_headers: Optional[Mapping[str, str]] = None,
51
- default_query: Optional[Mapping[str, object]] = None,
52
- http_client: Optional[httpx.AsyncClient] = None,
53
- _strict_response_validation: bool = False,
54
- ) -> None: ...
55
-
56
- @overload
57
- def __init__(
58
- self,
59
- *,
60
- base_url: str,
61
- maitai_api_key: Optional[str] = None,
62
- api_version: Optional[str] = None,
63
- api_key: Optional[str] = None,
64
- azure_ad_token: Optional[str] = None,
65
- azure_ad_token_provider: Optional[AsyncAzureADTokenProvider] = None,
66
- organization: Optional[str] = None,
67
- project: Optional[str] = None,
68
- timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NotGiven,
69
- max_retries: int = DEFAULT_MAX_RETRIES,
70
- default_headers: Optional[Mapping[str, str]] = None,
71
- default_query: Optional[Mapping[str, object]] = None,
72
- http_client: Optional[httpx.AsyncClient] = None,
73
- _strict_response_validation: bool = False,
74
- ) -> None: ...
75
-
76
- def __init__(
77
- self,
78
- *,
79
- maitai_api_key: Optional[str] = None,
80
- azure_endpoint: Optional[str] = None,
81
- azure_deployment: Optional[str] = None,
82
- api_version: Optional[str] = None,
83
- api_key: Optional[str] = None,
84
- azure_ad_token: Optional[str] = None,
85
- azure_ad_token_provider: Optional[AsyncAzureADTokenProvider] = None,
86
- organization: Optional[str] = None,
87
- project: Optional[str] = None,
88
- base_url: Optional[str] = None,
89
- timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NotGiven,
90
- max_retries: int = DEFAULT_MAX_RETRIES,
91
- default_headers: Optional[Mapping[str, str]] = None,
92
- default_query: Optional[Mapping[str, object]] = None,
93
- http_client: Optional[httpx.AsyncClient] = None,
94
- _strict_response_validation: bool = False,
95
- ):
96
- if maitai_api_key:
97
- config.initialize(maitai_api_key)
98
- self.client = openai.AsyncAzureOpenAI(
99
- azure_endpoint=azure_endpoint,
100
- azure_deployment=azure_deployment,
101
- api_version=api_version,
102
- api_key=api_key,
103
- azure_ad_token=azure_ad_token,
104
- azure_ad_token_provider=azure_ad_token_provider,
105
- organization=organization,
106
- project=project,
107
- base_url=base_url,
108
- timeout=timeout,
109
- max_retries=max_retries,
110
- default_headers=default_headers,
111
- default_query=default_query,
112
- http_client=http_client,
113
- _strict_response_validation=_strict_response_validation,
114
- )
115
-
116
- self.chat = AsyncChat(self.client)
117
-
118
-
119
- class MaitaiAzureOpenAIClient:
120
- @overload
121
- def __init__(
122
- self,
123
- *,
124
- maitai_api_key: Optional[str] = None,
125
- azure_endpoint: str,
126
- azure_deployment: Optional[str] = None,
127
- api_version: Optional[str] = None,
128
- api_key: Optional[str] = None,
129
- azure_ad_token: Optional[str] = None,
130
- azure_ad_token_provider: Optional[AzureADTokenProvider] = None,
131
- organization: Optional[str] = None,
132
- timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NotGiven,
133
- max_retries: int = DEFAULT_MAX_RETRIES,
134
- default_headers: Optional[Mapping[str, str]] = None,
135
- default_query: Optional[Mapping[str, object]] = None,
136
- http_client: Optional[httpx.Client] = None,
137
- _strict_response_validation: bool = False,
138
- ) -> None: ...
139
-
140
- @overload
141
- def __init__(
142
- self,
143
- *,
144
- maitai_api_key: Optional[str] = None,
145
- azure_deployment: Optional[str] = None,
146
- api_version: Optional[str] = None,
147
- api_key: Optional[str] = None,
148
- azure_ad_token: Optional[str] = None,
149
- azure_ad_token_provider: Optional[AzureADTokenProvider] = None,
150
- organization: Optional[str] = None,
151
- timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NotGiven,
152
- max_retries: int = DEFAULT_MAX_RETRIES,
153
- default_headers: Optional[Mapping[str, str]] = None,
154
- default_query: Optional[Mapping[str, object]] = None,
155
- http_client: Optional[httpx.Client] = None,
156
- _strict_response_validation: bool = False,
157
- ) -> None: ...
158
-
159
- @overload
160
- def __init__(
161
- self,
162
- *,
163
- base_url: str,
164
- maitai_api_key: Optional[str] = None,
165
- api_version: Optional[str] = None,
166
- api_key: Optional[str] = None,
167
- azure_ad_token: Optional[str] = None,
168
- azure_ad_token_provider: Optional[AzureADTokenProvider] = None,
169
- organization: Optional[str] = None,
170
- timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NotGiven,
171
- max_retries: int = DEFAULT_MAX_RETRIES,
172
- default_headers: Optional[Mapping[str, str]] = None,
173
- default_query: Optional[Mapping[str, object]] = None,
174
- http_client: Optional[httpx.Client] = None,
175
- _strict_response_validation: bool = False,
176
- ) -> None: ...
177
-
178
- def __init__(
179
- self,
180
- *,
181
- maitai_api_key: Optional[str] = None,
182
- api_version: Optional[str] = None,
183
- azure_endpoint: Optional[str] = None,
184
- azure_deployment: Optional[str] = None,
185
- api_key: Optional[str] = None,
186
- azure_ad_token: Optional[str] = None,
187
- azure_ad_token_provider: Optional[AzureADTokenProvider] = None,
188
- organization: Optional[str] = None,
189
- project: Optional[str] = None,
190
- base_url: Optional[str] = None,
191
- timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NotGiven,
192
- max_retries: int = DEFAULT_MAX_RETRIES,
193
- default_headers: Optional[Mapping[str, str]] = None,
194
- default_query: Optional[Mapping[str, object]] = None,
195
- http_client: Optional[httpx.Client] = None,
196
- _strict_response_validation: bool = False,
197
- ) -> None:
198
- if maitai_api_key:
199
- config.initialize(maitai_api_key)
200
- self.client = openai.AzureOpenAI(
201
- azure_endpoint=azure_endpoint,
202
- azure_deployment=azure_deployment,
203
- api_version=api_version,
204
- api_key=api_key,
205
- azure_ad_token=azure_ad_token,
206
- azure_ad_token_provider=azure_ad_token_provider,
207
- organization=organization,
208
- project=project,
209
- base_url=base_url,
210
- timeout=timeout,
211
- max_retries=max_retries,
212
- default_headers=default_headers,
213
- default_query=default_query,
214
- http_client=http_client,
215
- _strict_response_validation=_strict_response_validation,
216
- )
217
- self.chat = Chat(self.client)