How to Log and Debug AI Features

When normal software fails, you get an error. When an AI feature fails, you get a confident wrong answer and a 200 response. So you have to build your own way of seeing what happened.

How to Log and Debug AI Features — Troiana insight cover

In short

To debug AI features, log each model call with its exact prompt, retrieved context, tool calls, model and version, parameters, response, tokens, cost, latency and a trace ID linking the steps. Add user feedback. Redact personal data, and limit how long logs are kept. To diagnose a bad answer, replay it, then work out whether the fault lay in the data, the retrieval, the prompt or the model.

Why it's different

Normal debugging assumes that the same input gives the same output, and that failures make themselves known. AI features break both assumptions.

  • Failure looks like success. A wrong answer returns HTTP 200.
  • Results vary. The same question can give a different answer tomorrow.
  • The real input is hidden. The user typed one line, but the model saw 4,000 tokens of prompt, history and documents.
  • Steps multiply. One request might trigger retrieval, three tool calls and a second model call.
  • Models change. A provider update can shift behaviour with no change in your code.

So ordinary error tracking isn't enough. You'll want it for crashes, but it won't catch a confident hallucination.

What to log for every model call

FieldWhy it matters
Trace ID and step IDLinks everything in one request
Exact final prompt, including system promptShows what the model really saw
Prompt versionConnects behaviour to changes
Retrieved documents and scoresShows whether retrieval failed
Tool calls, arguments and resultsShows what it did
Model name and exact versionExplains provider changes
Parameters, such as temperatureHelps with reproducing
Raw response and stop reasonShows truncation and refusals
Input, output and cached tokensCost and context use
Latency, including time to first tokenSpeed problems
Errors and retriesHidden failures
Feature name, and an anonymised user or accountPatterns by feature and customer
User feedbackFinds bad answers

A simple record might look like this:

{
  "trace_id": "t_8f2a",
  "step": "answer",
  "feature": "support_assistant",
  "prompt_version": "support-v14",
  "model": "example-model-2026-10-01",
  "retrieved_ids": ["doc_41", "doc_77"],
  "input_tokens": 3120,
  "output_tokens": 240,
  "cost_usd": 0.0043,
  "latency_ms": 1810,
  "stop_reason": "end_turn",
  "feedback": null
}

Trace across steps

For anything with more than one call, particularly agents, you need to see the entire chain. A trace shows each step, in order, with its inputs and outputs. It's what lets you see that the final wrong answer came from a tool returning stale data three steps earlier.

OpenTelemetry's generative AI conventions offer a standard format for this, which helps you to avoid being tied to one vendor. They're still evolving, so check their current status.

Requesttrace t_8f2a
Rewrite querymodel call
Retrieve documentssearch
Tool: order lookuptool call
Answermodel call
An invented trace. One user request becomes several steps, and a shared trace ID lets you see which of them went wrong.

A method for debugging a bad answer

  1. Find the trace. Start with the user's report, or with low-rated answers.
  2. Read what the model saw. This is often the whole answer. You may spot contradictory instructions, or find that a key fact was missing altogether.
  3. Classify the failure:
Where it went wrongSignsFix
Source dataThe document is wrong or out of dateFix the content
RetrievalThe right document wasn't foundAdjust chunking, search or filters
ContextFound, but cut off or buriedReorder or trim context
PromptUnclear or conflicting instructionsRewrite and add examples
ToolWrong call or bad resultImprove its description or fix the tool
ModelEverything was right, but the answer's wrongTest another model
TruncationStop reason shows the output limitRaise the limit or shorten
  1. Replay it. Send the same logged input again, several times. Does it fail every time, or only sometimes?
  2. Change one thing at a time, and test.
  3. Add the case to your test set, so that this failure can't quietly come back. See how to evaluate an LLM feature.

That last step is what makes your system steadily improve, rather than going around in circles.

A bad answer
Find the traceFrom the report
Read what it sawOften the whole answer
Classify itData, retrieval, context, prompt, tool, model
ReplayChange one thing
Add to the test setSo it stays fixed
Most of the time it isn't the model. The last step is what makes the system steadily improve.

Finding problems nobody reports

Most people won't report a bad answer. They'll just stop using it. So actively look:

  • Thumbs up or down, with an optional comment
  • Behavioural signals: retries, rephrasing, quickly leaving, or asking for a human
  • Sampling: a person reviews a random sample each week
  • Automated checks: scoring answers for faithfulness to their sources, or checking the format
  • Dashboards: spend, latency, error rates and refusals, by feature and prompt version
  • Alerts on spikes, particularly on cost. A runaway loop can be expensive. See how to control AI API costs.

Privacy and security

Logs of prompts can contain everything your users typed, so treat them as sensitive.

  • Redact personal data before storage, where possible. Don't assume that your filters catch everything.
  • Never log secrets. Check that API keys don't end up in prompts or tool results.
  • Limit access to a small group, and record who views logs.
  • Set a retention period, and delete on schedule.
  • Include logging in your privacy notice, and honour deletion requests.
  • Consider sampling full-text logs, keeping only metadata for the rest.
  • Check where a logging vendor stores your data, and on what terms.

Tools

You can start with structured logs in your existing system. Dedicated tools add trace views, prompt management and evaluations. Options include Langfuse and Arize Phoenix, which have open-source versions, and LangSmith, Helicone and others. Compare current features and pricing, and check that you can self-host if your data requires it.

Don't choose a tool first. Begin with one simple table of logged calls, and add a tool once you feel the pain.

Common mistakes

  • Logging the user's message, but not the final prompt. That's the most important thing to see.
  • Not versioning prompts. You can't connect a drop in quality to a change.
  • Ignoring stop reasons, and missing truncated answers.
  • Testing only happy paths.
  • Looking only at averages. Your worst 1% of traces often reveal the most.
  • Logging forever.

Before you launch

Check that you can answer these questions from your logs:

  1. What exactly did the model see for this answer?
  2. Which prompt and model version were used?
  3. How much did this feature cost yesterday?
  4. Which documents get retrieved but never help?
  5. Which customers are seeing the most failures?

If you can't, then you'll be debugging from guesses. Also see how to handle LLM failures gracefully.

If you'd like help making your AI feature reliable, and easier to debug, book a call.

Common questions

What should I log for an LLM application?

Log the final prompt, retrieved context, tool calls, model version, parameters, response, stop reason, tokens, cost, latency and a trace ID. Add prompt version and user feedback. Redact personal data and limit retention, as these logs can be very sensitive.

How do you debug a wrong answer from an AI?

Find its trace and read exactly what the model saw. Then decide whether the problem lies in the source data, retrieval, context, prompt, tool or model. Replay it, change one thing at a time, and add the case to your tests.

What is LLM observability?

It means being able to see how your AI feature behaves in production, including prompts, responses, steps, costs, latency and quality. It's different from basic monitoring, as a failure often looks like a normal successful response with a wrong answer.

Is it safe to log prompts and responses?

It can be, with care. They often contain personal or confidential data, so redact what you can, restrict access, set retention limits, and cover logging in your privacy notice. Check any vendor's terms before you send them this data.

Have something worth building right?