maitai-python 1.0.3__tar.gz → 1.0.5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {maitai_python-1.0.3 → maitai_python-1.0.5}/PKG-INFO +2 -2
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai/__init__.py +3 -3
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai/_azure.py +1 -1
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai/_config.py +10 -0
- maitai_python-1.0.5/maitai/_evaluator.py +133 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai/_inference.py +15 -15
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai/_maitai_client.py +1 -1
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai/_openai.py +73 -58
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai/_openai_async.py +75 -58
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai/_utils.py +2 -35
- maitai_python-1.0.5/maitai_common/config/config_service.py +51 -0
- maitai_python-1.0.5/maitai_gen/__init__.py +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_gen/application/__init__.py +19 -2
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_gen/chat/__init__.py +5 -3
- maitai_python-1.0.5/maitai_gen/config/__init__.py +31 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_gen/sandbox/__init__.py +6 -3
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_gen/sentinel/__init__.py +7 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_gen/session/__init__.py +1 -1
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_python.egg-info/PKG-INFO +2 -2
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_python.egg-info/SOURCES.txt +3 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/setup.py +2 -2
- maitai_python-1.0.3/maitai/_evaluator.py +0 -304
- {maitai_python-1.0.3 → maitai_python-1.0.5}/README.md +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai/_config_listener_thread.py +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai/_openai_types.py +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai/_types.py +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_common/__init__.py +0 -0
- {maitai_python-1.0.3/maitai_common/processes → maitai_python-1.0.5/maitai_common/config}/__init__.py +0 -0
- {maitai_python-1.0.3/maitai_common/utils → maitai_python-1.0.5/maitai_common/processes}/__init__.py +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_common/processes/io_thread.py +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_common/processes/stream_evaluation_thread.py +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_common/processes/websocket_listener_thread.py +0 -0
- {maitai_python-1.0.3/maitai_gen → maitai_python-1.0.5/maitai_common/utils}/__init__.py +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_common/utils/proto_utils.py +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_gen/company/__init__.py +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_gen/inference/__init__.py +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_gen/notification/__init__.py +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_python.egg-info/dependency_links.txt +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_python.egg-info/requires.txt +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/maitai_python.egg-info/top_level.txt +0 -0
- {maitai_python-1.0.3 → maitai_python-1.0.5}/setup.cfg +0 -0
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import os
|
|
2
2
|
|
|
3
3
|
import maitai._types as types
|
|
4
|
-
from maitai._azure import
|
|
4
|
+
from maitai._azure import MaitaiAsyncAzureOpenAIClient as AsyncAzureOpenAI, MaitaiAzureOpenAIClient as AzureOpenAI
|
|
5
5
|
from maitai._evaluator import Evaluator as Evaluator
|
|
6
6
|
from maitai._inference import Inference as Inference
|
|
7
|
-
from maitai._openai import
|
|
8
|
-
from maitai._openai_async import
|
|
7
|
+
from maitai._openai import MaitaiOpenAIClient as OpenAI
|
|
8
|
+
from maitai._openai_async import MaitaiAsyncOpenAIClient as AsyncOpenAI
|
|
9
9
|
|
|
10
10
|
chat = OpenAI().chat
|
|
11
11
|
|
|
@@ -3,7 +3,9 @@ import os
|
|
|
3
3
|
import requests
|
|
4
4
|
|
|
5
5
|
from maitai._config_listener_thread import ConfigListenerThread
|
|
6
|
+
from maitai_common.config import config_service
|
|
6
7
|
from maitai_gen.application import Application
|
|
8
|
+
from maitai_gen.config import Config as ActionConfig
|
|
7
9
|
|
|
8
10
|
|
|
9
11
|
class Config:
|
|
@@ -16,6 +18,7 @@ class Config:
|
|
|
16
18
|
self._company_id = None
|
|
17
19
|
self.websocket_listener_thread = None
|
|
18
20
|
self.config_listener_thread = None
|
|
21
|
+
self._application_action_configs: dict[str, dict[str, ActionConfig]] = {}
|
|
19
22
|
|
|
20
23
|
@property
|
|
21
24
|
def api_key(self):
|
|
@@ -36,6 +39,9 @@ class Config:
|
|
|
36
39
|
def get_application(self, application_ref_name: str) -> Application:
|
|
37
40
|
return self._applications.get(application_ref_name)
|
|
38
41
|
|
|
42
|
+
def get_application_action_config(self, application_ref_name: str, action_type: str) -> ActionConfig:
|
|
43
|
+
return self._application_action_configs.get(application_ref_name, {}).get(action_type, config_service.get_default_config())
|
|
44
|
+
|
|
39
45
|
def _initialize_company(self):
|
|
40
46
|
host = self.maitai_host
|
|
41
47
|
url = f'{host}/company/'
|
|
@@ -59,6 +65,10 @@ class Config:
|
|
|
59
65
|
applications = [Application().from_dict(app_json) for app_json in response.json()]
|
|
60
66
|
for application in applications:
|
|
61
67
|
self._applications[application.application_ref_name] = application
|
|
68
|
+
for action_type in application.action_types:
|
|
69
|
+
if application.application_ref_name not in self._application_action_configs:
|
|
70
|
+
self._application_action_configs[application.application_ref_name] = {}
|
|
71
|
+
self._application_action_configs[application.application_ref_name][action_type.action_type] = action_type.meta
|
|
62
72
|
|
|
63
73
|
def _initialize_websocket(self):
|
|
64
74
|
self.config_listener_thread = ConfigListenerThread(self, self.maitai_ws, "APPLICATION_CONFIG_CHANGE", self._company_id)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import traceback
|
|
3
|
+
from typing import Iterable
|
|
4
|
+
|
|
5
|
+
import aiohttp
|
|
6
|
+
import requests
|
|
7
|
+
from betterproto import Casing
|
|
8
|
+
|
|
9
|
+
from maitai._config import config
|
|
10
|
+
from maitai._maitai_client import MaitaiClient
|
|
11
|
+
from maitai._types import EvaluateCallback
|
|
12
|
+
from maitai_gen.chat import ChatCompletionChunk, EvaluateRequest, EvaluateResponse, EvaluationContentType
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _get_content_type(content, partial=None):
|
|
16
|
+
if partial is not None:
|
|
17
|
+
return EvaluateResponse.PARTIAL_CONTENT
|
|
18
|
+
if isinstance(content, str):
|
|
19
|
+
return EvaluationContentType.TEXT
|
|
20
|
+
elif isinstance(content, list):
|
|
21
|
+
return EvaluationContentType.MESSAGE
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Evaluator(MaitaiClient):
|
|
25
|
+
|
|
26
|
+
def __init__(self):
|
|
27
|
+
super().__init__()
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
async def evaluate_async(cls, session_id, reference_id, action_type, content, content_type=None, application_id=None, application_ref_name=None, callback=None):
|
|
31
|
+
if content_type is None:
|
|
32
|
+
content_type = _get_content_type(content)
|
|
33
|
+
if content_type is None:
|
|
34
|
+
raise Exception('Unable to automatically determine content_type')
|
|
35
|
+
if application_id is None and application_ref_name is None:
|
|
36
|
+
raise Exception('application_id or application_ref_name must be provided')
|
|
37
|
+
eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id, reference_id, action_type, content_type, content)
|
|
38
|
+
await asyncio.create_task(cls.send_evaluation_request_async(eval_request, callback))
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def evaluate(cls, session_id, reference_id, action_type, content, content_type=None, application_id=None, application_ref_name=None, callback=None, partial=None):
|
|
42
|
+
if content_type is None:
|
|
43
|
+
content_type = _get_content_type(content, partial)
|
|
44
|
+
if content_type is None:
|
|
45
|
+
raise Exception('Unable to automatically determine content_type')
|
|
46
|
+
if application_id is None and application_ref_name is None:
|
|
47
|
+
raise Exception('application_id or application_ref_name must be provided')
|
|
48
|
+
eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id, reference_id, action_type, content_type, content, partial=partial)
|
|
49
|
+
cls.run_async(cls.send_evaluation_request_async(eval_request, callback))
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def evaluate_realtime(cls, session_id, reference_id, action_type, content_type, content, application_ref_name, partial, fault_description, sentinel_id):
|
|
53
|
+
eval_request: EvaluateRequest = cls.create_eval_request(None, application_ref_name, session_id, reference_id, action_type, content_type, content, partial=partial,
|
|
54
|
+
fault_description=fault_description)
|
|
55
|
+
eval_request.sentinel_id = sentinel_id
|
|
56
|
+
return cls.send_realtime_eval_request(eval_request)
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def create_eval_request(cls, application_id, application_ref_name, session_id, reference_id, action_type,
|
|
60
|
+
content_type, content, partial=None, fault_description=None):
|
|
61
|
+
eval_request: EvaluateRequest = EvaluateRequest()
|
|
62
|
+
eval_request.evaluation_content_type = content_type
|
|
63
|
+
if content_type == EvaluationContentType.TEXT:
|
|
64
|
+
if type(content) != str:
|
|
65
|
+
raise Exception('Content must be a string')
|
|
66
|
+
eval_request.text_content = content
|
|
67
|
+
elif content_type == EvaluationContentType.MESSAGE:
|
|
68
|
+
eval_request.message_content = content
|
|
69
|
+
elif content_type == EvaluationContentType.PARTIAL:
|
|
70
|
+
eval_request.message_content = content
|
|
71
|
+
eval_request.text_content = partial
|
|
72
|
+
eval_request.application_id = application_id
|
|
73
|
+
eval_request.application_ref_name = application_ref_name
|
|
74
|
+
eval_request.session_id = session_id
|
|
75
|
+
eval_request.reference_id = reference_id
|
|
76
|
+
eval_request.action_type = action_type
|
|
77
|
+
if fault_description:
|
|
78
|
+
eval_request.fault_description = fault_description
|
|
79
|
+
return eval_request
|
|
80
|
+
|
|
81
|
+
@classmethod
|
|
82
|
+
async def send_evaluation_request_async(cls, eval_request: EvaluateRequest, callback: EvaluateCallback = None):
|
|
83
|
+
async def send_request():
|
|
84
|
+
host = config.maitai_host
|
|
85
|
+
url = f'{host}/evaluation/request'
|
|
86
|
+
headers = {
|
|
87
|
+
'Content-Type': 'application/json',
|
|
88
|
+
'x-api-key': config.api_key
|
|
89
|
+
}
|
|
90
|
+
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
|
|
91
|
+
async with session.post(url, headers=headers,
|
|
92
|
+
data=eval_request.to_json(casing=Casing.SNAKE)) as response:
|
|
93
|
+
if response.status != 200:
|
|
94
|
+
error_text = await response.text()
|
|
95
|
+
print(f"Failed to send evaluation request. Status code: {response.status}. Error: {error_text}")
|
|
96
|
+
return None
|
|
97
|
+
return await response.read()
|
|
98
|
+
|
|
99
|
+
result = await send_request()
|
|
100
|
+
if result is not None:
|
|
101
|
+
eval_result = EvaluateResponse().from_json(result)
|
|
102
|
+
if callback is not None:
|
|
103
|
+
try:
|
|
104
|
+
callback(eval_result)
|
|
105
|
+
except:
|
|
106
|
+
traceback.print_exc()
|
|
107
|
+
else:
|
|
108
|
+
return eval_result
|
|
109
|
+
|
|
110
|
+
@classmethod
|
|
111
|
+
def send_realtime_eval_request(cls, eval_request: EvaluateRequest) -> Iterable[ChatCompletionChunk]:
|
|
112
|
+
def consume_stream():
|
|
113
|
+
host = config.maitai_host
|
|
114
|
+
url = f'{host}/evaluation/realtime'
|
|
115
|
+
headers = {
|
|
116
|
+
'Content-Type': 'application/json',
|
|
117
|
+
'x-api-key': config.api_key
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
response = requests.post(url, headers=headers, data=eval_request.to_json(casing=Casing.SNAKE), verify=False, stream=True)
|
|
121
|
+
if response.status_code != 200:
|
|
122
|
+
print(f"Failed to send realtime evaluation request. Status code: {response.status_code}. Error: {response.text}")
|
|
123
|
+
return
|
|
124
|
+
try:
|
|
125
|
+
for line in response.iter_lines():
|
|
126
|
+
if line:
|
|
127
|
+
yield line
|
|
128
|
+
finally:
|
|
129
|
+
response.close()
|
|
130
|
+
|
|
131
|
+
for resp in consume_stream():
|
|
132
|
+
inference_response: ChatCompletionChunk = ChatCompletionChunk().from_json(resp)
|
|
133
|
+
yield inference_response
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import traceback
|
|
1
2
|
from typing import AsyncIterable, Iterable
|
|
2
3
|
|
|
3
4
|
import aiohttp
|
|
@@ -5,22 +6,21 @@ import requests
|
|
|
5
6
|
from betterproto import Casing
|
|
6
7
|
|
|
7
8
|
from maitai._config import config
|
|
8
|
-
from maitai._maitai_client import
|
|
9
|
+
from maitai._maitai_client import MaitaiClient
|
|
9
10
|
from maitai._types import AsyncChunkQueue, ChunkQueue, EvaluateCallback, QueueIterable
|
|
10
11
|
from maitai_gen.chat import ChatCompletionParams, ChatCompletionRequest
|
|
11
12
|
from maitai_gen.inference import InferenceStreamResponse
|
|
12
13
|
|
|
13
14
|
|
|
14
|
-
class Inference(
|
|
15
|
+
class Inference(MaitaiClient):
|
|
15
16
|
|
|
16
17
|
def __init__(self):
|
|
17
18
|
super().__init__()
|
|
18
19
|
|
|
19
20
|
@classmethod
|
|
20
|
-
def infer(cls, session_id, reference_id, action_type, application_ref_name, completion_params: ChatCompletionParams, evaluate_callback: EvaluateCallback = None,
|
|
21
|
+
def infer(cls, session_id, reference_id, action_type, application_ref_name, completion_params: ChatCompletionParams, apply_corrections: bool, evaluation_enabled: bool, evaluate_callback: EvaluateCallback = None,
|
|
21
22
|
timeout=None) -> Iterable[InferenceStreamResponse]:
|
|
22
|
-
|
|
23
|
-
chat_request: ChatCompletionRequest = cls.create_inference_request(application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params)
|
|
23
|
+
chat_request: ChatCompletionRequest = cls.create_inference_request(application_ref_name, session_id, reference_id, action_type, apply_corrections, evaluation_enabled, completion_params)
|
|
24
24
|
if evaluate_callback:
|
|
25
25
|
q = ChunkQueue()
|
|
26
26
|
cls.run_async(cls.send_inference_request_async(chat_request, chunk_queue=q, evaluation_callback=evaluate_callback))
|
|
@@ -29,16 +29,16 @@ class Inference(MaiTaiClient):
|
|
|
29
29
|
return cls.send_inference_request(chat_request)
|
|
30
30
|
|
|
31
31
|
@classmethod
|
|
32
|
-
async def infer_async(cls, session_id, reference_id, action_type, application_ref_name, completion_params: ChatCompletionParams,
|
|
32
|
+
async def infer_async(cls, session_id, reference_id, action_type, application_ref_name, completion_params: ChatCompletionParams, apply_corrections: bool, evaluation_enabled: bool,
|
|
33
|
+
evaluate_callback: EvaluateCallback = None,
|
|
33
34
|
timeout=None) -> AsyncIterable[InferenceStreamResponse]:
|
|
34
|
-
|
|
35
|
-
chat_request: ChatCompletionRequest = cls.create_inference_request(application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params)
|
|
35
|
+
chat_request: ChatCompletionRequest = cls.create_inference_request(application_ref_name, session_id, reference_id, action_type, apply_corrections, evaluation_enabled, completion_params)
|
|
36
36
|
q = AsyncChunkQueue()
|
|
37
37
|
cls.run_async(cls.send_inference_request_async(chat_request, async_chunk_queue=q, evaluation_callback=evaluate_callback))
|
|
38
38
|
return QueueIterable(q, timeout=timeout)
|
|
39
39
|
|
|
40
40
|
@classmethod
|
|
41
|
-
def create_inference_request(cls, application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params: ChatCompletionParams):
|
|
41
|
+
def create_inference_request(cls, application_ref_name, session_id, reference_id, action_type, apply_corrections, evaluation_enabled, completion_params: ChatCompletionParams):
|
|
42
42
|
infer_request: ChatCompletionRequest = ChatCompletionRequest()
|
|
43
43
|
infer_request.application_ref_name = application_ref_name
|
|
44
44
|
infer_request.reference_id = reference_id
|
|
@@ -46,6 +46,7 @@ class Inference(MaiTaiClient):
|
|
|
46
46
|
infer_request.action_type = action_type
|
|
47
47
|
infer_request.apply_corrections = apply_corrections
|
|
48
48
|
infer_request.params = completion_params
|
|
49
|
+
infer_request.evaluation_enabled = evaluation_enabled
|
|
49
50
|
return infer_request
|
|
50
51
|
|
|
51
52
|
@classmethod
|
|
@@ -57,7 +58,6 @@ class Inference(MaiTaiClient):
|
|
|
57
58
|
'Content-Type': 'application/json',
|
|
58
59
|
'x-api-key': config.api_key
|
|
59
60
|
}
|
|
60
|
-
|
|
61
61
|
response = requests.post(url, headers=headers, data=chat_request.to_json(casing=Casing.SNAKE), verify=False, stream=True)
|
|
62
62
|
if response.status_code != 200:
|
|
63
63
|
print(f"Failed to send inference request. Status code: {response.status_code}. Error: {response.text}")
|
|
@@ -93,7 +93,6 @@ class Inference(MaiTaiClient):
|
|
|
93
93
|
if async_chunk_queue:
|
|
94
94
|
await async_chunk_queue.put("done")
|
|
95
95
|
return
|
|
96
|
-
last_item = None
|
|
97
96
|
async for line in response.content:
|
|
98
97
|
if line:
|
|
99
98
|
inference_response: InferenceStreamResponse = InferenceStreamResponse().from_json(line)
|
|
@@ -101,11 +100,12 @@ class Inference(MaiTaiClient):
|
|
|
101
100
|
chunk_queue.put(inference_response)
|
|
102
101
|
if async_chunk_queue:
|
|
103
102
|
await async_chunk_queue.put(inference_response)
|
|
104
|
-
|
|
103
|
+
if inference_response.evaluate_response and evaluation_callback:
|
|
104
|
+
try:
|
|
105
|
+
evaluation_callback(inference_response.evaluate_response)
|
|
106
|
+
except:
|
|
107
|
+
traceback.print_exc()
|
|
105
108
|
if chunk_queue:
|
|
106
109
|
chunk_queue.put("done")
|
|
107
110
|
if async_chunk_queue:
|
|
108
111
|
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)
|
|
@@ -7,19 +7,19 @@ import openai.types.chat as openai_chat_types
|
|
|
7
7
|
|
|
8
8
|
import maitai
|
|
9
9
|
from maitai._config import config
|
|
10
|
+
from maitai._evaluator import Evaluator
|
|
10
11
|
from maitai._openai_types import Body, Headers, Query
|
|
11
12
|
from maitai._types import EvaluateCallback
|
|
12
|
-
from maitai._utils import convert_open_ai_chat_completion_chunk, convert_openai_chat_completion, get_chat_completion_params,
|
|
13
|
-
set_completion_evaluation_response
|
|
14
|
-
from maitai_common.processes.stream_evaluation_thread import StreamEvaluationThread
|
|
13
|
+
from maitai._utils import convert_open_ai_chat_completion_chunk, convert_openai_chat_completion, get_chat_completion_params, required_args
|
|
15
14
|
from maitai_common.utils.proto_utils import openai_messages_to_proto
|
|
16
|
-
from maitai_gen.chat import ChatCompletionChunk, ChatCompletionResponse, ChatMessage,
|
|
15
|
+
from maitai_gen.chat import ChatCompletionChunk, ChatCompletionResponse, ChatMessage, EvaluationContentType
|
|
16
|
+
from maitai_gen.config import InferenceLocations
|
|
17
17
|
from maitai_gen.inference import InferenceStreamResponse
|
|
18
18
|
|
|
19
19
|
DEFAULT_MAX_RETRIES = 2
|
|
20
20
|
|
|
21
21
|
|
|
22
|
-
class
|
|
22
|
+
class MaitaiOpenAIClient:
|
|
23
23
|
def __init__(
|
|
24
24
|
self,
|
|
25
25
|
*,
|
|
@@ -63,7 +63,8 @@ class Completions:
|
|
|
63
63
|
client = openai.OpenAI()
|
|
64
64
|
self.client = client
|
|
65
65
|
|
|
66
|
-
@required_args(["session_id", "action_type", "application_ref_name", "messages"
|
|
66
|
+
@required_args(["session_id", "action_type", "application_ref_name", "messages"],
|
|
67
|
+
["session_id", "action_type", "application_ref_name", "messages", "model"],
|
|
67
68
|
["session_id", "action_type", "application_ref_name", "messages", "model", "stream"])
|
|
68
69
|
def create(
|
|
69
70
|
self,
|
|
@@ -74,10 +75,12 @@ class Completions:
|
|
|
74
75
|
action_type: str = None,
|
|
75
76
|
application_ref_name: str = None,
|
|
76
77
|
callback: Optional[EvaluateCallback] = None,
|
|
77
|
-
server_side_inference: bool =
|
|
78
|
+
server_side_inference: bool = None,
|
|
79
|
+
evaluation_enabled: bool = None,
|
|
80
|
+
apply_corrections: bool = None,
|
|
78
81
|
# OpenAI Arguments
|
|
79
82
|
messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
|
|
80
|
-
model: Union[str, openai_types.ChatModel],
|
|
83
|
+
model: Union[str, openai_types.ChatModel, openai.NotGiven] = openai.NOT_GIVEN,
|
|
81
84
|
frequency_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
82
85
|
function_call: Union[openai_chat_types.completion_create_params.FunctionCall, openai.NotGiven] = openai.NOT_GIVEN,
|
|
83
86
|
functions: Union[Iterable[openai_chat_types.completion_create_params.Function], openai.NotGiven] = openai.NOT_GIVEN,
|
|
@@ -89,7 +92,7 @@ class Completions:
|
|
|
89
92
|
response_format: Union[openai_chat_types.completion_create_params.ResponseFormat, openai.NotGiven] = openai.NOT_GIVEN,
|
|
90
93
|
seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
|
|
91
94
|
stop: Union[Union[Optional[str], List[str]], openai.NotGiven] = openai.NOT_GIVEN,
|
|
92
|
-
stream: Optional[bool] =
|
|
95
|
+
stream: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
|
|
93
96
|
stream_options: Union[Optional[openai_chat_types.ChatCompletionStreamOptionsParam], openai.NotGiven] = openai.NOT_GIVEN,
|
|
94
97
|
temperature: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
|
|
95
98
|
tool_choice: Union[openai_chat_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven] = openai.NOT_GIVEN,
|
|
@@ -104,6 +107,33 @@ class Completions:
|
|
|
104
107
|
) -> Union[ChatCompletionResponse, Iterable[ChatCompletionChunk]]:
|
|
105
108
|
if not config.api_key:
|
|
106
109
|
raise ValueError("Maitai API Key has not been set")
|
|
110
|
+
if server_side_inference is False and apply_corrections is True:
|
|
111
|
+
raise ValueError("server_side_inference must be true to apply_corrections")
|
|
112
|
+
if apply_corrections is True and evaluation_enabled is False:
|
|
113
|
+
raise ValueError("evaluations must be enabled to apply_corrections")
|
|
114
|
+
maitai_config = config.get_application_action_config(application_ref_name, action_type)
|
|
115
|
+
if server_side_inference is None:
|
|
116
|
+
server_side_inference = maitai_config.inference_location == InferenceLocations.SERVER
|
|
117
|
+
if evaluation_enabled is None:
|
|
118
|
+
evaluation_enabled = maitai_config.evaluation_enabled
|
|
119
|
+
if apply_corrections is None:
|
|
120
|
+
apply_corrections = maitai_config.apply_corrections
|
|
121
|
+
if model is None:
|
|
122
|
+
model = maitai_config.model
|
|
123
|
+
if temperature == openai.NOT_GIVEN:
|
|
124
|
+
temperature = maitai_config.temperature
|
|
125
|
+
if stream is None:
|
|
126
|
+
stream = maitai_config.streaming
|
|
127
|
+
if response_format == openai.NOT_GIVEN:
|
|
128
|
+
response_format = {"type": maitai_config.response_format}
|
|
129
|
+
if stop == openai.NOT_GIVEN and maitai_config.stop is not None:
|
|
130
|
+
stop = maitai_config.stop
|
|
131
|
+
if logprobs == openai.NOT_GIVEN:
|
|
132
|
+
logprobs = maitai_config.logprobs
|
|
133
|
+
if max_tokens == openai.NOT_GIVEN and maitai_config.max_tokens is not None:
|
|
134
|
+
max_tokens = maitai_config.max_tokens
|
|
135
|
+
if n == openai.NOT_GIVEN:
|
|
136
|
+
n = maitai_config.n
|
|
107
137
|
if server_side_inference:
|
|
108
138
|
completion_params = get_chat_completion_params(
|
|
109
139
|
messages=messages,
|
|
@@ -129,20 +159,13 @@ class Completions:
|
|
|
129
159
|
response_timeout = None
|
|
130
160
|
if isinstance(timeout, float) or isinstance(timeout, int):
|
|
131
161
|
response_timeout = timeout
|
|
132
|
-
response = maitai.Inference.infer(session_id, reference_id, action_type, application_ref_name, completion_params, callback, timeout=response_timeout)
|
|
162
|
+
response = maitai.Inference.infer(session_id, reference_id, action_type, application_ref_name, completion_params, apply_corrections, evaluation_enabled, callback, timeout=response_timeout)
|
|
133
163
|
if stream:
|
|
134
|
-
return _process_inference_stream(response
|
|
164
|
+
return _process_inference_stream(response)
|
|
135
165
|
# ChatCompletion only
|
|
136
166
|
chat_completion: Optional[ChatCompletionResponse] = None
|
|
137
167
|
for resp in response:
|
|
138
|
-
|
|
139
|
-
return resp.chat_completion_response
|
|
140
|
-
else:
|
|
141
|
-
if resp.chat_completion_response:
|
|
142
|
-
chat_completion = resp.chat_completion_response
|
|
143
|
-
if resp.evaluate_response and chat_completion:
|
|
144
|
-
set_completion_evaluation_response(chat_completion, resp.evaluate_response)
|
|
145
|
-
return chat_completion
|
|
168
|
+
return resp.chat_completion_response
|
|
146
169
|
return chat_completion
|
|
147
170
|
else:
|
|
148
171
|
response = self.client.chat.completions.create(
|
|
@@ -174,23 +197,22 @@ class Completions:
|
|
|
174
197
|
|
|
175
198
|
)
|
|
176
199
|
if stream:
|
|
177
|
-
return _process_openai_stream(session_id, reference_id, action_type, application_ref_name, messages, response, callback)
|
|
200
|
+
return _process_openai_stream(session_id, reference_id, action_type, application_ref_name, messages, response, evaluation_enabled, callback)
|
|
178
201
|
else:
|
|
179
202
|
maitai_completion = convert_openai_chat_completion(response)
|
|
180
203
|
proto_messages = openai_messages_to_proto(messages)
|
|
181
204
|
proto_messages.append(
|
|
182
205
|
ChatMessage(role="assistant", content=maitai_completion.choices[0].message.content))
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
set_completion_evaluation_response(maitai_completion, maitai_eval)
|
|
206
|
+
if evaluation_enabled:
|
|
207
|
+
maitai.Evaluator.evaluate(
|
|
208
|
+
session_id=session_id,
|
|
209
|
+
reference_id=reference_id,
|
|
210
|
+
action_type=action_type,
|
|
211
|
+
content_type=EvaluationContentType.MESSAGE,
|
|
212
|
+
content=proto_messages,
|
|
213
|
+
application_ref_name=application_ref_name,
|
|
214
|
+
callback=callback,
|
|
215
|
+
)
|
|
194
216
|
return maitai_completion
|
|
195
217
|
|
|
196
218
|
|
|
@@ -200,41 +222,34 @@ def _process_openai_stream(session_id: Union[str, int],
|
|
|
200
222
|
application_ref_name: str,
|
|
201
223
|
messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
|
|
202
224
|
stream: openai.Stream[openai_chat_types.ChatCompletionChunk],
|
|
225
|
+
evaluation_enabled: bool,
|
|
203
226
|
callback: Optional[EvaluateCallback] = None) -> Iterable[ChatCompletionChunk]:
|
|
204
227
|
full_body = ""
|
|
205
228
|
proto_messages = openai_messages_to_proto(messages)
|
|
206
|
-
stream_eval_thread = StreamEvaluationThread()
|
|
207
|
-
stream_eval_thread.start()
|
|
208
229
|
for chunk in stream:
|
|
209
|
-
if stream_eval_thread.output:
|
|
210
|
-
result: EvaluateResponse = stream_eval_thread.output
|
|
211
|
-
stream_eval_thread.terminate()
|
|
212
|
-
new_stream = maitai.Evaluator.evaluate_realtime(session_id, reference_id, action_type, EvaluationContentType.PARTIAL, proto_messages, application_ref_name, full_body,
|
|
213
|
-
result.evaluation_results[0].description, result.evaluation_results[0].sentinel_id)
|
|
214
|
-
for new_chunk in new_stream:
|
|
215
|
-
yield new_chunk
|
|
216
|
-
return
|
|
217
230
|
maitai_chunk = convert_open_ai_chat_completion_chunk(chunk)
|
|
218
|
-
|
|
219
|
-
if
|
|
220
|
-
|
|
221
|
-
full_body = new_full_body
|
|
222
|
-
if result_chunk is not None:
|
|
223
|
-
yield result_chunk
|
|
224
|
-
break
|
|
231
|
+
content = maitai_chunk.choices[0].delta.content
|
|
232
|
+
if content is not None:
|
|
233
|
+
full_body += content
|
|
225
234
|
yield maitai_chunk
|
|
226
|
-
|
|
235
|
+
if maitai_chunk.choices[0].finish_reason and evaluation_enabled:
|
|
236
|
+
proto_messages.append(ChatMessage(role="assistant", content=full_body))
|
|
237
|
+
Evaluator.evaluate(
|
|
238
|
+
session_id=session_id,
|
|
239
|
+
reference_id=reference_id,
|
|
240
|
+
action_type=action_type,
|
|
241
|
+
content_type=EvaluationContentType.MESSAGE,
|
|
242
|
+
content=proto_messages,
|
|
243
|
+
application_ref_name=application_ref_name,
|
|
244
|
+
callback=callback
|
|
245
|
+
)
|
|
246
|
+
return
|
|
227
247
|
|
|
228
248
|
|
|
229
|
-
def _process_inference_stream(stream: Iterable[InferenceStreamResponse]
|
|
230
|
-
last_chat_completion_chunk: Optional[ChatCompletionChunk] = None
|
|
249
|
+
def _process_inference_stream(stream: Iterable[InferenceStreamResponse]) -> Iterable[ChatCompletionChunk]:
|
|
231
250
|
for infer_resp in stream:
|
|
232
|
-
chunk =
|
|
251
|
+
chunk = infer_resp.chat_completion_chunk
|
|
233
252
|
if chunk is not None:
|
|
234
|
-
if chunk.choices[0].finish_reason:
|
|
235
|
-
if callback:
|
|
236
|
-
yield chunk
|
|
237
|
-
return
|
|
238
|
-
else:
|
|
239
|
-
last_chat_completion_chunk = chunk
|
|
240
253
|
yield chunk
|
|
254
|
+
if chunk.choices[0].finish_reason:
|
|
255
|
+
return
|