maitai-python 1.0.1b0__tar.gz → 1.0.1b2__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.1b0 → maitai_python-1.0.1b2}/PKG-INFO +2 -2
  2. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/README.md +1 -1
  3. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai/__init__.py +1 -0
  4. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai/_evaluator.py +31 -19
  5. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai/_inference.py +27 -9
  6. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai/_openai.py +21 -131
  7. maitai_python-1.0.1b2/maitai/_openai_async.py +226 -0
  8. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai/_types.py +31 -2
  9. maitai_python-1.0.1b2/maitai/_utils.py +235 -0
  10. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_python.egg-info/PKG-INFO +2 -2
  11. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_python.egg-info/SOURCES.txt +1 -0
  12. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/setup.py +1 -1
  13. maitai_python-1.0.1b0/maitai/_utils.py +0 -112
  14. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai/_config.py +0 -0
  15. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai/_config_listener_thread.py +0 -0
  16. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai/_maitai_client.py +0 -0
  17. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai/_openai_types.py +0 -0
  18. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_common/__init__.py +0 -0
  19. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_common/processes/__init__.py +0 -0
  20. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_common/processes/io_thread.py +0 -0
  21. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_common/processes/websocket_listener_thread.py +0 -0
  22. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_common/utils/__init__.py +0 -0
  23. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_common/utils/proto_utils.py +0 -0
  24. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_gen/__init__.py +0 -0
  25. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_gen/application/__init__.py +0 -0
  26. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_gen/chat/__init__.py +0 -0
  27. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_gen/company/__init__.py +0 -0
  28. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_gen/inference/__init__.py +0 -0
  29. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_gen/notification/__init__.py +0 -0
  30. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_gen/sandbox/__init__.py +0 -0
  31. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_gen/sentinel/__init__.py +0 -0
  32. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_gen/session/__init__.py +0 -0
  33. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_python.egg-info/dependency_links.txt +0 -0
  34. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_python.egg-info/requires.txt +0 -0
  35. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/maitai_python.egg-info/top_level.txt +0 -0
  36. {maitai_python-1.0.1b0 → maitai_python-1.0.1b2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: maitai-python
3
- Version: 1.0.1b0
3
+ Version: 1.0.1b2
4
4
  Summary: MaiTai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -19,7 +19,7 @@ Requires-Dist: websocket-client
19
19
 
20
20
  # Quickstart
21
21
 
22
- Full documents can be found at https://docs.trymaitai.ai
22
+ Full docs can be found at https://docs.trymaitai.ai
23
23
 
24
24
  ## Configure your application in the Maitai portal
25
25
 
@@ -1,6 +1,6 @@
1
1
  # Quickstart
2
2
 
3
- Full documents can be found at https://docs.trymaitai.ai
3
+ Full docs can be found at https://docs.trymaitai.ai
4
4
 
5
5
  ## Configure your application in the Maitai portal
6
6
 
@@ -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
 
@@ -11,37 +11,47 @@ from maitai._types import EvaluateCallback
11
11
  from maitai_gen.chat import EvaluateRequest, EvaluateResponse, EvaluationContentType
12
12
 
13
13
 
14
+ def _get_content_type(content):
15
+ if isinstance(content, str):
16
+ return EvaluationContentType.TEXT
17
+ elif isinstance(content, list):
18
+ return EvaluationContentType.MESSAGE
19
+
20
+
14
21
  class Evaluator(MaiTaiClient):
15
22
 
16
23
  def __init__(self):
17
24
  super().__init__()
18
25
 
19
26
  @classmethod
20
- def evaluate_with_callback(cls, session_id, reference_id, action_type, content_type, content, application_id=None,
21
- application_ref_name=None, callback=None):
27
+ async def evaluate_async(cls, session_id, reference_id, action_type, content, content_type=None, application_id=None, application_ref_name=None, callback=None):
28
+ if content_type is None:
29
+ content_type = _get_content_type(content)
30
+ if content_type is None:
31
+ raise Exception('Unable to automatically determine content_type')
22
32
  if application_id is None and application_ref_name is None:
23
33
  raise Exception('application_id or application_ref_name must be provided')
24
- eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id,
25
- reference_id, action_type, content_type, content)
26
- cls.run_async(cls.send_evaluation_request_async(eval_request, callback))
34
+ eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id, reference_id, action_type, content_type, content)
35
+ if callback is None:
36
+ return await cls.send_evaluation_request_async(eval_request)
37
+ else:
38
+ cls.run_async(cls.send_evaluation_request_async(eval_request, callback))
39
+ return None
27
40
 
