maitai-python 1.0.0b0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
maitai/_openai.py ADDED
@@ -0,0 +1,334 @@
1
+ from typing import 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, required_args, set_chunk_evaluation_response, set_completion_evaluation_response
13
+ 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.inference import InferenceStreamResponse
16
+
17
+ DEFAULT_MAX_RETRIES = 2
18
+
19
+
20
+ class MaiTaiOpenAIClient:
21
+ def __init__(
22
+ self,
23
+ *,
24
+ maitai_api_key: Optional[str] = None,
25
+ api_key: Optional[str] = None,
26
+ organization: Optional[str] = None,
27
+ project: Optional[str] = None,
28
+ base_url: Union[str, httpx.URL, None] = None,
29
+ timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NOT_GIVEN,
30
+ max_retries: int = DEFAULT_MAX_RETRIES,
31
+ default_headers: Optional[Mapping[str, str]] = None,
32
+ default_query: Optional[Mapping[str, object]] = None,
33
+ http_client: Optional[httpx.Client] = None,
34
+ _strict_response_validation: bool = False,
35
+ ):
36
+ if maitai_api_key:
37
+ config.initialize(maitai_api_key)
38
+ self.client = openai.OpenAI(
39
+ api_key=api_key,
40
+ organization=organization,
41
+ project=project,
42
+ base_url=base_url,
43
+ timeout=timeout,
44
+ max_retries=max_retries,
45
+ default_headers=default_headers,
46
+ default_query=default_query,
47
+ http_client=http_client,
48
+ )
49
+ self.chat = Chat(self.client)
50
+
51
+
52
+ class Chat:
53
+ def __init__(self, client=None):
54
+ self.completions = Completions(client)
55
+
56
+
57
+ class Completions:
58
+ def __init__(self, client: Optional[openai.Client] = None):
59
+ if client is None:
60
+ client = openai.OpenAI()
61
+ self.client = client
62
+
63
+ @required_args(["session_id", "action_type", "application_ref_name", "messages", "model"],
64
+ ["session_id", "action_type", "application_ref_name", "messages", "model", "stream"])
65
+ def create(
66
+ self,
67
+ *,
68
+ # Maitai Arguments
69
+ session_id: Union[str, int] = None,
70
+ reference_id: Union[str, int, None] = None,
71
+ action_type: str = None,
72
+ application_ref_name: str = None,
73
+ callback: Optional[EvaluateCallback] = None,
74
+ server_side_inference: bool = False, # TODO make this a config item
75
+ # OpenAI Arguments
76
+ messages: Iterable[openai_chat_types.ChatCompletionMessageParam],
77
+ model: Union[str, openai_types.ChatModel],
78
+ frequency_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
79
+ function_call: Union[openai_chat_types.completion_create_params.FunctionCall, openai.NotGiven] = openai.NOT_GIVEN,
80
+ functions: Union[Iterable[openai_chat_types.completion_create_params.Function], openai.NotGiven] = openai.NOT_GIVEN,
81
+ logit_bias: Union[Optional[Dict[str, int]], openai.NotGiven] = openai.NOT_GIVEN,
82
+ logprobs: Union[Optional[bool], openai.NotGiven] = openai.NOT_GIVEN,
83
+ max_tokens: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
84
+ n: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
85
+ presence_penalty: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
86
+ response_format: Union[openai_chat_types.completion_create_params.ResponseFormat, openai.NotGiven] = openai.NOT_GIVEN,
87
+ seed: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
88
+ stop: Union[Union[Optional[str], List[str]], openai.NotGiven] = openai.NOT_GIVEN,
89
+ stream: Optional[bool] = False,
90
+ stream_options: Union[Optional[openai_chat_types.ChatCompletionStreamOptionsParam], openai.NotGiven] = openai.NOT_GIVEN,
91
+ temperature: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
92
+ tool_choice: Union[openai_chat_types.ChatCompletionToolChoiceOptionParam, openai.NotGiven] = openai.NOT_GIVEN,
93
+ tools: Union[Iterable[openai_chat_types.ChatCompletionToolParam], openai.NotGiven] = openai.NOT_GIVEN,
94
+ top_logprobs: Union[Optional[int], openai.NotGiven] = openai.NOT_GIVEN,
95
+ top_p: Union[Optional[float], openai.NotGiven] = openai.NOT_GIVEN,
96
+ user: Union[str, openai.NotGiven] = openai.NOT_GIVEN,
97
+ extra_headers: Optional[Headers] = None,
98
+ extra_query: Optional[Query] = None,
99
+ extra_body: Optional[Body] = None,
100
+ timeout: Union[float, httpx.Timeout, None, openai.NotGiven] = openai.NOT_GIVEN,
101
+ ) -> Union[ChatCompletionResponse, Iterable[ChatCompletionChunk]]:
102
+ if not config.api_key:
103
+ raise ValueError("Maitai API Key has not been set")
104
+ if server_side_inference:
105
+ completion_params = get_chat_completion_params(
106
+ messages=messages,
107
+ model=model,
108
+ frequency_penalty=frequency_penalty,
109
+ logit_bias=logit_bias,
110
+ logprobs=logprobs,
111
+ max_tokens=max_tokens,
112
+ n=n,
113
+ presence_penalty=presence_penalty,
114
+ response_format=response_format,
115
+ seed=seed,
116
+ stop=stop,
117
+ stream=stream,
118
+ stream_options=stream_options,
119
+ temperature=temperature,
120
+ tool_choice=tool_choice,
121
+ tools=tools,
122
+ top_logprobs=top_logprobs,
123
+ top_p=top_p,
124
+ user=user,
125
+ )
126
+ response_timeout = None
127
+ if isinstance(timeout, float) or isinstance(timeout, int):
128
+ response_timeout = timeout
129
+ response = maitai.Inference.infer(session_id, reference_id, action_type, application_ref_name, completion_params, callback, timeout=response_timeout)
130
+ if stream:
131
+ return _process_inference_stream(response, callback)
132
+ # ChatCompletion only
133
+ chat_completion: Optional[ChatCompletionResponse] = None
134
+ for resp in response:
135
+ if callback:
136
+ return resp.chat_completion_response
137
+ else:
138
+ if resp.chat_completion_response:
139
+ chat_completion = resp.chat_completion_response
140
+ if resp.evaluate_response and chat_completion:
141
+ set_completion_evaluation_response(chat_completion, resp.evaluate_response)
142
+ return chat_completion
143
+ return chat_completion
144
+ else:
145
+ response = self.client.chat.completions.create(
146
+ messages=messages,
147
+ model=model,
148
+ frequency_penalty=frequency_penalty,
149
+ function_call=function_call,
150
+ functions=functions,
151
+ logit_bias=logit_bias,
152
+ logprobs=logprobs,
153
+ max_tokens=max_tokens,
154
+ n=n,
155
+ presence_penalty=presence_penalty,
156
+ response_format=response_format,
157
+ seed=seed,
158
+ stop=stop,
159
+ stream=stream,
160
+ stream_options=stream_options,
161
+ temperature=temperature,
162
+ tool_choice=tool_choice,
163
+ tools=tools,
164
+ top_logprobs=top_logprobs,
165
+ top_p=top_p,
166
+ user=user,
167
+ extra_headers=extra_headers,
168
+ extra_query=extra_query,
169
+ extra_body=extra_body,
170
+ timeout=timeout,
171
+
172
+ )
173
+ if stream:
174
+ return _process_stream(session_id, reference_id, action_type, application_ref_name, messages, response, callback)
175
+ else:
176
+ maitai_completion = convert_openai_chat_completion(response)
177
+ proto_messages = openai_messages_to_proto(messages)
178
+ proto_messages.append(
179
+ 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
+ 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
242
+ break
243
+ yield maitai_chunk
244
+
245
+
246
+ def _process_inference_stream(stream: Iterable[InferenceStreamResponse], callback: EvaluateCallback) -> Iterable[ChatCompletionChunk]:
247
+ last_chat_completion_chunk: Optional[ChatCompletionChunk] = None
248
+ 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
257
+ if chunk.choices[0].finish_reason:
258
+ if callback:
259
+ yield chunk
260
+ return
261
+ else:
262
+ 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
@@ -0,0 +1,13 @@
1
+ from typing import Mapping, Union
2
+
3
+ from typing_extensions import Literal
4
+
5
+
6
+ class Omit:
7
+ def __bool__(self) -> Literal[False]:
8
+ return False
9
+
10
+
11
+ Headers = Mapping[str, Union[str, Omit]]
12
+ Query = Mapping[str, object]
13
+ Body = object
maitai/_types.py ADDED
@@ -0,0 +1,37 @@
1
+ import queue
2
+ from typing import Callable, Union
3
+
4
+ import maitai_gen.chat as chat_types
5
+ from maitai_gen.chat import EvaluateResponse
6
+
7
+ ChunkQueue = queue.Queue[Union[chat_types.ChatCompletionChunk, "done"]]
8
+
9
+
10
+ class QueueIterable:
11
+ def __init__(self, chunk_queue: ChunkQueue, timeout=None) -> None:
12
+ self.queue = chunk_queue
13
+ self.done = False # Indicates if "done" token has been received
14
+ self.timeout = timeout
15
+
16
+ def __iter__(self):
17
+ """Returns the iterator object itself."""
18
+ return self
19
+
20
+ def __next__(self) -> chat_types.ChatCompletionChunk:
21
+ """Waits for the next item from the queue or raises StopIteration if "done"."""
22
+ while not self.done:
23
+ try:
24
+ # Wait for an item from the queue, block if necessary
25
+ item = self.queue.get(timeout=self.timeout) # Wait for 10 seconds, adjust as needed
26
+ if item == "done":
27
+ self.done = True # Set done to True to prevent further blocking
28
+ raise StopIteration
29
+ return item
30
+ except queue.Empty:
31
+ print("Queue timed out")
32
+ self.done = True
33
+ raise TimeoutError
34
+ raise StopIteration
35
+
36
+
37
+ EvaluateCallback = Callable[[EvaluateResponse], None]
maitai/_utils.py ADDED
@@ -0,0 +1,112 @@
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())
File without changes
File without changes
@@ -0,0 +1,62 @@
1
+ import threading
2
+ import time
3
+ from threading import Thread
4
+
5
+
6
+ class IOThread(Thread):
7
+ def __init__(self, interval=0.1, name=None):
8
+ super(IOThread, self).__init__(name=name)
9
+ self.input = None
10
+ self.output = None
11
+ self.run_thread = True
12
+ self.is_running = False
13
+ self.initialized = False
14
+ self.interval = interval
15
+ self.completed_loops = 0
16
+ self.avg_loop_time = 0
17
+ self.cleaned = False
18
+ self.timer_thread = None
19
+ self.last_loop_start = -1
20
+ self.child_name = self.__class__.__name__ if name is None else name
21
+
22
+ def run(self):
23
+ if not self.initialized:
24
+ self.initialize()
25
+ time.sleep(self.interval)
26
+ self.loop()
27
+
28
+ def loop(self):
29
+ if self.run_thread:
30
+ self.last_loop_start = time.time()
31
+ self.is_running = True
32
+ try:
33
+ self.process()
34
+ except Exception as e:
35
+ print(e, f'[{self.child_name}] Exception hit processing')
36
+ finally:
37
+ self.is_running = False
38
+
39
+ delta = time.time() - self.last_loop_start
40
+ self.avg_loop_time = ((self.avg_loop_time * self.completed_loops) * delta) / (self.completed_loops + 1)
41
+ self.completed_loops += 1
42
+ next_run = self.interval - delta
43
+ self.timer_thread = threading.Timer(0 if next_run < 0 else next_run, self.loop)
44
+ self.timer_thread.name = self.child_name
45
+ self.timer_thread.start()
46
+ else:
47
+ if self.timer_thread is not None:
48
+ self.timer_thread.cancel()
49
+ self.cleaned = True
50
+
51
+ def terminate(self):
52
+ self.run_thread = False
53
+ if self.timer_thread is not None:
54
+ self.timer_thread.cancel()
55
+ self.cleaned = True
56
+ print(f'{self.child_name} cleaned up')
57
+
58
+ def process(self):
59
+ return None
60
+
61
+ def initialize(self):
62
+ self.initialized = True
@@ -0,0 +1,95 @@
1
+ import threading
2
+
3
+ import websocket
4
+
5
+ from maitai_common.processes.io_thread import IOThread
6
+
7
+
8
+ class WebsocketListenerThread(IOThread):
9
+ def __init__(self, path, type, key=None):
10
+ super(WebsocketListenerThread, self).__init__(interval=60)
11
+ self.child_name = f'{self.__class__.__name__}'
12
+ self.messages = []
13
+ self.ws_url = f'{path}?type={type}'
14
+ if key:
15
+ self.ws_url += f'&key={key}'
16
+ self.ws = None
17
+ self.ws_threads = []
18
+ self.closing_ws = False # Add a shutdown flag
19
+ self.connection_established_event = threading.Event() # Add an event attribute
20
+
21
+ def connect_to_websocket(self):
22
+ self.connection_established_event.clear() # Clear the event before attempting a new connection
23
+ if self.run_thread and not self.closing_ws:
24
+ self.ws = websocket.WebSocketApp(
25
+ self.ws_url,
26
+ on_message=self.on_message,
27
+ on_close=self.on_close,
28
+ on_error=self.on_error,
29
+ on_open=self.on_open
30
+ )
31
+ # Starting a new thread to handle the WebSocket connection
32
+ ws_thread = threading.Thread(target=self.ws.run_forever, name="WebsocketThread")
33
+ ws_thread.start()
34
+ tmp = [ws_thread]
35
+ for t in self.ws_threads:
36
+ if t.is_alive():
37
+ tmp.append(t)
38
+ self.ws_threads = tmp
39
+
40
+ def on_message(self, ws, message):
41
+ print(f'Received message: {message}')
42
+ self.messages.append(message)
43
+
44
+ def on_close(self, ws):
45
+ print("WebSocket connection closed. Reconnecting...")
46
+ self.connect_to_websocket()
47
+
48
+ def on_open(self, ws):
49
+ self.connection_established_event.set() # Set the event when connection is open
50
+ if not self.run_thread or self.closing_ws:
51
+ ws.close()
52
+ if self.ws:
53
+ self.ws.close()
54
+
55
+ def on_error(self, ws, error):
56
+ print(f"WebSocket error: {error}. Reconnecting...")
57
+ self.connect_to_websocket()
58
+
59
+ def initialize(self):
60
+ self.connect_to_websocket()
61
+
62
+ super(WebsocketListenerThread, self).initialize()
63
+
64
+ def terminate(self):
65
+ self.closing_ws = True # Indicate that shutdown is in progress
66
+ if self.ws:
67
+ self.ws.close()
68
+ for i, ws_thread in enumerate(self.ws_threads):
69
+ if ws_thread.is_alive():
70
+ ws_thread.join(timeout=1)
71
+ super(WebsocketListenerThread, self).terminate()
72
+
73
+ def clear(self):
74
+ self.messages = []
75
+
76
+ def process(self):
77
+ if self.run_thread:
78
+ old_ws = self.ws
79
+ # Temporarily override the on_close to prevent reconnection
80
+ old_on_close = old_ws.on_close
81
+ old_ws.on_close = lambda *args, **kwargs: None
82
+
83
+ try:
84
+ # Try to establish a new connection
85
+ self.connect_to_websocket()
86
+ # Wait for the on_open callback to set the event
87
+ self.connection_established_event.wait()
88
+ # If successful, close the old connection
89
+ old_ws.close()
90
+ except Exception as e:
91
+ # If new connection fails, keep the old connection
92
+ old_ws.on_close = old_on_close
93
+ self.ws = old_ws
94
+
95
+ super(WebsocketListenerThread, self).process()
File without changes
@@ -0,0 +1,13 @@
1
+ from typing import Iterable
2
+
3
+ from openai.types.chat import ChatCompletionMessageParam
4
+
5
+ from maitai_gen.chat import ChatMessage
6
+
7
+
8
+ def openai_messages_to_proto(messages: Iterable[ChatCompletionMessageParam]):
9
+ proto_messages: [ChatMessage] = []
10
+ for message in messages:
11
+ proto_messages.append(
12
+ ChatMessage(role=message["role"], content=message["content"]))
13
+ return proto_messages
maitai_gen/__init__.py ADDED
File without changes