maitai-python 1.0.1b1__py3-none-any.whl → 1.0.2__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 +1 -0
- maitai/_evaluator.py +72 -31
- maitai/_inference.py +27 -17
- maitai/_openai.py +42 -137
- maitai/_openai_async.py +241 -0
- maitai/_types.py +31 -2
- maitai/_utils.py +125 -2
- maitai_common/processes/io_thread.py +5 -2
- maitai_common/processes/stream_evaluation_thread.py +23 -0
- maitai_gen/chat/__init__.py +44 -0
- {maitai_python-1.0.1b1.dist-info → maitai_python-1.0.2.dist-info}/METADATA +1 -1
- {maitai_python-1.0.1b1.dist-info → maitai_python-1.0.2.dist-info}/RECORD +14 -12
- {maitai_python-1.0.1b1.dist-info → maitai_python-1.0.2.dist-info}/WHEEL +0 -0
- {maitai_python-1.0.1b1.dist-info → maitai_python-1.0.2.dist-info}/top_level.txt +0 -0
maitai/__init__.py
CHANGED
|
@@ -4,6 +4,7 @@ import maitai._types as types
|
|
|
4
4
|
from maitai._evaluator import Evaluator as Evaluator
|
|
5
5
|
from maitai._inference import Inference as Inference
|
|
6
6
|
from maitai._openai import MaiTaiOpenAIClient as OpenAI
|
|
7
|
+
from maitai._openai_async import MaiTaiAsyncOpenAIClient as AsyncOpenAI
|
|
7
8
|
|
|
8
9
|
chat = OpenAI().chat
|
|
9
10
|
|
maitai/_evaluator.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import json
|
|
2
|
-
import
|
|
2
|
+
from typing import Iterable
|
|
3
3
|
|
|
4
4
|
import aiohttp
|
|
5
5
|
import requests
|
|
@@ -8,7 +8,16 @@ from betterproto import Casing
|
|
|
8
8
|
from maitai._config import config
|
|
9
9
|
from maitai._maitai_client import MaiTaiClient
|
|
10
10
|
from maitai._types import EvaluateCallback
|
|
11
|
-
from maitai_gen.chat import EvaluateRequest, EvaluateResponse, EvaluationContentType
|
|
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
|
|
12
21
|
|
|
13
22
|
|
|
14
23
|
class Evaluator(MaiTaiClient):
|
|
@@ -17,48 +26,63 @@ class Evaluator(MaiTaiClient):
|
|
|
17
26
|
super().__init__()
|
|
18
27
|
|
|
19
28
|
@classmethod
|
|
20
|
-
def
|
|
21
|
-
|
|
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')
|
|
22
34
|
if application_id is None and application_ref_name is None:
|
|
23
35
|
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
|
-
|
|
26
|
-
|
|
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
|
|
27
42
|
|
|
28
43
|
@classmethod
|
|
29
|
-
|
|
30
|
-
|
|
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')
|
|
31
49
|
if application_id is None and application_ref_name is None:
|
|
32
50
|
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
|
-
|
|
35
|
-
|
|
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
|
|
36
57
|
|
|
37
58
|
@classmethod
|
|
38
|
-
def
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
reference_id, action_type, content_type, content)
|
|
44
|
-
return cls.send_evaluation_request(eval_request)
|
|
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)
|
|
45
64
|
|
|
46
65
|
@classmethod
|
|
47
66
|
def create_eval_request(cls, application_id, application_ref_name, session_id, reference_id, action_type,
|
|
48
|
-
content_type, content):
|
|
67
|
+
content_type, content, partial=None, fault_description=None):
|
|
49
68
|
eval_request: EvaluateRequest = EvaluateRequest()
|
|
50
69
|
eval_request.evaluation_content_type = content_type
|
|
51
70
|
if content_type == EvaluationContentType.TEXT:
|
|
52
71
|
if type(content) != str:
|
|
53
72
|
raise Exception('Content must be a string')
|
|
54
73
|
eval_request.text_content = content
|
|
55
|
-
|
|
74
|
+
elif content_type == EvaluationContentType.MESSAGE:
|
|
75
|
+
eval_request.message_content = content
|
|
76
|
+
elif content_type == EvaluationContentType.PARTIAL:
|
|
56
77
|
eval_request.message_content = content
|
|
78
|
+
eval_request.text_content = partial
|
|
57
79
|
eval_request.application_id = application_id
|
|
58
80
|
eval_request.application_ref_name = application_ref_name
|
|
59
81
|
eval_request.session_id = session_id
|
|
60
82
|
eval_request.reference_id = reference_id
|
|
61
83
|
eval_request.action_type = action_type
|
|
84
|
+
if fault_description:
|
|
85
|
+
eval_request.fault_description = fault_description
|
|
62
86
|
return eval_request
|
|
63
87
|
|
|
64
88
|
@classmethod
|
|
@@ -117,8 +141,6 @@ class Evaluator(MaiTaiClient):
|
|
|
117
141
|
|
|
118
142
|
@classmethod
|
|
119
143
|
async def send_evaluation_request_async(cls, eval_request: EvaluateRequest, callback: EvaluateCallback = None):
|
|
120
|
-
start = time.time()
|
|
121
|
-
|
|
122
144
|
async def send_request():
|
|
123
145
|
host = config.maitai_host
|
|
124
146
|
url = f'{host}/evaluation/request'
|
|
@@ -133,9 +155,6 @@ class Evaluator(MaiTaiClient):
|
|
|
133
155
|
error_text = await response.text()
|
|
134
156
|
print(f"Failed to send evaluation request. Status code: {response.status}. Error: {error_text}")
|
|
135
157
|
return None
|
|
136
|
-
else:
|
|
137
|
-
print(f"Successfully sent evaluation request. Status code: {response.status}")
|
|
138
|
-
print(time.time() - start)
|
|
139
158
|
return await response.read()
|
|
140
159
|
|
|
141
160
|
result = await send_request()
|
|
@@ -143,11 +162,11 @@ class Evaluator(MaiTaiClient):
|
|
|
143
162
|
eval_result = EvaluateResponse().from_json(result)
|
|
144
163
|
if callback is not None:
|
|
145
164
|
callback(eval_result)
|
|
165
|
+
else:
|
|
166
|
+
return eval_result
|
|
146
167
|
|
|
147
168
|
@classmethod
|
|
148
169
|
def send_evaluation_request(cls, eval_request: EvaluateRequest) -> EvaluateResponse:
|
|
149
|
-
start = time.time()
|
|
150
|
-
|
|
151
170
|
def send_request():
|
|
152
171
|
host = config.maitai_host
|
|
153
172
|
url = f'{host}/evaluation/request'
|
|
@@ -160,9 +179,6 @@ class Evaluator(MaiTaiClient):
|
|
|
160
179
|
if response.status_code != 200:
|
|
161
180
|
print(f"Failed to send evaluation request. Status code: {response.status_code}. Error: {response.text}")
|
|
162
181
|
return None
|
|
163
|
-
else:
|
|
164
|
-
print(f"Successfully sent evaluation request. Status code: {response.status_code}")
|
|
165
|
-
print(time.time() - start)
|
|
166
182
|
return response.content
|
|
167
183
|
|
|
168
184
|
result = send_request()
|
|
@@ -261,3 +277,28 @@ class Evaluator(MaiTaiClient):
|
|
|
261
277
|
print(f"An error occurred while sending application context for append: {e}")
|
|
262
278
|
|
|
263
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
|
maitai/_inference.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import
|
|
2
|
-
from typing import Iterable
|
|
1
|
+
from typing import AsyncIterable, Iterable
|
|
3
2
|
|
|
4
3
|
import aiohttp
|
|
5
4
|
import requests
|
|
@@ -7,7 +6,7 @@ from betterproto import Casing
|
|
|
7
6
|
|
|
8
7
|
from maitai._config import config
|
|
9
8
|
from maitai._maitai_client import MaiTaiClient
|
|
10
|
-
from maitai._types import ChunkQueue, EvaluateCallback, QueueIterable
|
|
9
|
+
from maitai._types import AsyncChunkQueue, ChunkQueue, EvaluateCallback, QueueIterable
|
|
11
10
|
from maitai_gen.chat import ChatCompletionParams, ChatCompletionRequest
|
|
12
11
|
from maitai_gen.inference import InferenceStreamResponse
|
|
13
12
|
|
|
@@ -24,11 +23,20 @@ class Inference(MaiTaiClient):
|
|
|
24
23
|
chat_request: ChatCompletionRequest = cls.create_inference_request(application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params)
|
|
25
24
|
if evaluate_callback:
|
|
26
25
|
q = ChunkQueue()
|
|
27
|
-
cls.run_async(cls.send_inference_request_async(chat_request, q, evaluate_callback))
|
|
26
|
+
cls.run_async(cls.send_inference_request_async(chat_request, chunk_queue=q, evaluation_callback=evaluate_callback))
|
|
28
27
|
return QueueIterable(q, timeout=timeout)
|
|
29
28
|
else:
|
|
30
29
|
return cls.send_inference_request(chat_request)
|
|
31
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
|
+
|
|
32
40
|
@classmethod
|
|
33
41
|
def create_inference_request(cls, application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params: ChatCompletionParams):
|
|
34
42
|
infer_request: ChatCompletionRequest = ChatCompletionRequest()
|
|
@@ -42,8 +50,6 @@ class Inference(MaiTaiClient):
|
|
|
42
50
|
|
|
43
51
|
@classmethod
|
|
44
52
|
def send_inference_request(cls, chat_request: ChatCompletionRequest) -> Iterable[InferenceStreamResponse]:
|
|
45
|
-
start = time.time()
|
|
46
|
-
|
|
47
53
|
def consume_stream():
|
|
48
54
|
host = config.maitai_host
|
|
49
55
|
url = f'{host}/chat/completions/serialized'
|
|
@@ -68,12 +74,9 @@ class Inference(MaiTaiClient):
|
|
|
68
74
|
for resp in consume_stream():
|
|
69
75
|
inference_response: InferenceStreamResponse = InferenceStreamResponse().from_json(resp)
|
|
70
76
|
yield inference_response
|
|
71
|
-
print(time.time() - start)
|
|
72
77
|
|
|
73
78
|
@classmethod
|
|
74
|
-
async def send_inference_request_async(cls, chat_request: ChatCompletionRequest, chunk_queue: ChunkQueue, evaluation_callback: EvaluateCallback):
|
|
75
|
-
start = time.time()
|
|
76
|
-
|
|
79
|
+
async def send_inference_request_async(cls, chat_request: ChatCompletionRequest, chunk_queue: ChunkQueue = None, async_chunk_queue: AsyncChunkQueue = None, evaluation_callback: EvaluateCallback = None):
|
|
77
80
|
host = config.maitai_host
|
|
78
81
|
url = f'{host}/chat/completions/serialized'
|
|
79
82
|
headers = {
|
|
@@ -85,17 +88,24 @@ class Inference(MaiTaiClient):
|
|
|
85
88
|
if response.status != 200:
|
|
86
89
|
error_text = await response.text()
|
|
87
90
|
print(f"Failed to send evaluation request. Status code: {response.status}. Error: {error_text}")
|
|
88
|
-
chunk_queue
|
|
91
|
+
if chunk_queue:
|
|
92
|
+
chunk_queue.put("done")
|
|
93
|
+
if async_chunk_queue:
|
|
94
|
+
await async_chunk_queue.put("done")
|
|
89
95
|
return
|
|
90
|
-
else:
|
|
91
|
-
print(f"Successfully sent evaluation request. Status code: {response.status}")
|
|
92
96
|
last_item = None
|
|
93
97
|
async for line in response.content:
|
|
94
98
|
if line:
|
|
95
99
|
inference_response: InferenceStreamResponse = InferenceStreamResponse().from_json(line)
|
|
96
|
-
chunk_queue
|
|
100
|
+
if chunk_queue:
|
|
101
|
+
chunk_queue.put(inference_response)
|
|
102
|
+
if async_chunk_queue:
|
|
103
|
+
await async_chunk_queue.put(inference_response)
|
|
97
104
|
last_item = inference_response
|
|
98
|
-
chunk_queue
|
|
105
|
+
if chunk_queue:
|
|
106
|
+
chunk_queue.put("done")
|
|
107
|
+
if async_chunk_queue:
|
|
108
|
+
await async_chunk_queue.put("done")
|
|
99
109
|
if last_item is not None and last_item.evaluate_response:
|
|
100
|
-
evaluation_callback
|
|
101
|
-
|
|
110
|
+
if evaluation_callback:
|
|
111
|
+
evaluation_callback(last_item.evaluate_response)
|
maitai/_openai.py
CHANGED
|
@@ -9,9 +9,11 @@ import maitai
|
|
|
9
9
|
from maitai._config import config
|
|
10
10
|
from maitai._openai_types import Body, Headers, Query
|
|
11
11
|
from maitai._types import EvaluateCallback
|
|
12
|
-
from maitai._utils import convert_open_ai_chat_completion_chunk, convert_openai_chat_completion,
|
|
12
|
+
from maitai._utils import convert_open_ai_chat_completion_chunk, convert_openai_chat_completion, get_chat_completion_params, process_chunk, process_stream_response, required_args, \
|
|
13
|
+
set_completion_evaluation_response
|
|
14
|
+
from maitai_common.processes.stream_evaluation_thread import StreamEvaluationThread
|
|
13
15
|
from maitai_common.utils.proto_utils import openai_messages_to_proto
|
|
14
|
-
from maitai_gen.chat import ChatCompletionChunk,
|
|
16
|
+
from maitai_gen.chat import ChatCompletionChunk, ChatCompletionResponse, ChatMessage, EvaluateResponse, EvaluationContentType
|
|
15
17
|
from maitai_gen.inference import InferenceStreamResponse
|
|
16
18
|
|
|
17
19
|
DEFAULT_MAX_RETRIES = 2
|
|
@@ -171,64 +173,12 @@ class Completions:
|
|
|
171
173
|
|
|
172
174
|
)
|
|
173
175
|
if stream:
|
|
174
|
-
return
|
|
176
|
+
return _process_openai_stream(session_id, reference_id, action_type, application_ref_name, messages, response, callback)
|
|
175
177
|
else:
|
|
176
178
|
maitai_completion = convert_openai_chat_completion(response)
|
|
177
179
|
proto_messages = openai_messages_to_proto(messages)
|
|
178
180
|
proto_messages.append(
|
|
179
181
|
ChatMessage(role="assistant", content=maitai_completion.choices[0].message.content))
|
|
180
|
-
if callback:
|
|
181
|
-
maitai.Evaluator.evaluate_with_callback(
|
|
182
|
-
session_id=session_id,
|
|
183
|
-
reference_id=reference_id,
|
|
184
|
-
action_type=action_type,
|
|
185
|
-
content_type=EvaluationContentType.MESSAGE,
|
|
186
|
-
content=proto_messages,
|
|
187
|
-
application_ref_name=application_ref_name,
|
|
188
|
-
callback=callback
|
|
189
|
-
)
|
|
190
|
-
return maitai_completion
|
|
191
|
-
else:
|
|
192
|
-
maitai_eval = maitai.Evaluator.evaluate(
|
|
193
|
-
session_id=session_id,
|
|
194
|
-
reference_id=reference_id,
|
|
195
|
-
action_type=action_type,
|
|
196
|
-
content_type=EvaluationContentType.MESSAGE,
|
|
197
|
-
content=proto_messages,
|
|
198
|
-
application_ref_name=application_ref_name,
|
|
199
|
-
)
|
|
200
|
-
set_completion_evaluation_response(maitai_completion, maitai_eval)
|
|
201
|
-
return maitai_completion
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
def _process_stream(session_id: Union[str, int],
|
|
205
|
-
reference_id: Union[str, int, None],
|
|
206
|
-
action_type: str,
|
|
207
|
-
application_ref_name: str,
|
|
208
|
-
messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
|
|
209
|
-
stream: Union[openai.Stream[openai_chat_types.ChatCompletionChunk], openai_chat_types.ChatCompletion],
|
|
210
|
-
callback: Optional[EvaluateCallback] = None) -> Iterable[ChatCompletionChunk]:
|
|
211
|
-
full_body = ""
|
|
212
|
-
proto_messages = openai_messages_to_proto(messages)
|
|
213
|
-
for chunk in stream:
|
|
214
|
-
maitai_chunk = convert_open_ai_chat_completion_chunk(chunk)
|
|
215
|
-
content = maitai_chunk.choices[0].delta.content
|
|
216
|
-
if content is not None:
|
|
217
|
-
full_body += content
|
|
218
|
-
if maitai_chunk.choices[0].finish_reason:
|
|
219
|
-
proto_messages.append(ChatMessage(role="assistant", content=full_body))
|
|
220
|
-
if callback:
|
|
221
|
-
yield maitai_chunk
|
|
222
|
-
maitai.Evaluator.evaluate_with_callback(
|
|
223
|
-
session_id=session_id,
|
|
224
|
-
reference_id=reference_id,
|
|
225
|
-
action_type=action_type,
|
|
226
|
-
content_type=EvaluationContentType.MESSAGE,
|
|
227
|
-
content=proto_messages,
|
|
228
|
-
application_ref_name=application_ref_name,
|
|
229
|
-
callback=callback
|
|
230
|
-
)
|
|
231
|
-
else:
|
|
232
182
|
maitai_eval = maitai.Evaluator.evaluate(
|
|
233
183
|
session_id=session_id,
|
|
234
184
|
reference_id=reference_id,
|
|
@@ -236,99 +186,54 @@ def _process_stream(session_id: Union[str, int],
|
|
|
236
186
|
content_type=EvaluationContentType.MESSAGE,
|
|
237
187
|
content=proto_messages,
|
|
238
188
|
application_ref_name=application_ref_name,
|
|
189
|
+
callback=callback,
|
|
239
190
|
)
|
|
240
|
-
|
|
241
|
-
|
|
191
|
+
if not callback:
|
|
192
|
+
set_completion_evaluation_response(maitai_completion, maitai_eval)
|
|
193
|
+
return maitai_completion
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _process_openai_stream(session_id: Union[str, int],
|
|
197
|
+
reference_id: Union[str, int, None],
|
|
198
|
+
action_type: str,
|
|
199
|
+
application_ref_name: str,
|
|
200
|
+
messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
|
|
201
|
+
stream: openai.Stream[openai_chat_types.ChatCompletionChunk],
|
|
202
|
+
callback: Optional[EvaluateCallback] = None) -> Iterable[ChatCompletionChunk]:
|
|
203
|
+
full_body = ""
|
|
204
|
+
proto_messages = openai_messages_to_proto(messages)
|
|
205
|
+
stream_eval_thread = StreamEvaluationThread()
|
|
206
|
+
stream_eval_thread.start()
|
|
207
|
+
for chunk in stream:
|
|
208
|
+
if stream_eval_thread.output:
|
|
209
|
+
result: EvaluateResponse = stream_eval_thread.output
|
|
210
|
+
stream_eval_thread.terminate()
|
|
211
|
+
new_stream = maitai.Evaluator.evaluate_realtime(session_id, reference_id, action_type, EvaluationContentType.PARTIAL, proto_messages, application_ref_name, full_body,
|
|
212
|
+
result.evaluation_results[0].description, result.evaluation_results[0].sentinel_id)
|
|
213
|
+
for new_chunk in new_stream:
|
|
214
|
+
yield new_chunk
|
|
215
|
+
return
|
|
216
|
+
maitai_chunk = convert_open_ai_chat_completion_chunk(chunk)
|
|
217
|
+
new_full_body, result_chunk = process_chunk(session_id, reference_id, action_type, application_ref_name, proto_messages, full_body, maitai_chunk, callback)
|
|
218
|
+
if new_full_body != full_body:
|
|
219
|
+
stream_eval_thread.input.append((session_id, reference_id, action_type, EvaluationContentType.PARTIAL, proto_messages, application_ref_name, new_full_body))
|
|
220
|
+
full_body = new_full_body
|
|
221
|
+
if result_chunk is not None:
|
|
222
|
+
yield result_chunk
|
|
242
223
|
break
|
|
243
224
|
yield maitai_chunk
|
|
225
|
+
stream_eval_thread.terminate()
|
|
244
226
|
|
|
245
227
|
|
|
246
228
|
def _process_inference_stream(stream: Iterable[InferenceStreamResponse], callback: EvaluateCallback) -> Iterable[ChatCompletionChunk]:
|
|
247
229
|
last_chat_completion_chunk: Optional[ChatCompletionChunk] = None
|
|
248
230
|
for infer_resp in stream:
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
maitai_chunk = last_chat_completion_chunk
|
|
252
|
-
set_chunk_evaluation_response(maitai_chunk, infer_resp.evaluate_response)
|
|
253
|
-
yield maitai_chunk
|
|
254
|
-
return
|
|
255
|
-
if infer_resp.chat_completion_chunk:
|
|
256
|
-
chunk = infer_resp.chat_completion_chunk
|
|
231
|
+
chunk = process_stream_response(infer_resp, callback, last_chat_completion_chunk)
|
|
232
|
+
if chunk is not None:
|
|
257
233
|
if chunk.choices[0].finish_reason:
|
|
258
234
|
if callback:
|
|
259
235
|
yield chunk
|
|
260
236
|
return
|
|
261
237
|
else:
|
|
262
238
|
last_chat_completion_chunk = chunk
|
|
263
|
-
|
|
264
|
-
yield chunk
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
def get_chat_completion_params(*,
|
|
268
|
-
messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
|
|
269
|
-
model: Union[str, openai_types.ChatModel],
|
|
270
|
-
frequency_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
271
|
-
logit_bias: Union[Optional[Dict[str, int]], openai.NotGiven] = openai.NOT_GIVEN,
|
|
272
|
-
logprobs: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
|
|
273
|
-
max_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
274
|
-
n: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
275
|
-
presence_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
276
|
-
response_format: Union[openai_chat_types.completion_create_params.ResponseFormat, openai.NotGiven] = openai.NOT_GIVEN,
|
|
277
|
-
seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
278
|
-
stop: Union[Union[Optional[str], List[str]], openai.NotGiven] = openai.NOT_GIVEN,
|
|
279
|
-
stream: Optional[bool] = False,
|
|
280
|
-
stream_options: Union[Optional[openai_chat_types.ChatCompletionStreamOptionsParam], openai.NotGiven] = openai.NOT_GIVEN,
|
|
281
|
-
temperature: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
282
|
-
tool_choice: Union[openai_chat_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven] = openai.NOT_GIVEN,
|
|
283
|
-
tools: Union[Iterable[openai_chat_types.ChatCompletionToolParam], openai.NotGiven] = openai.NOT_GIVEN,
|
|
284
|
-
top_logprobs: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
285
|
-
top_p: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
286
|
-
user: Union[str, openai.NotGiven] = openai.NOT_GIVEN,
|
|
287
|
-
) -> ChatCompletionParams:
|
|
288
|
-
params = ChatCompletionParams(
|
|
289
|
-
messages=openai_messages_to_proto(messages),
|
|
290
|
-
model=model,
|
|
291
|
-
stream=stream,
|
|
292
|
-
)
|
|
293
|
-
# Define all optional parameters in a dictionary
|
|
294
|
-
optional_params = {
|
|
295
|
-
'max_tokens': max_tokens,
|
|
296
|
-
'temperature': temperature,
|
|
297
|
-
'top_p': top_p,
|
|
298
|
-
'stop': stop,
|
|
299
|
-
'logprobs': logprobs,
|
|
300
|
-
'top_logprobs': top_logprobs,
|
|
301
|
-
'n': n,
|
|
302
|
-
'seed': seed,
|
|
303
|
-
'logit_bias': logit_bias,
|
|
304
|
-
'presence_penalty': presence_penalty,
|
|
305
|
-
'frequency_penalty': frequency_penalty,
|
|
306
|
-
'user': user,
|
|
307
|
-
'tool_choice': tool_choice,
|
|
308
|
-
}
|
|
309
|
-
# Set each parameter that is not marked as NOT_GIVEN
|
|
310
|
-
for param_name, value in optional_params.items():
|
|
311
|
-
if value != openai.NOT_GIVEN:
|
|
312
|
-
setattr(params, param_name, value)
|
|
313
|
-
|
|
314
|
-
if stream_options != openai.NOT_GIVEN and stream_options:
|
|
315
|
-
params.stream_options = StreamOptions(include_usage=stream_options.get("include_usage"))
|
|
316
|
-
|
|
317
|
-
if response_format != openai.NOT_GIVEN:
|
|
318
|
-
params.response_format = ResponseFormat(type=response_format["type"])
|
|
319
|
-
|
|
320
|
-
if tools != openai.NOT_GIVEN:
|
|
321
|
-
params.tools = []
|
|
322
|
-
for tool in tools:
|
|
323
|
-
function = tool.get("function")
|
|
324
|
-
params.tools.append(
|
|
325
|
-
Tool(
|
|
326
|
-
type=tool["type"],
|
|
327
|
-
function=Function(
|
|
328
|
-
name=function.get("name"),
|
|
329
|
-
description=function.get("description"),
|
|
330
|
-
parameters=function.get("parameters")
|
|
331
|
-
)
|
|
332
|
-
)
|
|
333
|
-
)
|
|
334
|
-
return params
|
|
239
|
+
yield chunk
|
maitai/_openai_async.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
from typing import AsyncIterable, Dict, Iterable, List, Mapping, Optional, Union
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import openai
|
|
5
|
+
import openai.types as openai_types
|
|
6
|
+
import openai.types.chat as openai_chat_types
|
|
7
|
+
|
|
8
|
+
import maitai
|
|
9
|
+
from maitai._config import config
|
|
10
|
+
from maitai._openai_types import Body, Headers, Query
|
|
11
|
+
from maitai._types import EvaluateCallback
|
|
12
|
+
from maitai._utils import convert_open_ai_chat_completion_chunk, convert_openai_chat_completion, get_chat_completion_params, process_chunk, process_stream_response, required_args, \
|
|
13
|
+
set_completion_evaluation_response
|
|
14
|
+
from maitai_common.processes.stream_evaluation_thread import StreamEvaluationThread
|
|
15
|
+
from maitai_common.utils.proto_utils import openai_messages_to_proto
|
|
16
|
+
from maitai_gen.chat import ChatCompletionChunk, ChatCompletionResponse, ChatMessage, EvaluateResponse, EvaluationContentType
|
|
17
|
+
from maitai_gen.inference import InferenceStreamResponse
|
|
18
|
+
|
|
19
|
+
DEFAULT_MAX_RETRIES = 2
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class MaiTaiAsyncOpenAIClient:
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
*,
|
|
26
|
+
maitai_api_key: Optional[str] = None,
|
|
27
|
+
api_key: Optional[str] = None,
|
|
28
|
+
organization: Optional[str] = None,
|
|
29
|
+
project: Optional[str] = None,
|
|
30
|
+
base_url: Union[str, httpx.URL, None] = None,
|
|
31
|
+
timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NOT_GIVEN,
|
|
32
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
33
|
+
default_headers: Optional[Mapping[str, str]] = None,
|
|
34
|
+
default_query: Optional[Mapping[str, object]] = None,
|
|
35
|
+
http_client: Optional[httpx.Client] = None,
|
|
36
|
+
_strict_response_validation: bool = False,
|
|
37
|
+
|
|
38
|
+
):
|
|
39
|
+
if maitai_api_key:
|
|
40
|
+
config.initialize(maitai_api_key)
|
|
41
|
+
self.client = openai.AsyncClient(
|
|
42
|
+
api_key=api_key,
|
|
43
|
+
organization=organization,
|
|
44
|
+
project=project,
|
|
45
|
+
base_url=base_url,
|
|
46
|
+
timeout=timeout,
|
|
47
|
+
max_retries=max_retries,
|
|
48
|
+
default_headers=default_headers,
|
|
49
|
+
default_query=default_query,
|
|
50
|
+
http_client=http_client,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
self.chat = AsyncChat(self.client)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class AsyncChat:
|
|
57
|
+
def __init__(self, client=None):
|
|
58
|
+
self.completions = AsyncCompletions(client)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class AsyncCompletions:
|
|
62
|
+
def __init__(self, client: Optional[openai.AsyncClient] = None):
|
|
63
|
+
if client is None:
|
|
64
|
+
client = openai.AsyncClient()
|
|
65
|
+
self.client = client
|
|
66
|
+
|
|
67
|
+
@required_args(["session_id", "action_type", "application_ref_name", "messages", "model"],
|
|
68
|
+
["session_id", "action_type", "application_ref_name", "messages", "model", "stream"])
|
|
69
|
+
async def create(
|
|
70
|
+
self,
|
|
71
|
+
*,
|
|
72
|
+
# Maitai Arguments
|
|
73
|
+
session_id: Union[str, int] = None,
|
|
74
|
+
reference_id: Union[str, int, None] = None,
|
|
75
|
+
action_type: str = None,
|
|
76
|
+
application_ref_name: str = None,
|
|
77
|
+
callback: Optional[EvaluateCallback] = None,
|
|
78
|
+
server_side_inference: bool = False, # TODO make this a config item
|
|
79
|
+
# OpenAI Arguments
|
|
80
|
+
messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
|
|
81
|
+
model: Union[str, openai_types.ChatModel],
|
|
82
|
+
frequency_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
83
|
+
function_call: Union[openai_chat_types.completion_create_params.FunctionCall, openai.NotGiven] = openai.NOT_GIVEN,
|
|
84
|
+
functions: Union[Iterable[openai_chat_types.completion_create_params.Function], openai.NotGiven] = openai.NOT_GIVEN,
|
|
85
|
+
logit_bias: Union[Optional[Dict[str, int]], openai.NotGiven] = openai.NOT_GIVEN,
|
|
86
|
+
logprobs: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
|
|
87
|
+
max_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
88
|
+
n: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
89
|
+
presence_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
90
|
+
response_format: Union[openai_chat_types.completion_create_params.ResponseFormat, openai.NotGiven] = openai.NOT_GIVEN,
|
|
91
|
+
seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
92
|
+
stop: Union[Union[Optional[str], List[str]], openai.NotGiven] = openai.NOT_GIVEN,
|
|
93
|
+
stream: Optional[bool] = False,
|
|
94
|
+
stream_options: Union[Optional[openai_chat_types.ChatCompletionStreamOptionsParam], openai.NotGiven] = openai.NOT_GIVEN,
|
|
95
|
+
temperature: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
96
|
+
tool_choice: Union[openai_chat_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven] = openai.NOT_GIVEN,
|
|
97
|
+
tools: Union[Iterable[openai_chat_types.ChatCompletionToolParam], openai.NotGiven] = openai.NOT_GIVEN,
|
|
98
|
+
top_logprobs: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
99
|
+
top_p: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
100
|
+
user: Union[str, openai.NotGiven] = openai.NOT_GIVEN,
|
|
101
|
+
extra_headers: Optional[Headers] = None,
|
|
102
|
+
extra_query: Optional[Query] = None,
|
|
103
|
+
extra_body: Optional[Body] = None,
|
|
104
|
+
timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NOT_GIVEN,
|
|
105
|
+
) -> Union[ChatCompletionResponse, AsyncIterable[ChatCompletionChunk]]:
|
|
106
|
+
if not config.api_key:
|
|
107
|
+
raise ValueError("Maitai API Key has not been set")
|
|
108
|
+
if server_side_inference:
|
|
109
|
+
completion_params = get_chat_completion_params(
|
|
110
|
+
messages=messages,
|
|
111
|
+
model=model,
|
|
112
|
+
frequency_penalty=frequency_penalty,
|
|
113
|
+
logit_bias=logit_bias,
|
|
114
|
+
logprobs=logprobs,
|
|
115
|
+
max_tokens=max_tokens,
|
|
116
|
+
n=n,
|
|
117
|
+
presence_penalty=presence_penalty,
|
|
118
|
+
response_format=response_format,
|
|
119
|
+
seed=seed,
|
|
120
|
+
stop=stop,
|
|
121
|
+
stream=stream,
|
|
122
|
+
stream_options=stream_options,
|
|
123
|
+
temperature=temperature,
|
|
124
|
+
tool_choice=tool_choice,
|
|
125
|
+
tools=tools,
|
|
126
|
+
top_logprobs=top_logprobs,
|
|
127
|
+
top_p=top_p,
|
|
128
|
+
user=user,
|
|
129
|
+
)
|
|
130
|
+
response_timeout = None
|
|
131
|
+
if isinstance(timeout, float) or isinstance(timeout, int):
|
|
132
|
+
response_timeout = timeout
|
|
133
|
+
response = await maitai.Inference.infer_async(session_id, reference_id, action_type, application_ref_name, completion_params, callback, timeout=response_timeout)
|
|
134
|
+
if stream:
|
|
135
|
+
return _process_inference_stream_async(response, callback)
|
|
136
|
+
# ChatCompletion only
|
|
137
|
+
chat_completion: Optional[ChatCompletionResponse] = None
|
|
138
|
+
async for resp in response:
|
|
139
|
+
if callback:
|
|
140
|
+
return resp.chat_completion_response
|
|
141
|
+
else:
|
|
142
|
+
if resp.chat_completion_response:
|
|
143
|
+
chat_completion = resp.chat_completion_response
|
|
144
|
+
if resp.evaluate_response and chat_completion:
|
|
145
|
+
set_completion_evaluation_response(chat_completion, resp.evaluate_response)
|
|
146
|
+
return chat_completion
|
|
147
|
+
return chat_completion
|
|
148
|
+
else:
|
|
149
|
+
response = await self.client.chat.completions.create(
|
|
150
|
+
messages=messages,
|
|
151
|
+
model=model,
|
|
152
|
+
frequency_penalty=frequency_penalty,
|
|
153
|
+
function_call=function_call,
|
|
154
|
+
functions=functions,
|
|
155
|
+
logit_bias=logit_bias,
|
|
156
|
+
logprobs=logprobs,
|
|
157
|
+
max_tokens=max_tokens,
|
|
158
|
+
n=n,
|
|
159
|
+
presence_penalty=presence_penalty,
|
|
160
|
+
response_format=response_format,
|
|
161
|
+
seed=seed,
|
|
162
|
+
stop=stop,
|
|
163
|
+
stream=stream,
|
|
164
|
+
stream_options=stream_options,
|
|
165
|
+
temperature=temperature,
|
|
166
|
+
tool_choice=tool_choice,
|
|
167
|
+
tools=tools,
|
|
168
|
+
top_logprobs=top_logprobs,
|
|
169
|
+
top_p=top_p,
|
|
170
|
+
user=user,
|
|
171
|
+
extra_headers=extra_headers,
|
|
172
|
+
extra_query=extra_query,
|
|
173
|
+
extra_body=extra_body,
|
|
174
|
+
timeout=timeout,
|
|
175
|
+
|
|
176
|
+
)
|
|
177
|
+
if stream:
|
|
178
|
+
return _process_async_openai_stream(session_id, reference_id, action_type, application_ref_name, messages, response, callback)
|
|
179
|
+
else:
|
|
180
|
+
maitai_completion = convert_openai_chat_completion(response)
|
|
181
|
+
proto_messages = openai_messages_to_proto(messages)
|
|
182
|
+
proto_messages.append(
|
|
183
|
+
ChatMessage(role="assistant", content=maitai_completion.choices[0].message.content))
|
|
184
|
+
maitai_eval = await maitai.Evaluator.evaluate_async(
|
|
185
|
+
session_id=session_id,
|
|
186
|
+
reference_id=reference_id,
|
|
187
|
+
action_type=action_type,
|
|
188
|
+
content_type=EvaluationContentType.MESSAGE,
|
|
189
|
+
content=proto_messages,
|
|
190
|
+
application_ref_name=application_ref_name,
|
|
191
|
+
callback=callback,
|
|
192
|
+
)
|
|
193
|
+
if not callback:
|
|
194
|
+
set_completion_evaluation_response(maitai_completion, maitai_eval)
|
|
195
|
+
return maitai_completion
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
async def _process_async_openai_stream(session_id: Union[str, int],
|
|
199
|
+
reference_id: Union[str, int, None],
|
|
200
|
+
action_type: str,
|
|
201
|
+
application_ref_name: str,
|
|
202
|
+
messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
|
|
203
|
+
stream: openai.AsyncStream[openai_chat_types.ChatCompletionChunk],
|
|
204
|
+
callback: Optional[EvaluateCallback] = None) -> AsyncIterable[ChatCompletionChunk]:
|
|
205
|
+
full_body = ""
|
|
206
|
+
proto_messages = openai_messages_to_proto(messages)
|
|
207
|
+
stream_eval_thread = StreamEvaluationThread()
|
|
208
|
+
stream_eval_thread.start()
|
|
209
|
+
async for chunk in stream:
|
|
210
|
+
if stream_eval_thread.output:
|
|
211
|
+
result: EvaluateResponse = stream_eval_thread.output
|
|
212
|
+
stream_eval_thread.terminate()
|
|
213
|
+
new_stream = maitai.Evaluator.evaluate_realtime(session_id, reference_id, action_type, EvaluationContentType.PARTIAL, proto_messages, application_ref_name, full_body,
|
|
214
|
+
result.evaluation_results[0].description, result.evaluation_results[0].sentinel_id)
|
|
215
|
+
for new_chunk in new_stream:
|
|
216
|
+
yield new_chunk
|
|
217
|
+
return
|
|
218
|
+
maitai_chunk = convert_open_ai_chat_completion_chunk(chunk)
|
|
219
|
+
new_full_body, result_chunk = process_chunk(session_id, reference_id, action_type, application_ref_name, proto_messages, full_body, maitai_chunk, callback)
|
|
220
|
+
if new_full_body != full_body:
|
|
221
|
+
stream_eval_thread.input.append((session_id, reference_id, action_type, EvaluationContentType.PARTIAL, proto_messages, application_ref_name, new_full_body))
|
|
222
|
+
full_body = new_full_body
|
|
223
|
+
if result_chunk is not None:
|
|
224
|
+
yield result_chunk
|
|
225
|
+
break
|
|
226
|
+
yield maitai_chunk
|
|
227
|
+
stream_eval_thread.terminate()
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
async def _process_inference_stream_async(stream: AsyncIterable[InferenceStreamResponse], callback: EvaluateCallback) -> AsyncIterable[ChatCompletionChunk]:
|
|
231
|
+
last_chat_completion_chunk: Optional[ChatCompletionChunk] = None
|
|
232
|
+
async for infer_resp in stream:
|
|
233
|
+
chunk = process_stream_response(infer_resp, callback, last_chat_completion_chunk)
|
|
234
|
+
if chunk is not None:
|
|
235
|
+
if chunk.choices[0].finish_reason:
|
|
236
|
+
if callback:
|
|
237
|
+
yield chunk
|
|
238
|
+
return
|
|
239
|
+
else:
|
|
240
|
+
last_chat_completion_chunk = chunk
|
|
241
|
+
yield chunk
|
maitai/_types.py
CHANGED
|
@@ -1,18 +1,24 @@
|
|
|
1
|
+
import asyncio
|
|
1
2
|
import queue
|
|
2
3
|
from typing import Callable, Union
|
|
3
4
|
|
|
4
5
|
import maitai_gen.chat as chat_types
|
|
5
|
-
from maitai_gen.chat import
|
|
6
|
+
from maitai_gen.chat import *
|
|
6
7
|
|
|
7
8
|
ChunkQueue = queue.Queue[Union[chat_types.ChatCompletionChunk, "done"]]
|
|
9
|
+
AsyncChunkQueue = asyncio.Queue[Union[chat_types.ChatCompletionChunk, "done"]]
|
|
8
10
|
|
|
9
11
|
|
|
10
12
|
class QueueIterable:
|
|
11
|
-
def __init__(self, chunk_queue: ChunkQueue, timeout=None) -> None:
|
|
13
|
+
def __init__(self, chunk_queue: Union[ChunkQueue, AsyncChunkQueue], timeout=None) -> None:
|
|
12
14
|
self.queue = chunk_queue
|
|
13
15
|
self.done = False # Indicates if "done" token has been received
|
|
14
16
|
self.timeout = timeout
|
|
15
17
|
|
|
18
|
+
def __aiter__(self):
|
|
19
|
+
"""Returns the asynchronous iterator object itself."""
|
|
20
|
+
return self
|
|
21
|
+
|
|
16
22
|
def __iter__(self):
|
|
17
23
|
"""Returns the iterator object itself."""
|
|
18
24
|
return self
|
|
@@ -33,5 +39,28 @@ class QueueIterable:
|
|
|
33
39
|
raise TimeoutError
|
|
34
40
|
raise StopIteration
|
|
35
41
|
|
|
42
|
+
async def __anext__(self) -> chat_types.ChatCompletionChunk:
|
|
43
|
+
"""Waits for the next item from the queue or raises StopAsyncIteration if "done"."""
|
|
44
|
+
if self.done:
|
|
45
|
+
raise StopAsyncIteration
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
# Wait for an item from the queue with a timeout if specified
|
|
49
|
+
if self.timeout:
|
|
50
|
+
item = await asyncio.wait_for(self.queue.get(), timeout=self.timeout)
|
|
51
|
+
else:
|
|
52
|
+
item = await self.queue.get()
|
|
53
|
+
|
|
54
|
+
if item == "done":
|
|
55
|
+
self.done = True # Set done to True to prevent further blocking
|
|
56
|
+
raise StopAsyncIteration
|
|
57
|
+
|
|
58
|
+
return item
|
|
59
|
+
|
|
60
|
+
except asyncio.TimeoutError:
|
|
61
|
+
print("Queue timed out")
|
|
62
|
+
self.done = True
|
|
63
|
+
raise StopAsyncIteration
|
|
64
|
+
|
|
36
65
|
|
|
37
66
|
EvaluateCallback = Callable[[EvaluateResponse], None]
|
maitai/_utils.py
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import functools
|
|
2
2
|
import inspect
|
|
3
|
-
from typing import Any, Callable, Sequence, TypeVar, Union
|
|
3
|
+
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union
|
|
4
4
|
|
|
5
|
+
import openai
|
|
5
6
|
import openai.types.chat as openai_types
|
|
7
|
+
from openai.types import ChatModel
|
|
6
8
|
|
|
7
9
|
import maitai_gen.chat as chat_types
|
|
8
|
-
from
|
|
10
|
+
from maitai import Evaluator
|
|
11
|
+
from maitai._types import EvaluateCallback
|
|
12
|
+
from maitai_common.utils.proto_utils import openai_messages_to_proto
|
|
13
|
+
from maitai_gen.chat import ChatCompletionParams, EvaluateResponse, Function, ResponseFormat, StreamOptions, Tool
|
|
14
|
+
from maitai_gen.inference import InferenceStreamResponse
|
|
9
15
|
|
|
10
16
|
CallableT = TypeVar("CallableT", bound=Callable[..., Any])
|
|
11
17
|
|
|
@@ -110,3 +116,120 @@ def set_chunk_evaluation_response(chunk: chat_types.ChatCompletionChunk, respons
|
|
|
110
116
|
|
|
111
117
|
def convert_open_ai_chat_completion_chunk(chunk: openai_types.ChatCompletionChunk) -> chat_types.ChatCompletionChunk:
|
|
112
118
|
return chat_types.ChatCompletionChunk().from_dict(chunk.to_dict())
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def get_chat_completion_params(*,
|
|
122
|
+
messages: Iterable[openai_types.ChatCompletionMessageParam],
|
|
123
|
+
model: Union[str, ChatModel],
|
|
124
|
+
frequency_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
125
|
+
logit_bias: Union[Optional[Dict[str, int]], openai.NotGiven] = openai.NOT_GIVEN,
|
|
126
|
+
logprobs: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
|
|
127
|
+
max_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
128
|
+
n: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
129
|
+
presence_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
130
|
+
response_format: Union[openai_types.completion_create_params.ResponseFormat, openai.NotGiven] = openai.NOT_GIVEN,
|
|
131
|
+
seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
132
|
+
stop: Union[Union[Optional[str], List[str]], openai.NotGiven] = openai.NOT_GIVEN,
|
|
133
|
+
stream: Optional[bool] = False,
|
|
134
|
+
stream_options: Union[Optional[openai_types.ChatCompletionStreamOptionsParam], openai.NotGiven] = openai.NOT_GIVEN,
|
|
135
|
+
temperature: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
136
|
+
tool_choice: Union[openai_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven] = openai.NOT_GIVEN,
|
|
137
|
+
tools: Union[Iterable[openai_types.ChatCompletionToolParam], openai.NotGiven] = openai.NOT_GIVEN,
|
|
138
|
+
top_logprobs: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
139
|
+
top_p: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
140
|
+
user: Union[str, openai.NotGiven] = openai.NOT_GIVEN,
|
|
141
|
+
) -> ChatCompletionParams:
|
|
142
|
+
params = ChatCompletionParams(
|
|
143
|
+
messages=openai_messages_to_proto(messages),
|
|
144
|
+
model=model,
|
|
145
|
+
stream=stream,
|
|
146
|
+
)
|
|
147
|
+
# Define all optional parameters in a dictionary
|
|
148
|
+
optional_params = {
|
|
149
|
+
'max_tokens': max_tokens,
|
|
150
|
+
'temperature': temperature,
|
|
151
|
+
'top_p': top_p,
|
|
152
|
+
'stop': stop,
|
|
153
|
+
'logprobs': logprobs,
|
|
154
|
+
'top_logprobs': top_logprobs,
|
|
155
|
+
'n': n,
|
|
156
|
+
'seed': seed,
|
|
157
|
+
'logit_bias': logit_bias,
|
|
158
|
+
'presence_penalty': presence_penalty,
|
|
159
|
+
'frequency_penalty': frequency_penalty,
|
|
160
|
+
'user': user,
|
|
161
|
+
'tool_choice': tool_choice,
|
|
162
|
+
}
|
|
163
|
+
# Set each parameter that is not marked as NOT_GIVEN
|
|
164
|
+
for param_name, value in optional_params.items():
|
|
165
|
+
if value != openai.NOT_GIVEN:
|
|
166
|
+
setattr(params, param_name, value)
|
|
167
|
+
|
|
168
|
+
if stream_options != openai.NOT_GIVEN and stream_options:
|
|
169
|
+
params.stream_options = StreamOptions(include_usage=stream_options.get("include_usage"))
|
|
170
|
+
|
|
171
|
+
if response_format != openai.NOT_GIVEN:
|
|
172
|
+
params.response_format = ResponseFormat(type=response_format["type"])
|
|
173
|
+
|
|
174
|
+
if tools != openai.NOT_GIVEN:
|
|
175
|
+
params.tools = []
|
|
176
|
+
for tool in tools:
|
|
177
|
+
function = tool.get("function")
|
|
178
|
+
params.tools.append(
|
|
179
|
+
Tool(
|
|
180
|
+
type=tool["type"],
|
|
181
|
+
function=Function(
|
|
182
|
+
name=function.get("name"),
|
|
183
|
+
description=function.get("description"),
|
|
184
|
+
parameters=function.get("parameters")
|
|
185
|
+
)
|
|
186
|
+
)
|
|
187
|
+
)
|
|
188
|
+
return params
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def process_stream_response(infer_resp: InferenceStreamResponse, callback: EvaluateCallback,
|
|
192
|
+
last_chat_completion_chunk: Optional[chat_types.ChatCompletionChunk]) -> Union[chat_types.ChatCompletionChunk, None]:
|
|
193
|
+
if infer_resp.evaluate_response:
|
|
194
|
+
if not callback:
|
|
195
|
+
maitai_chunk = last_chat_completion_chunk
|
|
196
|
+
set_chunk_evaluation_response(maitai_chunk, infer_resp.evaluate_response)
|
|
197
|
+
return maitai_chunk
|
|
198
|
+
|
|
199
|
+
if infer_resp.chat_completion_chunk:
|
|
200
|
+
chunk = infer_resp.chat_completion_chunk
|
|
201
|
+
if chunk.choices[0].finish_reason:
|
|
202
|
+
if callback:
|
|
203
|
+
return chunk
|
|
204
|
+
else:
|
|
205
|
+
return chunk
|
|
206
|
+
return chunk
|
|
207
|
+
return None
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def process_chunk(session_id: Union[str, int],
|
|
211
|
+
reference_id: Union[str, int, None],
|
|
212
|
+
action_type: str,
|
|
213
|
+
application_ref_name: str,
|
|
214
|
+
proto_messages: list,
|
|
215
|
+
full_body: str,
|
|
216
|
+
maitai_chunk: chat_types.ChatCompletionChunk,
|
|
217
|
+
callback: Optional[EvaluateCallback]) -> Tuple[str, Optional[chat_types.ChatCompletionChunk]]:
|
|
218
|
+
content = maitai_chunk.choices[0].delta.content
|
|
219
|
+
if content is not None:
|
|
220
|
+
full_body += content
|
|
221
|
+
if maitai_chunk.choices[0].finish_reason:
|
|
222
|
+
proto_messages.append(chat_types.ChatMessage(role="assistant", content=full_body))
|
|
223
|
+
maitai_eval = Evaluator.evaluate(
|
|
224
|
+
session_id=session_id,
|
|
225
|
+
reference_id=reference_id,
|
|
226
|
+
action_type=action_type,
|
|
227
|
+
content_type=chat_types.EvaluationContentType.MESSAGE,
|
|
228
|
+
content=proto_messages,
|
|
229
|
+
application_ref_name=application_ref_name,
|
|
230
|
+
callback=callback
|
|
231
|
+
)
|
|
232
|
+
if not callback:
|
|
233
|
+
maitai_chunk.evaluate_response = maitai_eval
|
|
234
|
+
return full_body, maitai_chunk
|
|
235
|
+
return full_body, None
|
|
@@ -32,7 +32,7 @@ class IOThread(Thread):
|
|
|
32
32
|
try:
|
|
33
33
|
self.process()
|
|
34
34
|
except Exception as e:
|
|
35
|
-
print(e, f'[{self.child_name}] Exception hit processing')
|
|
35
|
+
self.print(e, f'[{self.child_name}] Exception hit processing')
|
|
36
36
|
finally:
|
|
37
37
|
self.is_running = False
|
|
38
38
|
|
|
@@ -53,10 +53,13 @@ class IOThread(Thread):
|
|
|
53
53
|
if self.timer_thread is not None:
|
|
54
54
|
self.timer_thread.cancel()
|
|
55
55
|
self.cleaned = True
|
|
56
|
-
print(f'{self.child_name} cleaned up')
|
|
56
|
+
self.print(f'{self.child_name} cleaned up')
|
|
57
57
|
|
|
58
58
|
def process(self):
|
|
59
59
|
return None
|
|
60
60
|
|
|
61
61
|
def initialize(self):
|
|
62
62
|
self.initialized = True
|
|
63
|
+
|
|
64
|
+
def print(self, *args, **kwargs):
|
|
65
|
+
print(*args, **kwargs)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import maitai
|
|
2
|
+
from maitai_common.processes.io_thread import IOThread
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class StreamEvaluationThread(IOThread):
|
|
6
|
+
def __init__(self):
|
|
7
|
+
super(StreamEvaluationThread, self).__init__(interval=0.01)
|
|
8
|
+
self.input = []
|
|
9
|
+
self.output = []
|
|
10
|
+
|
|
11
|
+
def process(self):
|
|
12
|
+
if len(self.input) == 0:
|
|
13
|
+
return
|
|
14
|
+
input_list = self.input
|
|
15
|
+
self.input = []
|
|
16
|
+
session_id, reference_id, action_type, content_type, proto_messages, application_ref_name, partial = input_list.pop()
|
|
17
|
+
result = maitai.Evaluator.evaluate(session_id, reference_id, action_type, proto_messages, content_type=content_type, application_ref_name=application_ref_name, partial=partial)
|
|
18
|
+
if len(result.evaluation_results) > 0:
|
|
19
|
+
if result.evaluation_results[0].status == "FAULT":
|
|
20
|
+
self.output = result
|
|
21
|
+
|
|
22
|
+
def print(self, *args, **kwargs):
|
|
23
|
+
pass
|
maitai_gen/chat/__init__.py
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
from dataclasses import dataclass
|
|
7
7
|
from typing import (
|
|
8
8
|
TYPE_CHECKING,
|
|
9
|
+
AsyncIterator,
|
|
9
10
|
Dict,
|
|
10
11
|
List,
|
|
11
12
|
Optional,
|
|
@@ -27,6 +28,7 @@ if TYPE_CHECKING:
|
|
|
27
28
|
class EvaluationContentType(betterproto.Enum):
|
|
28
29
|
MESSAGE = 0
|
|
29
30
|
TEXT = 1
|
|
31
|
+
PARTIAL = 2
|
|
30
32
|
|
|
31
33
|
|
|
32
34
|
@dataclass(eq=False, repr=False)
|
|
@@ -202,6 +204,8 @@ class EvaluateRequest(betterproto.Message):
|
|
|
202
204
|
text_content: str = betterproto.string_field(9)
|
|
203
205
|
message_content: List["ChatMessage"] = betterproto.message_field(12)
|
|
204
206
|
request_id: str = betterproto.string_field(14)
|
|
207
|
+
sentinel_id: int = betterproto.int64_field(15)
|
|
208
|
+
fault_description: str = betterproto.string_field(16)
|
|
205
209
|
|
|
206
210
|
|
|
207
211
|
@dataclass(eq=False, repr=False)
|
|
@@ -248,12 +252,36 @@ class EvaluationServiceStub(betterproto.ServiceStub):
|
|
|
248
252
|
metadata=metadata,
|
|
249
253
|
)
|
|
250
254
|
|
|
255
|
+
async def evaluate_realtime(
|
|
256
|
+
self,
|
|
257
|
+
evaluate_request: "EvaluateRequest",
|
|
258
|
+
*,
|
|
259
|
+
timeout: Optional[float] = None,
|
|
260
|
+
deadline: Optional["Deadline"] = None,
|
|
261
|
+
metadata: Optional["MetadataLike"] = None
|
|
262
|
+
) -> AsyncIterator["ChatCompletionChunk"]:
|
|
263
|
+
async for response in self._unary_stream(
|
|
264
|
+
"/chat.EvaluationService/EvaluateRealtime",
|
|
265
|
+
evaluate_request,
|
|
266
|
+
ChatCompletionChunk,
|
|
267
|
+
timeout=timeout,
|
|
268
|
+
deadline=deadline,
|
|
269
|
+
metadata=metadata,
|
|
270
|
+
):
|
|
271
|
+
yield response
|
|
272
|
+
|
|
251
273
|
|
|
252
274
|
class EvaluationServiceBase(ServiceBase):
|
|
253
275
|
|
|
254
276
|
async def evaluate(self, evaluate_request: "EvaluateRequest") -> "EvaluateResponse":
|
|
255
277
|
raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
|
|
256
278
|
|
|
279
|
+
async def evaluate_realtime(
|
|
280
|
+
self, evaluate_request: "EvaluateRequest"
|
|
281
|
+
) -> AsyncIterator["ChatCompletionChunk"]:
|
|
282
|
+
raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
|
|
283
|
+
yield ChatCompletionChunk()
|
|
284
|
+
|
|
257
285
|
async def __rpc_evaluate(
|
|
258
286
|
self, stream: "grpclib.server.Stream[EvaluateRequest, EvaluateResponse]"
|
|
259
287
|
) -> None:
|
|
@@ -261,6 +289,16 @@ class EvaluationServiceBase(ServiceBase):
|
|
|
261
289
|
response = await self.evaluate(request)
|
|
262
290
|
await stream.send_message(response)
|
|
263
291
|
|
|
292
|
+
async def __rpc_evaluate_realtime(
|
|
293
|
+
self, stream: "grpclib.server.Stream[EvaluateRequest, ChatCompletionChunk]"
|
|
294
|
+
) -> None:
|
|
295
|
+
request = await stream.recv_message()
|
|
296
|
+
await self._call_rpc_handler_server_stream(
|
|
297
|
+
self.evaluate_realtime,
|
|
298
|
+
stream,
|
|
299
|
+
request,
|
|
300
|
+
)
|
|
301
|
+
|
|
264
302
|
def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
|
|
265
303
|
return {
|
|
266
304
|
"/chat.EvaluationService/Evaluate": grpclib.const.Handler(
|
|
@@ -269,4 +307,10 @@ class EvaluationServiceBase(ServiceBase):
|
|
|
269
307
|
EvaluateRequest,
|
|
270
308
|
EvaluateResponse,
|
|
271
309
|
),
|
|
310
|
+
"/chat.EvaluationService/EvaluateRealtime": grpclib.const.Handler(
|
|
311
|
+
self.__rpc_evaluate_realtime,
|
|
312
|
+
grpclib.const.Cardinality.UNARY_STREAM,
|
|
313
|
+
EvaluateRequest,
|
|
314
|
+
ChatCompletionChunk,
|
|
315
|
+
),
|
|
272
316
|
}
|
|
@@ -1,29 +1,31 @@
|
|
|
1
|
-
maitai/__init__.py,sha256=
|
|
1
|
+
maitai/__init__.py,sha256=cz2wNmyYNHmGxRxerFYwXmqicre9rs86zlLJu2WFFpA,531
|
|
2
2
|
maitai/_config.py,sha256=vIEc57aNF7FsZnfFPkrm3qN_tPpRCyoLaI4-ECjf4F0,2249
|
|
3
3
|
maitai/_config_listener_thread.py,sha256=Wg8dh5K8ubmZMZJ3RWdtenGCFnhR0B5gzpqhhnMy6kM,495
|
|
4
|
-
maitai/_evaluator.py,sha256=
|
|
5
|
-
maitai/_inference.py,sha256=
|
|
4
|
+
maitai/_evaluator.py,sha256=X7ZByQqZtnCgPf1NpiX0UayOiziwqNwgY1-hMlKNQFc,14793
|
|
5
|
+
maitai/_inference.py,sha256=tIMHm5k0tgJNjMFpwb7SbzuUxpsERUceCPLRMbaZM8E,5720
|
|
6
6
|
maitai/_maitai_client.py,sha256=s-OkiBAhDND2DpcUqvnfXiv_VAfnHk5FFwThJVbyz-w,1135
|
|
7
|
-
maitai/_openai.py,sha256=
|
|
7
|
+
maitai/_openai.py,sha256=TeZomocUdUGmnGZo1vMfgilOsCPRHcZtmAJBE_vqca4,11510
|
|
8
|
+
maitai/_openai_async.py,sha256=URzUEmFE5e1aRMWq4C-SY73BInhOYefMVIG4MKOQgC0,11754
|
|
8
9
|
maitai/_openai_types.py,sha256=8OrDnYca0PSU4ICYeB0DGkVIV-sAh89_zRcJPu8h_i0,236
|
|
9
|
-
maitai/_types.py,sha256=
|
|
10
|
-
maitai/_utils.py,sha256=
|
|
10
|
+
maitai/_types.py,sha256=dOn2Sn1dojHHbwbJ_954cUb2ucD_HyjxnZz7Mnn0q_c,2324
|
|
11
|
+
maitai/_utils.py,sha256=7ryPT44zJ9c6UyLU_dvJpsNDz9iFLPUMsm2utEW5uzU,10243
|
|
11
12
|
maitai_common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
13
|
maitai_common/processes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
13
|
-
maitai_common/processes/io_thread.py,sha256=
|
|
14
|
+
maitai_common/processes/io_thread.py,sha256=Ab4P1XtfL_7vvksC7zRVGLBBsiDX6cyweZNYHqcLJ14,2057
|
|
15
|
+
maitai_common/processes/stream_evaluation_thread.py,sha256=UFUfUWsQOUZhvIthVcL5BW_bgxKvIS8Nk9C1reMsfHs,894
|
|
14
16
|
maitai_common/processes/websocket_listener_thread.py,sha256=gJg838HnG7QGki0CtNM1m86bQWBgtvL1rnCGrCRStGQ,3392
|
|
15
17
|
maitai_common/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
16
18
|
maitai_common/utils/proto_utils.py,sha256=MhJx_exWOIrroS13UDvmSon_AAJ0O6kbJ_5QApJBtWI,407
|
|
17
19
|
maitai_gen/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
18
20
|
maitai_gen/application/__init__.py,sha256=VLSzeOJinN_lJTDQT6pc52vauQF-GN3DB4QWZckC1XE,1364
|
|
19
|
-
maitai_gen/chat/__init__.py,sha256=
|
|
21
|
+
maitai_gen/chat/__init__.py,sha256=tz_86t_sK_VFWNQVxP11HCeVAtqtReBXfShqOSy0dgw,11403
|
|
20
22
|
maitai_gen/company/__init__.py,sha256=AuGIsQJzcxnkZZl5-4wEr1zWeI4d4fMXrASBu-OuXG0,641
|
|
21
23
|
maitai_gen/inference/__init__.py,sha256=pn77lTsfX9JlEwEFTEVKFAdsbnmXS_o0jzYn20SIL1k,600
|
|
22
24
|
maitai_gen/notification/__init__.py,sha256=2WaCP-EwmiPDkneJyGJnB1fpgriukmjHH2ZPgH-1XK0,1198
|
|
23
25
|
maitai_gen/sandbox/__init__.py,sha256=fX4BSSo_Qbkh4jhk56E9r5SxO44XmwGh4O3OZCAcKtI,1460
|
|
24
26
|
maitai_gen/sentinel/__init__.py,sha256=hWwzr0izFZ1qS6zhWo2ZuPS5bBCeLjxBcpamF3Xmbho,1518
|
|
25
27
|
maitai_gen/session/__init__.py,sha256=riq0bcNozstLBCkAUmcNAj6RyX7gP5IIFcBO6CLSwqA,886
|
|
26
|
-
maitai_python-1.0.
|
|
27
|
-
maitai_python-1.0.
|
|
28
|
-
maitai_python-1.0.
|
|
29
|
-
maitai_python-1.0.
|
|
28
|
+
maitai_python-1.0.2.dist-info/METADATA,sha256=dFBStI8_EvqV2O64sHzdsxTgnTe_9NPGtlxamWQcc20,1719
|
|
29
|
+
maitai_python-1.0.2.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
|
|
30
|
+
maitai_python-1.0.2.dist-info/top_level.txt,sha256=-5U1krxnwlqB-AY7nEe29ZcNvwByNc-SnBe-mph-QjI,32
|
|
31
|
+
maitai_python-1.0.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|