maitai-python 1.2.33__py3-none-any.whl → 1.2.35__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/__init__.py CHANGED
@@ -19,11 +19,40 @@ __all__ = [
19
19
  "set_session",
20
20
  "session",
21
21
  "get_session",
22
+ "set_agent",
23
+ "get_agent",
24
+ "agent",
25
+ "set_intent",
26
+ "get_intent",
27
+ "intent",
28
+ "workflow_run",
29
+ "workflow",
30
+ "log_workflow_run",
31
+ "set_run_type",
32
+ "get_run_type",
33
+ "run_type",
22
34
  ]
23
35
 
24
36
  # Lazy attrs served from maitai.integrations, so base `import maitai` never
25
37
  # pulls in the optional observability extra (OTel / OpenInference).
26
- _LAZY_INTEGRATIONS = {"observe", "set_session", "session", "get_session"}
38
+ _LAZY_INTEGRATIONS = {
39
+ "observe",
40
+ "set_session",
41
+ "session",
42
+ "get_session",
43
+ "set_agent",
44
+ "get_agent",
45
+ "agent",
46
+ "set_intent",
47
+ "get_intent",
48
+ "intent",
49
+ "set_run_type",
50
+ "get_run_type",
51
+ "run_type",
52
+ }
53
+
54
+ # BYOW logging surfaces — light deps, but kept lazy so import cost stays flat.
55
+ _LAZY_WORKFLOW_LOG = {"workflow_run", "workflow", "log_workflow_run"}
27
56
 
28
57
 
29
58
  def __getattr__(name: str):
@@ -31,4 +60,8 @@ def __getattr__(name: str):
31
60
  import maitai.integrations as _integrations
32
61
 
33
62
  return getattr(_integrations, name)
63
+ if name in _LAZY_WORKFLOW_LOG:
64
+ import maitai._workflow_logger as _workflow_logger
65
+
66
+ return getattr(_workflow_logger, name)
34
67
  raise AttributeError(f"module 'maitai' has no attribute '{name}'")
maitai/_config.py CHANGED
@@ -21,7 +21,9 @@ class Config(MaitaiClient):
21
21
  super().__init__()
22
22
  self._api_key = None
23
23
  self._company_id = None
24
+ self._native_event_stream = False
24
25
  self.websocket_listener_thread = None
26
+ self._listener_lock = threading.RLock()
25
27
  self.config_listener = None
26
28
  self._application_action_configs: dict[str, dict[str, ActionConfig]] = {}
27
29
  self.initialized = False
@@ -77,6 +79,7 @@ class Config(MaitaiClient):
77
79
  self._company_id = response_json.get("company_id")
78
80
  if not self._company_id:
79
81
  raise Exception("Company ID not found in response")
82
+ self._native_event_stream = response_json.get("native_event_stream") is True
80
83
 
81
84
  # Process API keys from the response
82
85
  if "api_keys" in response_json:
@@ -136,6 +139,13 @@ class Config(MaitaiClient):
136
139
  def _refresh_and_reschedule(self):
137
140
  try:
138
141
  self.refresh_applications()
142
+ if (
143
+ self.config_listener
144
+ and (self.config_listener.native_auth is not None)
145
+ != self._native_event_stream
146
+ and not os.getenv("MAITAI_EVENT_SOCKET_URL")
147
+ ):
148
+ self._initialize_websocket()
139
149
  except Exception as e:
140
150
  pass
141
151
  finally:
@@ -148,6 +158,19 @@ class Config(MaitaiClient):
148
158
  action_type, config_service.get_default_config()
149
159
  )
150
160
 
161
+ def has_application_action_config(
162
+ self, application_ref_name: str, action_type: str
163
+ ) -> bool:
164
+ """Whether a real (locally-fetched) config exists for this intent.
165
+
166
+ ``get_application_action_config`` falls back to a hardcoded default when
167
+ the store is empty, so callers use this to tell "server said this model"
168
+ apart from "no config known — let the server decide".
169
+ """
170
+ return action_type in self._application_action_configs.get(
171
+ application_ref_name, {}
172
+ )
173
+
151
174
  def store_application_metadata(self, applications: List[Application]):
