Skip to content

Module 2: Additional Suggested Resources

Carlos Lizarraga-Celaya edited this page Oct 1, 2026 · 3 revisions

2.4 Additional Suggested Resources

This page complements the Module 2 lessons with reference notes and runnable code examples. It is optional, but it is the most direct bridge between the Chapter 1–3 concepts and the code you write in the Guided Lab and the Hands-On Project.

Note

Version note. All code on this page uses LangChain 1.x and its create_agent function, which replaces the legacy AgentExecutor, create_react_agent and create_tool_calling_agent APIs. The examples were tested with langchain 1.4. If you find older tutorials that import AgentExecutor from langchain.agents, they will not run on current versions; see the migration table in Section 9.

1. Primary LLM Agent Reasoning Paradigms

Paradigm Structure Relative cost Best suited for
Chain-of-Thought (CoT) A single linear sequence of intermediate reasoning steps, generated entirely from the model's internal (parametric) knowledge. No external tools. Low: one generation per answer. Arithmetic, symbolic and logical problems that benefit from step-by-step deduction and need no external information.
ReAct (Reason + Act) A linear loop that interleaves reasoning (Thought) with tool use (Action) and the tool's result (Observation), repeated until the model can answer. Moderate: one model call per loop iteration. Multi-hop questions and workflows that need live or external information and adapt as results arrive.
Tree of Thoughts (ToT) Generates several candidate reasoning steps at each stage, evaluates them (with a heuristic or the model itself), and searches the resulting tree with breadth-first or depth-first search, including backtracking. High: many generations and evaluations per problem. Problems with a large solution space, where intermediate steps can be evaluated and early mistakes are costly.
Language Agent Tree Search (LATS) Combines ToT's tree search with ReAct's tool use and adds self-reflection. Each node in the tree is an action and its observation, so the search is guided by real feedback from the environment rather than only by the model's own judgment. Highest: many model and tool calls per task, plus state management for the tree. Tasks that need both deliberate planning over many alternatives and live information during the search, when cost and latency permit.

The four paradigms form a progression: from linear to branching, from reasoning only to reasoning with action, and from low to high cost. The Chapter 1 lesson develops this progression, and the Chapter 5 lesson explains how to choose among them.


2. The ReAct Loop

ReAct (Yao et al., 2023) runs a repeated cycle of three phases:

  • Thought. The model reviews the conversation so far, identifies what information is missing, and decides on the next step.
  • Action. The model selects a tool and specifies its arguments.
  • Observation. The tool runs and returns a result, which is added to the agent's context.

After each Observation, the model decides whether it has enough information. If it does, the loop ends and the agent produces its final answer. If not, the cycle repeats with a new Thought. In practice, a framework also enforces a maximum number of steps, so an agent that never reaches an answer is stopped rather than looping indefinitely.

Tip

One loop, three sets of names. The ReAct paper uses Thought / Action / Observation. Some lessons shorten these to Thought / Act / Observe. In create_agent, the same phases appear as an assistant message (Thought), a tool call inside that message (Action), and a tool message containing the result (Observation). Section 7 shows how to read them.


3. ReAct Compared with Tree of Thoughts

The main difference is how each paradigm explores solutions.

  • ReAct follows one path. The agent thinks, acts, observes the result and continues. It is fast and practical, and it is the default for tool-using agents in production.
  • Tree of Thoughts explores several paths. It branches into alternative reasoning steps, scores each branch and pursues the most promising ones, backtracking when a branch fails.

The trade-off. ReAct is cheaper and faster, but because it commits to a single path, an early wrong assumption can carry through to the final answer. ToT can recover from wrong turns and weigh alternative strategies, but it may require dozens of model calls for a single problem. LATS extends ToT by grounding each branch in real tool results, at even higher cost.


4. The Belief–Desire–Intention (BDI) Architecture

