agentflight-sdk 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.
Files changed (49) hide show
  1. agentflight/__init__.py +59 -0
  2. agentflight/_queue.py +234 -0
  3. agentflight/_spool.py +280 -0
  4. agentflight/attributes.py +68 -0
  5. agentflight/exporter.py +272 -0
  6. agentflight/integrations/__init__.py +5 -0
  7. agentflight/integrations/langgraph.py +369 -0
  8. agentflight/integrations/openai.py +172 -0
  9. agentflight/py.typed +0 -0
  10. agentflight/replayer.py +436 -0
  11. agentflight/sdk.py +803 -0
  12. agentflight/server/__init__.py +5 -0
  13. agentflight/server/app.py +176 -0
  14. agentflight/server/auth.py +87 -0
  15. agentflight/server/cli.py +95 -0
  16. agentflight/server/db.py +41 -0
  17. agentflight/server/limits.py +115 -0
  18. agentflight/server/main.py +5 -0
  19. agentflight/server/migrations/env.py +38 -0
  20. agentflight/server/migrations/script.py.mako +22 -0
  21. agentflight/server/migrations/versions/0001_initial.py +58 -0
  22. agentflight/server/migrations/versions/0002_event_columns_run_totals.py +168 -0
  23. agentflight/server/migrations/versions/0003_unset_status_unknown.py +47 -0
  24. agentflight/server/migrations/versions/0004_run_dropped_spans.py +29 -0
  25. agentflight/server/models.py +81 -0
  26. agentflight/server/schemas.py +91 -0
  27. agentflight/server/service.py +483 -0
  28. agentflight/server/settings.py +198 -0
  29. agentflight/server/viewer/__init__.py +11 -0
  30. agentflight/server/viewer/format.py +180 -0
  31. agentflight/server/viewer/routes.py +293 -0
  32. agentflight/server/viewer/session.py +120 -0
  33. agentflight/server/viewer/static/VENDORED.md +32 -0
  34. agentflight/server/viewer/static/htmx-2.0.11.min.js +1 -0
  35. agentflight/server/viewer/static/viewer.css +104 -0
  36. agentflight/server/viewer/templates/_event.html +36 -0
  37. agentflight/server/viewer/templates/_runs_table.html +35 -0
  38. agentflight/server/viewer/templates/_timeline_rows.html +25 -0
  39. agentflight/server/viewer/templates/base.html +26 -0
  40. agentflight/server/viewer/templates/event.html +6 -0
  41. agentflight/server/viewer/templates/login.html +14 -0
  42. agentflight/server/viewer/templates/not_found.html +6 -0
  43. agentflight/server/viewer/templates/run.html +45 -0
  44. agentflight/server/viewer/templates/runs.html +31 -0
  45. agentflight_sdk-0.1.0.dist-info/METADATA +836 -0
  46. agentflight_sdk-0.1.0.dist-info/RECORD +49 -0
  47. agentflight_sdk-0.1.0.dist-info/WHEEL +4 -0
  48. agentflight_sdk-0.1.0.dist-info/entry_points.txt +2 -0
  49. agentflight_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,272 @@
