Claw Mart
← Back to Blog
August 12, 20267 min readClaw Mart Team

How to Create and Manage Sub-Agents in OpenClaw

How to Create and Manage Sub-Agents in OpenClaw

How to Create and Manage Sub-Agents in OpenClaw

Let's skip the theory and get straight to it: if you're building anything meaningful with OpenClaw, you're going to need sub-agents. Not because they're cool (they are), but because a single monolithic agent trying to do everything is like hiring one person to run your entire company. It works until it doesn't, and when it stops working, it fails catastrophically.

Sub-agents are how you take a complex workflow and break it into manageable, debuggable, cost-controllable pieces. One agent researches. Another analyzes. A third writes the output. They share context, respect boundaries, and you can actually see what's happening at every step.

The problem is that most people either don't know sub-agents exist in OpenClaw, or they try to use them and immediately run into a wall of confusion. Context doesn't get shared properly. Agents spawn out of control. One failure takes down the whole pipeline. Costs spiral because there's no budget control.

I've been through all of it. Here's how to actually set up and manage sub-agents in OpenClaw without losing your mind or your wallet.

Why Sub-Agents Instead of One Big Agent?

Before we get into the how, let's make sure the why is clear.

A single agent handling research, analysis, data extraction, summarization, and output formatting is going to hit context window limits fast. It's going to hallucinate because it's juggling too many instructions. And when it fails, you have zero idea where things went wrong.

Sub-agents solve this by letting you decompose work. Each agent has a clear, narrow responsibility. You can test them independently, monitor their costs individually, and swap them out without rebuilding your entire system.

Think of it like microservices for AI workflows. Same philosophy: single responsibility, independent deployment, clear interfaces.

Setting Up Your First Sub-Agent

The basic structure in OpenClaw is straightforward. You have a parent Claw instance that orchestrates, and sub-agents that handle specific tasks.

from openclaw import Claw

# Initialize the parent orchestrator
claw = Claw(
    verbose=True,
    max_sub_agents=5,
    max_depth=2
)

# Define sub-agents with decorators
@claw.sub_agent
async def research_agent(query):
    """Handles all research and information gathering."""
    results = await claw.search(query)
    return results

@claw.sub_agent
async def analysis_agent(data):
    """Takes raw research and produces structured analysis."""
    analysis = await claw.analyze(data)
    return analysis

@claw.sub_agent
async def writing_agent(analysis):
    """Converts analysis into final output."""
    output = await claw.generate(analysis)
    return output

# Execute the workflow
result = await claw.execute(task)

That's the skeleton. But the skeleton alone is going to get you into trouble. Let's talk about the things that actually matter.

Sharing Context Between Sub-Agents (Without Duplicating Work)

This is the number one pain point I see. You have a research agent that extracts a list of company names from documents. Then your summarization agent needs those company names but can't access them, so it re-extracts them. You just doubled your API costs for no reason.

OpenClaw has a SharedContext object that solves this cleanly:

from openclaw import Claw, SharedContext

context = SharedContext()
claw = Claw(shared_context=context)

@claw.sub_agent
async def extract_entities(doc):
    entities = await llm.extract(doc)
    # Store in shared context — other agents can access this immediately
    context.set("entities", entities)
    return entities

@claw.sub_agent
async def summarize(doc):
    # Pull from shared context instead of re-extracting
    entities = context.get("entities")
    return await llm.summarize(doc, known_entities=entities)

result = await claw.execute_parallel([
    extract_entities(document),
    summarize(document)
])

The key detail: SharedContext handles versioning and race conditions for you. If summarize runs before extract_entities finishes, it won't crash — it'll either wait for the dependency or work with what's available, depending on how you configure it.

This alone saved me from a system that was making 2x the API calls it needed to. Every sub-agent was independently fetching the same data because there was no shared state. Once I wired up SharedContext, costs dropped by nearly half.

Controlling Agent Spawning (Before It Controls Your Bank Account)

Here's a horror story that's way too common: someone sets up an agent with the instruction "research this topic thoroughly," and the agent interprets "thoroughly" as "spawn a new sub-agent for every single search result." Suddenly you've got 30+ agents running in parallel, each making GPT-4 calls, and your bill looks like a car payment.

OpenClaw gives you hard limits. Use them. Always.

from openclaw import Claw, BudgetManager

