maitai-python 1.2.14b1__tar.gz → 1.2.16__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 (40) hide show
  1. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/PKG-INFO +2 -2
  2. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/_config.py +29 -38
  3. maitai_python-1.2.16/maitai/_config_listener.py +136 -0
  4. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/_maitai.py +1 -1
  5. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/_maitai_async.py +3 -3
  6. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/_maitai_client.py +5 -3
  7. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/models/application.py +4 -4
  8. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/models/chat.py +10 -9
  9. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/models/event.py +1 -1
  10. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/models/key.py +2 -2
  11. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/models/sentinel.py +3 -3
  12. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai_common/version.py +1 -1
  13. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai_python.egg-info/PKG-INFO +2 -2
  14. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai_python.egg-info/SOURCES.txt +1 -4
  15. maitai_python-1.2.14b1/maitai/_config_listener_thread.py +0 -23
  16. maitai_python-1.2.14b1/maitai_common/processes/__init__.py +0 -0
  17. maitai_python-1.2.14b1/maitai_common/processes/io_thread.py +0 -73
  18. maitai_python-1.2.14b1/maitai_common/processes/websocket_listener_thread.py +0 -155
  19. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/README.md +0 -0
  20. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/__init__.py +0 -0
  21. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/_context.py +0 -0
  22. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/_evaluator.py +0 -0
  23. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/_inference.py +0 -0
  24. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/_pydantic.py +0 -0
  25. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/_types.py +0 -0
  26. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/_utils.py +0 -0
  27. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/exceptions.py +0 -0
  28. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/models/__init__.py +0 -0
  29. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/models/config.py +0 -0
  30. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/models/inference.py +0 -0
  31. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/models/metric.py +0 -0
  32. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai/tools/__init__.py +0 -0
  33. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai_common/__init__.py +0 -0
  34. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai_common/config/__init__.py +0 -0
  35. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai_common/config/config_service.py +0 -0
  36. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai_python.egg-info/dependency_links.txt +0 -0
  37. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai_python.egg-info/requires.txt +0 -0
  38. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/maitai_python.egg-info/top_level.txt +0 -0
  39. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/setup.cfg +0 -0
  40. {maitai_python-1.2.14b1 → maitai_python-1.2.16}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: maitai-python
3
- Version: 1.2.14b1
3
+ Version: 1.2.16
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -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
@@ -13,9 +13,7 @@ from maitai_common.config import config_service
13
13
 
14
14
  class Config(MaitaiClient):
15
15
 
16
- maitai_ws = os.environ.get(
17
- "MAITAI_WS", "wss://09hidyy627.execute-api.us-west-2.amazonaws.com/production"
18
- )
16
+ maitai_ws = "wss://09hidyy627.execute-api.us-west-2.amazonaws.com/production"
19
17
  config_dir = os.path.expanduser(os.environ.get("MAITAI_CONFIG_DIR", "~/.maitai"))
20
18
  refresh_timer = None
21
19
 
@@ -23,7 +21,7 @@ class Config(MaitaiClient):
23
21
  self._api_key = None
24
22
  self._company_id = None
25
23
  self.websocket_listener_thread = None
26
- self.config_listener_thread = None
24
+ self.config_listener = None
27
25
  self._application_action_configs: dict[str, dict[str, ActionConfig]] = {}
28
26
  self.initialized = False
