OpenClaw + Claude API: Complete Setup Guide
Claude is one of the most capable AI models for code understanding, document analysis, and long-context reasoning. This guide walks you through configuring OpenClaw to use the Anthropic API from first key to production automation.
Why Use Claude with OpenClaw?
OpenClaw supports multiple LLM backends — OpenAI, Ollama, and Anthropic Claude. Claude is the recommended model for tasks that involve:
- Long documents and code review — Claude 3.5 Sonnet handles 200k token contexts natively, so you can pass entire codebases, log files, or PDF transcripts in a single request
- High-accuracy reasoning — Claude produces fewer hallucinations than most models on structured tasks: classification, extraction, and multi-step analysis
- Writing quality — For reports, release notes, PR descriptions, and documentation, Claude produces publication-ready prose with minimal prompting
- Safety-sensitive workflows — Claude's Constitutional AI training makes it less likely to generate harmful outputs in automated pipelines running without human review
Step 1: Get Your Anthropic API Key
- Go to console.anthropic.com and sign in or create an account
- Navigate to Settings → API Keys
- Click Create Key, give it a name (e.g.
openclaw-dev), copy the key - Optionally set a monthly spend limit under Billing → Usage Limits
Set the key in your environment:
# Add to ~/.bashrc, ~/.zshrc, or use a .env file
export ANTHROPIC_API_KEY="sk-ant-api03-..."
# Verify it is set
echo $ANTHROPIC_API_KEYStep 2: Configure OpenClaw to Use Claude
OpenClaw reads its LLM configuration from ~/.openclaw/config.yaml (or the path set in OPENCLAW_CONFIG). There are three ways to point it at Claude.
Option A: config.yaml (recommended)
# ~/.openclaw/config.yaml
llm:
provider: anthropic
model: claude-3-5-sonnet-20241022
api_key_env: ANTHROPIC_API_KEY # name of the env var, not the key itself
max_tokens: 4096
temperature: 0.1 # low temperature = more consistent, less creative
stream: true # stream token-by-token to terminal
agent:
max_iterations: 10
allow_shell: false # set to true to grant shell execution permissions
Option B: Environment Variables Only
export OPENCLAW_LLM_PROVIDER=anthropic
export OPENCLAW_LLM_MODEL=claude-3-5-sonnet-20241022
export ANTHROPIC_API_KEY=sk-ant-api03-...
# Test
openclaw run "Summarise this in one sentence: OpenClaw is an autonomous AI agent framework."Option C: Per-Command Flag
openclaw run "Review this pull request diff" \
--provider anthropic \
--model claude-3-5-haiku-20241022 \
--file diff.txtStep 3: Choose the Right Claude Model
Anthropic offers several Claude variants. Pick based on your trade-off between cost, speed, and output quality.
| Model | Context | Speed | Cost (input/1M) | Best for |
|---|---|---|---|---|
| claude-3-5-haiku-20241022 | 200k | Very fast | $0.80 | Quick tasks, classification, summaries, chat |
| claude-3-5-sonnet-20241022 | 200k | Fast | $3.00 | Code review, analysis, long docs, most tasks |
| claude-opus-4-5 | 200k | Slower | $15.00 | Complex reasoning, research, multi-step plans |
claude-3-5-sonnet-20241022. It delivers near-Opus quality at one-fifth the price for most automation tasks. Switch to Haiku for high-volume, low-complexity operations to cut costs 4×.
Step 4: Real Automation Examples
4.1 — Code Review on Every Commit
#!/bin/bash
# .git/hooks/commit-msg
DIFF=$(git diff --cached)
if [ -z "$DIFF" ]; then exit 0; fi
REVIEW=$(echo "$DIFF" | openclaw run \
"Review this git diff for bugs, security issues, and style problems.
Format output as markdown with three sections: Bugs, Security, Style.
Be concise — max 300 words." \
--stdin --provider anthropic --model claude-3-5-sonnet-20241022)
echo ""
echo "=== AI Code Review ==="
echo "$REVIEW"
echo "====================="4.2 — Summarise Any Document
# Summarise a long PDF (after extracting text with pdftotext)
pdftotext report.pdf - | openclaw run \
"Summarise this document in 5 bullet points, then list any action items." \
--stdin
# Summarise a URL (requires allow-shell)
openclaw run --allow-shell \
"Fetch https://example.com/changelog.md and summarise what changed in v2.0"4.3 — Intelligent Pull Request Description
#!/bin/bash
# Generate PR description from branch diff
BASE_BRANCH="${1:-main}"
DIFF=$(git diff "$BASE_BRANCH"...HEAD)
COMMITS=$(git log "$BASE_BRANCH"...HEAD --oneline)
PR_BODY=$(printf "Commits:\n%s\n\nDiff:\n%s" "$COMMITS" "$DIFF" | \
openclaw run \
"Write a GitHub Pull Request description for these changes.
Include: Summary, Changes Made (bullet list), Testing, Screenshots if applicable.
Use GitHub Flavoured Markdown." \
--stdin)
echo "$PR_BODY" | pbcopy # macOS — copies to clipboard
echo "PR description copied to clipboard!"4.4 — Multi-Step Research Pipeline
# ~/.openclaw/tasks/competitor-research.yaml
name: Competitor Research Brief
provider: anthropic
model: claude-opus-4-5
allow_shell: true
steps:
- prompt: |
You are a market research analyst.
Research the company: {{ company_name }}
1. Summarise their main product and positioning
2. Identify their key differentiators vs OpenClaw
3. Note any recent news (funding, product launches)
Write a 500-word brief in markdown format.
output: research_brief.mdopenclaw task run competitor-research.yaml --var company_name="AutoGPT"Step 5: Cost Control and Rate Limits
The Anthropic API bills per token. With automation scripts running frequently, costs can add up fast. Here are the key controls:
Set Max Tokens to Limit Output Length
llm:
provider: anthropic
model: claude-3-5-sonnet-20241022
max_tokens: 1024 # caps output — default 4096
max_input_tokens: 8000 # truncate large inputs before sendingUse Haiku for Preprocessing, Sonnet for Final Output
# Stage 1: Fast Haiku extracts structure from raw input
STRUCTURED=$(cat raw-data.txt | openclaw run \
"Extract key facts as JSON. Keep it short." \
--stdin --model claude-3-5-haiku-20241022)
# Stage 2: Sonnet writes the final report from structured data
echo "$STRUCTURED" | openclaw run \
"Write a 300-word executive summary of these facts." \
--stdin --model claude-3-5-sonnet-20241022Set a Spend Cap in the Anthropic Console
Go to Billing → Usage Limits and set a hard monthly limit. When the limit is reached, API calls return a 429 billing_limit_exceeded error — safer than an open-ended bill.
Track Usage with OpenClaw's Cost Summary
openclaw run "..." --summary # prints tokens in/out + estimated cost after each run
openclaw log show --cost # show cost breakdown from session logsStreaming Output
Enable streaming so tokens appear in your terminal as they are generated, rather than waiting for the full response. This is configured in config.yaml or via the flag:
openclaw run "Write a blog post about AI automation" --stream
# Disable streaming (wait for full response — useful for piping output to files)
openclaw run "Generate a report" --no-stream > report.mdTroubleshooting Claude-Specific Errors
| Error | Cause | Fix |
|---|---|---|
401 authentication_error | Invalid or missing API key | Check $ANTHROPIC_API_KEY is set and starts with sk-ant- |
429 rate_limit_error | Too many tokens per minute | Add request_delay: 1.0 to config.yaml, or use a rate-limited wrapper |
529 overloaded_error | Anthropic API overloaded (rare) | Retry after 30s. OpenClaw retries automatically up to 3 times |
context_length_exceeded | Input exceeds 200k tokens | Set max_input_tokens in config to truncate automatically |
billing_limit_exceeded | Monthly spend cap reached | Raise limit in Anthropic console or wait for billing cycle reset |
| Response truncated mid-sentence | max_tokens too low | Increase max_tokens in config or CLI flag |
| Slow first token (no streaming) | stream: false | Set stream: true in config.yaml |
Enable Debug Logging
OPENCLAW_LOG_LEVEL=debug openclaw run "test prompt"
# Shows: model, tokens, request payload, response timeNext Steps
Now that Claude is configured, here are good places to go deeper:
- Claude Integration Reference — all supported parameters, function calling, and vision mode
- API Keys Configuration — secure storage, rotation, and multi-key setups
- Responsible AI Automation Best Practices — rate limiting, cost governance, human-in-the-loop patterns
- Automation Tutorials — 10 real-world Claude automation scripts to copy and adapt
Discussion