maitai-python 1.2.15__py3-none-any.whl → 1.2.16__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/_config.py CHANGED
@@ -3,7 +3,7 @@ import os
3
3
  import threading
4
4
  from typing import List
5
5
 
6
- from maitai._config_listener_thread import ConfigListenerThread
6
+ from maitai._config_listener import ConfigListener
7
7
  from maitai._maitai_client import MaitaiClient
8
8
  from maitai.models.application import Application
9
9
  from maitai.models.config import Config as ActionConfig
@@ -21,7 +21,7 @@ class Config(MaitaiClient):
21
21
  self._api_key = None
22
22
  self._company_id = None
23
23
  self.websocket_listener_thread = None
24
- self.config_listener_thread = None
24
+ self.config_listener = None
25
25
  self._application_action_configs: dict[str, dict[str, ActionConfig]] = {}
26
26
  self.initialized = False
27
27
  self.auth_keys: KeyMap = KeyMap(
@@ -161,22 +161,14 @@ class Config(MaitaiClient):
161
161
  )
162
162
 
163
163
  def _initialize_websocket(self):
164
- self.config_listener_thread = ConfigListenerThread(
164
+ self.config_listener = ConfigListener(
165
165
  self, self.maitai_ws, "APPLICATION_CONFIG_CHANGE", self._company_id
166
166
  )
167
- self.config_listener_thread.daemon = True
168
- self.config_listener_thread.start()
167
+ self.config_listener.start()
169
168
 
170
169
  def cleanup(self):
171
- if self.config_listener_thread:
172
- self.config_listener_thread.terminate()
173
- try:
174
- self.config_listener_thread.join(
175
- timeout=1.0
176
- ) # Give thread time to cleanup
177
- except Exception:
178
- pass # If join fails, continue with cleanup
179
- self.config_listener_thread = None
170
+ if self.config_listener:
171
+ self.config_listener.stop()
180
172
 
181
173
  if self.refresh_timer:
182
174
  self.refresh_timer.cancel()
@@ -0,0 +1,136 @@
1
+ import json
2
+ import logging
3
+ import os
4
+ import threading
5
+
6
+ import websocket
7
+
8
+ from maitai.models.application import Application
9
+
10
+
11
+ class ConfigListener:
12
+ def __init__(self, config, path, type, key=None):
13
+ self.config = config
14
+ self.ws_url = f"{path}?type={type}"
15
+ if key:
16
+ self.ws_url += f"&key={key}"
17
+
18
+ self.ws = None
19
+ self.ws_thread = None
20
+ self.running = False
21
+
22
+ def on_message(self, ws, message):
23
+ event = json.loads(message)
24
+ if event.get("event_type") == "APPLICATION_CONFIG_CHANGE":
25
+ application_json = event.get("event_data")
26
+ if application_json:
27
+ try:
28
+ application = Application.model_validate(application_json)
29
+ logging.log("Maitai received configuration change")
30
+ self.config.store_application_metadata([application])
31
+ except Exception as e:
32
+ if os.environ.get("MAITAI_ENV") in [
33
+ "development",
34
+ "staging",
35
+ "prod",
36
+ ]:
37
+ logging.error(
38
+ "Error refreshing applications",
39
+ exc_info=e,
40
+ )
41
+ self.config.refresh_applications()
42
+ else:
43
+ self.config.refresh_applications()
44
+
45
+ def on_error(self, ws, error):
46
+ if not isinstance(error, (AttributeError, ConnectionError)):
47
+ logging.error(f"Maitai config websocket error: {error}")
48
+
49
+ def on_close(self, ws, close_status_code, close_msg):
50
+ logging.info(
51
+ f"Maitai config websocket connection closed: {close_status_code} {close_msg}"
52
+ )
53
+
54
+ def on_open(self, ws):
55
+ logging.info(f"Maitai config websocket connection established")
56
+
57
+ def _websocket_thread(self):
58
+ """Run the websocket client in a thread with automatic reconnection."""
59
+ retry_count = 0
60
+ max_retries = 10
61
+ reconnect_delay = 3 # Start with 3 seconds
62
+
63
+ while self.running and retry_count < max_retries:
64
+ try:
65
+ # Create new websocket connection
66
+ self.ws = websocket.WebSocketApp(
67
+ self.ws_url,
68
+ on_message=self.on_message,
69
+ on_error=self.on_error,
70
+ on_close=self.on_close,
71
+ on_open=self.on_open,
72
+ )
73
+
74
+ # Run the websocket (this blocks until connection closes)
75
+ self.ws.run_forever(ping_interval=30, ping_timeout=10)
76
+
77
+ # If we get here, connection closed - retry with backoff if still running
78
+ if self.running:
79
+ retry_count += 1
80
+ # Exponential backoff with max of 60 seconds
81
+ retry_delay = min(reconnect_delay * (2**retry_count), 60)
82
+ logging.info(f"Websocket reconnecting in {retry_delay} seconds...")
83
+ threading.Event().wait(retry_delay)
84
+ except Exception as e:
85
+ logging.error(f"Error in websocket thread: {e}")
86
+ if self.running:
87
+ retry_count += 1
88
+ # Exponential backoff with max of 60 seconds
89
+ retry_delay = min(reconnect_delay * (2**retry_count), 60)
90
+ logging.info(f"Websocket reconnecting in {retry_delay} seconds...")
91
+ threading.Event().wait(retry_delay)
92
+
93
+ def _reconnect(self):
94
+ """Attempt to reconnect the websocket."""
95
+ if self.ws:
96
+ try:
97
+ self.ws.close()
98
+ except:
99
+ pass
100
+ self.ws = None
101
+
102
+ def start(self):
103
+ """Start the websocket connection."""
104
+ if self.running:
105
+ return
106
+
107
+ self.running = True
108
+
109
+ # Start websocket in a separate thread with reconnection logic
110
+ self.ws_thread = threading.Thread(
111
+ target=self._websocket_thread,
112
+ name="WebsocketThread",
113
+ daemon=True,
114
+ )
115
+ self.ws_thread.start()
116
+
117
+ def stop(self):
118
+ """Stop the websocket connection."""
119
+ if not self.running:
120
+ return
121
+
122
+ self.running = False
123
+
124
+ # Close the websocket connection
125
+ if self.ws:
126
+ try:
127
+ self.ws.close()
128
+ except Exception as e:
129
+ logging.debug(f"Error closing websocket: {e}")
130
+
131
+ # Wait for the thread to finish
132
+ if self.ws_thread and self.ws_thread.is_alive():
133
+ self.ws_thread.join(timeout=2.0)
134
+
135
+ self.ws = None
136
+ self.ws_thread = None
maitai/_maitai_async.py CHANGED
@@ -533,7 +533,7 @@ class AsyncCompletions:
533
533
  metadata=metadata,
534
534
  )