28
41
  @classmethod
29
- async def evaluate_async(cls, session_id, reference_id, action_type, content_type, content, application_id=None,
30
- application_ref_name=None):
42
+ def evaluate(cls, session_id, reference_id, action_type, content, content_type=None, application_id=None, application_ref_name=None, callback=None):
43
+ if content_type is None:
44
+ content_type = _get_content_type(content)
45
+ if content_type is None:
46
+ raise Exception('Unable to automatically determine content_type')
31
47
  if application_id is None and application_ref_name is None:
32
48
  raise Exception('application_id or application_ref_name must be provided')
33
- eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id,
34
- reference_id, action_type, content_type, content)
35
- return await cls.send_evaluation_request_async(eval_request)
36
-
37
- @classmethod
38
- def evaluate(cls, session_id, reference_id, action_type, content_type, content, application_id=None,
39
- application_ref_name=None):
40
- if application_id is None and application_ref_name is None:
41
- raise Exception('application_id or application_ref_name must be provided')
42
- eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id,
43
- reference_id, action_type, content_type, content)
44
- return cls.send_evaluation_request(eval_request)
49
+ eval_request: EvaluateRequest = cls.create_eval_request(application_id, application_ref_name, session_id, reference_id, action_type, content_type, content)
50
+ if callback is None:
51
+ return cls.send_evaluation_request(eval_request)
52
+ else:
53
+ cls.run_async(cls.send_evaluation_request_async(eval_request, callback))
54
+ return None
45
55
 
46
56
  @classmethod
