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.

@@ -0,0 +1,395 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """LangChain / LangGraph callback handler.
3
+
4
+ Attach :class:`MATraceCallbackHandler` through ``config={"callbacks": [handler]}`` (or use
5
+ :func:`ma_trace.adapters.langgraph.trace_config`). Runs are mapped as follows:
6
+
7
+ * chain runs whose metadata carries ``langgraph_node`` (LangGraph nodes), ``agent_name``
8
+ or ``ma_trace_agent``, or whose name is listed in ``agent_chains`` -> agent spans;
9
+ * consecutive agent runs -> ``handoff`` coordination edges (``infer_handoffs``);
10
+ * LLM / chat-model runs -> recorded LLM calls (model taken from LangSmith metadata);
11
+ * tool runs -> recorded tool calls;
12
+ * retriever runs -> semantic-memory reads (hit when at least one document came back).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from contextlib import ExitStack
18
+ from typing import Any
19
+ from uuid import UUID
20
+
21
+ try:
22
+ from langchain_core.callbacks import BaseCallbackHandler
23
+ except ImportError as e: # pragma: no cover - exercised only without the extra
24
+ raise ImportError(
25
+ "the LangChain adapter needs langchain-core: pip install 'multi-agent-observability[langgraph]'"
26
+ ) from e
27
+
28
+ from ..context import current_agent
29
+ from ..events import CoordinationKind, MemoryOp, MemoryType, truncate
30
+ from ..tracer import CallHandle, MATrace, get_tracer
31
+
32
+ AGENT_METADATA_KEYS: tuple[str, ...] = ("ma_trace_agent", "langgraph_node", "agent_name")
33
+
34
+
35
+ class _Run:
36
+ __slots__ = ("agent", "handle", "is_agent", "kind", "name", "parent", "stack")
37
+
38
+ def __init__(self, kind: str, name: str, agent: str | None, parent: UUID | None) -> None:
39
+ self.kind = kind
40
+ self.name = name
41
+ self.agent = agent
42
+ self.parent = parent
43
+ self.stack: ExitStack | None = None
44
+ self.handle: CallHandle | None = None
45
+ self.is_agent = False
46
+
47
+
48
+ def _serialized_name(serialized: Any) -> str | None:
49
+ if not isinstance(serialized, dict):
50
+ return None
51
+ name = serialized.get("name")
52
+ if name:
53
+ return str(name)
54
+ ident = serialized.get("id")
55
+ if isinstance(ident, list) and ident:
56
+ return str(ident[-1])
57
+ return None
58
+
59
+
60
+ def _serialized_kwargs(serialized: Any) -> dict[str, Any]:
61
+ if isinstance(serialized, dict) and isinstance(serialized.get("kwargs"), dict):
62
+ return serialized["kwargs"]
63
+ return {}
64
+
65
+
66
+ def _llm_inputs(payload: Any) -> Any:
67
+ if isinstance(payload, list):
68
+ out: list[Any] = []
69
+ for item in payload:
70
+ if isinstance(item, list):
71
+ out.append([_message_dict(m) for m in item])
72
+ else:
73
+ out.append(_message_dict(item))
74
+ return out
75
+ return payload
76
+
77
+
78
+ def _message_dict(m: Any) -> Any:
79
+ if isinstance(m, str):
80
+ return m
81
+ return {"type": getattr(m, "type", type(m).__name__), "content": getattr(m, "content", str(m))}
82
+
83
+
84
+ def _llm_output(response: Any) -> Any:
85
+ try:
86
+ gen = response.generations[0][0]
87
+ except (AttributeError, IndexError, TypeError):
88
+ return str(response)
89
+ message = getattr(gen, "message", None)
90
+ if message is not None and getattr(message, "content", None) is not None:
91
+ return message.content
92
+ return getattr(gen, "text", str(gen))
93
+
94
+
95
+ def _tool_output(output: Any) -> Any:
96
+ if isinstance(output, (str, int, float, bool, list, dict)) or output is None:
97
+ return output
98
+ content = getattr(output, "content", None)
99
+ return content if content is not None else str(output)
100
+
101
+
102
+ class MATraceCallbackHandler(BaseCallbackHandler):
103
+ """Records LangChain / LangGraph callbacks into the current ma-trace episode."""
104
+
105
+ raise_error = False
106
+ run_inline = True
107
+
108
+ def __init__(
109
+ self,
110
+ tracer: MATrace | None = None,
111
+ *,
112
+ infer_handoffs: bool = True,
113
+ agent_chains: tuple[str, ...] | list[str] = (),
114
+ record_outputs: bool = True,
115
+ agent_metadata_keys: tuple[str, ...] = AGENT_METADATA_KEYS,
116
+ default_provider: str = "langchain",
117
+ ) -> None:
118
+ super().__init__()
119
+ self._tracer = tracer
120
+ self.infer_handoffs = infer_handoffs
121
+ self.agent_chains = set(agent_chains)
122
+ self.record_outputs = record_outputs
123
+ self.agent_metadata_keys = agent_metadata_keys
124
+ self.default_provider = default_provider
125
+ self._runs: dict[UUID, _Run] = {}
126
+ self._last_agent: str | None = None
127
+
128
+ @property
129
+ def tracer(self) -> MATrace:
130
+ return self._tracer or get_tracer()
131
+
132
+ # -- helpers ------------------------------------------------------------
133
+
134
+ def _agent_for(
135
+ self,
136
+ parent_run_id: UUID | None,
137
+ metadata: dict[str, Any] | None,
138
+ serialized: Any,
139
+ name_hint: str | None,
140
+ ) -> tuple[str | None, bool]:
141
+ agent: str | None = None
142
+ if metadata:
143
+ for key in self.agent_metadata_keys:
144
+ if metadata.get(key):
145
+ agent = str(metadata[key])
146
+ break
147
+ if agent is None:
148
+ sname = _serialized_name(serialized) or name_hint
149
+ if sname and sname in self.agent_chains:
150
+ agent = sname
151
+ if agent is None:
152
+ return None, False
153
+ parent = parent_run_id
154
+ for _ in range(64):
155
+ if parent is None:
156
+ break
157
+ run = self._runs.get(parent)
158
+ if run is None:
159
+ break
160
+ if run.is_agent and run.agent == agent:
161
+ return agent, False
162
+ parent = run.parent
163
+ return agent, True
164
+
165
+ def _enclosing_agent(self, parent_run_id: UUID | None) -> str | None:
166
+ parent = parent_run_id
167
+ for _ in range(64):
168
+ if parent is None:
169
+ break
170
+ run = self._runs.get(parent)
171
+ if run is None:
172
+ break
173
+ if run.agent:
174
+ return run.agent
175
+ parent = run.parent
176
+ return current_agent()
177
+
178
+ def _close(self, run_id: UUID, error: BaseException | None = None) -> None:
179
+ run = self._runs.pop(run_id, None)
180
+ if run is None or run.stack is None:
181
+ return
182
+ try:
183
+ if error is None:
184
+ run.stack.close()
185
+ else:
186
+ run.stack.__exit__(type(error), error, error.__traceback__)
187
+ except BaseException: # the agent/call span re-raises the error; never propagate from a callback
188
+ pass
189
+
190
+ # -- chains / LangGraph nodes ------------------------------------------
191
+
192
+ def on_chain_start(
193
+ self,
194
+ serialized: dict[str, Any],
195
+ inputs: dict[str, Any],
196
+ *,
197
+ run_id: UUID,
198
+ parent_run_id: UUID | None = None,
199
+ tags: list[str] | None = None,
200
+ metadata: dict[str, Any] | None = None,
201
+ **kwargs: Any,
202
+ ) -> Any:
203
+ name_hint = kwargs.get("name")
204
+ agent, open_span = self._agent_for(parent_run_id, metadata, serialized, name_hint)
205
+ run = _Run("chain", _serialized_name(serialized) or name_hint or "chain", agent, parent_run_id)
206
+ if agent and open_span:
207
+ if self.infer_handoffs and self._last_agent and self._last_agent != agent:
208
+ self.tracer.coordination(self._last_agent, agent, "handoff", kind=CoordinationKind.HANDOFF)
209
+ self._last_agent = agent
210
+ run.stack = ExitStack()
211
+ run.stack.enter_context(self.tracer.agent_span(agent))
212
+ run.is_agent = True
213
+ self._runs[run_id] = run
214
+
215
+ def on_chain_end(
216
+ self, outputs: dict[str, Any], *, run_id: UUID, parent_run_id: UUID | None = None, **kwargs: Any
217
+ ) -> Any:
218
+ self._close(run_id)
219
+
220
+ def on_chain_error(
221
+ self, error: BaseException, *, run_id: UUID, parent_run_id: UUID | None = None, **kwargs: Any
222
+ ) -> Any:
223
+ self._close(run_id, error)
224
+
225
+ # -- LLMs ---------------------------------------------------------------
226
+
227
+ def _start_llm(
228
+ self,
229
+ serialized: Any,
230
+ payload: Any,
231
+ run_id: UUID,
232
+ parent_run_id: UUID | None,
233
+ metadata: dict[str, Any] | None,
234
+ kwargs: dict[str, Any],
235
+ ) -> None:
236
+ md = metadata or {}
237
+ params = kwargs.get("invocation_params") or {}
238
+ skw = _serialized_kwargs(serialized)
239
+ model = (
240
+ md.get("ls_model_name")
241
+ or params.get("model")
242
+ or params.get("model_name")
243
+ or skw.get("model")
244
+ or skw.get("model_name")
245
+ )
246
+ provider = md.get("ls_provider") or self.default_provider
247
+ agent = self._enclosing_agent(parent_run_id)
248
+ run = _Run("llm", _serialized_name(serialized) or "llm", agent, parent_run_id)
249
+ run.stack = ExitStack()
250
+ run.handle = run.stack.enter_context(
251
+ self.tracer.call(
252
+ "llm",
253
+ "chat",
254
+ agent=agent,
255
+ provider=provider,
256
+ model=model,
257
+ inputs=_llm_inputs(payload),
258
+ record_output=self.record_outputs,
259
+ )
260
+ )
261
+ self._runs[run_id] = run
262
+
263
+ def on_chat_model_start(
264
+ self,
265
+ serialized: dict[str, Any],
266
+ messages: list[list[Any]],
267
+ *,
268
+ run_id: UUID,
269
+ parent_run_id: UUID | None = None,
270
+ tags: list[str] | None = None,
271
+ metadata: dict[str, Any] | None = None,
272
+ **kwargs: Any,
273
+ ) -> Any:
274
+ self._start_llm(serialized, messages, run_id, parent_run_id, metadata, kwargs)
275
+
276
+ def on_llm_start(
277
+ self,
278
+ serialized: dict[str, Any],
279
+ prompts: list[str],
280
+ *,
281
+ run_id: UUID,
282
+ parent_run_id: UUID | None = None,
283
+ tags: list[str] | None = None,
284
+ metadata: dict[str, Any] | None = None,
285
+ **kwargs: Any,
286
+ ) -> Any:
287
+ self._start_llm(serialized, prompts, run_id, parent_run_id, metadata, kwargs)
288
+
289
+ def on_llm_end(
290
+ self, response: Any, *, run_id: UUID, parent_run_id: UUID | None = None, **kwargs: Any
291
+ ) -> Any:
292
+ run = self._runs.get(run_id)
293
+ if run is not None and run.handle is not None:
294
+ run.handle.set_output(_llm_output(response))
295
+ self._close(run_id)
296
+
297
+ def on_llm_error(
298
+ self, error: BaseException, *, run_id: UUID, parent_run_id: UUID | None = None, **kwargs: Any
299
+ ) -> Any:
300
+ self._close(run_id, error)
301
+
302
+ # -- tools --------------------------------------------------------------
303
+
304
+ def on_tool_start(
305
+ self,
306
+ serialized: dict[str, Any],
307
+ input_str: str,
308
+ *,
309
+ run_id: UUID,
310
+ parent_run_id: UUID | None = None,
311
+ tags: list[str] | None = None,
312
+ metadata: dict[str, Any] | None = None,
313
+ inputs: dict[str, Any] | None = None,
314
+ **kwargs: Any,
315
+ ) -> Any:
316
+ name = _serialized_name(serialized) or kwargs.get("name") or "tool"
317
+ agent = self._enclosing_agent(parent_run_id)
318
+ run = _Run("tool", name, agent, parent_run_id)
319
+ run.stack = ExitStack()
320
+ run.handle = run.stack.enter_context(
321
+ self.tracer.call(
322
+ "tool",
323
+ name,
324
+ agent=agent,
325
+ inputs=inputs if inputs is not None else input_str,
326
+ record_output=self.record_outputs,
327
+ )
328
+ )
329
+ self._runs[run_id] = run
330
+
331
+ def on_tool_end(
332
+ self, output: Any, *, run_id: UUID, parent_run_id: UUID | None = None, **kwargs: Any
333
+ ) -> Any:
334
+ run = self._runs.get(run_id)
335
+ if run is not None and run.handle is not None:
336
+ run.handle.set_output(_tool_output(output))
337
+ self._close(run_id)
338
+
339
+ def on_tool_error(
340
+ self, error: BaseException, *, run_id: UUID, parent_run_id: UUID | None = None, **kwargs: Any
341
+ ) -> Any:
342
+ self._close(run_id, error)
343
+
344
+ # -- retrievers (memory) ------------------------------------------------
345
+
346
+ def on_retriever_start(
347
+ self,
348
+ serialized: dict[str, Any],
349
+ query: str,
350
+ *,
351
+ run_id: UUID,
352
+ parent_run_id: UUID | None = None,
353
+ tags: list[str] | None = None,
354
+ metadata: dict[str, Any] | None = None,
355
+ **kwargs: Any,
356
+ ) -> Any:
357
+ self._runs[run_id] = _Run("retriever", query, self._enclosing_agent(parent_run_id), parent_run_id)
358
+
359
+ def on_retriever_end(
360
+ self, documents: Any, *, run_id: UUID, parent_run_id: UUID | None = None, **kwargs: Any
361
+ ) -> Any:
362
+ run = self._runs.pop(run_id, None)
363
+ if run is None:
364
+ return
365
+ count = len(documents) if documents is not None else 0
366
+ self.tracer.memory(
367
+ run.agent or "unknown",
368
+ MemoryOp.READ,
369
+ MemoryType.SEMANTIC,
370
+ truncate(run.name, 120),
371
+ hit=count > 0,
372
+ documents=count,
373
+ )
374
+
375
+ def on_retriever_error(
376
+ self, error: BaseException, *, run_id: UUID, parent_run_id: UUID | None = None, **kwargs: Any
377
+ ) -> Any:
378
+ run = self._runs.pop(run_id, None)
379
+ if run is not None:
380
+ self.tracer.memory(
381
+ run.agent or "unknown",
382
+ MemoryOp.READ,
383
+ MemoryType.SEMANTIC,
384
+ truncate(run.name, 120),
385
+ hit=False,
386
+ error=str(error),
387
+ )
388
+
389
+ # -- legacy agent executors --------------------------------------------
390
+
391
+ def on_agent_action(
392
+ self, action: Any, *, run_id: UUID, parent_run_id: UUID | None = None, **kwargs: Any
393
+ ) -> Any:
394
+ agent = self._enclosing_agent(parent_run_id) or "agent"
395
+ self.tracer.action(agent, getattr(action, "tool", "tool"), getattr(action, "tool_input", None))
@@ -0,0 +1,100 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """LangGraph helpers.
3
+
4
+ Zero-code path::
5
+
6
+ from ma_trace.adapters.langgraph import trace_config
7
+ with mt.episode("pipeline", seed=1):
8
+ graph.invoke(inputs, config=trace_config())
9
+
10
+ Every node becomes an agent span (via the ``langgraph_node`` run metadata), node-to-node
11
+ transitions become ``handoff`` coordination edges, and LLM/tool calls made inside nodes
12
+ are recorded when the node passes ``config`` on to them.
13
+
14
+ Explicit path: decorate node functions with :func:`traced_node` to open the agent span
15
+ yourself and snapshot the node's output state for oscillation detection.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import functools
21
+ import inspect
22
+ from collections.abc import Callable
23
+ from typing import Any
24
+
25
+ from ..context import current_agent
26
+ from ..contracts import state_fingerprint
27
+ from ..tracer import MATrace, get_tracer
28
+ from .langchain import MATraceCallbackHandler
29
+
30
+ __all__ = ["MATraceCallbackHandler", "state_fingerprint", "trace_config", "traced_node"]
31
+
32
+
33
+ def trace_config(
34
+ tracer: MATrace | None = None, *, config: dict[str, Any] | None = None, **handler_kwargs: Any
35
+ ) -> dict[str, Any]:
36
+ """Return a ``RunnableConfig`` (dict) carrying an :class:`MATraceCallbackHandler`.
37
+
38
+ Existing ``config`` entries are preserved; the handler is appended to its callbacks.
39
+ """
40
+ handler = MATraceCallbackHandler(tracer, **handler_kwargs)
41
+ cfg: dict[str, Any] = dict(config or {})
42
+ existing = cfg.get("callbacks")
43
+ if existing is None:
44
+ callbacks: list[Any] = []
45
+ elif isinstance(existing, list):
46
+ callbacks = list(existing)
47
+ else: # a CallbackManager instance
48
+ callbacks = list(getattr(existing, "handlers", []))
49
+ callbacks.append(handler)
50
+ cfg["callbacks"] = callbacks
51
+ return cfg
52
+
53
+
54
+ def traced_node(
55
+ name: str | None = None, *, tracer: MATrace | None = None, snapshot: bool = True
56
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
57
+ """Decorator for LangGraph node functions.
58
+
59
+ Opens an agent span named after the node (unless the callback handler already did)
60
+ and, when ``snapshot`` is true, records the node's returned state update as a
61
+ :class:`~ma_trace.events.StateEvent` so that oscillation between states is measurable.
62
+ """
63
+
64
+ def decorate(fn: Callable[..., Any]) -> Callable[..., Any]:
65
+ node_name: str = name or str(getattr(fn, "__name__", "node"))
66
+
67
+ def _t() -> MATrace:
68
+ return tracer or get_tracer()
69
+
70
+ if inspect.iscoroutinefunction(fn):
71
+
72
+ @functools.wraps(fn)
73
+ async def async_wrapper(state: Any, *args: Any, **kwargs: Any) -> Any:
74
+ t = _t()
75
+ if current_agent() == node_name:
76
+ out = await fn(state, *args, **kwargs)
77
+ else:
78
+ with t.agent_span(node_name):
79
+ out = await fn(state, *args, **kwargs)
80
+ if snapshot:
81
+ t.state(node_name, out, label="node_output")
82
+ return out
83
+
84
+ return async_wrapper
85
+
86
+ @functools.wraps(fn)
87
+ def wrapper(state: Any, *args: Any, **kwargs: Any) -> Any:
88
+ t = _t()
89
+ if current_agent() == node_name:
90
+ out = fn(state, *args, **kwargs)
91
+ else:
92
+ with t.agent_span(node_name):
93
+ out = fn(state, *args, **kwargs)
94
+ if snapshot:
95
+ t.state(node_name, out, label="node_output")
96
+ return out
97
+
98
+ return wrapper
99
+
100
+ return decorate