maigp-light 1.0.0__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.
- aigp_light/__init__.py +43 -0
- aigp_light/adapters/__init__.py +1 -0
- aigp_light/adapters/openai.py +56 -0
- aigp_light/config.py +118 -0
- aigp_light/core.py +367 -0
- aigp_light/policy.py +242 -0
- aigp_light/responses.py +143 -0
- aigp_light/signals.py +160 -0
- aigp_light/trace.py +164 -0
- maigp_light-1.0.0.dist-info/METADATA +167 -0
- maigp_light-1.0.0.dist-info/RECORD +13 -0
- maigp_light-1.0.0.dist-info/WHEEL +4 -0
- maigp_light-1.0.0.dist-info/licenses/LICENSE.md +74 -0
aigp_light/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""AIGP-Light: Minimal detect & respond governance for AI model calls.
|
|
2
|
+
|
|
3
|
+
Zero-dependency, local-first governance that produces RFC-010 §5.3 compatible traces.
|
|
4
|
+
|
|
5
|
+
Usage:
|
|
6
|
+
from aigp_light import AigpLight
|
|
7
|
+
|
|
8
|
+
gov = AigpLight.from_yaml("aigp-light.yaml")
|
|
9
|
+
response = gov.call(client.chat.completions.create,
|
|
10
|
+
model="gpt-4o", messages=messages)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
__version__ = "1.0.0"
|
|
14
|
+
|
|
15
|
+
from .config import PolicyConfigError
|
|
16
|
+
from .core import AigpLight
|
|
17
|
+
from .policy import Breach, PolicyEngine, PolicyResult, ResponseAction
|
|
18
|
+
from .responses import (
|
|
19
|
+
AigpLightError,
|
|
20
|
+
CircuitOpenError,
|
|
21
|
+
GovernanceBlockedError,
|
|
22
|
+
RateLimitedError,
|
|
23
|
+
)
|
|
24
|
+
from .signals import CallObservation, SignalSnapshot, SignalStore
|
|
25
|
+
from .trace import TraceEmitter, TraceSpan
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"AigpLight",
|
|
29
|
+
"AigpLightError",
|
|
30
|
+
"Breach",
|
|
31
|
+
"CallObservation",
|
|
32
|
+
"CircuitOpenError",
|
|
33
|
+
"GovernanceBlockedError",
|
|
34
|
+
"PolicyConfigError",
|
|
35
|
+
"PolicyEngine",
|
|
36
|
+
"PolicyResult",
|
|
37
|
+
"RateLimitedError",
|
|
38
|
+
"ResponseAction",
|
|
39
|
+
"SignalSnapshot",
|
|
40
|
+
"SignalStore",
|
|
41
|
+
"TraceEmitter",
|
|
42
|
+
"TraceSpan",
|
|
43
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""AIGP-Light framework adapters."""
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""AIGP-Light OpenAI adapter — governed wrapper for OpenAI API calls."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from ..core import AigpLight
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class LightOpenAI:
|
|
11
|
+
"""AIGP-Light governed OpenAI client.
|
|
12
|
+
|
|
13
|
+
Drop-in wrapper providing local detect & respond governance.
|
|
14
|
+
|
|
15
|
+
Usage:
|
|
16
|
+
from openai import OpenAI
|
|
17
|
+
from aigp_light.adapters.openai import LightOpenAI
|
|
18
|
+
|
|
19
|
+
governed = LightOpenAI(client=OpenAI(), policy="aigp-light.yaml")
|
|
20
|
+
response = governed.chat("gpt-4o", messages)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, client: Any, policy: str | dict):
|
|
24
|
+
self._client = client
|
|
25
|
+
if isinstance(policy, str):
|
|
26
|
+
self._gov = AigpLight.from_yaml(policy)
|
|
27
|
+
else:
|
|
28
|
+
self._gov = AigpLight.from_dict(policy)
|
|
29
|
+
|
|
30
|
+
def chat(self, model: str, messages: list, **kwargs) -> Any:
|
|
31
|
+
"""Governed chat completion."""
|
|
32
|
+
return self._gov.call(
|
|
33
|
+
self._client.chat.completions.create,
|
|
34
|
+
model=model, messages=messages, **kwargs
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
async def achat(self, model: str, messages: list, **kwargs) -> Any:
|
|
38
|
+
"""Async governed chat completion."""
|
|
39
|
+
return await self._gov.acall(
|
|
40
|
+
self._client.chat.completions.create,
|
|
41
|
+
model=model, messages=messages, **kwargs
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def metrics(self) -> dict:
|
|
46
|
+
"""Current governance metrics."""
|
|
47
|
+
return self._gov.metrics
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def traces(self) -> list[dict]:
|
|
51
|
+
"""Emitted traces."""
|
|
52
|
+
return self._gov.traces
|
|
53
|
+
|
|
54
|
+
def flush(self) -> None:
|
|
55
|
+
"""Flush trace buffer."""
|
|
56
|
+
self._gov.flush()
|
aigp_light/config.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Configuration loader for AIGP-Light policy files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class PolicyConfigError(Exception):
|
|
10
|
+
"""Invalid policy configuration."""
|
|
11
|
+
|
|
12
|
+
def __init__(self, path: str, details: str):
|
|
13
|
+
self.path = path
|
|
14
|
+
self.details = details
|
|
15
|
+
super().__init__(f"Invalid policy config at '{path}': {details}")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def load_config(path: str) -> dict:
|
|
19
|
+
"""Load policy configuration from YAML or JSON file.
|
|
20
|
+
|
|
21
|
+
Supports:
|
|
22
|
+
- .yaml / .yml files (requires pyyaml)
|
|
23
|
+
- .json files (stdlib)
|
|
24
|
+
|
|
25
|
+
Raises PolicyConfigError on invalid config.
|
|
26
|
+
"""
|
|
27
|
+
if not os.path.isfile(path):
|
|
28
|
+
raise PolicyConfigError(path, "File not found")
|
|
29
|
+
|
|
30
|
+
ext = os.path.splitext(path)[1].lower()
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
if ext in (".yaml", ".yml"):
|
|
34
|
+
return _load_yaml(path)
|
|
35
|
+
elif ext == ".json":
|
|
36
|
+
return _load_json(path)
|
|
37
|
+
else:
|
|
38
|
+
# Try YAML first, fall back to JSON
|
|
39
|
+
try:
|
|
40
|
+
return _load_yaml(path)
|
|
41
|
+
except (ImportError, Exception):
|
|
42
|
+
return _load_json(path)
|
|
43
|
+
except PolicyConfigError:
|
|
44
|
+
raise
|
|
45
|
+
except Exception as e:
|
|
46
|
+
raise PolicyConfigError(path, str(e))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def validate_config(config: dict) -> dict:
|
|
50
|
+
"""Validate policy configuration and apply defaults.
|
|
51
|
+
|
|
52
|
+
Returns the config with defaults applied.
|
|
53
|
+
Raises PolicyConfigError on invalid config.
|
|
54
|
+
"""
|
|
55
|
+
if not isinstance(config, dict):
|
|
56
|
+
raise PolicyConfigError("<dict>", "Config must be a dictionary")
|
|
57
|
+
|
|
58
|
+
# Apply defaults
|
|
59
|
+
config.setdefault("version", "1.0")
|
|
60
|
+
config.setdefault("app_id", "")
|
|
61
|
+
config.setdefault("model_id", "")
|
|
62
|
+
config.setdefault("detection", {})
|
|
63
|
+
config.setdefault("response", {})
|
|
64
|
+
config.setdefault("trace", {})
|
|
65
|
+
|
|
66
|
+
# Trace defaults
|
|
67
|
+
trace = config["trace"]
|
|
68
|
+
trace.setdefault("output", "file")
|
|
69
|
+
trace.setdefault("path", "./aigp-traces/")
|
|
70
|
+
trace.setdefault("format", "jsonl")
|
|
71
|
+
trace.setdefault("buffer_size", 10)
|
|
72
|
+
trace.setdefault("include_detection", True)
|
|
73
|
+
|
|
74
|
+
# Detection defaults
|
|
75
|
+
det = config["detection"]
|
|
76
|
+
if "latency" in det:
|
|
77
|
+
det["latency"].setdefault("window_seconds", 60)
|
|
78
|
+
if "refusal_rate" in det:
|
|
79
|
+
det["refusal_rate"].setdefault("window_seconds", 300)
|
|
80
|
+
det["refusal_rate"].setdefault("patterns", [
|
|
81
|
+
"I cannot", "I'm unable", "I apologize, but", "As an AI"
|
|
82
|
+
])
|
|
83
|
+
if "error_rate" in det:
|
|
84
|
+
det["error_rate"].setdefault("window_seconds", 60)
|
|
85
|
+
if "token_explosion" in det:
|
|
86
|
+
det["token_explosion"].setdefault("baseline_window_seconds", 3600)
|
|
87
|
+
if "cost" in det:
|
|
88
|
+
det["cost"].setdefault("pricing", {})
|
|
89
|
+
det["cost"]["pricing"].setdefault("input_per_million", 2.50)
|
|
90
|
+
det["cost"]["pricing"].setdefault("output_per_million", 10.00)
|
|
91
|
+
|
|
92
|
+
return config
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _load_yaml(path: str) -> dict:
|
|
96
|
+
"""Load YAML file."""
|
|
97
|
+
try:
|
|
98
|
+
import yaml
|
|
99
|
+
except ImportError:
|
|
100
|
+
raise PolicyConfigError(
|
|
101
|
+
path,
|
|
102
|
+
"pyyaml not installed. Install with: pip install aigp-light[yaml] "
|
|
103
|
+
"or use JSON config instead."
|
|
104
|
+
)
|
|
105
|
+
with open(path, "r") as f:
|
|
106
|
+
data = yaml.safe_load(f)
|
|
107
|
+
if not isinstance(data, dict):
|
|
108
|
+
raise PolicyConfigError(path, "YAML root must be a mapping")
|
|
109
|
+
return data
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _load_json(path: str) -> dict:
|
|
113
|
+
"""Load JSON file."""
|
|
114
|
+
with open(path, "r") as f:
|
|
115
|
+
data = json.load(f)
|
|
116
|
+
if not isinstance(data, dict):
|
|
117
|
+
raise PolicyConfigError(path, "JSON root must be an object")
|
|
118
|
+
return data
|
aigp_light/core.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
"""AigpLight — Primary entry point for minimal detect & respond governance."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import functools
|
|
7
|
+
import time
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from typing import Any, Callable
|
|
10
|
+
|
|
11
|
+
from .config import PolicyConfigError, load_config, validate_config
|
|
12
|
+
from .policy import PolicyEngine
|
|
13
|
+
from .responses import (
|
|
14
|
+
CircuitOpenError,
|
|
15
|
+
GovernanceBlockedError,
|
|
16
|
+
RateLimitedError,
|
|
17
|
+
execute_actions,
|
|
18
|
+
)
|
|
19
|
+
from .signals import CallObservation, SignalStore
|
|
20
|
+
from .trace import TraceEmitter, TraceSpan
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class AigpLight:
|
|
24
|
+
"""Minimal AIGP governance — detect & respond at model call boundary.
|
|
25
|
+
|
|
26
|
+
Usage:
|
|
27
|
+
gov = AigpLight.from_yaml("aigp-light.yaml")
|
|
28
|
+
response = gov.call(client.chat.completions.create,
|
|
29
|
+
model="gpt-4o", messages=messages)
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, config: dict):
|
|
33
|
+
"""Initialize with validated config dict."""
|
|
34
|
+
self._config = validate_config(config)
|
|
35
|
+
self._signals = SignalStore(self._config)
|
|
36
|
+
self._policy = PolicyEngine(self._config)
|
|
37
|
+
self._trace = TraceEmitter(self._config)
|
|
38
|
+
|
|
39
|
+
# Refusal detection patterns
|
|
40
|
+
det = self._config.get("detection", {})
|
|
41
|
+
self._refusal_patterns = det.get("refusal_rate", {}).get("patterns", [
|
|
42
|
+
"I cannot", "I'm unable", "I apologize, but", "As an AI"
|
|
43
|
+
])
|
|
44
|
+
|
|
45
|
+
# Fallback config
|
|
46
|
+
self._fallback_model = None
|
|
47
|
+
for key, rule in self._config.get("response", {}).items():
|
|
48
|
+
if isinstance(rule, dict) and "fallback" in rule:
|
|
49
|
+
self._fallback_model = rule["fallback"].get("model_id")
|
|
50
|
+
break
|
|
51
|
+
|
|
52
|
+
@classmethod
|
|
53
|
+
def from_yaml(cls, path: str) -> "AigpLight":
|
|
54
|
+
"""Load policy from YAML (or JSON) configuration file."""
|
|
55
|
+
config = load_config(path)
|
|
56
|
+
return cls(config)
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def from_dict(cls, config: dict) -> "AigpLight":
|
|
60
|
+
"""Load policy from dictionary."""
|
|
61
|
+
return cls(config)
|
|
62
|
+
|
|
63
|
+
def call(self, fn: Callable, *args, **kwargs) -> Any:
|
|
64
|
+
"""Govern a synchronous model call.
|
|
65
|
+
|
|
66
|
+
Intercepts the call, evaluates policy, executes response
|
|
67
|
+
actions if thresholds breached, emits trace span.
|
|
68
|
+
"""
|
|
69
|
+
# Pre-call: check circuit breaker
|
|
70
|
+
if self._policy.circuit_open:
|
|
71
|
+
raise CircuitOpenError(
|
|
72
|
+
self._policy.circuit_remaining,
|
|
73
|
+
self._policy.circuit_reason,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
trace_id = TraceEmitter.generate_trace_id()
|
|
77
|
+
start_time = time.time()
|
|
78
|
+
start_iso = self._iso(start_time)
|
|
79
|
+
|
|
80
|
+
error: Exception | None = None
|
|
81
|
+
response = None
|
|
82
|
+
fallback_used = False
|
|
83
|
+
|
|
84
|
+
try:
|
|
85
|
+
response = fn(*args, **kwargs)
|
|
86
|
+
except Exception as e:
|
|
87
|
+
error = e
|
|
88
|
+
|
|
89
|
+
end_time = time.time()
|
|
90
|
+
duration_ms = int((end_time - start_time) * 1000)
|
|
91
|
+
|
|
92
|
+
# Extract signals from response
|
|
93
|
+
observation = self._extract_observation(response, duration_ms, error, start_time)
|
|
94
|
+
self._signals.record(observation)
|
|
95
|
+
|
|
96
|
+
# Evaluate policy
|
|
97
|
+
snapshot = self._signals.snapshot()
|
|
98
|
+
result = self._policy.evaluate(snapshot)
|
|
99
|
+
|
|
100
|
+
# Execute response actions
|
|
101
|
+
actions_applied: list[str] = []
|
|
102
|
+
if result.triggered:
|
|
103
|
+
action_results = execute_actions(
|
|
104
|
+
result.actions, result.breaches[0] if result.breaches else None,
|
|
105
|
+
self._config,
|
|
106
|
+
)
|
|
107
|
+
actions_applied = [r.action for r in action_results if r.applied]
|
|
108
|
+
|
|
109
|
+
# Handle behavioral actions
|
|
110
|
+
for ar in action_results:
|
|
111
|
+
if ar.action == "CIRCUIT_BREAK" and ar.applied:
|
|
112
|
+
self._policy.apply_circuit_break(result.breaches[0])
|
|
113
|
+
elif ar.action == "RATE_LIMIT" and ar.applied:
|
|
114
|
+
self._policy.apply_rate_limit()
|
|
115
|
+
elif ar.action == "BLOCK" and ar.applied:
|
|
116
|
+
raise GovernanceBlockedError(result.breaches[0])
|
|
117
|
+
elif ar.action == "FALLBACK" and ar.applied and self._fallback_model:
|
|
118
|
+
# Re-call with fallback model
|
|
119
|
+
if "model" in kwargs:
|
|
120
|
+
kwargs["model"] = self._fallback_model
|
|
121
|
+
try:
|
|
122
|
+
response = fn(*args, **kwargs)
|
|
123
|
+
fallback_used = True
|
|
124
|
+
error = None
|
|
125
|
+
except Exception as e:
|
|
126
|
+
error = e
|
|
127
|
+
|
|
128
|
+
# Emit policy span
|
|
129
|
+
self._trace.emit_policy_span(
|
|
130
|
+
trace_id=trace_id,
|
|
131
|
+
breaches=[
|
|
132
|
+
{"signal": b.signal, "threshold": b.threshold, "actual": b.actual}
|
|
133
|
+
for b in result.breaches
|
|
134
|
+
],
|
|
135
|
+
actions=actions_applied,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
# Emit trace span
|
|
139
|
+
status = "OK" if not error else "ERROR"
|
|
140
|
+
if fallback_used:
|
|
141
|
+
status = "FALLBACK"
|
|
142
|
+
|
|
143
|
+
attributes: dict[str, Any] = {
|
|
144
|
+
"model_id": self._config.get("model_id", observation.model_id),
|
|
145
|
+
"input_tokens": observation.input_tokens,
|
|
146
|
+
"output_tokens": observation.output_tokens,
|
|
147
|
+
}
|
|
148
|
+
if self._trace._include_detection:
|
|
149
|
+
attributes["detection"] = {
|
|
150
|
+
"latency_p95_ms": snapshot.latency_p95_ms,
|
|
151
|
+
"refusal_rate": snapshot.refusal_rate,
|
|
152
|
+
"error_rate": snapshot.error_rate,
|
|
153
|
+
"cost_rate_usd_min": snapshot.cost_per_minute_usd,
|
|
154
|
+
}
|
|
155
|
+
if actions_applied:
|
|
156
|
+
attributes["policy"] = {
|
|
157
|
+
"triggered": True,
|
|
158
|
+
"actions": actions_applied,
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
span = TraceSpan(
|
|
162
|
+
trace_id=trace_id,
|
|
163
|
+
stage=9,
|
|
164
|
+
stage_name="runtime_invocation",
|
|
165
|
+
start_time=start_iso,
|
|
166
|
+
end_time=self._iso(end_time),
|
|
167
|
+
duration_ms=duration_ms,
|
|
168
|
+
status=status,
|
|
169
|
+
attributes=attributes,
|
|
170
|
+
)
|
|
171
|
+
self._trace.emit(span, policy_actions=actions_applied)
|
|
172
|
+
|
|
173
|
+
# Re-raise original error if not handled
|
|
174
|
+
if error and not fallback_used:
|
|
175
|
+
raise error
|
|
176
|
+
|
|
177
|
+
return response
|
|
178
|
+
|
|
179
|
+
async def acall(self, fn: Callable, *args, **kwargs) -> Any:
|
|
180
|
+
"""Govern an async model call."""
|
|
181
|
+
# Pre-call: check circuit breaker
|
|
182
|
+
if self._policy.circuit_open:
|
|
183
|
+
raise CircuitOpenError(
|
|
184
|
+
self._policy.circuit_remaining,
|
|
185
|
+
self._policy.circuit_reason,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
trace_id = TraceEmitter.generate_trace_id()
|
|
189
|
+
start_time = time.time()
|
|
190
|
+
start_iso = self._iso(start_time)
|
|
191
|
+
|
|
192
|
+
error: Exception | None = None
|
|
193
|
+
response = None
|
|
194
|
+
|
|
195
|
+
try:
|
|
196
|
+
if asyncio.iscoroutinefunction(fn):
|
|
197
|
+
response = await fn(*args, **kwargs)
|
|
198
|
+
else:
|
|
199
|
+
response = fn(*args, **kwargs)
|
|
200
|
+
except Exception as e:
|
|
201
|
+
error = e
|
|
202
|
+
|
|
203
|
+
end_time = time.time()
|
|
204
|
+
duration_ms = int((end_time - start_time) * 1000)
|
|
205
|
+
|
|
206
|
+
# Same logic as sync — extract, evaluate, respond
|
|
207
|
+
observation = self._extract_observation(response, duration_ms, error, start_time)
|
|
208
|
+
self._signals.record(observation)
|
|
209
|
+
|
|
210
|
+
snapshot = self._signals.snapshot()
|
|
211
|
+
result = self._policy.evaluate(snapshot)
|
|
212
|
+
|
|
213
|
+
actions_applied: list[str] = []
|
|
214
|
+
if result.triggered:
|
|
215
|
+
action_results = execute_actions(
|
|
216
|
+
result.actions, result.breaches[0] if result.breaches else None,
|
|
217
|
+
self._config,
|
|
218
|
+
)
|
|
219
|
+
actions_applied = [r.action for r in action_results if r.applied]
|
|
220
|
+
|
|
221
|
+
for ar in action_results:
|
|
222
|
+
if ar.action == "CIRCUIT_BREAK" and ar.applied:
|
|
223
|
+
self._policy.apply_circuit_break(result.breaches[0])
|
|
224
|
+
elif ar.action == "BLOCK" and ar.applied:
|
|
225
|
+
raise GovernanceBlockedError(result.breaches[0])
|
|
226
|
+
|
|
227
|
+
self._trace.emit_policy_span(
|
|
228
|
+
trace_id=trace_id,
|
|
229
|
+
breaches=[
|
|
230
|
+
{"signal": b.signal, "threshold": b.threshold, "actual": b.actual}
|
|
231
|
+
for b in result.breaches
|
|
232
|
+
],
|
|
233
|
+
actions=actions_applied,
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
status = "OK" if not error else "ERROR"
|
|
237
|
+
attributes: dict[str, Any] = {
|
|
238
|
+
"model_id": self._config.get("model_id", observation.model_id),
|
|
239
|
+
"input_tokens": observation.input_tokens,
|
|
240
|
+
"output_tokens": observation.output_tokens,
|
|
241
|
+
}
|
|
242
|
+
if self._trace._include_detection:
|
|
243
|
+
attributes["detection"] = {
|
|
244
|
+
"latency_p95_ms": snapshot.latency_p95_ms,
|
|
245
|
+
"refusal_rate": snapshot.refusal_rate,
|
|
246
|
+
"error_rate": snapshot.error_rate,
|
|
247
|
+
"cost_rate_usd_min": snapshot.cost_per_minute_usd,
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
span = TraceSpan(
|
|
251
|
+
trace_id=trace_id, stage=9, stage_name="runtime_invocation",
|
|
252
|
+
start_time=start_iso, end_time=self._iso(end_time),
|
|
253
|
+
duration_ms=duration_ms, status=status, attributes=attributes,
|
|
254
|
+
)
|
|
255
|
+
self._trace.emit(span, policy_actions=actions_applied)
|
|
256
|
+
|
|
257
|
+
if error:
|
|
258
|
+
raise error
|
|
259
|
+
return response
|
|
260
|
+
|
|
261
|
+
def wrap(self, fn: Callable) -> Callable:
|
|
262
|
+
"""Return a governed wrapper around fn (decorator pattern)."""
|
|
263
|
+
@functools.wraps(fn)
|
|
264
|
+
def wrapper(*args, **kwargs):
|
|
265
|
+
return self.call(fn, *args, **kwargs)
|
|
266
|
+
return wrapper
|
|
267
|
+
|
|
268
|
+
@property
|
|
269
|
+
def metrics(self) -> dict:
|
|
270
|
+
"""Current windowed signal state."""
|
|
271
|
+
snap = self._signals.snapshot()
|
|
272
|
+
return {
|
|
273
|
+
"latency_p95_ms": snap.latency_p95_ms,
|
|
274
|
+
"latency_p99_ms": snap.latency_p99_ms,
|
|
275
|
+
"refusal_rate": snap.refusal_rate,
|
|
276
|
+
"error_rate": snap.error_rate,
|
|
277
|
+
"token_output_avg": snap.token_output_avg,
|
|
278
|
+
"cost_per_minute_usd": snap.cost_per_minute_usd,
|
|
279
|
+
"total_calls": snap.total_calls,
|
|
280
|
+
"window_calls": snap.window_calls,
|
|
281
|
+
"circuit_open": self._policy.circuit_open,
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
@property
|
|
285
|
+
def traces(self) -> list[dict]:
|
|
286
|
+
"""All emitted traces."""
|
|
287
|
+
return self._trace.export()
|
|
288
|
+
|
|
289
|
+
def flush(self) -> None:
|
|
290
|
+
"""Force flush buffered traces to configured output."""
|
|
291
|
+
self._trace.flush()
|
|
292
|
+
|
|
293
|
+
def reset(self) -> None:
|
|
294
|
+
"""Reset all state (for testing)."""
|
|
295
|
+
self._signals.reset()
|
|
296
|
+
self._trace.clear()
|
|
297
|
+
|
|
298
|
+
def _extract_observation(
|
|
299
|
+
self, response: Any, duration_ms: int, error: Exception | None, timestamp: float
|
|
300
|
+
) -> CallObservation:
|
|
301
|
+
"""Extract observation signals from a model response."""
|
|
302
|
+
if error:
|
|
303
|
+
return CallObservation(
|
|
304
|
+
timestamp=timestamp, duration_ms=duration_ms,
|
|
305
|
+
input_tokens=0, output_tokens=0,
|
|
306
|
+
success=False, refusal=False, error=error,
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
# Try to extract token usage (OpenAI-style)
|
|
310
|
+
input_tokens = 0
|
|
311
|
+
output_tokens = 0
|
|
312
|
+
model_id = ""
|
|
313
|
+
refusal = False
|
|
314
|
+
|
|
315
|
+
if response is not None:
|
|
316
|
+
# OpenAI ChatCompletion
|
|
317
|
+
if hasattr(response, "usage") and response.usage:
|
|
318
|
+
input_tokens = int(getattr(response.usage, "prompt_tokens", 0) or 0)
|
|
319
|
+
output_tokens = int(getattr(response.usage, "completion_tokens", 0) or 0)
|
|
320
|
+
# Also check Anthropic-style naming
|
|
321
|
+
if input_tokens == 0 and hasattr(response.usage, "input_tokens"):
|
|
322
|
+
val = getattr(response.usage, "input_tokens", 0)
|
|
323
|
+
if isinstance(val, (int, float)):
|
|
324
|
+
input_tokens = int(val)
|
|
325
|
+
if output_tokens == 0 and hasattr(response.usage, "output_tokens"):
|
|
326
|
+
val = getattr(response.usage, "output_tokens", 0)
|
|
327
|
+
if isinstance(val, (int, float)):
|
|
328
|
+
output_tokens = int(val)
|
|
329
|
+
|
|
330
|
+
# Model ID
|
|
331
|
+
if hasattr(response, "model"):
|
|
332
|
+
model_id = response.model or ""
|
|
333
|
+
|
|
334
|
+
# Refusal detection
|
|
335
|
+
content = self._extract_content(response)
|
|
336
|
+
if content and self._refusal_patterns:
|
|
337
|
+
refusal = any(p.lower() in content.lower() for p in self._refusal_patterns)
|
|
338
|
+
|
|
339
|
+
return CallObservation(
|
|
340
|
+
timestamp=timestamp, duration_ms=duration_ms,
|
|
341
|
+
input_tokens=input_tokens, output_tokens=output_tokens,
|
|
342
|
+
success=True, refusal=refusal, model_id=model_id,
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
@staticmethod
|
|
346
|
+
def _extract_content(response: Any) -> str:
|
|
347
|
+
"""Try to extract text content from various response formats."""
|
|
348
|
+
# OpenAI
|
|
349
|
+
if hasattr(response, "choices") and response.choices:
|
|
350
|
+
msg = response.choices[0].message
|
|
351
|
+
if hasattr(msg, "content"):
|
|
352
|
+
return msg.content or ""
|
|
353
|
+
# Anthropic
|
|
354
|
+
if hasattr(response, "content") and isinstance(response.content, list):
|
|
355
|
+
for block in response.content:
|
|
356
|
+
if hasattr(block, "text"):
|
|
357
|
+
return block.text or ""
|
|
358
|
+
# Dict response
|
|
359
|
+
if isinstance(response, dict):
|
|
360
|
+
return response.get("content", "") or response.get("text", "")
|
|
361
|
+
return ""
|
|
362
|
+
|
|
363
|
+
@staticmethod
|
|
364
|
+
def _iso(ts: float) -> str:
|
|
365
|
+
"""Convert timestamp to ISO 8601 UTC."""
|
|
366
|
+
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
|
|
367
|
+
return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{dt.microsecond // 1000:03d}Z"
|