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
Prefer local/private processing? Use OpenClaw with Ollama instead. Claude requires sending data to Anthropic's API servers. Review Anthropic's Privacy Policy for data retention terms.

Step 1: Get Your Anthropic API Key

  1. Go to console.anthropic.com and sign in or create an account
  2. Navigate to Settings → API Keys
  3. Click Create Key, give it a name (e.g. openclaw-dev), copy the key
  4. Optionally set a monthly spend limit under Billing → Usage Limits
Keep your key secret. Never embed API keys in source code or commit them to Git. Use environment variables or a secrets manager. If a key is ever exposed, rotate it immediately from the Anthropic console.

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_KEY

Step 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.txt
Config priority: CLI flags override environment variables, which override config.yaml. Use config.yaml for your default model and flags for one-off overrides.

Step 3: Choose the Right Claude Model

Anthropic offers several Claude variants. Pick based on your trade-off between cost, speed, and output quality.

ModelContextSpeedCost (input/1M)Best for
claude-3-5-haiku-20241022200kVery fast$0.80Quick tasks, classification, summaries, chat
claude-3-5-sonnet-20241022200kFast$3.00Code review, analysis, long docs, most tasks
claude-opus-4-5200kSlower$15.00Complex reasoning, research, multi-step plans
Default recommendation: Start with 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.md
openclaw 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 sending

Use 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-20241022

Set 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 logs

Streaming 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.md

Troubleshooting Claude-Specific Errors

ErrorCauseFix
401 authentication_errorInvalid or missing API keyCheck $ANTHROPIC_API_KEY is set and starts with sk-ant-
429 rate_limit_errorToo many tokens per minuteAdd request_delay: 1.0 to config.yaml, or use a rate-limited wrapper
529 overloaded_errorAnthropic API overloaded (rare)Retry after 30s. OpenClaw retries automatically up to 3 times
context_length_exceededInput exceeds 200k tokensSet max_input_tokens in config to truncate automatically
billing_limit_exceededMonthly spend cap reachedRaise limit in Anthropic console or wait for billing cycle reset
Response truncated mid-sentencemax_tokens too lowIncrease max_tokens in config or CLI flag
Slow first token (no streaming)stream: falseSet stream: true in config.yaml

Enable Debug Logging

OPENCLAW_LOG_LEVEL=debug openclaw run "test prompt"
# Shows: model, tokens, request payload, response time

Next Steps

Now that Claude is configured, here are good places to go deeper: