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/events.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Event model recorded inside an episode.
|
|
3
|
+
|
|
4
|
+
Every observable thing that happens while an episode is open is appended to the
|
|
5
|
+
episode as one of the dataclasses below. They are plain data: JSON-serialisable
|
|
6
|
+
through :meth:`Event.to_dict` and reconstructable through :func:`event_from_dict`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import dataclasses
|
|
12
|
+
import enum
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Any, ClassVar
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class CoordinationKind(str, enum.Enum):
|
|
21
|
+
"""Semantics of a coordination edge between two agents."""
|
|
22
|
+
|
|
23
|
+
MESSAGE = "message"
|
|
24
|
+
DELEGATION = "delegation"
|
|
25
|
+
NEGOTIATION = "negotiation"
|
|
26
|
+
CONSENSUS = "consensus"
|
|
27
|
+
RESPONSE = "response"
|
|
28
|
+
BROADCAST = "broadcast"
|
|
29
|
+
HANDOFF = "handoff"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class MemoryOp(str, enum.Enum):
|
|
33
|
+
READ = "read"
|
|
34
|
+
WRITE = "write"
|
|
35
|
+
EVICT = "evict"
|
|
36
|
+
DELETE = "delete"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class MemoryType(str, enum.Enum):
|
|
40
|
+
EPISODIC = "episodic"
|
|
41
|
+
SEMANTIC = "semantic"
|
|
42
|
+
WORKING = "working"
|
|
43
|
+
PROCEDURAL = "procedural"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class EvictionReason(str, enum.Enum):
|
|
47
|
+
CAPACITY = "capacity"
|
|
48
|
+
POLICY = "policy"
|
|
49
|
+
TTL = "ttl"
|
|
50
|
+
STALE = "stale"
|
|
51
|
+
MANUAL = "manual"
|
|
52
|
+
UNKNOWN = "unknown"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class CallType(str, enum.Enum):
|
|
56
|
+
LLM = "llm"
|
|
57
|
+
TOOL = "tool"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
_ADDRESS_RE = re.compile(r" at 0x[0-9a-fA-F]+")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _json_default(obj: Any) -> Any:
|
|
64
|
+
if isinstance(obj, enum.Enum):
|
|
65
|
+
return obj.value
|
|
66
|
+
if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
|
|
67
|
+
return dataclasses.asdict(obj)
|
|
68
|
+
if isinstance(obj, (set, frozenset)):
|
|
69
|
+
return sorted(obj, key=repr)
|
|
70
|
+
if isinstance(obj, (bytes, bytearray)):
|
|
71
|
+
return obj.hex()
|
|
72
|
+
model_dump = getattr(obj, "model_dump", None)
|
|
73
|
+
if callable(model_dump):
|
|
74
|
+
try:
|
|
75
|
+
return model_dump()
|
|
76
|
+
except Exception: # pragma: no cover - defensive
|
|
77
|
+
pass
|
|
78
|
+
to_dict = getattr(obj, "to_dict", None)
|
|
79
|
+
if callable(to_dict):
|
|
80
|
+
try:
|
|
81
|
+
return to_dict()
|
|
82
|
+
except Exception: # pragma: no cover - defensive
|
|
83
|
+
pass
|
|
84
|
+
return repr(obj)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def canonical_json(obj: Any) -> str:
|
|
88
|
+
"""Deterministic JSON encoding (sorted keys, compact separators, repr fallback)."""
|
|
89
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), default=_json_default, ensure_ascii=False)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def fingerprint(obj: Any) -> str:
|
|
93
|
+
"""SHA-256 fingerprint of ``obj`` based on :func:`canonical_json`.
|
|
94
|
+
|
|
95
|
+
Python object addresses (``<Foo object at 0x...>``) are stripped before hashing so
|
|
96
|
+
that the fingerprint of an un-serialisable object is stable across processes.
|
|
97
|
+
"""
|
|
98
|
+
text = _ADDRESS_RE.sub("", canonical_json(obj))
|
|
99
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def json_safe(obj: Any) -> tuple[Any, bool]:
|
|
103
|
+
"""Return ``(value, serialisable)`` where ``value`` can be stored as JSON.
|
|
104
|
+
|
|
105
|
+
If ``obj`` (or a natural conversion of it - pydantic ``model_dump``, dataclass,
|
|
106
|
+
``to_dict``) is JSON serialisable it is returned with ``True``. Otherwise a
|
|
107
|
+
``{"__repr__": ...}`` placeholder is returned with ``False`` so that the episode
|
|
108
|
+
can still be persisted, while replay knows that the output is not available.
|
|
109
|
+
"""
|
|
110
|
+
try:
|
|
111
|
+
json.dumps(obj)
|
|
112
|
+
return obj, True
|
|
113
|
+
except (TypeError, ValueError):
|
|
114
|
+
pass
|
|
115
|
+
try:
|
|
116
|
+
converted = json.loads(canonical_json(obj))
|
|
117
|
+
except (TypeError, ValueError): # pragma: no cover - canonical_json never raises in practice
|
|
118
|
+
return {"__repr__": repr(obj)}, False
|
|
119
|
+
# canonical_json falls back to ``repr`` for unknown objects; treat a bare
|
|
120
|
+
# string result for a non-string input as "not really serialisable".
|
|
121
|
+
if isinstance(converted, str) and not isinstance(obj, str):
|
|
122
|
+
return {"__repr__": converted}, False
|
|
123
|
+
return converted, True
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def truncate(text: Any, limit: int) -> str:
|
|
127
|
+
s = text if isinstance(text, str) else canonical_json(text)
|
|
128
|
+
if limit and len(s) > limit:
|
|
129
|
+
return s[: limit - 1] + "…"
|
|
130
|
+
return s
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# --- Events -----------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass
|
|
137
|
+
class Event:
|
|
138
|
+
"""Base class for everything recorded in an episode."""
|
|
139
|
+
|
|
140
|
+
type: ClassVar[str] = "event"
|
|
141
|
+
seq: int = 0
|
|
142
|
+
t: float = 0.0
|
|
143
|
+
agent: str | None = None
|
|
144
|
+
|
|
145
|
+
def to_dict(self) -> dict[str, Any]:
|
|
146
|
+
data = json.loads(canonical_json(dataclasses.asdict(self)))
|
|
147
|
+
data["type"] = self.type
|
|
148
|
+
return data
|
|
149
|
+
|
|
150
|
+
@classmethod
|
|
151
|
+
def from_dict(cls, data: dict[str, Any]) -> Event:
|
|
152
|
+
known = {f.name for f in dataclasses.fields(cls)}
|
|
153
|
+
kwargs: dict[str, Any] = {}
|
|
154
|
+
for key, value in data.items():
|
|
155
|
+
if key not in known:
|
|
156
|
+
continue
|
|
157
|
+
enum_cls = _ENUM_FIELDS.get(key)
|
|
158
|
+
if enum_cls is not None and isinstance(value, str):
|
|
159
|
+
value = enum_cls(value)
|
|
160
|
+
kwargs[key] = value
|
|
161
|
+
return cls(**kwargs)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@dataclass
|
|
165
|
+
class AgentEvent(Event):
|
|
166
|
+
"""Start/end of an agent invocation."""
|
|
167
|
+
|
|
168
|
+
type: ClassVar[str] = "agent"
|
|
169
|
+
phase: str = "start" # "start" | "end"
|
|
170
|
+
duration_s: float | None = None
|
|
171
|
+
error: str | None = None
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@dataclass
|
|
175
|
+
class CoordinationEvent(Event):
|
|
176
|
+
"""A directed coordination edge ``source -> target`` carrying a message."""
|
|
177
|
+
|
|
178
|
+
type: ClassVar[str] = "coordination"
|
|
179
|
+
source: str = ""
|
|
180
|
+
target: str = ""
|
|
181
|
+
message: str = ""
|
|
182
|
+
kind: CoordinationKind = CoordinationKind.MESSAGE
|
|
183
|
+
confidence: float | None = None
|
|
184
|
+
message_id: str | None = None
|
|
185
|
+
in_reply_to: str | None = None
|
|
186
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@dataclass
|
|
190
|
+
class MemoryEvent(Event):
|
|
191
|
+
"""One access to an agent memory system."""
|
|
192
|
+
|
|
193
|
+
type: ClassVar[str] = "memory"
|
|
194
|
+
op: MemoryOp = MemoryOp.READ
|
|
195
|
+
memory_type: MemoryType = MemoryType.EPISODIC
|
|
196
|
+
key: str = ""
|
|
197
|
+
confidence: float | None = None
|
|
198
|
+
hit: bool | None = None
|
|
199
|
+
eviction_reason: EvictionReason | None = None
|
|
200
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@dataclass
|
|
204
|
+
class ContractEvent(Event):
|
|
205
|
+
"""An environment contract: pre-state, post-state, seed and result of an action."""
|
|
206
|
+
|
|
207
|
+
type: ClassVar[str] = "contract"
|
|
208
|
+
action: str = ""
|
|
209
|
+
pre_hash: str = ""
|
|
210
|
+
post_hash: str | None = None
|
|
211
|
+
seed: int | None = None
|
|
212
|
+
result: str | None = None
|
|
213
|
+
verified: bool | None = None
|
|
214
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@dataclass
|
|
218
|
+
class CallEvent(Event):
|
|
219
|
+
"""A recorded non-deterministic call (LLM inference or tool execution)."""
|
|
220
|
+
|
|
221
|
+
type: ClassVar[str] = "call"
|
|
222
|
+
call_type: CallType = CallType.LLM
|
|
223
|
+
name: str = ""
|
|
224
|
+
provider: str | None = None
|
|
225
|
+
model: str | None = None
|
|
226
|
+
index: int = 0
|
|
227
|
+
input_fingerprint: str = ""
|
|
228
|
+
output: Any = None
|
|
229
|
+
output_fingerprint: str | None = None
|
|
230
|
+
output_recorded: bool = False
|
|
231
|
+
duration_s: float = 0.0
|
|
232
|
+
error: str | None = None
|
|
233
|
+
replayed: bool = False
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@dataclass
|
|
237
|
+
class ActionEvent(Event):
|
|
238
|
+
"""A discrete action taken by an agent (used for the redundant-action SLO)."""
|
|
239
|
+
|
|
240
|
+
type: ClassVar[str] = "action"
|
|
241
|
+
name: str = ""
|
|
242
|
+
args_fingerprint: str = ""
|
|
243
|
+
noop: bool = False
|
|
244
|
+
state_before: str | None = None
|
|
245
|
+
state_after: str | None = None
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
@dataclass
|
|
249
|
+
class StateEvent(Event):
|
|
250
|
+
"""A snapshot of an agent's (hashed) state, used for oscillation detection."""
|
|
251
|
+
|
|
252
|
+
type: ClassVar[str] = "state"
|
|
253
|
+
state_hash: str = ""
|
|
254
|
+
label: str | None = None
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
@dataclass
|
|
258
|
+
class LogEvent(Event):
|
|
259
|
+
type: ClassVar[str] = "log"
|
|
260
|
+
level: str = "info"
|
|
261
|
+
message: str = ""
|
|
262
|
+
data: dict[str, Any] = field(default_factory=dict)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
_ENUM_FIELDS: dict[str, type[enum.Enum]] = {
|
|
266
|
+
"kind": CoordinationKind,
|
|
267
|
+
"op": MemoryOp,
|
|
268
|
+
"memory_type": MemoryType,
|
|
269
|
+
"eviction_reason": EvictionReason,
|
|
270
|
+
"call_type": CallType,
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
EVENT_TYPES: dict[str, type[Event]] = {
|
|
274
|
+
cls.type: cls
|
|
275
|
+
for cls in (
|
|
276
|
+
AgentEvent,
|
|
277
|
+
CoordinationEvent,
|
|
278
|
+
MemoryEvent,
|
|
279
|
+
ContractEvent,
|
|
280
|
+
CallEvent,
|
|
281
|
+
ActionEvent,
|
|
282
|
+
StateEvent,
|
|
283
|
+
LogEvent,
|
|
284
|
+
)
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def event_from_dict(data: dict[str, Any]) -> Event:
|
|
289
|
+
"""Rebuild an event from its :meth:`Event.to_dict` form."""
|
|
290
|
+
cls = EVENT_TYPES.get(data.get("type", ""), Event)
|
|
291
|
+
return cls.from_dict(data)
|
ma_trace/exporters.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Helpers that build OpenTelemetry providers wired for MA-Trace.
|
|
3
|
+
|
|
4
|
+
The defaults suit a collector-based deployment: traces are buffered locally and exported
|
|
5
|
+
in batches every 10 seconds.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from opentelemetry import metrics as otel_metrics
|
|
14
|
+
from opentelemetry import trace
|
|
15
|
+
from opentelemetry.sdk.metrics import MeterProvider
|
|
16
|
+
from opentelemetry.sdk.metrics.export import (
|
|
17
|
+
ConsoleMetricExporter,
|
|
18
|
+
MetricReader,
|
|
19
|
+
PeriodicExportingMetricReader,
|
|
20
|
+
)
|
|
21
|
+
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
|
|
22
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
23
|
+
from opentelemetry.sdk.trace.export import (
|
|
24
|
+
BatchSpanProcessor,
|
|
25
|
+
ConsoleSpanExporter,
|
|
26
|
+
SimpleSpanProcessor,
|
|
27
|
+
SpanExporter,
|
|
28
|
+
)
|
|
29
|
+
from opentelemetry.sdk.trace.sampling import Sampler
|
|
30
|
+
|
|
31
|
+
log = logging.getLogger("ma_trace")
|
|
32
|
+
|
|
33
|
+
BATCH_DELAY_MS = 10_000 # batched export every 10 s
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def build_tracer_provider(
|
|
37
|
+
service_name: str = "ma-trace",
|
|
38
|
+
exporter: str | SpanExporter | None = "console",
|
|
39
|
+
*,
|
|
40
|
+
endpoint: str | None = None,
|
|
41
|
+
headers: dict[str, str] | None = None,
|
|
42
|
+
sampler: Sampler | None = None,
|
|
43
|
+
batch_delay_ms: int = BATCH_DELAY_MS,
|
|
44
|
+
max_queue_size: int = 8192,
|
|
45
|
+
max_export_batch_size: int = 512,
|
|
46
|
+
simple: bool = False,
|
|
47
|
+
resource_attributes: dict[str, Any] | None = None,
|
|
48
|
+
set_global: bool = True,
|
|
49
|
+
) -> TracerProvider:
|
|
50
|
+
"""Create a :class:`TracerProvider`.
|
|
51
|
+
|
|
52
|
+
``exporter`` may be ``"console"``, ``"otlp"`` (HTTP/protobuf; needs the ``otlp``
|
|
53
|
+
extra), ``"none"``/``None`` (no export) or any :class:`SpanExporter` instance.
|
|
54
|
+
"""
|
|
55
|
+
attrs: dict[str, Any] = {SERVICE_NAME: service_name, "ma_trace.version": _version()}
|
|
56
|
+
if resource_attributes:
|
|
57
|
+
attrs.update(resource_attributes)
|
|
58
|
+
provider = TracerProvider(resource=Resource.create(attrs), sampler=sampler)
|
|
59
|
+
span_exporter = _resolve_span_exporter(exporter, endpoint, headers)
|
|
60
|
+
if span_exporter is not None:
|
|
61
|
+
if simple:
|
|
62
|
+
provider.add_span_processor(SimpleSpanProcessor(span_exporter))
|
|
63
|
+
else:
|
|
64
|
+
provider.add_span_processor(
|
|
65
|
+
BatchSpanProcessor(
|
|
66
|
+
span_exporter,
|
|
67
|
+
max_queue_size=max_queue_size,
|
|
68
|
+
schedule_delay_millis=batch_delay_ms,
|
|
69
|
+
max_export_batch_size=max_export_batch_size,
|
|
70
|
+
)
|
|
71
|
+
)
|
|
72
|
+
if set_global:
|
|
73
|
+
_set_global_tracer_provider(provider)
|
|
74
|
+
return provider
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def build_meter_provider(
|
|
78
|
+
service_name: str = "ma-trace",
|
|
79
|
+
exporter: str | Any | None = "console",
|
|
80
|
+
*,
|
|
81
|
+
endpoint: str | None = None,
|
|
82
|
+
headers: dict[str, str] | None = None,
|
|
83
|
+
interval_ms: int = BATCH_DELAY_MS,
|
|
84
|
+
readers: list[MetricReader] | None = None,
|
|
85
|
+
set_global: bool = True,
|
|
86
|
+
) -> MeterProvider:
|
|
87
|
+
resource = Resource.create({SERVICE_NAME: service_name})
|
|
88
|
+
all_readers: list[MetricReader] = list(readers or [])
|
|
89
|
+
metric_exporter = _resolve_metric_exporter(exporter, endpoint, headers)
|
|
90
|
+
if metric_exporter is not None:
|
|
91
|
+
all_readers.append(PeriodicExportingMetricReader(metric_exporter, export_interval_millis=interval_ms))
|
|
92
|
+
provider = MeterProvider(resource=resource, metric_readers=all_readers)
|
|
93
|
+
if set_global:
|
|
94
|
+
try:
|
|
95
|
+
otel_metrics.set_meter_provider(provider)
|
|
96
|
+
except Exception: # pragma: no cover - OTel logs a warning when re-set
|
|
97
|
+
log.debug("global meter provider already set")
|
|
98
|
+
return provider
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _version() -> str:
|
|
102
|
+
from ._version import __version__
|
|
103
|
+
|
|
104
|
+
return __version__
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _set_global_tracer_provider(provider: TracerProvider) -> None:
|
|
108
|
+
current = trace.get_tracer_provider()
|
|
109
|
+
if isinstance(current, TracerProvider):
|
|
110
|
+
log.debug("global tracer provider already set; not overriding")
|
|
111
|
+
return
|
|
112
|
+
trace.set_tracer_provider(provider)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _resolve_span_exporter(
|
|
116
|
+
exporter: str | SpanExporter | None, endpoint: str | None, headers: dict[str, str] | None
|
|
117
|
+
) -> SpanExporter | None:
|
|
118
|
+
if exporter is None or exporter == "none":
|
|
119
|
+
return None
|
|
120
|
+
if isinstance(exporter, str):
|
|
121
|
+
if exporter == "console":
|
|
122
|
+
return ConsoleSpanExporter()
|
|
123
|
+
if exporter == "otlp":
|
|
124
|
+
try:
|
|
125
|
+
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
|
126
|
+
except ImportError as e:
|
|
127
|
+
raise ImportError(
|
|
128
|
+
"OTLP export requires the otlp extra: pip install 'multi-agent-observability[otlp]'"
|
|
129
|
+
) from e
|
|
130
|
+
return OTLPSpanExporter(endpoint=endpoint, headers=headers)
|
|
131
|
+
raise ValueError(
|
|
132
|
+
f"unknown span exporter {exporter!r}; use 'console', 'otlp', 'none' or a SpanExporter"
|
|
133
|
+
)
|
|
134
|
+
return exporter
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _resolve_metric_exporter(
|
|
138
|
+
exporter: str | Any | None, endpoint: str | None, headers: dict[str, str] | None
|
|
139
|
+
) -> Any:
|
|
140
|
+
if exporter is None or exporter == "none":
|
|
141
|
+
return None
|
|
142
|
+
if isinstance(exporter, str):
|
|
143
|
+
if exporter == "console":
|
|
144
|
+
return ConsoleMetricExporter()
|
|
145
|
+
if exporter == "otlp":
|
|
146
|
+
try:
|
|
147
|
+
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
|
148
|
+
except ImportError as e:
|
|
149
|
+
raise ImportError(
|
|
150
|
+
"OTLP export requires the otlp extra: pip install 'multi-agent-observability[otlp]'"
|
|
151
|
+
) from e
|
|
152
|
+
return OTLPMetricExporter(endpoint=endpoint, headers=headers)
|
|
153
|
+
raise ValueError(f"unknown metric exporter {exporter!r}")
|
|
154
|
+
return exporter
|
ma_trace/graph.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Coordination graphs: agents as nodes, coordination events as directed edges."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
from collections import defaultdict
|
|
8
|
+
from collections.abc import Iterable
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from .events import CoordinationEvent, CoordinationKind
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class EdgeSummary:
|
|
17
|
+
source: str
|
|
18
|
+
target: str
|
|
19
|
+
count: int
|
|
20
|
+
kinds: tuple[str, ...]
|
|
21
|
+
mean_confidence: float | None
|
|
22
|
+
first_t: float
|
|
23
|
+
last_t: float
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class CoordinationGraph:
|
|
27
|
+
"""A directed multigraph of agent-to-agent coordination events.
|
|
28
|
+
|
|
29
|
+
Nodes are agent names; every :class:`~ma_trace.events.CoordinationEvent` is one
|
|
30
|
+
directed edge from ``source`` to ``target`` carrying the message, its kind, a
|
|
31
|
+
confidence and a timestamp.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self) -> None:
|
|
35
|
+
self._agents: dict[str, None] = {}
|
|
36
|
+
self._edges: list[CoordinationEvent] = []
|
|
37
|
+
self._adj: dict[str, dict[str, list[CoordinationEvent]]] = defaultdict(lambda: defaultdict(list))
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def from_events(cls, events: Iterable[CoordinationEvent]) -> CoordinationGraph:
|
|
41
|
+
g = cls()
|
|
42
|
+
for e in events:
|
|
43
|
+
g.add(e)
|
|
44
|
+
return g
|
|
45
|
+
|
|
46
|
+
# -- mutation -----------------------------------------------------------
|
|
47
|
+
|
|
48
|
+
def add_agent(self, name: str) -> None:
|
|
49
|
+
self._agents.setdefault(name, None)
|
|
50
|
+
|
|
51
|
+
def add(self, event: CoordinationEvent) -> None:
|
|
52
|
+
self.add_agent(event.source)
|
|
53
|
+
self.add_agent(event.target)
|
|
54
|
+
self._edges.append(event)
|
|
55
|
+
self._adj[event.source][event.target].append(event)
|
|
56
|
+
|
|
57
|
+
# -- queries ------------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def agents(self) -> list[str]:
|
|
61
|
+
return list(self._agents)
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def edges(self) -> list[CoordinationEvent]:
|
|
65
|
+
return list(self._edges)
|
|
66
|
+
|
|
67
|
+
def successors(self, agent: str) -> list[str]:
|
|
68
|
+
return list(self._adj.get(agent, {}))
|
|
69
|
+
|
|
70
|
+
def predecessors(self, agent: str) -> list[str]:
|
|
71
|
+
return [src for src, targets in self._adj.items() if agent in targets]
|
|
72
|
+
|
|
73
|
+
def out_degree(self, agent: str) -> int:
|
|
74
|
+
return sum(len(v) for v in self._adj.get(agent, {}).values())
|
|
75
|
+
|
|
76
|
+
def in_degree(self, agent: str) -> int:
|
|
77
|
+
return sum(len(targets[agent]) for targets in self._adj.values() if agent in targets)
|
|
78
|
+
|
|
79
|
+
def edge_count(self, source: str, target: str) -> int:
|
|
80
|
+
return len(self._adj.get(source, {}).get(target, []))
|
|
81
|
+
|
|
82
|
+
def edge_summaries(self) -> list[EdgeSummary]:
|
|
83
|
+
out: list[EdgeSummary] = []
|
|
84
|
+
for src, targets in self._adj.items():
|
|
85
|
+
for tgt, evs in targets.items():
|
|
86
|
+
confs = [e.confidence for e in evs if e.confidence is not None]
|
|
87
|
+
kinds = tuple(sorted({e.kind.value for e in evs}))
|
|
88
|
+
out.append(
|
|
89
|
+
EdgeSummary(
|
|
90
|
+
source=src,
|
|
91
|
+
target=tgt,
|
|
92
|
+
count=len(evs),
|
|
93
|
+
kinds=kinds,
|
|
94
|
+
mean_confidence=(sum(confs) / len(confs)) if confs else None,
|
|
95
|
+
first_t=min(e.t for e in evs),
|
|
96
|
+
last_t=max(e.t for e in evs),
|
|
97
|
+
)
|
|
98
|
+
)
|
|
99
|
+
out.sort(key=lambda s: (s.first_t, s.source, s.target))
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
def bottlenecks(self, top: int = 3) -> list[tuple[str, int]]:
|
|
103
|
+
"""Agents ranked by inbound message volume (the busiest receivers)."""
|
|
104
|
+
ranked = sorted(((a, self.in_degree(a)) for a in self._agents), key=lambda x: (-x[1], x[0]))
|
|
105
|
+
return [(a, d) for a, d in ranked[:top] if d > 0]
|
|
106
|
+
|
|
107
|
+
def cycles(self) -> list[list[str]]:
|
|
108
|
+
"""Simple cycles in the aggregated digraph (each returned once, rotated to start at min)."""
|
|
109
|
+
found: set[tuple[str, ...]] = set()
|
|
110
|
+
result: list[list[str]] = []
|
|
111
|
+
nodes = list(self._agents)
|
|
112
|
+
|
|
113
|
+
def dfs(start: str, node: str, path: list[str], visited: set[str]) -> None:
|
|
114
|
+
for nxt in self.successors(node):
|
|
115
|
+
if nxt == start and len(path) >= 1:
|
|
116
|
+
cyc = path[:]
|
|
117
|
+
# rotate so the lexicographically smallest node comes first
|
|
118
|
+
i = cyc.index(min(cyc))
|
|
119
|
+
key = tuple(cyc[i:] + cyc[:i])
|
|
120
|
+
if key not in found:
|
|
121
|
+
found.add(key)
|
|
122
|
+
result.append(list(key))
|
|
123
|
+
elif nxt not in visited and nxt > start:
|
|
124
|
+
visited.add(nxt)
|
|
125
|
+
dfs(start, nxt, path + [nxt], visited)
|
|
126
|
+
visited.discard(nxt)
|
|
127
|
+
|
|
128
|
+
for n in nodes:
|
|
129
|
+
dfs(n, n, [n], {n})
|
|
130
|
+
return result
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def is_dag(self) -> bool:
|
|
134
|
+
return not self.cycles()
|
|
135
|
+
|
|
136
|
+
def delegation_depth(self) -> dict[str, int]:
|
|
137
|
+
"""Depth of every agent in the delegation tree (roots have depth 0)."""
|
|
138
|
+
deleg: dict[str, set[str]] = defaultdict(set)
|
|
139
|
+
parents: dict[str, set[str]] = defaultdict(set)
|
|
140
|
+
for e in self._edges:
|
|
141
|
+
if e.kind in (CoordinationKind.DELEGATION, CoordinationKind.HANDOFF):
|
|
142
|
+
deleg[e.source].add(e.target)
|
|
143
|
+
parents[e.target].add(e.source)
|
|
144
|
+
depth: dict[str, int] = {}
|
|
145
|
+
roots = [a for a in self._agents if not parents.get(a)]
|
|
146
|
+
frontier = [(r, 0) for r in roots]
|
|
147
|
+
while frontier:
|
|
148
|
+
node, d = frontier.pop(0)
|
|
149
|
+
if node in depth and depth[node] <= d:
|
|
150
|
+
continue
|
|
151
|
+
depth[node] = d
|
|
152
|
+
for child in deleg.get(node, ()):
|
|
153
|
+
if depth.get(child, 10**9) > d + 1:
|
|
154
|
+
frontier.append((child, d + 1))
|
|
155
|
+
return depth
|
|
156
|
+
|
|
157
|
+
def timeline(self) -> list[tuple[float, str, str, str, str]]:
|
|
158
|
+
return [
|
|
159
|
+
(e.t, e.source, e.target, e.kind.value, e.message)
|
|
160
|
+
for e in sorted(self._edges, key=lambda e: e.seq)
|
|
161
|
+
]
|
|
162
|
+
|
|
163
|
+
# -- export -------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
def to_dict(self) -> dict[str, Any]:
|
|
166
|
+
return {
|
|
167
|
+
"agents": self.agents,
|
|
168
|
+
"edges": [
|
|
169
|
+
{
|
|
170
|
+
"source": s.source,
|
|
171
|
+
"target": s.target,
|
|
172
|
+
"count": s.count,
|
|
173
|
+
"kinds": list(s.kinds),
|
|
174
|
+
"mean_confidence": s.mean_confidence,
|
|
175
|
+
}
|
|
176
|
+
for s in self.edge_summaries()
|
|
177
|
+
],
|
|
178
|
+
"bottlenecks": self.bottlenecks(),
|
|
179
|
+
"cycles": self.cycles(),
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
def to_json(self, indent: int | None = 2) -> str:
|
|
183
|
+
return json.dumps(self.to_dict(), indent=indent)
|
|
184
|
+
|
|
185
|
+
def to_dot(self, name: str = "coordination") -> str:
|
|
186
|
+
lines = [f"digraph {json.dumps(name)} {{", " rankdir=LR;", " node [shape=box, style=rounded];"]
|
|
187
|
+
for a in self._agents:
|
|
188
|
+
lines.append(f" {json.dumps(a)};")
|
|
189
|
+
for s in self.edge_summaries():
|
|
190
|
+
label = f"{'/'.join(s.kinds)} x{s.count}"
|
|
191
|
+
if s.mean_confidence is not None:
|
|
192
|
+
label += f" c={s.mean_confidence:.2f}"
|
|
193
|
+
lines.append(f" {json.dumps(s.source)} -> {json.dumps(s.target)} [label={json.dumps(label)}];")
|
|
194
|
+
lines.append("}")
|
|
195
|
+
return "\n".join(lines)
|
|
196
|
+
|
|
197
|
+
def to_mermaid(self) -> str:
|
|
198
|
+
ids = {a: f"a{i}" for i, a in enumerate(self._agents)}
|
|
199
|
+
lines = ["flowchart LR"]
|
|
200
|
+
for a, i in ids.items():
|
|
201
|
+
lines.append(f' {i}["{a}"]')
|
|
202
|
+
for s in self.edge_summaries():
|
|
203
|
+
label = f"{'/'.join(s.kinds)} x{s.count}"
|
|
204
|
+
lines.append(f" {ids[s.source]} -->|{label}| {ids[s.target]}")
|
|
205
|
+
return "\n".join(lines)
|
|
206
|
+
|
|
207
|
+
def __len__(self) -> int:
|
|
208
|
+
return len(self._edges)
|
|
209
|
+
|
|
210
|
+
def __repr__(self) -> str: # pragma: no cover - trivial
|
|
211
|
+
return f"CoordinationGraph(agents={len(self._agents)}, edges={len(self._edges)})"
|