The BDI architecture is a classic model from agent research that describes an agent's decision-making in terms of three mental states:

  • Beliefs. What the agent holds to be true about its environment. For an LLM agent, this is its pre-trained knowledge plus everything it has observed during the task.
  • Desires. The goals the agent wants to achieve, which usually correspond to the user's request and the objectives in the system prompt.
  • Intentions. The plans the agent has committed to, expressed in an LLM agent as the sequence of tool calls it decides to execute.

BDI is useful as a lens for analyzing modern agents. In a create_agent agent, beliefs correspond to the message history (Section 5), desires to the system prompt and user message, and intentions to the tool calls the model emits.


5. Functional Components of a Tool-Calling Agent in create_agent

A tool-calling agent can be described by four functional components. The table shows how each one is realized in create_agent.

Component Role In create_agent
Model (LLM backbone) Interprets the request, reasons, and decides which tool to call or when to answer. The model argument: a chat model instance or a provider string such as "openai:gpt-4o-mini". The model must support tool calling.
Tool registry The set of available tools, each with a name, a description and an argument schema that tell the model what it can do. The tools argument: functions decorated with @tool, BaseTool objects, or tool schemas. The docstring becomes the tool description.
Tool executor Runs the tool the model selected, with the arguments the model generated, and returns the result. Built in. The agent's tool node executes each tool call and adds the result to the conversation as a ToolMessage.
Memory Keeps track of the conversation, tool calls and observations so the model has context at each step. The agent's state, a list of messages, provides short-term memory within a run. Adding a checkpointer persists that state across separate invocations (Section 8).

Information flow during one task

  1. The user's message, together with the system prompt and any earlier messages in the state, is sent to the model.
  2. The model reads the available tool descriptions and either answers directly or returns one or more tool calls: structured requests containing a tool name and arguments.
  3. The tool executor runs each requested tool and appends the result to the state as a tool message.
  4. The updated message list is sent back to the model, which evaluates the new information.
  5. The loop repeats until the model returns a message with no tool calls. That message is the final answer.

Because the model returns tool calls as structured data rather than as text, create_agent does not need a separate output parser to turn the model's text into a tool call, and there is no agent_scratchpad placeholder in the prompt. The message list itself is the scratchpad.


6. Building a ReAct Agent with create_agent

The example below builds a project-assistant agent with two tools. Notice how much of the specification work is in the tool docstrings: they follow the five-question discipline from the Chapter 2 lesson (what the tool does, when to use it and when not to, its arguments, its output, and its error state).

# pip install -U langchain langchain-openai
from langchain.agents import create_agent
from langchain.tools import tool

@tool
def get_task_status(task_id: str) -> str:
    """Look up the current status of a project task.

    Use this tool when the user asks about the progress, owner, or due date
    of a specific task. Do not use it for questions about documentation.

    Args:
        task_id: The task identifier, for example "task1".

    Returns:
        A one-line status string, or "NOT_FOUND" if the task does not exist.
    """
    statuses = {"task1": "In progress (owner: Ana, due Oct 15)"}
    return statuses.get(task_id, "NOT_FOUND")

@tool
def search_docs(query: str) -> str:
    """Search the project documentation and return the most relevant passage.

    Use this tool for questions about procedures, definitions, or policies.
    Do not use it to check the status of a task.

    Args:
        query: A short plain-English search phrase (3-10 words).
    """
    return "Tasks move from 'In progress' to 'Review' when the owner opens a pull request."

agent = create_agent(
    model="openai:gpt-4o-mini",          # any chat model that supports tool calling
    tools=[get_task_status, search_docs],
    system_prompt=(
        "You are a project assistant. Use the tools to answer questions about "
        "project tasks and documentation. If a tool returns NOT_FOUND, say so; "
        "do not guess."
    ),
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "What's the status of task1?"}]}
)
print(result["messages"][-1].content)

What changed from the legacy approach

  • There is no separate executor object. create_agent returns a runnable agent that contains the loop.
  • The system prompt is a plain string passed as system_prompt. There is no prompt template with {input} and {agent_scratchpad} placeholders.
  • The agent's input and output are a dictionary with a messages list, not {"input": ...} and {"output": ...}. The final answer is the last message.

