ClawMart AI
← Back to Blog
November 23, 20269 min readClaw Mart Team

Prevent OpenClaw Agents From Looping on Errors

Prevent OpenClaw Agents From Looping on Errors

Prevent OpenClaw Agents From Looping on Errors

If you've spent any time building agents in OpenClaw, you've hit this wall. You know the one. Your agent encounters an error β€” maybe a tool returns unexpected data, maybe an API times out β€” and instead of recovering gracefully, it just… loops. It retries the same failing action over and over. Your token count climbs. Your API bill climbs. And you're sitting there watching your agent slam its head into the same wall forty times in a row like it's being paid by the attempt.

This is probably the single most common frustration I hear from people building with any agent framework, and it's one of the main reasons developers abandon their projects before they ever ship anything useful. The good news: OpenClaw gives you real tools to prevent this. The bad news: most people don't set them up correctly β€” or at all β€” until after they've already burned through a weekend and a chunk of their OpenAI budget.

Let's fix that. Here's everything you need to know about stopping error loops dead, explained the way I wish someone had explained it to me six months ago.

Why Agents Loop in the First Place

Before we fix the problem, it helps to understand why it happens. And it's actually not that complicated once you see it.

An OpenClaw agent operates on a basic loop: observe the current state, decide what to do, execute an action, observe the result, repeat. When a tool call fails, the agent sees the error in its context and tries to reason about what to do next. The problem is that LLMs are not great at reasoning about errors they've never seen before. So the model often does the most "reasonable" thing it can think of: try again.

And when "try again" produces the same error, the model sees the error again, reasons that it should try again, and you've got yourself an infinite loop.

This gets worse in a few specific situations:

  • Ambiguous error messages. If the tool returns something vague like None or an empty string instead of a clear error, the agent doesn't even know something went wrong. It just sees unexpected data and tries the same call with slightly different parameters.
  • No retry limits configured. OpenClaw won't stop your agent unless you tell it when to stop.
  • No timeout on tool execution. If a tool hangs for 60 seconds and then fails, your agent will happily wait 60 seconds, get an error, and wait another 60 seconds. Forever.
  • Context window overflow. After enough retries, the error messages fill up the context window, and the agent starts losing track of what it was even trying to do. Now it's not just looping β€” it's looping confused.

The core issue is that most developers treat error handling as something they'll add later. With agents, "later" means "after a $200 API bill."

The Fix: Execution Limits (Set These First, Always)

The single most important thing you can do when building any OpenClaw agent is configure execution limits before you do anything else. This is your circuit breaker. This is what prevents a Saturday afternoon experiment from becoming a Monday morning credit card dispute.

from openclaw import Agent, ExecutionLimits

agent = Agent(
    name="research_agent",
    limits=ExecutionLimits(
        max_steps=20,              # Hard stop after 20 steps total
        max_tool_calls=10,         # No more than 10 tool executions
        max_tokens=50000,          # Total token budget for the run
        timeout_seconds=300,       # 5 minutes max, then it's done
        retry_limit=3              # Max 3 retries per individual tool
    )
)

Let me break down what each of these actually does and why they matter:

max_steps is your overall execution cap. Every time the agent goes through its observe-decide-act cycle, that's a step. Twenty is a generous limit for most tasks. If your agent needs more than 20 steps for a single task, the task is probably too complex and should be broken into subtasks.

max_tool_calls is specifically about tool executions. An agent might take several "reasoning" steps between tool calls, so this is a tighter limit on the expensive operations. This is what directly prevents the "call the same API 1,000 times" nightmare.

max_tokens is your budget limit. Set this based on what you're willing to spend on a single execution. For GPT-4-class models, 50,000 tokens is roughly $1.50-2.00. Adjust to your comfort level, but set it to something.

timeout_seconds is your wall-clock limit. This catches situations where individual tool calls are hanging, or where the overall task is just taking too long.

