trainhiro-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.
Potentially problematic release.
This version of trainhiro-sdk might be problematic. Click here for more details.
- trainhiro/__init__.py +50 -0
- trainhiro/__main__.py +7 -0
- trainhiro/_record.py +633 -0
- trainhiro/_util.py +103 -0
- trainhiro/cli.py +915 -0
- trainhiro/context.py +267 -0
- trainhiro/export.py +38 -0
- trainhiro/exporters.py +810 -0
- trainhiro/integrations/__init__.py +188 -0
- trainhiro/integrations/_common.py +275 -0
- trainhiro/integrations/anthropic.py +186 -0
- trainhiro/integrations/langchain.py +608 -0
- trainhiro/integrations/openai.py +408 -0
- trainhiro/pricing.json +394 -0
- trainhiro/pricing.py +285 -0
- trainhiro/py.typed +0 -0
- trainhiro/redaction.json +174 -0
- trainhiro/routing/__init__.py +54 -0
- trainhiro/routing/config.py +500 -0
- trainhiro/routing/gate.py +877 -0
- trainhiro/routing/jsonschema_subset.py +383 -0
- trainhiro/routing/router.py +1464 -0
- trainhiro/routing/safe_regex.py +565 -0
- trainhiro/routing/translate.py +864 -0
- trainhiro/schema/__init__.py +76 -0
- trainhiro/schema/routing.v1.json +165 -0
- trainhiro/schema/span.v1.json +249 -0
- trainhiro/scrub.py +633 -0
- trainhiro/span.py +305 -0
- trainhiro/step_key.py +135 -0
- trainhiro_sdk-0.1.0.dist-info/METADATA +257 -0
- trainhiro_sdk-0.1.0.dist-info/RECORD +35 -0
- trainhiro_sdk-0.1.0.dist-info/WHEEL +4 -0
- trainhiro_sdk-0.1.0.dist-info/entry_points.txt +2 -0
- trainhiro_sdk-0.1.0.dist-info/licenses/LICENSE +23 -0
trainhiro/__init__.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Hiro SDK: trace every LLM call your app makes, and route proven steps to a small model.
|
|
2
|
+
|
|
3
|
+
Quick start::
|
|
4
|
+
|
|
5
|
+
import trainhiro, anthropic
|
|
6
|
+
client = trainhiro.wrap(anthropic.Anthropic()) # or trainhiro.instrument() for every client
|
|
7
|
+
with trainhiro.trace("my-agent-run"):
|
|
8
|
+
with trainhiro.step("plan"):
|
|
9
|
+
client.messages.create(...)
|
|
10
|
+
trainhiro.flush()
|
|
11
|
+
|
|
12
|
+
Export is configured from env vars (``HIRO_API_KEY``, ``HIRO_COLLECTOR_URL``, ``HIRO_TRACE_FILE``;
|
|
13
|
+
see :mod:`trainhiro.exporters`) or with :func:`trainhiro.configure`. The routing config
|
|
14
|
+
comes from ``HIRO_ROUTING_CONFIG`` or ``trainhiro.configure(routing=...)``, and
|
|
15
|
+
``HIRO_ROUTING=off`` turns it off (see :mod:`trainhiro.routing.config`).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
|
19
|
+
|
|
20
|
+
from trainhiro.context import TraceHandle, current_trace_id, set_attributes, step, trace
|
|
21
|
+
from trainhiro.exporters import (
|
|
22
|
+
HttpExporter,
|
|
23
|
+
InMemoryExporter,
|
|
24
|
+
JsonlExporter,
|
|
25
|
+
configure,
|
|
26
|
+
flush,
|
|
27
|
+
shutdown,
|
|
28
|
+
)
|
|
29
|
+
from trainhiro.integrations import instrument, uninstrument, wrap
|
|
30
|
+
from trainhiro.routing.config import get_routing, reload_routing
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"HttpExporter",
|
|
34
|
+
"InMemoryExporter",
|
|
35
|
+
"JsonlExporter",
|
|
36
|
+
"TraceHandle",
|
|
37
|
+
"__version__",
|
|
38
|
+
"configure",
|
|
39
|
+
"current_trace_id",
|
|
40
|
+
"flush",
|
|
41
|
+
"get_routing",
|
|
42
|
+
"instrument",
|
|
43
|
+
"reload_routing",
|
|
44
|
+
"set_attributes",
|
|
45
|
+
"shutdown",
|
|
46
|
+
"step",
|
|
47
|
+
"trace",
|
|
48
|
+
"uninstrument",
|
|
49
|
+
"wrap",
|
|
50
|
+
]
|
trainhiro/__main__.py
ADDED
trainhiro/_record.py
ADDED
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
"""Recording one LLM call as a span, and instrumenting provider stream objects.
|
|
2
|
+
|
|
3
|
+
Everything here is internal and defensive: a failure inside the SDK is logged
|
|
4
|
+
and swallowed, the user's call proceeds as if the SDK were not installed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import inspect
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
import weakref
|
|
13
|
+
from collections.abc import Callable, Mapping
|
|
14
|
+
from typing import Any, Protocol
|
|
15
|
+
|
|
16
|
+
from trainhiro import context, exporters, pricing, step_key
|
|
17
|
+
from trainhiro._util import logger, warn_limited
|
|
18
|
+
from trainhiro.span import Provider, Request, Response, Span, SpanError, Usage, new_span_id, now_rfc3339
|
|
19
|
+
|
|
20
|
+
ATTR_STREAM = "hiro.stream"
|
|
21
|
+
ATTR_STREAM_INCOMPLETE = "hiro.stream.incomplete"
|
|
22
|
+
ATTR_TTFT_MS = "hiro.ttft_ms"
|
|
23
|
+
ATTR_RESPONSE_MODEL = "hiro.response_model"
|
|
24
|
+
ATTR_ERROR_STATUS = "hiro.error.status_code"
|
|
25
|
+
ATTR_API = "hiro.api"
|
|
26
|
+
ATTR_RAW_RESPONSE = "hiro.raw_response"
|
|
27
|
+
ATTR_RAW_UNPARSED = "hiro.raw_response.unparsed"
|
|
28
|
+
# Routing; set only on calls whose step_key has a route.
|
|
29
|
+
ATTR_ROUTE = "hiro.route"
|
|
30
|
+
ATTR_ROUTE_ID = "hiro.route.id"
|
|
31
|
+
ATTR_ROUTE_CONFIG_ID = "hiro.route.config_id"
|
|
32
|
+
ATTR_ROUTE_MODE = "hiro.route.mode"
|
|
33
|
+
ATTR_ROUTE_REASON = "hiro.route.reason"
|
|
34
|
+
ATTR_ROUTE_SMALL_LATENCY_MS = "hiro.route.small_latency_ms"
|
|
35
|
+
ATTR_ROUTE_GATE_MS = "hiro.route.gate_ms"
|
|
36
|
+
ATTR_ROUTE_SMALL_USAGE = "hiro.route.small_usage"
|
|
37
|
+
ATTR_ROUTE_SMALL_RESPONSE = "hiro.route.small_response"
|
|
38
|
+
ATTR_ROUTE_BUFFERED = "hiro.route.buffered"
|
|
39
|
+
ATTR_ROUTE_SHADOW_GATE = "hiro.route.shadow_gate"
|
|
40
|
+
ATTR_ROUTE_SHADOW_RESPONSE = "hiro.route.shadow_response"
|
|
41
|
+
ATTR_ROUTE_SHADOW_USAGE = "hiro.route.shadow_usage"
|
|
42
|
+
ATTR_ROUTE_SHADOW_LATENCY_MS = "hiro.route.shadow_latency_ms"
|
|
43
|
+
ATTR_ROUTE_SHADOW_ERROR = "hiro.route.shadow_error"
|
|
44
|
+
ROUTE_SMALL = "small"
|
|
45
|
+
|
|
46
|
+
# Keys never copied into request.params: transport settings, and headers that may carry secrets.
|
|
47
|
+
_NOT_PARAMS = frozenset({"extra_headers", "extra_query", "timeout"})
|
|
48
|
+
_RAW_RESPONSE_HEADER = "x-stainless-raw-response"
|
|
49
|
+
_HELPER_METHOD_HEADER = "x-stainless-helper-method"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _header(kwargs: Mapping[str, Any], name: str) -> Any:
|
|
53
|
+
headers = kwargs.get("extra_headers")
|
|
54
|
+
if not isinstance(headers, Mapping):
|
|
55
|
+
return None
|
|
56
|
+
for key, value in headers.items():
|
|
57
|
+
if isinstance(key, str) and key.lower() == name:
|
|
58
|
+
return value
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def raw_response_mode(kwargs: Mapping[str, Any]) -> str | None:
|
|
63
|
+
"""``"raw"`` for ``with_raw_response``, ``"stream"`` for ``with_streaming_response``, else None.
|
|
64
|
+
|
|
65
|
+
Both wrappers call the regular method with this header set and get back an
|
|
66
|
+
HTTP response object instead of the parsed result. The header value is
|
|
67
|
+
``"stream"`` for the streaming form and ``"raw"`` (anthropic) or ``"true"``
|
|
68
|
+
(openai) for the other, whose body is read before the call returns.
|
|
69
|
+
"""
|
|
70
|
+
value = _header(kwargs, _RAW_RESPONSE_HEADER)
|
|
71
|
+
if value is None or value is False or value == "":
|
|
72
|
+
return None
|
|
73
|
+
return "stream" if value == "stream" else "raw"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def is_raw_response_call(kwargs: Mapping[str, Any]) -> bool:
|
|
77
|
+
return raw_response_mode(kwargs) is not None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def helper_method(kwargs: Mapping[str, Any]) -> str | None:
|
|
81
|
+
"""The SDK helper that built this call (e.g. openai ``chat.completions.stream``), if it says so."""
|
|
82
|
+
value = _header(kwargs, _HELPER_METHOD_HEADER)
|
|
83
|
+
return value if isinstance(value, str) and "." in value else None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def materialize(kwargs: dict[str, Any], *keys: str) -> None:
|
|
87
|
+
"""Turn one-shot iterables (generators) into lists so recording does not consume them."""
|
|
88
|
+
for key in keys:
|
|
89
|
+
value = kwargs.get(key)
|
|
90
|
+
if (
|
|
91
|
+
value is not None
|
|
92
|
+
and not isinstance(value, (list, tuple, str, bytes, Mapping))
|
|
93
|
+
and hasattr(value, "__iter__")
|
|
94
|
+
):
|
|
95
|
+
kwargs[key] = list(value)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def params_from(kwargs: Mapping[str, Any], exclude: frozenset[str]) -> dict[str, Any]:
|
|
99
|
+
return {
|
|
100
|
+
k: v
|
|
101
|
+
for k, v in kwargs.items()
|
|
102
|
+
if k not in exclude
|
|
103
|
+
and k not in _NOT_PARAMS
|
|
104
|
+
and not (k == "extra_body" and v is None) # helpers pass extra_body=None
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def compute_step_key(system: Any, tools: list[dict[str, Any]]) -> str:
|
|
109
|
+
try:
|
|
110
|
+
return step_key.compute(system, tools)
|
|
111
|
+
except Exception:
|
|
112
|
+
# Tools without a name (e.g. provider built-ins) cannot be normalized; key on the rest.
|
|
113
|
+
usable = []
|
|
114
|
+
for tool in tools:
|
|
115
|
+
try:
|
|
116
|
+
step_key.normalize_tool(tool)
|
|
117
|
+
usable.append(tool)
|
|
118
|
+
except Exception:
|
|
119
|
+
continue
|
|
120
|
+
try:
|
|
121
|
+
return step_key.compute(system, usable)
|
|
122
|
+
except Exception:
|
|
123
|
+
return step_key.compute(None, [])
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def route_attributes(state: Any) -> dict[str, Any]:
|
|
127
|
+
"""The ``hiro.route*`` span attributes of a :class:`trainhiro.routing.router.RouteState`.
|
|
128
|
+
|
|
129
|
+
A routed call the SDK never sent (it raised before its HTTP request) is
|
|
130
|
+
``frontier`` with reason ``not_sent``. ``small_response`` is kept only on
|
|
131
|
+
``frontier_fallback`` and ``mode: shadow`` calls that ran serve, so gate precision
|
|
132
|
+
and live agreement can be measured; on ``small`` it is the span's response. The
|
|
133
|
+
``shadow_*`` attributes are set on sampled shadow calls (see :mod:`trainhiro.routing.router`).
|
|
134
|
+
"""
|
|
135
|
+
path = state.path or "frontier"
|
|
136
|
+
attrs: dict[str, Any] = {
|
|
137
|
+
ATTR_ROUTE: path,
|
|
138
|
+
ATTR_ROUTE_ID: state.route.route_id,
|
|
139
|
+
ATTR_ROUTE_CONFIG_ID: state.config_id,
|
|
140
|
+
ATTR_ROUTE_MODE: state.route.mode,
|
|
141
|
+
}
|
|
142
|
+
if path != ROUTE_SMALL:
|
|
143
|
+
attrs[ATTR_ROUTE_REASON] = state.reason if state.path is not None and state.reason else "not_sent"
|
|
144
|
+
if state.small_latency_ms is not None:
|
|
145
|
+
attrs[ATTR_ROUTE_SMALL_LATENCY_MS] = state.small_latency_ms
|
|
146
|
+
if state.gate_ms is not None:
|
|
147
|
+
attrs[ATTR_ROUTE_GATE_MS] = state.gate_ms
|
|
148
|
+
if state.small_usage is not None:
|
|
149
|
+
attrs[ATTR_ROUTE_SMALL_USAGE] = dict(state.small_usage)
|
|
150
|
+
if state.small_response is not None and (path == "frontier_fallback" or state.shadow_gate is not None):
|
|
151
|
+
attrs[ATTR_ROUTE_SMALL_RESPONSE] = state.small_response
|
|
152
|
+
if state.buffered:
|
|
153
|
+
attrs[ATTR_ROUTE_BUFFERED] = True
|
|
154
|
+
if state.shadow_gate is not None:
|
|
155
|
+
attrs[ATTR_ROUTE_SHADOW_GATE] = state.shadow_gate
|
|
156
|
+
if path == ROUTE_SMALL:
|
|
157
|
+
if state.shadow_response is not None:
|
|
158
|
+
attrs[ATTR_ROUTE_SHADOW_RESPONSE] = state.shadow_response
|
|
159
|
+
if state.shadow_usage is not None:
|
|
160
|
+
attrs[ATTR_ROUTE_SHADOW_USAGE] = dict(state.shadow_usage)
|
|
161
|
+
if state.shadow_latency_ms is not None:
|
|
162
|
+
attrs[ATTR_ROUTE_SHADOW_LATENCY_MS] = state.shadow_latency_ms
|
|
163
|
+
if state.shadow_error is not None:
|
|
164
|
+
attrs[ATTR_ROUTE_SHADOW_ERROR] = state.shadow_error
|
|
165
|
+
return attrs
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def small_span_usage(provider: str, small: Mapping[str, Any]) -> Usage:
|
|
169
|
+
"""serve's counts (``hiro.route.small_usage``) in the caller's provider accounting.
|
|
170
|
+
|
|
171
|
+
Used for a ``small`` span whose replayed stream reports no usage (an OpenAI
|
|
172
|
+
stream without ``stream_options.include_usage``, exactly what the caller asked for).
|
|
173
|
+
"""
|
|
174
|
+
prompt, output, cached = small.get("input_tokens"), small.get("output_tokens"), small.get("cached_tokens")
|
|
175
|
+
if provider == "anthropic" and isinstance(prompt, int): # Anthropic counts the uncached prompt
|
|
176
|
+
return Usage(input_tokens=max(prompt - (cached or 0), 0), output_tokens=output, cache_read_tokens=cached)
|
|
177
|
+
return Usage(input_tokens=prompt, output_tokens=output, cache_read_tokens=cached)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class CallRecord:
|
|
181
|
+
"""One in-flight call. ``finish``/``fail`` are idempotent and never raise.
|
|
182
|
+
|
|
183
|
+
``route`` is the call's ``RouteState`` when its step has a route (set by the
|
|
184
|
+
router before the call); the span then carries the ``hiro.route*`` attributes,
|
|
185
|
+
and on the ``small`` path ``cost_usd`` is ``0.0`` and ``hiro.response_model`` is
|
|
186
|
+
the small model (``response``/``usage`` are the small model's: the SDK parsed them
|
|
187
|
+
from the synthesized response).
|
|
188
|
+
"""
|
|
189
|
+
|
|
190
|
+
def __init__(
|
|
191
|
+
self,
|
|
192
|
+
provider: Provider,
|
|
193
|
+
model: str,
|
|
194
|
+
request: Request,
|
|
195
|
+
attributes: Mapping[str, Any] | None = None,
|
|
196
|
+
*,
|
|
197
|
+
ctx: context.CallContext | None = None,
|
|
198
|
+
span_id: str | None = None,
|
|
199
|
+
) -> None:
|
|
200
|
+
"""``ctx`` and ``span_id`` default to the current ``trainhiro`` context and a fresh id; the
|
|
201
|
+
LangChain handler passes both, derived from the LangChain run tree."""
|
|
202
|
+
if ctx is None:
|
|
203
|
+
ctx = context.capture()
|
|
204
|
+
self.span_id = span_id
|
|
205
|
+
self.provider = provider
|
|
206
|
+
self.model = model or "unknown"
|
|
207
|
+
self.request = request
|
|
208
|
+
self.ctx = ctx
|
|
209
|
+
self.step_key = compute_step_key(request.system, request.tools)
|
|
210
|
+
self.attributes: dict[str, Any] = dict(ctx.attributes)
|
|
211
|
+
self.attributes.update(attributes or {})
|
|
212
|
+
self.route: Any = None
|
|
213
|
+
self._lock = threading.Lock()
|
|
214
|
+
self._done = False
|
|
215
|
+
self._frozen: tuple[float, str] | None = None
|
|
216
|
+
self.restart_clock()
|
|
217
|
+
|
|
218
|
+
def restart_clock(self) -> None:
|
|
219
|
+
self.started_at = now_rfc3339()
|
|
220
|
+
self._t0 = time.perf_counter()
|
|
221
|
+
self._frozen = None
|
|
222
|
+
|
|
223
|
+
def freeze_clock(self) -> None:
|
|
224
|
+
"""Fix ``latency_ms``/``ended_at`` now; used when the response is complete
|
|
225
|
+
before the caller gets around to reading it (raw responses)."""
|
|
226
|
+
self._frozen = (self.elapsed_ms(), now_rfc3339())
|
|
227
|
+
|
|
228
|
+
def elapsed_ms(self) -> float:
|
|
229
|
+
if self._frozen is not None:
|
|
230
|
+
return self._frozen[0]
|
|
231
|
+
return round((time.perf_counter() - self._t0) * 1000, 3)
|
|
232
|
+
|
|
233
|
+
def _claim(self) -> bool:
|
|
234
|
+
with self._lock:
|
|
235
|
+
if self._done:
|
|
236
|
+
return False
|
|
237
|
+
self._done = True
|
|
238
|
+
return True
|
|
239
|
+
|
|
240
|
+
def finish(
|
|
241
|
+
self,
|
|
242
|
+
response: Response | None,
|
|
243
|
+
usage: Usage | None = None,
|
|
244
|
+
*,
|
|
245
|
+
response_model: str | None = None,
|
|
246
|
+
attributes: Mapping[str, Any] | None = None,
|
|
247
|
+
) -> None:
|
|
248
|
+
if not self._claim():
|
|
249
|
+
return
|
|
250
|
+
self._emit(response, usage or Usage(), None, response_model, attributes)
|
|
251
|
+
|
|
252
|
+
def fail(self, exc: BaseException, *, partial: Response | None = None, usage: Usage | None = None) -> None:
|
|
253
|
+
if not self._claim():
|
|
254
|
+
return
|
|
255
|
+
attrs: dict[str, Any] = {}
|
|
256
|
+
status = getattr(exc, "status_code", None)
|
|
257
|
+
if isinstance(status, int):
|
|
258
|
+
attrs[ATTR_ERROR_STATUS] = status
|
|
259
|
+
try:
|
|
260
|
+
message = str(exc)
|
|
261
|
+
except Exception:
|
|
262
|
+
message = "<unprintable error>"
|
|
263
|
+
self._emit(partial, usage or Usage(), SpanError(type=type(exc).__name__, message=message), None, attrs)
|
|
264
|
+
|
|
265
|
+
def _emit(
|
|
266
|
+
self,
|
|
267
|
+
response: Response | None,
|
|
268
|
+
usage: Usage,
|
|
269
|
+
error: SpanError | None,
|
|
270
|
+
response_model: str | None,
|
|
271
|
+
extra: Mapping[str, Any] | None,
|
|
272
|
+
) -> None:
|
|
273
|
+
# The call's own timing is taken now; with a shadow call still running the span is
|
|
274
|
+
# built and exported when it ends (the route attributes are read then).
|
|
275
|
+
try:
|
|
276
|
+
latency = self.elapsed_ms()
|
|
277
|
+
ended_at = self._frozen[1] if self._frozen is not None else now_rfc3339()
|
|
278
|
+
except Exception as exc: # pragma: no cover - clock reads do not raise
|
|
279
|
+
warn_limited.warning("span-build", "hiro: could not build span: %s", exc)
|
|
280
|
+
return
|
|
281
|
+
|
|
282
|
+
def build() -> None:
|
|
283
|
+
self._build(response, usage, error, response_model, extra, latency, ended_at)
|
|
284
|
+
|
|
285
|
+
if self.route is None:
|
|
286
|
+
build()
|
|
287
|
+
return
|
|
288
|
+
try:
|
|
289
|
+
self.route.when_settled(build)
|
|
290
|
+
except Exception as exc: # pragma: no cover - when_settled only takes a lock
|
|
291
|
+
logger.debug("hiro: shadow wait failed: %s", exc)
|
|
292
|
+
build()
|
|
293
|
+
|
|
294
|
+
def _build(
|
|
295
|
+
self,
|
|
296
|
+
response: Response | None,
|
|
297
|
+
usage: Usage,
|
|
298
|
+
error: SpanError | None,
|
|
299
|
+
response_model: str | None,
|
|
300
|
+
extra: Mapping[str, Any] | None,
|
|
301
|
+
latency: float,
|
|
302
|
+
ended_at: str,
|
|
303
|
+
) -> None:
|
|
304
|
+
try:
|
|
305
|
+
attrs = dict(self.attributes)
|
|
306
|
+
attrs.update(extra or {})
|
|
307
|
+
small = False
|
|
308
|
+
if self.route is not None:
|
|
309
|
+
attrs.update(route_attributes(self.route))
|
|
310
|
+
small = attrs[ATTR_ROUTE] == ROUTE_SMALL
|
|
311
|
+
if small and self.route.small_model:
|
|
312
|
+
response_model = self.route.small_model
|
|
313
|
+
if small and error is None and usage == Usage() and self.route.small_usage:
|
|
314
|
+
usage = small_span_usage(self.provider, self.route.small_usage)
|
|
315
|
+
if response_model and response_model != self.model:
|
|
316
|
+
attrs[ATTR_RESPONSE_MODEL] = response_model
|
|
317
|
+
cost = None
|
|
318
|
+
if error is None:
|
|
319
|
+
# Local serving costs nothing per call (electricity is not counted).
|
|
320
|
+
cost = (
|
|
321
|
+
0.0 if small else pricing.estimate_cost(self.provider, self.model, usage, alt_model=response_model)
|
|
322
|
+
)
|
|
323
|
+
span = Span(
|
|
324
|
+
span_id=self.span_id or new_span_id(),
|
|
325
|
+
trace_id=self.ctx.trace_id,
|
|
326
|
+
parent_span_id=self.ctx.parent_span_id,
|
|
327
|
+
step_key=self.step_key,
|
|
328
|
+
step_name=self.ctx.step_name,
|
|
329
|
+
provider=self.provider,
|
|
330
|
+
model=self.model,
|
|
331
|
+
request=self.request,
|
|
332
|
+
response=response,
|
|
333
|
+
usage=usage,
|
|
334
|
+
latency_ms=latency,
|
|
335
|
+
cost_usd=cost,
|
|
336
|
+
started_at=self.started_at,
|
|
337
|
+
ended_at=ended_at,
|
|
338
|
+
status="error" if error is not None else "ok",
|
|
339
|
+
error=error,
|
|
340
|
+
attributes=attrs,
|
|
341
|
+
)
|
|
342
|
+
except Exception as exc:
|
|
343
|
+
warn_limited.warning("span-build", "hiro: could not build span: %s", exc)
|
|
344
|
+
return
|
|
345
|
+
exporters.emit(span)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
class Accumulator(Protocol):
|
|
349
|
+
"""Rebuilds a response from stream items (provider specific)."""
|
|
350
|
+
|
|
351
|
+
def add(self, item: Any) -> bool:
|
|
352
|
+
"""Fold ``item`` in; return True if it carried output content (text,
|
|
353
|
+
thinking or tool-call deltas). The first such item sets ``hiro.ttft_ms``."""
|
|
354
|
+
...
|
|
355
|
+
|
|
356
|
+
def result(self) -> tuple[Response, Usage, str | None]: ...
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
class _StreamState:
|
|
360
|
+
"""Shared by the wrapped iterator, ``close`` and the GC finalizer; holds no ref to the stream."""
|
|
361
|
+
|
|
362
|
+
def __init__(self, record: CallRecord, acc: Accumulator) -> None:
|
|
363
|
+
self.record = record
|
|
364
|
+
self.acc = acc
|
|
365
|
+
self.ttft_ms: float | None = None
|
|
366
|
+
self.broken = False
|
|
367
|
+
|
|
368
|
+
def on_item(self, item: Any) -> None:
|
|
369
|
+
if self.broken:
|
|
370
|
+
return
|
|
371
|
+
try:
|
|
372
|
+
if self.acc.add(item) and self.ttft_ms is None:
|
|
373
|
+
self.ttft_ms = self.record.elapsed_ms()
|
|
374
|
+
except Exception as exc:
|
|
375
|
+
self.broken = True
|
|
376
|
+
logger.debug("hiro: stream accumulator failed: %s", exc)
|
|
377
|
+
|
|
378
|
+
def _attrs(self, incomplete: bool) -> dict[str, Any]:
|
|
379
|
+
attrs: dict[str, Any] = {ATTR_STREAM: True}
|
|
380
|
+
if self.ttft_ms is not None:
|
|
381
|
+
attrs[ATTR_TTFT_MS] = self.ttft_ms
|
|
382
|
+
if incomplete:
|
|
383
|
+
attrs[ATTR_STREAM_INCOMPLETE] = True
|
|
384
|
+
return attrs
|
|
385
|
+
|
|
386
|
+
def _result(self) -> tuple[Response | None, Usage, str | None]:
|
|
387
|
+
try:
|
|
388
|
+
return self.acc.result()
|
|
389
|
+
except Exception as exc:
|
|
390
|
+
logger.debug("hiro: stream result failed: %s", exc)
|
|
391
|
+
return None, Usage(), None
|
|
392
|
+
|
|
393
|
+
def done(self, incomplete: bool = False) -> None:
|
|
394
|
+
try:
|
|
395
|
+
response, usage, model = self._result()
|
|
396
|
+
self.record.finish(response, usage, response_model=model, attributes=self._attrs(incomplete))
|
|
397
|
+
except Exception: # pragma: no cover - finish never raises
|
|
398
|
+
pass
|
|
399
|
+
|
|
400
|
+
def error(self, exc: BaseException) -> None:
|
|
401
|
+
try:
|
|
402
|
+
response, usage, _ = self._result()
|
|
403
|
+
self.record.attributes.update(self._attrs(False))
|
|
404
|
+
self.record.fail(exc, partial=response, usage=usage)
|
|
405
|
+
except Exception: # pragma: no cover
|
|
406
|
+
pass
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _patch_close(stream: Any, state: _StreamState, is_async: bool) -> None:
|
|
410
|
+
orig_close: Callable[[], Any] | None = getattr(stream, "close", None)
|
|
411
|
+
if orig_close is None:
|
|
412
|
+
return
|
|
413
|
+
if is_async:
|
|
414
|
+
|
|
415
|
+
async def aclose() -> None:
|
|
416
|
+
try:
|
|
417
|
+
await orig_close()
|
|
418
|
+
finally:
|
|
419
|
+
state.done(incomplete=True)
|
|
420
|
+
|
|
421
|
+
stream.close = aclose
|
|
422
|
+
else:
|
|
423
|
+
|
|
424
|
+
def close() -> None:
|
|
425
|
+
try:
|
|
426
|
+
orig_close()
|
|
427
|
+
finally:
|
|
428
|
+
state.done(incomplete=True)
|
|
429
|
+
|
|
430
|
+
stream.close = close
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def instrument_stream(stream: Any, record: CallRecord, acc: Accumulator, *, is_async: bool) -> Any:
|
|
434
|
+
"""Make ``stream`` (an openai/anthropic ``Stream`` or ``AsyncStream``) record ``record`` as it is consumed.
|
|
435
|
+
|
|
436
|
+
The same object is returned: items reach the user unchanged. The span is
|
|
437
|
+
emitted when the stream ends, errors, is closed early, or is garbage
|
|
438
|
+
collected unconsumed (then ``hiro.stream.incomplete`` is set).
|
|
439
|
+
"""
|
|
440
|
+
state = _StreamState(record, acc)
|
|
441
|
+
try:
|
|
442
|
+
orig_iter = stream._iterator
|
|
443
|
+
except Exception:
|
|
444
|
+
orig_iter = None
|
|
445
|
+
if orig_iter is None:
|
|
446
|
+
state.done(incomplete=True)
|
|
447
|
+
return stream
|
|
448
|
+
|
|
449
|
+
if is_async:
|
|
450
|
+
|
|
451
|
+
async def agen() -> Any:
|
|
452
|
+
try:
|
|
453
|
+
async for item in orig_iter:
|
|
454
|
+
state.on_item(item)
|
|
455
|
+
yield item
|
|
456
|
+
except GeneratorExit:
|
|
457
|
+
state.done(incomplete=True)
|
|
458
|
+
raise
|
|
459
|
+
except BaseException as exc:
|
|
460
|
+
state.error(exc)
|
|
461
|
+
raise
|
|
462
|
+
state.done()
|
|
463
|
+
|
|
464
|
+
wrapped: Any = agen()
|
|
465
|
+
else:
|
|
466
|
+
|
|
467
|
+
def gen() -> Any:
|
|
468
|
+
try:
|
|
469
|
+
for item in orig_iter:
|
|
470
|
+
state.on_item(item)
|
|
471
|
+
yield item
|
|
472
|
+
except GeneratorExit:
|
|
473
|
+
state.done(incomplete=True)
|
|
474
|
+
raise
|
|
475
|
+
except BaseException as exc:
|
|
476
|
+
state.error(exc)
|
|
477
|
+
raise
|
|
478
|
+
state.done()
|
|
479
|
+
|
|
480
|
+
wrapped = gen()
|
|
481
|
+
try:
|
|
482
|
+
stream._iterator = wrapped
|
|
483
|
+
_patch_close(stream, state, is_async)
|
|
484
|
+
fin = weakref.finalize(stream, state.done, True)
|
|
485
|
+
fin.atexit = False
|
|
486
|
+
except Exception as exc:
|
|
487
|
+
warn_limited.warning("stream-patch", "hiro: cannot instrument stream: %s", exc)
|
|
488
|
+
state.done(incomplete=True)
|
|
489
|
+
return stream
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def instrument_raw_response(
|
|
493
|
+
raw: Any,
|
|
494
|
+
record: CallRecord,
|
|
495
|
+
on_parsed: Callable[[Any], Any],
|
|
496
|
+
*,
|
|
497
|
+
freeze: bool,
|
|
498
|
+
) -> Any:
|
|
499
|
+
"""Record ``record`` from a ``with_raw_response`` / ``with_streaming_response`` result.
|
|
500
|
+
|
|
501
|
+
``raw`` is the provider's HTTP response wrapper; the parsed value is only
|
|
502
|
+
known once the caller calls ``raw.parse()``. That method is patched on the
|
|
503
|
+
instance: the first default ``parse()`` (no ``to=``) hands its result to
|
|
504
|
+
``on_parsed`` (which records it, or instruments it when it is a stream) and
|
|
505
|
+
returns what ``on_parsed`` returns. The provider caches ``parse()`` results,
|
|
506
|
+
so later calls return the same object. If the response is closed or
|
|
507
|
+
garbage collected without a default ``parse()``, a span without a response
|
|
508
|
+
is emitted with ``hiro.raw_response.unparsed``. With ``freeze`` the latency
|
|
509
|
+
is taken now (the body is already read), not when the caller parses.
|
|
510
|
+
"""
|
|
511
|
+
if freeze:
|
|
512
|
+
record.freeze_clock()
|
|
513
|
+
lock = threading.Lock()
|
|
514
|
+
handled = [False]
|
|
515
|
+
|
|
516
|
+
def claim() -> bool:
|
|
517
|
+
with lock:
|
|
518
|
+
if handled[0]:
|
|
519
|
+
return False
|
|
520
|
+
handled[0] = True
|
|
521
|
+
return True
|
|
522
|
+
|
|
523
|
+
def unparsed() -> None:
|
|
524
|
+
if claim():
|
|
525
|
+
record.finish(None, attributes={ATTR_RAW_UNPARSED: True})
|
|
526
|
+
|
|
527
|
+
def done(result: Any) -> Any:
|
|
528
|
+
try:
|
|
529
|
+
return on_parsed(result)
|
|
530
|
+
except Exception as exc: # pragma: no cover - on_parsed is defensive
|
|
531
|
+
logger.debug("hiro: raw response record failed: %s", exc)
|
|
532
|
+
return result
|
|
533
|
+
|
|
534
|
+
try:
|
|
535
|
+
orig_parse = raw.parse
|
|
536
|
+
orig_close = getattr(raw, "close", None)
|
|
537
|
+
except Exception:
|
|
538
|
+
unparsed()
|
|
539
|
+
return raw
|
|
540
|
+
|
|
541
|
+
def is_default(args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> bool:
|
|
542
|
+
return not args and kwargs.get("to") is None
|
|
543
|
+
|
|
544
|
+
if inspect.iscoroutinefunction(orig_parse):
|
|
545
|
+
|
|
546
|
+
async def aparse(*args: Any, **kwargs: Any) -> Any:
|
|
547
|
+
default = is_default(args, kwargs)
|
|
548
|
+
try:
|
|
549
|
+
result = await orig_parse(*args, **kwargs)
|
|
550
|
+
except BaseException as exc:
|
|
551
|
+
if default and claim():
|
|
552
|
+
record.fail(exc)
|
|
553
|
+
raise
|
|
554
|
+
return done(result) if default and claim() else result
|
|
555
|
+
|
|
556
|
+
parse: Any = aparse
|
|
557
|
+
else:
|
|
558
|
+
|
|
559
|
+
def sparse(*args: Any, **kwargs: Any) -> Any:
|
|
560
|
+
default = is_default(args, kwargs)
|
|
561
|
+
try:
|
|
562
|
+
result = orig_parse(*args, **kwargs)
|
|
563
|
+
except BaseException as exc:
|
|
564
|
+
if default and claim():
|
|
565
|
+
record.fail(exc)
|
|
566
|
+
raise
|
|
567
|
+
return done(result) if default and claim() else result
|
|
568
|
+
|
|
569
|
+
parse = sparse
|
|
570
|
+
|
|
571
|
+
try:
|
|
572
|
+
raw.parse = parse
|
|
573
|
+
if orig_close is not None:
|
|
574
|
+
if inspect.iscoroutinefunction(orig_close):
|
|
575
|
+
|
|
576
|
+
async def aclose() -> None:
|
|
577
|
+
try:
|
|
578
|
+
await orig_close()
|
|
579
|
+
finally:
|
|
580
|
+
unparsed()
|
|
581
|
+
|
|
582
|
+
raw.close = aclose
|
|
583
|
+
else:
|
|
584
|
+
|
|
585
|
+
def close() -> None:
|
|
586
|
+
try:
|
|
587
|
+
orig_close()
|
|
588
|
+
finally:
|
|
589
|
+
unparsed()
|
|
590
|
+
|
|
591
|
+
raw.close = close
|
|
592
|
+
fin = weakref.finalize(raw, unparsed)
|
|
593
|
+
fin.atexit = False
|
|
594
|
+
except Exception as exc:
|
|
595
|
+
warn_limited.warning("raw-patch", "hiro: cannot instrument raw response: %s", exc)
|
|
596
|
+
unparsed()
|
|
597
|
+
return raw
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
__all__ = [
|
|
601
|
+
"ATTR_API",
|
|
602
|
+
"ATTR_RAW_RESPONSE",
|
|
603
|
+
"ATTR_RAW_UNPARSED",
|
|
604
|
+
"ATTR_ROUTE",
|
|
605
|
+
"ATTR_ROUTE_BUFFERED",
|
|
606
|
+
"ATTR_ROUTE_CONFIG_ID",
|
|
607
|
+
"ATTR_ROUTE_GATE_MS",
|
|
608
|
+
"ATTR_ROUTE_ID",
|
|
609
|
+
"ATTR_ROUTE_MODE",
|
|
610
|
+
"ATTR_ROUTE_REASON",
|
|
611
|
+
"ATTR_ROUTE_SMALL_LATENCY_MS",
|
|
612
|
+
"ATTR_ROUTE_SMALL_RESPONSE",
|
|
613
|
+
"ATTR_ROUTE_SHADOW_ERROR",
|
|
614
|
+
"ATTR_ROUTE_SHADOW_GATE",
|
|
615
|
+
"ATTR_ROUTE_SHADOW_LATENCY_MS",
|
|
616
|
+
"ATTR_ROUTE_SHADOW_RESPONSE",
|
|
617
|
+
"ATTR_ROUTE_SHADOW_USAGE",
|
|
618
|
+
"ATTR_ROUTE_SMALL_USAGE",
|
|
619
|
+
"ATTR_STREAM",
|
|
620
|
+
"ATTR_STREAM_INCOMPLETE",
|
|
621
|
+
"ATTR_TTFT_MS",
|
|
622
|
+
"Accumulator",
|
|
623
|
+
"CallRecord",
|
|
624
|
+
"helper_method",
|
|
625
|
+
"instrument_raw_response",
|
|
626
|
+
"instrument_stream",
|
|
627
|
+
"is_raw_response_call",
|
|
628
|
+
"materialize",
|
|
629
|
+
"params_from",
|
|
630
|
+
"raw_response_mode",
|
|
631
|
+
"route_attributes",
|
|
632
|
+
"small_span_usage",
|
|
633
|
+
]
|