maitai-python 1.2.34__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 +34 -1
- maitai/_config.py +26 -4
- maitai/_config_listener.py +45 -6
- maitai/_logger.py +5 -0
- maitai/_workflow_log_transport.py +174 -0
- maitai/_workflow_logger.py +287 -0
- maitai/agent/__init__.py +28 -0
- maitai/integrations/__init__.py +24 -1
- maitai/integrations/_identity.py +117 -0
- maitai/integrations/_observe.py +24 -3
- maitai/integrations/_run_type.py +114 -0
- maitai/integrations/_session.py +4 -0
- maitai_common/onnx_embedding_model.py +119 -0
- maitai_common/version.py +1 -1
- maitai_models/chat.py +1 -0
- maitai_models/key.py +7 -1
- maitai_models/workflow.py +21 -0
- {maitai_python-1.2.34.dist-info → maitai_python-1.2.35.dist-info}/METADATA +1 -1
- {maitai_python-1.2.34.dist-info → maitai_python-1.2.35.dist-info}/RECORD +21 -16
- {maitai_python-1.2.34.dist-info → maitai_python-1.2.35.dist-info}/WHEEL +1 -1
- {maitai_python-1.2.34.dist-info → maitai_python-1.2.35.dist-info}/top_level.txt +0 -0
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 = {
|
|
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:
|
|
@@ -200,18 +210,30 @@ class Config(MaitaiClient):
|
|
|
200
210
|
)
|
|
201
211
|
|
|
202
212
|
def _initialize_websocket(self):
|
|
203
|
-
|
|
213
|
+
listener = ConfigListener(
|
|
204
214
|
self,
|
|
205
215
|
self.maitai_ws,
|
|
206
216
|
"APPLICATION_CONFIG_CHANGE",
|
|
207
217
|
self._company_id,
|
|
208
218
|
self.api_key,
|
|
219
|
+
native_api_origin=self.maitai_host if self._native_event_stream else None,
|
|
209
220
|
)
|
|
210
|
-
self.
|
|
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
|
|
211
231
|
|
|
212
232
|
def cleanup(self):
|
|
213
|
-
|
|
214
|
-
self.config_listener
|
|
233
|
+
with self._listener_lock:
|
|
234
|
+
if self.config_listener:
|
|
235
|
+
self.config_listener.stop()
|
|
236
|
+
self.config_listener = None
|
|
215
237
|
|
|
216
238
|
if self.refresh_timer:
|
|
217
239
|
self.refresh_timer.cancel()
|
maitai/_config_listener.py
CHANGED
|
@@ -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__(
|
|
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.
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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/_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
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Fire-and-forget logging of bring-your-own workflow runs.
|
|
2
|
+
|
|
3
|
+
Surfaces:
|
|
4
|
+
* ``with maitai.workflow_run(...) as run:`` — context manager
|
|
5
|
+
* ``@maitai.workflow(...)`` — decorator (args → input, return → output)
|
|
6
|
+
* ``maitai.log_workflow_run(...)`` — one-shot post-hoc logging
|
|
7
|
+
|
|
8
|
+
Parity with ``_logger.py``: non-blocking, never raises into caller code for
|
|
9
|
+
transport failures, respects ``MAITAI_LOGGING_ENABLED`` / sample-rate env vars,
|
|
10
|
+
and drains on process exit. Uncaught exceptions inside ``workflow_run`` still
|
|
11
|
+
propagate after a FAILED log is queued.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import functools
|
|
17
|
+
import inspect
|
|
18
|
+
import logging
|
|
19
|
+
import os
|
|
20
|
+
import time
|
|
21
|
+
import uuid
|
|
22
|
+
from contextlib import contextmanager
|
|
23
|
+
from typing import Any, Callable, Dict, Iterator, Optional, TypeVar
|
|
24
|
+
|
|
25
|
+
from maitai._logger import _to_dict
|
|
26
|
+
from maitai._workflow_log_transport import get_workflow_logger
|
|
27
|
+
from maitai.integrations._session import get_session, set_session
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger("maitai")
|
|
30
|
+
|
|
31
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class WorkflowRunHandle:
|
|
35
|
+
"""Mutable handle yielded by :func:`workflow_run`."""
|
|
36
|
+
|
|
37
|
+
__slots__ = (
|
|
38
|
+
"workflow_ref",
|
|
39
|
+
"application",
|
|
40
|
+
"session_id",
|
|
41
|
+
"input",
|
|
42
|
+
"output",
|
|
43
|
+
"error_message",
|
|
44
|
+
"meta",
|
|
45
|
+
"source_tool",
|
|
46
|
+
"_status",
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
*,
|
|
52
|
+
workflow_ref: str,
|
|
53
|
+
application: str,
|
|
54
|
+
session_id: str,
|
|
55
|
+
input: Optional[Dict[str, Any]] = None,
|
|
56
|
+
meta: Optional[Dict[str, Any]] = None,
|
|
57
|
+
source_tool: Optional[str] = None,
|
|
58
|
+
):
|
|
59
|
+
self.workflow_ref = workflow_ref
|
|
60
|
+
self.application = application
|
|
61
|
+
self.session_id = session_id
|
|
62
|
+
self.input = input
|
|
63
|
+
self.output: Any = None
|
|
64
|
+
self.error_message: Optional[str] = None
|
|
65
|
+
self.meta = meta
|
|
66
|
+
self.source_tool = source_tool
|
|
67
|
+
self._status = "COMPLETED"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _resolve_application(application: Optional[str]) -> str:
|
|
71
|
+
if application and application.strip():
|
|
72
|
+
return application.strip()
|
|
73
|
+
for env_key in ("MAITAI_APPLICATION", "MAITAI_PROJECT"):
|
|
74
|
+
raw = os.environ.get(env_key)
|
|
75
|
+
if raw and raw.strip():
|
|
76
|
+
return raw.strip()
|
|
77
|
+
raise ValueError(
|
|
78
|
+
"application is required (pass application=... or set MAITAI_APPLICATION)"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _is_jsonish(value: Any) -> bool:
|
|
83
|
+
return isinstance(value, (dict, list, str, int, float, bool, type(None)))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _capture_call_input(
|
|
87
|
+
fn: Callable[..., Any], args: tuple, kwargs: dict
|
|
88
|
+
) -> Dict[str, Any]:
|
|
89
|
+
try:
|
|
90
|
+
bound = inspect.signature(fn).bind_partial(*args, **kwargs)
|
|
91
|
+
bound.apply_defaults()
|
|
92
|
+
return {
|
|
93
|
+
k: v if _is_jsonish(v) else _to_dict(v) for k, v in bound.arguments.items()
|
|
94
|
+
}
|
|
95
|
+
except Exception:
|
|
96
|
+
return {"args": list(args), "kwargs": dict(kwargs)}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _finish_run(
|
|
100
|
+
handle: WorkflowRunHandle,
|
|
101
|
+
started: float,
|
|
102
|
+
*,
|
|
103
|
+
sample_rate: Optional[float],
|
|
104
|
+
) -> None:
|
|
105
|
+
# Portal Duration card reads profile.spans (script_execute / worker_execution),
|
|
106
|
+
# not bare duration_ms — emit both so EXTERNAL runs match native UX.
|
|
107
|
+
duration_ms = int((time.perf_counter() - started) * 1000)
|
|
108
|
+
profile = {
|
|
109
|
+
"duration_ms": duration_ms,
|
|
110
|
+
"spans": [
|
|
111
|
+
{
|
|
112
|
+
"label": "script_execute",
|
|
113
|
+
"start_ms": 0,
|
|
114
|
+
"end_ms": max(duration_ms, 1),
|
|
115
|
+
}
|
|
116
|
+
],
|
|
117
|
+
}
|
|
118
|
+
try:
|
|
119
|
+
get_workflow_logger().log_workflow_run(
|
|
120
|
+
workflow_ref=handle.workflow_ref,
|
|
121
|
+
application=handle.application,
|
|
122
|
+
session_id=handle.session_id,
|
|
123
|
+
status=handle._status,
|
|
124
|
+
input=handle.input,
|
|
125
|
+
output=handle.output,
|
|
126
|
+
error_message=handle.error_message,
|
|
127
|
+
profile=profile,
|
|
128
|
+
meta=handle.meta,
|
|
129
|
+
source_tool=handle.source_tool,
|
|
130
|
+
sample_rate=sample_rate,
|
|
131
|
+
)
|
|
132
|
+
except Exception:
|
|
133
|
+
logger.debug("workflow_run finish failed to queue", exc_info=True)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def log_workflow_run(
|
|
137
|
+
*,
|
|
138
|
+
workflow_ref: str,
|
|
139
|
+
application: Optional[str] = None,
|
|
140
|
+
session_id: Optional[str] = None,
|
|
141
|
+
status: str = "COMPLETED",
|
|
142
|
+
input: Any = None,
|
|
143
|
+
output: Any = None,
|
|
144
|
+
error_message: Optional[str] = None,
|
|
145
|
+
profile: Optional[Dict[str, Any]] = None,
|
|
146
|
+
meta: Optional[Dict[str, Any]] = None,
|
|
147
|
+
source_tool: Optional[str] = None,
|
|
148
|
+
sample_rate: Optional[float] = None,
|
|
149
|
+
) -> None:
|
|
150
|
+
"""One-shot post-hoc workflow run logging (fire-and-forget, never raises)."""
|
|
151
|
+
try:
|
|
152
|
+
app = _resolve_application(application)
|
|
153
|
+
sid = (session_id or get_session() or str(uuid.uuid4())).strip()
|
|
154
|
+
get_workflow_logger().log_workflow_run(
|
|
155
|
+
workflow_ref=workflow_ref,
|
|
156
|
+
application=app,
|
|
157
|
+
session_id=sid,
|
|
158
|
+
status=status,
|
|
159
|
+
input=input,
|
|
160
|
+
output=output,
|
|
161
|
+
error_message=error_message,
|
|
162
|
+
profile=profile,
|
|
163
|
+
meta=meta,
|
|
164
|
+
source_tool=source_tool,
|
|
165
|
+
sample_rate=sample_rate,
|
|
166
|
+
)
|
|
167
|
+
except Exception:
|
|
168
|
+
logger.debug("log_workflow_run failed to queue", exc_info=True)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@contextmanager
|
|
172
|
+
def workflow_run(
|
|
173
|
+
workflow_ref: str,
|
|
174
|
+
*,
|
|
175
|
+
application: Optional[str] = None,
|
|
176
|
+
input: Any = None,
|
|
177
|
+
session_id: Optional[str] = None,
|
|
178
|
+
meta: Optional[Dict[str, Any]] = None,
|
|
179
|
+
source_tool: Optional[str] = None,
|
|
180
|
+
sample_rate: Optional[float] = None,
|
|
181
|
+
) -> Iterator[WorkflowRunHandle]:
|
|
182
|
+
"""Capture a workflow execution bound and log it on exit.
|
|
183
|
+
|
|
184
|
+
Sets the session context so nested ``maitai.log()`` / proxied calls inherit
|
|
185
|
+
``session_id``. On success status is COMPLETED; on uncaught exception status
|
|
186
|
+
is FAILED with ``error_message``, then the exception re-raises.
|
|
187
|
+
"""
|
|
188
|
+
app = _resolve_application(application)
|
|
189
|
+
sid = (session_id or str(uuid.uuid4())).strip()
|
|
190
|
+
run_input = input if input is None or isinstance(input, dict) else _to_dict(input)
|
|
191
|
+
handle = WorkflowRunHandle(
|
|
192
|
+
workflow_ref=workflow_ref,
|
|
193
|
+
application=app,
|
|
194
|
+
session_id=sid,
|
|
195
|
+
input=run_input,
|
|
196
|
+
meta=meta,
|
|
197
|
+
source_tool=source_tool,
|
|
198
|
+
)
|
|
199
|
+
prior = get_session()
|
|
200
|
+
set_session(sid)
|
|
201
|
+
started = time.perf_counter()
|
|
202
|
+
try:
|
|
203
|
+
yield handle
|
|
204
|
+
except Exception as exc:
|
|
205
|
+
handle._status = "FAILED"
|
|
206
|
+
if handle.error_message is None:
|
|
207
|
+
handle.error_message = str(exc) or exc.__class__.__name__
|
|
208
|
+
_finish_run(handle, started, sample_rate=sample_rate)
|
|
209
|
+
raise
|
|
210
|
+
else:
|
|
211
|
+
_finish_run(handle, started, sample_rate=sample_rate)
|
|
212
|
+
finally:
|
|
213
|
+
set_session(prior)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _wrap_sync_workflow(
|
|
217
|
+
fn: F,
|
|
218
|
+
workflow_ref: str,
|
|
219
|
+
application: Optional[str],
|
|
220
|
+
meta: Optional[Dict[str, Any]],
|
|
221
|
+
source_tool: Optional[str],
|
|
222
|
+
sample_rate: Optional[float],
|
|
223
|
+
) -> F:
|
|
224
|
+
@functools.wraps(fn)
|
|
225
|
+
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
226
|
+
run_input = _capture_call_input(fn, args, kwargs)
|
|
227
|
+
with workflow_run(
|
|
228
|
+
workflow_ref,
|
|
229
|
+
application=application,
|
|
230
|
+
input=run_input,
|
|
231
|
+
meta=meta,
|
|
232
|
+
source_tool=source_tool,
|
|
233
|
+
sample_rate=sample_rate,
|
|
234
|
+
) as run:
|
|
235
|
+
result = fn(*args, **kwargs)
|
|
236
|
+
run.output = result
|
|
237
|
+
return result
|
|
238
|
+
|
|
239
|
+
return sync_wrapper # type: ignore[return-value]
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _wrap_async_workflow(
|
|
243
|
+
fn: F,
|
|
244
|
+
workflow_ref: str,
|
|
245
|
+
application: Optional[str],
|
|
246
|
+
meta: Optional[Dict[str, Any]],
|
|
247
|
+
source_tool: Optional[str],
|
|
248
|
+
sample_rate: Optional[float],
|
|
249
|
+
) -> F:
|
|
250
|
+
@functools.wraps(fn)
|
|
251
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
252
|
+
run_input = _capture_call_input(fn, args, kwargs)
|
|
253
|
+
with workflow_run(
|
|
254
|
+
workflow_ref,
|
|
255
|
+
application=application,
|
|
256
|
+
input=run_input,
|
|
257
|
+
meta=meta,
|
|
258
|
+
source_tool=source_tool,
|
|
259
|
+
sample_rate=sample_rate,
|
|
260
|
+
) as run:
|
|
261
|
+
result = await fn(*args, **kwargs)
|
|
262
|
+
run.output = result
|
|
263
|
+
return result
|
|
264
|
+
|
|
265
|
+
return async_wrapper # type: ignore[return-value]
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def workflow(
|
|
269
|
+
workflow_ref: str,
|
|
270
|
+
*,
|
|
271
|
+
application: Optional[str] = None,
|
|
272
|
+
meta: Optional[Dict[str, Any]] = None,
|
|
273
|
+
source_tool: Optional[str] = None,
|
|
274
|
+
sample_rate: Optional[float] = None,
|
|
275
|
+
) -> Callable[[F], F]:
|
|
276
|
+
"""Decorator equivalent of :func:`workflow_run`."""
|
|
277
|
+
|
|
278
|
+
def decorator(fn: F) -> F:
|
|
279
|
+
if inspect.iscoroutinefunction(fn):
|
|
280
|
+
return _wrap_async_workflow(
|
|
281
|
+
fn, workflow_ref, application, meta, source_tool, sample_rate
|
|
282
|
+
)
|
|
283
|
+
return _wrap_sync_workflow(
|
|
284
|
+
fn, workflow_ref, application, meta, source_tool, sample_rate
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
return decorator
|
maitai/agent/__init__.py
CHANGED
|
@@ -1,4 +1,32 @@
|
|
|
1
|
+
"""Hosted agent client package (``Completions`` / ``AsyncCompletions``).
|
|
2
|
+
|
|
3
|
+
Also callable as a BYOA observe context manager so the AC surface
|
|
4
|
+
``with maitai.agent(\"name\"):`` works despite this submodule owning the
|
|
5
|
+
``maitai.agent`` attribute::
|
|
6
|
+
|
|
7
|
+
with maitai.agent(\"triage\"):
|
|
8
|
+
graph.invoke(...)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import sys
|
|
14
|
+
from types import ModuleType
|
|
15
|
+
from typing import Iterator
|
|
16
|
+
|
|
1
17
|
from maitai.agent._completions import Completions
|
|
2
18
|
from maitai.agent._completions_async import AsyncCompletions
|
|
3
19
|
|
|
4
20
|
__all__ = ["Completions", "AsyncCompletions"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _AgentModule(ModuleType):
|
|
24
|
+
"""Makes ``maitai.agent(\"name\")`` return the BYOA identity context manager."""
|
|
25
|
+
|
|
26
|
+
def __call__(self, agent_name: str) -> Iterator[None]:
|
|
27
|
+
from maitai.integrations._identity import agent as agent_cm
|
|
28
|
+
|
|
29
|
+
return agent_cm(agent_name)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
sys.modules[__name__].__class__ = _AgentModule
|