retry_limit is the most directly relevant to our looping problem. This tells OpenClaw: if a specific tool fails three times, stop trying and move on. The agent will receive a clear message that the tool has hit its retry limit, which gives the LLM enough context to either try a different approach or gracefully report the failure.

Here's what you get back after execution:

result = await agent.execute("Research competitor pricing")
print(result.metrics)
# {
#   "tokens_used": 12450,
#   "estimated_cost": "$0.37",
#   "steps_taken": 8,
#   "tools_called": 4,
#   "retries_used": 1,
#   "execution_time": "43s",
#   "limit_hit": None
# }

That limit_hit field is key. If your agent was stopped by a limit rather than completing naturally, it'll tell you which limit was reached. This alone is worth its weight in gold for debugging.

Better Tool Definitions (Prevent Errors Before They Happen)

Half the error loops I see could be prevented by writing better tool definitions. The agent calls the wrong tool, or passes garbage parameters, because the tool descriptions are vague or the input schema is missing.

OpenClaw lets you define tools with strict schemas that get validated before the tool executes:

from openclaw import tool

@tool(
    name="search_customers",
    description="Search the customer database by email address or customer ID. Returns a list of matching customer records. Use email for fuzzy matches, use ID for exact lookups.",
    schema={
        "query": {
            "type": "string",
            "required": True,
            "description": "Email address or numeric customer ID"
        },
        "search_type": {
            "type": "string",
            "enum": ["email", "id"],
            "required": True,
            "description": "Whether to search by email or customer ID"
        },
        "limit": {
            "type": "integer",
            "default": 10,
            "minimum": 1,
            "maximum": 100,
            "description": "Maximum number of results to return"
        }
    }
)
async def search_customers(query: str, search_type: str, limit: int = 10):
    if search_type == "id":
        results = await db.get_customer(int(query))
        return [results] if results else []
    else:
        return await db.search_by_email(query, limit=limit)

Notice a few things here:

  1. The description is specific. Not just "search customers" but exactly what inputs it expects and when to use each search type.
  2. The schema has enums. The agent can only pass "email" or "id" for search_type. It literally cannot pass something invalid.
  3. There are min/max constraints. The agent can't ask for 10,000 results.
  4. Every field has a description. The LLM uses these to decide what to pass.

When the agent tries to call this tool with invalid parameters, OpenClaw catches it at the schema validation step and returns a clear, structured error to the agent β€” not a Python stack trace, but a message like "Parameter 'search_type' must be one of: email, id. Received: 'name'." The agent can then self-correct without burning a full tool execution cycle.

This is preventive medicine. Much cheaper than treating symptoms.

Structured Error Handling Within Tools

Even with great schemas, tools will sometimes fail. APIs go down. Databases time out. Files don't exist. The difference between an agent that recovers and an agent that loops is how you communicate those failures.

Here's the pattern I use for every tool:

from openclaw import tool, ToolError, ToolResult

@tool(name="fetch_pricing_data")
async def fetch_pricing(product_id: str, source: str = "primary"):
    try:
        if source == "primary":
            data = await primary_api.get_price(product_id)
        else:
            data = await backup_api.get_price(product_id)
        
        if data is None:
            return ToolResult(
                success=False,
                error=f"No pricing data found for product {product_id}",
                suggestion="Try a different product ID or check if the product exists using search_products tool first"
            )
        
        return ToolResult(
            success=True,
            data=data
        )
    
    except ConnectionError as e:
        return ToolResult(
            success=False,
            error=f"Could not connect to {source} pricing API: {str(e)}",
            suggestion="Try again with source='backup' to use the backup API"
        )
    
    except TimeoutError:
        return ToolResult(
            success=False,
            error=f"Pricing API timed out after 30 seconds",
            suggestion="The API may be overloaded. Consider retrying in a moment or using cached data if available"
        )

