maitai-python 1.0.0b0__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 +17 -0
- maitai/_config.py +69 -0
- maitai/_config_listener_thread.py +14 -0
- maitai/_evaluator.py +263 -0
- maitai/_inference.py +101 -0
- maitai/_maitai_client.py +34 -0
- maitai/_openai.py +334 -0
- maitai/_openai_types.py +13 -0
- maitai/_types.py +37 -0
- maitai/_utils.py +112 -0
- maitai_common/__init__.py +0 -0
- maitai_common/processes/__init__.py +0 -0
- maitai_common/processes/io_thread.py +62 -0
- maitai_common/processes/websocket_listener_thread.py +95 -0
- maitai_common/utils/__init__.py +0 -0
- maitai_common/utils/proto_utils.py +13 -0
- maitai_gen/__init__.py +0 -0
- maitai_gen/application/__init__.py +39 -0
- maitai_gen/chat/__init__.py +272 -0
- maitai_gen/company/__init__.py +21 -0
- maitai_gen/inference/__init__.py +19 -0
- maitai_gen/notification/__init__.py +34 -0
- maitai_gen/sandbox/__init__.py +43 -0
- maitai_gen/sentinel/__init__.py +47 -0
- maitai_gen/session/__init__.py +28 -0
- maitai_python-1.0.0b0.dist-info/METADATA +18 -0
- maitai_python-1.0.0b0.dist-info/RECORD +29 -0
- maitai_python-1.0.0b0.dist-info/WHEEL +5 -0
- maitai_python-1.0.0b0.dist-info/top_level.txt +3 -0
maitai/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import maitai._types as types
|
|
4
|
+
from maitai._evaluator import Evaluator as Evaluator
|
|
5
|
+
from maitai._inference import Inference as Inference
|
|
6
|
+
from maitai._openai import MaiTaiOpenAIClient as OpenAI
|
|
7
|
+
|
|
8
|
+
chat = OpenAI().chat
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def initialize(api_key):
|
|
12
|
+
from maitai._config import config
|
|
13
|
+
config.initialize(api_key)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
if os.environ.get("MAITAI_API_KEY") and os.environ.get("MAITAI_ENV") != "development":
|
|
17
|
+
initialize(os.environ.get("MAITAI_API_KEY"))
|
maitai/_config.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import requests
|
|
4
|
+
|
|
5
|
+
from maitai._config_listener_thread import ConfigListenerThread
|
|
6
|
+
from maitai_gen.application import Application
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Config:
|
|
10
|
+
maitai_host = os.environ.get("MAITAI_HOST", 'https://api.trymaitai.ai')
|
|
11
|
+
maitai_ws = os.environ.get("MAITAI_WS", 'wss://humrvommw4.execute-api.us-west-2.amazonaws.com/production')
|
|
12
|
+
|
|
13
|
+
def __init__(self):
|
|
14
|
+
self._api_key = None
|
|
15
|
+
self._applications: dict[str, Application] = {}
|
|
16
|
+
self._company_id = None
|
|
17
|
+
self.websocket_listener_thread = None
|
|
18
|
+
self.config_listener_thread = None
|
|
19
|
+
|
|
20
|
+
@property
|
|
21
|
+
def api_key(self):
|
|
22
|
+
if self._api_key is None:
|
|
23
|
+
raise ValueError("Maitai API Key has not been set")
|
|
24
|
+
return self._api_key
|
|
25
|
+
|
|
26
|
+
@api_key.setter
|
|
27
|
+
def api_key(self, value):
|
|
28
|
+
self._api_key = value
|
|
29
|
+
|
|
30
|
+
def initialize(self, api_key):
|
|
31
|
+
self.api_key = api_key
|
|
32
|
+
self._initialize_company()
|
|
33
|
+
self.refresh_applications()
|
|
34
|
+
self._initialize_websocket()
|
|
35
|
+
|
|
36
|
+
def get_application(self, application_ref_name: str) -> Application:
|
|
37
|
+
return self._applications.get(application_ref_name)
|
|
38
|
+
|
|
39
|
+
def _initialize_company(self):
|
|
40
|
+
host = self.maitai_host
|
|
41
|
+
url = f'{host}/company/'
|
|
42
|
+
headers = {
|
|
43
|
+
'Content-Type': 'application/json',
|
|
44
|
+
'x-api-key': self.api_key
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
response = requests.get(url, headers=headers, verify=False)
|
|
48
|
+
self._company_id = response.json().get("id")
|
|
49
|
+
|
|
50
|
+
def refresh_applications(self):
|
|
51
|
+
host = self.maitai_host
|
|
52
|
+
url = f'{host}/application/'
|
|
53
|
+
headers = {
|
|
54
|
+
'Content-Type': 'application/json',
|
|
55
|
+
'x-api-key': self.api_key
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
response = requests.get(url, headers=headers, verify=False)
|
|
59
|
+
applications = [Application().from_dict(app_json) for app_json in response.json()]
|
|
60
|
+
for application in applications:
|
|
61
|
+
self._applications[application.application_ref_name] = application
|
|
62
|
+
|
|
63
|
+
def _initialize_websocket(self):
|
|
64
|
+
self.config_listener_thread = ConfigListenerThread(self, self.maitai_ws, "APPLICATION_CONFIG_CHANGE", self._company_id)
|
|
65
|
+
self.config_listener_thread.daemon = True
|
|
66
|
+
self.config_listener_thread.start()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
config = Config()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
from maitai_common.processes.websocket_listener_thread import WebsocketListenerThread
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ConfigListenerThread(WebsocketListenerThread):
|
|
7
|
+
def __init__(self, config, path, type, key=None):
|
|
8
|
+
super(ConfigListenerThread, self).__init__(path, type, key)
|
|
9
|
+
self.config = config
|
|
10
|
+
|
|
11
|
+
def on_message(self, ws, message):
|
|
12
|
+
event = json.loads(message)
|
|
13
|
+
if event.get("event_type") == 'APPLICATION_CONFIG_CHANGE':
|
|
14
|
+
self.config.refresh_applications()
|
maitai/_evaluator.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
import aiohttp
|
|
5
|
+
import requests
|
|
6
|
+
from betterproto import Casing
|
|
7
|
+
|
|
8
|
+
from maitai._config import config
|
|
9
|
+
from maitai._maitai_client import MaiTaiClient
|
|
10
|
+
from maitai._types import EvaluateCallback
|
|
11
|
+
from maitai_gen.chat import EvaluateRequest, EvaluateResponse, EvaluationContentType
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Evaluator(MaiTaiClient):
|
|
15
|
+
|
|
16
|
+
def __init__(self):
|
|
17
|
+
super().__init__()
|
|
18
|
+
|
|
19
|
+
@classmethod
|
|
20
|
+
def evaluate_with_callback(cls, session_id, reference_id, action_type, content_type, content, application_id=None,
|
|
21
|
+
application_ref_name=None, callback=None):
|
|
22
|
+
if application_id is None and application_ref_name is None:
|
|
23
|
+
raise Exception('application_id or application_ref_name must be provided')
|
|
24
|
+
eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id,
|
|
25
|
+
reference_id, action_type, content_type, content)
|
|
26
|
+
cls.run_async(cls.send_evaluation_request_async(eval_request, callback))
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
async def evaluate_async(cls, session_id, reference_id, action_type, content_type, content, application_id=None,
|
|
30
|
+
application_ref_name=None):
|
|
31
|
+
if application_id is None and application_ref_name is None:
|
|
32
|
+
raise Exception('application_id or application_ref_name must be provided')
|
|
33
|
+
eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id,
|
|
34
|
+
reference_id, action_type, content_type, content)
|
|
35
|
+
return await cls.send_evaluation_request_async(eval_request)
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def evaluate(cls, session_id, reference_id, action_type, content_type, content, application_id=None,
|
|
39
|
+
application_ref_name=None):
|
|
40
|
+
if application_id is None and application_ref_name is None:
|
|
41
|
+
raise Exception('application_id or application_ref_name must be provided')
|
|
42
|
+
eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id,
|
|
43
|
+
reference_id, action_type, content_type, content)
|
|
44
|
+
return cls.send_evaluation_request(eval_request)
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def create_eval_request(cls, application_id, application_ref_name, session_id, reference_id, action_type,
|
|
48
|
+
content_type, content):
|
|
49
|
+
eval_request: EvaluateRequest = EvaluateRequest()
|
|
50
|
+
eval_request.evaluation_content_type = content_type
|
|
51
|
+
if content_type == EvaluationContentType.TEXT:
|
|
52
|
+
if type(content) != str:
|
|
53
|
+
raise Exception('Content must be a string')
|
|
54
|
+
eval_request.text_content = content
|
|
55
|
+
if content_type == EvaluationContentType.MESSAGE:
|
|
56
|
+
eval_request.message_content = content
|
|
57
|
+
eval_request.application_id = application_id
|
|
58
|
+
eval_request.application_ref_name = application_ref_name
|
|
59
|
+
eval_request.session_id = session_id
|
|
60
|
+
eval_request.reference_id = reference_id
|
|
61
|
+
eval_request.action_type = action_type
|
|
62
|
+
return eval_request
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
def update_session_context(cls, session_id, context, application_id=None, application_ref_name=None):
|
|
66
|
+
if type(context) != dict:
|
|
67
|
+
raise Exception('Context must be a dictionary')
|
|
68
|
+
if application_id is None and application_ref_name is None:
|
|
69
|
+
raise Exception('application_id or application_ref_name must be provided')
|
|
70
|
+
session_context = {
|
|
71
|
+
'application_id': application_id,
|
|
72
|
+
'application_ref_name': application_ref_name,
|
|
73
|
+
'session_id': session_id,
|
|
74
|
+
'context': context
|
|
75
|
+
}
|
|
76
|
+
cls.run_async(cls.send_session_context_update(session_context))
|
|
77
|
+
|
|
78
|
+
@classmethod
|
|
79
|
+
def append_session_context(cls, session_id, context, application_id=None, application_ref_name=None):
|
|
80
|
+
if type(context) != dict:
|
|
81
|
+
raise Exception('Context must be a dictionary')
|
|
82
|
+
if application_id is None and application_ref_name is None:
|
|
83
|
+
raise Exception('application_id or application_ref_name must be provided')
|
|
84
|
+
session_context = {
|
|
85
|
+
'application_id': application_id,
|
|
86
|
+
'application_ref_name': application_ref_name,
|
|
87
|
+
'session_id': session_id,
|
|
88
|
+
'context': context
|
|
89
|
+
}
|
|
90
|
+
cls.run_async(cls.send_session_context_append(session_context))
|
|
91
|
+
|
|
92
|
+
@classmethod
|
|
93
|
+
def update_application_context(cls, context, application_id=None, application_ref_name=None):
|
|
94
|
+
if type(context) != dict:
|
|
95
|
+
raise Exception('Context must be a dictionary')
|
|
96
|
+
if application_id is None and application_ref_name is None:
|
|
97
|
+
raise Exception('application_id or application_ref_name must be provided')
|
|
98
|
+
application_context = {
|
|
99
|
+
'application_id': application_id,
|
|
100
|
+
'application_ref_name': application_ref_name,
|
|
101
|
+
'context': context
|
|
102
|
+
}
|
|
103
|
+
cls.run_async(cls.send_application_context_update(application_context))
|
|
104
|
+
|
|
105
|
+
@classmethod
|
|
106
|
+
def append_application_context(cls, context, application_id=None, application_ref_name=None):
|
|
107
|
+
if type(context) != dict:
|
|
108
|
+
raise Exception('Context must be a dictionary')
|
|
109
|
+
if application_id is None and application_ref_name is None:
|
|
110
|
+
raise Exception('application_id or application_ref_name must be provided')
|
|
111
|
+
application_context = {
|
|
112
|
+
'application_id': application_id,
|
|
113
|
+
'application_ref_name': application_ref_name,
|
|
114
|
+
'context': context
|
|
115
|
+
}
|
|
116
|
+
cls.run_async(cls.send_application_context_append(application_context))
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
async def send_evaluation_request_async(cls, eval_request: EvaluateRequest, callback: EvaluateCallback = None):
|
|
120
|
+
start = time.time()
|
|
121
|
+
|
|
122
|
+
async def send_request():
|
|
123
|
+
host = config.maitai_host
|
|
124
|
+
url = f'{host}/evaluation/request'
|
|
125
|
+
headers = {
|
|
126
|
+
'Content-Type': 'application/json',
|
|
127
|
+
'x-api-key': config.api_key
|
|
128
|
+
}
|
|
129
|
+
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
|
|
130
|
+
async with session.post(url, headers=headers,
|
|
131
|
+
data=eval_request.to_json(casing=Casing.SNAKE)) as response:
|
|
132
|
+
if response.status != 200:
|
|
133
|
+
error_text = await response.text()
|
|
134
|
+
print(f"Failed to send evaluation request. Status code: {response.status}. Error: {error_text}")
|
|
135
|
+
return None
|
|
136
|
+
else:
|
|
137
|
+
print(f"Successfully sent evaluation request. Status code: {response.status}")
|
|
138
|
+
print(time.time() - start)
|
|
139
|
+
return await response.read()
|
|
140
|
+
|
|
141
|
+
result = await send_request()
|
|
142
|
+
if result is not None:
|
|
143
|
+
eval_result = EvaluateResponse().from_json(result)
|
|
144
|
+
if callback is not None:
|
|
145
|
+
callback(eval_result)
|
|
146
|
+
|
|
147
|
+
@classmethod
|
|
148
|
+
def send_evaluation_request(cls, eval_request: EvaluateRequest) -> EvaluateResponse:
|
|
149
|
+
start = time.time()
|
|
150
|
+
|
|
151
|
+
def send_request():
|
|
152
|
+
host = config.maitai_host
|
|
153
|
+
url = f'{host}/evaluation/request'
|
|
154
|
+
headers = {
|
|
155
|
+
'Content-Type': 'application/json',
|
|
156
|
+
'x-api-key': config.api_key
|
|
157
|
+
}
|
|
158
|
+
# Use requests to send a synchronous POST request
|
|
159
|
+
response = requests.post(url, headers=headers, data=eval_request.to_json(casing=Casing.SNAKE), verify=False)
|
|
160
|
+
if response.status_code != 200:
|
|
161
|
+
print(f"Failed to send evaluation request. Status code: {response.status_code}. Error: {response.text}")
|
|
162
|
+
return None
|
|
163
|
+
else:
|
|
164
|
+
print(f"Successfully sent evaluation request. Status code: {response.status_code}")
|
|
165
|
+
print(time.time() - start)
|
|
166
|
+
return response.content
|
|
167
|
+
|
|
168
|
+
result = send_request()
|
|
169
|
+
if result is not None:
|
|
170
|
+
eval_result = EvaluateResponse().from_json(result)
|
|
171
|
+
return eval_result
|
|
172
|
+
|
|
173
|
+
@classmethod
|
|
174
|
+
async def send_session_context_update(cls, session_context):
|
|
175
|
+
async def send_context():
|
|
176
|
+
try:
|
|
177
|
+
host = config.maitai_host
|
|
178
|
+
url = f'{host}/context/session'
|
|
179
|
+
headers = {
|
|
180
|
+
'Content-Type': 'application/json',
|
|
181
|
+
'x-api-key': config.api_key
|
|
182
|
+
}
|
|
183
|
+
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
|
|
184
|
+
async with session.put(url, headers=headers, data=json.dumps(session_context)) as response:
|
|
185
|
+
if response.status != 200:
|
|
186
|
+
error_text = await response.text()
|
|
187
|
+
print(
|
|
188
|
+
f"Failed to send session context update. Status code: {response.status}. Error: {error_text}")
|
|
189
|
+
else:
|
|
190
|
+
print(f"Successfully sent session context update. Status code: {response.status}")
|
|
191
|
+
except Exception as e:
|
|
192
|
+
print(f"An error occurred while sending session context update: {e}")
|
|
193
|
+
|
|
194
|
+
await send_context()
|
|
195
|
+
|
|
196
|
+
@classmethod
|
|
197
|
+
async def send_session_context_append(cls, session_context):
|
|
198
|
+
async def send_context():
|
|
199
|
+
try:
|
|
200
|
+
host = config.maitai_host
|
|
201
|
+
url = f'{host}/context/session/append'
|
|
202
|
+
headers = {
|
|
203
|
+
'Content-Type': 'application/json',
|
|
204
|
+
'x-api-key': config.api_key
|
|
205
|
+
}
|
|
206
|
+
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
|
|
207
|
+
async with session.put(url, headers=headers, data=json.dumps(session_context)) as response:
|
|
208
|
+
if response.status != 200:
|
|
209
|
+
error_text = await response.text()
|
|
210
|
+
print(
|
|
211
|
+
f"Failed to send session context for append. Status code: {response.status}. Error: {error_text}")
|
|
212
|
+
else:
|
|
213
|
+
print(f"Successfully sent session context for append. Status code: {response.status}")
|
|
214
|
+
except Exception as e:
|
|
215
|
+
print(f"An error occurred while sending session context for append: {e}")
|
|
216
|
+
|
|
217
|
+
await send_context()
|
|
218
|
+
|
|
219
|
+
@classmethod
|
|
220
|
+
async def send_application_context_update(cls, application_context):
|
|
221
|
+
async def send_context():
|
|
222
|
+
try:
|
|
223
|
+
host = config.maitai_host
|
|
224
|
+
url = f'{host}/context/application'
|
|
225
|
+
headers = {
|
|
226
|
+
'Content-Type': 'application/json',
|
|
227
|
+
'x-api-key': config.api_key
|
|
228
|
+
}
|
|
229
|
+
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
|
|
230
|
+
async with session.put(url, headers=headers, data=json.dumps(application_context)) as response:
|
|
231
|
+
if response.status != 200:
|
|
232
|
+
error_text = await response.text()
|
|
233
|
+
print(
|
|
234
|
+
f"Failed to send application context update. Status code: {response.status}. Error: {error_text}")
|
|
235
|
+
else:
|
|
236
|
+
print(f"Successfully sent application context update. Status code: {response.status}")
|
|
237
|
+
except Exception as e:
|
|
238
|
+
print(f"An error occurred while sending application context update: {e}")
|
|
239
|
+
|
|
240
|
+
await send_context()
|
|
241
|
+
|
|
242
|
+
@classmethod
|
|
243
|
+
async def send_application_context_append(cls, application_context):
|
|
244
|
+
async def send_context():
|
|
245
|
+
try:
|
|
246
|
+
host = config.maitai_host
|
|
247
|
+
url = f'{host}/context/application/append'
|
|
248
|
+
headers = {
|
|
249
|
+
'Content-Type': 'application/json',
|
|
250
|
+
'x-api-key': config.api_key
|
|
251
|
+
}
|
|
252
|
+
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
|
|
253
|
+
async with session.put(url, headers=headers, data=json.dumps(application_context)) as response:
|
|
254
|
+
if response.status != 200:
|
|
255
|
+
error_text = await response.text()
|
|
256
|
+
print(
|
|
257
|
+
f"Failed to send application context for append. Status code: {response.status}. Error: {error_text}")
|
|
258
|
+
else:
|
|
259
|
+
print(f"Successfully sent application context for append. Status code: {response.status}")
|
|
260
|
+
except Exception as e:
|
|
261
|
+
print(f"An error occurred while sending application context for append: {e}")
|
|
262
|
+
|
|
263
|
+
await send_context()
|
maitai/_inference.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from typing import Iterable
|
|
3
|
+
|
|
4
|
+
import aiohttp
|
|
5
|
+
import requests
|
|
6
|
+
from betterproto import Casing
|
|
7
|
+
|
|
8
|
+
from maitai._config import config
|
|
9
|
+
from maitai._maitai_client import MaiTaiClient
|
|
10
|
+
from maitai._types import ChunkQueue, EvaluateCallback, QueueIterable
|
|
11
|
+
from maitai_gen.chat import ChatCompletionParams, ChatCompletionRequest
|
|
12
|
+
from maitai_gen.inference import InferenceStreamResponse
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Inference(MaiTaiClient):
|
|
16
|
+
|
|
17
|
+
def __init__(self):
|
|
18
|
+
super().__init__()
|
|
19
|
+
|
|
20
|
+
@classmethod
|
|
21
|
+
def infer(cls, session_id, reference_id, action_type, application_ref_name, completion_params: ChatCompletionParams, evaluate_callback: EvaluateCallback = None,
|
|
22
|
+
timeout=None) -> Iterable[InferenceStreamResponse]:
|
|
23
|
+
apply_corrections = evaluate_callback is None
|
|
24
|
+
chat_request: ChatCompletionRequest = cls.create_inference_request(application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params)
|
|
25
|
+
if evaluate_callback:
|
|
26
|
+
q = ChunkQueue()
|
|
27
|
+
cls.run_async(cls.send_inference_request_async(chat_request, q, evaluate_callback))
|
|
28
|
+
return QueueIterable(q, timeout=timeout)
|
|
29
|
+
else:
|
|
30
|
+
return cls.send_inference_request(chat_request)
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def create_inference_request(cls, application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params: ChatCompletionParams):
|
|
34
|
+
infer_request: ChatCompletionRequest = ChatCompletionRequest()
|
|
35
|
+
infer_request.application_ref_name = application_ref_name
|
|
36
|
+
infer_request.reference_id = reference_id
|
|
37
|
+
infer_request.session_id = session_id
|
|
38
|
+
infer_request.action_type = action_type
|
|
39
|
+
infer_request.apply_corrections = apply_corrections
|
|
40
|
+
infer_request.params = completion_params
|
|
41
|
+
return infer_request
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def send_inference_request(cls, chat_request: ChatCompletionRequest) -> Iterable[InferenceStreamResponse]:
|
|
45
|
+
start = time.time()
|
|
46
|
+
|
|
47
|
+
def consume_stream():
|
|
48
|
+
host = config.maitai_host
|
|
49
|
+
url = f'{host}/chat/completions/serialized'
|
|
50
|
+
headers = {
|
|
51
|
+
'Content-Type': 'application/json',
|
|
52
|
+
'x-api-key': config.api_key
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
response = requests.post(url, headers=headers, data=chat_request.to_json(casing=Casing.SNAKE), verify=False, stream=True)
|
|
56
|
+
if response.status_code != 200:
|
|
57
|
+
print(f"Failed to send inference request. Status code: {response.status_code}. Error: {response.text}")
|
|
58
|
+
return
|
|
59
|
+
else:
|
|
60
|
+
print(f"Successfully sent inference request. Status code: {response.status_code}")
|
|
61
|
+
try:
|
|
62
|
+
for line in response.iter_lines():
|
|
63
|
+
if line:
|
|
64
|
+
yield line
|
|
65
|
+
finally:
|
|
66
|
+
response.close()
|
|
67
|
+
|
|
68
|
+
for resp in consume_stream():
|
|
69
|
+
inference_response: InferenceStreamResponse = InferenceStreamResponse().from_json(resp)
|
|
70
|
+
yield inference_response
|
|
71
|
+
print(time.time() - start)
|
|
72
|
+
|
|
73
|
+
@classmethod
|
|
74
|
+
async def send_inference_request_async(cls, chat_request: ChatCompletionRequest, chunk_queue: ChunkQueue, evaluation_callback: EvaluateCallback):
|
|
75
|
+
start = time.time()
|
|
76
|
+
|
|
77
|
+
host = config.maitai_host
|
|
78
|
+
url = f'{host}/chat/completions/serialized'
|
|
79
|
+
headers = {
|
|
80
|
+
'Content-Type': 'application/json',
|
|
81
|
+
'x-api-key': config.api_key
|
|
82
|
+
}
|
|
83
|
+
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
|
|
84
|
+
async with session.post(url, headers=headers, data=chat_request.to_json(casing=Casing.SNAKE)) as response:
|
|
85
|
+
if response.status != 200:
|
|
86
|
+
error_text = await response.text()
|
|
87
|
+
print(f"Failed to send evaluation request. Status code: {response.status}. Error: {error_text}")
|
|
88
|
+
chunk_queue.put("done")
|
|
89
|
+
return
|
|
90
|
+
else:
|
|
91
|
+
print(f"Successfully sent evaluation request. Status code: {response.status}")
|
|
92
|
+
last_item = None
|
|
93
|
+
async for line in response.content:
|
|
94
|
+
if line:
|
|
95
|
+
inference_response: InferenceStreamResponse = InferenceStreamResponse().from_json(line)
|
|
96
|
+
chunk_queue.put(inference_response)
|
|
97
|
+
last_item = inference_response
|
|
98
|
+
chunk_queue.put("done")
|
|
99
|
+
if last_item is not None and last_item.evaluate_response:
|
|
100
|
+
evaluation_callback(last_item.evaluate_response)
|
|
101
|
+
print(time.time() - start)
|
maitai/_maitai_client.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import os
|
|
3
|
+
import threading
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class MaiTaiClient:
|
|
7
|
+
MAITAI_HOST = os.environ.get("MAITAI_HOST", 'https://api.trymaitai.ai')
|
|
8
|
+
|
|
9
|
+
def __init__(self):
|
|
10
|
+
super().__init__()
|
|
11
|
+
|
|
12
|
+
@classmethod
|
|
13
|
+
def run_async(cls, coro):
|
|
14
|
+
"""
|
|
15
|
+
Modified helper method to run coroutine in a background thread if not already in an asyncio loop,
|
|
16
|
+
otherwise just run it. This allows for both asyncio and non-asyncio applications to use this method.
|
|
17
|
+
"""
|
|
18
|
+
try:
|
|
19
|
+
loop = asyncio.get_running_loop()
|
|
20
|
+
except RuntimeError: # No running event loop
|
|
21
|
+
loop = None
|
|
22
|
+
|
|
23
|
+
if loop and loop.is_running():
|
|
24
|
+
# We are in an asyncio loop, schedule coroutine execution
|
|
25
|
+
asyncio.create_task(coro, name='maitai')
|
|
26
|
+
else:
|
|
27
|
+
# Not in an asyncio loop, run in a new event loop in a background thread
|
|
28
|
+
def run():
|
|
29
|
+
new_loop = asyncio.new_event_loop()
|
|
30
|
+
asyncio.set_event_loop(new_loop)
|
|
31
|
+
new_loop.run_until_complete(coro)
|
|
32
|
+
new_loop.close()
|
|
33
|
+
|
|
34
|
+
threading.Thread(target=run).start()
|