To use a free local model instead of OpenAI, install langchain-ollama, start Ollama, and pass model=ChatOllama(model="llama3.2") (from langchain_ollama import ChatOllama). Choose a model that supports tool calling.


7. Reading the Reasoning Trace

In the legacy AgentExecutor, verbose=True printed text lines labeled Thought:, Action:, Action Input: and Observation:. create_agent has no verbose mode. Instead, the complete trace is the list of messages the agent returns, and you can label it yourself:

for msg in result["messages"]:
    if msg.type == "human":
        print(f"USER:        {msg.content}")
    elif msg.type == "ai" and msg.tool_calls:
        if msg.content:                                  # reasoning text, if any
            print(f"THOUGHT:     {msg.content}")
        for call in msg.tool_calls:
            print(f"ACTION:      {call['name']}({call['args']})")
    elif msg.type == "tool":
        print(f"OBSERVATION: {msg.content}")
    elif msg.type == "ai":
        print(f"FINAL:       {msg.content}")

A typical output:

USER:        What's the status of task1?
THOUGHT:     I need the status of task1, so I'll check the task tracker.
ACTION:      get_task_status({'task_id': 'task1'})
OBSERVATION: In progress (owner: Ana, due Oct 15)
FINAL:       task1 is in progress, owned by Ana and due October 15.

To watch the loop as it runs, stream the agent's updates. Each update shows which part of the agent produced the new message: model for Thought and Action, tools for Observation.

for step in agent.stream(
    {"messages": [{"role": "user", "content": "What's the status of task1?"}]},
    stream_mode="updates",
):
    for node, update in step.items():
        update["messages"][-1].pretty_print()

Important

The Thought may be empty. With native tool calling, many models return a tool call without any accompanying reasoning text. When you need visible reasoning for trace analysis (Chapter 3), add an instruction to the system prompt such as "Before each tool call, state in one sentence what you need and why." For production systems, tracing tools such as LangSmith record the same messages with timing and cost.

The Chapter 3 failure classes map directly onto these messages: incorrect tool selection appears in the tool call's name, a malformed call in its args, observation misinterpretation in the assistant message that follows a tool message, and loop failures in repeated, unproductive tool calls.


8. Structured Output, Error Handling, Limits and Memory

8.1 Structured output

Pass a Pydantic model as response_format to receive a validated object in addition to the message history. With ToolStrategy, the schema is offered to the model as a final "answer" tool, and invalid responses are sent back to the model to correct. With ProviderStrategy, the model provider's native structured output is used, where available. Passing the Pydantic model directly lets LangChain choose.

from typing import Literal
from pydantic import BaseModel, Field
from langchain.agents.structured_output import ToolStrategy

class TaskReport(BaseModel):
    """Structured answer about a project task."""
    task_id: str = Field(description="The task identifier that was looked up")
    status: str = Field(description="Current status as reported by the tracker")
    confidence: Literal["Low", "Medium", "High"] = Field(
        description="Confidence that the status is current"
    )

agent = create_agent(
    model="openai:gpt-4o-mini",
    tools=[get_task_status, search_docs],
    system_prompt="You are a project assistant.",
    response_format=ToolStrategy(TaskReport),
)

result = agent.invoke({"messages": [{"role": "user", "content": "Status of task1?"}]})
print(result["structured_response"])
# task_id='task1' status='In progress' confidence='High'

This is the code-level counterpart of the output format constraints dimension in Chapter 4. A format instruction in the system prompt is followed probabilistically; response_format is validated.

8.2 Error handling and loop limits

Middleware wraps the agent's model calls and tool calls. It can observe them, for logging or monitoring, and it can also change behavior, for example by retrying, stopping, or requesting human approval. The example below uses a custom wrapper to turn tool exceptions into a structured error the model can reason about, and two built-in middleware to cap the number of calls.

