Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 61

Tracing and Debugging Agent Execution

This lesson is built with resources from digitalocean.com and decodingai.com.

Hello! Welcome to the next lesson in our module on the Foundations of AI Agents.

In our last lesson, you built a business analyst agent that could intelligently select the correct tool for a given task based on the user's request. We focused on how clear tool descriptions—especially the docstrings—are crucial for guiding the agent's reasoning.

However, as any software engineer knows, just because the code runs doesn't mean it works as intended. Agents, with their layers of non-deterministic models and complex state, can fail in subtle and confusing ways. A simple print() statement won't be enough to untangle why an agent chose the wrong tool, got stuck in a loop, or hallucinated an answer.

This lesson directly addresses that challenge. We will shift our focus from building to debugging. You will learn how to trace an agent's execution flow to see its intermediate reasoning steps and tool calls, allowing you to systematically diagnose and fix problems.

What is an Agent Execution Flow?

Before we can debug a flow, we need a clear mental model of what it is. In our previous lessons, we've discussed the ReAct (Reason+Act) pattern. An agent's execution flow is simply the sequence of steps in this pattern.

Agentic Workflows Diagram
This diagram shows the high-level agentic workflow. Each cycle of "Make a plan" (Reason/Thought), "Execute actions" (Act), and "Reflect on results" (Observation) constitutes one step in the execution flow.

Let's break down this theoretical loop into the concrete steps that frameworks like LangGraph implement.

Building Production ReAct Agents From Scratch Is Simple

The article "Building Production ReAct Agents From Scratch Is Simple" does an excellent job of dissecting a LangGraph agent to reveal its inner workings. Reading this will solidify your understanding of the step-by-step process we need to trace.

Please read the sections "The ReAct LangGraph Graph", "Successful Example", and "Unsuccessful Example". As you read, focus on how the AgentState (messages list) grows with each step, creating a log of the agent's history. This sequence of state changes is the execution trace.

As you've just read, an execution trace is essentially a log of the conversation between the user, the LLM, and the tools. A single turn might look like this:

  1. HumanMessage: The user's initial prompt.
  2. AIMessage (Thought): The LLM analyzes the prompt and decides to call a tool. The message contains a tool_calls attribute.
  3. ToolMessage (Action & Observation): The framework executes the tool and appends the result to the message history. This message contains the content returned by the tool.
  4. AIMessage (Thought): The LLM observes the ToolMessage and decides its next step—either generating a final answer or calling another tool.

When an agent fails, the error is located somewhere in this sequence. Our goal is to find it.


The Challenge of Debugging Agents

Your experience as a backend developer has likely involved debugging complex, distributed systems. Debugging AI agents shares some of that difficulty. You can't just set a breakpoint inside the LLM to see why it made a certain decision.

LangSmith Explained: Debugging and Evaluating LLM ...

The article "LangSmith Explained" clearly articulates why debugging agents requires specialized tools.

Please read the section "The Agent Debugging Problem LangSmith Solves". It highlights the limitations of standard logging and the types of subtle failures that can occur.

The key challenges are:

  • Silent Failures: The agent might not crash; it might just give a wrong answer, hallucinate, or get stuck in a repetitive loop.
  • Non-Determinism: The same input can sometimes produce different reasoning paths, making failures hard to reproduce.
  • Complex State: The agent's "scratchpad" or message history is the full context. An error could be caused by a piece of information from several turns ago.

To overcome this, we need a way to capture the entire execution flow for inspection. This is where tracing comes in.


Tracing Agent Execution with LangSmith

LangSmith is a platform from the creators of LangChain, designed specifically for debugging, testing, and monitoring LLM applications. Its core feature is tracing. It automatically intercepts calls to LLMs, tools, and other components, and logs them in a structured, visual timeline.

Let's integrate it into the business analyst agent we built in the last lesson.

Step 1: Get Your LangSmith API Key

  1. Go to the LangSmith website and sign up for an account.
  2. Navigate to the "API Keys" section in your settings and create a new key.

Step 2: Set Up Your Environment

LangSmith tracing can be enabled by setting a few environment variables. In your Python script or terminal, set the following:

import os

os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "YOUR_LANGSMITH_API_KEY" # Replace with your key
# os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY" # Make sure this is also set

By setting LANGCHAIN_TRACING_V2 to "true", any LangChain application will automatically start sending traces to your LangSmith project. It's that simple.

Step 3: Run the Agent and Observe the Trace

Now, let's run a slightly modified version of our previous agent. We'll add a deliberately ambiguous tool to see how the agent handles it.

# Make sure you have langsmith installed: pip install langsmith
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langgraph.prebuilt import create_agent_executor
from langgraph.checkpoint.memory import InMemorySaver
from typing import Optional

# Tools from the previous lesson
@tool
def search_company_info(company_name: str, info_type: Optional[str] = "overview") -> str:
    """
    Search for company qualitative information.
    Use this for questions about a company's background, general info, or recent news.
    """
    print(f"\n>> Called search_company_info(company_name='{company_name}', info_type='{info_type}')")
    if "innovate" in company_name.lower():
        if info_type == "news":
            return f"Latest news for Innovate Inc: Expanded to new markets."
        else:
            return f"Innovate Inc. is a leading technology company specializing in AI solutions."
    return f"Sorry, I couldn't find any information on {company_name}."

