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 ADDED
@@ -0,0 +1,204 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """MA-Trace (pip install multi-agent-observability): causal tracing, coordination SLOs and
3
+ deterministic replay for multi-agent LLM systems.
4
+
5
+ Quick start::
6
+
7
+ import ma_trace as mt
8
+
9
+ mt.configure(exporter="console") # optional: OpenTelemetry export
10
+
11
+ with mt.episode("checkout", seed=42):
12
+ @mt.agent("planner")
13
+ def plan(goal): ...
14
+
15
+ mt.coordination("planner", "executor", "do step 1", kind="delegation", confidence=0.9)
16
+ mt.memory("executor", "read", "episodic", "step:1", hit=True, confidence=0.8)
17
+ with mt.contract("executor", "apply", pre_state=state) as c:
18
+ state = step(state); c.set_post_state(state)
19
+
20
+ report = mt.replay("latest", entrypoint="my_app:run")
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from ._version import __version__
26
+ from .context import current_agent, current_episode
27
+ from .contracts import Contract, ContractCheck, state_fingerprint
28
+ from .episode import Episode
29
+ from .events import (
30
+ ActionEvent,
31
+ AgentEvent,
32
+ CallEvent,
33
+ CallType,
34
+ ContractEvent,
35
+ CoordinationEvent,
36
+ CoordinationKind,
37
+ Event,
38
+ EvictionReason,
39
+ LogEvent,
40
+ MemoryEvent,
41
+ MemoryOp,
42
+ MemoryType,
43
+ StateEvent,
44
+ fingerprint,
45
+ )
46
+ from .graph import CoordinationGraph
47
+ from .memory import MemoryTrace, TracedMemory
48
+ from .metrics import (
49
+ OTelMetricsExporter,
50
+ PrometheusExporter,
51
+ SLOMetrics,
52
+ SLOThresholds,
53
+ SLOViolation,
54
+ compute_metrics,
55
+ evaluate,
56
+ )
57
+ from .replay import Divergence, ReplayDivergenceError, ReplayError, ReplayReport, run_replay
58
+ from .sampling import AdaptiveSampler
59
+ from .semconv import SemConv
60
+ from .store import EpisodeStore, EpisodeSummary, InMemoryEpisodeStore
61
+ from .tracer import CallHandle, MATrace, configure, get_tracer, set_tracer
62
+
63
+ __all__ = [
64
+ "ActionEvent",
65
+ "AdaptiveSampler",
66
+ "AgentEvent",
67
+ "CallEvent",
68
+ "CallHandle",
69
+ "CallType",
70
+ "Contract",
71
+ "ContractCheck",
72
+ "ContractEvent",
73
+ "CoordinationEvent",
74
+ "CoordinationGraph",
75
+ "CoordinationKind",
76
+ "Divergence",
77
+ "Episode",
78
+ "EpisodeStore",
79
+ "EpisodeSummary",
80
+ "Event",
81
+ "EvictionReason",
82
+ "InMemoryEpisodeStore",
83
+ "LogEvent",
84
+ "MATrace",
85
+ "MemoryEvent",
86
+ "MemoryOp",
87
+ "MemoryTrace",
88
+ "MemoryType",
89
+ "OTelMetricsExporter",
90
+ "PrometheusExporter",
91
+ "ReplayDivergenceError",
92
+ "ReplayError",
93
+ "ReplayReport",
94
+ "SLOMetrics",
95
+ "SLOThresholds",
96
+ "SLOViolation",
97
+ "SemConv",
98
+ "StateEvent",
99
+ "TracedMemory",
100
+ "__version__",
101
+ "action",
102
+ "agent",
103
+ "agent_span",
104
+ "compute_metrics",
105
+ "configure",
106
+ "contract",
107
+ "coordination",
108
+ "current_agent",
109
+ "current_episode",
110
+ "episode",
111
+ "evaluate",
112
+ "fingerprint",
113
+ "flag_anomaly",
114
+ "get_tracer",
115
+ "llm",
116
+ "llm_call",
117
+ "log",
118
+ "memory",
119
+ "replay",
120
+ "run_replay",
121
+ "set_tracer",
122
+ "state",
123
+ "state_fingerprint",
124
+ "tool",
125
+ "tool_call",
126
+ ]
127
+
128
+
129
+ # --- module-level convenience functions delegating to the default tracer -------
130
+
131
+
132
+ def episode(name, **kwargs): # type: ignore[no-untyped-def]
133
+ """See :meth:`MATrace.episode`."""
134
+ return get_tracer().episode(name, **kwargs)
135
+
136
+
137
+ def agent(name, **kwargs): # type: ignore[no-untyped-def]
138
+ """See :meth:`MATrace.agent`."""
139
+ return get_tracer().agent(name, **kwargs)
140
+
141
+
142
+ def agent_span(name, **kwargs): # type: ignore[no-untyped-def]
143
+ """See :meth:`MATrace.agent_span`."""
144
+ return get_tracer().agent_span(name, **kwargs)
145
+
146
+
147
+ def llm(agent=None, **kwargs): # type: ignore[no-untyped-def]
148
+ """See :meth:`MATrace.llm`."""
149
+ return get_tracer().llm(agent, **kwargs)
150
+
151
+
152
+ def tool(name=None, agent=None, **kwargs): # type: ignore[no-untyped-def]
153
+ """See :meth:`MATrace.tool`."""
154
+ return get_tracer().tool(name, agent, **kwargs)
155
+
156
+
157
+ def llm_call(agent=None, **kwargs): # type: ignore[no-untyped-def]
158
+ """See :meth:`MATrace.llm_call`."""
159
+ return get_tracer().llm_call(agent, **kwargs)
160
+
161
+
162
+ def tool_call(name, agent=None, **kwargs): # type: ignore[no-untyped-def]
163
+ """See :meth:`MATrace.tool_call`."""
164
+ return get_tracer().tool_call(name, agent, **kwargs)
165
+
166
+
167
+ def coordination(source, target, message="", **kwargs): # type: ignore[no-untyped-def]
168
+ """See :meth:`MATrace.coordination`."""
169
+ return get_tracer().coordination(source, target, message, **kwargs)
170
+
171
+
172
+ def memory(agent, op, memory_type, key, **kwargs): # type: ignore[no-untyped-def]
173
+ """See :meth:`MATrace.memory`."""
174
+ return get_tracer().memory(agent, op, memory_type, key, **kwargs)
175
+
176
+
177
+ def contract(agent, action, pre_state, **kwargs): # type: ignore[no-untyped-def]
178
+ """See :meth:`MATrace.contract`."""
179
+ return get_tracer().contract(agent, action, pre_state, **kwargs)
180
+
181
+
182
+ def action(agent, name, args=None, **kwargs): # type: ignore[no-untyped-def]
183
+ """See :meth:`MATrace.action`."""
184
+ return get_tracer().action(agent, name, args, **kwargs)
185
+
186
+
187
+ def state(agent, state_value, label=None): # type: ignore[no-untyped-def]
188
+ """See :meth:`MATrace.state`."""
189
+ return get_tracer().state(agent, state_value, label)
190
+
191
+
192
+ def log(message, **kwargs): # type: ignore[no-untyped-def]
193
+ """See :meth:`MATrace.log`."""
194
+ return get_tracer().log(message, **kwargs)
195
+
196
+
197
+ def flag_anomaly(reason=None): # type: ignore[no-untyped-def]
198
+ """See :meth:`MATrace.flag_anomaly`."""
199
+ return get_tracer().flag_anomaly(reason)
200
+
201
+
202
+ def replay(episode_ref, entrypoint=None, **kwargs): # type: ignore[no-untyped-def]
203
+ """See :meth:`MATrace.replay`."""
204
+ return get_tracer().replay(episode_ref, entrypoint, **kwargs)
ma_trace/_version.py ADDED
@@ -0,0 +1,2 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ __version__ = "0.1.0"
@@ -0,0 +1,9 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Framework adapters. Each module imports its framework lazily so that ``ma_trace``
3
+ itself has no framework dependency:
4
+
5
+ * :mod:`ma_trace.adapters.langchain` - ``MATraceCallbackHandler`` for LangChain and LangGraph
6
+ * :mod:`ma_trace.adapters.langgraph` - ``trace_config`` / ``traced_node`` helpers for LangGraph
7
+ * :mod:`ma_trace.adapters.crewai` - ``create_listener`` for the CrewAI event bus
8
+ * :mod:`ma_trace.adapters.autogen` - message tracing for AutoGen AgentChat (and AG2 hooks)
9
+ """
@@ -0,0 +1,159 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """AutoGen adapter.
3
+
4
+ AutoGen AgentChat (``autogen_agentchat`` 0.4+) exposes a run as a stream of typed
5
+ messages. :class:`AutoGenMessageTracer` turns them into ma-trace records:
6
+
7
+ * speaker changes -> coordination edges (``response``; ``handoff`` for HandoffMessage)
8
+ * ``ToolCallRequestEvent`` / ``ToolCallExecutionEvent`` -> actions and recorded tool calls
9
+ * ``MemoryQueryEvent`` -> semantic-memory reads
10
+ * ``ThoughtEvent`` -> log events
11
+
12
+ Use :func:`trace_task_result` after ``team.run(...)`` or wrap ``team.run_stream(...)`` with
13
+ :func:`traced_run_stream`. For the older AG2 / pyautogen ``ConversableAgent`` API use
14
+ :func:`register_ag2_hooks`. Everything is duck-typed, so no AutoGen import is required.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections.abc import AsyncIterator, Iterable
20
+ from typing import Any
21
+
22
+ from ..episode import Episode
23
+ from ..events import CoordinationKind, MemoryOp, MemoryType
24
+ from ..tracer import MATrace, get_tracer
25
+
26
+ TEXT_MESSAGES = {
27
+ "TextMessage",
28
+ "MultiModalMessage",
29
+ "StopMessage",
30
+ "ToolCallSummaryMessage",
31
+ "StructuredMessage",
32
+ }
33
+
34
+
35
+ class AutoGenMessageTracer:
36
+ def __init__(
37
+ self,
38
+ tracer: MATrace | None = None,
39
+ *,
40
+ team_name: str = "team",
41
+ user_name: str = "user",
42
+ record_outputs: bool = True,
43
+ ) -> None:
44
+ self._tracer = tracer
45
+ self.team_name = team_name
46
+ self.user_name = user_name
47
+ self.record_outputs = record_outputs
48
+ self._last_source: str | None = None
49
+ self._pending: dict[str, tuple[str, Any, str]] = {}
50
+ self.processed = 0
51
+
52
+ @property
53
+ def tracer(self) -> MATrace:
54
+ return self._tracer or get_tracer()
55
+
56
+ def process_all(self, messages: Iterable[Any]) -> int:
57
+ for m in messages:
58
+ self.process(m)
59
+ return self.processed
60
+
61
+ def process(self, message: Any) -> None:
62
+ cls = type(message).__name__
63
+ source = str(getattr(message, "source", None) or "unknown")
64
+ t = self.tracer
65
+ self.processed += 1
66
+ if cls in TEXT_MESSAGES:
67
+ content = getattr(message, "content", "")
68
+ if self._last_source and self._last_source != source:
69
+ t.coordination(self._last_source, source, content, kind=CoordinationKind.RESPONSE)
70
+ self._last_source = source
71
+ elif cls == "HandoffMessage":
72
+ target = str(getattr(message, "target", "unknown"))
73
+ t.coordination(source, target, getattr(message, "content", ""), kind=CoordinationKind.HANDOFF)
74
+ self._last_source = target
75
+ elif cls == "ToolCallRequestEvent":
76
+ for fc in getattr(message, "content", None) or []:
77
+ name = str(getattr(fc, "name", "tool"))
78
+ args = getattr(fc, "arguments", None)
79
+ call_id = str(getattr(fc, "id", ""))
80
+ self._pending[call_id] = (name, args, source)
81
+ t.action(source, name, args)
82
+ elif cls == "ToolCallExecutionEvent":
83
+ for res in getattr(message, "content", None) or []:
84
+ call_id = str(getattr(res, "call_id", ""))
85
+ name, args, agent = self._pending.pop(
86
+ call_id, (str(getattr(res, "name", None) or "tool"), None, source)
87
+ )
88
+ with t.call(
89
+ "tool",
90
+ name,
91
+ agent=agent,
92
+ inputs=args,
93
+ call_id=call_id or None,
94
+ record_output=self.record_outputs,
95
+ ) as h:
96
+ h.set_output(getattr(res, "content", None))
97
+ if getattr(res, "is_error", False):
98
+ h.event.error = "tool reported is_error=True"
99
+ elif cls == "MemoryQueryEvent":
100
+ results = getattr(message, "content", None) or []
101
+ t.memory(
102
+ source,
103
+ MemoryOp.READ,
104
+ MemoryType.SEMANTIC,
105
+ "memory_query",
106
+ hit=len(results) > 0,
107
+ results=len(results),
108
+ )
109
+ elif cls == "ThoughtEvent":
110
+ t.log(str(getattr(message, "content", "")), level="debug", agent=source)
111
+ elif cls == "UserInputRequestedEvent":
112
+ t.coordination(source, self.user_name, "input requested", kind=CoordinationKind.NEGOTIATION)
113
+ elif cls == "SelectSpeakerEvent":
114
+ for name in getattr(message, "content", None) or []:
115
+ t.coordination(self.team_name, str(name), "select speaker", kind=CoordinationKind.DELEGATION)
116
+ # streaming chunks and unknown events are ignored
117
+
118
+
119
+ def trace_task_result(
120
+ result: Any,
121
+ tracer: MATrace | None = None,
122
+ *,
123
+ episode_name: str = "autogen-task",
124
+ team_name: str = "team",
125
+ **episode_kwargs: Any,
126
+ ) -> Episode:
127
+ """Record the messages of a finished ``TaskResult`` as one episode and return it."""
128
+ t = tracer or get_tracer()
129
+ with t.episode(episode_name, **episode_kwargs) as ep:
130
+ AutoGenMessageTracer(t, team_name=team_name).process_all(getattr(result, "messages", result))
131
+ return ep
132
+
133
+
134
+ async def traced_run_stream(
135
+ stream: AsyncIterator[Any], tracer: MATrace | None = None, **kwargs: Any
136
+ ) -> AsyncIterator[Any]:
137
+ """Wrap ``team.run_stream(...)``; every yielded message is recorded as it arrives."""
138
+ proc = AutoGenMessageTracer(tracer, **kwargs)
139
+ async for item in stream:
140
+ if type(item).__name__ != "TaskResult":
141
+ proc.process(item)
142
+ yield item
143
+
144
+
145
+ def register_ag2_hooks(agent: Any, tracer: MATrace | None = None) -> None:
146
+ """Register a ``process_message_before_send`` hook on an AG2 / pyautogen ``ConversableAgent``."""
147
+ t = tracer or get_tracer()
148
+
149
+ def _hook(sender: Any, message: Any, recipient: Any, silent: bool) -> Any:
150
+ content = message.get("content", "") if isinstance(message, dict) else message
151
+ t.coordination(
152
+ str(getattr(sender, "name", sender)),
153
+ str(getattr(recipient, "name", recipient)),
154
+ content,
155
+ kind=CoordinationKind.MESSAGE,
156
+ )
157
+ return message
158
+
159
+ agent.register_hook("process_message_before_send", _hook)