# LLM analytics

> Record the model calls your server makes, with cost, tokens, latency, errors and traces per person and per model, using PostHog-compatible $ai_* events.

Source: https://apphelm.dev/docs/llm-analytics

LLM analytics shows what the model calls in your app cost, how fast they are, how often they fail and who they were for. You wrap your existing OpenAI, Anthropic or Vercel AI SDK client, or record each call yourself, and AppHelm groups the calls into traces, prices them and charts them.

**AppHelm never calls a model.** It doesn't proxy your requests or hold a provider key. Your app calls its provider exactly as before. The SDK watches the call inside your process and sends AppHelm an event that describes it. If a send fails, the error goes to your `onError` handler and never into your code.

The events are PostHog's (`$ai_generation`, `$ai_trace` and the rest), so each one is also an ordinary event. You can chart it in [Insights](https://apphelm.dev/docs/insights) or query it with SQL like any other event.

## What each SDK supports

Model calls usually run on a server, so the helpers live in the server SDKs. Browser and mobile SDKs have none.

| SDK | Wrap a client | Record a call by hand | Spans, traces, feedback, metrics |
| --- | --- | --- | --- |
| Node (`@sansavision/apphelm/server`) | `wrapOpenAI`, `wrapAnthropic`, `apphelmAiMiddleware` (Vercel AI SDK) | `captureAiGeneration`, `captureAiEmbedding` | `captureAiSpan`, `captureAiTrace`, `captureAiFeedback`, `captureAiMetric` |
| Python (`apphelm_llm`) | `wrap_openai`, `wrap_anthropic` (sync and async clients) | `capture_ai_generation` | `capture_ai_span`, `capture_ai_trace`, `capture_ai_feedback`, `capture_ai_metric` |
| Go, Ruby, PHP, .NET, Rust, Elixir | No | `CaptureAIGeneration` / `capture_ai_generation` / `captureAiGeneration` / `CaptureAiGeneration` | Send the `$ai_*` event with the SDK's normal capture call |
| Any language | No | `POST /api/v1/events` with a server key | The same endpoint |

None of the SDKs depend on a provider package. They recognise clients by their shape, so OpenAI-compatible clients work too, such as Azure OpenAI, OpenRouter, Groq and Together. So do Anthropic-compatible clients, such as the Bedrock and Vertex clients.

