Skip to content

Commit 336f515

Browse files
authored
docs(ai): add LLM observability page (#4568)
## Summary Adds a docs page for LLM observability: every opted-in Vercel AI SDK call inside a task becomes its own span in the run trace, carrying the model, provider, token counts, cost, and latency. The page covers turning it on per call with `experimental_telemetry: { isEnabled: true }`, what each span inspector tab shows (Overview, Messages, Tools, and a Prompt tab when linked), linking a call to its prompt version with `toAISDKTelemetry()`, and querying usage across runs with TRQL against the `llm_metrics` table. It sits in the AI dropdown under Features, next to [Prompts](https://trigger.dev/docs/ai/prompts), and cross-links the [Query](https://trigger.dev/docs/observability/query) page. It is explicit that capture is opt-in per call (not automatic) and only covers Vercel AI SDK calls, and notes the `@ai-sdk/otel` requirement on AI SDK 7. Every API name, span tab, and TRQL column was checked against the SDK and the live query schema. ## Also in this PR Corrects one bullet in the [AI Agents overview](https://trigger.dev/docs/ai-chat/overview): it claimed an in-progress chat resumes on the new version after a redeploy, which contradicts the version-upgrades and backend pages. Chat agent runs are pinned to the version they started on; moving onto new code is an explicit version upgrade.
1 parent e367899 commit 336f515

3 files changed

Lines changed: 176 additions & 1 deletion

File tree

docs/ai-chat/overview.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ See [Quick Start](/ai-chat/quick-start) for the matching server actions and a ru
4747

4848
## Why use AI Agents on Trigger.dev
4949

50-
- **Resume across refreshes, deploys, and crashes.** A chat in progress when you redeploy keeps streaming on the new version. Mid-stream refreshes pick up where they left off.
50+
- **Resume across refreshes, deploys, and crashes.** A chat in progress keeps streaming through a redeploy, pinned to the version it started on. Move it onto new code when you choose with a [version upgrade](/ai-chat/patterns/version-upgrades). Mid-stream refreshes pick up where they left off.
5151
- **Native AI SDK support.** Text, tool calls, reasoning, and custom `data-*` parts all flow through `useChat` over a custom `ChatTransport`. No custom protocol to maintain.
5252
- **Multi-turn for free.** Each turn is a step inside the same durable task; conversation history accumulates server-side, so clients only ship the new message.
5353
- **Fast cold starts.** Opt-in [Head Start](/ai-chat/fast-starts#head-start) runs the first `streamText` step in your warm Next.js / Hono / SvelteKit server while the agent boots in parallel — cuts time-to-first-chunk roughly in half.

docs/ai/observability.mdx

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
---
2+
title: "LLM observability"
3+
sidebarTitle: "LLM observability"
4+
description: "Capture Vercel AI SDK calls in a task as spans in the run trace, with model, token usage, cost, and latency. Opt in per call, link calls to prompt versions, and query usage across runs."
5+
---
6+
7+
**LLM observability turns a Vercel AI SDK call inside a task into its own span in the run trace, next to your logs and other spans.** Each span carries the model, provider, input, output, and total token counts, cost, and latency, so you can see what each generation did and what it cost without leaving the run.
8+
9+
Everything shows up inline in the run trace you already use to debug runs. There is no separate product and no dashboard to set up.
10+
11+
<Note>
12+
Observability is opt-in per call and only covers [Vercel AI SDK](https://ai-sdk.dev) functions (`generateText`, `streamText`, `generateObject`). Calls you make with a raw `fetch`, a provider's own SDK, or any other HTTP client are not captured automatically.
13+
</Note>
14+
15+
## Turn it on
16+
17+
Set `experimental_telemetry: { isEnabled: true }` on the AI SDK call. There is nothing to install for AI SDK 6, and nothing to configure on the Trigger.dev side.
18+
19+
```ts /trigger/summarize.ts
20+
import { task } from "@trigger.dev/sdk";
21+
import { generateText } from "ai";
22+
import { openai } from "@ai-sdk/openai";
23+
24+
export const summarize = task({
25+
id: "summarize",
26+
run: async (payload: { text: string }) => {
27+
const result = await generateText({
28+
model: openai("gpt-4o"),
29+
prompt: `Summarize the following text:\n\n${payload.text}`,
30+
experimental_telemetry: { isEnabled: true },
31+
});
32+
33+
return { summary: result.text };
34+
},
35+
});
36+
```
37+
38+
Trigger the task and open the run. The `generateText` call appears as a span in the trace. `streamText` and `generateObject` work the same way: add the same `experimental_telemetry` flag to each call you want captured.
39+
40+
<Note>
41+
**AI SDK 7** moved span emission out of `ai` core into the `@ai-sdk/otel` adapter. In a task, install `@ai-sdk/otel` and register it once yourself, for example at the top of your task file:
42+
43+
```ts /trigger/summarize.ts
44+
import { registerTelemetry } from "ai";
45+
import { OpenTelemetry } from "@ai-sdk/otel";
46+
47+
registerTelemetry(new OpenTelemetry());
48+
```
49+
50+
A [`chat.agent()`](/ai-chat/overview) run registers the adapter for you at run start, so chat agents need only the install. On AI SDK 5 and 6, `ai` core emits spans directly and no adapter is needed.
51+
</Note>
52+
53+
## What each span shows
54+
55+
Open an AI generation span in the run trace to get a dedicated inspector with three tabs:
56+
57+
- **Overview**: model, provider, token usage, cost, and a preview of the input and output.
58+
- **Messages**: the full message thread, including the system prompt and any tool results.
59+
- **Tools**: the tool definitions passed to the model, plus every tool call the model made with its arguments.
60+
61+
A fourth **Prompt** tab appears when the call is linked to an [AI Prompt](/ai/prompts) (see below).
62+
63+
## Link a call to its prompt
64+
65+
If you manage prompts with [AI Prompts](/ai/prompts), resolve the prompt and spread `toAISDKTelemetry()` into the call. This sets `experimental_telemetry` for you and links the span back to the exact prompt version that produced it.
66+
67+
```ts /trigger/support.ts
68+
import { task, prompts } from "@trigger.dev/sdk";
69+
import { generateText } from "ai";
70+
import { openai } from "@ai-sdk/openai";
71+
import type { supportPrompt } from "./prompts";
72+
73+
export const handleSupport = task({
74+
id: "handle-support",
75+
run: async (payload: { name: string; plan: string; issue: string }) => {
76+
const resolved = await prompts.resolve<typeof supportPrompt>("customer-support", {
77+
customerName: payload.name,
78+
plan: payload.plan,
79+
issue: payload.issue,
80+
});
81+
82+
const result = await generateText({
83+
model: openai(resolved.model ?? "gpt-4o"),
84+
system: resolved.text,
85+
prompt: payload.issue,
86+
...resolved.toAISDKTelemetry(),
87+
});
88+
89+
return { response: result.text };
90+
},
91+
});
92+
```
93+
94+
The span's **Prompt** tab now shows the linked template, its version, and the input variables the prompt was resolved with.
95+
96+
Pass custom attributes to `toAISDKTelemetry()` to tag the span with your own metadata:
97+
98+
```ts
99+
const result = await generateText({
100+
model: openai(resolved.model ?? "gpt-4o"),
101+
system: resolved.text,
102+
prompt: payload.issue,
103+
...resolved.toAISDKTelemetry({
104+
"task.type": "summarization",
105+
"customer.tier": "enterprise",
106+
}),
107+
});
108+
```
109+
110+
Custom attributes are stored on the span's `metadata`, so you can filter or group by them in TRQL, for example `metadata['task.type']`.
111+
112+
<Note>
113+
When you build an agent with `chat.agent()` and store a prompt with `chat.prompt.set()`, `chat.toStreamTextOptions()` sets `experimental_telemetry` for you, so those generations are captured without adding the flag by hand. Without a stored prompt, set `experimental_telemetry` on the call yourself. See [Prompts](/ai/prompts#using-with-chatagent).
114+
</Note>
115+
116+
## Query usage across runs
117+
118+
Every captured generation is also written to the `llm_metrics` table, which you can query with [TRQL](/observability/query). This lets you aggregate token usage, cost, and latency across many runs rather than inspecting one span at a time.
119+
120+
Cost and token usage by model:
121+
122+
```sql
123+
SELECT
124+
response_model,
125+
gen_ai_system AS provider,
126+
count() AS calls,
127+
sum(total_tokens) AS tokens,
128+
round(sum(total_cost), 4) AS cost_usd
129+
FROM llm_metrics
130+
GROUP BY response_model, gen_ai_system
131+
ORDER BY cost_usd DESC
132+
LIMIT 20
133+
```
134+
135+
Spend per task:
136+
137+
```sql
138+
SELECT
139+
task_identifier,
140+
sum(input_tokens) AS input_tokens,
141+
sum(output_tokens) AS output_tokens,
142+
round(sum(total_cost), 4) AS cost_usd
143+
FROM llm_metrics
144+
GROUP BY task_identifier
145+
ORDER BY cost_usd DESC
146+
LIMIT 20
147+
```
148+
149+
Cost by prompt version, when calls are linked to an [AI Prompt](/ai/prompts):
150+
151+
```sql
152+
SELECT
153+
prompt_slug,
154+
prompt_version,
155+
count() AS calls,
156+
round(sum(total_cost), 4) AS cost_usd
157+
FROM llm_metrics
158+
WHERE prompt_slug != ''
159+
GROUP BY prompt_slug, prompt_version
160+
ORDER BY prompt_slug, prompt_version
161+
```
162+
163+
Set the time window with the query's [period filter](/observability/query#time-ranges) rather than in the SQL itself. Run these from the [Query dashboard](/observability/query#using-the-query-dashboard), the SDK with `query.execute()`, or the REST API. `llm_metrics` also exposes `ms_to_first_chunk` and `tokens_per_second` for latency and throughput, plus `finish_reason`, `request_model`, `cached_read_tokens`, `reasoning_tokens`, and per-direction `input_cost` / `output_cost` for finer breakdowns.
164+
165+
## Next steps
166+
167+
<CardGroup cols={2}>
168+
<Card title="Prompts" icon="message-lines" href="/ai/prompts">
169+
Version prompts as code and link generations to the exact prompt version that produced them.
170+
</Card>
171+
<Card title="Query (TRQL)" icon="magnifying-glass-chart" href="/observability/query">
172+
Write custom queries against your runs, metrics, and LLM usage.
173+
</Card>
174+
</CardGroup>

docs/docs.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@
107107
"group": "Features",
108108
"pages": [
109109
"ai/prompts",
110+
"ai/observability",
110111
"ai-chat/fast-starts",
111112
"ai-chat/compaction",
112113
"ai-chat/prompt-caching",

0 commit comments

Comments
 (0)