The Engineer’s Guide to Debugging AI Agents: From Hallucinations to Reliable Systems
AI agents fail in ways a stack trace can't explain. This guide gives you a per-step log format, a checklist for the three most common failures (context overflow, bad tool arguments and reasoning loops), a bug report template for flaky runs, and agent tests you can run with a fake model. Code uses LangChain's create_agent and middleware.

This guide is for engineers whose AI agent works in a demo and then fails in real use: it loops, invents a tool argument or ignores an instruction. You will learn what to log for every step, how to find which layer failed, and how to fix the three most common failures. Then you will lock each fix in with tests that run against a fake model, so they cost nothing to run.
Key takeaways
- Log the full message list the model saw at every step, not just the last message. Most agent bugs live in that context.
- Find the failing layer before you touch the prompt: context, tool schema or control flow. Each one has its own fix.
- Turn every bug you fix into a test. A fake model makes agent tests free and repeatable.
Why agent bugs are different
In normal code, the same input gives the same output. When it breaks, a stack trace points to the line.
An agent is different. A model decides which tool to call, with which arguments, and when to stop. Debugging an AI agent means finding out what the model saw and decided at each step, then changing the context, tools or limits that led it astray. A stack trace rarely helps, because nothing crashed. The model just made a poor choice. A hallucination in an agent is usually one of these choices: an invented tool argument, a made-up fact or a claim that a step succeeded when it didn't. The checklist below traces each one back to its cause.
A breakpoint doesn't help much either. Pausing the code doesn't show why the model chose that tool. You need a record of each step: the messages in, the reply out, and every tool call and result.
What to log for every step
If you use a tracing tool such as LangSmith or Arize Phoenix, it records most of this for you. To learn how those tools hook into LangChain, read the guide to LangChain callbacks for debugging. Without one, log at least this record for each model step:
{
"run_id": "3f1c0c2e-...",
"step": 3,
"model": "gpt-6-luna",
"input_messages": [
{"role": "system", "content": "..."},
{"role": "user", "content": "..."},
{"role": "assistant", "content": "", "tool_calls": [{"name": "search", "args": {"q": "..."}}]},
{"role": "tool", "content": "Search results: ..."}
],
"output": {"content": "...", "tool_calls": []},
"approx_tokens": 5120,
"latency_ms": 1400
}
The key field is input_messages. Log the whole context the model saw, not just the newest message. Many failures come from that context: an old error, a huge tool result, or an instruction buried in the middle.
Install the packages first (Python 3.10 or newer):
pip install -U langchain langchain-openai pytest
Here is a small helper that writes a finished run to a JSON Lines file, one line per message. Create agent_debug.py:
# agent_debug.py
import json
import os
import uuid
from langchain.agents import create_agent
from langchain.agents.middleware import ModelCallLimitMiddleware, ToolCallLimitMiddleware
from langchain.tools import tool
from langchain_core.messages.utils import count_tokens_approximately
from pydantic import BaseModel, Field
def dump_trace(result, path, run_id=None):
"""Write every message of a finished agent run to a JSON Lines file."""
run_id = run_id or str(uuid.uuid4())
messages = result["messages"]
with open(path, "a") as f:
for step, m in enumerate(messages):
f.write(json.dumps({
"run_id": run_id,
"step": step,
"type": m.type,
"content": m.text,
"tool_calls": getattr(m, "tool_calls", []),
}) + "\n")
return count_tokens_approximately(messages)
Checked against langchain@1.4.7, langchain-core@1.7.1, langchain-openai@1.7.3 and pydantic@2.14.1, 2026-10-29.
count_tokens_approximately from langchain_core gives a rough token count without calling a provider. It's enough to spot a context that is growing out of control.
The agent debugging checklist
When an agent fails, don't change the prompt first. Work out which layer failed:
| Failure | Symptom | Where to look | Fix |
|---|---|---|---|
| Context overflow | Ignores instructions or early facts | Size and order of the input messages | Trim or summarize; keep instructions in the system prompt |
| Tool schema failure | Validation errors or invented arguments | The tool call arguments in the trace | Strict input schemas; errors fed back to the model |
| Reasoning loop | Calls the same tool again and again | The sequence of tool calls | Call limits plus a "don't repeat" rule |
1. Context overflow (the memory-loss bug)
Symptom: the agent forgets an instruction from the start, or ignores a constraint it followed earlier.
Cause: the context is long, and the instruction is buried. Retrieved documents and big JSON tool results grow fast. The "Lost in the Middle" study found that models use information near the start or end of a long input better than information in the middle.
Debug action: print the exact messages sent to the model at the failing step. Is the instruction still there? Is it under 400 lines of tool output?
Fix: cut tool results down to the fields the agent needs before you return them. For long chats, add SummarizationMiddleware, which summarizes older messages once a token or message threshold is passed.
2. Tool schema failure (the fat-finger bug)
Symptom: a tool call fails validation, or the agent passes made-up arguments.
Cause: the model guesses formats it can't know. If a tool needs a user ID like usr_8923 and the model sends 8923, the schema didn't make the format clear or didn't enforce it.
Fix: describe and enforce the format with a Pydantic schema, rather than only explaining it in the docstring. The LangChain tools docs show Pydantic models passed as args_schema:
# Not this: the format lives only in prose, and nothing checks it.
# @tool
# def get_user(user_id: str) -> str:
# """Look up a user. The id looks like usr_8923."""
class GetUserArgs(BaseModel):
user_id: str = Field(pattern=r"^usr_\d+$", description="User id, for example usr_8923")
@tool(args_schema=GetUserArgs)
def get_user(user_id: str) -> str:
"""Look up a user by id."""
return f"{user_id}: Priya, plan=pro"
In a test with the versions above, a call with user_id="8923" didn't crash the agent. create_agent sent the validation error back to the model as a tool message ("String should match pattern..."), so the model could correct itself on the next step. For other exceptions inside your tools, the tools docs show a wrap_tool_call middleware that turns errors into messages, and ToolRetryMiddleware retries failed calls with backoff.
3. Reasoning loop (the spinning-wheel bug)
Symptom: the agent calls the same tool five times with the same input, gets the same error, and doesn't stop.
Cause: nothing tells it to change course, and nothing stops the run.
Debug action: read the sequence of tool calls in the trace. Look for repeats with identical arguments.
Fix: do two things. Add a rule to the system prompt, and add hard limits in code, because a prompt is only a request:
SYSTEM_PROMPT = (
"You are a support agent. If a tool call fails, read the error and change the "
"arguments. Never repeat a call with the same arguments. If you can't fix it, "
"say what failed."
)
def build_agent(model):
return create_agent(
model,
tools=[get_user],
system_prompt=SYSTEM_PROMPT,
middleware=[
ToolCallLimitMiddleware(run_limit=5), # at most 5 tool calls per user message
ModelCallLimitMiddleware(run_limit=10), # at most 10 model calls per user message
],
)
Both are prebuilt LangChain middleware. Once ToolCallLimitMiddleware reaches its limit, it blocks further tool calls by default and returns an error message for each one, so the model learns it must stop calling tools. ModelCallLimitMiddleware ends the run when the model has been called too often. Pick limits from what a normal run needs, plus some headroom. That is a rule of thumb, so check your traces.
Finish agent_debug.py with a main guard, so tests can import it without an API key:
if __name__ == "__main__":
from langchain.chat_models import init_chat_model
# Needs OPENAI_API_KEY. Check the provider's models page for current ids.
agent = build_agent(init_chat_model(os.getenv("CHAT_MODEL", "openai:gpt-6-luna")))
result = agent.invoke({"messages": [{"role": "user", "content": "Who is user 8923?"}]})
print(result["messages"][-1].text)
print("approx tokens:", dump_trace(result, "trace.jsonl"))
On the date above, OpenAI's models page lists gpt-6-luna as its most efficient model. Model ids change often, so check that page and set CHAT_MODEL to switch. Log the model id with every trace, because a model change can change behaviour.
A bug report template for flaky runs
Agent bugs are often intermittent. A run might fail, say, one time in ten, and you can't make it fail on demand. Write each bug down in the same shape (the values below are an example):
Agent failure report
Input: "Summarize the open tickets for usr_8923."
Expected: get_user -> list_tickets -> summary
Actual: get_user -> get_user -> get_user -> timeout
Model and config: CHAT_MODEL=openai:gpt-6-luna, middleware: call limits off
Trace: run_id 3f1c0c2e-...
Replay result: fails 3 of 10 replays with the saved messages
The replay line is the key step. Save the exact message list from the failing step, send it to the model several times, and count the failures. Use the most deterministic settings your model allows, but don't expect identical outputs every time. As a rule of thumb:
- Fails every time: the instruction or tool description is wrong or missing. Fix the prompt or the schema.
- Fails sometimes: the instruction is too weak to guide the model reliably. Make it more direct, add an example, or enforce it in code with a schema or limit.
Lock fixes in with tests
Fixing bugs one at a time is a trap. A prompt change that fixes case A can quietly break case B. The answer is a set of agent tests you run after every change.
The LangChain testing docs describe three levels: unit tests with fake models, integration tests against real APIs, and trajectory evaluations that check the steps an agent took. Start with unit tests. A fake model replays a scripted run, so you test your wiring, schemas and limits for free:
# test_agent_debug.py
from langchain.messages import AIMessage, ToolCall
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from agent_debug import build_agent, dump_trace
class FakeToolModel(GenericFakeChatModel):
def bind_tools(self, tools, **kwargs):
return self
def call(name, args, id):
return AIMessage(content="", tool_calls=[ToolCall(name=name, args=args, id=id)])
def run(agent, text):
return agent.invoke({"messages": [{"role": "user", "content": text}]})
def test_bad_id_is_sent_back_to_the_model():
model = FakeToolModel(messages=iter([
call("get_user", {"user_id": "8923"}, "1"), # wrong format
call("get_user", {"user_id": "usr_8923"}, "2"), # corrected after the error
AIMessage(content="User usr_8923 is Priya."),
]))
messages = run(build_agent(model), "Who is user 8923?")["messages"]
tool_results = [m.text for m in messages if m.type == "tool"]
assert "should match pattern" in tool_results[0]
assert "Priya" in tool_results[1]
def test_loop_is_stopped_by_the_limit():
looping = [call("get_user", {"user_id": "usr_1"}, str(i)) for i in range(20)]
model = FakeToolModel(messages=iter([*looping, AIMessage(content="I could not finish.")]))
messages = run(build_agent(model), "Find user 1")["messages"]
real_results = [m for m in messages if m.type == "tool" and "limit" not in m.text.lower()]
assert len(real_results) == 5
def test_simple_question_needs_no_tools(tmp_path):
model = FakeToolModel(messages=iter([AIMessage(content="Paris.")]))
result = run(build_agent(model), "What is the capital of France?")
assert not any(getattr(m, "tool_calls", None) for m in result["messages"])
assert dump_trace(result, tmp_path / "trace.jsonl") > 0
Run them with pytest test_agent_debug.py.
The earlier version of this post asserted on agent.run(...).tool_calls. That couldn't work, because run returned a plain string. The tests above read the message list that invoke returns, which holds every tool call and result.
Fake models test the plumbing, not the model's judgment. For that, collect real inputs with the outcomes you expect, run them against the real model after each prompt change, and grade the answers. LangSmith supports LLM-as-a-judge evaluators, which use a model to grade runs at scale.
Make the agent boring
Debugging agents is less about clever prompts and more about visibility. Log every step, find the failing layer, fix it with the narrowest tool (a schema, a limit or a trim), and add a test so it stays fixed.
For the bigger picture of how agents are built, see how to build an AI agent from scratch. When you are ready to ship, read best practices for deploying LangChain to production.
Frequently asked questions
Why does my AI agent keep calling the same tool?
Usually the tool returns an error or an unhelpful result, and nothing in the context tells the model to change course. Add a system prompt rule against repeating identical calls, and add a hard cap such as ToolCallLimitMiddleware. Then read the tool results in the trace, because the real bug is often the tool's error message.
Can I make an LLM agent deterministic for debugging?
Not fully. Lower randomness settings reduce variation, but they don't guarantee the same output every time, and some models don't accept them. Replay the saved messages several times and measure the failure rate instead. Use a fake model when you need a fully repeatable test.
What should I log when debugging an AI agent?
For each step, log the run ID, the full message list the model received, its reply and tool calls, each tool result, the model id, a token count and the latency. The full message list matters most, because many failures come from what was or wasn't in the context.
How do I test an AI agent without paying for API calls?
Use a fake chat model that replays scripted replies, such as GenericFakeChatModel from langchain_core. Script the tool calls you want, then assert on the messages the agent returns. Keep a smaller set of integration tests against the real model for changes to prompts or models.
Sources
Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.
- LangChain docs: Tools (args_schema and error handling)
- LangChain docs: Prebuilt middleware (call limits, retries, summarization)
- LangChain docs: Test
- LangChain docs: Unit testing (fake chat models)
- LangSmith docs: Trace LangChain agents
- LangSmith docs: LLM-as-a-judge online evaluators
- Arize Phoenix docs: LangChain tracing
- Lost in the Middle: How Language Models Use Long Contexts, Liu et al.
- OpenAI API: Models
- langchain on PyPI
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...