Tool Chaining
Tool chaining is the practice of connecting tool outputs to subsequent tool inputs, allowing agents to execute multi-step workflows where each step enriches the context for the next. Mastering tool chaining patterns is key to building sophisticated, reliable automation with OpenClaw.
What Is Tool Chaining?
When an agent executes a task, it doesn't use just one tool — it orchestrates a sequence of tool calls where the output of one call informs the input of the next. For example, a research task might: search the web → extract relevant URLs → read each page → cross-reference facts → compile a summary. This chain of tool calls is how agents accomplish complex multi-step work.
OpenClaw gives you two levels of control over chaining: implicit chaining (the LLM decides the tool call order based on context) and explicit chaining (you define the pipeline in YAML for predictable, tested workflows).
Implicit LLM-Directed Chaining
By default, OpenClaw's agent uses a ReAct (Reasoning + Acting) pattern — after each tool call, the LLM reasons about what to do next. The entire tool call history is visible in context, and the LLM directs the next action based on what it has learned.
openclaw run "Research the 3 most recent LLM papers from arxiv and write a technical summary" --tools web_search,read_url,write_file --verboseThought: I need to search arxiv for recent LLM papers.
Action: web_search("arxiv LLM papers 2024 site:arxiv.org")
Observation: [search results with 10 arxiv paper URLs]
Thought: I have URLs. I should read the abstract pages of the top 3 papers.
Action: read_url("https://arxiv.org/abs/2401.12345")
Observation: [abstract and metadata for paper 1]
Action: read_url("https://arxiv.org/abs/2401.23456")
Observation: [abstract and metadata for paper 2]
Action: read_url("https://arxiv.org/abs/2401.34567")
Observation: [abstract and metadata for paper 3]
Thought: I have all three papers' content. Now I'll write the summary.
Action: write_file("summary.md", "# Recent LLM Research Summary
...")Implicit chaining works well for exploratory tasks where the exact tool call sequence can't be predetermined. The downside is unpredictability — different runs may chain tools differently, consuming different amounts of tokens.
Explicit Pipeline Chaining
For production workflows, explicit chaining with the pipeline config gives you predictability, testability, and cost control:
pipeline:
- id: search
task: "Search arxiv for the 5 most recent papers about {topic}"
tools: [web_search]
output_key: search_results
max_tokens: 1000
- id: extract_urls
task: "Extract all arxiv paper URLs from: {search_results}"
tools: [] # pure LLM reasoning, no tools needed
output_key: paper_urls
- id: read_papers
task: "Read each of these arxiv papers and extract key contributions: {paper_urls}"
tools: [read_url]
output_key: paper_contents
parallel_urls: true # read all URLs concurrently
- id: summarize
task: "Write a comprehensive technical summary comparing: {paper_contents}"
tools: [write_file]
output_file: "{topic}-summary.md"Common Chaining Patterns
| Pattern | Description | Use case |
|---|---|---|
| Search → Read → Synthesize | Discover URLs, retrieve content, combine | Research tasks, competitive analysis |
| Read → Classify → Route | Get content, categorize it, take different actions by category | Support ticket routing, email triage |
| Generate → Validate → Refine | Draft content, check it against criteria, improve | Code generation, documentation drafting |
| Query → Aggregate → Report | Fetch from multiple sources, merge, format | Dashboard generation, monitoring reports |
| Detect → Retrieve → Act | Find anomaly, get context, take action | Incident response, alerting workflows |
Error Handling in Chains
When a tool call fails midway through a chain, you have three options: abort the chain (default), skip the failed step and continue, or branch to a fallback tool. Configure this per-stage:
pipeline:
- id: read_primary_source
tools: [read_url]
on_failure:
strategy: fallback
fallback_task: "Use cached knowledge about {topic} instead"
fallback_tools: [] # pure LLM, no tool callDebugging Tool Chains
When a multi-tool chain produces unexpected output, the challenge is identifying which tool call introduced the problem. OpenClaw's verbose mode logs every tool call with its inputs and outputs in sequence, making chain inspection straightforward:
openclaw run "..." --verbose --log-file chain-trace.json
# chain-trace.json contains full tool call sequence
openclaw debug chain-trace.json --tool read_url # inspect all read_url callsCommon chaining failures: context contamination (an early tool's output confuses later tools — solve by summarizing outputs before passing them downstream), format mismatch (tool A outputs Markdown, tool B expects JSON — solve with an explicit parsing step), and chain elongation (agent calls the same tool multiple times when once would suffice — solve by being more specific in the task description).
Cost Optimization in Long Chains
Long tool chains accumulate large contexts — every tool call adds to the running context window passed to the LLM for reasoning. As the chain grows, token costs grow too. Three techniques to keep chain costs manageable:
Summarize intermediate results: After information-gathering steps, explicitly summarize before passing to the next stage: "Summarize the key facts from the search results in under 200 words, then..." reduces context bloat for subsequent reasoning steps.
Use cheaper models for simple steps: Route information-extraction and formatting steps to a smaller, cheaper model (e.g., GPT-4o-mini) while reserving the larger model for synthesis and decision steps. Configure per-stage model selection in your pipeline YAML.
Set token budgets per stage: Use max_tokens: N per pipeline stage to prevent runaway tool chains from consuming unexpectedly large amounts of context when upstream data is larger than expected.
Testing Tool Chains
Tool chains should be tested as integration tests — run the full chain with mocked external dependencies and verify both the final output structure and the intermediate tool call sequence. OpenClaw's test fixture system records the exact tool call sequence during a reference run, then replays it (with mocked responses) in subsequent tests to verify the chain logic hasn't changed unexpectedly.
# Record a reference run
openclaw run "..." --record-fixtures tests/fixtures/research_task.json
# Run tests against recorded fixtures
openclaw test tests/test_research_chain.py --fixtures tests/fixtures/This approach catches regressions where a prompt change causes the agent to call tools in a different order, skip a tool call, or call the wrong tool for a step — problems that surface as quality regressions in production but are hard to detect without chain-level testing.