Skip to main content
← Back to Blog
2026-02-22 · 11 min readAI AgentsPythonUpdated Oct 30, 2026

Architecting Autonomous Agents: A Builder’s Guide to Complex Workflows

A builder's guide to autonomous agents for multi-step tasks. You learn the ReAct loop, the three parts every agent needs (model, tools, state), when to split work across several agents, and the guardrails that keep a loop from running forever. Includes a small LangChain agent and a test that runs it against a fake model, with no API key spent.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
18 views
Architecting Autonomous Agents: A Builder’s Guide to Complex Workflows

This guide is for developers whose task has outgrown a single prompt: five steps, outside data and a decision in the middle. One LLM call, however clever the prompt, can't do that reliably. You will learn how an agent loop works, what parts it needs, when to split work across several agents, and which guardrails keep it from running away. A small LangChain agent and a free test with a fake model show each idea in code.

Key takeaways

  • An agent is a model that calls tools in a loop until the task is done. The loop (think, act, observe) is what separates it from a fixed chain.
  • The tool's name, description and argument schema matter more than the code inside it. The model reads them to decide when and how to call the tool.
  • Every agent needs hard limits in code: a step limit, argument validation and short tool results. A prompt alone won't stop a loop.

An AI agent is, in LangChain's words, "a model calling tools in a loop until a given task is complete." It isn't just a chatbot. It uses the model as a reasoning engine that decides which piece of software to run next.

This post is part 13 of the LLM & LangChain Fundamentals series. In part 12 you learned to see inside a run with LangChain callbacks for debugging. You'll need that visibility here, because agents fail in ways a chain doesn't.

The shift: from chains to loops

Early LLM apps were built as chains. A chain is a fixed sequence: the output of step A goes into step B. It is predictable and safe, but brittle.

If step A produces unexpected output, step B fails. And if the task needs to gather information before it can decide the next step, a chain can't do it.