The key insight here is the suggestion field. When you tell the agent what to do instead, it almost always follows the suggestion rather than blindly retrying the same thing. This turns a potential infinite loop into a single retry with a different strategy.

This is the difference between the agent seeing "Error: timeout" (response: try again) and "Error: timeout. Try the backup API instead" (response: call the backup API). Night and day.

Debug Mode and the Trace Viewer

When something does go wrong β€” and it will, because this is software β€” OpenClaw's debug mode and trace viewer are what save you from spending your entire afternoon staring at logs.

result = await agent.execute(
    "Analyze Q3 sales data and generate report",
    debug_mode=True
)

With debug_mode=True, you get a complete trace of every single thing the agent did:

Step 1: [REASONING] "I need to access the sales database to get Q3 data"
Step 2: [TOOL_CALL] query_database(table='sales', quarter='Q3')
        Input: {"table": "sales", "quarter": "Q3"}
        Duration: 234ms
        Output: {"rows": 1250, "columns": ["date", "amount", "region"...]}
Step 3: [REASONING] "Got 1250 rows. Now I need to aggregate by region"
Step 4: [TOOL_CALL] analyze_data(operation='group_by', field='region')
        Input: {"operation": "group_by", "field": "region"}
        Duration: 89ms
        Output: {"North": 45000, "South": 38000, "East": 52000}
Step 5: [REASONING] "Now generating the report with these insights"
Step 6: [TOOL_CALL] generate_report(template='quarterly', data={...})
        Input: {"template": "quarterly", "data": {...}}
        Duration: 1203ms
        βœ— ERROR: TemplateNotFound('quarterly')
Step 7: [REASONING] "Report template not found. Let me try the default template"
Step 8: [TOOL_CALL] generate_report(template='default', data={...})
        Duration: 890ms
        Output: {"report_url": "/reports/q3_2024.pdf"}

You can see everything: what the agent was thinking, what it passed to each tool, how long each call took, and β€” crucially β€” how it responded to the error in Step 6. It didn't loop. It saw the error, adjusted its approach, and succeeded on the next try.

When an agent is looping, the trace makes it painfully obvious:

Step 5: [TOOL_CALL] fetch_data(url='https://api.example.com/data')
        βœ— ERROR: ConnectionTimeout
Step 6: [REASONING] "Request timed out. Let me try again."
Step 7: [TOOL_CALL] fetch_data(url='https://api.example.com/data')
        βœ— ERROR: ConnectionTimeout
Step 8: [REASONING] "Still timing out. Let me try once more."
Step 9: [TOOL_CALL] fetch_data(url='https://api.example.com/data')
        βœ— RETRY_LIMIT_HIT: Tool 'fetch_data' has reached maximum retries (3)
Step 10: [REASONING] "Cannot reach the API. Reporting failure to user."

That's the retry limit doing its job. Without it, Steps 7-8 would repeat until your budget limit or heat death of the universe, whichever comes first.

State Snapshots: Your Safety Net

For longer-running agents β€” anything processing batches, doing multi-step research, or coordinating between multiple tools β€” state snapshots are essential:

from openclaw import Agent, StateManager

agent = Agent(
    name="batch_processor",
    state_manager=StateManager(
        persist=True,           # State survives crashes
        snapshot_every=5        # Checkpoint every 5 steps
    )
)

If your agent crashes at Step 17, you don't start over from scratch. You restore from the Step 15 snapshot and continue:

# After a crash, resume from last good state
agent.state.restore_snapshot(step=15)
result = await agent.resume()

This is especially valuable when debugging loops because you can rewind to before the loop started:

# Agent looped from steps 12-20 before hitting limit
# Rewind to step 11, fix the tool, try again
agent.state.restore_snapshot(step=11)

No re-running the entire pipeline. No re-fetching data you already have. Just pick up where things went sideways.

Testing Against Known Failures

Once you've fixed a loop, you want to make sure it stays fixed. OpenClaw's test runner lets you replay exact execution traces:

