Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

otel.md

279 lines15.0 KB

1---
2title: OpenTelemetry
3id: otel
4order: 3
5description: "Emit vendor-neutral OpenTelemetry traces and metrics from every TanStack AI chat() call, following the OTel GenAI semantic conventions."
6keywords:
7 - tanstack ai
8 - opentelemetry
9 - otel
10 - observability
11 - tracing
12 - metrics
13 - gen_ai
14 - semantic conventions
15---
16​
17The `otelMiddleware` factory wires TanStack AI into your existing OpenTelemetry setup. Every `chat()` call produces a root span, one child span per provider model call (agent-loop turn **or** structured-output finalization), and one grandchild span per tool call — all with [GenAI semantic-convention attributes](https://opentelemetry.io/docs/specs/semconv/gen-ai/). It also records GenAI token and duration histograms when a `Meter` is provided.
18​
19Structured-output calls with no tools skip the agent loop and only run the finalization request. That path still opens an iteration span (via the `structuredOutput` middleware phase) so backends that key off generation spans (e.g. PostHog `$ai_generation`) and `captureContent` both work. Native combined mode (`supportsCombinedToolsAndSchema`) does not fire that phase — the single `beforeModel` span covers the combined call.
20​
21## Setup
22​
23Install `@opentelemetry/api` — it's an optional peer dependency of `@tanstack/ai`:
24​
25<!-- ::start:tabs variant="package-manager" mode="install" -->
26​
27react: @opentelemetry/api
28vue: @opentelemetry/api
29solid: @opentelemetry/api
30svelte: @opentelemetry/api
31preact: @opentelemetry/api
32angular: @opentelemetry/api
33vanilla: @opentelemetry/api
34octane: @opentelemetry/api
35​
36<!-- ::end:tabs -->
37​
38Wire up your OTel SDK however you already do (e.g. `@opentelemetry/sdk-node`). Then pass a `Tracer` (and optionally a `Meter`) into the middleware. The OTel middleware lives on its own subpath — importing it never affects users who don't need OTel:
39​
40```ts
41import { chat } from '@tanstack/ai'
42import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
43import { openaiText } from '@tanstack/ai-openai'
44import { trace, metrics } from '@opentelemetry/api'
45​
46const otel = otelMiddleware({
47 tracer: trace.getTracer('my-app'),
48 meter: metrics.getMeter('my-app'),
49})
50​
51const result = await chat({
52 adapter: openaiText('gpt-5.5'),
53 messages: [{ role: 'user', content: 'hi' }],
54 middleware: [otel],
55 stream: false,
56})
57```
58​
59## What gets emitted
60​
61### Spans
62​
63```text
64chat gpt-5.5 (root, kind: INTERNAL)
65├── chat gpt-5.5 #0 (iteration, kind: CLIENT)
66│ ├── execute_tool get_weather
67│ └── execute_tool get_time
68└── chat gpt-5.5 #1 (iteration, kind: CLIENT)
69```
70​
71Iteration spans are numbered (`#0`, `#1`, ...) in the order model calls are observed, so distinct provider round-trips of the same chat are easy to pick apart in trace viewers.
72​
73### Attribute reference
74​
75| Level | Attribute | Value |
76| --- | --- | --- |
77| root / iteration | `gen_ai.system` | `openai`, `anthropic`, ... |
78| iteration | `gen_ai.operation.name` | `chat` |
79| root / iteration | `gen_ai.request.model` | requested model |
80| iteration | `gen_ai.response.model` | actual model |
81| iteration | `gen_ai.request.temperature` | from config |
82| iteration | `gen_ai.request.top_p` | from config |
83| iteration | `gen_ai.request.max_tokens` | from config |
84| iteration | `gen_ai.usage.input_tokens` | per iteration |
85| iteration | `gen_ai.usage.output_tokens` | per iteration |
86| root / iteration | `gen_ai.usage.total_tokens` | provider-reported total |
87| root / iteration | `gen_ai.usage.cost` | provider-reported cost, when available |
88| root / iteration | `gen_ai.usage.cache_read.input_tokens` | cached prompt tokens, when reported |
89| root / iteration | `gen_ai.usage.cache_creation.input_tokens` | cache-write prompt tokens, when reported |
90| root / iteration | `gen_ai.usage.reasoning.output_tokens` | reasoning/thinking tokens, when reported |
91| root / iteration | `tanstack.ai.usage.billed_quantity` | non-token billed quantity, when reported |
92| root / iteration | `tanstack.ai.usage.billed_unit` | unit of the billed quantity (`seconds`, `units`, ...) |
93| root / iteration | `tanstack.ai.usage.duration_seconds` | deprecated duration count; read `billed_quantity`/`billed_unit` instead |
94| root / iteration | `tanstack.ai.usage.units_billed` | deprecated bare unit count; read `billed_quantity`/`billed_unit` instead |
95| root / iteration | `tanstack.ai.usage.upstream_cost` | gateway upstream cost (e.g. OpenRouter), when reported |
96| root / iteration | `tanstack.ai.usage.upstream_input_cost` | upstream input cost split, when reported |
97| root / iteration | `tanstack.ai.usage.upstream_output_cost` | upstream output cost split, when reported |
98| iteration | `gen_ai.response.finish_reasons` | `[stop]`, `[tool_calls]`, ... |
99| root | `gen_ai.usage.input_tokens` | rolled up |
100| root | `gen_ai.usage.output_tokens` | rolled up |
101| root | `tanstack.ai.iterations` | iteration count |
102| tool | `gen_ai.tool.name` | tool name |
103| tool | `gen_ai.tool.call.id` | tool call id |
104| tool | `gen_ai.tool.type` | `function` |
105| tool | `tanstack.ai.tool.outcome` | `success` / `error` |
106​
107Usage attributes beyond input/output tokens are emitted only when the provider reports them, so spans stay clean otherwise. Cache and reasoning breakdowns use the official GenAI semconv names; `gen_ai.usage.cost` and `gen_ai.usage.total_tokens` are de-facto extensions consumed directly by backends like PostHog — without them, backends re-derive cost from their own price tables and lose cache discounts and gateway markup. Fields with no established convention (the billed quantity/unit pair, the upstream cost split, and the deprecated bare counts) are TanStack-namespaced.
108​
109For non-token billing (seconds of video or transcription, fal's endpoint units, ...), `tanstack.ai.usage.billed_quantity` and `tanstack.ai.usage.billed_unit` are emitted as a pair from `usage.billed`, so backends can label and aggregate media usage without knowing the provider. The deprecated `duration_seconds` / `units_billed` attributes carry the same quantities without the unit and remain emitted for backward compatibility.
110​
111### Metrics
112​
113Two GenAI-standard histograms:
114​
115- `gen_ai.client.operation.duration` (seconds) — recorded **once per `chat()` call**, covering all agent-loop iterations and tool execution. On error or abort the record carries an `error.type` attribute (the thrown error's `name`, or `"cancelled"` for aborts).
116- `gen_ai.client.token.usage` (tokens) — recorded **once per iteration** (two records: input and output), tagged with `gen_ai.token.type`.
117​
118Both `gen_ai.response.id` and `gen_ai.response.model` are deliberately excluded from metric attributes to keep cardinality low (per-request custom-model names and request IDs would blow up the series set).
119​
120## Privacy: capturing prompts and completions
121​
122By default, only metadata lands on spans. To record prompt and completion content, set `captureContent: true`. Content is captured as OTel span events following the GenAI convention:
123​
124- `gen_ai.user.message`, `gen_ai.system.message`, `gen_ai.assistant.message`, `gen_ai.tool.message`, `gen_ai.choice`
125​
126Pass a `redact` function to strip PII before anything is recorded:
127​
128```ts
129import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
130import { trace } from '@opentelemetry/api'
131​
132const tracer = trace.getTracer('my-app')
133​
134otelMiddleware({
135 tracer,
136 captureContent: true,
137 redact: (text) => text.replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[SSN]'),
138})
139```
140​
141If `redact` throws, the middleware writes the literal sentinel `"[redaction_failed]"` into the span event and logs a warning — it never falls back to the raw content. This is the load-bearing invariant for users who ship traces to third-party backends: a broken redactor should shut off capture, not leak prompts.
142​
143Accumulated assistant text (the `gen_ai.choice` event) is capped at `maxContentLength` characters (default `100 000`); longer completions are truncated with a trailing `"…"` marker.
144​
145Multimodal messages (images, audio, video, documents) keep their parts in `gen_ai.input.messages`, in the OTel GenAI part shapes:
146​
147- Text: `{ "type": "text", "content": "..." }`. `redact` runs on it.
148- URL source: `{ "type": "uri", "modality": "image", "uri": "https://...", "mime_type": "image/png" }`.
149- Provider file handle: `{ "type": "file", "modality": "image", "file_id": "..." }`.
150- Inline base64 data or a `data:` URL: a `[image]` text placeholder, so the bytes do not go onto the span.
151​
152Span events stay flat strings, with the same placeholders for every media part (`look at this [image]`).
153​
154Prompt/system/user message events fire from `onConfig` at the start of every iteration, which means the full conversation history (as the adapter will re-send it) is re-emitted on each iteration span. This mirrors what the provider actually sees on the wire.
155​
156## Extension points
157​
158All four extensions are optional. Each wraps user code in try/catch — a thrown callback becomes a log line, never a broken chat.
159​
160### `spanNameFormatter(info)`
161​
162Override default span names. `info.kind` is `'chat' | 'iteration' | 'tool'`.
163​
164```ts
165import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
166import { trace } from '@opentelemetry/api'
167​
168const tracer = trace.getTracer('my-app')
169​
170otelMiddleware({
171 tracer,
172 spanNameFormatter: (info) =>
173 info.kind === 'tool' ? `tool:${info.toolName}` : `chat:${info.ctx.model}`,
174})
175```
176​
177### `attributeEnricher(info)`
178​
179Add custom attributes to every span. Fires once per span.
180​
181```ts
182import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
183import { trace } from '@opentelemetry/api'
184import { getCurrentTenant } from './context'
185​
186const tracer = trace.getTracer('my-app')
187​
188otelMiddleware({
189 tracer,
190 attributeEnricher: () => ({
191 'tenant.id': getCurrentTenant(),
192 }),
193})
194```
195​
196### `onBeforeSpanStart(info, options)`
197​
198Mutate `SpanOptions` immediately before `tracer.startSpan(...)`. Useful for adding links, custom start times, or extra default attributes.
199​
200### `onSpanEnd(info, span)`
201​
202Fires just before every `span.end()`. Common uses: record custom events, emit per-tool metrics via your own `Meter`.
203​
204```ts
205import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
206import { trace, metrics } from '@opentelemetry/api'
207​
208const tracer = trace.getTracer('my-app')
209const meter = metrics.getMeter('my-app')
210​
211const toolDuration = meter.createHistogram('tool.duration')
212otelMiddleware({
213 tracer,
214 onSpanEnd: (info, span) => {
215 if (info.kind === 'tool') {
216 // span is still recording; read timestamps from your own store if needed
217 toolDuration.record(1, { 'tool.name': info.toolName })
218 }
219 },
220})
221```
222​
223## Beyond chat: media activities
224​
225`otelMiddleware` is not chat-only. The media activities (`generateImage`, `generateVideo`, `generateLiveVideo`, `generateWorld`, `generateAudio`, `generateSpeech`, and `generateTranscription`) accept the **same** `otelMiddleware` value on their `middleware` option. Each is a single request to response (or submit then poll for video), so the middleware emits one span per call instead of the chat span tree:
226​
227```ts
228import { generateImage } from '@tanstack/ai'
229import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
230import { openaiImage } from '@tanstack/ai-openai'
231import { trace, metrics } from '@opentelemetry/api'
232​
233const otel = otelMiddleware({
234 tracer: trace.getTracer('my-app'),
235 meter: metrics.getMeter('my-app'),
236})
237​
238const result = await generateImage({
239 adapter: openaiImage('gpt-image-2'),
240 prompt: 'A serene mountain landscape at sunset',
241 middleware: [otel],
242})
243```
244​
245You can pass the same `otel` value to `chat()`, `decide()`, and any media activity. Its shared lifecycle hooks (`onStart` / `onUsage` / `onFinish` / `onAbort` / `onError`) are authored against the activity-agnostic `GenerationMiddlewareContext`, so the one instance works everywhere.
246​
247Each media call produces one `CLIENT` span tagged with the activity's `gen_ai.operation.name`:
248​
249| Activity | `gen_ai.operation.name` |
250| --- | --- |
251| `generateImage` | `image_generation` |
252| `generateVideo` | `video_generation` |
253| `generateAudio` | `audio_generation` |
254| `generateSpeech` | `text_to_speech` |
255| `generateTranscription` | `transcription` |
256| `generateWorld` | `world_generation` |
257| `generateLiveVideo` | `live_video_generation` |
258| `summarize` | `summarize` |
259| `decide` | `evaluate` |
260​
261The span carries `gen_ai.system` and `gen_ai.request.model` at start and, on finish, the same `gen_ai.usage.*` / `tanstack.ai.usage.*` attributes documented above — including the `tanstack.ai.usage.billed_quantity` / `tanstack.ai.usage.billed_unit` pair for unit-billed media. When a `Meter` is supplied it records the `gen_ai.client.operation.duration` histogram, tagged per activity. For streaming video the span covers the full create → poll → complete lifecycle. Non-streaming video is two calls, so the submit itself emits no span — the run opens once the provider accepts the job, and the `getVideoJobStatus()` poll that observes a terminal state ends it. If a streaming video consumer abandons the stream before completion, the span is ended via `onAbort` (status `ERROR`, `tanstack.ai.completion.reason = cancelled`) rather than leaked.
262​
263`otelMiddleware` applies the same `spanNameFormatter`, `attributeEnricher`, `onBeforeSpanStart`, and `onSpanEnd` extension points to media spans — the span info is discriminated by `kind`, where media spans report `kind: 'generation'`. For a custom backend, implement the base `GenerationMiddleware` contract directly; its hooks (`onStart` / `onUsage` / `onFinish` / `onAbort` / `onError`) receive the `GenerationMiddlewareContext` and fire for every activity, chat included. The `GenerationMiddleware` types are exported from the package root, while the `otelMiddleware` value lives on the `@tanstack/ai/middlewares/otel` subpath so importing `@tanstack/ai` never requires the optional `@opentelemetry/api` peer.
264​
265### Capturing media content
266​
267Set `captureContent: true` to record what a media call was asked for and what came back. The media span then gets the same attributes as a chat iteration span:
268​
269- `gen_ai.input.messages` and `langfuse.observation.input`: one `user` message. It holds the prompt as a text part and each input image, video, or audio as a part. For `generateSpeech` it holds the text to speak. For `generateTranscription` it holds the source audio.
270- `gen_ai.output.messages` and `langfuse.observation.output`: one `assistant` message. It holds each generated image, audio, or video URL as a `uri` part. For `generateTranscription` it holds the transcript as a text part.
271​
272Media parts use the part shapes from [Privacy: capturing prompts and completions](#privacy-capturing-prompts-and-completions). A URL becomes `{ "type": "uri", "modality": "image", "uri": "https://..." }`. Inline data never goes onto the span. Base64 output, a `data:` URL, a `File`, or a `Blob` becomes a text placeholder such as `[image]`. `redact` and `maxContentLength` apply to each text part.
273​
274For non-streaming video, the `getVideoJobStatus()` span has the output URL but not the prompt. Use `generateVideo({ stream: true })` to get both on one span.
275​
276## Related
277​
278- [Middleware](./middleware) — the lifecycle this middleware hooks into
279- [Debug Logging](./debug-logging) — quick console-output diagnostics, complementary to OTel