Turn LLM traces into queryable production data
LLM features are easier to debug, evaluate, and govern when every call becomes a structured event in a queryable store. A SQLite and Datasette workflow highlights the broader engineering pattern, capture prompts, outputs, tool calls, timings, versions, and retention rules from day one.
Simon Willison’s note on datasette-llm 0.2a0 points to a useful pattern, storing LLM interactions in SQLite and exploring them with Datasette. The release detail matters less than the engineering direction. Once prompts, outputs, timings, and metadata live in a queryable store, your AI system stops being a black box.
If you ship AI into a product, your failure modes often hide in traces you did not keep. Latency spikes. Prompt drift. Tool misuse. Silent model changes. Cost blowouts tied to one route or one customer. A database-backed trace layer gives you something to inspect. It also gives your team a shared surface for debugging, evaluation, and governance.
Treat LLM calls as production events
Many teams log AI calls as blobs in app logs. That works for short-term debugging. It fails once you need pattern analysis across days or weeks.
A better model is to treat each LLM call as a production event with structured fields. Store it in a relational schema you can query.
Useful fields include:
- request ID
- user or tenant ID
- model name and provider
- system prompt hash
- user prompt hash
- tool list
- start time and end time
- input token count
- output token count
- cache hit state
- finish reason
- error type
- response status
- sampled evaluation score
Hashes matter. You often do not want raw prompts in clear text for every environment. A hash lets you group behavior by prompt version without exposing content everywhere. When you do need raw content for forensic work, keep it behind stricter access controls.
A simple schema usually beats a clever one. Start with one responses table and a small set of child tables for tool calls, attachments, and evaluations. If your agent loops across multiple tool steps, keep a parent session_id or trace_id so you can reconstruct the run.
Where teams go wrong:
- They keep only raw JSON, so every question needs custom parsing.
- They omit version fields, so prompt changes blend together.
- They log text but not token counts or timings, so cost and latency analysis stays fuzzy.
- They skip tenant and route metadata, so they cannot isolate one bad integration.
Design for queryability first
SQLite works well for local analysis, test fixtures, and single-node operational review. Datasette adds a fast read surface on top. The larger lesson is broader than one tool. Your trace store should support plain SQL from day one.
Why SQL matters:
- You can find regressions with one grouped query.
- You can compare prompt versions without building a dashboard first.
- You can join traces to app events, support tickets, or offline eval scores.
- You can export slices for model audits.
A few practical queries pay off early.
Latency by model and route:
select
route,
model,
count(*) as calls,
round(avg(duration_ms), 1) as avg_ms,
round(percentile_95(duration_ms), 1) as p95_ms
from responses
group by route, model
order by p95_ms desc;
Failure rate by prompt version:
select
system_prompt_hash,
count(*) as calls,
sum(case when error_type is not null then 1 else 0 end) as errors
from responses
group by system_prompt_hash
order by errors desc;
Token spend concentration:
select
tenant_id,
sum(input_tokens + output_tokens) as total_tokens
from responses
group by tenant_id
order by total_tokens desc
limit 20;
SQLite does not ship with every analytic function you might want. That is fine. Start with counts, averages, buckets, and joins. If your data volume outgrows it, the same event model ports cleanly into Postgres, ClickHouse, or a warehouse.
Where this commonly breaks:
- Free-text columns hold data that should be dimensions.
- Time fields use mixed formats or time zones.
- One row tries to represent an entire agent run with nested arrays.
- Teams wait for a full observability platform before storing anything useful.
Capture tool use as first-class data
Agent systems fail in different ways from single-shot completion APIs. The model might choose the wrong tool. It might call the right tool with bad arguments. It might loop. It might ignore tool output and answer from prior text.
If you only store the final answer, you lose the evidence.
Model each tool call separately. Keep:
- tool name
- argument JSON
- validation result
- execution start and end time
- output size
- output status
- retry count
- parent response ID
- sequence number in the run
This gives you direct signals.
Examples:
- One tool shows a 20 percent timeout rate after a deployment.
- A retrieval tool is selected far less after a prompt rewrite.
- Argument validation failures cluster around one field name.
- The agent starts repeating the same tool call three times in a row.
For Go services, this instrumentation fits cleanly around an interface boundary. If your tool runner exposes a standard Execute(ctx, input) path, wrap it with trace capture before and after execution. Keep the wrapper dumb. Record facts, not interpretations.
A minimal Go shape looks like this:
type ToolCallRecord struct {
ResponseID string
Seq int
ToolName string
ArgsJSON []byte
StartedAt time.Time
EndedAt time.Time
Status string
ErrorType string
OutputBytes int
RetryCount int
}
type Tool interface {
Name() string
Execute(ctx context.Context, args json.RawMessage) (json.RawMessage, error)
}
The same principle applies to retrieval. Store document IDs returned, rank positions, and whether those passages were cited in the final answer. Without this, you cannot tell whether bad answers came from retrieval failure or synthesis failure.
Make prompt and model changes diffable
AI systems drift because their inputs drift. You update a system prompt. A provider changes a model snapshot. Tool definitions evolve. Safety filters change. Grounding data changes.
If those changes are not versioned in your traces, you will spend hours guessing.
Practical steps:
- Hash every prompt segment separately, system, developer, user template.
- Store provider model ID, not the friendly alias alone.
- Version tool schemas and retrieval pipelines.
- Record sampling settings, temperature, top-p, max tokens.
- Keep a deployment version from your app in each row.
This supports diff-based analysis. You can ask:
- Did answer length drop after the prompt edit on Tuesday?
- Did one model snapshot increase tool-call frequency?
- Did a retrieval index rebuild reduce citation quality?
- Did support complaints rise on the same app release where token output doubled?
One useful pattern is to run shadow traffic for a slice of requests. Send the same normalized input to the old and new prompt or model, store both outputs, then compare with offline scoring. You do not need a full evaluation platform to start. A reviewed sample of 100 paired traces often exposes enough to stop a bad rollout.
Where teams slip:
- They overwrite prompt text in place.
- They store
gpt-4or another alias, but not the dated backend version. - They compare outputs by feel instead of by stored metrics and sampled review.
Plan for privacy, retention, and access
A trace store is useful because it is detailed. That detail creates risk.
LLM traces often contain:
- customer messages
- internal documents
- API arguments
- support transcripts
- personal data
- secrets pasted by users
You need retention rules and access controls from the start. Keep raw content separate from summary metadata if possible. Redact known secret patterns before persistence. Restrict who can view prompt and response bodies. Give engineers aggregate views by default.
For many teams, a split design works well:
- metadata tables for timings, token counts, versions, status
- content tables for prompts, outputs, tool payloads
- row-level links through response IDs
Then apply shorter retention to content and longer retention to metadata. The metadata keeps trend analysis intact after sensitive text ages out.
Audit access to the raw corpus. If your AI feature touches regulated data, include the trace store in your data inventory and deletion workflows. If a user asks for erasure, your traces count.
A final operational point matters here. Test your redaction on failure paths, not only success paths. Errors often dump the most sensitive material.
What to watch next
The useful shift is from chat logs to observability data. Expect more teams to store prompts, tool calls, evals, and retrieval events in a form SQL can inspect. Expect local-first workflows to stay popular, because engineers move faster when they can inspect traces without a heavy platform.
If you run AI in production, the question is not whether to keep traces. The question is whether your traces are structured enough to explain model behavior when your users need answers.