maitai-python 1.0.1__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 (36) hide show
  1. maitai_python-1.0.1/PKG-INFO +65 -0
  2. maitai_python-1.0.1/README.md +46 -0
  3. maitai_python-1.0.1/maitai/__init__.py +18 -0
  4. maitai_python-1.0.1/maitai/_config.py +69 -0
  5. maitai_python-1.0.1/maitai/_config_listener_thread.py +14 -0
  6. maitai_python-1.0.1/maitai/_evaluator.py +304 -0
  7. maitai_python-1.0.1/maitai/_inference.py +111 -0
  8. maitai_python-1.0.1/maitai/_maitai_client.py +34 -0
  9. maitai_python-1.0.1/maitai/_openai.py +239 -0
  10. maitai_python-1.0.1/maitai/_openai_async.py +241 -0
  11. maitai_python-1.0.1/maitai/_openai_types.py +13 -0
  12. maitai_python-1.0.1/maitai/_types.py +66 -0
  13. maitai_python-1.0.1/maitai/_utils.py +235 -0
  14. maitai_python-1.0.1/maitai_common/__init__.py +0 -0
  15. maitai_python-1.0.1/maitai_common/processes/__init__.py +0 -0
  16. maitai_python-1.0.1/maitai_common/processes/io_thread.py +65 -0
  17. maitai_python-1.0.1/maitai_common/processes/stream_evaluation_thread.py +23 -0
  18. maitai_python-1.0.1/maitai_common/processes/websocket_listener_thread.py +95 -0
  19. maitai_python-1.0.1/maitai_common/utils/__init__.py +0 -0
  20. maitai_python-1.0.1/maitai_common/utils/proto_utils.py +13 -0
  21. maitai_python-1.0.1/maitai_gen/__init__.py +0 -0
  22. maitai_python-1.0.1/maitai_gen/application/__init__.py +39 -0
  23. maitai_python-1.0.1/maitai_gen/chat/__init__.py +316 -0
  24. maitai_python-1.0.1/maitai_gen/company/__init__.py +21 -0
  25. maitai_python-1.0.1/maitai_gen/inference/__init__.py +19 -0
  26. maitai_python-1.0.1/maitai_gen/notification/__init__.py +34 -0
  27. maitai_python-1.0.1/maitai_gen/sandbox/__init__.py +43 -0
  28. maitai_python-1.0.1/maitai_gen/sentinel/__init__.py +47 -0
  29. maitai_python-1.0.1/maitai_gen/session/__init__.py +28 -0
  30. maitai_python-1.0.1/maitai_python.egg-info/PKG-INFO +65 -0
  31. maitai_python-1.0.1/maitai_python.egg-info/SOURCES.txt +34 -0
  32. maitai_python-1.0.1/maitai_python.egg-info/dependency_links.txt +1 -0
  33. maitai_python-1.0.1/maitai_python.egg-info/requires.txt +7 -0
  34. maitai_python-1.0.1/maitai_python.egg-info/top_level.txt +3 -0
  35. maitai_python-1.0.1/setup.cfg +4 -0
  36. maitai_python-1.0.1/setup.py +29 -0
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.1
2
+ Name: maitai-python
3
+ Version: 1.0.1
4
+ Summary: MaiTai SDK for Python
5
+ Home-page: https://docs.trymaitai.ai
6
+ Author: Maitai
7
+ Author-email: support@trymaitai.ai
8
+ License: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: requests
13
+ Requires-Dist: openai
14
+ Requires-Dist: betterproto
15
+ Requires-Dist: httpx
16
+ Requires-Dist: aiohttp
17
+ Requires-Dist: setuptools
18
+ Requires-Dist: websocket-client
19
+
20
+ # Quickstart
21
+
22
+ Full docs can be found at https://docs.trymaitai.ai
23
+
24
+ ## Configure your application in the Maitai portal
25
+
26
+ From the [Maitai Portal](https://portal.trymaitai.ai/), click the `+ New Application` button to create your first
27
+ application.
28
+
29
+ Fill out your application details, and note the `Application Reference` - you'll need that later
30
+
31
+ ## Create your first sentinel
32
+
33
+ Maitai will analyze your application and automatically create sentinels for you over time. However, if you want to
34
+ enable governance immediately, you can manually create sentinels as well.
35
+
36
+ Find your application in the portal and click the `+` button to create a new sentinel.
37
+
38
+ ## Installation
39
+
40
+ Install the Maitai SDK:
41
+
42
+ ```bash
43
+ pip install maitai-python
44
+ ```
45
+
46
+ ## Implementation
47
+
48
+ Integrating Maitai into your application requires minimal code changes
49
+
50
+ ```python
51
+ import maitai as openai
52
+
53
+ messages = [
54
+ {"role": "system", "content": "You are a helpful assistant"},
55
+ {"role": "user", "content": "Generate numbers 1-10"},
56
+ ]
57
+
58
+ response = openai.chat.completions.create(
59
+ messages=messages,
60
+ model="gpt-4",
61
+ session_id="YOUR_SESSION_ID",
62
+ action_type="NUMBER_GENERATOR",
63
+ application_ref_name="YOUR_APPLICATION_REF_NAME",
64
+ )
65
+ ```
@@ -0,0 +1,46 @@
1
+ # Quickstart
2
+
3
+ Full docs can be found at https://docs.trymaitai.ai
4
+
5
+ ## Configure your application in the Maitai portal
6
+
7
+ From the [Maitai Portal](https://portal.trymaitai.ai/), click the `+ New Application` button to create your first
8
+ application.
9
+
10
+ Fill out your application details, and note the `Application Reference` - you'll need that later
11
+
12
+ ## Create your first sentinel
13
+
14
+ Maitai will analyze your application and automatically create sentinels for you over time. However, if you want to
15
+ enable governance immediately, you can manually create sentinels as well.
16
+
17
+ Find your application in the portal and click the `+` button to create a new sentinel.
18
+
19
+ ## Installation
20
+
21
+ Install the Maitai SDK:
22
+
23
+ ```bash
24
+ pip install maitai-python
25
+ ```
26
+
27
+ ## Implementation
28
+
29
+ Integrating Maitai into your application requires minimal code changes
30
+
31
+ ```python
32
+ import maitai as openai
33
+
34
+ messages = [
35
+ {"role": "system", "content": "You are a helpful assistant"},
36
+ {"role": "user", "content": "Generate numbers 1-10"},
37
+ ]
38
+
39
+ response = openai.chat.completions.create(
40
+ messages=messages,
41
+ model="gpt-4",
42
+ session_id="YOUR_SESSION_ID",
43
+ action_type="NUMBER_GENERATOR",
44
+ application_ref_name="YOUR_APPLICATION_REF_NAME",
45
+ )
46
+ ```
@@ -0,0 +1,18 @@
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
+ from maitai._openai_async import MaiTaiAsyncOpenAIClient as AsyncOpenAI
8
+
9
+ chat = OpenAI().chat
10
+
11
+
12
+ def initialize(api_key):
13
+ from maitai._config import config
14
+ config.initialize(api_key)
15
+
16
+
17
+ if os.environ.get("MAITAI_API_KEY") and os.environ.get("MAITAI_ENV") != "development":
18
+ initialize(os.environ.get("MAITAI_API_KEY"))
@@ -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()
@@ -0,0 +1,304 @@
1
+ import json
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 EvaluateCallback
11
+ from maitai_gen.chat import ChatCompletionChunk, EvaluateRequest, EvaluateResponse, EvaluationContentType
12
+
13
+
14
+ def _get_content_type(content, partial=None):
15
+ if partial is not None:
16
+ return EvaluateResponse.PARTIAL_CONTENT
17
+ if isinstance(content, str):
18
+ return EvaluationContentType.TEXT
19
+ elif isinstance(content, list):
20
+ return EvaluationContentType.MESSAGE
21
+
22
+
23
+ class Evaluator(MaiTaiClient):
24
+
25
+ def __init__(self):
26
+ super().__init__()
27
+
28
+ @classmethod
29
+ async def evaluate_async(cls, session_id, reference_id, action_type, content, content_type=None, application_id=None, application_ref_name=None, callback=None):
30
+ if content_type is None:
31
+ content_type = _get_content_type(content)
32
+ if content_type is None:
33
+ raise Exception('Unable to automatically determine content_type')
34
+ if application_id is None and application_ref_name is None:
35
+ raise Exception('application_id or application_ref_name must be provided')
36
+ eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id, reference_id, action_type, content_type, content)
37
+ if callback is None:
38
+ return await cls.send_evaluation_request_async(eval_request)
39
+ else:
40
+ cls.run_async(cls.send_evaluation_request_async(eval_request, callback))
41
+ return None
42
+
43
+ @classmethod
44
+ def evaluate(cls, session_id, reference_id, action_type, content, content_type=None, application_id=None, application_ref_name=None, callback=None, partial=None):
45
+ if content_type is None:
46
+ content_type = _get_content_type(content, partial)
47
+ if content_type is None:
48
+ raise Exception('Unable to automatically determine content_type')
49
+ if application_id is None and application_ref_name is None:
50
+ raise Exception('application_id or application_ref_name must be provided')
51
+ eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id, reference_id, action_type, content_type, content, partial=partial)
52
+ if callback is None:
53
+ return cls.send_evaluation_request(eval_request)
54
+ else:
55
+ cls.run_async(cls.send_evaluation_request_async(eval_request, callback))
56
+ return None
57
+
58
+ @classmethod
59
+ def evaluate_realtime(cls, session_id, reference_id, action_type, content_type, content, application_ref_name, partial, fault_description, sentinel_id):
60
+ eval_request: EvaluateRequest = cls.create_eval_request(None, application_ref_name, session_id, reference_id, action_type, content_type, content, partial=partial,
61
+ fault_description=fault_description)
62
+ eval_request.sentinel_id = sentinel_id
63
+ return cls.send_realtime_eval_request(eval_request)
64
+
65
+ @classmethod
66
+ def create_eval_request(cls, application_id, application_ref_name, session_id, reference_id, action_type,
67
+ content_type, content, partial=None, fault_description=None):
68
+ eval_request: EvaluateRequest = EvaluateRequest()
69
+ eval_request.evaluation_content_type = content_type
70
+ if content_type == EvaluationContentType.TEXT:
71
+ if type(content) != str:
72
+ raise Exception('Content must be a string')
73
+ eval_request.text_content = content
74
+ elif content_type == EvaluationContentType.MESSAGE:
75
+ eval_request.message_content = content
76
+ elif content_type == EvaluationContentType.PARTIAL:
77
+ eval_request.message_content = content
78
+ eval_request.text_content = partial
79
+ eval_request.application_id = application_id
80
+ eval_request.application_ref_name = application_ref_name
81
+ eval_request.session_id = session_id
82
+ eval_request.reference_id = reference_id
83
+ eval_request.action_type = action_type
84
+ if fault_description:
85
+ eval_request.fault_description = fault_description
86
+ return eval_request
87
+
88
+ @classmethod
89
+ def update_session_context(cls, session_id, context, application_id=None, application_ref_name=None):
90
+ if type(context) != dict:
91
+ raise Exception('Context must be a dictionary')
92
+ if application_id is None and application_ref_name is None:
93
+ raise Exception('application_id or application_ref_name must be provided')
94
+ session_context = {
95
+ 'application_id': application_id,
96
+ 'application_ref_name': application_ref_name,
97
+ 'session_id': session_id,
98
+ 'context': context
99
+ }
100
+ cls.run_async(cls.send_session_context_update(session_context))
101
+
102
+ @classmethod
103
+ def append_session_context(cls, session_id, context, application_id=None, application_ref_name=None):
104
+ if type(context) != dict:
105
+ raise Exception('Context must be a dictionary')
106
+ if application_id is None and application_ref_name is None:
107
+ raise Exception('application_id or application_ref_name must be provided')
108
+ session_context = {
109
+ 'application_id': application_id,
110
+ 'application_ref_name': application_ref_name,
111
+ 'session_id': session_id,
112
+ 'context': context
113
+ }
114
+ cls.run_async(cls.send_session_context_append(session_context))
115
+
116
+ @classmethod
117
+ def update_application_context(cls, context, application_id=None, application_ref_name=None):
118
+ if type(context) != dict:
119
+ raise Exception('Context must be a dictionary')
120
+ if application_id is None and application_ref_name is None:
121
+ raise Exception('application_id or application_ref_name must be provided')
122
+ application_context = {
123
+ 'application_id': application_id,
124
+ 'application_ref_name': application_ref_name,
125
+ 'context': context
126
+ }
127
+ cls.run_async(cls.send_application_context_update(application_context))
128
+
129
+ @classmethod
130
+ def append_application_context(cls, context, application_id=None, application_ref_name=None):
131
+ if type(context) != dict:
132
+ raise Exception('Context must be a dictionary')
133
+ if application_id is None and application_ref_name is None:
134
+ raise Exception('application_id or application_ref_name must be provided')
135
+ application_context = {
136
+ 'application_id': application_id,
137
+ 'application_ref_name': application_ref_name,
138
+ 'context': context
139
+ }
140
+ cls.run_async(cls.send_application_context_append(application_context))
141
+
142
+ @classmethod
143
+ async def send_evaluation_request_async(cls, eval_request: EvaluateRequest, callback: EvaluateCallback = None):
144
+ async def send_request():
145
+ host = config.maitai_host
146
+ url = f'{host}/evaluation/request'
147
+ headers = {
148
+ 'Content-Type': 'application/json',
149
+ 'x-api-key': config.api_key
150
+ }
151
+ async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
152
+ async with session.post(url, headers=headers,
153
+ data=eval_request.to_json(casing=Casing.SNAKE)) as response:
154
+ if response.status != 200:
155
+ error_text = await response.text()
156
+ print(f"Failed to send evaluation request. Status code: {response.status}. Error: {error_text}")
157
+ return None
158
+ return await response.read()
159
+
160
+ result = await send_request()
161
+ if result is not None:
162
+ eval_result = EvaluateResponse().from_json(result)
163
+ if callback is not None:
164
+ callback(eval_result)
165
+ else:
166
+ return eval_result
167
+
168
+ @classmethod
169
+ def send_evaluation_request(cls, eval_request: EvaluateRequest) -> EvaluateResponse:
170
+ def send_request():
171
+ host = config.maitai_host
172
+ url = f'{host}/evaluation/request'
173
+ headers = {
174
+ 'Content-Type': 'application/json',
175
+ 'x-api-key': config.api_key
176
+ }
177
+ # Use requests to send a synchronous POST request
178
+ response = requests.post(url, headers=headers, data=eval_request.to_json(casing=Casing.SNAKE), verify=False)
179
+ if response.status_code != 200:
180
+ print(f"Failed to send evaluation request. Status code: {response.status_code}. Error: {response.text}")
181
+ return None
182
+ return response.content
183
+
184
+ result = send_request()
185
+ if result is not None:
186
+ eval_result = EvaluateResponse().from_json(result)
187
+ return eval_result
188
+
189
+ @classmethod
190
+ async def send_session_context_update(cls, session_context):
191
+ async def send_context():
192
+ try:
193
+ host = config.maitai_host
194
+ url = f'{host}/context/session'
195
+ headers = {
196
+ 'Content-Type': 'application/json',
197
+ 'x-api-key': config.api_key
198
+ }
199
+ async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
200
+ async with session.put(url, headers=headers, data=json.dumps(session_context)) as response:
201
+ if response.status != 200:
202
+ error_text = await response.text()
203
+ print(
204
+ f"Failed to send session context update. Status code: {response.status}. Error: {error_text}")
205
+ else:
206
+ print(f"Successfully sent session context update. Status code: {response.status}")
207
+ except Exception as e:
208
+ print(f"An error occurred while sending session context update: {e}")
209
+
210
+ await send_context()
211
+
212
+ @classmethod
213
+ async def send_session_context_append(cls, session_context):
214
+ async def send_context():
215
+ try:
216
+ host = config.maitai_host
217
+ url = f'{host}/context/session/append'
218
+ headers = {
219
+ 'Content-Type': 'application/json',
220
+ 'x-api-key': config.api_key
221
+ }
222
+ async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
223
+ async with session.put(url, headers=headers, data=json.dumps(session_context)) as response:
224
+ if response.status != 200:
225
+ error_text = await response.text()
226
+ print(
227
+ f"Failed to send session context for append. Status code: {response.status}. Error: {error_text}")
228
+ else:
229
+ print(f"Successfully sent session context for append. Status code: {response.status}")
230
+ except Exception as e:
231
+ print(f"An error occurred while sending session context for append: {e}")
232
+
233
+ await send_context()
234
+
235
+ @classmethod
236
+ async def send_application_context_update(cls, application_context):
237
+ async def send_context():
238
+ try:
239
+ host = config.maitai_host
240
+ url = f'{host}/context/application'
241
+ headers = {
242
+ 'Content-Type': 'application/json',
243
+ 'x-api-key': config.api_key
244
+ }
245
+ async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
246
+ async with session.put(url, headers=headers, data=json.dumps(application_context)) as response:
247
+ if response.status != 200:
248
+ error_text = await response.text()
249
+ print(
250
+ f"Failed to send application context update. Status code: {response.status}. Error: {error_text}")
251
+ else:
252
+ print(f"Successfully sent application context update. Status code: {response.status}")
253
+ except Exception as e:
254
+ print(f"An error occurred while sending application context update: {e}")
255
+
256
+ await send_context()
257
+
258
+ @classmethod
259
+ async def send_application_context_append(cls, application_context):
260
+ async def send_context():
261
+ try:
262
+ host = config.maitai_host
263
+ url = f'{host}/context/application/append'
264
+ headers = {
265
+ 'Content-Type': 'application/json',
266
+ 'x-api-key': config.api_key
267
+ }
268
+ async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
269
+ async with session.put(url, headers=headers, data=json.dumps(application_context)) as response:
270
+ if response.status != 200:
271
+ error_text = await response.text()
272
+ print(
273
+ f"Failed to send application context for append. Status code: {response.status}. Error: {error_text}")
274
+ else:
275
+ print(f"Successfully sent application context for append. Status code: {response.status}")
276
+ except Exception as e:
277
+ print(f"An error occurred while sending application context for append: {e}")
278
+
279
+ await send_context()
280
+
281
+ @classmethod
282
+ def send_realtime_eval_request(cls, eval_request: EvaluateRequest) -> Iterable[ChatCompletionChunk]:
283
+ def consume_stream():
284
+ host = config.maitai_host
285
+ url = f'{host}/evaluation/realtime'
286
+ headers = {
287
+ 'Content-Type': 'application/json',
288
+ 'x-api-key': config.api_key
289
+ }
290
+
291
+ response = requests.post(url, headers=headers, data=eval_request.to_json(casing=Casing.SNAKE), verify=False, stream=True)
292
+ if response.status_code != 200:
293
+ print(f"Failed to send realtime evaluation request. Status code: {response.status_code}. Error: {response.text}")
294
+ return
295
+ try:
296
+ for line in response.iter_lines():
297
+ if line:
298
+ yield line
299
+ finally:
300
+ response.close()
301
+
302
+ for resp in consume_stream():
303
+ inference_response: ChatCompletionChunk = ChatCompletionChunk().from_json(resp)
304
+ yield inference_response
@@ -0,0 +1,111 @@
1
+ from typing import AsyncIterable, Iterable
2
+
3
+ import aiohttp
4
+ import requests
5
+ from betterproto import Casing
6
+
7
+ from maitai._config import config
8
+ from maitai._maitai_client import MaiTaiClient
9
+ from maitai._types import AsyncChunkQueue, ChunkQueue, EvaluateCallback, QueueIterable
10
+ from maitai_gen.chat import ChatCompletionParams, ChatCompletionRequest
11
+ from maitai_gen.inference import InferenceStreamResponse
12
+
13
+
14
+ class Inference(MaiTaiClient):
15
+
16
+ def __init__(self):
17
+ super().__init__()
18
+
19
+ @classmethod
20
+ def infer(cls, session_id, reference_id, action_type, application_ref_name, completion_params: ChatCompletionParams, evaluate_callback: EvaluateCallback = None,
21
+ timeout=None) -> Iterable[InferenceStreamResponse]:
22
+ apply_corrections = evaluate_callback is None
23
+ chat_request: ChatCompletionRequest = cls.create_inference_request(application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params)
24
+ if evaluate_callback:
25
+ q = ChunkQueue()
26
+ cls.run_async(cls.send_inference_request_async(chat_request, chunk_queue=q, evaluation_callback=evaluate_callback))
27
+ return QueueIterable(q, timeout=timeout)
28
+ else:
29
+ return cls.send_inference_request(chat_request)
30
+
31
+ @classmethod
32
+ async def infer_async(cls, session_id, reference_id, action_type, application_ref_name, completion_params: ChatCompletionParams, evaluate_callback: EvaluateCallback = None,
33
+ timeout=None) -> AsyncIterable[InferenceStreamResponse]:
34
+ apply_corrections = evaluate_callback is None
35
+ chat_request: ChatCompletionRequest = cls.create_inference_request(application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params)
36
+ q = AsyncChunkQueue()
37
+ cls.run_async(cls.send_inference_request_async(chat_request, async_chunk_queue=q, evaluation_callback=evaluate_callback))
38
+ return QueueIterable(q, timeout=timeout)
39
+
40
+ @classmethod
41
+ def create_inference_request(cls, application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params: ChatCompletionParams):
42
+ infer_request: ChatCompletionRequest = ChatCompletionRequest()
43
+ infer_request.application_ref_name = application_ref_name
44
+ infer_request.reference_id = reference_id
45
+ infer_request.session_id = session_id
46
+ infer_request.action_type = action_type
47
+ infer_request.apply_corrections = apply_corrections
48
+ infer_request.params = completion_params
49
+ return infer_request
50
+
51
+ @classmethod
52
+ def send_inference_request(cls, chat_request: ChatCompletionRequest) -> Iterable[InferenceStreamResponse]:
53
+ def consume_stream():
54
+ host = config.maitai_host
55
+ url = f'{host}/chat/completions/serialized'
56
+ headers = {
57
+ 'Content-Type': 'application/json',
58
+ 'x-api-key': config.api_key
59
+ }
60
+
61
+ response = requests.post(url, headers=headers, data=chat_request.to_json(casing=Casing.SNAKE), verify=False, stream=True)
62
+ if response.status_code != 200:
63
+ print(f"Failed to send inference request. Status code: {response.status_code}. Error: {response.text}")
64
+ return
65
+ else:
66
+ print(f"Successfully sent inference request. Status code: {response.status_code}")
67
+ try:
68
+ for line in response.iter_lines():
69
+ if line:
70
+ yield line
71
+ finally:
72
+ response.close()
73
+
74
+ for resp in consume_stream():
75
+ inference_response: InferenceStreamResponse = InferenceStreamResponse().from_json(resp)
76
+ yield inference_response
77
+
78
+ @classmethod
79
+ async def send_inference_request_async(cls, chat_request: ChatCompletionRequest, chunk_queue: ChunkQueue = None, async_chunk_queue: AsyncChunkQueue = None, evaluation_callback: EvaluateCallback = None):
80
+ host = config.maitai_host
81
+ url = f'{host}/chat/completions/serialized'
82
+ headers = {
83
+ 'Content-Type': 'application/json',
84
+ 'x-api-key': config.api_key
85
+ }
86
+ async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
87
+ async with session.post(url, headers=headers, data=chat_request.to_json(casing=Casing.SNAKE)) as response:
88
+ if response.status != 200:
89
+ error_text = await response.text()
90
+ print(f"Failed to send evaluation request. Status code: {response.status}. Error: {error_text}")
91
+ if chunk_queue:
92
+ chunk_queue.put("done")
93
+ if async_chunk_queue:
94
+ await async_chunk_queue.put("done")
95
+ return
96
+ last_item = None
97
+ async for line in response.content:
98
+ if line:
99
+ inference_response: InferenceStreamResponse = InferenceStreamResponse().from_json(line)
100
+ if chunk_queue:
101
+ chunk_queue.put(inference_response)
102
+ if async_chunk_queue:
103
+ await async_chunk_queue.put(inference_response)
104
+ last_item = inference_response
105
+ if chunk_queue:
106
+ chunk_queue.put("done")
107
+ if async_chunk_queue:
108
+ await async_chunk_queue.put("done")
109
+ if last_item is not None and last_item.evaluate_response:
110
+ if evaluation_callback:
111
+ evaluation_callback(last_item.evaluate_response)
@@ -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()