from langchain.agents.middleware import (
    wrap_tool_call, ToolCallLimitMiddleware, ModelCallLimitMiddleware,
)
from langchain_core.messages import ToolMessage

@wrap_tool_call
def structured_tool_errors(request, handler):
    """Return a structured error to the agent instead of a raw traceback."""
    try:
        return handler(request)
    except Exception as e:
        return ToolMessage(
            content=(
                f'{{"status": "error", "tool": "{request.tool_call["name"]}", '
                f'"message": "{e}", '
                f'"recommendation": "Check the arguments or try a different tool."}}'
            ),
            tool_call_id=request.tool_call["id"],
        )

@tool
def divide(a: float, b: float) -> float:
    """Divide a by b. Use for arithmetic only. Raises an error if b is 0."""
    return a / b

agent = create_agent(
    model="openai:gpt-4o-mini",
    tools=[divide],
    middleware=[
        structured_tool_errors,
        ToolCallLimitMiddleware(run_limit=5),     # at most 5 tool calls per run
        ModelCallLimitMiddleware(run_limit=10),   # at most 10 model calls per run
    ],
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "What is 1/0?"}]},
    config={"recursion_limit": 25},               # hard stop on total graph steps
)

The recursion_limit setting replaces max_iterations from AgentExecutor. It counts every step of the underlying graph, so a value of about twice the number of tool calls you expect, plus a margin, is a reasonable starting point. The call-limit middleware gives finer control and lets the agent finish gracefully instead of raising an error. These mechanisms address the loop failure class in Chapter 3 and the undocumented error problem in Chapter 2.

8.3 Memory across turns

By default, each invoke call starts with only the messages you pass in. To let the agent remember earlier turns of a conversation, add a checkpointer and identify the conversation with a thread_id:

from langgraph.checkpoint.memory import InMemorySaver

agent = create_agent(
    model="openai:gpt-4o-mini",
    tools=[get_task_status, search_docs],
    checkpointer=InMemorySaver(),
)

config = {"configurable": {"thread_id": "session-1"}}
agent.invoke({"messages": [{"role": "user", "content": "My name is Maria."}]}, config=config)
result = agent.invoke({"messages": [{"role": "user", "content": "What is my name?"}]}, config=config)
print(result["messages"][-1].content)   # the agent can answer from the earlier turn

InMemorySaver keeps memory only while the program runs. Production systems use a database-backed checkpointer. Longer-term memory and retrieval are covered in Module 3.


9. Migrating from AgentExecutor to create_agent

Use this table when you meet legacy code in tutorials, videos, or older notebooks.

Legacy (AgentExecutor) Current (create_agent)
from langchain.agents import AgentExecutor, create_tool_calling_agent (or create_react_agent) from langchain.agents import create_agent
Two steps: build an agent, then wrap it in AgentExecutor(agent=..., tools=...) One step: agent = create_agent(model=..., tools=...)
PromptTemplate or ChatPromptTemplate with {input} and {agent_scratchpad} system_prompt="..."; the message list replaces the scratchpad
Tool(name=..., func=..., description=...) from langchain.tools @tool decorator with a docstring, from langchain.tools
Text output parsed for Action: / Action Input: Native tool calls returned by the model as structured data
executor.invoke({"input": "..."}) → result["output"] agent.invoke({"messages": [...]}) → result["messages"][-1].content
verbose=True Inspect or stream the message list; use tracing tools such as LangSmith
max_iterations=5 config={"recursion_limit": ...} and/or call-limit middleware
handle_parsing_errors=True Usually unnecessary with native tool calls; handle tool errors with wrap_tool_call middleware
memory=ConversationBufferMemory(...) checkpointer=InMemorySaver() plus a thread_id
Output format requested in the prompt response_format= with a Pydantic schema

If you must run legacy code unchanged, the old classes are available in the separate langchain-classic package. New work in this course should use create_agent.


10. Further Reading


Created: 05/09/2026 (C. Lizárraga)
Updated: 09/30/2026 (C. Lizárraga)

Clone this wiki locally