budget = BudgetManager(
    total_budget=5.00,         # Hard stop at $5
    per_agent_limit=0.50,      # No single agent can spend more than $0.50
    warning_threshold=0.8,     # Alert when 80% of budget is consumed
    callback=lambda spent, limit: print(f"⚠️ Budget warning: ${spent:.2f}/${limit:.2f}")
)

claw = Claw(
    max_sub_agents=5,          # Never more than 5 concurrent sub-agents
    max_depth=2,               # Sub-agents can't spawn sub-sub-sub-agents
    budget_manager=budget
)

result = await claw.execute(task)

# Always check what you spent
print(f"Total cost: ${result.total_cost:.2f}")
for agent_cost in result.cost_breakdown:
    print(f"  {agent_cost.agent_id}: ${agent_cost.cost:.2f}")

The max_depth=2 parameter is critical. Without it, a sub-agent can spawn its own sub-agents, which can spawn their own, and you're in recursive agent hell. Depth limiting puts a floor under the madness.

And please, use the BudgetManager during development too. I know it's tempting to think "I'm just testing, it'll be fine." It won't be fine. One infinite loop at GPT-4 pricing will remind you why budget limits exist.

Speaking of development, OpenClaw has a dedicated mode for this:

claw = Claw(
    mode="development",    # Automatically uses cheaper models
    dry_run=True,          # Simulates without real API calls
    mock_responses=True    # Uses cached responses
)

result = await claw.execute(task)
print(f"Would have cost: ${result.estimated_cost:.2f}")

Use dry_run=True until you're confident your agent graph does what you expect. Then switch to development mode with cheaper models. Only go to production configuration when everything is solid.

Handling Failures Without Losing Everything

The default behavior in most agent frameworks is: one sub-agent fails, everything dies. This is unacceptable for any real workload.

Say you have 10 sub-agents processing 10 documents. Agent #7 hits a rate limit and throws an error. Without proper failure handling, you lose the results from all 10 agents, including the 9 that completed successfully.

OpenClaw lets you configure failure strategies per agent:

from openclaw import Claw, FailureStrategy

claw = Claw(
    failure_strategy=FailureStrategy.CONTINUE,
    max_retries=3,
    retry_delay=1.0
)

@claw.sub_agent(
    fallback=lambda: "Default analysis — primary agent failed",
    critical=False    # Non-critical: failure won't stop the pipeline
)
async def analysis_agent(data):
    return await analyze(data)

@claw.sub_agent(critical=True)    # Critical: failure stops everything
async def validation_agent(data):
    return await validate(data)

result = await claw.execute(task)

# Inspect what happened
for agent_result in result.sub_results:
    if agent_result.failed:
        print(f"❌ {agent_result.id}: {agent_result.error}")
        print(f"   Used fallback: {agent_result.used_fallback}")
    else:
        print(f"✅ {agent_result.id}: Success")

# Get whatever succeeded
successful_data = result.get_successful_results()

The critical flag is the key design decision. Mark agents as critical=True only when their failure genuinely means the entire workflow is invalid. Everything else should be non-critical with a sensible fallback. This way, you always get the maximum amount of useful output, even when things go wrong.

Orchestrating Dependencies with Execution Graphs

Real workflows aren't "run everything in parallel and hope for the best." They have dependencies. The analysis agent needs the research agent's output. The report agent needs the analysis. You need a way to express this.

from openclaw import Claw, ExecutionGraph

claw = Claw()
graph = ExecutionGraph()

# These run in parallel — no dependencies between them
graph.add_node("research", research_agent)
graph.add_node("data_collection", data_agent)

# This waits for both research AND data_collection to finish
graph.add_node(
    "analysis",
    analysis_agent,
    depends_on=["research", "data_collection"]
)

# This waits for analysis
graph.add_node(
    "report",
    report_agent,
    depends_on=["analysis"]
)

# OpenClaw resolves the graph and runs things in optimal order
result = await claw.execute_graph(graph)

This is so much cleaner than manually chaining async calls and trying to manage your own concurrency. OpenClaw resolves the dependency graph, runs independent nodes in parallel, and feeds outputs into dependent nodes automatically.

If you also need resource-level coordination (like preventing two agents from writing to the same file simultaneously), OpenClaw has built-in primitives:

async with claw.coordinate("database_write") as lock:
    await write_to_database(data)

Simple. No external locking libraries needed.

Checkpointing Long-Running Workflows

If your agent workflow takes more than a few minutes, you need checkpointing. Period. Not optional. Not nice-to-have. Essential.

