aid-runtime-python 0.1.55__py3-none-any.whl → 0.1.56__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.
aid_runtime/__init__.py CHANGED
@@ -128,6 +128,7 @@ from aid_runtime.evals import (
128
128
  z_critical,
129
129
  )
130
130
  from aid_runtime.gateway import ModelGateway, estimate_usage
131
+ from aid_runtime.local_trace import TRACE_DIR_ENV, local_trace_enabled
131
132
  from aid_runtime.pipeline import (
132
133
  STEPS_KEY,
133
134
  Pipeline,
@@ -268,7 +269,7 @@ from aid_runtime.types import (
268
269
  )
269
270
 
270
271
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
271
- __version__ = "0.1.55"
272
+ __version__ = "0.1.56"
272
273
 
273
274
  __all__ = [
274
275
  "ATTRIBUTES",
@@ -285,6 +286,7 @@ __all__ = [
285
286
  "REDUCED_KEY",
286
287
  "RESERVED_KEYS",
287
288
  "STEPS_KEY",
289
+ "TRACE_DIR_ENV",
288
290
  "AgentBudgetDegradedError",
289
291
  "AgentCheckpoint",
290
292
  "AgentDefinition",
@@ -471,6 +473,7 @@ __all__ = [
471
473
  "lexical_ranking",
472
474
  "lexical_score",
473
475
  "llm_span",
476
+ "local_trace_enabled",
474
477
  "map_step",
475
478
  "metric_names",
476
479
  "normalize",
@@ -0,0 +1,230 @@
1
+ """A local JSONL trace sink, enabled by ``AID_TRACE_DIR``.
2
+
3
+ The OpenTelemetry path is unchanged: with no provider installed, spans are no-ops and
4
+ tracing costs nothing. This module exists for the other case -- the CLI needs trace
5
+ data on disk, without the application installing an exporter, an SDK or a collector.
6
+ Setting ``AID_TRACE_DIR`` is that explicit request, and nothing here runs otherwise.
7
+
8
+ It is deliberately *not* an OpenTelemetry ``SpanExporter``: exporting one would mean
9
+ depending on the SDK, and the runtime deliberately depends only on the API so it never
10
+ decides a host application's telemetry. Instead it mirrors the span surface the
11
+ runtime itself uses (attributes, events, status) and writes one JSON line per span.
12
+
13
+ Writing must never fail a request, so every failure to record is swallowed.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import contextlib
19
+ import functools
20
+ import json
21
+ import math
22
+ import os
23
+ import secrets
24
+ import threading
25
+ import time
26
+ from contextvars import ContextVar
27
+ from datetime import UTC, datetime
28
+ from pathlib import Path
29
+ from typing import TYPE_CHECKING, Any, cast
30
+
31
+ if TYPE_CHECKING:
32
+ from collections.abc import Mapping
33
+
34
+ from opentelemetry.trace import Span, Status
35
+
36
+ __all__ = ["TRACE_DIR_ENV", "finish_span", "local_trace_enabled", "wrap_span"]
37
+
38
+ TRACE_DIR_ENV = "AID_TRACE_DIR"
39
+
40
+ #: ``(span_id, trace_id)`` for the spans currently open in this context. A tuple, so
41
+ #: a context cannot see a sibling's stack, and a span that ends out of order removes
42
+ #: only its own entry.
43
+ _OPEN: ContextVar[tuple[tuple[str, str], ...]] = ContextVar("aid_local_trace_open", default=())
44
+
45
+ _lock = threading.Lock()
46
+
47
+
48
+ def local_trace_enabled() -> bool:
49
+ """Whether ``AID_TRACE_DIR`` names a directory to write to."""
50
+ return bool(_configured_dir())
51
+
52
+
53
+ def wrap_span(
54
+ span: Span,
55
+ *,
56
+ name: str,
57
+ kind: str,
58
+ attributes: Mapping[str, Any] | None = None,
59
+ ) -> Span:
60
+ """Return ``span`` itself unless a local trace is requested, else a recording proxy."""
61
+ if not local_trace_enabled():
62
+ return span
63
+ return cast("Span", _LocalSpan(span, name=name, kind=kind, attributes=attributes or {}))
64
+
65
+
66
+ def finish_span(span: Span) -> None:
67
+ """End a wrapped span. A no-op for an ordinary OpenTelemetry span."""
68
+ if isinstance(span, _LocalSpan):
69
+ span.end()
70
+
71
+
72
+ def _configured_dir() -> str:
73
+ return os.environ.get(TRACE_DIR_ENV, "").strip()
74
+
75
+
76
+ def _now() -> str:
77
+ return datetime.now(UTC).isoformat(timespec="microseconds").replace("+00:00", "Z")
78
+
79
+
80
+ def _jsonable(value: Any) -> Any:
81
+ """Coerce an attribute value to something ``json`` can always serialise.
82
+
83
+ OpenTelemetry accepts attribute types that JSON does not (tuples, arbitrary
84
+ objects), and a value that failed to serialise would cost the whole record.
85
+ """
86
+ if value is None or isinstance(value, str | bool | int):
87
+ return value
88
+ if isinstance(value, float):
89
+ return value if math.isfinite(value) else str(value)
90
+ if isinstance(value, list | tuple):
91
+ return [_jsonable(item) for item in value]
92
+ return str(value)
93
+
94
+
95
+ @functools.lru_cache(maxsize=4)
96
+ def _sink_path_for(configured: str) -> Path:
97
+ """The file for one configured directory, created on first use.
98
+
99
+ Cached per directory so one process writes one file, while a caller that
100
+ points ``AID_TRACE_DIR`` somewhere else still gets a fresh file.
101
+ """
102
+ directory = Path(configured)
103
+ with contextlib.suppress(OSError):
104
+ directory.mkdir(parents=True, exist_ok=True)
105
+ stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%S%fZ")
106
+ return directory / f"trace-{stamp}-{os.getpid()}.jsonl"
107
+
108
+
109
+ def _sink_path() -> Path | None:
110
+ configured = _configured_dir()
111
+ if not configured:
112
+ return None
113
+ return _sink_path_for(configured)
114
+
115
+
116
+ def _write(record: dict[str, Any]) -> None:
117
+ path = _sink_path()
118
+ if path is None:
119
+ return
120
+ line = json.dumps(record, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
121
+ # A trace that could not be written is a lost trace, not a failed request.
122
+ with (
123
+ contextlib.suppress(OSError, TypeError, ValueError),
124
+ _lock,
125
+ path.open("a", encoding="utf-8") as handle,
126
+ ):
127
+ handle.write(f"{line}\n")
128
+
129
+
130
+ class _LocalSpan:
131
+ """Mirrors the span methods this runtime calls, then writes one JSON line."""
132
+
133
+ def __init__(
134
+ self,
135
+ span: Span,
136
+ *,
137
+ name: str,
138
+ kind: str,
139
+ attributes: Mapping[str, Any],
140
+ ) -> None:
141
+ self._span = span
142
+ self._name = name
143
+ self._kind = kind
144
+ self._attributes: dict[str, Any] = {
145
+ key: _jsonable(value) for key, value in attributes.items()
146
+ }
147
+ self._events: list[dict[str, Any]] = []
148
+ self._status: dict[str, Any] | None = None
149
+ self._monotonic = time.monotonic()
150
+ self._started_at = _now()
151
+ self._ended = False
152
+
153
+ open_spans = _OPEN.get()
154
+ parent = open_spans[-1] if open_spans else None
155
+ self._trace_id = parent[1] if parent is not None else secrets.token_hex(16)
156
+ self._span_id = secrets.token_hex(8)
157
+ self._parent_span_id = parent[0] if parent is not None else None
158
+ _OPEN.set((*open_spans, (self._span_id, self._trace_id)))
159
+
160
+ def set_attribute(self, key: str, value: Any) -> None:
161
+ self._attributes[key] = _jsonable(value)
162
+ self._span.set_attribute(key, value)
163
+
164
+ def set_attributes(self, attributes: Mapping[str, Any]) -> None:
165
+ for key, value in attributes.items():
166
+ self.set_attribute(key, value)
167
+
168
+ def add_event(
169
+ self,
170
+ name: str,
171
+ attributes: Mapping[str, Any] | None = None,
172
+ timestamp: int | None = None,
173
+ ) -> None:
174
+ self._events.append(
175
+ {
176
+ "name": name,
177
+ "at": _now(),
178
+ "attributes": {key: _jsonable(value) for key, value in (attributes or {}).items()},
179
+ }
180
+ )
181
+ self._span.add_event(name, attributes, timestamp)
182
+
183
+ def record_exception(
184
+ self,
185
+ exception: BaseException,
186
+ attributes: Mapping[str, Any] | None = None,
187
+ *,
188
+ escaped: bool = True,
189
+ timestamp: int | None = None,
190
+ ) -> None:
191
+ recorded = {
192
+ "exception.type": f"{type(exception).__module__}.{type(exception).__qualname__}",
193
+ "exception.message": str(exception),
194
+ **{key: _jsonable(value) for key, value in (attributes or {}).items()},
195
+ }
196
+ self._events.append({"name": "exception", "at": _now(), "attributes": recorded})
197
+ self._span.record_exception(exception, attributes, escaped=escaped, timestamp=timestamp)
198
+
199
+ def set_status(self, status: Status) -> None:
200
+ self._status = {"code": status.status_code.name, "message": status.description}
201
+ self._span.set_status(status)
202
+
203
+ def update_name(self, name: str) -> None:
204
+ self._name = name
205
+ self._span.update_name(name)
206
+
207
+ def end(self, end_time: int | None = None) -> None:
208
+ if self._ended:
209
+ return
210
+ self._ended = True
211
+ _OPEN.set(tuple(entry for entry in _OPEN.get() if entry[0] != self._span_id))
212
+ self._span.end(end_time)
213
+ _write(
214
+ {
215
+ "trace_id": self._trace_id,
216
+ "span_id": self._span_id,
217
+ "parent_span_id": self._parent_span_id,
218
+ "name": self._name,
219
+ "kind": self._kind,
220
+ "started_at": self._started_at,
221
+ "ended_at": _now(),
222
+ "duration_ms": round((time.monotonic() - self._monotonic) * 1000, 3),
223
+ "attributes": self._attributes,
224
+ "events": self._events,
225
+ "status": self._status,
226
+ }
227
+ )
228
+
229
+ def __getattr__(self, name: str) -> Any:
230
+ return getattr(self._span, name)
aid_runtime/tracing.py CHANGED
@@ -20,6 +20,7 @@ from typing import TYPE_CHECKING, Any
20
20
  from opentelemetry import trace
21
21
  from opentelemetry.trace import Span, SpanKind, Status, StatusCode
22
22
 
23
+ from aid_runtime.local_trace import finish_span, wrap_span
23
24
  from aid_runtime.types import TokenUsage
24
25
 
25
26
  if TYPE_CHECKING:
@@ -130,11 +131,19 @@ def llm_span(
130
131
  record_exception=False,
131
132
  set_status_on_exception=False,
132
133
  ) as span:
134
+ recorded = wrap_span(
135
+ span,
136
+ name=f"{operation} {model}",
137
+ kind=SpanKind.CLIENT.name,
138
+ attributes=attributes,
139
+ )
133
140
  try:
134
- yield span
141
+ yield recorded
135
142
  except BaseException as exc:
136
- record_exception(span, exc)
143
+ record_exception(recorded, exc)
137
144
  raise
145
+ finally:
146
+ finish_span(recorded)
138
147
 
139
148
 
140
149
  def record_usage(span: Span, usage: TokenUsage) -> None:
@@ -166,18 +175,27 @@ def agent_span(
166
175
  makes open their own CLIENT child spans.
167
176
  """
168
177
  active = tracer or get_tracer()
178
+ attributes = aid_attributes(agent_id=agent_id, agent_engine=engine)
169
179
  with active.start_as_current_span(
170
180
  f"invoke_agent {agent_id}",
171
181
  kind=SpanKind.INTERNAL,
172
- attributes=aid_attributes(agent_id=agent_id, agent_engine=engine),
182
+ attributes=attributes,
173
183
  record_exception=False,
174
184
  set_status_on_exception=False,
175
185
  ) as span:
186
+ recorded = wrap_span(
187
+ span,
188
+ name=f"invoke_agent {agent_id}",
189
+ kind=SpanKind.INTERNAL.name,
190
+ attributes=attributes,
191
+ )
176
192
  try:
177
- yield span
193
+ yield recorded
178
194
  except BaseException as exc:
179
- record_exception(span, exc)
195
+ record_exception(recorded, exc)
180
196
  raise
197
+ finally:
198
+ finish_span(recorded)
181
199
 
182
200
 
183
201
  def record_hitl(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.55
3
+ Version: 0.1.56
4
4
  Summary: The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline.
5
5
  Author: The AID Framework authors
6
6
  License-Expression: Apache-2.0
@@ -1,17 +1,18 @@
1
- aid_runtime/__init__.py,sha256=UKmY4iZqL15XpdU1DWUVMH3dybViUFnLYd-W5mr61N8,11009
1
+ aid_runtime/__init__.py,sha256=qWuR61oWYNA3xA51kLbIJSbFXYNawViljD7BwxP_tU0,11128
2
2
  aid_runtime/cache.py,sha256=jhw_EBd9dfWEUzYeibOvIkVBqqiLUjqF5WKEPz9GkhE,6836
3
3
  aid_runtime/concurrency.py,sha256=z0tFQHw35ttFLKfazGBjCMPOLQOnUotE_OPpvR1piH4,2829
4
4
  aid_runtime/control.py,sha256=u4U97QFdYSSjOPY3D6f1-GZhkGhygEdR-apdgw_jJok,13797
5
5
  aid_runtime/cost.py,sha256=Hc7X6mtkeanL9eJ1lEZZCQ9LxZurhL1it0gm3s9LpQE,5465
6
6
  aid_runtime/errors.py,sha256=TKkZyZZcFTl5yxNKlA8jUF4ORpYHLGFEvc6r9FK4X70,12572
7
7
  aid_runtime/gateway.py,sha256=p0qsaQUAYrwSzlWwpUi1wY6pdOeU98QjsWLzq8045Fo,18267
8
+ aid_runtime/local_trace.py,sha256=eg5LDsg1VfNmJNqs8KjtdzTjSqg7SWTXunLwg-b3IcM,7870
8
9
  aid_runtime/pipeline.py,sha256=Y2jiiYISLLxgBKGBj5J2rseEDzE8RXP8v5pJ_edjHfM,6334
9
10
  aid_runtime/prompts.py,sha256=eN3p_Yc-J6pyKaL2w4I-EmwvcPKErnXBvvI_Syq13ZM,7083
10
11
  aid_runtime/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
12
  aid_runtime/steps.py,sha256=44v8-ebN77VGZePmfhBYi0KORFBrH2GWFSzlfczaJhs,12047
12
13
  aid_runtime/structured.py,sha256=Uga-VoGJN56lUtr-M3nmUjAKGF32cAAk-p7WceUgPzg,5061
13
14
  aid_runtime/tools.py,sha256=7LeaPI5aJioNe3vexUv94tvIRpOwxj1Ujt723qvO3UI,9906
14
- aid_runtime/tracing.py,sha256=Ii2ypuHxHLZ4lmE6oYhcCJiA9dFE5KhXKRTsdQnDDLE,8524
15
+ aid_runtime/tracing.py,sha256=WEnmXRfRPEb5eRpH2JWZlnim7V4IHDv4SV2HS_qjUrU,9081
15
16
  aid_runtime/types.py,sha256=cVYgmacDIhStQT5dX_X67-q57sPBBaWC5nybtGVqVsw,10389
16
17
  aid_runtime/agents/__init__.py,sha256=XOOecYSBtWzD0Ylaurbz3w2Tuffpzc_5nNeMIznCucU,2398
17
18
  aid_runtime/agents/chat_model.py,sha256=fZdCmSpoECuBVGZE1s8NmT2erT33RhDuLh3yJM6kAJE,14808
@@ -46,7 +47,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
46
47
  aid_runtime/retrieval/retriever.py,sha256=hVLP0xOLKioYsa-aS1akyJl5p-WbpVjm8OfCw26m4CE,13941
47
48
  aid_runtime/retrieval/stores.py,sha256=VEi68AaMHcQjdAbWOHflp3jCl1_1db71rIzZjTouLlo,5857
48
49
  aid_runtime/retrieval/types.py,sha256=8vKP21rmE9LglnB5gtv0dLBIkXzaPqdG3-GS98K0gpc,13498
49
- aid_runtime_python-0.1.55.dist-info/METADATA,sha256=hAgYYibEVxPiVvSZkUoEaacdaV423uVqX4vrX9IZzZ0,15559
50
- aid_runtime_python-0.1.55.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
51
- aid_runtime_python-0.1.55.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
52
- aid_runtime_python-0.1.55.dist-info/RECORD,,
50
+ aid_runtime_python-0.1.56.dist-info/METADATA,sha256=hbGZRt7HjfSzdxd7Hji_acCwKTXeafbuooqSErWfHCg,15559
51
+ aid_runtime_python-0.1.56.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
52
+ aid_runtime_python-0.1.56.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
53
+ aid_runtime_python-0.1.56.dist-info/RECORD,,