@tool
def get_financial_data(company_name: str) -> str:
    """
    Retrieves quantitative financial data for a company.
    Use this for questions about revenue, profit, or market position.
    """
    print(f"\n>> Called get_financial_data(company_name='{company_name}')")
    if "innovate" in company_name.lower():
        return f"Financial data for {company_name}: Revenue $10M, Profit $2M, Growth 25%."
    return f"Sorry, no financial data found for {company_name}."
    
tools = [search_company_info, get_financial_data]

# Setup the agent with tracing enabled
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0)
memory = InMemorySaver()
agent_executor = create_agent_executor(llm, tools, checkpointer=memory)

thread_id = "business-analyst-debug-1"
config = {"configurable": {"thread_id": thread_id}}

# This query is intentionally ambiguous. "status" could mean news or financials.
query = {"messages": ["What is the latest status of Innovate Inc?"]}
print("--- Running ambiguous query ---")

for event in agent_executor.stream(query, config):
    print(event)

print("\n--- Run complete. Check your LangSmith project for the trace! ---")

After running this code, go to your LangSmith project. You will see a new trace listed. Click on it to explore the full execution flow.


How to Read a Trace and Diagnose Failures

The LangSmith UI provides a detailed view of the agent's run.

AI Agent Trace Details and LLM Interaction
An example of a trace visualization. On the left, you see the hierarchy of calls (the "run tree"). On the right, you see the specific inputs and outputs for a selected step, like an LLM call.

When looking at a trace, you are playing detective. Your goal is to pinpoint where the agent's reasoning went off-track. Here is a systematic way to approach it, based on common failure modes.

LangSmith Explained: Debugging and Evaluating LLM ...

The following table from "LangSmith Explained" provides an excellent framework for diagnosing issues by reading traces. I've adapted it below.

Review the table in the "Reading Traces" section. It categorizes failures and links them to what you'd see in a trace.

Here are the key failure patterns to look for in your trace:

Failure Type What It Looks Like in the Trace Likely Fix
Tool Failure A ToolNode step shows an error message or returns an empty/unexpected result. The subsequent AIMessage might show the LLM trying to recover or just giving up. Improve the tool's internal logic and error handling. Make sure it returns a helpful message on failure so the agent can reason about it.
Prompt/Reasoning Failure All tool calls return the correct information, but the final AIMessage from the LLM is wrong, hallucinated, or ignores the tool's output. Inspect the final LLM call in the trace. The issue is likely in your system prompt. You may need to add more explicit instructions, provide examples (few-shot), or adjust model parameters like temperature.
Orchestration Failure The agent calls the wrong tool, gets stuck in a loop calling the same tool repeatedly, or fails to call a tool when it should have. This is often a tool design issue. Inspect the AIMessage where the wrong tool was chosen. Compare the user's query to the docstrings of the available tools. The fix is usually to make the docstrings more distinct and explicit about when each tool should (and should not) be used.
Test your understanding!

Look at the trace generated by the Python code you just ran for the query "What is the latest status of Innovate Inc?".

  1. Which tool did the agent choose to call?
  2. Based on the trace, was this a good choice? Why or why not?
  3. This is an example of which failure type from the table above?
  4. How would you modify the docstrings of search_company_info and get_financial_data to make the agent's choice less ambiguous for a query like this?
Show answer
  1. The agent likely chose search_company_info. (The exact result can vary slightly due to the non-deterministic nature of the LLM).

  2. It's an okay choice, but not perfect. "Status" is ambiguous. The user might have wanted financial status. The agent picked the more "general" tool.

  3. This is a mild Orchestration Failure. The agent made a plausible but not necessarily correct choice due to ambiguity. In more critical scenarios, this could lead to wrong answers.

  4. To fix this, we can make the docstrings more specific and even reference each other:

    • search_company_info docstring: "Search for qualitative company information like its background, mission, or recent news announcements. For quantitative data like revenue or profit, use the get_financial_data tool."
    • get_financial_data docstring: "Retrieves quantitative financial data for a company, such as revenue, profit, and market position. For general news or company background, use the search_company_info tool."

    This cross-referencing helps the LLM better distinguish the boundary between the two tools.


Conclusion

You are now equipped with the fundamental skill of debugging AI agents. Just as you wouldn't write backend code without proper logging and monitoring, you shouldn't build agents without a robust tracing mechanism.

Key Takeaways:

  • An agent's execution flow is the sequence of Thought, Action, and Observation steps, materialized as a history of messages.
  • Debugging agents is challenging due to silent failures and non-determinism, requiring specialized tools like LangSmith.
  • Tracing provides a complete, structured log of an agent's run, allowing you to inspect every LLM call, tool execution, input, and output.
  • By analyzing traces, you can systematically diagnose common failures, whether they lie in the tool's logic, the agent's core prompt, or the tool descriptions that guide its decisions.

What's Next?

Having mastered the essentials of building, managing, and now debugging ReAct agents, you are ready to tackle more sophisticated agentic systems. In the next module, "Advanced Agent Architectures," we will move beyond the simple single-thought loop. Our first lesson will focus on building an agent that can create a multi-step plan to solve a complex task, a crucial step towards building truly powerful and autonomous AI.