152
175
  for application in applications:
153
176
  for action_type in application.action_types:
@@ -187,18 +210,30 @@ class Config(MaitaiClient):
187
210
  )
188
211
 
189
212
  def _initialize_websocket(self):
190
- self.config_listener = ConfigListener(
213
+ listener = ConfigListener(
191
214
  self,
192
215
  self.maitai_ws,
193
216
  "APPLICATION_CONFIG_CHANGE",
194
217
  self._company_id,
195
218
  self.api_key,
219
+ native_api_origin=self.maitai_host if self._native_event_stream else None,
196
220
  )
197
- self.config_listener.start()
221
+ with self._listener_lock:
222
+ previous = self.config_listener
223
+ listener.start()
224
+ if previous:
225
+ # Discovery is retried on the next configuration refresh.
226
+ if not listener.opened.wait(timeout=10):
227
+ listener.stop()
228
+ return
229
+ previous.stop()
230
+ self.config_listener = listener
198
231
 
199
232
  def cleanup(self):
200
- if self.config_listener:
201
- self.config_listener.stop()
233
+ with self._listener_lock:
234
+ if self.config_listener:
235
+ self.config_listener.stop()
236
+ self.config_listener = None
202
237
 
203
238
  if self.refresh_timer:
204
239
  self.refresh_timer.cancel()
@@ -2,6 +2,7 @@ import json
2
2
  import logging
3
3
  import os
4
4
  import threading
5
+ from urllib.parse import urlsplit
5
6
 
6
7
  import websocket
7
8
 
@@ -13,15 +14,50 @@ logger = logging.getLogger("maitai")
13
14
 
14
15
 
15
16
  class ConfigListener:
16
- def __init__(self, config, path, type, key=None, api_key=None):
17
+ def __init__(
18
+ self, config, path, type, key=None, api_key=None, *, native_api_origin=None
19
+ ):
17
20
  self.config = config
18
- self.ws_url = f"{path}?type={type}"
19
- if key:
20
- self.ws_url += f"&key={key}"
21
- if api_key:
22
- self.ws_url += f"&api_key={api_key}"
21
+ self.native_auth = None
22
+ endpoint = os.getenv("MAITAI_EVENT_SOCKET_URL")
23
+ if not endpoint and native_api_origin:
24
+ origin = urlsplit(native_api_origin)
25
+ if (
26
+ origin.scheme != "https"
27
+ or not origin.hostname
28
+ or origin.username is not None
29
+ or origin.password is not None
30
+ ):
31
+ raise ValueError(
32
+ "Native event discovery requires an authenticated HTTPS API origin"
33
+ )
34
+ endpoint = f"wss://{origin.netloc}/maitai-live"
35
+ if endpoint:
36
+ address = urlsplit(endpoint)
37
+ if (
38
+ address.scheme != "wss"
39
+ or not address.hostname
40
+ or address.netloc.endswith(":")
41
+ or address.port == 0
42
+ or address.username is not None
43
+ or address.password is not None
44
+ or address.query
45
+ or address.fragment
46
+ ):
47
+ raise ValueError(
48
+ "MAITAI_EVENT_SOCKET_URL must be a secure WebSocket endpoint"
49
+ )
50
+ self.ws_url = endpoint
51
+ self.native_auth = {"type": type, "key": str(key), "api_key": api_key}
52
+ else:
53
+ self.ws_url = f"{path}?type={type}"
54
+ if key:
55
+ self.ws_url += f"&key={key}"
56
+ if api_key:
57
+ self.ws_url += f"&api_key={api_key}"
23
58
 
24
59
  self.ws = None
60
+ self.opened = threading.Event()
25
61
  self.ws_thread = None
26
62
  self.running = False
27
63
 
@@ -61,6 +97,9 @@ class ConfigListener:
61
97
  )
62
98
 
63
99
  def on_open(self, ws):
100
+ if self.native_auth is not None:
101
+ ws.send(json.dumps(self.native_auth))
102
+ self.opened.set()
64
103
  logger.info("Maitai config listener: websocket connection established")