535
535
  else:
536
- self.inference_client.store_chat_response_async(
536
+ await self.inference_client.store_chat_response_async(
537
537
  session_id=session_id,
538
538
  reference_id=reference_id,
539
539
  intent=intent,
@@ -598,7 +598,7 @@ class AsyncCompletions:
598
598
  metadata=metadata,
599
599
  )
600
600
  else:
601
- self.inference_client.store_chat_response_async(
601
+ await self.inference_client.store_chat_response_async(
602
602
  session_id=session_id,
603
603
  reference_id=reference_id,
604
604
  intent=intent,
maitai/_maitai_client.py CHANGED
@@ -70,8 +70,10 @@ def _determine_maitai_host():
70
70
  if gcp_zone:
71
71
  if "us-west1" in gcp_zone:
72
72
  return "https://api.gcp.us-west1.trymaitai.ai"
73
- elif "us-central1" in gcp_zone:
74
- return "https://api.gcp.us-central1.trymaitai.ai"
73
+ # elif "us-central1" in gcp_zone:
74
+ # return "https://api.gcp.us-central1.trymaitai.ai"
75
+ elif "us-south1" in gcp_zone:
76
+ return "https://api.gcp.us-south1.trymaitai.ai"
75
77
 
76
78
  azure_region = _get_azure_instance_metadata()
77
79
  if azure_region == "westus2":
@@ -8,7 +8,7 @@ from maitai.models.config import Config
8
8
 
9
9
  class ApplicationObjective(BaseModel):
10
10
  id: Optional[int] = 0
11
- date_created: Optional[Union[int, float]] = 0
11
+ date_created: Optional[float] = 0
12
12
  application_id: int
13
13
  objective_body: Dict[str, str] = Field(default_factory=dict)
14
14
 
@@ -16,7 +16,7 @@ class ApplicationObjective(BaseModel):
16
16
  class ApplicationAction(BaseModel):
17
17
  id: Optional[int] = -1
18
18
  action_type: str
19
- date_created: Optional[Union[int, float]] = 0
19
+ date_created: Optional[float] = 0
20
20
  application_id: int
21
21
  meta: Optional[Config] = None
22
22
  last_activity: Optional[int] = 0
@@ -28,7 +28,7 @@ class ApplicationAction(BaseModel):
28
28
 
29
29
  class Application(BaseModel):
30
30
  id: Optional[int] = -1
31
- date_created: Optional[Union[int, float]] = 0
31
+ date_created: Optional[float] = 0
32
32
  application_name: Optional[str] = None
33
33
  application_ref_name: Optional[str] = None
34
34
  company_id: int = 0
@@ -43,7 +43,7 @@ class Application(BaseModel):
43
43
 
44
44
  class ApplicationContext(BaseModel):
45
45
  id: Optional[int] = -1
46
- date_created: Optional[Union[int, float]] = 0
46
+ date_created: Optional[float] = 0
47
47
  application_id: Optional[int] = None
48
48
  context_body: Optional[Union[str, Dict[Any, Any]]] = None
49
49
  context_path: Optional[str] = None
maitai/models/chat.py CHANGED
@@ -1,4 +1,5 @@
1
1
  # codegen: frontend, sdk
2
+ import time
2
3
  import uuid
3
4
  from enum import Enum, IntEnum
4
5
  from typing import Any, Dict, List, Optional, Union
@@ -152,7 +153,7 @@ class ChatCompletionRequest(BaseModel):
152
153
  company_id: Optional[int] = None
153
154
  apply_corrections: Optional[bool] = False
154
155
  id: Optional[int] = None
155
- date_created: Optional[int] = None
156
+ date_created: Optional[float] = None
156
157
  request_id: Optional[str] = None
157
158
  evaluation_enabled: Optional[bool] = True
158
159
  auth_info: Optional[ChatCompletionAuth] = ChatCompletionAuth()
@@ -233,8 +234,8 @@ class EvaluateResult(BaseModel):
233
234
  confidence: Optional[float] = None
234
235
  meta: Dict[str, Any] = Field(default_factory=dict)
235
236
  sentinel_id: Optional[int] = None
236
- eval_time: Optional[int] = 0
237
- date_created: Optional[Union[int, float]] = 0
237
+ eval_time: Optional[float] = 0
238
+ date_created: Optional[float] = 0
238
239
  usage: Optional[ChatCompletionUsage] = None
239
240
  sentinel_name: Optional[str] = None
240
241
  severity: Optional[int] = None
@@ -253,10 +254,10 @@ class EvaluateResponse(BaseModel):
253
254
  evaluation_results: List[EvaluateResult] = Field(default_factory=list)
254
255
  evaluation_request_id: Optional[str] = None
255
256
  evaluate_summary: Optional[str] = None
256
- evaluation_time: Optional[int] = None
257
+ evaluation_time: Optional[float] = None
257
258
  reference_id: Optional[Union[str, int]] = None
258
259
  id: Optional[int] = -1
259
- date_created: Optional[Union[int, float]] = 0
260
+ date_created: Optional[float] = 0
260
261
  correction: Optional[str] = None
261
262
  meta: Dict[str, Any] = Field(default_factory=dict)
262
263
 
@@ -264,7 +265,7 @@ class EvaluateResponse(BaseModel):
264
265
  class ChatCompletionResponse(BaseModel):
265
266
  id: Optional[Union[int, str]] = None
266
267
  object: str = "chat.completion"
267
- created: int = 0
268
+ created: float = Field(default_factory=time.time)
268
269
  model: str = None
269
270
  system_fingerprint: Optional[str] = None
270
271
  choices: List[ChatCompletionChoice] = Field(default_factory=list)
@@ -315,7 +316,7 @@ class ChunkChoice(BaseModel):
315
316
  class ChatCompletionChunk(BaseModel):
316
317
  id: str = ""
317
318
  choices: List[ChunkChoice] = Field(default_factory=list)
318
- created: int = 0
319
+ created: float = Field(default_factory=time.time)
319
320
  model: str = ""
320
321
  object: str = ""
321
322
  system_fingerprint: Optional[str] = ""
@@ -347,7 +348,7 @@ class EvaluateRequest(BaseModel):
347
348
  model_config = ConfigDict(use_enum_values=True)
348
349
 
349
350
  id: Optional[int] = None
350
- date_created: Optional[int] = None
351
+ date_created: Optional[float] = None
351
352
  application_id: Optional[int] = None
352
353
  application_ref_name: str = None
353
354
  session_id: str = None
@@ -390,7 +391,7 @@ class SessionMessage(BaseModel):
390
391
  role: str
391
392
  message: ChatMessage
392
393
  instructions: str
393
- date_created: Optional[Union[int, float]] = 0
394
+ date_created: Optional[float] = 0
394
395
 
395
396
 
396
397
  # This is needed because of the forward reference in Property
maitai/models/event.py CHANGED
@@ -6,7 +6,7 @@ from pydantic import BaseModel, Field
6
6
 
7
7
  class Event(BaseModel):
8
8
  id: Optional[int] = -1
9
- date_created: Optional[Union[int, float]] = 0
9
+ date_created: Optional[float] = 0
10
10
  event_type: str
11
11
  event_key: str
12
12
  event_data: str
maitai/models/key.py CHANGED
@@ -1,12 +1,12 @@
1
1
  # codegen: frontend, sdk
2
- from typing import Optional, Union
2
+ from typing import Optional
3
3
 
4
4
  from pydantic import BaseModel
5
5
 
6
6
 
7
7
  class Key(BaseModel):
8
8
  id: Optional[int] = 0
9
- date_created: Optional[Union[int, float]] = 0
9
+ date_created: Optional[float] = 0
10
10
  key_value: Optional[str] = None
11
11
  company_id: int = 0
12
12
  description: str = ""
maitai/models/sentinel.py CHANGED
@@ -26,7 +26,7 @@ class DirectiveBody(BaseModel):
26
26
  class SentinelDirective(BaseModel):
27
27
  id: Optional[int] = -1
28
28
  sentinel_id: Optional[int] = None
29
- date_created: Optional[Union[int, float]] = 0
29
+ date_created: Optional[float] = 0
30
30
  directive_body: DirectiveBody
31
31
  examples: List[SentinelExample] = Field(default_factory=list)
32
32
 
@@ -42,7 +42,7 @@ class Sentinel(BaseModel):
42
42
  id: Optional[int] = -1
43
43
  application_id: Optional[int] = None
44
44
  sentinel_name: str
45
- date_created: Optional[Union[int, float]] = 0
45
+ date_created: Optional[float] = 0
46
46
  sentinel_directive: Optional[SentinelDirective] = None
47
47
  state: Optional[str] = None
48
48
  action_types: List[str] = None
@@ -56,7 +56,7 @@ class Sentinel(BaseModel):
56
56
 
57
57
  class SentinelGeneration(BaseModel):
58
58
  id: Optional[int] = -1
59
- date_created: Optional[Union[int, float]] = 0
59
+ date_created: Optional[float] = 0
60
60
  company_id: int = 0
61
61
  application_id: Optional[int] = None
62
62
  application_action_id: Optional[int] = None
maitai_common/version.py CHANGED
@@ -1,3 +1,3 @@
1
- version = "1.2.15"
1
+ version = "1.2.16"
2
2
  if __name__ == "__main__":
3
3
  print(version)
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: maitai-python
3
- Version: 1.2.15
3
+ Version: 1.2.16
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -0,0 +1,31 @@
1
+ maitai/__init__.py,sha256=UocvQ1455PnA27V1S6vk3yc_BysjTgLGbwfdMF2eL0A,336
2
+ maitai/_config.py,sha256=cIZ7epkjYIhrrjUgOV04RLw1AL5E1HR27RBkrg_WvfA,6947
3
+ maitai/_config_listener.py,sha256=LhwX-SsbnO74qMjit8xQtEyH5U-s5bSIgpdov4d90oQ,4697
4
+ maitai/_context.py,sha256=WMLqfG68SR9jMIQ-p6eh-jyA2p4jknR4MXIsWntg8Cc,2482
5
+ maitai/_evaluator.py,sha256=bGxMTe5zEos0jeP7iz-7RrfJyCaUx-W90vpGaHQQMl8,11633
6
+ maitai/_inference.py,sha256=4fh9wndwculf-KkJ0auYJlbWNMi46V9ouuPScw_aIKw,12057
7
+ maitai/_maitai.py,sha256=JuMsa-a9PIezoZGmOtgupuLyPZLj9Y9Cg-LynXGZIYs,27911
8
+ maitai/_maitai_async.py,sha256=8Tlzd8JmdEq-I4piu00njBr_EzwdCgumXQfUEgH06jw,27924
9
+ maitai/_maitai_client.py,sha256=3-Mt7yVBpnErmRkoADW0DT7WdQDAFAfjTEVrS5QXooY,5807
10
+ maitai/_pydantic.py,sha256=8clflOhR7-6AeLFBzmsYO0aaQSAkp8KMuxsrYwPthaA,5683
11
+ maitai/_types.py,sha256=C_ifBii5KdQuxcNwFv8RKHOZVgIBuatDSwfYISDip_k,5069
12
+ maitai/_utils.py,sha256=2sAG6D-ZFcFUqiGzxMp76ySnS-8xpsIdB2iDdfbXg6s,10861
13
+ maitai/exceptions.py,sha256=n0jwH3dhq8ewdgkCHTaaMd1GeB3EL_zulytnwqD3XUg,500
14
+ maitai/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ maitai/models/application.py,sha256=nfddjI5gt56MkSZgvG-EZmsO3JFxpAA5mzPwVoGig10,1656
16
+ maitai/models/chat.py,sha256=Fz4HCknWKus2EbZNXGbxRoPHdWpDO1VuLc9t-jeJDJ4,12633
17
+ maitai/models/config.py,sha256=zOgcuag-WHtVQgRhQrZchCP5gCjV0bszNDowL2WRrjY,1989
18
+ maitai/models/event.py,sha256=xrwSCP-nVdFsO6F30pmYdSg9M_L1RG-0vj9e_17amEY,313
19
+ maitai/models/inference.py,sha256=lySiDgdsu6IdX7KG8O6orjZokeX5mR4OnLuJFJykY68,516
20
+ maitai/models/key.py,sha256=kmSy3bx7HY063jcCZumgoV68jCvq7MK-NSVe3UIBnF0,930
21
+ maitai/models/metric.py,sha256=iL1FqaJ-3ii5pgY4cGZKp0nuQVG1XnBggopazQhGN_E,451
22
+ maitai/models/sentinel.py,sha256=QwjxnVnZJdPz9t-hlQwQO8Uxd6JDRziqpZnlUV4Q2rY,1779
23
+ maitai/tools/__init__.py,sha256=Fo7tOLJNFbFtVN9LI8fpFUPk95lcq97Pp1TP5-2NU3s,4086
24
+ maitai_common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
25
+ maitai_common/version.py,sha256=uTKVEd5FdnBrZD2NV0LbFaIpkLdRdTLGLDbbK5wKotQ,65
26
+ maitai_common/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
27
+ maitai_common/config/config_service.py,sha256=CRUz-LYyGxCaDqqkqaJ6CyhpTKr11NKux104oU__NBg,1110
28
+ maitai_python-1.2.16.dist-info/METADATA,sha256=Nn5nz8mX9gL7Ve9j4JPeIcwWNOSESj4wPv-TTVzO6NA,1662
29
+ maitai_python-1.2.16.dist-info/WHEEL,sha256=1tXe9gY0PYatrMPMDd6jXqjfpz_B-Wqm32CPfRC58XU,91
30
+ maitai_python-1.2.16.dist-info/top_level.txt,sha256=3uBDd_HUkDZhdPkUjbHJpoKMT3YoYszkUeOLIxgjzUo,21
31
+ maitai_python-1.2.16.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (76.0.0)
2
+ Generator: setuptools (77.0.3)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,31 +0,0 @@
1
- import json
2
- import logging
3
- import os
4
-
5
- from maitai.models.application import Application
6
- from maitai_common.processes.websocket_listener_thread import WebsocketListenerThread
7
-
8
-
9
- class ConfigListenerThread(WebsocketListenerThread):
10
- def __init__(self, config, path, type, key=None):
11
- super(ConfigListenerThread, self).__init__(path, type, key, interval=60)
12
- self.config = config
13
-
14
- def on_message(self, ws, message):
15
- event = json.loads(message)
16
- if event.get("event_type") == "APPLICATION_CONFIG_CHANGE":
17
- application_json = event.get("event_data")
18
- if application_json:
19
- try:
20
- application = Application.model_validate(application_json)
21
- logging.log("Maitai received configuration change")
22
- self.config.store_application_metadata([application])
23
- except Exception as e:
24
- if os.environ.get("MAITAI_ENV") == "development":
25
- logging.error(
26
- "Error refreshing applications",
27
- exc_info=e,
28
- )
29
- self.config.refresh_applications()
30
- else:
31
- self.config.refresh_applications()
File without changes
@@ -1,73 +0,0 @@
1
- import asyncio
2
- import time
3
- import traceback
4
- from threading import Thread
5
-
6
-
7
- class IOThread(Thread):
8
- def __init__(self, interval=0.1, name=None):
9
- super(IOThread, self).__init__(name=name)
10
- self.input = None
11
- self.output = None
12
- self.run_thread = True
13
- self.is_running = False
14
- self.initialized = False
15
- self.interval = interval
16
- self.completed_loops = 0
17
- self.avg_loop_time = 0
18
- self.cleaned = False
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
- asyncio.run(self.main_loop())
26
-
27
- async def main_loop(self):
28
- await asyncio.sleep(self.interval)
29
- while self.run_thread:
30
- await self.process_loop()
31
-
32
- async def process_loop(self):
33
- if self.run_thread:
34
- self.last_loop_start = time.time()
35
- self.is_running = True
36
- try:
37
- self.process()
38
- await self.process_async()
39
- except Exception as e:
40
- self.print(
41
- e,
42
- f"[{self.child_name}] Exception hit processing",
43
- traceback.format_exc(),
44
- )
45
- finally:
46
- self.is_running = False
47
-
48
- delta = time.time() - self.last_loop_start
49
- self.avg_loop_time = (
50
- (self.avg_loop_time * self.completed_loops) * delta
51
- ) / (self.completed_loops + 1)
52
- self.completed_loops += 1
53
- next_run = self.interval - delta
54
- await asyncio.sleep(max(0, next_run))
55
- else:
56
- self.cleaned = True
57
-
58
- def terminate(self):
59
- self.run_thread = False
60
- self.cleaned = True
61
- self.print(f"{self.child_name} cleaned up")
62
-
63
- def process(self):
64
- return None
65
-
66
- async def process_async(self):
67
- return None
68
-
69
- def initialize(self):
70
- self.initialized = True
71
-
72
- def print(self, *args, **kwargs):
73
- print(*args, **kwargs)
@@ -1,155 +0,0 @@
1
- import logging
2
- import threading
3
- import time
4
-
5
- import websocket
6
-
7
- from maitai_common.processes.io_thread import IOThread
8
-
9
- logging.getLogger("websocket").setLevel(logging.FATAL)
10
-
11
-
12
- class WebsocketListenerThread(IOThread):
13
- def __init__(self, path, type, key=None, interval=60):
14
- super(WebsocketListenerThread, self).__init__(interval=interval)
15
- self.child_name = f"{self.__class__.__name__}"
16
- self.messages = []
17
- self.ws_url = f"{path}?type={type}"
18
- if key:
19
- self.ws_url += f"&key={key}"
20
- self.ws = None
21
- self.ws_thread = None # Single thread reference
22
- self.closing_ws = False
23
- self.connection_established_event = threading.Event()
24
- self.retry_backoff = 1
25
- self.connection_lock = threading.Lock()
26
- self.last_reconnect_attempt = None
27
-
28
- def connect_to_websocket(self):
29
- self.connection_established_event.clear()
30
- with self.connection_lock:
31
- # Only create new connection if we're still running
32
- if self.run_thread and not self.closing_ws:
33
- old_ws = self.ws
34
- self.ws = websocket.WebSocketApp(
35
- self.ws_url,
36
- on_message=self.on_message,
37
- on_close=self.on_close,
38
- on_error=self.on_error,
39
- on_open=self.on_open,
40
- )
41
- old_ws_thread = None
42
- if self.ws_thread and self.ws_thread.is_alive():
43
- # Store reference to old thread but don't join it here
44
- old_ws_thread = self.ws_thread
45
-
46
- # Create and start new thread
47
- self.ws_thread = threading.Thread(
48
- target=self.ws.run_forever, name="WebsocketThread", daemon=True
49
- )
50
- self.ws_thread.start()
51
- self.retry_backoff = 1
52
-
53
- # Close old websocket connection
54
- if old_ws:
55
- old_ws.close()
56
-
57
- # Only join the old thread if it's not the current thread
58
- if old_ws_thread and old_ws_thread != threading.current_thread():
59
- old_ws_thread.join(timeout=2.0)
60
-
61
- def on_message(self, ws, message):
62
- self.messages.append(message)
63
-
64
- def on_close(self, ws, _, __):
65
- if self.run_thread and not self.closing_ws:
66
- # Add a small delay before reconnecting to prevent rapid reconnection cycles
67
- time.sleep(self.retry_backoff)
68
- self.retry_backoff = min(
69
- self.retry_backoff * 2, 60
70
- ) # Increase max backoff time
71
- self.connect_to_websocket()
72
-
73
- def on_open(self, ws):
74
- self.connection_established_event.set() # Set the event when connection is open
75
- if not self.run_thread or self.closing_ws:
76
- ws.close()
77
- if self.ws:
78
- self.ws.close()
79
-
80
- def on_error(self, ws, error):
81
- # Log the error to help with debugging
82
- logging.error(f"WebSocket error: {error}")
83
-
84
- # Don't attempt to reconnect from within the websocket thread
85
- # Instead, let the process method handle reconnection
86
- if threading.current_thread() != self.ws_thread:
87
- time.sleep(self.retry_backoff)
88
- self.retry_backoff *= 2
89
- self.retry_backoff = min(
90
- self.retry_backoff, 60
91
- ) # Increase max backoff time
92
- self.connect_to_websocket()
93
-
94
- def initialize(self):
95
- self.connect_to_websocket()
96
-
97
- super(WebsocketListenerThread, self).initialize()
98
-
99
- def terminate(self):
100
- self.closing_ws = True
101
- if self.ws:
102
- self.ws.close()
103
-
104
- # Join the single thread with timeout
105
- if self.ws_thread and self.ws_thread.is_alive():
106
- self.ws_thread.join(timeout=2.0)
107
-
108
- self.ws_thread = None
109
- super(WebsocketListenerThread, self).terminate()
110
-
111
- def clear(self):
112
- self.messages = []
113
-
114
- def process(self):
115
- if self.run_thread:
116
- # Check if websocket is connected and functioning
117
- if (
118
- not self.ws
119
- or not (self.ws and self.ws.sock)
120
- or not (self.ws.sock and self.ws.sock.connected)
121
- ):
122
- # Add connection attempt tracking to prevent excessive reconnects
123
- if (
124
- hasattr(self, "last_reconnect_attempt")
125
- and time.time() - self.last_reconnect_attempt < self.retry_backoff
126
- ):
127
- # Skip reconnection attempt if we tried recently
128
- pass
129
- else:
130
- self.last_reconnect_attempt = time.time()
131
- old_ws = self.ws
132
- # Temporarily override the on_close to prevent reconnection
133
- old_on_close = None
134
- if old_ws:
135
- old_on_close = old_ws.on_close
136
- old_ws.on_close = lambda *args, **kwargs: None
137
-
138
- try:
139
- # Try to establish a new connection
140
- self.connect_to_websocket()
141
- # Wait for the on_open callback to set the event with a timeout
142
- connection_success = self.connection_established_event.wait(
143
- timeout=10
144
- )
145
- # If successful, close the old connection
146
- if old_ws and connection_success:
147
- old_ws.close()
148
- except Exception as e:
149
- logging.error(f"Error reconnecting to WebSocket: {e}")
150
- # If new connection fails, keep the old connection
151
- if old_ws and old_on_close:
152
- old_ws.on_close = old_on_close
153
- self.ws = old_ws
154
-
155
- super(WebsocketListenerThread, self).process()
@@ -1,34 +0,0 @@
1
- maitai/__init__.py,sha256=UocvQ1455PnA27V1S6vk3yc_BysjTgLGbwfdMF2eL0A,336
2
- maitai/_config.py,sha256=0hEpVe_AEDq6vNexoHETUi1ux9DR54Lmi6HXFMT2GHc,7342
3
- maitai/_config_listener_thread.py,sha256=GbHYe0xhFMYApSurpMQYFIKaM-RbAd_LjA6SLn8JZeU,1269
4
- maitai/_context.py,sha256=WMLqfG68SR9jMIQ-p6eh-jyA2p4jknR4MXIsWntg8Cc,2482
5
- maitai/_evaluator.py,sha256=bGxMTe5zEos0jeP7iz-7RrfJyCaUx-W90vpGaHQQMl8,11633
6
- maitai/_inference.py,sha256=4fh9wndwculf-KkJ0auYJlbWNMi46V9ouuPScw_aIKw,12057
7
- maitai/_maitai.py,sha256=JuMsa-a9PIezoZGmOtgupuLyPZLj9Y9Cg-LynXGZIYs,27911
8
- maitai/_maitai_async.py,sha256=bF30X08AbHDGmELq1OfKZt-TWqGQM4F_660Qs8ifDz0,27912
9
- maitai/_maitai_client.py,sha256=sSm-YG0-X72TiwYBoJt6HfRGhGh6Erm-XteTYtD02uQ,5705
10
- maitai/_pydantic.py,sha256=8clflOhR7-6AeLFBzmsYO0aaQSAkp8KMuxsrYwPthaA,5683
11
- maitai/_types.py,sha256=C_ifBii5KdQuxcNwFv8RKHOZVgIBuatDSwfYISDip_k,5069
12
- maitai/_utils.py,sha256=2sAG6D-ZFcFUqiGzxMp76ySnS-8xpsIdB2iDdfbXg6s,10861
13
- maitai/exceptions.py,sha256=n0jwH3dhq8ewdgkCHTaaMd1GeB3EL_zulytnwqD3XUg,500
14
- maitai/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
- maitai/models/application.py,sha256=ozzSdpgfiUgcUvjHz8XuborU0nzA0Lvpv1twQdAsj2A,1704
16
- maitai/models/chat.py,sha256=CtUVM-aSSD4YOvTr7aqmrPUpgO4h-FUmGpnpTLCa1eA,12583
17
- maitai/models/config.py,sha256=zOgcuag-WHtVQgRhQrZchCP5gCjV0bszNDowL2WRrjY,1989
18
- maitai/models/event.py,sha256=GlOuoL-upwMyNKRshi4A7ocO0BG3PYJXIGXgcY9vrUE,325
19
- maitai/models/inference.py,sha256=lySiDgdsu6IdX7KG8O6orjZokeX5mR4OnLuJFJykY68,516
20
- maitai/models/key.py,sha256=xAn64DxmdaX0X4RLBewtlwao4EaTz3sZ71FP12h4pN0,949
21
- maitai/models/metric.py,sha256=iL1FqaJ-3ii5pgY4cGZKp0nuQVG1XnBggopazQhGN_E,451
22
- maitai/models/sentinel.py,sha256=w8RtMGPgttkCYxY_fheuUzpGzTOtwNc-AmiryUJBvwc,1815
23
- maitai/tools/__init__.py,sha256=Fo7tOLJNFbFtVN9LI8fpFUPk95lcq97Pp1TP5-2NU3s,4086
24
- maitai_common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
25
- maitai_common/version.py,sha256=noee8orSgJo8GF8b6xo4Hdxv3FYasMoUQR5HNSMIi3c,65
26
- maitai_common/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
27
- maitai_common/config/config_service.py,sha256=CRUz-LYyGxCaDqqkqaJ6CyhpTKr11NKux104oU__NBg,1110
28
- maitai_common/processes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
29
- maitai_common/processes/io_thread.py,sha256=w08N8LY1nMADbaKGWtplYVZpe95jlkO4OR-gK-1Ctak,2110
30
- maitai_common/processes/websocket_listener_thread.py,sha256=6F8YdE39cib0fC1uRbFDnQVkZzPnCmSpvQx66-SFbVs,5996
31
- maitai_python-1.2.15.dist-info/METADATA,sha256=OkKxmgJQMltFTl95D9DoOd3aZKS6oUbpbvBIQHvmlSE,1662
32
- maitai_python-1.2.15.dist-info/WHEEL,sha256=52BFRY2Up02UkjOa29eZOS2VxUrpPORXg1pkohGGUS8,91
33
- maitai_python-1.2.15.dist-info/top_level.txt,sha256=3uBDd_HUkDZhdPkUjbHJpoKMT3YoYszkUeOLIxgjzUo,21
34
- maitai_python-1.2.15.dist-info/RECORD,,