Agents run in a loop, not a straight line:

  1. Observation: the agent looks at the current state (the user's request or the last tool result).
  2. Reasoning (thought): the model decides what to do next.
  3. Action: the agent runs a tool (an API call, a database query, a script).
  4. Loop: the tool's output becomes the next observation, and the cycle repeats until the goal is met.

This is the ReAct (Reason + Act) pattern, from a 2022 paper by Yao et al. The model alternates between reasoning steps and actions, so the actions pull in outside information and the reasoning adjusts the plan.

Chain Agent
Control flow Fixed: A always leads to B The model picks the next step
Trade-off Predictable and cheap, but rigid Flexible, but harder to test and to bound
Use it when The steps are known in advance The next step depends on what a tool returns

As a rule of thumb, start with a chain and move to an agent only when the path really depends on the data.

Core parts of an agent

An agent needs three parts.

1. The brain (the model)

The model does the routing, so it needs reliable tool calling. It must pick the right tool and fill in arguments that match the tool's schema. Small local models can work for narrow tasks, but as a rule of thumb, give a complex agent a strong tool-calling model and test it on your own tasks.

Model lists change often. On the date this post was checked, Anthropic's models page lists claude-sonnet-5-5 as "the best combination of speed and intelligence," and OpenAI's models page lists gpt-6-astra as its most capable model. Check both pages before you pick one, and read the id from an environment variable so you can switch without editing code.

2. The tools (the body)

An agent without tools can only talk. Tools are functions the agent can call. Here is a stock-price tool written as a LangChain tool. Install the packages first (Python 3.10 or newer):

pip install -U langchain langchain-anthropic pydantic

Create price_agent.py:

# price_agent.py
import os

from langchain.agents import create_agent
from langchain.agents.middleware import ModelCallLimitMiddleware
from langchain.tools import tool
from pydantic import BaseModel, Field

class PriceArgs(BaseModel):
    ticker: str = Field(
        pattern=r"^[A-Z]{1,5}$",
        description="Stock ticker in capital letters, for example AAPL (not the company name)",
    )

@tool(args_schema=PriceArgs)
def get_current_stock_price(ticker: str) -> str:
    """Fetch the current stock price for a ticker symbol such as AAPL."""
    prices = {"AAPL": 231.40, "MSFT": 512.10}  # stand-in for a call to your finance API
    if ticker not in prices:
        return f"No price found for {ticker}. Check the ticker symbol."
    return f"{ticker}: {prices[ticker]} USD"

Checked against langchain@1.4.7, langchain-core@1.7.3, langchain-anthropic@1.7.7 and pydantic@2.14.2, 2026-10-30.

The important part isn't the code inside the function. LangChain's tools docs say the docstring becomes the tool's description, which the model uses to decide when to call it. The Pydantic schema tells the model how to format the input, and it checks that input before your code runs.

3. The state (memory)

In a multi-step task, the agent must remember what it has already done. If it already searched for "vector database release notes," it shouldn't run the same search again. LangChain's create_agent keeps this state as a list of messages: every model reply, tool call and tool result is appended, and the model sees the whole list on its next turn.

Now wire the model, the tool and a limit together. Add this to price_agent.py:

SYSTEM_PROMPT = (
    "You are a market assistant. Use the tools to get prices and never guess a number. "
    "If a tool returns an error, fix the arguments or say what failed."
)

def build_agent(model):
    return create_agent(
        model,
        tools=[get_current_stock_price],
        system_prompt=SYSTEM_PROMPT,
        middleware=[ModelCallLimitMiddleware(run_limit=10)],  # at most 10 model calls per request
    )

if __name__ == "__main__":
    from langchain.chat_models import init_chat_model

    # Needs ANTHROPIC_API_KEY. Check the provider's models page for current ids.
    model = init_chat_model(os.getenv("AGENT_MODEL", "anthropic:claude-sonnet-5-5"))
    agent = build_agent(model)
    result = agent.invoke(
        {"messages": [{"role": "user", "content": "What is Apple's share price?"}]},
        config={"recursion_limit": 60},  # backstop in graph steps, see "Endless loops"
    )
    print(result["messages"][-1].text)

The run code sits under if __name__ == "__main__":, so a test can import build_agent without an API key. Only the model line is tied to a provider. To use OpenAI instead, install langchain-openai and set AGENT_MODEL to an id such as openai:gpt-6-astra.

Walk through one run

Take a research agent with two tools, a search tool and a page reader. This walk-through is illustrative: it shows the shape of a run, not output from real code. The goal: "Summarize the breaking changes in the latest release of vector database X." A model on its own may invent an answer, because the release came after its training data. An agent goes and looks.

Step 1: the first thought

The system prompt says: "You are a researcher. You have a search tool and a page reader. Use them to answer the user's request."

  • Input: "What are the breaking changes in the latest release of vector database X?"
  • Thought: "I don't know this. I need to search."
  • Action: a call to the search tool with the query "vector database X latest release breaking changes".

Step 2: the tool runs

Your code, not the model, runs the tool. It calls a search API (Tavily and Serper are two such services) and gets back a block of JSON results.

Step 3: observe and rethink

The results go back into the context as a tool message.

  • Thought: "One result links to the migration guide. I need to read that page."
  • Action: a call to the page reader with that guide's URL.

Step 4: the answer

The page reader returns the text. The agent now has what it needs.

  • Thought: "I have the information. I'll answer now."
  • Final output: "The latest release changes the following…"

You only defined the tools and the loop. The model chose the order of the steps.

Test the loop without an API key

You can check the wiring for free with a fake model that replays a scripted run. LangChain's testing docs describe this approach. Save this as test_price_agent.py next to price_agent.py:

# test_price_agent.py
from langchain.messages import AIMessage, ToolCall
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel

from price_agent import build_agent

class FakeToolModel(GenericFakeChatModel):
    def bind_tools(self, tools, **kwargs):
        return self

def call(args, id):
    return AIMessage(content="", tool_calls=[ToolCall(name="get_current_stock_price", args=args, id=id)])

def test_bad_ticker_is_sent_back_and_fixed():
    model = FakeToolModel(messages=iter([
        call({"ticker": "Apple"}, "1"),  # the company name, not the ticker
        call({"ticker": "AAPL"}, "2"),   # corrected after reading the error
        AIMessage(content="Apple trades at 231.40 USD."),
    ]))
    result = build_agent(model).invoke({"messages": [{"role": "user", "content": "Apple's price?"}]})
    tool_results = [m.text for m in result["messages"] if m.type == "tool"]
    assert "should match pattern" in tool_results[0]
    assert tool_results[1] == "AAPL: 231.4 USD"
    assert result["messages"][-1].text == "Apple trades at 231.40 USD."

def test_call_limit_ends_an_endless_loop():
    model = FakeToolModel(messages=iter([call({"ticker": "AAPL"}, str(i)) for i in range(50)]))
    result = build_agent(model).invoke(
        {"messages": [{"role": "user", "content": "Apple's price?"}]},
        config={"recursion_limit": 60},
    )
    model_turns = [m for m in result["messages"] if m.type == "ai" and m.tool_calls]
    assert len(model_turns) == 10
    assert "Model call limits exceeded" in result["messages"][-1].text

Run it with pip install -U pytest and then pytest test_price_agent.py. With the versions above, both tests passed. The GenericFakeChatModel subclass ignores bind_tools, because the fake model doesn't need the tool list; it only replays the messages you give it.

The first test shows the self-correction from the guardrails section below: the bad argument didn't crash the agent. create_agent sent the validation error back as a tool message, and the model fixed the call on its next turn.

Handle complexity with several agents

One agent loop works for moderate tasks. As tasks grow, one agent struggles. Its context fills up with tool results, instructions and reasoning.

One answer is to split the work across agents. LangChain's multi-agent docs describe several patterns. In the subagents pattern, a main agent calls specialist agents as tools and routes all the work:

  • Main agent: breaks the request into subtasks and hands them out.
  • Researcher: has only the search tools.
  • Coder: has only a code runner and file access.
  • Writer: only formats the final text.

Other patterns include handoffs, where agents pass control to each other, and routers, which classify the input and send it to the right specialist. You can build these with LangGraph or with other frameworks such as CrewAI.

The multi-agent docs give context management as a main reason: each agent gets the knowledge it needs "without overwhelming the model's context window." A narrow prompt and a short tool list also give each model fewer ways to go wrong. That last point is a rule of thumb, so test it on your own tasks.

Guardrails for production

A demo is easy. A robust agent is hard. These are the three failures you'll meet first.

1. Endless loops

Sometimes the agent gets stuck. It searches, doesn't find exactly what it wants, searches again with a slightly different query, and keeps going.

Fix: set limits in code, and know what each one counts.

  • ModelCallLimitMiddleware(run_limit=10) counts model calls. Once the limit is hit, it ends the run gracefully by default and returns a final message. This is your main cap.
  • recursion_limit counts graph steps, not model calls. LangGraph's docs define it as a cap on super-steps, and one agent turn takes several of them: the middleware, the model and the tools each run as a step. LangGraph's default is 10,007 steps, far too high to protect you. When the limit is reached, LangGraph raises GraphRecursionError.

Set recursion_limit above what your call limit needs, so the graceful cap fires first and the step limit is only a backstop. With the versions above and a fake model that calls the tool forever, the agent needed 42 steps to reach its 10th model call. With recursion_limit=25, it raised GraphRecursionError before the call limit could fire; with 60, as in the code above, the call limit ended the run. Pick limits from what a normal run needs, plus some headroom. That is a rule of thumb, so check your traces.

2. Bad tool arguments

The model might call the stock tool with ticker="Apple" instead of ticker="AAPL".

Fix: enforce the format with a Pydantic schema, as PriceArgs does, rather than only describing it in the docstring:

# Not this: the format lives only in prose, and nothing checks it.
# @tool
# def get_current_stock_price(ticker: str) -> str:
#     """Fetch a stock price. Use the ticker, like AAPL, not the company name."""

When validation fails, the error goes back to the model, which can retry with the right value. The test above shows this happening. For other exceptions inside your tools, the tools docs show a wrap_tool_call middleware that turns errors into messages the model can read.

3. Context overflow

Web pages and API responses can be huge, and a few of them fill the context window.

Fix: don't pass raw HTML to the agent. Strip the page to text, cut it into chunks, or summarize it inside the tool, and return only what the agent needs.

From chatting to assigning tasks

Agents move you from chatting with a model to giving it tasks. Your work shifts from writing prompts to designing systems: tools, state, limits and tests.

Start small. Build an agent with two tools. Watch it fail, read the trace and fix the loop. When it works, the next part shows you how to ship it: best practices for deploying LangChain apps to production.

Frequently asked questions

What is the difference between an AI agent and a chain?

A chain runs fixed steps in a fixed order: step A always leads to step B. An agent lets the model choose the next step, such as which tool to call, based on what it has seen so far. Use a chain when the steps are known, and an agent when they depend on tool results.

What is the ReAct pattern?

ReAct stands for Reason + Act. It comes from a 2022 paper by Yao et al., in which the model alternates between reasoning about the task and taking actions such as tool calls. Each action's result feeds the next round of reasoning.

How do I stop an AI agent from looping forever?

Set hard limits in code. In LangChain, add ModelCallLimitMiddleware or ToolCallLimitMiddleware as the main cap, and pass a recursion_limit in the run config as a backstop. recursion_limit counts graph steps, not model calls, so set it high enough that the call limit fires first. Also tell the model in the system prompt not to repeat a failed call, but don't rely on the prompt alone.

When should I use several agents instead of one?

Split the work when one agent's context fills up with tool results and instructions, or when subtasks need very different tools. A main agent can hand subtasks to specialist agents. Each extra agent adds cost and moving parts, so start with one.

Which model should I use for an AI agent?

Use a model with reliable tool calling, and test it on your own tasks. Model ids change often, so check the provider's models page, such as Anthropic's or OpenAI's, and read the id from an environment variable.

Sources

Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.

  1. ReAct: Synergizing Reasoning and Acting in Language Models (Yao et al.)
  2. LangChain docs: Agents
  3. LangChain docs: Tools
  4. LangChain docs: Prebuilt middleware (call limits)
  5. LangChain docs: Multi-agent
  6. LangGraph docs: Graph API (recursion limit)
  7. LangChain docs: Unit testing (fake chat models)
  8. Claude docs: Models overview
  9. OpenAI API: Models
  10. langchain on PyPI
All 14 parts in this series
Written by

Avnish Yadav

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.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.