multi-agent-observability 0.1.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.
Potentially problematic release.
This version of multi-agent-observability might be problematic. Click here for more details.
- ma_trace/__init__.py +204 -0
- ma_trace/_version.py +2 -0
- ma_trace/adapters/__init__.py +9 -0
- ma_trace/adapters/autogen.py +159 -0
- ma_trace/adapters/crewai.py +337 -0
- ma_trace/adapters/langchain.py +395 -0
- ma_trace/adapters/langgraph.py +100 -0
- ma_trace/cli.py +349 -0
- ma_trace/context.py +29 -0
- ma_trace/contracts.py +107 -0
- ma_trace/episode.py +208 -0
- ma_trace/events.py +291 -0
- ma_trace/exporters.py +154 -0
- ma_trace/graph.py +211 -0
- ma_trace/memory.py +174 -0
- ma_trace/metrics.py +340 -0
- ma_trace/py.typed +0 -0
- ma_trace/replay.py +398 -0
- ma_trace/sampling.py +117 -0
- ma_trace/semconv.py +140 -0
- ma_trace/store.py +185 -0
- ma_trace/tracer.py +779 -0
- multi_agent_observability-0.1.0.dist-info/METADATA +365 -0
- multi_agent_observability-0.1.0.dist-info/RECORD +27 -0
- multi_agent_observability-0.1.0.dist-info/WHEEL +4 -0
- multi_agent_observability-0.1.0.dist-info/entry_points.txt +2 -0
- multi_agent_observability-0.1.0.dist-info/licenses/LICENSE +201 -0
ma_trace/memory.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Memory operation traces and a drop-in wrapper for dict-like memory stores."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections import Counter, defaultdict
|
|
7
|
+
from collections.abc import Iterable, MutableMapping
|
|
8
|
+
from typing import TYPE_CHECKING, Any
|
|
9
|
+
|
|
10
|
+
from .events import EvictionReason, MemoryEvent, MemoryOp, MemoryType
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
13
|
+
from .tracer import MATrace
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class MemoryTrace:
|
|
17
|
+
"""Analysis helpers over a sequence of :class:`~ma_trace.events.MemoryEvent`."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, events: Iterable[MemoryEvent]) -> None:
|
|
20
|
+
self.events = list(events)
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def reads(self) -> list[MemoryEvent]:
|
|
24
|
+
return [e for e in self.events if e.op == MemoryOp.READ]
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def writes(self) -> list[MemoryEvent]:
|
|
28
|
+
return [e for e in self.events if e.op == MemoryOp.WRITE]
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def evictions(self) -> list[MemoryEvent]:
|
|
32
|
+
return [e for e in self.events if e.op == MemoryOp.EVICT]
|
|
33
|
+
|
|
34
|
+
def hit_ratio(self, reads_only: bool = False) -> float:
|
|
35
|
+
"""Memory hit ratio.
|
|
36
|
+
|
|
37
|
+
MA-Trace defines it as successful retrievals divided by *total memory
|
|
38
|
+
accesses* (reads and writes). Pass ``reads_only=True`` for the classic
|
|
39
|
+
cache-hit-ratio denominator (reads only).
|
|
40
|
+
"""
|
|
41
|
+
hits = sum(1 for e in self.reads if e.hit)
|
|
42
|
+
denom = len(self.reads) if reads_only else len(self.reads) + len(self.writes)
|
|
43
|
+
return hits / denom if denom else 0.0
|
|
44
|
+
|
|
45
|
+
def by_agent(self) -> dict[str, MemoryTrace]:
|
|
46
|
+
groups: dict[str, list[MemoryEvent]] = defaultdict(list)
|
|
47
|
+
for e in self.events:
|
|
48
|
+
groups[e.agent or "?"].append(e)
|
|
49
|
+
return {a: MemoryTrace(evs) for a, evs in groups.items()}
|
|
50
|
+
|
|
51
|
+
def by_type(self) -> dict[str, MemoryTrace]:
|
|
52
|
+
groups: dict[str, list[MemoryEvent]] = defaultdict(list)
|
|
53
|
+
for e in self.events:
|
|
54
|
+
groups[e.memory_type.value].append(e)
|
|
55
|
+
return {t: MemoryTrace(evs) for t, evs in groups.items()}
|
|
56
|
+
|
|
57
|
+
def eviction_reasons(self) -> dict[str, int]:
|
|
58
|
+
return dict(Counter((e.eviction_reason or EvictionReason.UNKNOWN).value for e in self.evictions))
|
|
59
|
+
|
|
60
|
+
def thrashing_keys(self, min_cycles: int = 2) -> list[tuple[str, int]]:
|
|
61
|
+
"""Keys that were written and evicted repeatedly (write->evict cycles)."""
|
|
62
|
+
cycles: Counter[str] = Counter()
|
|
63
|
+
last_written: set[str] = set()
|
|
64
|
+
for e in self.events:
|
|
65
|
+
if e.op == MemoryOp.WRITE:
|
|
66
|
+
last_written.add(e.key)
|
|
67
|
+
elif e.op in (MemoryOp.EVICT, MemoryOp.DELETE) and e.key in last_written:
|
|
68
|
+
cycles[e.key] += 1
|
|
69
|
+
last_written.discard(e.key)
|
|
70
|
+
return sorted(((k, n) for k, n in cycles.items() if n >= min_cycles), key=lambda x: -x[1])
|
|
71
|
+
|
|
72
|
+
def low_confidence_reads(self, threshold: float = 0.5) -> list[MemoryEvent]:
|
|
73
|
+
return [e for e in self.reads if e.confidence is not None and e.confidence < threshold]
|
|
74
|
+
|
|
75
|
+
def misses(self) -> list[MemoryEvent]:
|
|
76
|
+
return [e for e in self.reads if e.hit is False]
|
|
77
|
+
|
|
78
|
+
def summary(self) -> dict[str, Any]:
|
|
79
|
+
return {
|
|
80
|
+
"accesses": len(self.events),
|
|
81
|
+
"reads": len(self.reads),
|
|
82
|
+
"writes": len(self.writes),
|
|
83
|
+
"evictions": len(self.evictions),
|
|
84
|
+
"hit_ratio": round(self.hit_ratio(), 4),
|
|
85
|
+
"hit_ratio_reads_only": round(self.hit_ratio(reads_only=True), 4),
|
|
86
|
+
"eviction_reasons": self.eviction_reasons(),
|
|
87
|
+
"thrashing_keys": self.thrashing_keys(),
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class TracedMemory(MutableMapping[str, Any]):
|
|
92
|
+
"""Wrap any dict-like store so every access is recorded as a memory operation.
|
|
93
|
+
|
|
94
|
+
>>> mem = TracedMemory({}, agent="planner", memory_type=MemoryType.EPISODIC, tracer=tracer)
|
|
95
|
+
>>> mem["goal"] = "buy milk" # WRITE
|
|
96
|
+
>>> mem.get("goal") # READ (hit)
|
|
97
|
+
>>> mem.evict("goal", EvictionReason.CAPACITY)
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
def __init__(
|
|
101
|
+
self,
|
|
102
|
+
store: MutableMapping[str, Any] | None,
|
|
103
|
+
*,
|
|
104
|
+
agent: str,
|
|
105
|
+
memory_type: MemoryType | str = MemoryType.EPISODIC,
|
|
106
|
+
tracer: MATrace | None = None,
|
|
107
|
+
capacity: int | None = None,
|
|
108
|
+
) -> None:
|
|
109
|
+
self._store: MutableMapping[str, Any] = store if store is not None else {}
|
|
110
|
+
self.agent = agent
|
|
111
|
+
self.memory_type = MemoryType(memory_type)
|
|
112
|
+
self._tracer = tracer
|
|
113
|
+
self.capacity = capacity
|
|
114
|
+
self._order: list[str] = list(self._store.keys())
|
|
115
|
+
|
|
116
|
+
def _t(self) -> MATrace:
|
|
117
|
+
if self._tracer is None:
|
|
118
|
+
from .tracer import get_tracer
|
|
119
|
+
|
|
120
|
+
self._tracer = get_tracer()
|
|
121
|
+
return self._tracer
|
|
122
|
+
|
|
123
|
+
# MutableMapping protocol ------------------------------------------------
|
|
124
|
+
|
|
125
|
+
def __getitem__(self, key: str) -> Any:
|
|
126
|
+
hit = key in self._store
|
|
127
|
+
self._t().memory(self.agent, MemoryOp.READ, self.memory_type, key, hit=hit)
|
|
128
|
+
return self._store[key]
|
|
129
|
+
|
|
130
|
+
def get(self, key: str, default: Any = None, *, confidence: float | None = None) -> Any: # type: ignore[override]
|
|
131
|
+
hit = key in self._store
|
|
132
|
+
self._t().memory(self.agent, MemoryOp.READ, self.memory_type, key, hit=hit, confidence=confidence)
|
|
133
|
+
return self._store.get(key, default)
|
|
134
|
+
|
|
135
|
+
def __setitem__(self, key: str, value: Any) -> None:
|
|
136
|
+
self.set(key, value)
|
|
137
|
+
|
|
138
|
+
def set(self, key: str, value: Any, *, confidence: float | None = None) -> None:
|
|
139
|
+
if self.capacity is not None and key not in self._store and len(self._store) >= self.capacity:
|
|
140
|
+
victim = self._order.pop(0)
|
|
141
|
+
self._store.pop(victim, None)
|
|
142
|
+
self._t().memory(
|
|
143
|
+
self.agent, MemoryOp.EVICT, self.memory_type, victim, eviction_reason=EvictionReason.CAPACITY
|
|
144
|
+
)
|
|
145
|
+
if key not in self._store:
|
|
146
|
+
self._order.append(key)
|
|
147
|
+
self._store[key] = value
|
|
148
|
+
self._t().memory(self.agent, MemoryOp.WRITE, self.memory_type, key, confidence=confidence)
|
|
149
|
+
|
|
150
|
+
def __delitem__(self, key: str) -> None:
|
|
151
|
+
del self._store[key]
|
|
152
|
+
if key in self._order:
|
|
153
|
+
self._order.remove(key)
|
|
154
|
+
self._t().memory(self.agent, MemoryOp.DELETE, self.memory_type, key)
|
|
155
|
+
|
|
156
|
+
def evict(self, key: str, reason: EvictionReason | str = EvictionReason.POLICY) -> None:
|
|
157
|
+
self._store.pop(key, None)
|
|
158
|
+
if key in self._order:
|
|
159
|
+
self._order.remove(key)
|
|
160
|
+
self._t().memory(
|
|
161
|
+
self.agent, MemoryOp.EVICT, self.memory_type, key, eviction_reason=EvictionReason(reason)
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
def __iter__(self): # type: ignore[no-untyped-def]
|
|
165
|
+
return iter(self._store)
|
|
166
|
+
|
|
167
|
+
def __len__(self) -> int:
|
|
168
|
+
return len(self._store)
|
|
169
|
+
|
|
170
|
+
def __contains__(self, key: object) -> bool:
|
|
171
|
+
return key in self._store
|
|
172
|
+
|
|
173
|
+
def raw(self) -> MutableMapping[str, Any]:
|
|
174
|
+
return self._store
|
ma_trace/metrics.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Multi-agent service level objectives (SLOs).
|
|
3
|
+
|
|
4
|
+
Three coordination-quality metrics are computed for every episode:
|
|
5
|
+
|
|
6
|
+
* **Coordination overhead** ``CO = (T_wall - sum(T_llm + T_tool)) / T_wall`` -
|
|
7
|
+
the share of wall-clock time not spent doing productive inference or tool work.
|
|
8
|
+
* **Redundant action rate** ``RAR`` - duplicate or no-op actions relative to all
|
|
9
|
+
actions (``redundant_actions_per_second`` gives the time-normalised variant).
|
|
10
|
+
* **Oscillation rate** ``OR = repeated state transitions / total state transitions`` -
|
|
11
|
+
how often agents flip back and forth between states they have already visited.
|
|
12
|
+
|
|
13
|
+
plus the **memory hit ratio** ``MHR = successful retrievals / total memory accesses``.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import itertools
|
|
19
|
+
from dataclasses import asdict, dataclass
|
|
20
|
+
from typing import TYPE_CHECKING, Any
|
|
21
|
+
|
|
22
|
+
from ._version import __version__
|
|
23
|
+
from .events import ActionEvent, CallEvent, CallType, ContractEvent, MemoryOp, StateEvent
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
26
|
+
from .episode import Episode
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class SLOMetrics:
|
|
31
|
+
episode_id: str
|
|
32
|
+
episode_name: str
|
|
33
|
+
wall_time_s: float
|
|
34
|
+
llm_time_s: float
|
|
35
|
+
tool_time_s: float
|
|
36
|
+
coordination_overhead: float
|
|
37
|
+
coordination_overhead_raw: float
|
|
38
|
+
total_actions: int
|
|
39
|
+
redundant_actions: int
|
|
40
|
+
redundant_action_rate: float
|
|
41
|
+
redundant_actions_per_second: float
|
|
42
|
+
total_transitions: int
|
|
43
|
+
repeated_transitions: int
|
|
44
|
+
oscillation_rate: float
|
|
45
|
+
memory_accesses: int
|
|
46
|
+
memory_hits: int
|
|
47
|
+
memory_hit_ratio: float
|
|
48
|
+
coordination_events: int
|
|
49
|
+
agents: int
|
|
50
|
+
llm_calls: int
|
|
51
|
+
tool_calls: int
|
|
52
|
+
|
|
53
|
+
def to_dict(self) -> dict[str, Any]:
|
|
54
|
+
return asdict(self)
|
|
55
|
+
|
|
56
|
+
def format(self) -> str:
|
|
57
|
+
rows = [
|
|
58
|
+
("coordination overhead (CO)", f"{self.coordination_overhead:.3f}"),
|
|
59
|
+
(
|
|
60
|
+
"redundant action rate (RAR)",
|
|
61
|
+
f"{self.redundant_action_rate:.3f} ({self.redundant_actions}/{self.total_actions})",
|
|
62
|
+
),
|
|
63
|
+
(
|
|
64
|
+
"oscillation rate (OR)",
|
|
65
|
+
f"{self.oscillation_rate:.3f} ({self.repeated_transitions}/{self.total_transitions})",
|
|
66
|
+
),
|
|
67
|
+
(
|
|
68
|
+
"memory hit ratio (MHR)",
|
|
69
|
+
f"{self.memory_hit_ratio:.3f} ({self.memory_hits}/{self.memory_accesses})",
|
|
70
|
+
),
|
|
71
|
+
("wall time", f"{self.wall_time_s:.3f}s"),
|
|
72
|
+
("llm / tool time", f"{self.llm_time_s:.3f}s / {self.tool_time_s:.3f}s"),
|
|
73
|
+
("llm / tool calls", f"{self.llm_calls} / {self.tool_calls}"),
|
|
74
|
+
("coordination events", str(self.coordination_events)),
|
|
75
|
+
("agents", str(self.agents)),
|
|
76
|
+
]
|
|
77
|
+
width = max(len(r[0]) for r in rows)
|
|
78
|
+
return "\n".join(f"{k.ljust(width)} {v}" for k, v in rows)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class SLOThresholds:
|
|
83
|
+
"""Alert thresholds. The defaults are conservative levels typical of an un-optimised
|
|
84
|
+
multi-agent system: crossing one means the system is doing no better than such a baseline.
|
|
85
|
+
Calibrate them against your own recorded episodes."""
|
|
86
|
+
|
|
87
|
+
coordination_overhead_max: float = 0.42
|
|
88
|
+
redundant_action_rate_max: float = 0.18
|
|
89
|
+
oscillation_rate_max: float = 0.23
|
|
90
|
+
memory_hit_ratio_min: float | None = None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass
|
|
94
|
+
class SLOViolation:
|
|
95
|
+
metric: str
|
|
96
|
+
value: float
|
|
97
|
+
threshold: float
|
|
98
|
+
comparison: str # ">" or "<"
|
|
99
|
+
|
|
100
|
+
def __str__(self) -> str:
|
|
101
|
+
return f"{self.metric}={self.value:.3f} {self.comparison} {self.threshold:.3f}"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def evaluate(metrics: SLOMetrics, thresholds: SLOThresholds | None = None) -> list[SLOViolation]:
|
|
105
|
+
t = thresholds or SLOThresholds()
|
|
106
|
+
out: list[SLOViolation] = []
|
|
107
|
+
if metrics.coordination_overhead > t.coordination_overhead_max:
|
|
108
|
+
out.append(
|
|
109
|
+
SLOViolation(
|
|
110
|
+
"coordination_overhead", metrics.coordination_overhead, t.coordination_overhead_max, ">"
|
|
111
|
+
)
|
|
112
|
+
)
|
|
113
|
+
if metrics.redundant_action_rate > t.redundant_action_rate_max:
|
|
114
|
+
out.append(
|
|
115
|
+
SLOViolation(
|
|
116
|
+
"redundant_action_rate", metrics.redundant_action_rate, t.redundant_action_rate_max, ">"
|
|
117
|
+
)
|
|
118
|
+
)
|
|
119
|
+
if metrics.oscillation_rate > t.oscillation_rate_max:
|
|
120
|
+
out.append(SLOViolation("oscillation_rate", metrics.oscillation_rate, t.oscillation_rate_max, ">"))
|
|
121
|
+
if (
|
|
122
|
+
t.memory_hit_ratio_min is not None
|
|
123
|
+
and metrics.memory_accesses
|
|
124
|
+
and metrics.memory_hit_ratio < t.memory_hit_ratio_min
|
|
125
|
+
):
|
|
126
|
+
out.append(SLOViolation("memory_hit_ratio", metrics.memory_hit_ratio, t.memory_hit_ratio_min, "<"))
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# --- building blocks ----------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def find_redundant_actions(actions: list[ActionEvent]) -> list[ActionEvent]:
|
|
134
|
+
"""Return the actions that are duplicates of an earlier action or explicit no-ops."""
|
|
135
|
+
seen: set[tuple[str | None, str, str]] = set()
|
|
136
|
+
redundant: list[ActionEvent] = []
|
|
137
|
+
for a in sorted(actions, key=lambda e: e.seq):
|
|
138
|
+
key = (a.agent, a.name, a.args_fingerprint)
|
|
139
|
+
is_noop = a.noop or (
|
|
140
|
+
a.state_before is not None and a.state_after is not None and a.state_before == a.state_after
|
|
141
|
+
)
|
|
142
|
+
if key in seen or is_noop:
|
|
143
|
+
redundant.append(a)
|
|
144
|
+
seen.add(key)
|
|
145
|
+
return redundant
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def state_sequences(episode: Episode) -> dict[str, list[str]]:
|
|
149
|
+
"""Ordered state-hash sequence per agent, with consecutive duplicates collapsed."""
|
|
150
|
+
seqs: dict[str, list[str]] = {}
|
|
151
|
+
|
|
152
|
+
def push(agent: str | None, h: str | None) -> None:
|
|
153
|
+
if not h:
|
|
154
|
+
return
|
|
155
|
+
key = agent or "?"
|
|
156
|
+
seq = seqs.setdefault(key, [])
|
|
157
|
+
if not seq or seq[-1] != h:
|
|
158
|
+
seq.append(h)
|
|
159
|
+
|
|
160
|
+
for e in sorted(episode.events, key=lambda ev: ev.seq):
|
|
161
|
+
if isinstance(e, StateEvent):
|
|
162
|
+
push(e.agent, e.state_hash)
|
|
163
|
+
elif isinstance(e, ContractEvent):
|
|
164
|
+
push(e.agent, e.pre_hash)
|
|
165
|
+
push(e.agent, e.post_hash)
|
|
166
|
+
elif isinstance(e, ActionEvent):
|
|
167
|
+
push(e.agent, e.state_before)
|
|
168
|
+
push(e.agent, e.state_after)
|
|
169
|
+
return seqs
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def count_transitions(seqs: dict[str, list[str]]) -> tuple[int, int]:
|
|
173
|
+
"""``(total_transitions, repeated_transitions)`` over all agents."""
|
|
174
|
+
total = repeated = 0
|
|
175
|
+
for seq in seqs.values():
|
|
176
|
+
seen: set[tuple[str, str]] = set()
|
|
177
|
+
for a, b in itertools.pairwise(seq):
|
|
178
|
+
total += 1
|
|
179
|
+
if (a, b) in seen:
|
|
180
|
+
repeated += 1
|
|
181
|
+
seen.add((a, b))
|
|
182
|
+
return total, repeated
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def compute_metrics(episode: Episode) -> SLOMetrics:
|
|
186
|
+
wall = episode.duration_s
|
|
187
|
+
calls: list[CallEvent] = episode.calls
|
|
188
|
+
llm_time = sum(c.duration_s for c in calls if c.call_type == CallType.LLM)
|
|
189
|
+
tool_time = sum(c.duration_s for c in calls if c.call_type == CallType.TOOL)
|
|
190
|
+
co_raw = (wall - (llm_time + tool_time)) / wall if wall > 0 else 0.0
|
|
191
|
+
co = min(1.0, max(0.0, co_raw))
|
|
192
|
+
|
|
193
|
+
actions = episode.actions
|
|
194
|
+
redundant = find_redundant_actions(actions)
|
|
195
|
+
rar = len(redundant) / len(actions) if actions else 0.0
|
|
196
|
+
rar_per_s = len(redundant) / wall if wall > 0 else 0.0
|
|
197
|
+
|
|
198
|
+
total_tr, repeated_tr = count_transitions(state_sequences(episode))
|
|
199
|
+
osc = repeated_tr / total_tr if total_tr else 0.0
|
|
200
|
+
|
|
201
|
+
mem = episode.memory_events
|
|
202
|
+
reads = [m for m in mem if m.op == MemoryOp.READ]
|
|
203
|
+
writes = [m for m in mem if m.op == MemoryOp.WRITE]
|
|
204
|
+
hits = sum(1 for m in reads if m.hit)
|
|
205
|
+
accesses = len(reads) + len(writes)
|
|
206
|
+
mhr = hits / accesses if accesses else 0.0
|
|
207
|
+
|
|
208
|
+
return SLOMetrics(
|
|
209
|
+
episode_id=episode.id,
|
|
210
|
+
episode_name=episode.name,
|
|
211
|
+
wall_time_s=wall,
|
|
212
|
+
llm_time_s=llm_time,
|
|
213
|
+
tool_time_s=tool_time,
|
|
214
|
+
coordination_overhead=co,
|
|
215
|
+
coordination_overhead_raw=co_raw,
|
|
216
|
+
total_actions=len(actions),
|
|
217
|
+
redundant_actions=len(redundant),
|
|
218
|
+
redundant_action_rate=rar,
|
|
219
|
+
redundant_actions_per_second=rar_per_s,
|
|
220
|
+
total_transitions=total_tr,
|
|
221
|
+
repeated_transitions=repeated_tr,
|
|
222
|
+
oscillation_rate=osc,
|
|
223
|
+
memory_accesses=accesses,
|
|
224
|
+
memory_hits=hits,
|
|
225
|
+
memory_hit_ratio=mhr,
|
|
226
|
+
coordination_events=len(episode.coordination_events),
|
|
227
|
+
agents=len(episode.agents),
|
|
228
|
+
llm_calls=sum(1 for c in calls if c.call_type == CallType.LLM),
|
|
229
|
+
tool_calls=sum(1 for c in calls if c.call_type == CallType.TOOL),
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
# --- exporters ----------------------------------------------------------------
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class OTelMetricsExporter:
|
|
237
|
+
"""Publishes SLO metrics through the OpenTelemetry metrics API.
|
|
238
|
+
|
|
239
|
+
Instruments (all unit ``1`` unless noted): ``<ns>.coordination_overhead``,
|
|
240
|
+
``<ns>.redundant_action_rate``, ``<ns>.oscillation_rate``, ``<ns>.memory_hit_ratio``
|
|
241
|
+
(histograms), ``<ns>.episodes`` and ``<ns>.redundant_actions`` (counters) and
|
|
242
|
+
``<ns>.episode.duration`` (histogram, seconds).
|
|
243
|
+
"""
|
|
244
|
+
|
|
245
|
+
def __init__(self, meter_provider: Any = None, namespace: str = "ma_trace") -> None:
|
|
246
|
+
from opentelemetry import metrics as otel_metrics
|
|
247
|
+
|
|
248
|
+
meter = otel_metrics.get_meter("ma_trace", __version__, meter_provider=meter_provider)
|
|
249
|
+
ns = namespace
|
|
250
|
+
self._co = meter.create_histogram(
|
|
251
|
+
f"{ns}.coordination_overhead", unit="1", description="Coordination overhead per episode"
|
|
252
|
+
)
|
|
253
|
+
self._rar = meter.create_histogram(
|
|
254
|
+
f"{ns}.redundant_action_rate", unit="1", description="Redundant action rate per episode"
|
|
255
|
+
)
|
|
256
|
+
self._or = meter.create_histogram(
|
|
257
|
+
f"{ns}.oscillation_rate", unit="1", description="Oscillation rate per episode"
|
|
258
|
+
)
|
|
259
|
+
self._mhr = meter.create_histogram(
|
|
260
|
+
f"{ns}.memory_hit_ratio", unit="1", description="Memory hit ratio per episode"
|
|
261
|
+
)
|
|
262
|
+
self._dur = meter.create_histogram(
|
|
263
|
+
f"{ns}.episode.duration", unit="s", description="Episode wall-clock duration"
|
|
264
|
+
)
|
|
265
|
+
self._episodes = meter.create_counter(f"{ns}.episodes", unit="1", description="Episodes completed")
|
|
266
|
+
self._redundant = meter.create_counter(
|
|
267
|
+
f"{ns}.redundant_actions", unit="1", description="Redundant actions observed"
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
def export(self, m: SLOMetrics, attributes: dict[str, Any] | None = None) -> None:
|
|
271
|
+
attrs = {"episode.name": m.episode_name}
|
|
272
|
+
if attributes:
|
|
273
|
+
attrs.update(attributes)
|
|
274
|
+
self._co.record(m.coordination_overhead, attrs)
|
|
275
|
+
self._rar.record(m.redundant_action_rate, attrs)
|
|
276
|
+
self._or.record(m.oscillation_rate, attrs)
|
|
277
|
+
self._mhr.record(m.memory_hit_ratio, attrs)
|
|
278
|
+
self._dur.record(m.wall_time_s, attrs)
|
|
279
|
+
self._episodes.add(1, attrs)
|
|
280
|
+
if m.redundant_actions:
|
|
281
|
+
self._redundant.add(m.redundant_actions, attrs)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
class PrometheusExporter:
|
|
285
|
+
"""Exposes the SLO metrics as Prometheus gauges (requires ``prometheus-client``).
|
|
286
|
+
|
|
287
|
+
>>> exporter = PrometheusExporter() # uses the default registry
|
|
288
|
+
>>> tracer = MATrace(metrics_exporters=[exporter])
|
|
289
|
+
>>> # then serve with prometheus_client.start_http_server(9464)
|
|
290
|
+
"""
|
|
291
|
+
|
|
292
|
+
def __init__(self, registry: Any = None, prefix: str = "ma_trace") -> None:
|
|
293
|
+
try:
|
|
294
|
+
from prometheus_client import REGISTRY, Counter, Gauge
|
|
295
|
+
except ImportError as e: # pragma: no cover - exercised only without the extra
|
|
296
|
+
raise ImportError(
|
|
297
|
+
"PrometheusExporter requires prometheus-client: "
|
|
298
|
+
"pip install 'multi-agent-observability[prometheus]'"
|
|
299
|
+
) from e
|
|
300
|
+
reg = registry or REGISTRY
|
|
301
|
+
labels = ["episode_name"]
|
|
302
|
+
self.coordination_overhead = Gauge(
|
|
303
|
+
f"{prefix}_coordination_overhead",
|
|
304
|
+
"Coordination overhead of the last episode",
|
|
305
|
+
labels,
|
|
306
|
+
registry=reg,
|
|
307
|
+
)
|
|
308
|
+
self.redundant_action_rate = Gauge(
|
|
309
|
+
f"{prefix}_redundant_action_rate",
|
|
310
|
+
"Redundant action rate of the last episode",
|
|
311
|
+
labels,
|
|
312
|
+
registry=reg,
|
|
313
|
+
)
|
|
314
|
+
self.oscillation_rate = Gauge(
|
|
315
|
+
f"{prefix}_oscillation_rate", "Oscillation rate of the last episode", labels, registry=reg
|
|
316
|
+
)
|
|
317
|
+
self.memory_hit_ratio = Gauge(
|
|
318
|
+
f"{prefix}_memory_hit_ratio", "Memory hit ratio of the last episode", labels, registry=reg
|
|
319
|
+
)
|
|
320
|
+
self.episode_duration = Gauge(
|
|
321
|
+
f"{prefix}_episode_duration_seconds",
|
|
322
|
+
"Wall-clock duration of the last episode",
|
|
323
|
+
labels,
|
|
324
|
+
registry=reg,
|
|
325
|
+
)
|
|
326
|
+
self.episodes_total = Counter(f"{prefix}_episodes", "Episodes completed", labels, registry=reg)
|
|
327
|
+
self.redundant_actions_total = Counter(
|
|
328
|
+
f"{prefix}_redundant_actions", "Redundant actions observed", labels, registry=reg
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
def export(self, m: SLOMetrics, attributes: dict[str, Any] | None = None) -> None:
|
|
332
|
+
lbl = {"episode_name": m.episode_name}
|
|
333
|
+
self.coordination_overhead.labels(**lbl).set(m.coordination_overhead)
|
|
334
|
+
self.redundant_action_rate.labels(**lbl).set(m.redundant_action_rate)
|
|
335
|
+
self.oscillation_rate.labels(**lbl).set(m.oscillation_rate)
|
|
336
|
+
self.memory_hit_ratio.labels(**lbl).set(m.memory_hit_ratio)
|
|
337
|
+
self.episode_duration.labels(**lbl).set(m.wall_time_s)
|
|
338
|
+
self.episodes_total.labels(**lbl).inc()
|
|
339
|
+
if m.redundant_actions:
|
|
340
|
+
self.redundant_actions_total.labels(**lbl).inc(m.redundant_actions)
|
ma_trace/py.typed
ADDED
|
File without changes
|