65
104
 
66
105
  def _websocket_thread(self):
maitai/_inference.py CHANGED
@@ -89,6 +89,9 @@ class Inference(MaitaiClient):
89
89
  "x-api-key": self.config.api_key,
90
90
  "User-Agent": version,
91
91
  }
92
+ client_request_id = request_dict.get("request_id")
93
+ if client_request_id:
94
+ headers["X-Request-ID"] = str(client_request_id)
92
95
 
93
96
  client = self.get_client()
94
97
 
@@ -160,6 +163,9 @@ class Inference(MaitaiClient):
160
163
  "x-api-key": self.config.api_key,
161
164
  "User-Agent": version,
162
165
  }
166
+ client_request_id = request_dict.get("request_id")
167
+ if client_request_id:
168
+ headers["X-Request-ID"] = str(client_request_id)
163
169
 
164
170
  # Log the request being made
165
171
  logger.info(f"Making inference request to {url} with timeout={timeout}")
maitai/_logger.py CHANGED
@@ -27,6 +27,7 @@ from typing import Any, Dict, Optional, Union
27
27
  from maitai._config import Config
28
28
  from maitai._maitai_client import MaitaiClient
29
29
  from maitai._utils import __version__ as version
30
+ from maitai.integrations._session import get_session
30
31
  from maitai.models.chat import LogCompletionRequest
31
32
  from maitai.models.metric import RequestTimingMetric
32
33
 
@@ -247,6 +248,10 @@ class Logger(MaitaiClient):
247
248
  if not self._should_sample(sample_rate):
248
249
  return None
249
250
  try:
251
+ # Inherit session from maitai.session() / workflow_run() when the
252
+ # caller omits session_id so nested BYO logs join the same run.
253
+ if session_id is None:
254
+ session_id = get_session()
250
255
  effective_rate = (
251
256
  sample_rate if sample_rate is not None else self.default_sample_rate
252
257
  )