1
+ """OpenTelemetry span exporter that ships spans to an AgentFlight server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from collections.abc import Sequence
8
+ from contextlib import closing
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+
12
+ import httpx
13
+ from opentelemetry.sdk.trace import ReadableSpan
14
+ from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
15
+ from opentelemetry.trace import StatusCode
16
+
17
+ from agentflight._spool import Spool
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ INGEST_PATH = "/v1/spans"
22
+
23
+
24
+ def _hex(value: int, width: int) -> str:
25
+ return format(value, f"0{width}x")
26
+
27
+
28
+ def span_to_dict(span: ReadableSpan) -> dict[str, Any]:
29
+ """Convert a finished span into the JSON shape the ingest API accepts."""
30
+ ctx = span.get_span_context()
31
+ if ctx is None: # pragma: no cover - finished spans always have a context
32
+ raise ValueError("span has no context")
33
+ parent = span.parent
34
+ status = span.status.status_code
35
+ return {
36
+ "trace_id": _hex(ctx.trace_id, 32),
37
+ "span_id": _hex(ctx.span_id, 16),
38
+ "parent_span_id": _hex(parent.span_id, 16) if parent is not None else None,
39
+ "name": span.name,
40
+ "start_time_ns": span.start_time,
41
+ "end_time_ns": span.end_time,
42
+ "status": {StatusCode.ERROR: "error", StatusCode.OK: "ok"}.get(status, "unset"),
43
+ "status_message": span.status.description,
44
+ "attributes": dict(span.attributes or {}),
45
+ "events": [
46
+ {
47
+ "name": event.name,
48
+ "time_ns": event.timestamp,
49
+ "attributes": dict(event.attributes or {}),
50
+ }
51
+ for event in span.events
52
+ ],
53
+ }
54
+
55
+
56
+ DEFAULT_MAX_ATTEMPTS = 32
57
+ """HTTP requests one ``export()`` may make while splitting batches the server rejects
58
+ with 413. Isolating one oversized span in a 512-span batch takes 19."""
59
+
60
+ _RETRYABLE = frozenset({408, 425, 429})
61
+ """Besides 5xx: statuses that may succeed later, so their spans are spooled."""
62
+
63
+
64
+ @dataclass
65
+ class _ExportState:
66
+ """Shared by the requests of one ``export()`` call, spool replay included."""
67
+
68
+ remaining: int
69
+ deadline: float | None = None # time.monotonic() value; None: no overall deadline
70
+ aborted: str | None = None
71
+
72
+ def abort(self, reason: str) -> str:
73
+ self.aborted = reason
74
+ return reason
75
+
76
+
77
+ @dataclass
78
+ class _Outcome:
79
+ """What happened to one batch: spans worth retrying later, and spans lost for good."""
80
+
81
+ retry: list[dict[str, Any]] = field(default_factory=list)
82
+ lost: int = 0
83
+ why: str | None = None # the first failure; "" when already logged (credentials)
84
+
85
+ def fail(self, why: str) -> None:
86
+ if self.why is None:
87
+ self.why = why
88
+
89
+
90
+ Payload = dict[str, Any]
91
+
92
+
93
+ class AgentFlightExporter(SpanExporter):
94
+ """POSTs batches of spans as JSON to ``{endpoint}/v1/spans``.
95
+
96
+ ``api_key`` is sent as ``Authorization: Bearer <key>``. Auth failures are logged once
97
+ (without the key) and never raised.
98
+
99
+ If the server answers ``413`` (batch over its body cap), the batch is split in half
100
+ and each half retried, so only spans that are too big on their own are dropped. One
101
+ ``export()`` makes at most ``max_attempts`` requests, and stops at the first failure
102
+ that isn't a 413. Each export that drops spans logs one warning.
103
+
104
+ With a ``spool``, spans that weren't stored because of a failure that may clear up
105
+ (transport error, timeout, 5xx, 408/425/429, credentials, attempt cap, deadline) are
106
+ written to disk instead of dropped, and every later ``export()`` first sends what is
107
+ spooled, oldest first, within the same attempt cap. Spans the server rejects for good
108
+ (a single span over the body cap, other 4xx) are not spooled.
109
+
110
+ An ``httpx.Client`` can be injected (useful for tests or custom auth/TLS).
111
+ """
112
+
113
+ def __init__(
114
+ self,
115
+ endpoint: str = "http://localhost:8000",
116
+ *,
117
+ client: httpx.Client | None = None,
118
+ timeout: float = 5.0,
119
+ headers: dict[str, str] | None = None,
120
+ api_key: str | None = None,
121
+ max_attempts: int = DEFAULT_MAX_ATTEMPTS,
122
+ spool: Spool | None = None,
123
+ ) -> None:
124
+ if max_attempts < 1:
125
+ raise ValueError("max_attempts must be at least 1")
126
+ self._url = endpoint.rstrip("/") + INGEST_PATH
127
+ self._auth_warned = False
128
+ self._max_attempts = max_attempts
129
+ self._timeout = timeout
130
+ self.spool = spool
131
+ self._owns_client = client is None
132
+ self._client = client or httpx.Client(timeout=timeout)
133
+ self._headers = dict(headers or {})
134
+ if api_key:
135
+ self._headers["Authorization"] = f"Bearer {api_key}"
136
+
137
+ def __repr__(self) -> str:
138
+ return f"AgentFlightExporter(url={self._url!r})"
139
+
140
+ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
141
+ return self._export(spans, deadline_s=None, replay=True)
142
+
143
+ def export_within(self, spans: Sequence[ReadableSpan], deadline_s: float) -> SpanExportResult:
144
+ """Like ``export``, but give up after ``deadline_s`` seconds in total.
145
+
146
+ Each request's timeouts are capped to what is left of the deadline, and no request
147
+ starts after it has passed. Used for run spans, which skip the batch queue. It
148
+ sends ``spans`` before anything spooled, and replays the spool only once they are
149
+ stored, within the same deadline.
150
+ """
151
+ return self._export(spans, deadline_s=deadline_s, replay=False)
152
+
153
+ def _export(
154
+ self, spans: Sequence[ReadableSpan], *, deadline_s: float | None, replay: bool
155
+ ) -> SpanExportResult:
156
+ # Never raise: OTel processors log exporter exceptions, but a custom processor might
157
+ # not, and export failures must never reach agent code.
158
+ try:
159
+ deadline = None if deadline_s is None else time.monotonic() + deadline_s
160
+ state = _ExportState(remaining=self._max_attempts, deadline=deadline)
161
+ if replay and self.spool is not None:
162
+ self._replay(self.spool, state)
163
+ items = [span_to_dict(s) for s in spans]
164
+ outcome = _Outcome()
165
+ self._send(items, state, outcome)
166
+ if not replay and outcome.why is None and self.spool is not None:
167
+ self._replay(self.spool, state)
168
+ except Exception as exc:
169
+ logger.warning("agentflight: failed to export %d spans: %r", len(spans), exc)
170
+ return SpanExportResult.FAILURE
171
+ if outcome.why is None:
172
+ return SpanExportResult.SUCCESS
173
+ spooled = 0
174
+ if outcome.retry:
175
+ if self.spool is not None and self.spool.put(outcome.retry):
176
+ spooled = len(outcome.retry)
177
+ else:
178
+ outcome.lost += len(outcome.retry)
179
+ if outcome.why: # "": already reported (credentials)
180
+ logger.warning(
181
+ "agentflight: failed to export %d of %d spans: %s%s",
182
+ outcome.lost + spooled,
183
+ len(spans),
184
+ outcome.why,
185
+ f" ({spooled} spooled to retry later)" if spooled else "",
186
+ )
187
+ return SpanExportResult.FAILURE
188
+
189
+ def _replay(self, spool: Spool, state: _ExportState) -> None:
190
+ """Send spooled batches, oldest first, until one fails or the budget runs out."""
191
+ with closing(spool.replay()) as batches:
192
+ for f, items in batches:
193
+ if state.aborted is not None or state.remaining <= 0:
194
+ break
195
+ outcome = _Outcome()
196
+ self._send(items, state, outcome)
197
+ spool.settle(f, len(items), outcome.retry)
198
+ if outcome.lost:
199
+ logger.warning(
200
+ "agentflight: dropped %d spooled spans: %s", outcome.lost, outcome.why
201
+ )
202
+
203
+ def _send(self, items: list[Payload], state: _ExportState, out: _Outcome) -> None:
204
+ """POST ``items``, splitting on 413; record what happened in ``out``.
205
+
206
+ The first failure other than 413 (timeout, transport error, 5xx, credentials, ...)
207
+ aborts the rest of the export: the halves still waiting are not sent, since they
208
+ would most likely fail the same way. They go to ``out.retry``, like the spans of
209
+ any failure that may clear up; spans the server rejects for good count as lost.
210
+ """
211
+ if state.aborted is not None:
212
+ out.fail(state.aborted)
213
+ out.retry.extend(items)
214
+ return
215
+ if state.remaining <= 0:
216
+ out.fail(f"gave up after {self._max_attempts} requests")
217
+ out.retry.extend(items)
218
+ return
219
+ extra: dict[str, Any] = {}
220
+ if state.deadline is not None:
221
+ left = state.deadline - time.monotonic()
222
+ if left <= 0:
223
+ out.fail(state.abort("deadline passed"))
224
+ out.retry.extend(items)
225
+ return
226
+ # An injected client keeps its own timeouts, capped to the deadline.
227
+ extra["timeout"] = min(left, self._timeout) if self._owns_client else left
228
+ state.remaining -= 1
229
+ try:
230
+ response = self._client.post(
231
+ self._url, json={"spans": items}, headers=self._headers, **extra
232
+ )
233
+ except Exception as exc:
234
+ out.fail(state.abort(repr(exc)))
235
+ out.retry.extend(items)
236
+ return
237
+ code = response.status_code
238
+ if code in (401, 403):
239
+ if not self._auth_warned:
240
+ self._auth_warned = True
241
+ logger.warning(
242
+ "agentflight: server rejected credentials (HTTP %d); spans are being "
243
+ "dropped. Check AGENTFLIGHT_API_KEY.",
244
+ code,
245
+ )
246
+ out.fail(state.abort(""))
247
+ out.retry.extend(items)
248
+ return
249
+ if code == 413:
250
+ if len(items) == 1:
251
+ out.fail("span is larger than the server's body cap (HTTP 413)")
252
+ out.lost += 1
253
+ return
254
+ half = len(items) // 2
255
+ self._send(items[:half], state, out)
256
+ self._send(items[half:], state, out)
257
+ return
258
+ if 200 <= code < 300:
259
+ return
260
+ reason = state.abort(f"HTTP {code} from {self._url}")
261
+ out.fail(reason)
262
+ if code >= 500 or code in _RETRYABLE:
263
+ out.retry.extend(items)
264
+ else:
265
+ out.lost += len(items)
266
+
267
+ def shutdown(self) -> None:
268
+ if self._owns_client:
269
+ try:
270
+ self._client.close()
271
+ except Exception:
272
+ logger.warning("agentflight: error closing exporter client", exc_info=True)
@@ -0,0 +1,5 @@
1
+ """Optional integrations with agent frameworks and model clients.
2
+
3
+ Each submodule only imports its framework when you import that submodule, so none of them
4
+ is a dependency of the core SDK.
5
+ """
@@ -0,0 +1,369 @@
1
+ """LangGraph instrumentation through LangChain callbacks.
2
+
3
+ Needs ``langchain-core`` (installed with ``langgraph``; ``pip install agentflight-sdk[langgraph]``).
4
+ Pass the handler in the run config; nothing in your graph changes::
5
+
6
+ from agentflight.integrations.langgraph import AgentFlightCallbackHandler
7
+
8
+ graph.invoke(inputs, config={"callbacks": [AgentFlightCallbackHandler()]})
9
+
10
+ Recorded:
11
+
12
+ * the graph as a ``run`` (or, inside an ``agentflight.run``, as a ``node`` span in that run),
13
+ * each executed graph node as a ``node`` span with its step, input state and state update,
14
+ * chat model / LLM calls as ``llm`` spans with messages and token usage,
15
+ * tool calls as ``tool`` spans with arguments and result,
16
+ * errors on the span where they happened (one failure id per exception, as in the SDK).
17
+
18
+ LangChain's internal runnables inside a node (prompts, sequences, routers) aren't recorded;
19
+ their children are attached to the nearest recorded ancestor.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import logging
25
+ import threading
26
+ from collections.abc import Callable
27
+ from typing import Any
28
+ from uuid import UUID
29
+
30
+ from langchain_core.callbacks import BaseCallbackHandler
31
+ from langchain_core.messages import BaseMessage
32
+ from opentelemetry import trace
33
+ from opentelemetry.trace import Span, Status, StatusCode
34
+
35
+ from agentflight import attributes as A
36
+ from agentflight import sdk
37
+
38
+ logger = logging.getLogger("agentflight")
39
+
40
+ INTEGRATION = "langgraph"
41
+
42
+ # Control-flow exceptions LangGraph raises for interrupts and parent commands.
43
+ _BUBBLE_UP = "GraphBubbleUp"
44
+
45
+ _SECRET_PARTS = ("api_key", "secret", "password", "authorization")
46
+
47
+
48
+ def _jsonable(value: Any, depth: int = 0) -> Any:
49
+ """Turn LangChain messages and pydantic models into plain JSON-ish values."""
50
+ if depth > 20:
51
+ return value
52
+ if isinstance(value, BaseMessage):
53
+ out: dict[str, Any] = {"type": value.type, "content": _jsonable(value.content, depth + 1)}
54
+ for name in ("name", "tool_calls", "tool_call_id"):
55
+ item = getattr(value, name, None)
56
+ if item:
57
+ out[name] = _jsonable(item, depth + 1)
58
+ return out
59
+ if isinstance(value, dict):
60
+ return {str(k): _jsonable(v, depth + 1) for k, v in value.items()}
61
+ if isinstance(value, list | tuple):
62
+ return [_jsonable(v, depth + 1) for v in value]
63
+ dump = getattr(value, "model_dump", None)
64
+ if callable(dump) and not isinstance(value, type):
65
+ return dump(mode="json")
66
+ return value
67
+
68
+
69
+ def _params(invocation_params: dict[str, Any] | None) -> dict[str, Any]:
70
+ return {
71
+ k: v
72
+ for k, v in (invocation_params or {}).items()
73
+ if not any(part in k.lower() for part in _SECRET_PARTS)
74
+ }
75
+
76
+
77
+ def _model_name(serialized: dict[str, Any] | None, kwargs: dict[str, Any]) -> str:
78
+ params = kwargs.get("invocation_params") or {}
79
+ metadata = kwargs.get("metadata") or {}
80
+ for value in (
81
+ params.get("model"),
82
+ params.get("model_name"),
83
+ metadata.get("ls_model_name"),
84
+ kwargs.get("name"),
85
+ (serialized or {}).get("name"),
86
+ ):
87
+ if value:
88
+ return str(value)
89
+ return "unknown"
90
+
91
+
92
+ def _is_bubble_up(exc: BaseException) -> bool:
93
+ return any(cls.__name__ == _BUBBLE_UP for cls in type(exc).__mro__)
94
+
95
+
96
+ def _usage(response: Any) -> tuple[Any, int | None, int | None]:
97
+ """(recorded response, tokens_in, tokens_out) from a LangChain ``LLMResult``."""
98
+ generations = [g for batch in response.generations for g in batch]
99
+ first = generations[0] if generations else None
100
+ message = getattr(first, "message", None)
101
+ recorded: Any = _jsonable(message) if message is not None else getattr(first, "text", None)
102
+ usage = getattr(message, "usage_metadata", None) or {}
103
+ tokens_in, tokens_out = usage.get("input_tokens"), usage.get("output_tokens")
104
+ if tokens_in is None and tokens_out is None:
105
+ token_usage = (response.llm_output or {}).get("token_usage") or {}
106
+ tokens_in = token_usage.get("prompt_tokens")
107
+ tokens_out = token_usage.get("completion_tokens")
108
+ return recorded, tokens_in, tokens_out
109
+
110
+
111
+ class AgentFlightCallbackHandler(BaseCallbackHandler):
112
+ """Records LangGraph runs as AgentFlight spans. Never raises into the graph.
113
+
114
+ ``run_name`` and ``metadata`` are used when the handler creates the run itself (no
115
+ surrounding ``agentflight.run``). ``run_id`` holds the id of the last run it created.
116
+ """
117
+
118
+ raise_error = False
119
+ run_inline = True
120
+
121
+ def __init__(self, *, run_name: str | None = None, metadata: dict[str, Any] | None = None):
122
+ super().__init__()
123
+ self.run_name = run_name
124
+ self.metadata = metadata or {}
125
+ self.run_id: str | None = None
126
+ self._spans: dict[UUID, Span] = {}
127
+ # Unrecorded LangChain runs -> nearest recorded ancestor (or None).
128
+ self._skipped: dict[UUID, UUID | None] = {}
129
+ self._lock = threading.Lock()
130
+
131
+ # -- span bookkeeping -------------------------------------------------------------
132
+
133
+ def _guard(self, fn: Callable[..., None], *args: Any, **kwargs: Any) -> None:
134
+ sdk._safe(fn, *args, **kwargs)
135
+
136
+ def _resolve(self, parent_run_id: UUID | None) -> UUID | None:
137
+ seen = 0
138
+ while parent_run_id is not None and parent_run_id not in self._spans and seen < 1000:
139
+ parent_run_id = self._skipped.get(parent_run_id)
140
+ seen += 1
141
+ return parent_run_id if parent_run_id in self._spans else None
142
+
143
+ def _open(
144
+ self,
145
+ run_id: UUID,
146
+ parent_run_id: UUID | None,
147
+ name: str,
148
+ attrs: dict[str, Any],
149
+ *,
150
+ new_trace: bool = False,
151
+ ) -> None:
152
+ tracer = sdk.get_recorder().tracer
153
+ with self._lock:
154
+ parent = self._resolve(parent_run_id)
155
+ if parent is not None:
156
+ context = trace.set_span_in_context(self._spans[parent])
157
+ elif new_trace:
158
+ context = trace.set_span_in_context(trace.INVALID_SPAN)
159
+ else:
160
+ context = None # the current span, e.g. a surrounding agentflight.run
161
+ attrs = {A.INTEGRATION: INTEGRATION, **attrs}
162
+ self._spans[run_id] = tracer.start_span(
163
+ name, context=context, attributes=sdk._finalize(attrs)
164
+ )
165
+
166
+ def _skip(self, run_id: UUID, parent_run_id: UUID | None) -> None:
167
+ with self._lock:
168
+ self._skipped[run_id] = self._resolve(parent_run_id)
169
+
170
+ def _close(
171
+ self,
172
+ run_id: UUID,
173
+ payloads: dict[str, Any] | None = None,
174
+ error: BaseException | None = None,
175
+ ) -> None:
176
+ with self._lock:
177
+ self._skipped.pop(run_id, None)
178
+ span = self._spans.pop(run_id, None)
179
+ if span is None:
180
+ return
181
+ try:
182
+ for key, value in (payloads or {}).items():
183
+ sdk._safe(sdk._set_payload, span, key, value)
184
+ if error is None:
185
+ span.set_status(Status(StatusCode.OK))
186
+ elif _is_bubble_up(error):
187
+ sdk._safe(
188
+ sdk._set_payload, span, A.NODE_OUTPUT, {"interrupted": type(error).__name__}
189
+ )
190
+ span.set_status(Status(StatusCode.OK))
191
+ else:
192
+ sdk._record_error(span, error)
193
+ finally:
194
+ span.end()
195
+
196
+ # -- chains: the graph and its nodes ----------------------------------------------
197
+
198
+ def on_chain_start(
199
+ self,
200
+ serialized: dict[str, Any] | None,
201
+ inputs: Any,
202
+ *,
203
+ run_id: UUID,
204
+ parent_run_id: UUID | None = None,
205
+ tags: list[str] | None = None,
206
+ metadata: dict[str, Any] | None = None,
207
+ **kwargs: Any,
208
+ ) -> None:
209
+ self._guard(
210
+ self._chain_start, serialized, inputs, run_id, parent_run_id, tags, metadata, kwargs
211
+ )
212
+
213
+ def _chain_start(
214
+ self,
215
+ serialized: dict[str, Any] | None,
216
+ inputs: Any,
217
+ run_id: UUID,
218
+ parent_run_id: UUID | None,
219
+ tags: list[str] | None,
220
+ metadata: dict[str, Any] | None,
221
+ kwargs: dict[str, Any],
222
+ ) -> None:
223
+ name = str(kwargs.get("name") or (serialized or {}).get("name") or "graph")
224
+ metadata = metadata or {}
225
+ if parent_run_id is None:
226
+ current = trace.get_current_span()
227
+ inside_run = A.KIND in (getattr(current, "attributes", None) or {})
228
+ if inside_run:
229
+ attrs: dict[str, Any] = {A.KIND: A.NODE, A.NODE_NAME: name}
230
+ attrs[A.NODE_INPUT] = sdk._Payload(_jsonable(inputs))
231
+ self._open(run_id, None, f"graph:{name}", attrs)
232
+ return
233
+ run_name = self.run_name or name
234
+ attrs = {
235
+ A.KIND: A.RUN,
236
+ A.RUN_NAME: run_name,
237
+ A.RUN_METADATA: sdk._Payload(self.metadata),
238
+ A.NODE_INPUT: sdk._Payload(_jsonable(inputs)),
239
+ }
240
+ self._open(run_id, None, f"run:{run_name}", attrs, new_trace=True)
241
+ span = self._spans.get(run_id)
242
+ if span is not None:
243
+ self.run_id = format(span.get_span_context().trace_id, "032x")
244
+ return
245
+ is_node = name == metadata.get("langgraph_node") and any(
246
+ t.startswith("graph:step:") for t in tags or []
247
+ )
248
+ if not is_node:
249
+ self._skip(run_id, parent_run_id)
250
+ return
251
+ attrs = {
252
+ A.KIND: A.NODE,
253
+ A.NODE_NAME: name,
254
+ A.NODE_INPUT: sdk._Payload(_jsonable(inputs)),
255
+ }
256
+ step = metadata.get("langgraph_step")
257
+ if isinstance(step, int):
258
+ attrs[A.NODE_STEP] = step
259
+ self._open(run_id, parent_run_id, f"node:{name}", attrs)
260
+
261
+ def on_chain_end(self, outputs: Any, *, run_id: UUID, **kwargs: Any) -> None:
262
+ self._guard(lambda: self._close(run_id, {A.NODE_OUTPUT: _jsonable(outputs)}))
263
+
264
+ def on_chain_error(self, error: BaseException, *, run_id: UUID, **kwargs: Any) -> None:
265
+ self._guard(self._close, run_id, None, error)
266
+
267
+ # -- model calls ------------------------------------------------------------------
268
+
269
+ def _llm_start(
270
+ self,
271
+ serialized: dict[str, Any] | None,
272
+ messages: Any,
273
+ run_id: UUID,
274
+ parent_run_id: UUID | None,
275
+ kwargs: dict[str, Any],
276
+ ) -> None:
277
+ model = _model_name(serialized, kwargs)
278
+ attrs: dict[str, Any] = {
279
+ A.KIND: A.LLM,
280
+ A.LLM_MODEL: model,
281
+ A.LLM_MESSAGES: sdk._Payload(_jsonable(messages)),
282
+ }
283
+ params = _params(kwargs.get("invocation_params"))
284
+ if params:
285
+ attrs[A.LLM_PARAMS] = sdk._Payload(params)
286
+ self._open(run_id, parent_run_id, f"llm:{model}", attrs)
287
+
288
+ def on_chat_model_start(
289
+ self,
290
+ serialized: dict[str, Any] | None,
291
+ messages: list[list[BaseMessage]],
292
+ *,
293
+ run_id: UUID,
294
+ parent_run_id: UUID | None = None,
295
+ **kwargs: Any,
296
+ ) -> None:
297
+ batch: Any = messages[0] if len(messages) == 1 else messages
298
+ self._guard(self._llm_start, serialized, batch, run_id, parent_run_id, kwargs)
299
+
300
+ def on_llm_start(
301
+ self,
302
+ serialized: dict[str, Any] | None,
303
+ prompts: list[str],
304
+ *,
305
+ run_id: UUID,
306
+ parent_run_id: UUID | None = None,
307
+ **kwargs: Any,
308
+ ) -> None:
309
+ batch: Any = prompts[0] if len(prompts) == 1 else prompts
310
+ self._guard(self._llm_start, serialized, batch, run_id, parent_run_id, kwargs)
311
+
312
+ def _llm_end(self, response: Any, run_id: UUID) -> None:
313
+ with self._lock:
314
+ span = self._spans.get(run_id)
315
+ if span is not None:
316
+ recorded, tokens_in, tokens_out = _usage(response)
317
+ if tokens_in is not None:
318
+ span.set_attribute(A.LLM_TOKENS_IN, int(tokens_in))
319
+ if tokens_out is not None:
320
+ span.set_attribute(A.LLM_TOKENS_OUT, int(tokens_out))
321
+ self._close(run_id, {A.LLM_RESPONSE: recorded})
322
+
323
+ def on_llm_end(self, response: Any, *, run_id: UUID, **kwargs: Any) -> None:
324
+ def end() -> None:
325
+ try:
326
+ self._llm_end(response, run_id)
327
+ finally:
328
+ self._close(run_id) # no-op unless _llm_end failed part way
329
+
330
+ self._guard(end)
331
+
332
+ def on_llm_error(self, error: BaseException, *, run_id: UUID, **kwargs: Any) -> None:
333
+ self._guard(self._close, run_id, None, error)
334
+
335
+ # -- tools ------------------------------------------------------------------------
336
+
337
+ def _tool_start(
338
+ self,
339
+ serialized: dict[str, Any] | None,
340
+ input_str: str,
341
+ run_id: UUID,
342
+ parent_run_id: UUID | None,
343
+ kwargs: dict[str, Any],
344
+ ) -> None:
345
+ name = str((serialized or {}).get("name") or kwargs.get("name") or "tool")
346
+ inputs = kwargs.get("inputs")
347
+ attrs = {
348
+ A.KIND: A.TOOL,
349
+ A.TOOL_NAME: name,
350
+ A.TOOL_ARGS: sdk._Payload(_jsonable(inputs) if inputs is not None else input_str),
351
+ }
352
+ self._open(run_id, parent_run_id, f"tool:{name}", attrs)
353
+
354
+ def on_tool_start(
355
+ self,
356
+ serialized: dict[str, Any] | None,
357
+ input_str: str,
358
+ *,
359
+ run_id: UUID,
360
+ parent_run_id: UUID | None = None,
361
+ **kwargs: Any,
362
+ ) -> None:
363
+ self._guard(self._tool_start, serialized, input_str, run_id, parent_run_id, kwargs)
364
+
365
+ def on_tool_end(self, output: Any, *, run_id: UUID, **kwargs: Any) -> None:
366
+ self._guard(lambda: self._close(run_id, {A.TOOL_RESULT: _jsonable(output)}))
367
+
368
+ def on_tool_error(self, error: BaseException, *, run_id: UUID, **kwargs: Any) -> None:
369
+ self._guard(self._close, run_id, None, error)