from openclaw import TestRunner

test_runner = TestRunner(agent)

@test_runner.test_case
async def test_api_timeout_recovery():
    """Agent should fall back to cache when API times out"""
    result = await agent.execute(
        "Get latest pricing data",
        mock_tools={
            "fetch_pricing": TimeoutError("Connection timed out")
        }
    )
    # Agent should have used the cache instead of looping
    assert "fetch_cached_data" in [t.name for t in result.tool_calls]
    assert result.metrics["retries_used"] <= 3

You're testing that the agent behaves correctly when things go wrong. This is the kind of testing that most people skip entirely, and it's the kind that matters most.

The Practical Setup That Covers 90% of Cases

Here's the template I use for every agent I build. It's not fancy. It just works:

from openclaw import Agent, ExecutionLimits, StateManager

agent = Agent(
    name="my_agent",
    limits=ExecutionLimits(
        max_steps=25,
        max_tool_calls=15,
        max_tokens=50000,
        timeout_seconds=300,
        retry_limit=3
    ),
    state_manager=StateManager(
        persist=True,
        snapshot_every=5
    )
)

Every tool returns structured ToolResult objects with suggestions on failure. Every execution runs with debug_mode=True during development. And I write at least one test for each known failure mode.

This catches maybe 90% of looping issues before they ever reach production. The remaining 10% get caught by the execution limits and show up clearly in the trace logs.

Skip the Setup With a Pre-Built Kit

If you don't want to configure all of this from scratch β€” the execution limits, the error handling patterns, the state management, the test templates β€” Felix's OpenClaw Starter Pack on Claw Mart includes pre-configured skills that have all of this baked in. It's $29 and comes with error handling patterns, retry logic, and circuit breaker configurations that are already tuned for common use cases. I've recommended it to a few people who were struggling with exactly the looping issues we've been discussing, and they were up and running in an afternoon instead of spending a week fighting configuration. If you're just getting started with OpenClaw or you've been bitten by runaway agents before, it's genuinely worth looking at.

What to Do Next

Here's your action plan:

  1. Right now: Add ExecutionLimits to every agent you have running. Even if the limits are generous, having any limit is infinitely better than having none. This is a five-minute change that could save you hundreds of dollars.

  2. This week: Refactor your tools to return structured errors with suggestions. Start with the tools that fail most often. Check your trace logs to find them.

  3. This month: Build a small test suite for your most critical agent flows. Focus on failure cases, not happy paths. Mock tools to simulate timeouts, empty responses, and invalid data.

  4. Ongoing: Run with debug_mode=True during development. Read the traces. You'll learn more about how your agent actually behaves in one trace than in ten hours of guessing.

The agents that work in production aren't the ones that never encounter errors. They're the ones that handle errors intelligently and know when to stop trying. OpenClaw gives you the tools to build exactly that kind of agent β€” you just have to actually use them.

Stop letting your agents run in circles. Set the limits, structure the errors, read the traces, and ship something that actually works.

Recommended for this post

Your MCP builder that generates protocol-compliant tool servers with testing and deployment -- extend any AI agent.

All platformsProductivity
Brian Gorzelic β€” SpookyJuice.AIBrian Gorzelic β€” SpookyJuice.AI
$19Buy

Your orchestrator that coordinates agent swarms with task decomposition and consensus protocols -- agents working together.

All platformsEngineering2 sold
Brian Gorzelic β€” SpookyJuice.AIBrian Gorzelic β€” SpookyJuice.AI
$19Buy
Felix

Felix

Entrepreneur

Your AI CEO β€” ships products, manages code, handles comms, remembers everything, runs your business

All platformsExecutive1,148 sold
Felix CraftFelix Craft
$99Buy

Claw Mart Daily

Get one AI agent tip every morning

Free daily tips to make your OpenClaw agent smarter. No spam, unsubscribe anytime.

More From the Blog