maitai-python 1.2.2__tar.gz → 1.2.4__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 (50) hide show
  1. {maitai_python-1.2.2 → maitai_python-1.2.4}/PKG-INFO +1 -1
  2. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai/__init__.py +3 -7
  3. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai/_config.py +24 -103
  4. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai/_evaluator.py +3 -4
  5. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai/_inference.py +12 -55
  6. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai/_maitai.py +43 -14
  7. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai/_maitai_async.py +42 -15
  8. maitai_python-1.2.4/maitai/_maitai_client.py +232 -0
  9. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_common/version.py +1 -1
  10. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/chat/__init__.py +9 -0
  11. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/evaluation/__init__.py +19 -0
  12. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/key/__init__.py +2 -0
  13. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/model.py +3 -3
  14. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_python.egg-info/PKG-INFO +1 -1
  15. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_python.egg-info/SOURCES.txt +0 -1
  16. maitai_python-1.2.2/maitai/_azure.py +0 -217
  17. maitai_python-1.2.2/maitai/_maitai_client.py +0 -64
  18. {maitai_python-1.2.2 → maitai_python-1.2.4}/README.md +0 -0
  19. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai/_config_listener_thread.py +0 -0
  20. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai/_context.py +0 -0
  21. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai/_types.py +0 -0
  22. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai/_utils.py +0 -0
  23. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai/tools/__init__.py +0 -0
  24. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_common/__init__.py +0 -0
  25. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_common/config/__init__.py +0 -0
  26. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_common/config/config_service.py +0 -0
  27. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_common/processes/__init__.py +0 -0
  28. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_common/processes/io_thread.py +0 -0
  29. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_common/processes/websocket_listener_thread.py +0 -0
  30. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/__init__.py +0 -0
  31. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/application/__init__.py +0 -0
  32. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/backtest/__init__.py +0 -0
  33. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/billing/__init__.py +0 -0
  34. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/company/__init__.py +0 -0
  35. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/config/__init__.py +0 -0
  36. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/embedding/__init__.py +0 -0
  37. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/event/__init__.py +0 -0
  38. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/finetuning/__init__.py +0 -0
  39. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/inference/__init__.py +0 -0
  40. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/metric/__init__.py +0 -0
  41. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/notification/__init__.py +0 -0
  42. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/rates/__init__.py +0 -0
  43. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/sandbox/__init__.py +0 -0
  44. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/sentinel/__init__.py +0 -0
  45. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_gen/session/__init__.py +0 -0
  46. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_python.egg-info/dependency_links.txt +0 -0
  47. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_python.egg-info/requires.txt +0 -0
  48. {maitai_python-1.2.2 → maitai_python-1.2.4}/maitai_python.egg-info/top_level.txt +0 -0
  49. {maitai_python-1.2.2 → maitai_python-1.2.4}/setup.cfg +0 -0
  50. {maitai_python-1.2.2 → maitai_python-1.2.4}/setup.py +0 -0
@@ -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,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):
@@ -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
@@ -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():
@@ -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()
@@ -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", ""):
@@ -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", ""):