maitai-python 1.2.1__tar.gz → 1.2.3__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.
- {maitai_python-1.2.1 → maitai_python-1.2.3}/PKG-INFO +1 -1
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai/_config.py +24 -103
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai/_evaluator.py +3 -4
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai/_inference.py +12 -55
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai/_maitai.py +25 -5
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai/_maitai_async.py +24 -6
- maitai_python-1.2.3/maitai/_maitai_client.py +232 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai/_types.py +7 -1
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_common/version.py +1 -1
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/chat/__init__.py +2 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/config/__init__.py +8 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/evaluation/__init__.py +19 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_python.egg-info/PKG-INFO +1 -1
- maitai_python-1.2.1/maitai/_maitai_client.py +0 -64
- {maitai_python-1.2.1 → maitai_python-1.2.3}/README.md +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai/_azure.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai/_config_listener_thread.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai/_context.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai/_utils.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai/tools/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_common/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_common/config/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_common/config/config_service.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_common/processes/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_common/processes/io_thread.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_common/processes/websocket_listener_thread.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/application/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/backtest/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/billing/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/company/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/embedding/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/event/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/finetuning/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/inference/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/key/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/metric/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/model.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/notification/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/rates/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/sandbox/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/sentinel/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_gen/session/__init__.py +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_python.egg-info/SOURCES.txt +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_python.egg-info/dependency_links.txt +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_python.egg-info/requires.txt +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_python.egg-info/top_level.txt +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/setup.cfg +0 -0
- {maitai_python-1.2.1 → maitai_python-1.2.3}/setup.py +0 -0
|
@@ -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.
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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()
|
|
@@ -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
|
|
274
|
-
|
|
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
|
|
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", ""):
|
|
@@ -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
|
|
275
|
-
|
|
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
|
|
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", ""):
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import atexit
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import threading
|
|
6
|
+
|
|
7
|
+
import aiohttp
|
|
8
|
+
import requests
|
|
9
|
+
from requests.adapters import HTTPAdapter
|
|
10
|
+
from urllib3.util.retry import Retry
|
|
11
|
+
|
|
12
|
+
from maitai_common.version import version
|
|
13
|
+
|
|
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
|
+
|
|
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
|
+
)
|
|
92
|
+
|
|
93
|
+
def __init__(self):
|
|
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())
|
|
137
|
+
|
|
138
|
+
@classmethod
|
|
139
|
+
def run_async(cls, coro):
|
|
140
|
+
"""
|
|
141
|
+
Modified helper method to run coroutine in a background thread if not already in an asyncio loop,
|
|
142
|
+
otherwise just run it. This allows for both asyncio and non-asyncio applications to use this method.
|
|
143
|
+
"""
|
|
144
|
+
try:
|
|
145
|
+
loop = asyncio.get_running_loop()
|
|
146
|
+
except RuntimeError: # No running event loop
|
|
147
|
+
loop = None
|
|
148
|
+
|
|
149
|
+
if loop and loop.is_running():
|
|
150
|
+
# We are in an asyncio loop, schedule coroutine execution
|
|
151
|
+
asyncio.create_task(coro, name="maitai")
|
|
152
|
+
else:
|
|
153
|
+
# Not in an asyncio loop, run in a new event loop in a background thread
|
|
154
|
+
def run():
|
|
155
|
+
new_loop = asyncio.new_event_loop()
|
|
156
|
+
asyncio.set_event_loop(new_loop)
|
|
157
|
+
new_loop.run_until_complete(coro)
|
|
158
|
+
new_loop.close()
|
|
159
|
+
|
|
160
|
+
threading.Thread(target=run).start()
|
|
161
|
+
|
|
162
|
+
@classmethod
|
|
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()
|
|
168
|
+
|
|
169
|
+
@classmethod
|
|
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
|
|
176
|
+
url = f"{host}/metrics/increment/python_sdk_error"
|
|
177
|
+
headers = {
|
|
178
|
+
"Content-Type": "application/json",
|
|
179
|
+
"x-api-key": api_key,
|
|
180
|
+
"x-client-version": version,
|
|
181
|
+
}
|
|
182
|
+
labels = {
|
|
183
|
+
"cause": error,
|
|
184
|
+
"type": "ERROR",
|
|
185
|
+
"path": path,
|
|
186
|
+
}
|
|
187
|
+
try:
|
|
188
|
+
async with aiohttp.ClientSession(
|
|
189
|
+
connector=aiohttp.TCPConnector(ssl=False)
|
|
190
|
+
) as session:
|
|
191
|
+
return await session.put(url, headers=headers, data=json.dumps(labels))
|
|
192
|
+
except:
|
|
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()
|
|
@@ -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]
|
|
@@ -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,64 +0,0 @@
|
|
|
1
|
-
import asyncio
|
|
2
|
-
import json
|
|
3
|
-
import threading
|
|
4
|
-
|
|
5
|
-
import aiohttp
|
|
6
|
-
|
|
7
|
-
from maitai._config import config
|
|
8
|
-
from maitai_common.version import version
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class MaitaiClient:
|
|
12
|
-
|
|
13
|
-
def __init__(self):
|
|
14
|
-
super().__init__()
|
|
15
|
-
|
|
16
|
-
@classmethod
|
|
17
|
-
def run_async(cls, coro):
|
|
18
|
-
"""
|
|
19
|
-
Modified helper method to run coroutine in a background thread if not already in an asyncio loop,
|
|
20
|
-
otherwise just run it. This allows for both asyncio and non-asyncio applications to use this method.
|
|
21
|
-
"""
|
|
22
|
-
try:
|
|
23
|
-
loop = asyncio.get_running_loop()
|
|
24
|
-
except RuntimeError: # No running event loop
|
|
25
|
-
loop = None
|
|
26
|
-
|
|
27
|
-
if loop and loop.is_running():
|
|
28
|
-
# We are in an asyncio loop, schedule coroutine execution
|
|
29
|
-
asyncio.create_task(coro, name="maitai")
|
|
30
|
-
else:
|
|
31
|
-
# Not in an asyncio loop, run in a new event loop in a background thread
|
|
32
|
-
def run():
|
|
33
|
-
new_loop = asyncio.new_event_loop()
|
|
34
|
-
asyncio.set_event_loop(new_loop)
|
|
35
|
-
new_loop.run_until_complete(coro)
|
|
36
|
-
new_loop.close()
|
|
37
|
-
|
|
38
|
-
threading.Thread(target=run).start()
|
|
39
|
-
|
|
40
|
-
@classmethod
|
|
41
|
-
def log_error(cls, error: str, path: str):
|
|
42
|
-
cls.run_async(cls.increment_error(error, path))
|
|
43
|
-
|
|
44
|
-
@classmethod
|
|
45
|
-
async def increment_error(cls, error: str, path: str):
|
|
46
|
-
host = config.maitai_host
|
|
47
|
-
url = f"{host}/metrics/increment/python_sdk_error"
|
|
48
|
-
headers = {
|
|
49
|
-
"Content-Type": "application/json",
|
|
50
|
-
"x-api-key": config.api_key,
|
|
51
|
-
"x-client-version": version,
|
|
52
|
-
}
|
|
53
|
-
labels = {
|
|
54
|
-
"cause": error,
|
|
55
|
-
"type": "ERROR",
|
|
56
|
-
"path": path,
|
|
57
|
-
}
|
|
58
|
-
try:
|
|
59
|
-
async with aiohttp.ClientSession(
|
|
60
|
-
connector=aiohttp.TCPConnector(ssl=False)
|
|
61
|
-
) as session:
|
|
62
|
-
return await session.put(url, headers=headers, data=json.dumps(labels))
|
|
63
|
-
except:
|
|
64
|
-
pass
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{maitai_python-1.2.1 → maitai_python-1.2.3}/maitai_common/processes/websocket_listener_thread.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|