There is no OpenTelemetry, LiteLLM or LangChain integration. If your stack uses one of those, record each call by hand with [the manual capture](#record-a-call-by-hand).

## Before you start

You need a **server key** (`ahl_live_…`) with the `events:write` scope, and the server SDK for your language set up as on [Install and configure](https://apphelm.dev/docs/install). LLM events are ordinary events: they go through the same ingest and count toward your event allowance like any other event.

## Wrap your client

Wrap the client once per request, and pass the person the calls are for. Everything else about the client stays the same.

Node.js — chat.ts:
```ts
import OpenAI from "openai";
import Anthropic from "@anthropic-ai/sdk";
import { Apphelm } from "@sansavision/apphelm";
import { wrapOpenAI, wrapAnthropic } from "@sansavision/apphelm/server";

const apphelm = new Apphelm({ apiKey: process.env.APPHELM_API_KEY!, workspaceId: "org_…", productId: "prd_…" });

// Per request: whose calls these are, and one trace for the whole request.
const openai = wrapOpenAI(new OpenAI(), { apphelm, distinctId: user.id, traceId: requestId });
const reply = await openai.chat.completions.create({ model: "gpt-5-mini", messages });

const anthropic = wrapAnthropic(new Anthropic(), { apphelm, distinctId: user.id, traceId: requestId });
const answer = await anthropic.messages.create({ model: "claude-haiku-4-5", max_tokens: 512, messages });
```

Python — chat.py:
```python
import os
from openai import OpenAI
from anthropic import AsyncAnthropic
from apphelm import Apphelm
from apphelm_llm import wrap_openai, wrap_anthropic

apphelm = Apphelm(api_key=os.environ["APPHELM_API_KEY"])

client = wrap_openai(OpenAI(), apphelm, "org_…", "prd_…", distinct_id=user.id, trace_id=request_id)
client.chat.completions.create(model="gpt-5-mini", messages=messages)

claude = wrap_anthropic(AsyncAnthropic(), apphelm, "org_…", "prd_…", distinct_id=user.id, trace_id=request_id)
await claude.messages.create(model="claude-haiku-4-5", max_tokens=512, messages=messages)
```

**Only for Node.js:**

For the **Vercel AI SDK**, add the middleware to the model. It records `generateText`, `streamText`, `generateObject` and `streamObject` calls of that model. The middleware takes no per-call options, so create one per request when the person changes.

```ts
import { generateText, wrapLanguageModel } from "ai";
import { openai } from "@ai-sdk/openai";
import { apphelmAiMiddleware } from "@sansavision/apphelm/server";

const model = wrapLanguageModel({
  model: openai("gpt-5-mini"),
  middleware: apphelmAiMiddleware({ apphelm, distinctId: user.id, traceId: requestId }),
});
const { text } = await generateText({ model, prompt });
```

### What the wrappers record

| Wrapper | Calls recorded | Event |
| --- | --- | --- |
| `wrapOpenAI` / `wrap_openai` | `chat.completions.create`, `responses.create` | `$ai_generation` |
| | `embeddings.create` | `$ai_embedding` |
| `wrapAnthropic` (Node) | `messages.create` (also with `stream: true`) and `messages.stream` | `$ai_generation` |
| `wrap_anthropic` (Python) | `messages.create` (also with `stream=True`) and `messages.stream`, recorded when its `with` block ends | `$ai_generation` |
| `apphelmAiMiddleware` (Node) | Generate and stream calls of the wrapped model | `$ai_generation` |

Each event carries the model the provider reported, the provider, input, output, cached and reasoning tokens, latency, HTTP status, error, whether it streamed, the tool **names** (not their definitions) and scalar parameters such as `temperature` and `max_tokens`.

- **Streams** are recorded when they end, with the tokens from the final chunk. A stream closed early (a `break`) is recorded with what was read, not as an error. For an OpenAI chat stream, the wrapper asks for usage (`stream_options.include_usage`). It hides that extra chunk from your code unless you asked for it yourself.
- **Failures** are recorded with their status and message, then thrown again unchanged, so your error handling still works.
- **Other providers on the same client shape.** The provider defaults to `openai` or `anthropic`. Pass `provider` (for example `"azure"` or `"openrouter"`) when the client talks to another host. The client's base URL is recorded as its host only.

### Options

| Node | Python | Default | What it does |
| --- | --- | --- | --- |
| `apphelm` | second argument | required | Your `Apphelm` client. Python also takes `workspace_id` and `product_id` |
| `distinctId` | `distinct_id` | none | The person, as you identify them elsewhere. Without one the call is kept off any person |
| `traceId` | `trace_id` | a new id per call | Groups calls into one trace: one request, one agent run |
| `parentId` | `parent_id` | none | The span these calls sit under, for nested agent steps |
| `sessionId` | `session_id` | none | A conversation that holds several traces (`$ai_session_id`) |
| `captureContent` | `capture_content` | `false` | Send prompts and completions. See [Prompts and privacy](#prompts-and-privacy) |
| `properties` | `properties` | none | Extra properties on every event |
| `provider` | `provider` | `openai` / `anthropic` | The provider name to record |
| `onError` | `on_error` | dropped | Called when an event couldn't be sent. It never throws into your code |
| `waitUntil` | – | none | Keeps a send alive after the response in serverless runtimes, for example `ctx.waitUntil` |
| `workspaceId`, `productId` | – | the client's | Override the client's scope |
| – | `sync` | `False` | `True` sends inline instead of on a background thread |

To change options for one call, add `apphelm` to the request. The wrapper removes it before the provider sees the request. Per-call keys are `traceId`, `distinctId`, `parentId`, `sessionId`, `spanId`, `spanName`, `captureContent` and `properties` in Node, and the same names in snake case in Python.

Node.js:
```ts
// The provider's types don't know `apphelm`, so build the request first: TypeScript only
// rejects unknown keys on an object written inline in the call.
const request = { model: "gpt-5-mini", messages, apphelm: { spanName: "summarise", captureContent: true } };
await openai.chat.completions.create(request);
```

Python:
```python
client.chat.completions.create(model="gpt-5-mini", messages=messages, apphelm={"span_name": "summarise", "capture_content": True})
```

### Short-lived processes

Sends run in the background so they never slow your call down. Before a script, job or serverless function ends, wait for them.

Node.js:
```ts
import { flushAiEvents } from "@sansavision/apphelm/server";

await flushAiEvents(); // or pass waitUntil: ctx.waitUntil to the wrapper
```

Python:
```python
from apphelm_llm import flush

flush()  # waits up to 10 seconds per pending send
```

## Record a call by hand

For any other provider, a self-hosted model or a gateway, record the call after it returns. Every server SDK has a helper for `$ai_generation`. Leave the cost out and AppHelm works it out (see [Cost](#cost)).

Node.js:
```ts
import { captureAiGeneration } from "@sansavision/apphelm/server";

await captureAiGeneration(apphelm, {
  distinctId: user.id, traceId: requestId,
  model: "llama-3.3-70b", provider: "self-hosted",
  inputTokens: 812, outputTokens: 96, latencyMs: 640, httpStatus: 200,
});
```

Python:
```python
from apphelm_llm import capture_ai_generation

capture_ai_generation(apphelm, "org_…", "prd_…", model="llama-3.3-70b", provider="self-hosted",
                      distinct_id=user.id, trace_id=request_id, input_tokens=812, output_tokens=96,
                      latency_seconds=0.64, http_status=200)
```

Go:
```go
client.CaptureAIGeneration(apphelm.AIGeneration{
	DistinctID: user.ID, TraceID: requestID, Model: "llama-3.3-70b", Provider: "self-hosted",
	InputTokens: apphelm.Int(812), OutputTokens: apphelm.Int(96), LatencySeconds: apphelm.Float(0.64),
	HTTPStatus: apphelm.Int(200),
})
```

Ruby:
```ruby
APPHELM.capture_ai_generation(distinct_id: user.id, trace_id: request.request_id, model: "llama-3.3-70b",
                              provider: "self-hosted", input_tokens: 812, output_tokens: 96,
                              latency_seconds: 0.64, http_status: 200)
```

PHP:
```php
$apphelm->captureAiGeneration('llama-3.3-70b', 'self-hosted', distinctId: (string) $user->id, traceId: $requestId,
    inputTokens: 812, outputTokens: 96, latencySeconds: 0.64, httpStatus: 200);
```

.NET (C#):
```csharp
apphelm.CaptureAiGeneration(new AiGeneration
{
    Model = "llama-3.3-70b", Provider = "self-hosted", DistinctId = user.Id, TraceId = requestId,
    InputTokens = 812, OutputTokens = 96, Latency = TimeSpan.FromMilliseconds(640), HttpStatus = 200,
});
```

Rust:
```rust
use apphelm::AiGeneration;

apphelm.capture_ai_generation(
    AiGeneration::new("llama-3.3-70b").provider("self-hosted").distinct_id(&user.id)
        .trace_id(&request_id).tokens(812, 96).latency_seconds(0.64).http_status(200),
)?;
```

Elixir:
```elixir
Apphelm.capture_ai_generation(model: "llama-3.3-70b", provider: "self-hosted", distinct_id: user.id,
  trace_id: request_id, input_tokens: 812, output_tokens: 96, latency_seconds: 0.64, http_status: 200)
```

HTTP (curl):
```bash
curl -X POST https://apphelm.dev/api/v1/events \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{"workspaceId":"org_…","productId":"prd_…","eventName":"$ai_generation","eventId":"gen-8f2c1a7e",
    "properties":{"distinct_id":"user-123","$ai_trace_id":"req-42","$ai_model":"llama-3.3-70b","$ai_provider":"self-hosted",
    "$ai_input_tokens":812,"$ai_output_tokens":96,"$ai_latency":0.64,"$ai_http_status":200}}'
```

What the helpers take differs a little by SDK:

- **Latency** is in seconds everywhere (`$ai_latency` is PostHog's unit), except Node's `latencyMs` and .NET's `Latency` (a `TimeSpan`). They are converted for you.
- **Errors.** Pass the error message (`error`) to mark the call failed. An HTTP status of 400 or more also marks it failed. Messages are cut to 1,000 characters.
- **Cached tokens.** Node, Python, Go, Ruby, PHP and Elixir take cache-read and cache-write counts. In .NET use `Properties` and in Rust `.property(…)` with `$ai_cache_read_input_tokens` and `$ai_cache_creation_input_tokens`.
- **Content.** Node, Python, Go, Ruby, PHP and Elixir send `input` and `output` only when you also pass `captureContent` / `capture_content` / `CaptureContent`. Each field is bounded to 20,000 characters of JSON. The .NET and Rust helpers have no content fields.
- **Python's manual helpers send on a background thread**, like the wrappers. Call `flush()` before a short-lived process exits, or pass `sync=True` to send inline.

For the HTTP API, `eventId` (8–64 letters, digits, `_` or `-`) makes a retry safe: AppHelm stores the same id once. A request body over 64 KB is refused.

## Traces, spans, feedback and metrics

A **trace** is everything that shares an `$ai_trace_id`: the model calls of one request or one agent run, plus your own steps. Pass the same `traceId` to every wrapper and helper in the request. A call with no trace id is its own trace.

Record your own steps (retrieval, a tool, an agent step) as **spans**. Give a step a `spanId` and pass that as `parentId` to the calls inside it, and the trace view draws the tree. Name the trace and record its overall input and output with `captureAiTrace`. Record what the person thought with **feedback** (their words) or a **metric** (a thumbs up as 1 or 0, a rating, an evaluation score).

Node.js:
```ts
import { captureAiSpan, captureAiTrace, captureAiFeedback, captureAiMetric } from "@sansavision/apphelm/server";

await captureAiSpan(apphelm, { traceId: requestId, spanId: "retrieve-1", name: "retrieve", latencyMs: 85, distinctId: user.id });
await captureAiTrace(apphelm, { traceId: requestId, name: "support-answer", latencyMs: 2400, distinctId: user.id });

// Later, when the person reacts:
await captureAiMetric(apphelm, { traceId: requestId, name: "thumbs_up", value: 1, distinctId: user.id });
await captureAiFeedback(apphelm, { traceId: requestId, text: "It missed my second question", distinctId: user.id });
```

Python:
```python
from apphelm_llm import capture_ai_span, capture_ai_trace, capture_ai_feedback, capture_ai_metric

capture_ai_span(apphelm, "org_…", "prd_…", trace_id=request_id, span_id="retrieve-1", name="retrieve", latency_seconds=0.085, distinct_id=user.id)
capture_ai_trace(apphelm, "org_…", "prd_…", trace_id=request_id, name="support-answer", latency_seconds=2.4, distinct_id=user.id)

capture_ai_metric(apphelm, "org_…", "prd_…", trace_id=request_id, name="thumbs_up", value=1, distinct_id=user.id)
capture_ai_feedback(apphelm, "org_…", "prd_…", trace_id=request_id, text="It missed my second question", distinct_id=user.id)
```

HTTP (curl):
```bash
curl -X POST https://apphelm.dev/api/v1/events \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Content-Type: application/json" \
  --data '{"workspaceId":"org_…","productId":"prd_…","eventName":"$ai_metric",
    "properties":{"distinct_id":"user-123","$ai_trace_id":"req-42","$ai_metric_name":"thumbs_up","$ai_metric_value":1}}'
```

In Go, Ruby, PHP, .NET, Rust and Elixir, send `$ai_span`, `$ai_trace`, `$ai_feedback` and `$ai_metric` with the SDK's normal capture call and the properties in [The events](#the-events).

Feedback and metrics can arrive before or after the calls. A trace that isn't known yet gets its row at once, and later calls fill it in.

## The events

These are PostHog's event names and properties. AppHelm reads the properties below. Anything else stays on the event like any other property.

| Event | What it is |
| --- | --- |
| `$ai_generation` | One model call: a chat, completion or Responses API call |
| `$ai_embedding` | One embedding call |
| `$ai_span` | A step of your own: retrieval, a tool, an agent step |
| `$ai_trace` | The trace itself: its name, overall input and output, latency and error |
| `$ai_feedback` | A person's words about a trace (`$ai_feedback_text`, up to 2,000 characters) |
| `$ai_metric` | A named score on a trace (`$ai_metric_name`, `$ai_metric_value`) |

| Property | Meaning |
| --- | --- |
| `distinct_id` | The person. See [Who the calls belong to](#who-the-calls-belong-to) |
| `$ai_trace_id` | Groups calls and spans into one trace. When it's missing, the span id is used, so the call is its own trace |
| `$ai_span_id`, `$ai_parent_id` | Build the tree inside a trace |
| `$ai_span_name` (`$ai_trace_name` on `$ai_trace`) | A step's name, or the trace's name. A trace without its own name takes the name of its top-level span |
| `$ai_session_id` | A conversation that holds several traces |
| `$ai_model`, `$ai_provider` | The model id as the provider reported it (up to 120 characters), and the provider. A missing provider is taken from the price table |
| `$ai_input_tokens`, `$ai_output_tokens` | Token counts |
| `$ai_cache_read_input_tokens`, `$ai_cache_creation_input_tokens`, `$ai_reasoning_tokens` | Cached input read, cache written, and reasoning tokens |
| `$ai_latency` | Seconds. Values over a day are ignored |
| `$ai_http_status`, `$ai_is_error`, `$ai_error` | The outcome. A status of 400 or more, `$ai_is_error: true` or any `$ai_error` marks the call failed |
| `$ai_input_cost_usd`, `$ai_output_cost_usd`, `$ai_total_cost_usd` | Your own cost. When present it is used as sent |
| `$ai_base_url` | The provider host. Only the host is kept, never the path or query |
| `$ai_tools` | Tool definitions. Only the names are kept (up to 30) |
| `$ai_stream`, `$ai_model_parameters` | Whether the call streamed, and scalar parameters (up to 20) such as temperature |
| `$ai_input`, `$ai_output_choices` (or `$ai_output`) | A call's prompt and completion |
| `$ai_input_state`, `$ai_output_state` | A span's or trace's input and output |
| `$ai_feedback_score`, `$ai_feedback_name` | Optional on `$ai_feedback`: a number and a label |

`$ai_metric_value` can be a number, a boolean (stored as 1 or 0) or text. Numbers are averaged on the **Feedback** tab.

The call's time is the event's `occurredAt` when it is within a day of when AppHelm received it, and the receive time otherwise.

## Who the calls belong to

Pass `distinctId` (your user id) and the calls join that person. AppHelm hashes the id the way it hashes every event, so the calls link to the same person's other events, their customer profile and the **People** tab. See [Users, people and groups](https://apphelm.dev/docs/identify).

Without a distinct id, the SDK follows PostHog's convention. It sends the trace id as the distinct id with `$process_person_profile: false`, and AppHelm keeps the call off any person. Those calls still count in every total. On the **People** tab they are listed together as calls without a person.

## Cost

AppHelm works out each generation's and embedding's cost once, when it stores the event. It takes the first of these that applies:

1. **Your own cost.** If the event carries `$ai_input_cost_usd`, `$ai_output_cost_usd` or `$ai_total_cost_usd`, those are used as sent. Without a total, the total is input plus output.
2. **Your product's price** for the model, set on **LLM analytics → Model prices**.
3. **The built-in list price** for the model.
4. Otherwise the call has **no cost** and counts as *unpriced*. The **Model prices** tab lists these models so you can add a price.

When AppHelm works out the cost, it also adds `$ai_input_cost_usd`, `$ai_output_cost_usd` and `$ai_total_cost_usd` to the stored event. A trend can then sum cost like any numeric property. Spans have no cost.

> **Prices don't change the past:** A price change applies to calls stored after it. Calls already stored keep the cost they were given.

### How tokens are priced

Prices are in US dollars per million tokens: an input price, an output price, and optional cache-read and cache-write prices. If a model has no cache price, cached tokens are priced at the input rate. Embeddings are priced at the input rate.

Providers count cached tokens in two ways, and AppHelm follows each one:

- **Anthropic** reports cache reads and writes separately from `input_tokens`, so their cost is added on top.
- **Every other provider** includes cached tokens in the input count, so they are taken out of it before the input price applies.

The wrappers send the counts the way each provider reports them. When you record calls by hand, send them the same way, and set `provider` so AppHelm knows which rule applies.

### The built-in price table

The table holds the standard-tier list prices of OpenAI, Anthropic, Google (Gemini API), Mistral, DeepSeek (peak rates), xAI and Cohere (legacy per-token prices), and it is dated. The **Models** tab shows the date and the price used for each model. Batch, priority, regional and long-context surcharges aren't included, so a cost from the table is an estimate. If you pay other rates, set your own prices.

A model is looked up by its exact id after AppHelm removes a gateway prefix (`openai/`, `models/`, Bedrock's `us.anthropic.`), a Bedrock version (`-v1:0`) and a Vertex `@date`. If that fails, it tries again without a date or `-latest` suffix. Nothing looser is tried, so a new `gpt-5.7` is never priced as `gpt-5`. Add your own price for it.

### Your own prices

Open **LLM analytics → Model prices** and add the model id exactly as your app sends it, with its input and output prices and, if you have them, the cache prices.

- End the id with `*` to cover every model that starts with it, such as `ft:gpt-4o-mini:acme:*` for your fine-tunes. An exact id wins over a prefix, and a longer prefix wins over a shorter one.
- Prices are 0 to 100,000 dollars per million tokens. A product can have up to 200 prices.
- Workspace owners and admins can add, change and remove prices. Other members can see them. The demo product's prices are read-only.
- A new price can take up to a minute to apply to new calls.

## Prompts and privacy

Prompts, completions, tool results and feedback can contain personal data, so the SDKs send **metadata only** by default: model, tokens, latency, status, errors and tool names. They send content only with `captureContent: true` (Node), `capture_content=True` (Python) or the content option of the manual helpers. You can set it on the wrapper or on one call. Switch it on only where your privacy notice covers it.

What happens to content:

- **Bounded.** The SDKs cut strings to 4,000 characters and lists to 50 items, and each field to 20,000 characters of JSON. Node and Python replace binary data with `[binary]` and inline `data:…;base64` values with `[inline data]`. AppHelm applies the same string and list bounds, nests at most 8 levels deep and keeps at most 32,000 characters per field. Anything larger is kept as a truncated preview.
- **Secrets redacted.** Before storing, AppHelm replaces obvious API keys and bearer values: `sk-…`, `ahl_…`, AWS, GitHub and Slack tokens, and `api_key=`, `authorization:` or `bearer` values. It keeps other content as sent, emails included, because you chose to capture it. Error messages and feedback text get the same redaction. The Python SDK also scrubs secrets and email addresses from error messages and feedback text before sending.
- **Kept out of the property index.** Prompts, completions, span state, tool definitions, model parameters, error text and feedback text never become filterable event properties. They live only in LLM analytics' own storage. Token counts and costs do become properties, as numbers.
- **Who can read it.** Content appears only in the trace view, never in a list. Over the API it is returned only by `GET /api/v1/llm/traces/{id}` (`sessions:read`). SQL never returns it. The MCP tool returns it only with `includeContent: true`.
- **Change or drop events before they leave.** `beforeSend` (Node) and `before_send` (Python) see LLM events like every other event, so you can remove content or drop an event there.
- **Retention.** Calls, spans, traces and feedback expire with your plan's capture retention, like other events.
- **Deletion and export.** A privacy deletion of a person removes their calls, traces and feedback, content included, and the deletion report checks that none are left. A privacy export includes them. See [Privacy, consent and data controls](https://apphelm.dev/docs/privacy).

## View it in AppHelm

Open **Product analytics → LLM analytics** and choose a product and a range of 7, 30 or 90 days.

| Tab | What it shows |
| --- | --- |
| Overview | Cost, calls, tokens, latency p50 and p95, and error rate. A daily chart of cost, calls or tokens with error days marked, cost by model and by provider, and the top people by cost |
| Traces | Traces you can filter by model, person (a `cus_…` customer id or a person hash), trace name or id, minimum cost, minimum latency and errors only. Sort by newest, most expensive or slowest |
| Generations | Every call, newest first, by model, with an errors-only filter |
| People | Cost, calls, traces, tokens and errors per person. People your app identified show their name and link to their customer page |
| Models | Calls, tokens, errors, latency and cost per model, with the price used and where it came from |
| Feedback | The count, average, minimum and maximum of each metric, and the latest feedback with links to its trace |
| Model prices | Your product's own prices, and the models that have no price yet |

Open a trace to see its tree of spans, generations and embeddings. Each one shows its tokens, cost, latency, status, tools, parameters and any captured content. The trace view also lists the trace's feedback and metrics, up to 500 steps per trace. When a trace's events carry a browser session, the trace links to that session's replay.

Until the product records its first call, the page shows how to wrap a client. To look around first, add the demo product in **Setup**: it includes a sample shopping assistant.

## Chart and query it

**Insights.** Each `$ai_*` event is an ordinary event, so you can chart `$ai_generation` in a trend, sum `$ai_total_cost_usd` or `$ai_output_tokens`, break down by `$ai_model`, or put a generation step in a funnel. See [Insights, dashboards and SQL](https://apphelm.dev/docs/insights).

**SQL.** The `llm_generations` table holds generations and embeddings in the query's date range, metadata only. Its columns are `uuid`, `kind`, `trace_id`, `span_id`, `parent_id`, `name`, `model`, `provider`, `input_tokens`, `output_tokens`, `cache_read_tokens`, `reasoning_tokens`, `total_cost_usd`, `latency_ms`, `http_status`, `is_error`, `timestamp`, `person_id` and `session_id`.

```bash
curl -X POST https://apphelm.dev/api/v1/query/sql \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Content-Type: application/json" \
  --data '{"productId":"prd_…","days":30,"query":"SELECT model, count() AS calls, sum(total_cost_usd) AS cost FROM llm_generations GROUP BY model ORDER BY cost DESC LIMIT 10"}'
```

The SQL endpoint needs `analytics:read`.

### The LLM analytics API

Every route needs a workspace key. `productId` can be left out when the key covers one product. `days` is a whole number from 1 to 90 (default 30).

| Route | Scope | Returns |
| --- | --- | --- |
| `GET /api/v1/llm/summary?productId=&days=` | `metrics:read` | Totals, latency p50/p95, error rate, the daily series, and cost by model (with the price used) and by provider. The top people only when the key also holds `sessions:read` |
| `GET /api/v1/llm/traces` | `sessions:read` | Traces, without content. Filters: `model`, `person`, `errors=1`, `minCost` (USD), `minLatencyMs`, `q` (trace id or part of a name), `aiSession`, `sort` (`recent`, `cost`, `latency`), `limit` (up to 100) and `offset` |
| `GET /api/v1/llm/traces/{id}` | `sessions:read` | One trace with its steps (up to 500), captured content, feedback and metrics |
| `GET /api/v1/llm/generations` | `sessions:read` | Calls, newest first, without content. Filters: `model`, `provider`, `person`, `errors=1`, `limit` and `offset` |

```bash
curl "https://apphelm.dev/api/v1/llm/summary?productId=prd_…&days=7" \
  -H "Authorization: Bearer $APPHELM_API_KEY"

curl "https://apphelm.dev/api/v1/llm/traces?productId=prd_…&sort=cost&limit=20" \
  -H "Authorization: Bearer $APPHELM_API_KEY"
# Lists end with pagination.nextOffset; pass it as offset for the next page.
```

The full request and response shapes are in the [API reference](https://apphelm.dev/docs/api). The product [MCP server](https://apphelm.dev/docs/mcp) has the same reads as `apphelm_get_llm_costs` (`metrics:read`), `apphelm_list_llm_traces` and `apphelm_get_llm_trace` (`sessions:read`). An assistant can answer "what did our model calls cost this week?" with them. The demo product is never served through the API or MCP.

## Check that it works

### Make one call
Run one wrapped call, or one manual capture, from your server. In a script, call `flushAiEvents()` or `flush()` before it exits.

### Open the Generations tab
Open **LLM analytics → Generations** for the product. The call should appear within seconds, with its model, tokens and latency.

### Check the cost
If the cost column is empty, the model isn't in the price table. Add it on **Model prices**. Calls stored after that get a cost.

### Check the person
Open **People**. If the call is listed as without a person, pass `distinctId` to the wrapper.

## Limits

| What | Limit |
| --- | --- |
| One event (HTTP request body) | 64 KB |
| Content per field | 20,000 characters of JSON from the SDKs, 32,000 kept by AppHelm |
| Error message | 1,000 characters |
| Feedback text | 2,000 characters |
| Tool names kept | 30 per call |
| Steps shown per trace | 500 |
| Range in the app and API | Up to 90 days |
| Own model prices | 200 per product |
| Kept for | Your plan's capture retention |

## Best practices

- **Use one trace id per request.** Pass your request id as `traceId` so a request's calls, retries and tool steps read as one trace with one cost.
- **Always pass the person.** With `distinctId` set, cost per person and the People tab work, and a privacy deletion can find their calls.
- **Leave content off until you need it.** Metadata answers most cost and reliability questions. If you turn content on, do it for the routes that need it, with the per-call option.
- **Send the provider's own model id.** The price table matches exact ids. If you rename models in a gateway, add your own prices for those names.
- **Flush in short-lived code.** Serverless functions and scripts can end before a background send finishes. Use `waitUntil`, `flushAiEvents()` or `flush()`.

## Not supported yet

- **Browser and mobile helpers.** Record model calls on your server.
- **OpenTelemetry, LiteLLM and LangChain.** Use the manual capture.
- **Evaluations and prompt management.** Record evaluation results as `$ai_metric`.
- **PostHog imports.** `$ai_*` events imported from PostHog arrive as ordinary events that trends can use. They don't appear on the LLM analytics pages.
- **Changing prices through the API.** Prices are set in the app only.

## Troubleshooting

| Symptom | Likely cause | What to do |
| --- | --- | --- |
| Nothing appears | The key lacks `events:write`, or the process exits before sends finish | Use a server key with `events:write`. Call `flushAiEvents()` / `flush()` or pass `waitUntil` |
| Nothing appears and no error is shown | Send errors go to `onError` and are otherwise dropped | Pass `onError: (error) => console.error(error)` (`on_error=print` in Python) to see why |
| A streamed call is missing | The stream was neither read to the end nor closed | Read it to the end, or close it (`break` out of the loop, or leave its `with` block); what was read is then recorded |
| Every call is its own trace | No `traceId` was passed | Pass the same `traceId` to every wrapper and helper in the request |
| A call has no cost | The model isn't in the price table, or has a gateway name | Add the model on **Model prices**, or send `$ai_total_cost_usd` yourself |
| Cost looks too high for cached calls | Cached tokens were sent the wrong way for the provider | For Anthropic, send cache counts apart from input tokens. For other providers, include them in input tokens, and set `provider` |
| Calls are listed as without a person | No `distinctId` was passed | Pass `distinctId` / `distinct_id` |
| A trace shows no prompts | Content capture is off, which is the default | Pass `captureContent: true` where your privacy notice covers it |
| TypeScript rejects `apphelm` in a request | The provider's types don't know the per-call option | Build the request in a variable first, or set the option on the wrapper instead |
| The API answers `422 invalid_range` | `days` isn't a whole number from 1 to 90 | Send `days` between 1 and 90 |
| The API answers `422 product_required` | The key covers several products and no `productId` was sent | Add `productId=prd_…` |
| The API answers `403 scope_denied` | The key lacks `metrics:read` (summary) or `sessions:read` (traces, generations) | Create a key with the scope the route needs |
| `404 trace_not_found` | The trace expired with your plan's retention, a privacy deletion removed it, or it's in a product the key can't read | Check the trace id and the key's products |