29
27
  self.auth_keys: KeyMap = KeyMap(
@@ -55,7 +53,20 @@ class Config(MaitaiClient):
55
53
  def api_key(self, value):
56
54
  self._api_key = value
57
55
 
58
- def initialize(self, api_key, retry=0, use_async=False):
56
+ def refresh_applications(self):
57
+ response_json = self.init_sdk(self.api_key, self.maitai_host)
58
+
59
+ applications = [
60
+ Application.model_validate(app_json)
61
+ for app_json in response_json["applications"]
62
+ ]
63
+ self._company_id = response_json.get("company_id")
64
+ if not self._company_id:
65
+ raise Exception("Company ID not found in response")
66
+
67
+ self.store_application_metadata(applications)
68
+
69
+ def initialize(self, api_key, retry=0):
59
70
  if self.initialized and self.api_key == api_key:
60
71
  return
61
72
 
@@ -66,21 +77,9 @@ class Config(MaitaiClient):
66
77
  self.initialized = True
67
78
  try:
68
79
  # Call init_sdk and process the response
69
- response_json = self.init_sdk(
70
- api_key, self.maitai_host, use_async=use_async
71
- )
72
-
73
- applications = [
74
- Application.model_validate(app_json)
75
- for app_json in response_json["applications"]
76
- ]
77
- self._company_id = response_json.get("company_id")
78
- if not self._company_id:
79
- raise Exception("Company ID not found in response")
80
-
81
- self.store_application_metadata(applications)
80
+ self.refresh_applications()
82
81
  self._initialize_websocket()
83
- self._start_refresh_timer(use_async=use_async)
82
+ self._start_refresh_timer()
84
83
  except Exception as e:
85
84
  self.cleanup() # Ensure cleanup on failure
86
85
  try:
@@ -94,27 +93,27 @@ class Config(MaitaiClient):
94
93
  self.refresh_timer = threading.Timer(
95
94
  interval=2**retry,
96
95
  function=self.initialize,
97
- args=(api_key, retry + 1, use_async),
96
+ args=(api_key, retry + 1),
98
97
  )
99
98
  self.refresh_timer.daemon = True
100
99
  self.refresh_timer.start()
101
100
 
102
- def _start_refresh_timer(self, use_async=False):
101
+ def _start_refresh_timer(self):
103
102
  if self.refresh_timer:
104
103
  self.refresh_timer.cancel()
105
104
  self.refresh_timer = threading.Timer(
106
- self.refresh_interval, self._refresh_and_reschedule, args=(use_async,)
105
+ self.refresh_interval, self._refresh_and_reschedule
107
106
  )
108
107
  self.refresh_timer.daemon = True
109
108
  self.refresh_timer.start()
110
109
 
111
- def _refresh_and_reschedule(self, use_async=False):
110
+ def _refresh_and_reschedule(self):
112
111
  try:
113
- self.refresh_applications(use_async=use_async)
112
+ self.refresh_applications()
114
113
  except Exception as e:
115
114
  pass
116
115
  finally:
117
- self._start_refresh_timer(use_async=use_async)
116
+ self._start_refresh_timer()
118
117
 
119
118
  def get_application_action_config(
120
119
  self, application_ref_name: str, action_type: str
@@ -162,22 +161,14 @@ class Config(MaitaiClient):
162
161
  )
163
162
 
164
163
  def _initialize_websocket(self):
165
- self.config_listener_thread = ConfigListenerThread(
164
+ self.config_listener = ConfigListener(
166
165
  self, self.maitai_ws, "APPLICATION_CONFIG_CHANGE", self._company_id
167
166
  )
168
- self.config_listener_thread.daemon = True
169
- self.config_listener_thread.start()
167
+ self.config_listener.start()
170
168
 
171
169
  def cleanup(self):
172
- if self.config_listener_thread:
173
- self.config_listener_thread.terminate()
174
- try:
175
- self.config_listener_thread.join(
176
- timeout=1.0
177
- ) # Give thread time to cleanup
178
- except Exception:
179
- pass # If join fails, continue with cleanup
180
- self.config_listener_thread = None
170
+ if self.config_listener:
171
+ self.config_listener.stop()
181
172
 
182
173
  if self.refresh_timer:
183
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
@@ -78,7 +78,7 @@ class Maitai:
78
78
  if not maitai_api_key:
79
79
  maitai_api_key = os.environ.get("MAITAI_API_KEY")
80
80
  if maitai_api_key:
81
- config.initialize(maitai_api_key, use_async=False)
81
+ config.initialize(maitai_api_key)
82
82
  else:
83
83
  raise ValueError(
84
84
  "MAITAI_API_KEY has not been set. Either set via environment variable or pass it directly into the client."
@@ -78,7 +78,7 @@ class MaitaiAsync:
78
78
  if not maitai_api_key:
79
79
  maitai_api_key = os.environ.get("MAITAI_API_KEY")
80
80
  if maitai_api_key:
81
- config.initialize(maitai_api_key, use_async=True)
81
+ config.initialize(maitai_api_key)
82
82
  else:
83
83
  raise ValueError(
84
84
  "MAITAI_API_KEY has not been set. Either set via environment variable or pass it directly into the client."
@@ -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,
@@ -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":
@@ -173,7 +175,7 @@ class MaitaiClient:
173
175
  except:
174
176
  pass
175
177
 
176
- def init_sdk(self, api_key: str, host: str, use_async: bool = False):
178
+ def init_sdk(self, api_key: str, host: str):
177
179
  url = f"{host}/config/init_sdk"
178
180
  headers = {
179
181
  "Content-Type": "application/json",
@@ -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
@@ -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
@@ -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
@@ -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 = ""
@@ -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
@@ -1,3 +1,3 @@
1
- version = "1.2.14b1"
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.14b1
3
+ Version: 1.2.16
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -2,7 +2,7 @@ README.md
2
2
  setup.py
3
3
  maitai/__init__.py
4
4
  maitai/_config.py
5
- maitai/_config_listener_thread.py
5
+ maitai/_config_listener.py
6
6
  maitai/_context.py
7
7
  maitai/_evaluator.py
8
8
  maitai/_inference.py
@@ -27,9 +27,6 @@ maitai_common/__init__.py
27
27
  maitai_common/version.py
28
28
  maitai_common/config/__init__.py
29
29
  maitai_common/config/config_service.py
30
- maitai_common/processes/__init__.py
31
- maitai_common/processes/io_thread.py
32
- maitai_common/processes/websocket_listener_thread.py
33
30
  maitai_python.egg-info/PKG-INFO
34
31
  maitai_python.egg-info/SOURCES.txt
35
32
  maitai_python.egg-info/dependency_links.txt
@@ -1,23 +0,0 @@
1
- import json
2
-
3
- from maitai.models.application import Application
4
- from maitai_common.processes.websocket_listener_thread import WebsocketListenerThread
5
-
6
-
7
- class ConfigListenerThread(WebsocketListenerThread):
8
- def __init__(self, config, path, type, key=None):
9
- super(ConfigListenerThread, self).__init__(path, type, key, interval=60)
10
- self.config = config
11
-
12
- def on_message(self, ws, message):
13
- event = json.loads(message)
14
- if event.get("event_type") == "APPLICATION_CONFIG_CHANGE":
15
- application_json = event.get("event_data")
16
- if application_json:
17
- try:
18
- application = Application.model_validate(application_json)
19
- self.config.store_application_metadata([application])
20
- except:
21
- self.config.refresh_applications()
22
- else:
23
- self.config.refresh_applications()
@@ -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()