47
57
  def create_eval_request(cls, application_id, application_ref_name, session_id, reference_id, action_type,
@@ -143,6 +153,8 @@ class Evaluator(MaiTaiClient):
143
153
  eval_result = EvaluateResponse().from_json(result)
144
154
  if callback is not None:
145
155
  callback(eval_result)
156
+ else:
157
+ return eval_result
146
158
 
147
159
  @classmethod
148
160
  def send_evaluation_request(cls, eval_request: EvaluateRequest) -> EvaluateResponse:
@@ -1,5 +1,5 @@
1
1
  import time
2
- from typing import Iterable
2
+ from typing import AsyncIterable, Iterable
3
3
 
4
4
  import aiohttp
5
5
  import requests
@@ -7,7 +7,7 @@ from betterproto import Casing
7
7
 
8
8
  from maitai._config import config
9
9
  from maitai._maitai_client import MaiTaiClient
10
- from maitai._types import ChunkQueue, EvaluateCallback, QueueIterable
10
+ from maitai._types import AsyncChunkQueue, ChunkQueue, EvaluateCallback, QueueIterable
11
11
  from maitai_gen.chat import ChatCompletionParams, ChatCompletionRequest
12
12
  from maitai_gen.inference import InferenceStreamResponse
13
13
 
@@ -24,11 +24,20 @@ class Inference(MaiTaiClient):
24
24
  chat_request: ChatCompletionRequest = cls.create_inference_request(application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params)
25
25
  if evaluate_callback:
26
26
  q = ChunkQueue()
27
- cls.run_async(cls.send_inference_request_async(chat_request, q, evaluate_callback))
27
+ cls.run_async(cls.send_inference_request_async(chat_request, chunk_queue=q, evaluation_callback=evaluate_callback))
28
28
  return QueueIterable(q, timeout=timeout)
29
29
  else:
30
30
  return cls.send_inference_request(chat_request)
31
31
 
32
+ @classmethod
33
+ async def infer_async(cls, session_id, reference_id, action_type, application_ref_name, completion_params: ChatCompletionParams, evaluate_callback: EvaluateCallback = None,
34
+ timeout=None) -> AsyncIterable[InferenceStreamResponse]:
35
+ apply_corrections = evaluate_callback is None
36
+ chat_request: ChatCompletionRequest = cls.create_inference_request(application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params)
37
+ q = AsyncChunkQueue()
38
+ cls.run_async(cls.send_inference_request_async(chat_request, async_chunk_queue=q, evaluation_callback=evaluate_callback))
39
+ return QueueIterable(q, timeout=timeout)
40
+
32
41
  @classmethod
33
42
  def create_inference_request(cls, application_ref_name, session_id, reference_id, action_type, apply_corrections, completion_params: ChatCompletionParams):
34
43
  infer_request: ChatCompletionRequest = ChatCompletionRequest()
@@ -71,7 +80,7 @@ class Inference(MaiTaiClient):
71
80
  print(time.time() - start)
72
81
 
73
82
  @classmethod
74
- async def send_inference_request_async(cls, chat_request: ChatCompletionRequest, chunk_queue: ChunkQueue, evaluation_callback: EvaluateCallback):
83
+ async def send_inference_request_async(cls, chat_request: ChatCompletionRequest, chunk_queue: ChunkQueue = None, async_chunk_queue: AsyncChunkQueue = None, evaluation_callback: EvaluateCallback = None):
75
84
  start = time.time()
76
85
 
77
86
  host = config.maitai_host
@@ -85,7 +94,10 @@ class Inference(MaiTaiClient):
85
94
  if response.status != 200:
86
95
  error_text = await response.text()
87
96
  print(f"Failed to send evaluation request. Status code: {response.status}. Error: {error_text}")
88
- chunk_queue.put("done")
97
+ if chunk_queue:
98
+ chunk_queue.put("done")
99
+ if async_chunk_queue:
100
+ await async_chunk_queue.put("done")
89
101
  return
90
102
  else:
91
103
  print(f"Successfully sent evaluation request. Status code: {response.status}")
@@ -93,9 +105,15 @@ class Inference(MaiTaiClient):
93
105
  async for line in response.content:
94
106
  if line:
95
107
  inference_response: InferenceStreamResponse = InferenceStreamResponse().from_json(line)
96
- chunk_queue.put(inference_response)
108
+ if chunk_queue:
109
+ chunk_queue.put(inference_response)
110
+ if async_chunk_queue:
111
+ await async_chunk_queue.put(inference_response)
97
112
  last_item = inference_response
98
- chunk_queue.put("done")
113
+ if chunk_queue:
114
+ chunk_queue.put("done")
115
+ if async_chunk_queue:
116
+ await async_chunk_queue.put("done")
99
117
  if last_item is not None and last_item.evaluate_response:
100
- evaluation_callback(last_item.evaluate_response)
101
- print(time.time() - start)
118
+ if evaluation_callback:
119
+ evaluation_callback(last_item.evaluate_response)
@@ -9,9 +9,10 @@ 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, required_args, set_chunk_evaluation_response, set_completion_evaluation_response
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
13
14
  from maitai_common.utils.proto_utils import openai_messages_to_proto
14
- from maitai_gen.chat import ChatCompletionChunk, ChatCompletionParams, ChatCompletionResponse, ChatMessage, EvaluationContentType, Function, ResponseFormat, StreamOptions, Tool
15
+ from maitai_gen.chat import ChatCompletionChunk, ChatCompletionResponse, ChatMessage, EvaluationContentType
15
16
  from maitai_gen.inference import InferenceStreamResponse
16
17
 
17
18
  DEFAULT_MAX_RETRIES = 2
@@ -177,28 +178,18 @@ class Completions:
177
178
  proto_messages = openai_messages_to_proto(messages)
178
179
  proto_messages.append(
179
180
  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
- )
181
+ maitai_eval = maitai.Evaluator.evaluate(
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
+ if not callback:
200
191
  set_completion_evaluation_response(maitai_completion, maitai_eval)
201
- return maitai_completion
192
+ return maitai_completion
202
193
 
203
194
 
204
195
  def _process_stream(session_id: Union[str, int],
@@ -206,39 +197,15 @@ def _process_stream(session_id: Union[str, int],
206
197
  action_type: str,
207
198
  application_ref_name: str,
208
199
  messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
209
- stream: Union[openai.Stream[openai_chat_types.ChatCompletionChunk], openai_chat_types.ChatCompletion],
200
+ stream: openai.Stream[openai_chat_types.ChatCompletionChunk],
210
201
  callback: Optional[EvaluateCallback] = None) -> Iterable[ChatCompletionChunk]:
211
202
  full_body = ""
212
203
  proto_messages = openai_messages_to_proto(messages)
213
204
  for chunk in stream:
214
205
  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
- maitai_eval = maitai.Evaluator.evaluate(
233
- session_id=session_id,
234
- reference_id=reference_id,
235
- action_type=action_type,
236
- content_type=EvaluationContentType.MESSAGE,
237
- content=proto_messages,
238
- application_ref_name=application_ref_name,
239
- )
240
- maitai_chunk.evaluate_response = maitai_eval
241
- yield maitai_chunk
206
+ full_body, result_chunk = process_chunk(session_id, reference_id, action_type, application_ref_name, proto_messages, full_body, maitai_chunk, callback)
207
+ if result_chunk is not None:
208
+ yield result_chunk
242
209
  break
243
210
  yield maitai_chunk
244
211
 
@@ -246,89 +213,12 @@ def _process_stream(session_id: Union[str, int],
246
213
  def _process_inference_stream(stream: Iterable[InferenceStreamResponse], callback: EvaluateCallback) -> Iterable[ChatCompletionChunk]:
247
214
  last_chat_completion_chunk: Optional[ChatCompletionChunk] = None
248
215
  for infer_resp in stream:
249
- if infer_resp.evaluate_response:
250
- if not callback:
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
216
+ chunk = process_stream_response(infer_resp, callback, last_chat_completion_chunk)
217
+ if chunk is not None:
257
218
  if chunk.choices[0].finish_reason:
258
219
  if callback:
259
220
  yield chunk
260
221
  return
261
222
  else:
262
223
  last_chat_completion_chunk = chunk
263
- else:
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
224
+ yield chunk
@@ -0,0 +1,226 @@
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.utils.proto_utils import openai_messages_to_proto
15
+ from maitai_gen.chat import ChatCompletionChunk, ChatCompletionResponse, ChatMessage, EvaluationContentType
16
+ from maitai_gen.inference import InferenceStreamResponse
17
+
18
+ DEFAULT_MAX_RETRIES = 2
19
+
20
+
21
+ class MaiTaiAsyncOpenAIClient:
22
+ def __init__(
23
+ self,
24
+ *,
25
+ maitai_api_key: Optional[str] = None,
26
+ api_key: Optional[str] = None,
27
+ organization: Optional[str] = None,
28
+ project: Optional[str] = None,
29
+ base_url: Union[str, httpx.URL, None] = None,
30
+ timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NOT_GIVEN,
31
+ max_retries: int = DEFAULT_MAX_RETRIES,
32
+ default_headers: Optional[Mapping[str, str]] = None,
33
+ default_query: Optional[Mapping[str, object]] = None,
34
+ http_client: Optional[httpx.Client] = None,
35
+ _strict_response_validation: bool = False,
36
+
37
+ ):
38
+ if maitai_api_key:
39
+ config.initialize(maitai_api_key)
40
+ self.client = openai.AsyncClient(
41
+ api_key=api_key,
42
+ organization=organization,
43
+ project=project,
44
+ base_url=base_url,
45
+ timeout=timeout,
46
+ max_retries=max_retries,
47
+ default_headers=default_headers,
48
+ default_query=default_query,
49
+ http_client=http_client,
50
+ )
51
+
52
+ self.chat = AsyncChat(self.client)
53
+
54
+
55
+ class AsyncChat:
56
+ def __init__(self, client=None):
57
+ self.completions = AsyncCompletions(client)
58
+
59
+
60
+ class AsyncCompletions:
61
+ def __init__(self, client: Optional[openai.AsyncClient] = None):
62
+ if client is None:
63
+ client = openai.AsyncClient()
64
+ self.client = client
65
+
66
+ @required_args(["session_id", "action_type", "application_ref_name", "messages", "model"],
67
+ ["session_id", "action_type", "application_ref_name", "messages", "model", "stream"])
68
+ async def create(
69
+ self,
70
+ *,
71
+ # Maitai Arguments
72
+ session_id: Union[str, int] = None,
73
+ reference_id: Union[str, int, None] = None,
74
+ action_type: str = None,
75
+ application_ref_name: str = None,
76
+ callback: Optional[EvaluateCallback] = None,
77
+ server_side_inference: bool = False, # TODO make this a config item
78
+ # OpenAI Arguments
79
+ messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
80
+ model: Union[str, openai_types.ChatModel],
81
+ frequency_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
82
+ function_call: Union[openai_chat_types.completion_create_params.FunctionCall, openai.NotGiven] = openai.NOT_GIVEN,
83
+ functions: Union[Iterable[openai_chat_types.completion_create_params.Function], openai.NotGiven] = openai.NOT_GIVEN,
84
+ logit_bias: Union[Optional[Dict[str, int]], openai.NotGiven] = openai.NOT_GIVEN,
85
+ logprobs: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
86
+ max_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
87
+ n: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
88
+ presence_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
89
+ response_format: Union[openai_chat_types.completion_create_params.ResponseFormat, openai.NotGiven] = openai.NOT_GIVEN,
90
+ seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
91
+ stop: Union[Union[Optional[str], List[str]], openai.NotGiven] = openai.NOT_GIVEN,
92
+ stream: Optional[bool] = False,
93
+ stream_options: Union[Optional[openai_chat_types.ChatCompletionStreamOptionsParam], openai.NotGiven] = openai.NOT_GIVEN,
94
+ temperature: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
95
+ tool_choice: Union[openai_chat_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven] = openai.NOT_GIVEN,
96
+ tools: Union[Iterable[openai_chat_types.ChatCompletionToolParam], openai.NotGiven] = openai.NOT_GIVEN,
97
+ top_logprobs: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
98
+ top_p: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
99
+ user: Union[str, openai.NotGiven] = openai.NOT_GIVEN,
100
+ extra_headers: Optional[Headers] = None,
101
+ extra_query: Optional[Query] = None,
102
+ extra_body: Optional[Body] = None,
103
+ timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NOT_GIVEN,
104
+ ) -> Union[ChatCompletionResponse, AsyncIterable[ChatCompletionChunk]]:
105
+ if not config.api_key:
106
+ raise ValueError("Maitai API Key has not been set")
107
+ if server_side_inference:
108
+ completion_params = get_chat_completion_params(
109
+ messages=messages,
110
+ model=model,
111
+ frequency_penalty=frequency_penalty,
112
+ logit_bias=logit_bias,
113
+ logprobs=logprobs,
114
+ max_tokens=max_tokens,
115
+ n=n,
116
+ presence_penalty=presence_penalty,
117
+ response_format=response_format,
118
+ seed=seed,
119
+ stop=stop,
120
+ stream=stream,
121
+ stream_options=stream_options,
122
+ temperature=temperature,
123
+ tool_choice=tool_choice,
124
+ tools=tools,
125
+ top_logprobs=top_logprobs,
126
+ top_p=top_p,
127
+ user=user,
128
+ )
129
+ response_timeout = None
130
+ if isinstance(timeout, float) or isinstance(timeout, int):
131
+ response_timeout = timeout
132
+ response = await maitai.Inference.infer_async(session_id, reference_id, action_type, application_ref_name, completion_params, callback, timeout=response_timeout)
133
+ if stream:
134
+ return _process_inference_stream_async(response, callback)
135
+ # ChatCompletion only
136
+ chat_completion: Optional[ChatCompletionResponse] = None
137
+ async for resp in response:
138
+ if callback:
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
146
+ return chat_completion
147
+ else:
148
+ response = await self.client.chat.completions.create(
149
+ messages=messages,
150
+ model=model,
151
+ frequency_penalty=frequency_penalty,
152
+ function_call=function_call,
153
+ functions=functions,
154
+ logit_bias=logit_bias,
155
+ logprobs=logprobs,
156
+ max_tokens=max_tokens,
157
+ n=n,
158
+ presence_penalty=presence_penalty,
159
+ response_format=response_format,
160
+ seed=seed,
161
+ stop=stop,
162
+ stream=stream,
163
+ stream_options=stream_options,
164
+ temperature=temperature,
165
+ tool_choice=tool_choice,
166
+ tools=tools,
167
+ top_logprobs=top_logprobs,
168
+ top_p=top_p,
169
+ user=user,
170
+ extra_headers=extra_headers,
171
+ extra_query=extra_query,
172
+ extra_body=extra_body,
173
+ timeout=timeout,
174
+
175
+ )
176
+ if stream:
177
+ return _process_async_openai_stream(session_id, reference_id, action_type, application_ref_name, messages, response, callback)
178
+ else:
179
+ maitai_completion = convert_openai_chat_completion(response)
180
+ proto_messages = openai_messages_to_proto(messages)
181
+ proto_messages.append(
182
+ ChatMessage(role="assistant", content=maitai_completion.choices[0].message.content))
183
+ maitai_eval = await maitai.Evaluator.evaluate_async(
184
+ session_id=session_id,
185
+ reference_id=reference_id,
186
+ action_type=action_type,
187
+ content_type=EvaluationContentType.MESSAGE,
188
+ content=proto_messages,
189
+ application_ref_name=application_ref_name,
190
+ callback=callback,
191
+ )
192
+ if not callback:
193
+ set_completion_evaluation_response(maitai_completion, maitai_eval)
194
+ return maitai_completion
195
+
196
+
197
+ async def _process_async_openai_stream(session_id: Union[str, int],
198
+ reference_id: Union[str, int, None],
199
+ action_type: str,
200
+ application_ref_name: str,
201
+ messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
202
+ stream: openai.AsyncStream[openai_chat_types.ChatCompletionChunk],
203
+ callback: Optional[EvaluateCallback] = None) -> AsyncIterable[ChatCompletionChunk]:
204
+ full_body = ""
205
+ proto_messages = openai_messages_to_proto(messages)
206
+ async for chunk in stream:
207
+ maitai_chunk = convert_open_ai_chat_completion_chunk(chunk)
208
+ full_body, result_chunk = process_chunk(session_id, reference_id, action_type, application_ref_name, proto_messages, full_body, maitai_chunk, callback)
209
+ if result_chunk is not None:
210
+ yield result_chunk
211
+ break
212
+ yield maitai_chunk
213
+
214
+
215
+ async def _process_inference_stream_async(stream: AsyncIterable[InferenceStreamResponse], callback: EvaluateCallback) -> AsyncIterable[ChatCompletionChunk]:
216
+ last_chat_completion_chunk: Optional[ChatCompletionChunk] = None
217
+ async for infer_resp in stream:
218
+ chunk = process_stream_response(infer_resp, callback, last_chat_completion_chunk)
219
+ if chunk is not None:
220
+ if chunk.choices[0].finish_reason:
221
+ if callback:
222
+ yield chunk
223
+ return
224
+ else:
225
+ last_chat_completion_chunk = chunk
226
+ yield chunk
@@ -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 EvaluateResponse
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]
@@ -0,0 +1,235 @@
1
+ import functools
2
+ import inspect
3
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union
4
+
5
+ import openai
6
+ import openai.types.chat as openai_types
7
+ from openai.types import ChatModel
8
+
9
+ import maitai_gen.chat as chat_types
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
15
+
16
+ CallableT = TypeVar("CallableT", bound=Callable[..., Any])
17
+
18
+
19
+ def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]:
20
+ def inner(func: CallableT) -> CallableT:
21
+ params = inspect.signature(func).parameters
22
+ positional = [
23
+ name
24
+ for name, param in params.items()
25
+ if param.kind
26
+ in {
27
+ param.POSITIONAL_ONLY,
28
+ param.POSITIONAL_OR_KEYWORD,
29
+ }
30
+ ]
31
+
32
+ @functools.wraps(func)
33
+ def wrapper(*args: object, **kwargs: object) -> object:
34
+ given_params: set[str] = set()
35
+ for i, _ in enumerate(args):
36
+ try:
37
+ given_params.add(positional[i])
38
+ except IndexError:
39
+ raise TypeError(
40
+ f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given"
41
+ ) from None
42
+
43
+ for key in kwargs.keys():
44
+ given_params.add(key)
45
+
46
+ for variant in variants:
47
+ matches = all((param in given_params for param in variant))
48
+ if matches:
49
+ break
50
+ else: # no break
51
+ if len(variants) > 1:
52
+ variations = human_join(
53
+ ["(" + human_join([quote(arg) for arg in variant], final="and") + ")" for variant in variants]
54
+ )
55
+ msg = f"Missing required arguments; Expected either {variations} arguments to be given"
56
+ else:
57
+ assert len(variants) > 0
58
+
59
+ # TODO: this error message is not deterministic
60
+ missing = list(set(variants[0]) - given_params)
61
+ if len(missing) > 1:
62
+ msg = f"Missing required arguments: {human_join([quote(arg) for arg in missing])}"
63
+ else:
64
+ msg = f"Missing required argument: {quote(missing[0])}"
65
+ raise TypeError(msg)
66
+ return func(*args, **kwargs)
67
+
68
+ return wrapper # type: ignore
69
+
70
+ return inner
71
+
72
+
73
+ # copied from https://github.com/Rapptz/RoboDanny
74
+ def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> str:
75
+ size = len(seq)
76
+ if size == 0:
77
+ return ""
78
+
79
+ if size == 1:
80
+ return seq[0]
81
+
82
+ if size == 2:
83
+ return f"{seq[0]} {final} {seq[1]}"
84
+
85
+ return delim.join(seq[:-1]) + f" {final} {seq[-1]}"
86
+
87
+
88
+ def quote(string: str) -> str:
89
+ """Add single quotation marks around the given string. Does *not* do any escaping."""
90
+ return f"'{string}'"
91
+
92
+
93
+ def convert_openai_chat_completion(chat: openai_types.ChatCompletion) -> chat_types.ChatCompletionResponse:
94
+ return chat_types.ChatCompletionResponse().from_dict(chat.to_dict())
95
+
96
+
97
+ def set_completion_evaluation_response(completion: chat_types.ChatCompletionResponse, response: EvaluateResponse):
98
+ completion.evaluate_response = response
99
+ try:
100
+ completion.choices[0].message.content = response.evaluation_results[0].meta["correction_pre"]
101
+ completion.original_choices = [_copy_choice(choice) for choice in completion.choices]
102
+ except:
103
+ pass
104
+
105
+
106
+ def _copy_choice(choice: Union[openai_types.chat_completion.Choice, chat_types.ChatCompletionChoice]) -> chat_types.ChatCompletionChoice:
107
+ message = chat_types.ChatMessage(content=choice.message.content, role=choice.message.role)
108
+ copied_choice = chat_types.ChatCompletionChoice(finish_reason=choice.finish_reason, index=choice.index,
109
+ logprobs=choice.logprobs, message=message)
110
+ return copied_choice
111
+
112
+
113
+ def set_chunk_evaluation_response(chunk: chat_types.ChatCompletionChunk, response: EvaluateResponse):
114
+ chunk.evaluate_response = response
115
+
116
+
117
+ def convert_open_ai_chat_completion_chunk(chunk: openai_types.ChatCompletionChunk) -> chat_types.ChatCompletionChunk:
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
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: maitai-python
3
- Version: 1.0.1b0
3
+ Version: 1.0.1b2
4
4
  Summary: MaiTai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -19,7 +19,7 @@ Requires-Dist: websocket-client
19
19
 
20
20
  # Quickstart
21
21
 
22
- Full documents can be found at https://docs.trymaitai.ai
22
+ Full docs can be found at https://docs.trymaitai.ai
23
23
 
24
24
  ## Configure your application in the Maitai portal
25
25
 
@@ -7,6 +7,7 @@ maitai/_evaluator.py
7
7
  maitai/_inference.py
8
8
  maitai/_maitai_client.py
9
9
  maitai/_openai.py
10
+ maitai/_openai_async.py
10
11
  maitai/_openai_types.py
11
12
  maitai/_types.py
12
13
  maitai/_utils.py
@@ -3,7 +3,7 @@
3
3
  from setuptools import setup, find_packages
4
4
  setup(
5
5
  name='maitai-python',
6
- version='1.0.1-beta',
6
+ version='1.0.1b2',
7
7
  packages=find_packages(exclude=("maitai_back", "maitai_back.*")),
8
8
  install_requires=[
9
9
  'requests',
@@ -1,112 +0,0 @@
1
- import functools
2
- import inspect
3
- from typing import Any, Callable, Sequence, TypeVar, Union
4
-
5
- import openai.types.chat as openai_types
6
-
7
- import maitai_gen.chat as chat_types
8
- from maitai_gen.chat import EvaluateResponse
9
-
10
- CallableT = TypeVar("CallableT", bound=Callable[..., Any])
11
-
12
-
13
- def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]:
14
- def inner(func: CallableT) -> CallableT:
15
- params = inspect.signature(func).parameters
16
- positional = [
17
- name
18
- for name, param in params.items()
19
- if param.kind
20
- in {
21
- param.POSITIONAL_ONLY,
22
- param.POSITIONAL_OR_KEYWORD,
23
- }
24
- ]
25
-
26
- @functools.wraps(func)
27
- def wrapper(*args: object, **kwargs: object) -> object:
28
- given_params: set[str] = set()
29
- for i, _ in enumerate(args):
30
- try:
31
- given_params.add(positional[i])
32
- except IndexError:
33
- raise TypeError(
34
- f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given"
35
- ) from None
36
-
37
- for key in kwargs.keys():
38
- given_params.add(key)
39
-
40
- for variant in variants:
41
- matches = all((param in given_params for param in variant))
42
- if matches:
43
- break
44
- else: # no break
45
- if len(variants) > 1:
46
- variations = human_join(
47
- ["(" + human_join([quote(arg) for arg in variant], final="and") + ")" for variant in variants]
48
- )
49
- msg = f"Missing required arguments; Expected either {variations} arguments to be given"
50
- else:
51
- assert len(variants) > 0
52
-
53
- # TODO: this error message is not deterministic
54
- missing = list(set(variants[0]) - given_params)
55
- if len(missing) > 1:
56
- msg = f"Missing required arguments: {human_join([quote(arg) for arg in missing])}"
57
- else:
58
- msg = f"Missing required argument: {quote(missing[0])}"
59
- raise TypeError(msg)
60
- return func(*args, **kwargs)
61
-
62
- return wrapper # type: ignore
63
-
64
- return inner
65
-
66
-
67
- # copied from https://github.com/Rapptz/RoboDanny
68
- def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> str:
69
- size = len(seq)
70
- if size == 0:
71
- return ""
72
-
73
- if size == 1:
74
- return seq[0]
75
-
76
- if size == 2:
77
- return f"{seq[0]} {final} {seq[1]}"
78
-
79
- return delim.join(seq[:-1]) + f" {final} {seq[-1]}"
80
-
81
-
82
- def quote(string: str) -> str:
83
- """Add single quotation marks around the given string. Does *not* do any escaping."""
84
- return f"'{string}'"
85
-
86
-
87
- def convert_openai_chat_completion(chat: openai_types.ChatCompletion) -> chat_types.ChatCompletionResponse:
88
- return chat_types.ChatCompletionResponse().from_dict(chat.to_dict())
89
-
90
-
91
- def set_completion_evaluation_response(completion: chat_types.ChatCompletionResponse, response: EvaluateResponse):
92
- completion.evaluate_response = response
93
- try:
94
- completion.choices[0].message.content = response.evaluation_results[0].meta["correction_pre"]
95
- completion.original_choices = [_copy_choice(choice) for choice in completion.choices]
96
- except:
97
- pass
98
-
99
-
100
- def _copy_choice(choice: Union[openai_types.chat_completion.Choice, chat_types.ChatCompletionChoice]) -> chat_types.ChatCompletionChoice:
101
- message = chat_types.ChatMessage(content=choice.message.content, role=choice.message.role)
102
- copied_choice = chat_types.ChatCompletionChoice(finish_reason=choice.finish_reason, index=choice.index,
103
- logprobs=choice.logprobs, message=message)
104
- return copied_choice
105
-
106
-
107
- def set_chunk_evaluation_response(chunk: chat_types.ChatCompletionChunk, response: EvaluateResponse):
108
- chunk.evaluate_response = response
109
-
110
-
111
- def convert_open_ai_chat_completion_chunk(chunk: openai_types.ChatCompletionChunk) -> chat_types.ChatCompletionChunk:
112
- return chat_types.ChatCompletionChunk().from_dict(chunk.to_dict())