@@ -0,0 +1,174 @@
1
+ """Background HTTP transport for bring-your-own workflow run logging."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import atexit
6
+ import concurrent.futures
7
+ import logging
8
+ import os
9
+ import random
10
+ import traceback
11
+ import weakref
12
+ from typing import Any, Dict, Optional
13
+
14
+ from maitai._config import Config
15
+ from maitai._logger import _env_flag, _env_float, _to_dict
16
+ from maitai._maitai_client import MaitaiClient
17
+ from maitai._utils import __version__ as version
18
+
19
+ logger = logging.getLogger("maitai")
20
+
21
+
22
+ def _atexit_shutdown(self_ref: "weakref.ref[WorkflowLogger]") -> None:
23
+ inst = self_ref()
24
+ if inst is not None:
25
+ inst.shutdown()
26
+
27
+
28
+ class WorkflowLogger(MaitaiClient):
29
+ """Background transport for BYOW run logging."""
30
+
31
+ def __init__(self, config: Optional[Config] = None):
32
+ super().__init__()
33
+ self.config = config or Config(
34
+ os.environ.get("MAITAI_API_KEY"), server_side_only=True
35
+ )
36
+ self.enabled = _env_flag("MAITAI_LOGGING_ENABLED", True)
37
+ env_rate = _env_float("MAITAI_LOG_SAMPLE_RATE")
38
+ self.default_sample_rate = env_rate if env_rate is not None else 1.0
39
+ atexit.register(_atexit_shutdown, weakref.ref(self))
40
+
41
+ def log_workflow_run(
42
+ self,
43
+ *,
44
+ workflow_ref: str,
45
+ application: str,
46
+ session_id: str,
47
+ status: str = "COMPLETED",
48
+ input: Any = None,
49
+ output: Any = None,
50
+ error_message: Optional[str] = None,
51
+ profile: Optional[Dict[str, Any]] = None,
52
+ meta: Optional[Dict[str, Any]] = None,
53
+ source_tool: Optional[str] = None,
54
+ sample_rate: Optional[float] = None,
55
+ ) -> None:
56
+ payload = self._build_payload(
57
+ workflow_ref=workflow_ref,
58
+ application=application,
59
+ session_id=session_id,
60
+ status=status,
61
+ input=input,
62
+ output=output,
63
+ error_message=error_message,
64
+ profile=profile,
65
+ meta=meta,
66
+ source_tool=source_tool,
67
+ sample_rate=sample_rate,
68
+ )
69
+ if payload is None:
70
+ return
71
+ try:
72
+ self.executor.submit(self._send, payload)
73
+ except RuntimeError:
74
+ pass
75
+
76
+ def flush(self) -> None:
77
+ self.executor.shutdown(wait=True)
78
+ self.executor = concurrent.futures.ThreadPoolExecutor()
79
+
80
+ def shutdown(self) -> None:
81
+ try:
82
+ self.executor.shutdown(wait=True)
83
+ except Exception:
84
+ pass
85
+
86
+ def _safe_api_key(self) -> str:
87
+ try:
88
+ return self.config.api_key
89
+ except Exception:
90
+ return getattr(self.config, "_api_key", None) or ""
91
+
92
+ def _should_sample(self, sample_rate: Optional[float]) -> bool:
93
+ rate = sample_rate if sample_rate is not None else self.default_sample_rate
94
+ if rate >= 1.0:
95
+ return True
96
+ if rate <= 0.0:
97
+ return False
98
+ return random.random() < rate
99
+
100
+ def _build_payload(
101
+ self,
102
+ *,
103
+ workflow_ref: str,
104
+ application: str,
105
+ session_id: str,
106
+ status: str,
107
+ input: Any,
108
+ output: Any,
109
+ error_message: Optional[str],
110
+ profile: Optional[Dict[str, Any]],
111
+ meta: Optional[Dict[str, Any]],
112
+ source_tool: Optional[str],
113
+ sample_rate: Optional[float],
114
+ ) -> Optional[Dict[str, Any]]:
115
+ if not self.enabled:
116
+ return None
117
+ if not self._should_sample(sample_rate):
118
+ return None
119
+ try:
120
+ payload: Dict[str, Any] = {
121
+ "workflow_ref": str(workflow_ref),
122
+ "application": str(application),
123
+ "session_id": str(session_id),
124
+ "status": str(status or "COMPLETED"),
125
+ }
126
+ if input is not None:
127
+ payload["input"] = input if isinstance(input, dict) else _to_dict(input)
128
+ if output is not None:
129
+ payload["output"] = (
130
+ output if isinstance(output, dict) else _to_dict(output)
131
+ )
132
+ if error_message is not None:
133
+ payload["error_message"] = str(error_message)
134
+ if profile is not None:
135
+ payload["profile"] = profile
136
+ if meta is not None:
137
+ payload["meta"] = meta
138
+ if source_tool is not None:
139
+ payload["source_tool"] = str(source_tool)
140
+ return payload
141
+ except Exception:
142
+ self.log_error(
143
+ self._safe_api_key(), traceback.format_exc(), "log_workflow_run"
144
+ )
145
+ return None
146
+
147
+ def _log_url(self) -> str:
148
+ # Workflow APIs live on the backend (MAITAI_HOST), not the Go inference
149
+ # gateway. Using inference_host breaks local BYOW when chatsvc is down.
150
+ return f"{self.config.maitai_host}/workflow/runs/log"
151
+
152
+ def _headers(self) -> Dict[str, str]:
153
+ return {
154
+ "Content-Type": "application/json",
155
+ "x-api-key": self._safe_api_key(),
156
+ "User-Agent": version,
157
+ }
158
+
159
+ def _send(self, payload: Dict[str, Any]) -> None:
160
+ url = self._log_url()
161
+ try:
162
+ self.get_client().put(url, headers=self._headers(), json=payload)
163
+ except Exception:
164
+ self.log_error(self._safe_api_key(), traceback.format_exc(), url)
165
+
166
+
167
+ _default_logger: Optional[WorkflowLogger] = None
168
+
169
+
170
+ def get_workflow_logger() -> WorkflowLogger:
171
+ global _default_logger
172
+ if _default_logger is None:
173
+ _default_logger = WorkflowLogger()
174
+ return _default_logger