from openclaw import Claw, StateManager

claw = Claw(
    state_manager=StateManager(
        checkpoint_interval=60,    # Auto-save every 60 seconds
        storage="./checkpoints"
    )
)

result = await claw.execute(long_running_task)

# If it crashes, resume from the last checkpoint
claw = Claw.restore_from_checkpoint("./checkpoints/latest")
result = await claw.resume()

I learned this the hard way. A 90-minute workflow crashed at minute 87 because of a rate limit. No checkpointing. Had to start completely over. That was the last time I ran anything longer than 5 minutes without StateManager configured.

You can also add manual checkpoints at critical junctures inside your sub-agents:

@claw.sub_agent
async def expensive_agent(data):
    intermediate = await expensive_step_one(data)
    await claw.checkpoint()    # Save progress here
    final = await expensive_step_two(intermediate)
    return final

If the agent crashes during expensive_step_two, the resume will pick up after the checkpoint, and expensive_step_one won't need to re-run.

Monitoring and Debugging in Real Time

You need to see what's happening while it's happening. Not after.

claw = Claw(
    verbose=True,
    monitoring_callback=lambda event: print(f"[{event.agent_id}] {event.action}")
)

result = await claw.execute(task)

# Full execution tree after completion
print(claw.get_execution_tree())
# Output:
# └── Main Agent
#     ├── Research Agent (completed, 3 API calls, $0.02)
#     ├── Analysis Agent (completed, 5 API calls, $0.04)
#     └── Writing Agent (completed, 2 API calls, $0.01)

The execution tree is invaluable for debugging. You can immediately see which agent took the longest, which one made the most API calls, and where costs are concentrated. This is the kind of visibility that prevents the "my agent burned $500 and I don't know why" disaster.

Testing Sub-Agent Systems

Testing AI agents is notoriously hard because of LLM non-determinism. OpenClaw's recording/replay mode makes this tractable:

from openclaw import Claw

# Record a real execution
claw = Claw(recording_mode=True)
result = await claw.execute(task)
claw.save_recording("test_fixture.json")

# Replay deterministically in tests
def test_agent_workflow():
    claw = Claw.from_recording("test_fixture.json")
    result = await claw.execute(task)
    
    assert result.sub_agents_spawned == 3
    assert result.cost < 0.50
    assert "expected output" in result.final_answer

Record once with real LLM calls. Then replay infinitely with zero cost and deterministic behavior. This is how you actually build CI/CD pipelines for agent-based systems.

The Fastest Way to Get Up and Running

Everything I've described above works. But there's a meaningful difference between understanding the concepts and having a production-ready setup with properly configured sub-agents, sensible defaults, budget controls, and tested skill templates.

If you don't want to wire all of this up from scratch, Felix's OpenClaw Starter Pack on Claw Mart is genuinely worth the $29. It includes pre-configured sub-agent skills with shared context patterns, budget management, failure strategies, and execution graph templates already built out. The kind of stuff that takes a weekend to set up properly if you're doing it yourself. I used it as my starting point and customized from there — saved me a solid chunk of time and a few costly mistakes I would've made with default configurations.

It's particularly useful if you're new to the sub-agent pattern and want to see how someone experienced has structured the agent hierarchy, the context sharing, and the error handling. Reading well-structured starter code teaches you faster than any documentation.

What to Build Next

Once you have sub-agents working, the natural next steps are:

  1. Start simple. Two or three sub-agents with clear responsibilities. Don't build a 15-agent system on day one.
  2. Add monitoring first. Before you optimize anything, make sure you can see what's happening. Use verbose=True and the execution tree.
  3. Set budget limits immediately. Even in development. Especially in development.
  4. Test with recording/replay. Build your test fixtures early so you're not paying for LLM calls every test run.
  5. Add checkpointing for anything over 5 minutes. You will thank yourself later.

Sub-agents are where OpenClaw goes from "cool toy" to "actual production tool." The orchestration, the visibility, the cost controls — this is what separates a demo from a system you can rely on. Get the fundamentals right, and you can build surprisingly sophisticated AI workflows that don't break, don't bankrupt you, and actually do what you need them to do.

Recommended for this post

10 battle-tested automation patterns for OpenClaw agents. Cron scheduling, sub-agent spawning, memory sync, delivery, escalation. Copy-paste ready.

OpenClawOps
CI
Clawgear IO
$29Buy

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