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

otel.md

334 lines15.0 KB

1---
2title: OpenTelemetry
3id: otel
4order: 3
5description: "Send OpenTelemetry traces and metrics from every TanStack AI chat() call and media call. The spans follow 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 OpenTelemetry middleware records the model, token counts, and tool time on your existing traces.
18​
19Add `otelMiddleware` to your `chat()` call. Each call then sends spans and metrics with the [GenAI semantic-convention attributes](https://opentelemetry.io/docs/specs/semconv/gen-ai/).
20​
21## Quick setup
22​
23### 1. Install the OpenTelemetry API
24​
25`@opentelemetry/api` is an optional peer dependency of `@tanstack/ai`:
26​
27<!-- ::start:tabs variant="package-manager" mode="install" -->
28​
29react: @opentelemetry/api
30vue: @opentelemetry/api
31solid: @opentelemetry/api
32svelte: @opentelemetry/api
33preact: @opentelemetry/api
34angular: @opentelemetry/api
35vanilla: @opentelemetry/api
36octane: @opentelemetry/api
37​
38<!-- ::end:tabs -->
39​
40### 2. Start your OpenTelemetry SDK
41​
42Start the SDK the way your app already does, for example with `@opentelemetry/sdk-node`. The middleware uses the `Tracer` and `Meter` that you give it.
43​
44### 3. Add the middleware to `chat()`
45​
46```ts
47import { chat } from '@tanstack/ai'
48import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
49import { openaiText } from '@tanstack/ai-openai'
50import { trace, metrics } from '@opentelemetry/api'
51​
52const otel = otelMiddleware({
53 tracer: trace.getTracer('my-app'),
54 meter: metrics.getMeter('my-app'),
55})
56​
57const { text } = await chat({
58 adapter: openaiText('gpt-6.1-sol'),
59 messages: [{ role: 'user', content: 'hi' }],
60 threadId: 'thread-1',
61 middleware: [otel],
62 stream: false,
63})
64```
65​
66The middleware lives on its own subpath. Apps that do not import it do not need `@opentelemetry/api`.
67​
68Open your trace viewer. Each `chat()` call now shows as one span tree, with the model, the token counts, and each tool call.
69​
70## How it works
71​
72Each `chat()` call makes a span tree:
73​
74```text
75chat gpt-6.1-sol (root, kind: INTERNAL)
76├── chat gpt-6.1-sol #0 (iteration, kind: CLIENT)
77│ ├── execute_tool get_weather
78│ └── execute_tool get_time
79└── chat gpt-6.1-sol #1 (iteration, kind: CLIENT)
80```
81​
82- The **root span** covers the whole `chat()` call.
83- Each **iteration span** is one model call: one turn of the agent loop, or the final structured-output request. The spans are numbered (`#0`, `#1`) in the order of the model calls.
84- Each **tool span** is one tool call.
85​
86When you give a `Meter`, the middleware also records two token and duration histograms. See [Metrics](#metrics).
87​
88By default, only metadata goes onto the spans. Prompts and answers stay off until you turn them on.
89​
90## Capture prompts and completions
91​
92Set `captureContent: true` to record prompt and answer content. Pass a `redact` function to remove personal data before anything is recorded:
93​
94```ts
95import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
96import { trace } from '@opentelemetry/api'
97​
98const tracer = trace.getTracer('my-app')
99​
100otelMiddleware({
101 tracer,
102 captureContent: true,
103 redact: (text) => text.replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[SSN]'),
104})
105```
106​
107If `redact` throws, the middleware writes the text `"[redaction_failed]"` into the span event and logs a warning. It never falls back to the raw content. So a broken redactor stops the capture, and no prompt leaks to a third-party backend.
108​
109For the event names, the length limit, and media parts, see [Content capture details](#content-capture-details).
110​
111## Trace media calls
112​
113The media activities accept the same `otelMiddleware` value on their `middleware` option:
114​
115```ts
116import { generateImage } from '@tanstack/ai'
117import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
118import { openaiImage } from '@tanstack/ai-openai'
119import { trace, metrics } from '@opentelemetry/api'
120​
121const otel = otelMiddleware({
122 tracer: trace.getTracer('my-app'),
123 meter: metrics.getMeter('my-app'),
124})
125​
126const result = await generateImage({
127 adapter: openaiImage('gpt-image-2'),
128 prompt: 'A serene mountain landscape at sunset',
129 threadId: 'thread-1',
130 middleware: [otel],
131})
132```
133​
134A media call is one request and one response (or a submit and a poll, for video). So it makes one `CLIENT` span, not a span tree. You can pass the same `otel` value to `chat()`, `decide()`, and any media activity.
135​
136## Advanced
137​
138### Span attributes
139​
140| Level | Attribute | Value |
141| --- | --- | --- |
142| root / iteration | `gen_ai.system` | `openai`, `anthropic`, ... |
143| iteration | `gen_ai.operation.name` | `chat` |
144| root / iteration | `gen_ai.request.model` | requested model |
145| iteration | `gen_ai.response.model` | actual model |
146| iteration | `gen_ai.request.temperature` | from config |
147| iteration | `gen_ai.request.top_p` | from config |
148| iteration | `gen_ai.request.max_tokens` | from config |
149| iteration | `gen_ai.usage.input_tokens` | per iteration |
150| iteration | `gen_ai.usage.output_tokens` | per iteration |
151| root / iteration | `gen_ai.usage.total_tokens` | total from the provider |
152| root / iteration | `gen_ai.usage.cost` | cost from the provider, when available |
153| root / iteration | `gen_ai.usage.cache_read.input_tokens` | cached prompt tokens, when reported |
154| root / iteration | `gen_ai.usage.cache_creation.input_tokens` | cache-write prompt tokens, when reported |
155| root / iteration | `gen_ai.usage.reasoning.output_tokens` | reasoning or thinking tokens, when reported |
156| root / iteration | `tanstack.ai.usage.billed_quantity` | billed quantity that is not tokens, when reported |
157| root / iteration | `tanstack.ai.usage.billed_unit` | unit of the billed quantity (`seconds`, `units`, ...) |
158| root / iteration | `tanstack.ai.usage.upstream_cost` | upstream cost of a gateway (for example OpenRouter), when reported |
159| root / iteration | `tanstack.ai.usage.upstream_input_cost` | upstream input cost, when reported |
160| root / iteration | `tanstack.ai.usage.upstream_output_cost` | upstream output cost, when reported |
161| iteration | `gen_ai.response.finish_reasons` | `[stop]`, `[tool_calls]`, ... |
162| root | `gen_ai.usage.input_tokens` | sum of all iterations |
163| root | `gen_ai.usage.output_tokens` | sum of all iterations |
164| root | `tanstack.ai.iterations` | iteration count |
165| tool | `gen_ai.tool.name` | tool name |
166| tool | `gen_ai.tool.call.id` | tool call id |
167| tool | `gen_ai.tool.type` | `function` |
168| tool | `tanstack.ai.tool.outcome` | `success` / `error` |
169​
170How the usage attributes work:
171​
172- Usage attributes other than input and output tokens appear only when the provider reports them.
173- The cache and reasoning attributes use the official GenAI semconv names.
174- `gen_ai.usage.cost` and `gen_ai.usage.total_tokens` are common extensions that backends like PostHog read. Without them, a backend calculates the cost from its own price table, and loses cache discounts and gateway markup.
175- Fields with no standard name (the billed quantity and unit, and the upstream cost split) use the `tanstack.ai` namespace.
176​
177For billing that is not in tokens (seconds of video or transcription, fal endpoint units), the middleware sends `tanstack.ai.usage.billed_quantity` and `tanstack.ai.usage.billed_unit` as a pair from `usage.billed`. Backends can then label and add up media usage without knowing the provider.
178​
179### Structured output spans
180​
181A structured-output call with no tools skips the agent loop and runs only the final request. That path still opens an iteration span, through the `structuredOutput` middleware phase. So backends that read generation spans (for example PostHog `$ai_generation`) and `captureContent` both work.
182​
183Native combined mode (`supportsCombinedToolsAndSchema`) does not run that phase. The single `beforeModel` span covers the combined call.
184​
185### Metrics
186​
187When you give a `Meter`, the middleware records two GenAI-standard histograms:
188​
189- `gen_ai.client.operation.duration` (seconds): recorded **once for each `chat()` call**. It covers all agent-loop iterations and tool calls. On an error or an abort, the record has an `error.type` attribute: the `name` of the thrown error, or `"cancelled"` for an abort.
190- `gen_ai.client.token.usage` (tokens): recorded **once for each iteration**, as two records (input and output), tagged with `gen_ai.token.type`.
191​
192The metric attributes do not include `gen_ai.response.id` and `gen_ai.response.model`. This keeps the number of series low, because request ids and custom model names change on each request.
193​
194### Content capture details
195​
196With `captureContent: true`, content goes onto the spans as OTel span events, with the GenAI names:
197​
198- `gen_ai.user.message`, `gen_ai.system.message`, `gen_ai.assistant.message`
199- `gen_ai.tool.message`, `gen_ai.choice`
200​
201Limits and timing:
202​
203- The assistant text (the `gen_ai.choice` event) is limited to `maxContentLength` characters. The default is 100,000. Longer text is cut and ends with `"…"`. Set `maxContentLength: 0` to remove the limit.
204- The prompt, system, and user events fire from `onConfig` at the start of each iteration. So each iteration span has the full history again, the same as the provider gets it.
205​
206Multimodal messages (images, audio, video, documents) keep their parts in `gen_ai.input.messages`, in the OTel GenAI part shapes:
207​
208- Text: `{ "type": "text", "content": "..." }`. `redact` runs on it.
209- URL source: `{ "type": "uri", "modality": "image", "uri": "https://...", "mime_type": "image/png" }`.
210- Provider file handle: `{ "type": "file", "modality": "image", "file_id": "..." }`.
211- Inline base64 data or a `data:` URL: a `[image]` text placeholder, so that the bytes do not go onto the span.
212​
213Span events stay flat strings, with the same placeholders for each media part (`look at this [image]`).
214​
215### Extension points
216​
217All four callbacks are optional. Each one runs inside a try/catch. A callback that throws makes a log line, and the chat continues.
218​
219| Callback | What it does |
220| --- | --- |
221| `spanNameFormatter(info)` | Returns the span name. `info.kind` is `'chat'`, `'iteration'`, `'tool'`, or `'generation'`. |
222| `attributeEnricher(info)` | Returns extra attributes for each span. Fires once for each span. |
223| `onBeforeSpanStart(info, options)` | Returns the `SpanOptions` for `tracer.startSpan(...)`. Use it to add links, custom start times, or default attributes. |
224| `onSpanEnd(info, span)` | Fires immediately before each `span.end()`. Use it to record custom events, or per-tool metrics with your own `Meter`. |
225​
226Change the span names:
227​
228```ts
229import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
230import { trace } from '@opentelemetry/api'
231​
232const tracer = trace.getTracer('my-app')
233​
234otelMiddleware({
235 tracer,
236 spanNameFormatter: (info) =>
237 info.kind === 'tool' ? `tool:${info.toolName}` : `chat:${info.ctx.model}`,
238})
239```
240​
241Add an attribute to each span:
242​
243```ts
244import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
245import { trace } from '@opentelemetry/api'
246import { getCurrentTenant } from './context'
247​
248const tracer = trace.getTracer('my-app')
249​
250otelMiddleware({
251 tracer,
252 attributeEnricher: () => ({
253 'tenant.id': getCurrentTenant(),
254 }),
255})
256```
257​
258Record a metric for each tool call:
259​
260```ts
261import { otelMiddleware } from '@tanstack/ai/middlewares/otel'
262import { trace, metrics } from '@opentelemetry/api'
263​
264const tracer = trace.getTracer('my-app')
265const meter = metrics.getMeter('my-app')
266​
267const toolDuration = meter.createHistogram('tool.duration')
268otelMiddleware({
269 tracer,
270 onSpanEnd: (info, span) => {
271 if (info.kind === 'tool') {
272 // The span still records. Read timestamps from your own store if you need them.
273 toolDuration.record(1, { 'tool.name': info.toolName })
274 }
275 },
276})
277```
278​
279### Media spans
280​
281These activities accept `otelMiddleware`:
282​
283- `generateImage`, `generateVideo`, and `generateLiveVideo`.
284- `generateWorld` and `generateAudio`.
285- `generateSpeech` and `generateTranscription`.
286​
287Each media call makes one `CLIENT` span, tagged with the `gen_ai.operation.name` of the activity:
288​
289| Activity | `gen_ai.operation.name` |
290| --- | --- |
291| `generateImage` | `image_generation` |
292| `generateVideo` | `video_generation` |
293| `generateAudio` | `audio_generation` |
294| `generateSpeech` | `text_to_speech` |
295| `generateTranscription` | `transcription` |
296| `generateWorld` | `world_generation` |
297| `generateLiveVideo` | `live_video_generation` |
298| `summarize` | `summarize` |
299| `decide` | `evaluate` |
300​
301What the span has:
302​
303- At the start: `gen_ai.system` and `gen_ai.request.model`.
304- At the end: the same `gen_ai.usage.*` and `tanstack.ai.usage.*` attributes as a chat span. This includes the `billed_quantity` and `billed_unit` pair for media that bills in units.
305- With a `Meter`: the `gen_ai.client.operation.duration` histogram, tagged for each activity.
306​
307How video spans work:
308​
309- Streaming video: the span covers the full create, poll, and complete cycle.
310- Non-streaming video is two calls. The submit itself makes no span. The span opens when the provider accepts the job. The `getVideoJobStatus()` poll that sees a final state ends it.
311- If a consumer of a streaming video stops before the end, `onAbort` ends the span with status `ERROR` and `tanstack.ai.completion.reason = cancelled`. The span does not leak.
312​
313The four extension points also apply to media spans. Media spans report `kind: 'generation'`.
314​
315The shared lifecycle hooks (`onStart`, `onUsage`, `onFinish`, `onAbort`, `onError`) use the `GenerationMiddlewareContext`, which is the same for each activity. That is why one instance works everywhere. For a custom backend, implement the base `GenerationMiddleware` contract. Its hooks get the `GenerationMiddlewareContext` and fire for each activity, chat included.
316​
317The `GenerationMiddleware` types come from the package root. The `otelMiddleware` value lives on the `@tanstack/ai/middlewares/otel` subpath, so an import of `@tanstack/ai` never needs the optional `@opentelemetry/api` peer.
318​
319### Capturing media content
320​
321Set `captureContent: true` to record what a media call asked for and what came back. The media span then gets the same attributes as a chat iteration span:
322​
323- `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.
324- `gen_ai.output.messages` and `langfuse.observation.output`: one `assistant` message. It holds each URL of a generated image, audio, or video as a `uri` part. For `generateTranscription`, it holds the transcript as a text part.
325​
326Media parts use the part shapes from [Content capture details](#content-capture-details):
327​
328- A URL becomes `{ "type": "uri", "modality": "image", "uri": "https://..." }`.
329- Inline data never goes onto the span. Base64 output, a `data:` URL, a `File`, or a `Blob` becomes a text placeholder such as `[image]`.
330- `redact` and `maxContentLength` apply to each text part.
331​
332For non-streaming video, the `getVideoJobStatus()` span has the output URL but not the prompt. Use `generateVideo({ stream: true })` to get both on one span.
333​
334For quick console output while you develop, use [Debug Logging](./debug-logging). To learn the lifecycle that this middleware hooks into, see [Middleware](./middleware).