9 Free Ai Models Zero Cost Blockrun
9 Free AI Models, Zero Cost: How BlockRun Gives Developers Top-Tier LLMs for Nothing
The count in this title is a snapshot. It was 9 when this was written; the
published free tier is now 8 — models are withheld from /v1/models when aprovider's terms change, most recently over NVIDIA's prompt-retention policy.
The URL keeps its original slug so existing links do not break. Current figures:
blockrun.ai/brand/numbers.json.
The Cost Problem Nobody Talks About
It's 2026. Large language models are table stakes for developers. But here's the uncomfortable truth — the models you can afford aren't good enough, and the good ones aren't affordable.
Claude Opus 4 runs $15/$75 per million tokens. GPT-4o sits at $2.50/$10. Even the "cheap" models add up fast. For indie developers, students, and early-stage startups, $50–$200/month in API costs is real money — especially when half of it goes to throwaway experiments, prompt iterations, and dead-end debugging sessions.
You're not just paying for intelligence. You're paying for every mistake, every retry, every discarded attempt.
What if you had 9 high-quality LLMs — completely free, unlimited calls, up to 1M context — and could use them right now?
BlockRun's answer: just take them.
---
The Lineup: 9 Models, $0.00
Through ClawRouter — BlockRun's local AI routing proxy — you get zero-cost access to the following:
| Model | Context | Reasoning | Best For |
| --------------------------- | ------- | --------- | ------------------------------------------- |
| GPT-OSS 120B | 128K | — | General chat, summaries, formatting |
| GPT-OSS 20B | 128K | — | Fast lightweight tasks |
| DeepSeek V4 Flash | 1M | ✅ | Fast chat + summarization over huge context |
| Qwen3-Next 80B Thinking | 131K | ✅ | Reasoning, multi-step planning |
| Qwen3 Coder 480B | 131K | — | Professional code generation |
| GLM-4.7 | 131K | ✅ | Chinese-English bilingual reasoning |
| Llama 4 Maverick | 131K | ✅ | Open-source all-rounder |
| Mistral Small 4 119B | 131K | — | Fast multilingual chat |
| Nemotron 3 Nano Omni | 256K | ✅ | Vision — text + image + video + audio |
Price: $0.00 per million tokens. Input free. Output free. No hidden fees. No daily caps. No trial period.
This isn't "free for your first 1,000 requests." It's not "free but rate-limited to uselessness." It's production-grade, unlimited, genuinely free inference.
---
Why Free?
BlockRun's business model is simple: make the best models accessible, charge only for the premium ones.
The 9 free models are BlockRun's foundation tier. They cover the vast majority of everyday developer tasks — chat, coding, translation, summarization, lightweight reasoning — without costing a cent. When you need heavier firepower (Claude Opus 4, GPT-4o, o3), BlockRun charges per-call via x402 micropayments. No subscriptions, no monthly minimums — just pay for what you use, only when you need to.
The free tier isn't a loss leader. It's the product. BlockRun believes baseline AI capability should be accessible to every developer, regardless of budget. The premium tier exists for tasks that genuinely demand it.
---
Not Just Free: How Smart Routing Squeezes Every Dollar
ClawRouter's value proposition isn't just "here are free models." It's intelligent routing — automatically selecting the right model for each request based on prompt complexity.
The Four-Tier Architecture
ClawRouter classifies every incoming request into one of four complexity tiers:
| Tier | Typical Tasks | ECO Route (Cheapest) | AUTO Route (Balanced) |
| ------------- | ------------------------------------- | ----------------------------- | --------------------- |
| SIMPLE | Formatting, translation, Q&A | 🆓 GPT-OSS 120B (FREE) | GPT-4o Mini |
| MEDIUM | Summaries, analysis, general coding | 🆓 DeepSeek V3.2 (FREE) | DeepSeek V3.2 |
| COMPLEX | Architecture, complex code | 🆓 Nemotron Ultra 253B (FREE) | Claude Sonnet 4 |
| REASONING | Mathematical proofs, multi-step logic | DeepSeek R1 | Claude Opus 4 |
Look at the ECO column. Three out of four tiers route to free models. Unless you're doing the hardest reasoning tasks, your daily work costs nothing.
Real-World Cost Comparison
Assume 100 requests per day, distributed roughly as:
- 40% SIMPLE (chat, translation, formatting)
- 30% MEDIUM (coding, analysis)
- 20% COMPLEX (architecture, deep debugging)
- 10% REASONING (math, formal logic)
| Approach | Estimated Monthly Cost |
| --------------------------- | ---------------------- |
| Pure Claude Opus 4 | ~$75–150 |
| Pure GPT-4o | ~$15–30 |
| ClawRouter AUTO mode | ~$5–10 |
| ClawRouter ECO mode | ~$1–3 |
| Manual free model selection | $0 |
ECO mode is 98% cheaper than pinning Claude Opus 5 for every request.
---
Deep Dive: What Each Free Model Does Best
GPT-OSS 120B / 20B — The Workhorse
GPT-OSS is BlockRun's default general-purpose free model. The 120B version is ClawRouter's default SIMPLE-tier model in ECO mode and the ultimate fallback when wallet balance runs low. It handles conversation, text generation, and summarization with reliable consistency.
The 20B variant trades capability for speed — noticeably faster responses for tasks that don't need the bigger model's muscle.
Best for: Daily conversation, text summaries, reformatting, translation, quick answers.
Nemotron Ultra 253B — The Free Flagship
253 billion parameters. Reasoning capability. 131K context window. Nemotron Ultra is the single strongest free model on BlockRun — and it's the default when you type /model free in ClawRouter.
This is the model you reach for when the task is genuinely hard but you don't want to pay for it. Complex analysis, multi-step planning, mathematical reasoning — Nemotron Ultra handles them with surprising competence for a zero-cost option.
Best for: Complex reasoning, math, logic, deep analysis, planning. If you remember one free model name, remember this one.
Nemotron 3 Super 120B / Nemotron Super 49B — The Gradient
The Nemotron family gives you three reasoning-capable models at different scales (253B / 120B / 49B). This gradient lets you match firepower to task difficulty. The 49B version is noticeably faster, making it ideal for development workflows where you're iterating rapidly and don't need maximum capability on every call.
Best for: When you need reasoning but want faster responses than Ultra 253B.
DeepSeek V3.2 — The Developer's Weapon
DeepSeek has consistently punched above its weight on coding benchmarks. V3.2 adds reasoning capability on top of already strong code generation. It's ClawRouter's MEDIUM-tier primary in ECO mode — the model that handles your everyday coding tasks for free.
Best for: Code generation and completion, code review and refactoring, technical design, debugging and error analysis.
Mistral Large 675B — The Largest Free Model
At 675 billion parameters, Mistral Large is the biggest model in the free lineup by parameter count. Mistral has always excelled at multilingual tasks, with particular strength in European languages (French, German, Spanish). Reasoning-capable and formidable on long-form content.
Best for: Multilingual content, long document analysis, complex instruction following, cross-language translation.
Qwen3 Coder 480B — Brute-Force Code Generation
Alibaba's Qwen team built this 480B model specifically for code. When your task is "write a lot of correct code," raw parameter count matters — and 480B parameters dedicated to code generation produces noticeably more complete and accurate output than smaller generalist models.
Best for: Large-scale code generation, complex algorithm implementation, multi-file changes, codebase-level understanding.
Devstral 2 123B — Mistral's Developer Edition
Devstral is the developer-optimized variant of Mistral, fine-tuned for code comprehension, technical documentation, and API design. Think of it as Mistral Large's more focused sibling.
Best for: Code understanding, technical documentation, API design, developer tooling.
GLM-4.7 — The Chinese-English Bridge
Zhipu AI's GLM-4.7 shines in Chinese-language scenarios while maintaining strong English capability. Reasoning-capable. If your users, documentation, or codebase involves Chinese, this model deserves your attention.
Best for: Chinese content generation, Chinese-English translation, reasoning in Chinese context, applications targeting Chinese-speaking users.
Llama 4 Maverick — Meta's Latest
Meta's newest open-source model represents the current state of the art in open LLMs. Reasoning-capable, well-balanced across benchmarks, and backed by Meta's massive training infrastructure.
Best for: General-purpose tasks where you want the most recent open-source capabilities.
---
Get Started in 5 Minutes
Option 1: Via ClawRouter (Recommended)
Install
npm install @blockrun/clawrouterStart the local proxy
clawrouter startfrom openai import OpenAIclient = OpenAI(
base_url="http://localhost:8402/v1",
api_key="your-blockrun-key"
)
Pick a specific free model
response = client.chat.completions.create(
model="free/nemotron-ultra-253b",
messages=[{"role": "user", "content": "Explain quantum entanglement"}]
)Or let ECO routing pick the best free model automatically
response = client.chat.completions.create(
model="auto",
messages=[{"role": "user", "content": "Hello world"}]
)Option 2: Switch Models in Claude Code
If you're using Claude Code, one command switches you to any free model:
/model free → Nemotron Ultra 253B (strongest free)
/model deepseek-free → DeepSeek V3.2
/model mistral-free → Mistral Large 675B
/model glm-free → GLM-4.7
/model llama-free → Llama 4 MaverickSeamless. No config changes. No restarts.
---
The Honest Limitations
Free models aren't a silver bullet. Here's what you need to know:
1. No Verified Tool Calling
None of these 11 models have structured function calling (tool use) enabled. If your application depends on tool calling, you need a paid model (GPT-4o, Claude Sonnet, etc.).
2. Reasoning Has a Ceiling
Five models are marked reasoning-capable, and they handle most tasks well. But on the hardest problems — competition-level math, formal proofs, deep multi-step planning — they don't match Claude Opus 4 or o3. That's why ClawRouter's REASONING tier doesn't use free models.
3. Context Is Large, Not Largest
Most free models offer 128K–256K context (DeepSeek V4 Flash reaches 1M), which is generous for most tasks; but if you're processing entire book collections or massive monorepos, you may still want Gemini's 2M window.
---
Best Practices: Maximizing Free Models
Strategy 1: Match Model to Task
Don't use one model for everything. Route by task type:
Quick chat, formatting → GPT-OSS 120B (fastest)
Code generation → DeepSeek V3.2 or Qwen3 Coder 480B
Reasoning required → Nemotron Ultra 253B
Chinese content → GLM-4.7
Multilingual work → Mistral Large 675B
Latest open-source → Llama 4 MaverickStrategy 2: Free for 80%, Paid for 20%
Use ECO mode for the bulk of daily tasks — it's free. Reserve paid models (Claude Opus, GPT-4o) for the 20% that genuinely requires top-tier capability: production-critical reasoning, tool calling, agentic workflows. Monthly AI spend drops to single digits.
Strategy 3: Prototype Free, Ship Paid
During development, iterate freely — prompt engineering, edge case testing, architecture exploration — all on free models. Once you've nailed the approach, switch to a paid model for final quality assurance and production deployment.
---
The Bigger Picture: What This Means for AI Access
Look at the cost trajectory over the past three years:
- 2023: GPT-4 dominates alone at $30/$60 per M tokens
- 2024: Open-source models surge, prices halve repeatedly
- 2025: DeepSeek, Qwen push top-tier inference below $1/M
- 2026: BlockRun offers 9 free models through a single API
Nine free models isn't just a product feature — it's a signal. Baseline AI capability is becoming infrastructure. Like internet bandwidth before it, the cost of "good enough" AI inference is converging toward zero.
BlockRun and ClawRouter exist to be the routing layer in this transition: not locked to any single provider, not bound to any single model, always giving developers the lowest-cost path to the right capability.
Today it's 9 free models. Tomorrow it could be 50. Prices will only drop. Capabilities will only improve.
The one constant: your code doesn't need to change.
---
Start Now
npm install @blockrun/clawrouter
clawrouter startPoint your base_url to http://localhost:8402/v1. That's the whole setup.
Nine free models. Up to 1M context. Unlimited calls. Zero cost.
Go build something.
---
_Based on ClawRouter v0.12.84. Model availability may change with future releases. For the latest information, visit blockrun.ai._
---
Anthropic Cost Savings
Stop Overpaying for Claude: How ClawRouter Cuts Your Anthropic Bill by 70%
_You love Claude. Your wallet doesn't. Here's how to keep frontier-quality answers — at a fraction of the cost._
---
The Problem: Claude Is Brilliant, But Expensive
If you're building with the Anthropic API, you already know Claude is the best reasoning model available. Opus 4.6 runs $5/$25 per million tokens. Sonnet at $3/$15. Even Haiku costs $1/$5.
But here's what most developers won't admit: the majority of your API calls don't need Claude.
Think about your typical workload. You're building a SaaS app. Some requests need Claude's reasoning — debugging complex code, analyzing long documents, orchestrating multi-step agent workflows. But most requests are mundane: extracting JSON from text, answering simple user questions, translating a string, summarizing a paragraph.
You're paying $3-25 per million tokens for work that a $0.10 model handles identically.
The problem is simple: you're paying Claude rates on 100% of your requests, but only ~30% of them need Claude.
---
What Does a Typical Developer Workload Look Like?
The Everyday Tasks (~70% of requests)
These are the requests you fire off constantly and barely think about:
- "Extract the name and email from this text and return JSON" — Any model can do this. You're paying Claude $15/M output tokens for structured extraction that a $0.40 model handles perfectly.
- "Summarize this customer support ticket in 2 sentences" — Summarization is a solved problem. You don't need frontier reasoning here.
- "Translate this error message to Spanish" — Translation is a commodity task. Paying Claude rates for it is like taking a Lamborghini to the grocery store.
- "What's the difference between useEffect and useLayoutEffect?" — Factual Q&A. Every model gets this right.
- "Convert this CSV data to a markdown table" — Pure formatting. A free model does this identically.
The Tasks That Actually Need Claude (~30% of requests)
This is where you're paying for real value:
- Complex code generation — "Refactor this authentication module to support OAuth2 + PKCE, handle token refresh, and add rate limiting." Multi-file, multi-constraint reasoning. Claude earns its price here.
- Long-document analysis — "Read this 50-page contract and identify all clauses that could expose us to liability over $1M." Context window + reasoning quality matter.
- Multi-step agent orchestration — "Scan these 5 APIs, cross-reference the data, and generate a report with recommendations." Agentic workflows where the model needs to maintain a plan across many steps.
- Advanced reasoning — "Debug this race condition in our distributed system" or "Prove this algorithm is O(n log n)." Tasks where cheaper models lose the thread.
---
The Solution: ClawRouter
ClawRouter is an open-source local proxy that sits between your app and 70 AI models. It saves you money in three ways: smart routing, token optimization, and response caching.
┌─────────────┐ ┌──────────────────────────────┐ ┌──────────────────┐
│ Your App │────▶│ ClawRouter │────▶│ 41+ AI Models │
│ (OpenAI │ │ (local proxy) │ │ │
│ SDK) │ │ │ │ FREE (9 free) │
│ │ │ 1. Route to cheapest model │ │ $0.10 (gemini) │
│ model: │ │ 2. Compress tokens │ │ $3.00 (sonnet) │
│ "auto" │ │ 3. Cache repeated requests │ │ $0.20 (grok) │
└─────────────┘ └──────────────────────────────┘ └──────────────────┘---
How You Save: Three Layers
Layer 1: Smart Routing (the biggest win)
ClawRouter scores every prompt against 15 dimensions in <1ms and routes it to the cheapest model that can handle the task.
"What is the capital of France?"
→ SIMPLE → nvidia/gpt-oss-120b (FREE)"Extract JSON from this text"
→ SIMPLE → nvidia/gpt-oss-120b (FREE)
"Refactor this auth module with OAuth2 + PKCE"
→ COMPLEX → anthropic/claude-sonnet-4.6 ($3/$15)
"Prove sqrt(2) is irrational, show every step"
→ REASONING → xai/grok-4-1-fast-reasoning ($0.20/$0.50)
From real production data across 20,000+ paying user requests:
| Model | % of Requests | Price (input/output per M) |
| --------------------- | ------------- | -------------------------- |
| gemini-2.5-flash-lite | 34.5% | $0.10 / $0.40 |
| claude-sonnet-4.6 | 22.7% | $3.00 / $15.00 |
| kimi-k2.5 | 16.2% | $0.60 / $3.00 |
| minimax-m2.5 | 6.5% | $0.30 / $1.20 |
| grok-code-fast | 6.1% | $0.20 / $1.50 |
| claude-haiku-4.5 | 2.7% | $1.00 / $5.00 |
| nvidia/gpt-oss-120b | 2.1% | FREE |
| grok-reasoning | 2.9% | $0.20 / $0.50 |
| Others | 6.3% | varies |
Result: 77% of requests go to models that cost 5-150x less than Sonnet. Only the ~23% that genuinely need Claude still go to Claude.
Layer 2: Token Compression (saves on every request)
Even when a request does go to Claude, ClawRouter reduces the tokens you pay for. The proxy runs a multi-layer compression pipeline on your request before sending it to the provider — and you pay based on the compressed token count, not the original.
How it works:
| Compression Layer | What It Does | Savings |
| ---------------------------- | ------------------------------------------------------ | ------- |
| Deduplication | Removes duplicate messages in conversation history | 2-5% |
| Whitespace normalization | Strips excess whitespace, trailing spaces, empty lines | 3-8% |
| JSON compaction | Minifies JSON in tool calls and results | 2-4% |
These three layers are enabled by default and are completely safe — they don't change semantic meaning. The compression triggers automatically on requests larger than 180KB (common in agent workflows and long conversations).
For agent-heavy workloads (long tool outputs, multi-turn conversations), the savings are even larger. An optional observation compression layer can reduce massive tool outputs by up to 97% — turning 10KB of verbose log output into 300 characters of essential information.
Typical combined savings: 7-15% fewer tokens per request. On long-context agent workloads: 20-40%.
This matters most on expensive models. If you're sending a 50K-token agent conversation to Claude Sonnet, 15% compression saves ~$0.03 per request — that adds up to real money at scale.
Layer 3: Response Cache + Request Deduplication (saves 100%)
ClawRouter caches responses locally. If your app sends the same request within 10 minutes, you get an instant response at zero cost — no API call, no tokens billed.
This is more common than you'd think:
- Retry logic — Your app retries on timeout. Without dedup, you pay twice. With ClawRouter, the retry resolves from cache instantly.
- Redundant requests — Multiple users or processes asking the same thing? One API call, multiple responses.
- Agent loops — Agentic frameworks often re-query with identical context. Cache catches these.
Request 1: "Summarize this document" → API call → $0.02 → cached
Request 2: "Summarize this document" → cache hit → $0.00 → instant
Request 3: "Summarize this document" → cache hit → $0.00 → instantThe deduplicator also catches in-flight duplicates: if two identical requests arrive simultaneously, only one goes to the provider. Both callers get the same response.
---
The Cost Math (Honest Numbers)
10,000 mixed requests per month, averaging 1,000 input tokens and 500 output tokens each.
Direct Anthropic API
| Approach | Input (10M tokens) | Output (5M tokens) | Monthly Total |
| ----------------- | ------------------ | ------------------ | ------------- |
| All Claude Sonnet | $30.00 | $75.00 | $105.00 |
| All Claude Opus | $50.00 | $125.00 | $175.00 |
ClawRouter (real paying-user distribution)
| Tier | % Requests | Routed To | Cost |
| ------------------------ | ---------- | --------------------- | ----------- |
| Cheap models | 34.5% | gemini-flash-lite | $0.76 |
| Mid-tier | 16.2% | kimi-k2.5 | $2.43 |
| Claude (complex) | 22.7% | claude-sonnet-4.6 | $17.44 |
| Code models | 6.1% | grok-code-fast | $0.52 |
| Reasoning | 2.9% | grok-reasoning | $0.03 |
| Haiku | 2.7% | claude-haiku-4.5 | $0.76 |
| Free | 2.1% | nvidia/gpt-oss-120b | $0.00 |
| Other | 12.8% | various | $1.18 |
| Subtotal (routing) | | | $23.12 |
| Token compression (~10%) | | | -$2.31 |
| Cache hits (~5% est.) | | | -$1.16 |
| Final Total | | | ~$19.65 |
The Bottom Line
| Approach | Monthly Cost | Savings |
| -------------------- | ------------ | -------------------------------- |
| Direct Claude Sonnet | $105.00 | — |
| Direct Claude Opus | $175.00 | — |
| ClawRouter | ~$20 | ~81% vs Sonnet, ~89% vs Opus |
Breaking down where the savings come from:
| Savings Source | Estimated Impact | How |
| --------------------- | ------------------------ | -------------------------------- |
| Smart routing | ~68% cost reduction | 77% of requests → cheaper models |
| Token compression | ~7-15% on remaining cost | Fewer tokens billed per request |
| Response cache | ~3-5% additional | Repeat requests cost $0 |
| Request dedup | Prevents overcharges | Retries don't double-bill |
---
How the 15-Dimension Router Works
ClawRouter runs a weighted scoring algorithm on every prompt — entirely locally, in under 1 millisecond, zero external API calls.
| Dimension | Weight | Detects |
| -------------------- | ------ | ------------------------------------------ |
| Reasoning Markers | 0.18 | "prove," "step by step," "analyze" |
| Code Presence | 0.15 | function, class, import, code blocks |
| Multi-Step Patterns | 0.12 | "first...then," numbered steps |
| Technical Terms | 0.10 | Domain-specific vocabulary |
| Token Count | 0.08 | Short vs. long context |
| Question Complexity | 0.05 | Nested or compound questions |
| Creative Markers | 0.05 | Creative writing indicators |
| Constraint Count | 0.04 | "max," "minimum," "at most" |
| Imperative Verbs | 0.03 | "create," "generate," "build" |
| Output Format | 0.03 | JSON, YAML, table, markdown |
| Simple Indicators | 0.02 | "what is," "define," "translate" |
| Reference Complexity | 0.02 | "the code above," "the docs" |
| Domain Specificity | 0.02 | Quantum, genomics, etc. |
| Negation Complexity | 0.01 | "don't," "never," "avoid" |
The weighted score maps to four tiers:
Score < 0.0 → SIMPLE → Free or ultra-cheap models
Score 0.0–0.3 → MEDIUM → Mid-tier (Kimi K2.5, DeepSeek)
Score 0.3–0.5 → COMPLEX → Frontier (Claude Sonnet, Gemini Pro)
Score > 0.5 → REASONING → Specialized (Grok Reasoning, DeepSeek-R)Multilingual support across 9 languages. Tool-calling and vision requests automatically filter for compatible models. If the primary model fails, a fallback chain tries alternatives before returning an error.
---
Getting Started: 3 Minutes
Step 1: Install
npx @blockrun/clawrouterStarts a local proxy on port 8402. Auto-generates a crypto wallet. Done.
Step 2: Update Your Code
Python — change 2 lines:
from openai import OpenAIclient = OpenAI(
base_url="http://localhost:8402/v1", # ← was: https://api.anthropic.com
api_key="unused" # ← ClawRouter handles auth
)
response = client.chat.completions.create(
model="blockrun/auto", # ← was: claude-sonnet-4.6
messages=[{"role": "user", "content": "Your prompt here"}]
)
TypeScript — same idea:
import OpenAI from "openai";const client = new OpenAI({
baseURL: "http://localhost:8402/v1",
apiKey: "unused",
});
const response = await client.chat.completions.create({
model: "blockrun/auto", // or "eco" for max savings, "premium" for best quality
messages: [{ role: "user", content: "Your prompt here" }],
});
Routing profiles:
- blockrun/auto — Balanced cost/quality (default)
- blockrun/eco — Maximum savings (free tier aggressively)
- blockrun/premium — Best quality (Opus/Sonnet/GPT-5)
- blockrun/free — Free tier only (gpt-oss-120b)
Step 3: Fund (optional)
Your wallet address is shown on startup.
Send any amount of USDC on Base chain to that address.
$1 is enough for hundreds of requests.
Or start with $0 — the free tier model works immediately.
That's it. Your existing code works. Your output quality on complex tasks stays the same.
Check Your Savings
$ /stats 7╔═══════════════════════════════════════════════════════╗
║ ClawRouter v0.12.12 — Usage Statistics ║
╠═══════════════════════════════════════════════════════╣
║ Period: last 7 days ║
║ Total Requests: 1,523 ║
║ Actual Cost: $12.35 ║
║ Baseline Cost: $156.23 (if all went to Opus 4.6) ║
║ Saved: $143.89 (92.1%) ║
╠═══════════════════════════════════════════════════════╣
║ SIMPLE ████████████████ 50.2% (765 reqs) ║
║ MEDIUM ██████████ 28.5% (434 reqs) ║
║ COMPLEX ██████ 15.0% (228 reqs) ║
║ REASONING ██ 6.3% (96 reqs) ║
╚═══════════════════════════════════════════════════════╝
---
Why ClawRouter Instead of OpenRouter?
| | ClawRouter | OpenRouter |
| ---------------------- | --------------------------------------------------- | ---------------------------------- |
| Smart routing | Automatic — 15-dimension scorer picks the model | Manual — you pick the model |
| Token optimization | Built-in compression (7-15% savings) | None |
| Response caching | Local cache, repeat requests = $0 | None |
| Request dedup | Retries don't double-bill | None |
| Routing latency | <1ms (local, on your machine) | Additional network hop |
| Payments | Non-custodial USDC on Base (your wallet, your keys) | Prepaid credit balance (custodial) |
| Free tier | GPT-OSS-120B (always available) | No free models |
| API keys | Zero — proxy handles all auth | You manage keys per provider |
| Algorithm | Open-source, MIT license, modify it yourself | Proprietary |
The fundamental difference: OpenRouter is a model marketplace where you choose. ClawRouter is an intelligent proxy that chooses for you, compresses your tokens, caches your responses, and pays per-request with crypto from your own wallet.
---
TL;DR
| What | Details |
| -------------------- | -------------------------------------------------------------------------- |
| Problem | You pay Claude $3-25/M tokens on every request, but ~70% don't need Claude |
| Solution | ClawRouter auto-routes + compresses + caches |
| Savings | ~81% vs Sonnet, ~89% vs Opus |
| How | Routing (68%) + token compression (7-15%) + caching (3-5%) |
| Code change | 2 lines (base_url + model name) |
| Setup time | 3 minutes |
| Quality tradeoff | None — complex tasks still go to Claude |
| Open source | MIT license, local proxy, non-custodial payments |
Start saving now:
npx @blockrun/clawrouterLinks:
- ClawRouter on GitHub — MIT License
- BlockRun — AI model marketplace
- x402 Protocol — Per-request crypto payments for AI
---
_Cost data based on real production traffic from paying users across 20,000+ requests, March 2026. Savings vary by workload — agent-heavy and long-context workloads see larger compression benefits. ClawRouter is open-source and part of the BlockRun ecosystem._
---
Anthropic Third Party Harness Changes
Anthropic Is Cutting Off Third-Party Harnesses. Here's What You Can Do.
Starting April 4, 2026, Anthropic will no longer allow Claude subscription limits to cover third-party harnesses like OpenClaw. If you've been using your Claude Pro/Team subscription to power autonomous agents, code assistants, or any tool outside of Anthropic's own products — that stops tomorrow.
What Changed
Anthropic sent this to affected users:
Starting April 4 at 12pm PT, you'll no longer be able to use your Claude subscription limits for third-party harnesses including OpenClaw. To keep using third-party harnesses with your Claude login, turn on extra usage — a pay-as-you-go option billed separately from your subscription.
Translation: your $20/month Claude Pro subscription now only covers claude.ai, Claude Code, and Claude Cowork. Everything else requires "extra usage" — Anthropic's pay-as-you-go billing with no spending cap by default.
They're offering a one-time credit equal to your subscription price (redeemable by April 17) and up to 30% off on prepaid bundles. That softens the blow, but doesn't change the fundamental shift: third-party agent usage is now metered separately, at full API rates.
Why This Matters
If you're running agents through OpenClaw, Continue.dev, or any third-party harness, your costs are about to change dramatically:
- Claude Sonnet 4.6: $3/M input, $15/M output tokens
- Claude Opus 4.6: $15/M input, $75/M output tokens
An agent session that sends 50 requests averaging 4K tokens each? That's roughly $3–15 per session on Sonnet, $15–75 on Opus. Run a few sessions a day and you're looking at $100–500+/month — far more than the $20 subscription you were paying.
The Alternative: Stop Overpaying for Every Request
Here's the thing most people don't realize: ~70% of agent requests don't need Claude at all.
Status checks, JSON extraction, simple Q&A, code formatting, translation — these tasks get routed to Claude Opus at $75/M output tokens when a free model or Gemini Flash at $0.40/M would produce identical results.
This is exactly the problem ClawRouter solves.
ClawRouter: Smart Routing for Agents
ClawRouter is an open-source local proxy that sits between your agent and 70 LLM models across 9 providers. It analyzes every request across 15 dimensions and routes it to the cheapest model that can handle it — in under 1ms, entirely locally.
Your Agent → ClawRouter (localhost:8402) → Best model for the jobSIMPLE ("what is X?") → Free model $0.00
MEDIUM ("review this code") → Kimi-K2.5 $0.002
COMPLEX ("refactor this OAuth") → Claude Sonnet 4.6 $0.009
REASONING ("prove this theorem")→ Grok-4-Reasoning $0.001
Claude is still there when you need it — for complex reasoning, nuanced code review, architectural decisions. But it's not wasted on tasks a smaller model handles equally well.
Real Numbers
From 20,000+ production requests:
| Where requests actually go | % of traffic | Cost per M tokens |
| -------------------------------- | ------------ | ----------------- |
| Gemini Flash Lite (simple tasks) | 34.5% | $0.10 / $0.40 |
| Claude Sonnet (complex only) | 22.7% | $3.00 / $15.00 |
| Kimi-K2.5 (medium tasks) | 16.2% | $0.60 / $3.00 |
| Free models (trivial tasks) | 12.8% | $0.00 |
| Others | 13.8% | varies |
Result: 88% cheaper than pinning Claude Opus 5 for every request — the published figure, priced on a stated workload mix rather than estimated.
A typical user running 10K mixed requests/month:
- Direct Claude Sonnet: ~$105/month
- Direct Claude Opus: ~$175/month
- ClawRouter: ~$20/month
How It Works
npx @blockrun/clawrouter # Install and start (generates wallet automatically)Then point your agent at http://localhost:8402/v1/ with any OpenAI-compatible client. That's it.
- No API keys to manage — wallet-based cryptographic auth
- No subscriptions — pay per request in USDC (Base or Solana)
- No vendor lock-in — 70 models, switch anytime
- You control your wallet — non-custodial, funds never held by a third party
- Budget caps — set a max spend per session, ClawRouter gracefully downgrades when budget runs low
- Token compression — 7-layer pipeline reduces token costs by 7–40% before they hit any provider
- Response caching — identical requests within 10 minutes cost $0
- 9 free models — for tasks that don't need a paid model at all
Routing Profiles
| Profile | Strategy | Savings | Command |
| --------- | ----------------------- | ------- | ---------------- |
| auto | Balanced cost + quality | 74–100% | /model auto |
| eco | Maximum savings | 95–100% | /model eco |
| premium | Best quality always | 0% | /model premium |
| free | Free models only | 100% | /model free |
The Bottom Line
Anthropic's change isn't surprising — they need to manage capacity, and third-party harnesses were consuming disproportionate resources relative to subscription revenue. It's a reasonable business decision.
But it means the economics of running agents just changed. If you're paying API rates for every request, the cost adds up fast. Smart routing — sending each request to the cheapest model that can handle it — is no longer a nice-to-have. It's the difference between a $20/month AI workflow and a $200/month one.
ClawRouter is open source, runs locally, and takes 30 seconds to set up:
npx @blockrun/clawrouterYour agents keep working. Your costs stay under control. Claude is still there when you actually need it.
---
_ClawRouter is built by BlockRun. Source code: github.com/BlockRunAI/ClawRouter_
---
Architecture
Architecture
Technical deep-dive into ClawRouter's internals.
Table of Contents
- System Overview
- Request Flow
- Routing Engine
- Payment System
- Optimizations
- Source Structure
---
System Overview
/ Detailed source-code truncated for AI context efficiency. /Key Principles:
- 100% local routing — No API calls for model selection
- Client-side only — Your wallet key never leaves your machine
- Non-custodial — USDC stays in your wallet until spent
- Dual-chain — USDC on Base (EVM) or USDC on Solana; no SOL token accepted
---
Request Flow
1. Request Received
POST /v1/chat/completions
{
"model": "blockrun/auto",
"messages": [{ "role": "user", "content": "What is 2+2?" }],
"stream": true
}2. Deduplication Check
// SHA-256 hash of request body
const dedupKey = RequestDeduplicator.hash(body);// Check completed cache (30s TTL)
const cached = deduplicator.getCached(dedupKey);
if (cached) {
return cached; // Replay cached response
}
// Check in-flight requests
const inflight = deduplicator.getInflight(dedupKey);
if (inflight) {
return await inflight; // Wait for original to complete
}
3. Smart Routing (if model is blockrun/auto)
// Extract user's last message
const prompt = messages.findLast((m) => m.role === "user")?.content;// Run 15-dimension weighted scorer
const decision = route(prompt, systemPrompt, maxTokens, {
config: DEFAULT_ROUTING_CONFIG,
modelPricing,
});
// decision = {
// model: "google/gemini-2.5-flash",
// tier: "SIMPLE",
// confidence: 0.92,
// savings: 0.99,
// costEstimate: 0.0012,
// }
4. Balance Check
const estimated = estimateAmount(modelId, bodyLength, maxTokens);
const sufficiency = await balanceMonitor.checkSufficient(estimated);if (sufficiency.info.isEmpty) {
throw new EmptyWalletError(walletAddress);
}
if (!sufficiency.sufficient) {
throw new InsufficientFundsError({ ... });
}
if (sufficiency.info.isLow) {
onLowBalance({ balanceUSD, walletAddress });
}
5. SSE Heartbeat (for streaming)
if (isStreaming) {
// Send 200 + headers immediately
res.writeHead(200, {
"content-type": "text/event-stream",
"cache-control": "no-cache",
}); // Heartbeat every 2s to prevent timeout
heartbeatInterval = setInterval(() => {
res.write(": heartbeat\n\n");
}, 2000);
}
6. x402 Payment Flow
Base (EVM) — EIP-712 USDC:
1. Request → blockrun.ai/api
2. ← 402 Payment Required
{
"x402Version": 1,
"accepts": [{
"scheme": "exact",
"network": "base",
"maxAmountRequired": "5000", // $0.005 USDC
"resource": "https://blockrun.ai/api/v1/chat/completions",
"payTo": "0x..."
}]
}
3. Sign EIP-712 typed data (EIP-3009 TransferWithAuthorization) with EVM wallet key
4. Retry with X-PAYMENT header
5. ← 200 OK with responseSolana — SVM USDC:
1. Request → sol.blockrun.ai/api
2. ← 402 Payment Required
{
"x402Version": 1,
"accepts": [{
"scheme": "exact",
"network": "solana",
"maxAmountRequired": "5000", // $0.005 USDC (6 decimals)
"resource": "https://sol.blockrun.ai/api/v1/chat/completions",
"payTo": "<base58 address>"
}]
}
3. Build and sign Solana transaction (SPL Token USDC transfer) with Solana wallet key
- Wallet derived via SLIP-10 Ed25519 (BIP-44 m/44'/501'/0'/0', Phantom-compatible)
4. Retry with X-PAYMENT header (base64-encoded signed transaction)
5. ← 200 OK with responseImportant: Both chains accept only USDC tokens. Sending SOL or ETH to the wallet will not fund API payments.
7. Fallback Chain (on provider errors)
const FALLBACK_STATUS_CODES = [400, 401, 402, 403, 429, 500, 502, 503, 504];for (const model of fallbackChain) {
const result = await tryModelRequest(model, ...);
if (result.success) {
return result.response;
}
if (result.isProviderError && !isLastAttempt) {
console.log(Fallback: ${model} → next);
continue;
}
break;
}
8. Response Streaming
// Convert non-streaming JSON to SSE format
// (BlockRun API returns JSON, we simulate SSE)// Chunk 1: role
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"role":"assistant"}}]}
// Chunk 2: content
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"content":"4"}}]}
// Chunk 3: finish
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{},"finish_reason":"stop"}]}
data: [DONE]
---
Routing Engine
Weighted Scorer
The routing engine uses a 15-dimension weighted scorer that runs entirely locally:
function classifyByRules(
prompt: string,
systemPrompt: string | undefined,
tokenCount: number,
config: ScoringConfig,
): ClassificationResult {
let score = 0;
const signals: string[] = []; // Dimension 1: Reasoning markers (weight: 0.18)
const reasoningCount = countKeywords(prompt, config.reasoningKeywords);
if (reasoningCount >= 2) {
score += 0.18 * 2; // Double weight for multiple markers
signals.push("reasoning");
}
// Dimension 2: Code presence (weight: 0.15)
if (hasCodeBlock(prompt) || countKeywords(prompt, config.codeKeywords) > 0) {
score += 0.15;
signals.push("code");
}
// ... 13 more dimensions
// Sigmoid calibration
const confidence = sigmoid(score, (k = 8), (midpoint = 0.5));
return { score, confidence, tier: selectTier(score, confidence), signals };
}
Tier Selection
function selectTier(score: number, confidence: number): Tier | null {
// Special case: 2+ reasoning markers → REASONING at high confidence
if (signals.includes("reasoning") && reasoningCount >= 2) {
return "REASONING";
} if (confidence < 0.7) {
return null; // Ambiguous → default to MEDIUM
}
if (score < 0.3) return "SIMPLE";
if (score < 0.6) return "MEDIUM";
if (score < 0.8) return "COMPLEX";
return "REASONING";
}
Overrides
Certain conditions force tier assignment:
// Large context → COMPLEX
if (tokenCount > 100000) {
return { tier: "COMPLEX", method: "override:large_context" };
}// Structured output (JSON/YAML) → min MEDIUM
if (systemPrompt?.includes("json") || systemPrompt?.includes("yaml")) {
return { tier: Math.max(tier, "MEDIUM"), method: "override:structured" };
}
---
Payment System
x402 Protocol
ClawRouter uses the x402 protocol for micropayments. Both chains use the same flow; the signing step differs:
┌────────────┐ ┌──────────────────────┐ ┌────────────┐
│ Client │────▶│ BlockRun API │────▶│ Provider │
│ (ClawRouter) │ (Base: blockrun.ai │ │ (OpenAI) │
└────────────┘ │ Sol: sol.blockrun) │ └────────────┘
│ │
│ 1. Request │
│─────────────────▶│
│ │
│ 2. 402 + price │
│◀─────────────────│
│ │
│ 3. Sign payment │
│ Base: EIP-712 │
│ Solana: SVM tx │
│ (USDC only) │
│ │
│ 4. Retry + sig │
│─────────────────▶│
│ │
│ 5. Response │
│◀─────────────────│EVM Signing (Base — EIP-712)
const typedData = {
types: {
TransferWithAuthorization: [
{ name: "from", type: "address" },
{ name: "to", type: "address" },
{ name: "value", type: "uint256" },
{ name: "validAfter", type: "uint256" },
{ name: "validBefore", type: "uint256" },
{ name: "nonce", type: "bytes32" },
],
},
primaryType: "TransferWithAuthorization",
domain: { name: "USD Coin", version: "2", chainId: 8453, verifyingContract: USDC_BASE },
message: {
from: walletAddress,
to: payTo,
value: BigInt(5000), // 0.005 USDC (6 decimals)
validAfter: BigInt(0),
validBefore: BigInt(Math.floor(Date.now() / 1000) + 3600),
nonce: crypto.getRandomValues(new Uint8Array(32)),
},
};const signature = await account.signTypedData(typedData);
Solana Signing (SLIP-10 Ed25519)
// Wallet derived via SLIP-10 Ed25519 — Phantom-compatible
// Path: m/44'/501'/0'/0'
const solanaAccount = await deriveSlip10Ed25519Key(mnemonic, "m/44'/501'/0'/0'");// Build SPL Token USDC transfer instruction
const transaction = buildSolanaPaymentTransaction({
from: solanaAddress,
to: payTo, // base58 recipient
mint: USDC_SOLANA, // EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
amount: BigInt(5000), // 0.005 USDC (6 decimals)
});
const signedTx = await signTransaction(transaction, solanaAccount);
// Encoded as base64 in X-PAYMENT header
Pre-Authorization
To skip the 402 round trip:
// Estimate cost before request
const estimated = estimateAmount(modelId, bodyLength, maxTokens);// Pre-sign payment with estimate (+ 20% buffer)
const preAuth: PreAuthParams = { estimatedAmount: estimated };
// Request with pre-signed payment
const response = await payFetch(url, init, preAuth);
---
Optimizations
1. Request Deduplication
Prevents double-charging when clients retry after timeout:
class RequestDeduplicator {
private cache = new Map<string, CachedResponse>();
private inflight = new Map<string, Promise<CachedResponse>>();
private TTL_MS = 30_000; static hash(body: Buffer): string {
return createHash("sha256").update(body).digest("hex");
}
getCached(key: string): CachedResponse | undefined {
const entry = this.cache.get(key);
if (entry && Date.now() - entry.completedAt < this.TTL_MS) {
return entry;
}
return undefined;
}
}
2. SSE Heartbeat
Prevents upstream timeout while waiting for x402 payment:
0s: Request received
0s: → 200 OK, Content-Type: text/event-stream
0s: → : heartbeat
2s: → : heartbeat (client stays connected)
4s: → : heartbeat
5s: x402 payment completes
5s: → data: {"choices":[...]}
5s: → data: [DONE]3. Balance Caching
Avoids RPC calls on every request. Dual-chain monitors are chain-aware:
// EVM monitor (Base): reads USDC balance via eth_call on Base RPC
class BalanceMonitor {
private cachedBalance: bigint | undefined;
private cacheTime = 0;
private CACHE_TTL_MS = 60_000; // 1 minute async checkBalance(): Promise<BalanceInfo> {
if (this.cachedBalance !== undefined && Date.now() - this.cacheTime < this.CACHE_TTL_MS) {
return this.formatBalance(this.cachedBalance);
}
// Fetch USDC balance from Base RPC
const balance = await this.fetchUSDCBalance(); // ERC-20 balanceOf call
this.cachedBalance = balance;
this.cacheTime = Date.now();
return this.formatBalance(balance);
}
deductEstimated(amount: bigint): void {
if (this.cachedBalance !== undefined) {
this.cachedBalance -= amount;
}
}
}
// Solana monitor: reads SPL Token USDC balance via getTokenAccountBalance
class SolanaBalanceMonitor {
// Same interface as BalanceMonitor — proxy.ts uses AnyBalanceMonitor union type
// Retries once on empty to handle flaky public RPC endpoints
// Cache TTL 60s; startup balance never cached (forces fresh read after install)
}
// proxy.ts selects the correct monitor at startup:
const balanceMonitor: AnyBalanceMonitor =
paymentChain === "solana"
? new SolanaBalanceMonitor(solanaAddress, rpcUrl)
: new BalanceMonitor(evmAddress, rpcUrl);
4. Proxy Reuse
Detects and reuses existing proxy to avoid EADDRINUSE:
async function startProxy(options: ProxyOptions): Promise<ProxyHandle> {
const port = options.port ?? getProxyPort(); // Check if proxy already running
const existingWallet = await checkExistingProxy(port);
if (existingWallet) {
// Return handle that uses existing proxy
return {
port,
baseUrl: http://127.0.0.1:${port},
walletAddress: existingWallet,
close: async () => {}, // No-op
};
}
// Start new proxy
const server = createServer(...);
server.listen(port, "127.0.0.1");
// ...
}
---
Source Structure
src/
├── index.ts # Plugin entry, OpenClaw integration
├── proxy.ts # HTTP proxy server, request handling, chain selection
├── provider.ts # OpenClaw provider registration
├── models.ts # 41+ model definitions with pricing
├── auth.ts # Wallet key resolution (file → env → generate)
├── wallet.ts # BIP-39 mnemonic, EVM + Solana key derivation (SLIP-10)
├── x402.ts # EVM EIP-712 payment signing, @x402/fetch
├── balance.ts # EVM USDC balance monitoring (Base RPC)
├── solana-balance.ts # Solana USDC balance monitoring (SPL Token)
├── payment-preauth.ts # Pre-authorization caching (EVM only)
├── dedup.ts # Request deduplication (SHA-256 → cache)
├── logger.ts # JSON usage logging to disk
├── errors.ts # Custom error types
├── retry.ts # Fetch retry with exponential backoff
├── version.ts # Version from package.json
└── router/
├── index.ts # route() entry point
├── rules.ts # 15-dimension weighted scorer (9-language)
├── selector.ts # Tier → model selection + fallback
├── config.ts # Default routing configuration (ECO/AUTO/PREMIUM/AGENTIC)
└── types.ts # TypeScript type definitionsKey Files
| File | Purpose |
| -------------------- | ------------------------------------------------------------- |
| proxy.ts | Core request handling, SSE simulation, fallback chain |
| wallet.ts | BIP-39 mnemonic generation, EVM + Solana (SLIP-10) derivation |
| router/rules.ts | 15-dimension weighted scorer, 9-language keyword sets |
| x402.ts | EIP-712 typed data signing, payment header formatting |
| balance.ts | USDC balance via Base RPC (EVM), caching, thresholds |
| solana-balance.ts | USDC balance via Solana RPC (SPL Token), caching, retries |
| payment-preauth.ts | Pre-authorization cache (EVM; skipped for Solana) |
| dedup.ts | SHA-256 hashing, 30s response cache |
---
Clawrouter Cuts Llm Api Costs 500x
The Most AI-Agent-Native Router for OpenClaw
_OpenClaw is one of the best AI agent frameworks available. Its LLM abstraction layer is not._
---
The $248/Day Problem
<p align="center"><img src="assets/blockrun-248-day-cost-overrun-problem.png" alt="The Autopsy of an Overrun — token volume compounds exponentially in agentic workloads, reaching 11.3M input tokens in a single hour" width="720"></p>
From openclaw/openclaw#3181:
_"We ended up at $248/day before we caught it. Heartbeat on Opus 4.6 with a large context. The dedup fix reduced trigger rate, but there's nothing bounding the run itself."_
_"11.3M input tokens in 1 hour on claude-opus-4-6 (128K context), ~$20/hour."_
Both users ended up disabling heartbeat entirely. The workaround: heartbeat.every: "0" — turning off the feature to avoid burning money.
The root cause isn't configuration error. It's that OpenClaw's LLM layer has no concept of what things cost, and no way to stop a run that's spending too much.
---
What OpenClaw Gets Wrong at the Inference Layer
<p align="center"><img src="assets/blockrun-openclaw-inference-layer-blind-spots.png" alt="Orchestration frameworks are blind to inference realities — cost tier, error semantics, and context size go unscreened" width="720"></p>
OpenClaw is an excellent orchestration framework — session management, tool dispatch, agent routing, memory. But every request it makes hits a single configured model with no awareness of:
Cost tier — A heartbeat status check doesn't need Opus. A file read result doesn't need 128K context. OpenClaw sends both to the same model at the same price.
Rate limit isolation — When one provider hits a 429, OpenClaw's failover logic applies that cooldown to the entire profile, not just the offending model. Every model in the same group is penalized (#49834). If you configured 5 models for fallback, one slow provider can block all of them.
Empty/degraded responses — Some providers return HTTP 200 with empty content, repeated tokens, or a single newline. OpenClaw passes this through to the agent. The agent either errors out, loops, or silently gets a blank response (#49902).
Error semantics — OpenClaw's failover logic has known gaps. We found and fixed two while building ClawRouter:
- MiniMax HTTP 520 (PR #49550) — MiniMax returns {"type":"api_error","message":"unknown error, 520 (1000)"} for transient server errors. OpenClaw's classifier required both "type":"api_error" AND the string "internal server error". MiniMax fails the second check. Result: no failover, silent failure, retry storm.
- Z.ai codes 1311 and 1113 (PR #49552) — Z.ai error 1311 means "model not on your plan" (billing — stop retrying). Error 1113 means "wrong endpoint" (auth — rotate key). Both fell through to null, got treated as rate_limit, triggered exponential backoff, and charged for every retry.
Context size — Agents accumulate context. A 10-message conversation with tool results can easily hit 40K+ tokens. OpenClaw sends the full context every request, on every retry.
---
ClawRouter: Built for Agentic Workloads
<p align="center"><img src="assets/blockrun-clawrouter-openclaw-agentic-proxy-architecture.png" alt="ClawRouter proxy manifold sits between OpenClaw and upstream APIs like GPT-4o, Claude Opus, and Gemini — cost control is a gateway concern" width="720"></p>
ClawRouter is a local OpenAI-compatible proxy, purpose-built for how AI agents actually behave — not how simple chat clients do. It sits between OpenClaw and the upstream model APIs.
OpenClaw → ClawRouter → blockrun.ai → GPT-4o / Opus / Gemini / ...
↑
All the smart stuff happens here1. Token Compression — 7 Layers, Agent-Aware
<p align="center"><img src="assets/blockrun-clawrouter-7-layer-token-compression-openclaw.png" alt="Seven-layer agent-aware token compression — ClawRouter intercepts and compresses requests through 7 filters for 15–40% overall token reduction" width="720"></p>
Agents are the worst offenders for context bloat. Tool call results are verbose. File reads return thousands of lines. Conversation history compounds with every turn.
ClawRouter compresses every request through 7 layers before it hits the wire:
| Layer | What it does | Saves |
| --------------------------- | ------------------------------------------------ | ------------- |
| Deduplication | Removes repeated messages (retries, echoes) | Variable |
| Whitespace | Strips excessive whitespace from all content | 2–8% |
| Dictionary | Replaces common phrases with short codes | 5–15% |
| Path shortening | Codebook for repeated file paths in tool results | 3–10% |
| JSON compaction | Removes whitespace from embedded JSON | 5–12% |
| Observation compression | Summarizes tool results to key information | Up to 97% |
| Dynamic codebook | Learns repetitions in the actual conversation | 3–15% |
Layer 6 is the big one. Tool results — file reads, API responses, shell output — can be 10KB+ each. The actual useful signal is often 200–300 chars. ClawRouter extracts errors, status lines, key JSON fields, and compresses the rest. Same model intelligence, 97% fewer tokens on the bulk.
<p align="center"><img src="assets/blockrun-clawrouter-observation-compression-97-percent-token-savings.png" alt="Extracting intelligence from tool bloat — raw tool output is 97% noise, ClawRouter filters to 3% signal with errors, status lines, and key values" width="720"></p>
Overall reduction: 15–40% on typical agentic workloads. On the $248/day scenario, that's $150–$200/day in savings from compression alone, before any routing changes.
2. Automatic Tier Routing — Right Model for Each Request
<p align="center"><img src="assets/blockrun-clawrouter-openclaw-automatic-tier-routing-model-selection.png" alt="Right-sizing models for specific agent tasks — ClawRouter's task-to-tier routing engine with session pinning routes heartbeats to Flash and reasoning to Opus" width="720"></p>
ClawRouter classifies every request before forwarding:
heartbeat status check → SIMPLE → gemini-2.5-flash (~0.04¢ / request)
code review, refactor → COMPLEX → claude-sonnet-4-6 (~5¢ / request)
formal proof, reasoning → REASONING → o3 / claude-opus (~30¢ / request)Tool detection is automatic. When OpenClaw sends a request with tools attached, ClawRouter forces agentic routing tiers — guaranteeing tool-capable models and preventing the silent fallback to models that refuse tool calls.
Session pinning. Once a session selects a model for a task, ClawRouter pins that model for the session lifetime. No mid-task model switching, no consistency issues across a long agent run.
The heartbeat that was burning $248/day on Opus routes to Flash at ~1/500th the cost. Same heartbeat feature, working as designed.
3. Per-Model Rate Limit Isolation — No Cross-Contamination
When a provider returns 429, ClawRouter marks that specific model as rate-limited for 60 seconds (#49834). Other models in the fallback chain are unaffected. If Claude Sonnet gets rate-limited, Gemini Flash and GPT-4o continue working. No cascade.
Before failing over, ClawRouter also retries the rate-limited model once after 200ms. Token-bucket limits often recover within milliseconds — most short-burst 429s resolve on the first retry without ever touching a fallback model.
4. Empty Response Detection — No Silent Failures
ClawRouter inspects every HTTP 200 response body before forwarding it (#49902). Blank responses, repeated-token loops, and single-character outputs trigger model fallback — the same as a 5xx. The agent never sees a degraded response that would cause it to loop or silently fail.
5. Correct Error Classification — No Retry Storms
<p align="center"><img src="assets/blockrun-clawrouter-openclaw-error-classification-retry-storm-prevention.png" alt="Stopping retry storms at the HTTP layer — ClawRouter classifies errors per provider with logic gate classifier and automated mechanical actions" width="720"></p>
ClawRouter classifies errors at the HTTP/body layer before OpenClaw sees them:
401 / 403 → auth_failure → stop retrying, rotate key
402 / billing body → quota_exceeded → stop retrying, surface alert
429 → rate_limited → backoff, try next model
529 / overloaded body → overloaded → short cooldown, fallback model
5xx / 520 → server_error → retry with different model
Z.ai 1311 → billing → stop retrying
Z.ai 1113 → auth → rotate key
MiniMax 520 (api_error)→ server_error → retry with fallbackPer-provider error state is tracked independently. If MiniMax is having a bad hour, Anthropic and OpenAI routes continue working. No cross-contamination, no single provider poisoning the session.
6. Session Memory — Agents That Remember
<p align="center"><img src="assets/blockrun-clawrouter-openclaw-session-memory-journaling-vs-context-compounding.png" alt="Agents that remember without compounding cost — ClawRouter session journaling vs standard OpenClaw context compounding across turns" width="720"></p>
OpenClaw sessions can be long-lived. ClawRouter maintains a session journal — extracting decisions, results, and context from each turn — and injects relevant history when the agent asks questions that reference earlier work.
Less context repeated = fewer tokens = lower cost. Agents that need to recall earlier decisions don't need to carry the entire history in every prompt.
7. x402 Micropayments — Wallet-Based Budget Control
<p align="center"><img src="assets/blockrun-clawrouter-x402-usdc-micropayment-wallet-budget-control.png" alt="Budget limits enforced by physical construction — wallet loaded via Base/Solana, pay per call across 70 models, balance hits zero and the valve shuts cleanly" width="720"></p>
ClawRouter pays for inference via x402 USDC micropayments (Base or Solana). You load a wallet. Each inference call costs exactly what it costs. When the wallet runs low, requests stop cleanly.
There is no monthly invoice. There is no 3am email. There is a wallet balance, and it either has funds or it doesn't. Wallet-based billing means your budget stops the burn — not a monthly invoice that arrives after the damage is done.
maxCostPerRun — a per-session cost ceiling that stops or downgrades requests once a session exceeds a configured threshold (e.g., $0.50). This closes the remaining gap (#3181) where a wallet with sufficient funds can still accumulate within a single run. Two modes: graceful (downgrade to cheaper models) and strict (hard 429 once the cap is hit).
66 models. One wallet. Pay per call.---
OpenClaw + ClawRouter: The Full Picture
<p align="center"><img src="assets/blockrun-clawrouter-vs-openclaw-standalone-comparison-production-safety.png" alt="Architecting for production safety — OpenClaw standalone vs OpenClaw + ClawRouter comparison across cost, context, error handling, and budgeting" width="720"></p>
| Problem | OpenClaw alone | OpenClaw + ClawRouter |
| ------------------------------- | -------------------------------- | --------------------------------------------- |
| Heartbeat cost overrun | No per-run cap | Tier routing → 50–500× cheaper model |
| Large context | Full context every call | 7-layer compression, 15–40% reduction |
| Tool result bloat | Raw output forwarded | Observation compression, up to 97% |
| Rate limit contaminates profile | All models penalized (#49834) | Per-model 60s cooldown, others unaffected |
| Empty / degraded 200 response | Passed through to agent (#49902) | Detected, triggers model fallback |
| Short-burst 429 failover | Immediate failover to next model | 200ms retry first, failover only if needed |
| MiniMax 520 failure | Silent drop / retry storm | Classified as server_error, retried correctly |
| Z.ai 1311 (billing) | Treated as rate_limit, retried | Classified as billing, stopped immediately |
| Mid-task model switch | Model can change mid-session | Session pinning, consistent model per task |
| Monthly billing surprise | Possible | Wallet-based, stops when empty |
| Per-session cost ceiling | None | maxCostPerRun — graceful or strict cap |
| Cost visibility | None | /stats with per-provider error counts |
---
Getting Started
1. Install with smart routing enabled
curl -fsSL https://blockrun.ai/ClawRouter-update | bash
openclaw gateway restartClawRouter auto-injects itself into ~/.openclaw/openclaw.json as a provider on startup. No manual config needed — your existing tools, sessions, and extensions are unchanged.
Load a wallet, choose a model profile (eco / auto / premium / agentic), and run.
---
On Our OpenClaw Contributions
We contribute upstream when we find bugs. The two PRs linked above fix real error classification gaps. Everyone using OpenClaw directly benefits.
ClawRouter exists because proxy-layer cost control, context compression, and agent-aware routing are fundamentally gateway concerns — not framework concerns. OpenClaw can't know that your heartbeat doesn't need Opus. It can't compress tool results it hasn't seen. It can't enforce a wallet ceiling.
That's what ClawRouter is for.
---
_github.com/BlockRunAI/ClawRouter · blockrun.ai · npm install @blockrun/clawrouter_
---
Clawrouter Vs Openrouter Llm Routing Comparison
We Read 100 OpenClaw Issues About OpenRouter. Here's What We Built Instead.
_OpenRouter is the most popular LLM aggregator. It's also the source of the most frustration in OpenClaw's issue tracker._
---
The Data
We searched OpenClaw's GitHub issues for "openrouter" and read every result. 100 issues. Open and closed. Filed by users who ran into the same structural problems over and over:
| Category | Issue Count | Representative Issues |
| ------------------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Broken fallback / failover | ~20 | #22136, #45663, #50389, #49079 |
| Model ID mangling | ~15 | #49379, #50711, #25665, #2373 |
| Authentication / 401 errors | ~8 | #51056, #34830, #26960 |
| Cost / billing opacity | ~6 | #25371, #50738, #38248 |
| Routing opacity | ~5 | #7006, #35842 |
| Missing feature parity | ~10 | #46255, #50485, #30850 |
| Rate limit / key exhaustion | ~4 | #8615, #48729 |
| Model catalog staleness | ~5 | #10687, #30152 |
These aren't edge cases. They're structural consequences of how OpenRouter works: a middleman that adds latency, mangles model IDs, obscures routing decisions, and introduces its own failure modes on top of the providers it aggregates.
---
1. Broken Fallback — The #1 Pain Point
From #45663:
_"Provider returned error from OpenRouter does not trigger model failover."_
From #50389:
_"Rate limit errors surfaced to user instead of auto-failover."_
When OpenRouter returns a 429 or provider error, OpenClaw's failover logic often doesn't recognize it as retriable. The user sees a raw error. The agent stops. ~20 issues document variations of this: HTTP 529 (Anthropic overloaded) not triggering fallback (#49079), invalid model IDs causing 400 instead of failover (#50017), timeouts in cron sessions with no recovery (#49597).
How ClawRouter Solves This
ClawRouter maintains 8-deep fallback chains per routing tier. When a model fails:
1. 200ms retry — short-burst rate limits often recover in milliseconds
2. Next model — if retry fails, move to the next model in the chain
3. Per-model isolation — one provider's failure doesn't poison the others
4. All-failed summary — if every model in the chain fails, you get a structured error listing every attempt and failure reason
[ClawRouter] Trying model 1/6: google/gemini-2.5-flash
[ClawRouter] Model google/gemini-2.5-flash returned 429, retrying in 200ms...
[ClawRouter] Retry failed, trying model 2/6: deepseek/deepseek-chat
[ClawRouter] Success with model: deepseek/deepseek-chatNo silent failures. No raw 429s surfaced to the agent.
---
2. Model ID Mangling — Death by Prefix
From #25665:
_"Model config defaults to openrouter/openrouter/auto (double prefix)."_From #50711:
_"Control UI model picker strips openrouter/ prefix."_OpenRouter uses nested model IDs: openrouter/deepseek/deepseek-v3.2. OpenClaw's UI, Discord bot, and web gateway all handle these differently. Some add the prefix. Some strip it. Some double it. 15 issues trace back to model ID confusion.
How ClawRouter Solves This
ClawRouter uses clean aliases. You say sonnet and get anthropic/claude-sonnet-4-6. You say flash and get google/gemini-2.5-flash. No nested prefixes. No double-prefix bugs.
// resolveModelAlias() handles all normalization
"sonnet" → "anthropic/claude-sonnet-4-6"
"opus" → "anthropic/claude-opus-4-6"
"flash" → "google/gemini-2.5-flash"
"grok" → "xai/grok-4-0314"
"deepseek" → "deepseek/deepseek-chat"One canonical format. No mangling. No UI inconsistency.
---
3. API Key Hell — 401s, Leakage, and Rotation
From #51056:
_"OpenRouter fails with '401 Missing Authentication header' despite valid key."_
From #8615:
_"Feature request: native multi-API-key support with load balancing and fallback."_
API keys are the root cause of an entire category of failures. Keys expire. Keys leak into LLM context (every provider sees every other provider's keys in the serialized request). Keys hit rate limits that can't be load-balanced. 8 issues document auth failures alone.
How ClawRouter Solves This
ClawRouter has no API keys. Zero.
Payment happens via x402 — a cryptographic micropayment protocol. Your agent generates a wallet on first run (BIP-44 derivation, both EVM and Solana). Each request is signed with the wallet's private key. USDC moves per-request.
No keys to leak.
No keys to rotate.
No keys to rate-limit.
No keys to expire.The wallet is the identity. The signature is the authentication. Nothing to configure, nothing to paste into a config file, nothing for the LLM to accidentally serialize.
---
4. Cost and Billing Opacity — Surprise Bills
From #25371:
_"OpenRouter 402 billing error misclassified as 'Context overflow', triggering auto-compaction that drains remaining credits faster."_
From #7006:
_"openrouter/auto doesn't expose which model was actually used or its cost."_When OpenRouter runs out of credits, it returns a 402 that OpenClaw misreads as a context overflow. OpenClaw then auto-compacts the context and retries — on the same empty balance. Each retry charges the compaction cost. Credits drain faster. The agent burns money trying to fix a billing error it doesn't understand.
How ClawRouter Solves This
Per-request cost visibility. Every response includes cost headers:
x-clawrouter-cost: 0.0034
x-clawrouter-savings: 82%
x-clawrouter-model: google/gemini-2.5-flashPer-request USDC payments. No prepaid balance to drain. Each request shows its price before you pay. When the wallet is empty, requests don't fail — they fall back to the free tier (GPT-OSS-120B).
Budget guard. maxCostPerRun caps per-session spending. Two modes: graceful (downgrade to cheaper models) or strict (hard stop). The $248/day heartbeat scenario is structurally impossible.
Usage logging. Every request logs to ~/.openclaw/blockrun/logs/usage-YYYY-MM-DD.jsonl with model, tier, cost, baseline cost, savings, and latency. /stats shows the breakdown.
---
5. Routing Opacity — "Which Model Did I Just Pay For?"
From #7006:
_"No visibility into which model openrouter/auto actually uses."_From #35842:
_"Need explicit Claude Sonnet default instead of auto-routing."_
When you use openrouter/auto, you don't know what model served your request. You can't debug quality regressions. You can't understand cost spikes. You're paying for a black box.
How ClawRouter Solves This
ClawRouter's routing is 100% local, open-source, and transparent.
15-dimension weighted classifier runs locally in <1ms. It scores every request across: token count, code presence, reasoning markers, technical terms, multi-step patterns, question complexity, tool signals, and more.
Debug headers on every response:
x-clawrouter-profile: auto
x-clawrouter-tier: MEDIUM
x-clawrouter-model: moonshot/kimi-k2.5
x-clawrouter-confidence: 0.87
x-clawrouter-reasoning: "Code task with moderate complexity"SSE debug comments in streaming responses show the routing decision inline. You always know which model, why it was selected, and how confident the classifier was.
Four routing profiles give you explicit control:
| Profile | Behavior | Savings |
| --------- | ----------------------- | ------- |
| auto | Balanced quality + cost | 74–100% |
| eco | Cheapest possible | 95–100% |
| premium | Best quality always | 0% |
| free | Free models only | 100% |
No black box. No mystery routing. Full visibility, full control.
---
6. Missing Feature Parity — Images, Tools, Caching
From #46255:
_"Images not passed to OpenRouter models."_
From #47707:
_"Mistral models fail with strict tool call ID requirements."_
OpenRouter doesn't always pass through provider-specific features correctly. Image payloads get dropped. Cache retention headers get ignored. Tool call ID formats cause silent failures with strict providers.
How ClawRouter Solves This
Vision auto-detection. When image_url content parts are detected, ClawRouter automatically filters the fallback chain to vision-capable models only. No images dropped.
Tool calling validation. Every model has a toolCalling flag. When tools are present in the request, ClawRouter forces agentic routing tiers and excludes models without tool support. No silent tool call failures.
Direct provider routing. ClawRouter routes through BlockRun's API directly to providers — not through a second aggregator. One hop, not two. Provider-specific features work because there's no middleman translating them.
---
7. Model Catalog Staleness — "Where's the New Model?"
From #10687:
_"Need fully dynamic model discovery."_
From #30152:
_"Allowlist silently drops models not in catalog."_
When new models launch, OpenRouter's catalog lags. Users configure a model that exists at the provider but isn't in the catalog. The request fails silently or gets rerouted.
How ClawRouter Solves This
ClawRouter maintains a curated catalog of 70 models across 9 providers (including 9 free models), updated with each release. Delisted models have automatic redirect aliases:
// Delisted models redirect automatically
"xai/grok-code-fast-1" → "deepseek/deepseek-chat"
"google/gemini-2.0-pro" → "google/gemini-3.1-pro"No silent drops. No stale catalog. Models are benchmarked for speed, quality, and tool support before inclusion.
---
The Full Comparison
| | OpenRouter | ClawRouter |
| ------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------- |
| Authentication | API key (leak risk) | Wallet signature (no keys) |
| Payment | Prepaid balance (custodial) | Per-request USDC (non-custodial) |
| Routing | Server-side black box | Local 14-dim classifier, <1ms |
| Fallback | Often broken (20+ issues) | 8-deep chains, per-model isolation |
| Model IDs | Nested prefixes, mangling bugs | Clean aliases, single format |
| Cost visibility | None per-request | Headers + JSONL logs + /stats |
| Empty wallet | Request fails | Auto-fallback to free tier |
| Rate limits | Per-key, shared | Per-wallet, independent |
| Vision support | Images sometimes dropped | Auto-detected, vision-only fallback |
| Tool calling | Silent failures with some models | Flag-based filtering, guaranteed support |
| Model catalog | Laggy, silent drops | Curated 70 models, redirect aliases |
| Budget control | Monthly invoice | Per-session cap (maxCostPerRun) |
| Setup | Create account, paste key | Agent generates wallet, auto-configured |
| Average cost | $25/M tokens (Opus direct) | auto-routed = 88% savings |
---
Getting Started
Install
npm install @blockrun/clawrouterStart (auto-configures OpenClaw)
clawrouterCheck your wallet
/wallet
View routing stats
/stats
ClawRouter auto-injects itself into ~/.openclaw/openclaw.json as a provider on startup. Your existing tools, sessions, and extensions are unchanged.
Load a wallet with USDC on Base or Solana, pick a routing profile, and run.
---
_github.com/BlockRunAI/ClawRouter · blockrun.ai · npm install @blockrun/clawrouter_
---
Configuration
Configuration Reference
Complete reference for ClawRouter configuration options.
Table of Contents
- Environment Variables
- Wallet Configuration
- Wallet Backup & Recovery
- Proxy Settings
- Programmatic Usage
- Routing Configuration
- Tier Overrides
- Scoring Weights
- Testing Configuration
---
Environment Variables
| Variable | Default | Description |
| --------------------------- | ------------------------------------- | --------------------------------------------------------------------------------- |
| BLOCKRUN_WALLET_KEY | - | Ethereum private key (hex, 0x-prefixed). Used if no saved wallet exists. |
| BLOCKRUN_PROXY_PORT | 8402 | Port for the local x402 proxy server. |
| CLAWROUTER_SOLANA_RPC_URL | https://api.mainnet-beta.solana.com | Solana RPC endpoint for USDC balance checks. |
| CLAWROUTER_DISABLED | false | Set to true to disable smart routing (pass requests through as-is). |
| CLAWROUTER_WORKER | - | Set to 1 to enable Worker Mode (earn USDC by running health checks). |
| CLAWROUTER_DEBUG_HEADERS | (on) | Set to off/false/0 to suppress the x-clawrouter-* debug response headers. |
| BLOCKRUN_WEB_SEARCH | (auto-enabled) | Set to off to disable BlockRun's Exa web search provider registration. |
BLOCKRUN_WALLET_KEY
The wallet private key for signing x402 micropayments.
export BLOCKRUN_WALLET_KEY=0x...your_private_key...Resolution order:
1. Saved file (~/.openclaw/blockrun/wallet.key) — checked first
2. BLOCKRUN_WALLET_KEY environment variable — used if no saved file
3. Auto-generate — creates new wallet and saves to file
Security Note: The saved file takes priority to prevent accidentally switching wallets and losing access to funded balances.
BLOCKRUN_PROXY_PORT
Configure the proxy to listen on a different port:
export BLOCKRUN_PROXY_PORT=8403
openclaw gateway restartBehavior:
- If a proxy is already running on the configured port, ClawRouter will reuse it instead of failing with EADDRINUSE
- The proxy returns the wallet address of the existing instance, not the configured wallet
- A warning is logged if the existing proxy uses a different wallet
Valid values: 1-65535 (integers only). Invalid values fall back to 8402.
BLOCKRUN_WEB_SEARCH
Disable BlockRun's bundled Exa web search provider. By default ClawRouter calls registerWebSearchProvider(blockrun-exa) and lets OpenClaw auto-detect it as the active search provider; if you'd rather use a different provider (or no web search at all), turn it off.
Two equivalent opt-out paths:
Path 1: env var (CI / one-off runs)
export BLOCKRUN_WEB_SEARCH=off
openclaw gateway restart// Path 2: persistent — edit ~/.openclaw/openclaw.json
{
"tools": {
"web": {
"search": {
"enabled": false,
},
},
},
}When disabled:
- ClawRouter skips registerWebSearchProvider() so blockrun-exa never gets wired up.
- injectModelsConfig leaves your tools.web.search.enabled = false alone instead of flipping it back to true on every plugin load.
- The legacy tools.web.search.provider = "blockrun-exa" migration still runs (that's correctness — it's an invalid value rejected by OpenClaw 2026.5.2+ validators, regardless of whether you want search enabled).
CLAWROUTER_DEBUG_HEADERS
Non-streaming responses carry routing debug headers by default
(x-clawrouter-profile, x-clawrouter-tier, x-clawrouter-model,x-clawrouter-confidence, x-clawrouter-reasoning). To turn them off
globally:
export CLAWROUTER_DEBUG_HEADERS=off # also accepts false / 0
openclaw gateway restartPer-request alternative: send x-clawrouter-debug: false on the request.
Since v0.12.208 the reasoning value is percent-encoded, so non-ASCII routing
signals (Cyrillic/CJK keyword matches) can no longer produce an invalid
header. On v0.12.207 and earlier, non-English prompts could crash response
delivery with Invalid character in header content ["x-clawrouter-reasoning"]— upgrade rather than relying on this switch.
CLAWROUTER_SOLANA_RPC_URL
Override the Solana RPC endpoint used for USDC balance checks (Solana chain only):
export CLAWROUTER_SOLANA_RPC_URL=https://your-rpc-provider.com
openclaw gateway restartPublic RPC may rate-limit on heavy usage. Use a dedicated RPC for production.
---
Wallet Configuration
ClawRouter supports two payment chains: Base (EVM) and Solana. Both are USDC only — no SOL or ETH accepted for payments.
Check Active Wallet
View wallet address + balance (both chains shown)
/walletOr via HTTP
curl http://localhost:8402/health | jq .wallet
curl "http://localhost:8402/health?full=true" | jqResponse (dual-chain):
{
"status": "ok",
"wallet": "0x1234...abcd",
"solanaWallet": "7Xkr...xyz",
"paymentChain": "base",
"balance": "$2.50",
"isLow": false,
"isEmpty": false
}Switch Payment Chain
/wallet solana # Switch to Solana USDC payments
/wallet base # Switch back to Base (EVM) USDC paymentsOr use the /chain command:
/chain solana
/chain baseThe selected chain is persisted across gateway restarts.
Switch Wallets
To use a different wallet:
1. Remove saved wallet
rm ~/.openclaw/blockrun/wallet.key2. Set new wallet key
export BLOCKRUN_WALLET_KEY=0x...3. Restart
openclaw gateway restartBackup Wallet
Backup wallet key
cp ~/.openclaw/blockrun/wallet.key ~/backup/View wallet address from key file
cat ~/.openclaw/blockrun/wallet.keyWallet Backup & Recovery
ClawRouter generates a BIP-39 mnemonic on first install — stored at ~/.openclaw/blockrun/wallet.key. This single mnemonic derives both your EVM (Base) and Solana addresses. Back up this file before terminating any VPS or machine!
#### Using the /wallet Command
Check wallet status (address, balance, chain, file location)
/walletExport mnemonic + private keys for backup
/wallet exportThe /wallet export command displays your mnemonic and keys so you can copy them before terminating a machine.
#### Manual Backup
Option 1: Copy the key file
cp ~/.openclaw/blockrun/wallet.key ~/backup-wallet.keyOption 2: View mnemonic
cat ~/.openclaw/blockrun/wallet.key#### Restore on a New Machine
Option 1: Recover from mnemonic
npx @blockrun/clawrouter wallet recover "word1 word2 ... word12"Option 2: Set environment variable (before installing ClawRouter)
export BLOCKRUN_WALLET_KEY=0x...your_private_key...
openclaw plugins install @blockrun/clawrouterOption 3: Create the key file directly
mkdir -p ~/.openclaw/blockrun
echo "your twelve word mnemonic here" > ~/.openclaw/blockrun/wallet.key
chmod 600 ~/.openclaw/blockrun/wallet.key
openclaw plugins install @blockrun/clawrouterImportant: If a saved wallet file exists, it takes priority over the environment variable. To use a different wallet, delete the existing file first.
#### Lost Key Recovery
If you lose your wallet key, there is no way to recover it. The wallet is self-custodial, meaning only you have the private key. We do not store keys or have any way to restore access.
Prevention tips:
- Run /wallet export before terminating any VPS
- Keep a secure backup of ~/.openclaw/blockrun/wallet.key
- For production use, consider using a hardware wallet or key management system
---
Proxy Settings
Proxy Reuse (v0.4.1+)
ClawRouter automatically detects and reuses an existing proxy on startup:
Session 1: startProxy() → starts server on :8402
Session 2: startProxy() → detects existing, reuses handleBehavior:
- Health check is performed on the configured port before starting
- If responsive, returns a handle that uses the existing proxy
- close() on reused handles is a no-op (doesn't stop the original server)
- Warning logged if existing proxy uses a different wallet
Programmatic Usage
Use ClawRouter without OpenClaw:
import { startProxy } from "@blockrun/clawrouter";const proxy = await startProxy({
walletKey: process.env.BLOCKRUN_WALLET_KEY!,
onReady: (port) => console.log(Proxy on port ${port}),
onRouted: (d) => console.log(${d.model} saved ${(d.savings * 100).toFixed(0)}%),
});
// Any OpenAI-compatible client works
const res = await fetch(${proxy.baseUrl}/v1/chat/completions, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "blockrun/auto",
messages: [{ role: "user", content: "What is 2+2?" }],
}),
});
await proxy.close();
Or use the router directly (no proxy, no payments):
import { route, DEFAULT_ROUTING_CONFIG, BLOCKRUN_MODELS } from "@blockrun/clawrouter";// Build pricing map
const modelPricing = new Map();
for (const m of BLOCKRUN_MODELS) {
modelPricing.set(m.id, { inputPrice: m.inputPrice, outputPrice: m.outputPrice });
}
const decision = route("Prove sqrt(2) is irrational", undefined, 4096, {
config: DEFAULT_ROUTING_CONFIG,
modelPricing,
});
console.log(decision);
// {
// model: "deepseek/deepseek-reasoner",
// tier: "REASONING",
// confidence: 0.97,
// method: "rules",
// savings: 0.994,
// costEstimate: 0.002,
// }
Programmatic Options
All options for startProxy():
import { startProxy } from "@blockrun/clawrouter";const proxy = await startProxy({
walletKey: "0x...",
// Port configuration
port: 8402, // Default: 8402 or BLOCKRUN_PROXY_PORT
// Timeouts
requestTimeoutMs: 180000, // 3 minutes (covers on-chain tx + LLM response)
// API base (for testing)
apiBase: "https://blockrun.ai/api",
// Callbacks
onReady: (port) => console.log(Proxy ready on ${port}),
onError: (error) => console.error(error),
onRouted: (decision) => console.log(decision.model, decision.tier),
onLowBalance: (info) => console.warn(Low balance: ${info.balanceUSD}),
onInsufficientFunds: (info) => console.error(Need ${info.requiredUSD}),
onPayment: (info) => console.log(Paid ${info.amount} for ${info.model}),
// Routing config overrides
routingConfig: {
// See Routing Configuration below
},
});
---
Routing Configuration
Via openclaw.yaml
/ Detailed source-code truncated for AI context efficiency. /---
Tier Overrides
Default Tier Mappings
| Tier | Primary Model | Fallback Chain |
| --------- | ----------------------------- | ----------------------------------------------- |
| SIMPLE | google/gemini-2.5-flash | deepseek/deepseek-chat |
| MEDIUM | deepseek/deepseek-chat | openai/gpt-4o-mini, google/gemini-2.5-flash |
| COMPLEX | anthropic/claude-sonnet-4.6 | openai/gpt-4o, google/gemini-2.5-pro |
| REASONING | deepseek/deepseek-reasoner | openai/o3-mini, anthropic/claude-sonnet-4.6 |
Fallback Chain
When the primary model fails (rate limits, billing errors, provider outages), ClawRouter tries the next model in the fallback chain:
Request → gemini-2.5-flash (rate limited)
→ deepseek-chat (billing error)
→ gpt-4o-mini (success)Max fallback attempts: 3 models per request.
Custom Tier Configuration
routing:
tiers:
COMPLEX:
primary: "openai/gpt-4o" # Use GPT-4o instead of Claude
fallback:
- "anthropic/claude-sonnet-4.6"
- "google/gemini-2.5-pro"---
Scoring Weights
The 15-dimension weighted scorer determines query complexity:
| Dimension | Weight | Detection |
| --------------------- | ------ | ---------------------------------------- |
| reasoningMarkers | 0.18 | "prove", "theorem", "step by step" |
| codePresence | 0.15 | "function", "async", "import", "``" |multiStepPatterns
| | 0.12 | "first...then", "step 1", numbered lists |agenticTask
| | 0.10 | "run", "test", "fix", "deploy", "edit" |technicalTerms
| | 0.10 | "algorithm", "kubernetes", "distributed" |tokenCount
| | 0.08 | short (<50) vs long (>500) |creativeMarkers
| | 0.05 | "story", "poem", "brainstorm" |questionComplexity
| | 0.05 | Multiple question marks |constraintCount
| | 0.04 | "at most", "O(n)", "maximum" |imperativeVerbs
| | 0.03 | "build", "create", "implement" |outputFormat
| | 0.03 | "json", "yaml", "schema" |simpleIndicators
| | 0.02 | "what is", "define", "translate" |domainSpecificity
| | 0.02 | "quantum", "fpga", "genomics" |referenceComplexity
| | 0.02 | "the docs", "the api", "above" |negationComplexity
| | 0.01 | "don't", "avoid", "without" |
Custom Keywords
routing:
scoring:
# Add domain-specific reasoning triggers
reasoningKeywords:
- "prove"
- "theorem"
- "formal verification"
- "type theory" # Custom # Add framework-specific code triggers
codeKeywords:
- "function"
- "useEffect" # React-specific
- "prisma" # ORM-specific
---
Advanced: Confidence Calibration
The classifier uses sigmoid calibration to convert raw scores to confidence values:
confidence = 1 / (1 + exp(-k * (score - midpoint)))Parameters:
- k = 8 — steepness of the sigmoid curvemidpoint = 0.5
- — score at which confidence = 50%
Override Thresholds
routing:
classifier:
# Require higher confidence for tier assignment
confidenceThreshold: 0.8 # Default: 0.7 # Force REASONING tier at lower confidence
reasoningConfidence: 0.90 # Default: 0.97
---
Testing Configuration
Dry Run (No Payments)
For testing routing without spending USDC:
import { route, DEFAULT_ROUTING_CONFIG, BLOCKRUN_MODELS } from "@blockrun/clawrouter";// Build pricing map
const modelPricing = new Map();
for (const m of BLOCKRUN_MODELS) {
modelPricing.set(m.id, { inputPrice: m.inputPrice, outputPrice: m.outputPrice });
}
// Test routing decisions locally
const decision = route("Prove sqrt(2) is irrational", undefined, 4096, {
config: DEFAULT_ROUTING_CONFIG,
modelPricing,
});
console.log(decision);
// { model: "deepseek/deepseek-reasoner", tier: "REASONING", ... }
Run Tests
Router tests (no wallet needed)
npx tsx test/e2e.tsProxy end-to-end smoke (mock upstream, no wallet needed)
npm run test:e2eProxy reuse tests
npx tsx test/proxy-reuse.tsLive e2e with payments (requires funded wallet)
BLOCKRUN_WALLET_KEY=0x... npm run test:e2eOptional slower/costlier live coverage
CLAWROUTER_E2E_FULL=1 BLOCKRUN_WALLET_KEY=0x... npm run test:e2e
RUN_IMAGE_TEST=1 BLOCKRUN_WALLET_KEY=0x... npm run test:e2e
RUN_MUSIC_TEST=1 BLOCKRUN_WALLET_KEY=0x... npm run test:e2e---
Features
Advanced Features
ClawRouter v0.5+ includes intelligent routing features that work automatically.
Table of Contents
- Response Cache
- Agentic Auto-Detection
- Tool Detection
- Context-Length-Aware Routing
- Model Aliases
- Free Tier Fallback
- Session Persistence
- Cost Tracking with /stats
---
Response Cache
ClawRouter includes LLM response caching inspired by LiteLLM's caching system. Identical requests return cached responses, saving both cost and latency.
How it works:
Request: "What is 2+2?"
First call: → API ($0.001) → Cache response
Second call: → Cache HIT → Return instantly ($0)Features:
| Feature | Default | Description |
| ------------ | ----------- | -------------------------- |
| TTL | 10 minutes | Responses expire after TTL |
| Max size | 200 entries | LRU eviction when full |
| Item limit | 1MB | Large responses skipped |
| Auto-enabled | Yes | No config needed |
Cache key generation:
The cache key is a SHA-256 hash of the request body (model + messages + params), with normalization:
- Message timestamps stripped (OpenClaw injects [Mon 2024-01-15 10:30 UTC])
- Keys sorted for consistent hashing
- Stream mode, user, and request_id fields excluded
Bypass cache:
// Via header
fetch("/v1/chat/completions", {
headers: { "Cache-Control": "no-cache" }
})// Via body
{
"model": "blockrun/auto",
"cache": false, // or "no_cache": true
"messages": [...]
}
Check cache stats:
curl http://localhost:8402/cacheResponse:
{
"size": 42,
"maxSize": 200,
"hits": 156,
"misses": 89,
"evictions": 3,
"hitRate": "63.7%"
}Configuration:
Response caching is enabled by default with sensible defaults. For advanced tuning, the cache can be configured programmatically:
import { ResponseCache } from "@blockrun/clawrouter";const cache = new ResponseCache({
maxSize: 500, // Max cached responses
defaultTTL: 300, // 5 minutes
maxItemSize: 2_097_152, // 2MB max per item
enabled: true,
});
---
Agentic Auto-Detection
ClawRouter automatically detects multi-step agentic tasks and routes to models optimized for autonomous execution:
"what is 2+2" → gemini-flash (standard)
"build the project then run tests" → kimi-k2.5 (auto-agentic)
"fix the bug and make sure it works" → kimi-k2.5 (auto-agentic)How it works:
- Detects agentic keywords: file ops ("read", "edit"), execution ("run", "test", "deploy"), iteration ("fix", "debug", "verify")
- Threshold: 2+ signals triggers auto-switch to agentic tiers
- No config needed — works automatically
Agentic tier models (optimized for multi-step autonomy):
| Tier | Agentic Model | Why |
| --------- | ----------------- | ------------------------------ |
| SIMPLE | claude-haiku-4.5 | Fast + reliable tool use |
| MEDIUM | kimi-k2.5 | 200+ tool chains, 76% cheaper |
| COMPLEX | claude-sonnet-4.6 | Best balance for complex tasks |
| REASONING | kimi-k2.5 | Extended reasoning + execution |
Force Agentic Mode
You can also force agentic mode via config:
openclaw.yaml
plugins:
- id: "@blockrun/clawrouter"
config:
routing:
overrides:
agenticMode: true # Always use agentic tiers---
Tool Detection
When your request includes a tools array (function calling), ClawRouter automatically switches to agentic tiers:
// Request with tools → auto-agentic mode
{
model: "blockrun/auto",
messages: [{ role: "user", content: "Check the weather" }],
tools: [{ type: "function", function: { name: "get_weather", ... } }]
}
// → Routes to claude-haiku-4.5 (excellent tool use)
// → Instead of gemini-flash (may produce malformed tool calls)Why this matters: Some models (like deepseek-reasoner) are optimized for chain-of-thought reasoning but can generate malformed tool calls. Tool detection ensures requests with functions go to models proven to handle tool use correctly.
---
Context-Length-Aware Routing
ClawRouter automatically filters out models that can't handle your context size:
150K token request:
Full chain: [grok-4-fast (131K), deepseek (128K), kimi (262K), gemini (1M)]
Filtered: [kimi (262K), gemini (1M)]
→ Skips models that would fail with "context too long" errorsThis prevents wasted API calls and faster fallback to capable models.
---
Model Aliases
Use short aliases instead of full model paths:
/model free # gpt-oss-120b (FREE!)
/model br-sonnet # anthropic/claude-sonnet-4.6
/model br-opus # anthropic/claude-opus-4
/model br-haiku # anthropic/claude-haiku-4.5
/model gpt # openai/gpt-4o
/model gpt5 # openai/gpt-5.2
/model deepseek # deepseek/deepseek-chat
/model reasoner # deepseek/deepseek-reasoner
/model kimi # nvidia/kimi-k2.5 (reliable); /model kimi-k2.6 for Moonshot flagship
/model gemini # google/gemini-2.5-pro
/model flash # google/gemini-2.5-flash
/model grok # xai/grok-3
/model grok-fast # xai/grok-4-fast-reasoningAll aliases work with /model blockrun/xxx or just /model xxx.
---
Free Tier Fallback
When your wallet balance hits $0, ClawRouter automatically falls back to the free model (gpt-oss-120b):
Wallet: $0.00
Request: "Help me write a function"
→ Routes to gpt-oss-120b (FREE)
→ No "insufficient funds" error
→ Keep building while you top upYou'll never get blocked by an empty wallet — the free tier keeps you running.
---
Session Persistence
For multi-turn conversations, ClawRouter pins the model to prevent mid-task switching:
Turn 1: "Build a React component" → claude-sonnet-4.6
Turn 2: "Add dark mode support" → claude-sonnet-4.6 (pinned)
Turn 3: "Now add tests" → claude-sonnet-4.6 (pinned)Sessions are identified by conversation ID and persist for 1 hour of inactivity.
---
Cost Tracking with /stats
Track your savings in real-time:
In any OpenClaw conversation
/statsOutput:
+============================================================+
| ClawRouter Usage Statistics |
+============================================================+
| Period: last 7 days |
| Total Requests: 442 |
| Total Cost: $1.73 |
| Baseline Cost (Opus): $20.13 |
| Total Saved: $18.40 (91.4%) |
+------------------------------------------------------------+
| Routing by Tier: |
| SIMPLE =========== 55.0% (243) |
| MEDIUM ====== 30.8% (136) |
| COMPLEX = 7.2% (32) |
| REASONING = 7.0% (31) |
+============================================================+Stats are stored locally at ~/.openclaw/blockrun/logs/ and aggregated on demand.
---
Image Generation
Image Generation & Editing
Generate and edit images via BlockRun's image API with x402 micropayments — no API keys, pay per image.
Table of Contents
- Quick Start
- Models & Pricing
- API Reference
- POST /v1/images/generations
- POST /v1/images/image2image
- Code Examples
- Image Generation
- Image Editing (img2img)
- In-Chat Commands
- Notes
---
Quick Start
ClawRouter runs a local proxy on port 8402 that handles x402 payments automatically. Point any OpenAI-compatible client at it:
curl -X POST http://localhost:8402/v1/images/generations \
-H "Content-Type: application/json" \
-d '{
"model": "google/nano-banana",
"prompt": "a golden retriever surfing on a wave",
"size": "1024x1024",
"n": 1
}'Response:
{
"created": 1741460000,
"data": [
{
"url": "https://files.catbox.moe/abc123.png"
}
]
}The returned URL is a publicly hosted image, ready to use in Telegram, Discord, or any client.
---
Models & Pricing
| Model ID | Shorthand | Price | Max Size | Provider |
| --------------------------- | ------------- | ----------- | --------- | ------------------- |
| google/nano-banana | nano-banana | $0.05/image | 1024×1024 | Google Gemini Flash |google/nano-banana-pro
| | banana-pro | $0.10/image | 4096×4096 | Google Gemini Pro |openai/dall-e-3
| | dall-e-3 | $0.04/image | 1792×1024 | OpenAI DALL-E 3 |openai/gpt-image-1
| | gpt-image | $0.02/image | 1536×1024 | OpenAI GPT Image |black-forest/flux-1.1-pro
| | flux | $0.04/image | 1024×1024 | Black Forest Labs |
Default model: google/nano-banana.
---
API Reference
POST /v1/images/generations
OpenAI-compatible endpoint. Route via ClawRouter proxy (http://localhost:8402) for automatic x402 payment handling.
Request body:
| Field | Type | Required | Description |
| -------- | -------- | -------- | ---------------------------------------------- |
| model | string | Yes | Model ID (see table above) |prompt
| | string | Yes | Text description of the image to generate |size
| | string | No | Image dimensions, e.g. "1024x1024" (default) |n
| | number | No | Number of images (default: 1) |
Response:
{
created: number; // Unix timestamp
data: Array<{
url: string; // Publicly hosted image URL
revised_prompt?: string; // Model's rewritten prompt (dall-e-3 only)
}>;
}POST /v1/images/image2image
Edit an existing image using AI. Route via ClawRouter proxy (http://localhost:8402) for automatic x402 payment handling.
Request body:
| Field | Type | Required | Description |
| -------- | -------- | -------- | ----------------------------------------------------------- |
| model | string | No | Model ID (default: openai/gpt-image-1) |prompt
| | string | Yes | Text description of the edit to apply |image
| | string | Yes | Source image — see Image input formats below |mask
| | string | No | Mask image (white = area to edit) — same formats as image |size
| | string | No | Output dimensions, e.g. "1024x1024" (default) |
Image input formats — the image and mask fields accept any of:
| Format | Example | Description |
| ------------------ | ---------------------------------- | ---------------------------------------------- |
| Local file path | "/Users/me/photo.png" | Absolute path — ClawRouter reads the file |"~/photo.png"
| Home-relative path | | Expands ~ to home directory |"https://example.com/photo.png"
| HTTP/HTTPS URL | | ClawRouter downloads the image automatically |"data:image/png;base64,iVBOR..."
| Base64 data URI | | Passed through directly (no conversion needed) |
Supported image formats: PNG, JPG/JPEG, WebP.
Response:
{
created: number; // Unix timestamp
data: Array<{
url: string; // Locally cached image URL (http://localhost:8402/images/...)
revised_prompt?: string; // Model's rewritten prompt
}>;
}---
Code Examples
Image Generation Examples {#image-generation-examples}
curl
Default model (nano-banana, $0.05)
curl -X POST http://localhost:8402/v1/images/generations \
-H "Content-Type: application/json" \
-d '{
"model": "google/nano-banana",
"prompt": "a futuristic city at sunset, cyberpunk style",
"size": "1024x1024",
"n": 1
}'DALL-E 3 with landscape size ($0.04)
curl -X POST http://localhost:8402/v1/images/generations \
-H "Content-Type: application/json" \
-d '{
"model": "openai/dall-e-3",
"prompt": "a serene Japanese garden in autumn",
"size": "1792x1024",
"n": 1
}'TypeScript / Node.js
const response = await fetch("http://localhost:8402/v1/images/generations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "google/nano-banana",
prompt: "a golden retriever surfing on a wave",
size: "1024x1024",
n: 1,
}),
});const result = (await response.json()) as {
created: number;
data: Array<{ url: string; revised_prompt?: string }>;
};
const imageUrl = result.data[0].url;
console.log(imageUrl); // https://files.catbox.moe/xxx.png
Python
import requestsresponse = requests.post(
"http://localhost:8402/v1/images/generations",
json={
"model": "google/nano-banana",
"prompt": "a golden retriever surfing on a wave",
"size": "1024x1024",
"n": 1,
}
)
result = response.json()
image_url = result["data"][0]["url"]
print(image_url)
OpenAI SDK (drop-in)
import OpenAI from "openai";const client = new OpenAI({
apiKey: "blockrun", // any non-empty string
baseURL: "http://localhost:8402/v1",
});
const response = await client.images.generate({
model: "google/nano-banana",
prompt: "a golden retriever surfing on a wave",
size: "1024x1024",
n: 1,
});
console.log(response.data[0].url);
startProxy (programmatic)
If you're using ClawRouter as a library:
import { startProxy } from "@blockrun/clawrouter";${proxy.baseUrl}/v1/images/generationsconst proxy = await startProxy({ walletKey: process.env.BLOCKRUN_WALLET_KEY! });
const response = await fetch(
, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "openai/dall-e-3",
prompt: "a serene Japanese garden in autumn",
size: "1792x1024",
n: 1,
}),
});const { data } = await response.json();
console.log(data[0].url);await proxy.close();
Image Editing Examples {#image-editing-examples}
curl
Using a local file path (simplest)
curl -X POST http://localhost:8402/v1/images/image2image \
-H "Content-Type: application/json" \
-d '{
"prompt": "add sunglasses to the person",
"image": "~/photo.png"
}'Using an image URL
curl -X POST http://localhost:8402/v1/images/image2image \
-H "Content-Type: application/json" \
-d '{
"prompt": "change the background to a sunset beach",
"image": "https://example.com/photo.png"
}'With a mask (inpainting — white = area to edit)
curl -X POST http://localhost:8402/v1/images/image2image \
-H "Content-Type: application/json" \
-d '{
"prompt": "replace the background with a starry sky",
"image": "~/photo.png",
"mask": "~/mask.png"
}'With explicit model, size, and base64 data URI
curl -X POST http://localhost:8402/v1/images/image2image \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-image-1",
"prompt": "add a crown",
"image": "data:image/png;base64,iVBOR...",
"size": "1536x1024"
}'TypeScript / Node.js
// ClawRouter reads the file for you — no base64 encoding needed
const response = await fetch("http://localhost:8402/v1/images/image2image", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
prompt: "change the background to a starry sky",
image: "/Users/me/photo.png", // or "~/photo.png" or an HTTPS URL
}),
});const result = (await response.json()) as {
created: number;
data: Array<{ url: string; revised_prompt?: string }>;
};
console.log(result.data[0].url); // http://localhost:8402/images/xxx.png
Python
import requestsresponse = requests.post(
"http://localhost:8402/v1/images/image2image",
json={
"prompt": "add a hat to the person",
"image": "~/photo.png", # or an absolute path or HTTPS URL
},
)
result = response.json()
print(result["data"][0]["url"])
---
In-Chat Commands
When using ClawRouter with OpenClaw, generate and edit images directly from any conversation:
/cr-imagegen — Generate images
/cr-imagegen a dog dancing on the beach
/cr-imagegen --model dall-e-3 a futuristic city at sunset
/cr-imagegen --model banana-pro --size 2048x2048 mountain landscapeRegistered slash command: /cr-imagegen. Thecr-prefix avoids colliding with Telegram channels that reserve/imagegenfor their own image-gen bots. Typing the legacy/imagegenin chat still works for backward compatibility.
| Flag | Default | Description |
| --------- | ------------- | --------------------- |
| --model | nano-banana | Model shorthand or ID |--size
| | 1024x1024 | Image dimensions |
/img2img — Edit images
/img2img --image ~/photo.png change the background to a starry sky
/img2img --image ./cat.jpg --mask ./mask.png remove the background
/img2img --image /tmp/portrait.png --size 1536x1024 add a hat| Flag | Default | Description |
| --------- | ------------- | ------------------------------------- |
| --image | _(required)_ | Local image file path (supports ~/) |--mask
| | _(none)_ | Mask image (white = area to edit) |--model
| | gpt-image-1 | Model to use |--size
| | 1024x1024 | Output size |
Model shorthands
| Shorthand | Full ID |
| ------------- | --------------------------- |
| nano-banana | google/nano-banana |banana-pro
| | google/nano-banana-pro |dall-e-3
| | openai/dall-e-3 |gpt-image
| | openai/gpt-image-1 |flux
| | black-forest/flux-1.1-pro |
---
Notes
- Local image caching — All images (generated and edited) are cached locally at ~/.openclaw/blockrun/images/ and served via http://localhost:8402/images/. Both base64 data URIs and HTTP URLs from upstream are downloaded and replaced with localhost URLs.flux
- Payment — Each image costs the listed price in USDC, deducted from your wallet via x402. Make sure your wallet is funded before generating or editing.
- No DALL-E content policy bypass — DALL-E 3 and GPT Image 1 still apply OpenAI's content policy. Use or nano-banana for more flexibility with generation.--size
- Size limits — Requesting a size larger than the model's max will return an error. Check the table above before setting ./v1/images/image2image
- Image editing — The endpoint currently supports openai/gpt-image-1 (default). The image and mask fields accept local file paths (~/photo.png, /abs/path.png), HTTP/HTTPS URLs, or base64 data URIs. ClawRouter handles file reading and URL downloading automatically. Supported formats: PNG, JPG/JPEG, WebP.
---
Llm Router Benchmark 46 Models Sub 1ms Routing
We Benchmarked 39 AI Models Through Our Payment Gateway. Here's What We Found.
_March 16, 2026 | BlockRun Engineering_
Numbers in this post are a snapshot from the date above. They record what was
measured then and are deliberately not updated — rewriting them would misrepresent
the benchmark. For current figures see
blockrun.ai/brand/numbers.json.
Last week we ran every model on BlockRun through a real-world latency benchmark — 39 models, same prompts, same payment pipeline, same hardware. No cherry-picked results. No synthetic lab conditions. Just cold, hard numbers from production infrastructure.
The results changed how we route requests.
Why We Did This
BlockRun is an x402 micropayment gateway that sits between your AI agent and 39+ LLM providers. Every request flows through our payment verification layer before hitting the model API. That means our latency numbers include everything a real user experiences: payment auth, provider API call, and response delivery.
Most benchmarks measure model speed in isolation. We wanted to measure what users actually feel.
The Leaderboard
We sent 2 coding prompts per model (256 max tokens, non-streaming) and measured end-to-end response time.
Speed Rankings (End-to-End Latency Through BlockRun)
| # | Model | Latency | Tok/s | $/1M in | $/1M out |
| --- | ------------------------------- | ------- | ----- | ------- | -------- |
| 1 | xai/grok-4-fast-non-reasoning | 1,143ms | 224 | $0.20 | $0.50 |
| 2 | xai/grok-3-mini | 1,202ms | 215 | $0.30 | $0.50 |
| 3 | google/gemini-2.5-flash | 1,238ms | 208 | $0.15 | $0.60 |
| 4 | xai/grok-3 | 1,244ms | 207 | $3.00 | $15.00 |
| 5 | xai/grok-4-1-fast-non-reasoning | 1,244ms | 206 | $0.20 | $0.50 |
| 6 | nvidia/gpt-oss-120b | 1,252ms | 204 | FREE | FREE |
| 7 | minimax/minimax-m2.5 | 1,278ms | 202 | $0.30 | $1.10 |
| 8 | google/gemini-2.5-pro | 1,294ms | 198 | $1.25 | $10.00 |
| 9 | xai/grok-4-fast-reasoning | 1,298ms | 198 | $0.20 | $0.50 |
| 10 | xai/grok-4-0709 | 1,348ms | 190 | $0.20 | $1.50 |
| 11 | google/gemini-3-pro-preview | 1,352ms | 190 | $1.25 | $10.00 |
| 12 | google/gemini-2.5-flash-lite | 1,353ms | 193 | $0.10 | $0.40 |
| 13 | google/gemini-3-flash-preview | 1,398ms | 183 | $0.15 | $0.60 |
| 14 | deepseek/deepseek-chat | 1,431ms | 179 | $0.27 | $1.10 |
| 15 | deepseek/deepseek-reasoner | 1,454ms | 183 | $0.55 | $2.19 |
| 16 | xai/grok-4-1-fast-reasoning | 1,454ms | 176 | $0.20 | $0.50 |
| 17 | google/gemini-3.1-pro | 1,609ms | 167 | $1.25 | $10.00 |
| 18 | moonshot/kimi-k2.5 | 1,646ms | 156 | $0.60 | $3.00 |
| 19 | anthropic/claude-sonnet-4.6 | 2,110ms | 121 | $3.00 | $15.00 |
| 20 | anthropic/claude-opus-4.6 | 2,139ms | 120 | $15.00 | $75.00 |
| 21 | openai/o3-mini | 2,260ms | 114 | $1.10 | $4.40 |
| 22 | openai/gpt-5-mini | 2,264ms | 114 | $1.10 | $4.40 |
| 23 | anthropic/claude-haiku-4.5 | 2,305ms | 141 | $0.80 | $4.00 |
| 24 | openai/o4-mini | 2,328ms | 111 | $1.10 | $4.40 |
| 25 | openai/gpt-4.1-mini | 2,340ms | 109 | $0.40 | $1.60 |
| 26 | openai/o1 | 2,562ms | 100 | $15.00 | $60.00 |
| 27 | openai/gpt-4.1-nano | 2,640ms | 97 | $0.10 | $0.40 |
| 28 | openai/o1-mini | 2,746ms | 93 | $1.10 | $4.40 |
| 29 | openai/gpt-4o-mini | 2,764ms | 93 | $0.15 | $0.60 |
| 30 | openai/o3 | 2,862ms | 90 | $2.00 | $8.00 |
| 31 | openai/gpt-5-nano | 3,187ms | 81 | $0.50 | $2.00 |
| 32 | openai/gpt-5.2-pro | 3,546ms | 73 | $2.50 | $10.00 |
| 33 | openai/gpt-4o | 5,378ms | 48 | $2.50 | $10.00 |
| 34 | openai/gpt-4.1 | 5,477ms | 47 | $2.00 | $8.00 |
| 35 | openai/gpt-5.3 | 5,910ms | 43 | $2.50 | $10.00 |
| 36 | openai/gpt-5.4 | 6,213ms | 41 | $2.50 | $15.00 |
| 37 | openai/gpt-5.2 | 6,507ms | 40 | $2.50 | $10.00 |
| 38 | openai/gpt-5.4-pro | 6,671ms | 40 | $2.50 | $15.00 |
| 39 | openai/gpt-5.3-codex | 7,935ms | 32 | $2.50 | $10.00 |
Three Things That Surprised Us
1. xAI Grok is Absurdly Fast
Grok 4 Fast clocked in at 1,143ms end-to-end. That's the full round trip: payment verification, API call, response. For context, OpenAI's GPT-5.4 took 6,213ms for the same request — nearly 6x slower.
The entire xAI lineup dominated the top of the leaderboard. Five of the top 10 fastest models are from xAI. At $0.20 per million input tokens, they're also among the cheapest.
2. Google Gemini Owns the Efficiency Frontier
Gemini 2.5 Flash delivered 1,238ms latency at $0.15/$0.60 per million tokens. For simple tasks, it's the clear winner on cost-per-quality.
But here's what's more impressive: Gemini 2.5 Pro came in at 1,294ms — barely slower than Flash — while scoring significantly higher on intelligence benchmarks. Google's infrastructure advantage is showing.
Six Google models landed in the top 13. No other provider came close to that kind of lineup depth.
3. OpenAI Flagship Models Are Surprisingly Slow
Every OpenAI model with "5.x" in the name landed in the bottom third of the leaderboard. GPT-5.3 Codex was dead last at 7,935ms. Even GPT-4o, a model from 2024, took over 5 seconds.
OpenAI's "mini" and "nano" variants are faster (2.2-3.2s range) but still 2x slower than the fastest competitors. The speed gap is real and consistent across their entire lineup.
Speed vs. Intelligence: The Tradeoff That Broke Our Routing
We cross-referenced our latency data with quality scores from Artificial Analysis (Intelligence Index v4.0):
| Model | BlockRun Latency | Intelligence Index | Price Tier |
| ---------------------- | ---------------- | ------------------ | ----------- |
| Gemini 3.1 Pro | 1,609ms | 57 | $1.25/$10 |
| GPT-5.4 | 6,213ms | 57 | $2.50/$15 |
| GPT-5.3 Codex | 7,935ms | 54 | $2.50/$10 |
| Claude Opus 4.6 | 2,139ms | 53 | $15/$75 |
| Claude Sonnet 4.6 | 2,110ms | 52 | $3/$15 |
| Kimi K2.5 | 1,646ms | 47 | $0.60/$3 |
| Gemini 3 Flash Preview | 1,398ms | 46 | $0.15/$0.60 |
| Grok 4 | 1,348ms | 41 | $0.20/$1.50 |
| Grok 4.1 Fast | 1,244ms | 41 | $0.20/$0.50 |
| DeepSeek V3 | 1,431ms | 32 | $0.27/$1.10 |
| Grok 3 | 1,244ms | 32 | $3/$15 |
| Grok 4 Fast | 1,143ms | 23 | $0.20/$0.50 |
| Gemini 2.5 Flash | 1,238ms | 20 | $0.15/$0.60 |
Gemini 3.1 Pro is the standout: highest intelligence score (57) at just 1.6 seconds. GPT-5.4 matches its intelligence but takes 4x longer.
We initially used these numbers to promote fast models (Grok 4 Fast, Grok 4.1 Fast) as our default routing targets. It backfired. Users reported that the fast models were refusing complex tasks and giving shallow responses. Fast and cheap doesn't mean capable.
The fix: we now weight quality and user retention alongside speed in our routing algorithm. Gemini 2.5 Flash became our default for simple tasks (fast, cheap, reliable), while Kimi K2.5 handles medium-complexity work and Claude/GPT flagships handle the hard stuff.
What This Means for Developers
If you're building agents: Don't default to GPT. At 5-7 seconds per call, your agent's chain-of-actions will feel sluggish. Route simple subtasks to Grok/Gemini Flash and save the flagships for reasoning-heavy steps.
If you're cost-sensitive: Gemini 2.5 Flash-Lite at $0.10/$0.40 with 1.35s latency is the budget king. DeepSeek Chat at $0.27/$1.10 with 1.43s is a close second.
If you need peak intelligence: Gemini 3.1 Pro (IQ 57, 1.6s) gives you the same quality as GPT-5.4 (IQ 57, 6.2s) at one-quarter the latency and lower cost. Claude Opus 4.6 (IQ 53, 2.1s) is the best option if you need Anthropic-family capabilities.
If you want it all handled for you: That's what BlockRun's smart router does. Set your profile to auto and we'll pick the right model based on task complexity, balancing speed, quality, and cost automatically.
Methodology
- Date: March 16, 2026
- Setup: BlockRun ClawRouter v0.12.47 proxy on localhost, connected to BlockRun's x402 payment gateway on Base (EVM)
- Prompts: 3 Python coding tasks (IPv4 validation, LCS algorithm, LRU cache), 2 requests per model
- Config: 256 max tokens, non-streaming, temperature 0.7
- Latency: End-to-end wall clock time including x402 payment verification (~50-100ms overhead)
- Intelligence scores: Artificial Analysis Intelligence Index v4.0 (March 2026)
Raw benchmark data: benchmark-results.json
---
_BlockRun is the x402 micropayment gateway for AI. One wallet, 39+ models, pay-per-request with USDC. Get started_
---
Twitter Thread
Thread: We benchmarked 39 AI models through our payment gateway. The speed differences are wild. (thread)
1/ We ran every model on @BlockRunAI through a real-world latency benchmark. 39 models, same prompts, full payment pipeline included.
The fastest model (Grok 4 Fast) was 7x faster than the slowest (GPT-5.3 Codex). Here's the full breakdown:
2/ Top 5 fastest (end-to-end latency):
1. xai/grok-4-fast — 1,143ms
2. xai/grok-3-mini — 1,202ms
3. google/gemini-2.5-flash — 1,238ms
4. xai/grok-3 — 1,244ms
5. nvidia/gpt-oss-120b — 1,252ms (FREE)
3/ Bottom 5 (all OpenAI): 35. openai/gpt-5.3 — 5,910ms 36. openai/gpt-5.4 — 6,213ms 37. openai/gpt-5.2 — 6,507ms 38. openai/gpt-5.4-pro — 6,671ms 39. openai/gpt-5.3-codex — 7,935ms
Every OpenAI 5.x model: 5-8 seconds. Every Grok/Gemini model: ~1.2 seconds.
4/ But speed isn't everything.
We tried routing all requests to the fastest models. Users complained the "fast" models refused complex tasks and gave shallow answers.
Lesson: you need to balance speed, quality, AND cost.
5/ The efficiency frontier winners:
- Best overall: Gemini 3.1 Pro (IQ 57, 1.6s, $1.25/M)
- Best budget: Gemini 2.5 Flash (IQ 20, 1.2s, $0.15/M)
- Best reasoning: Claude Opus 4.6 (IQ 53, 2.1s, $15/M)
- Best speed/quality: Kimi K2.5 (IQ 47, 1.6s, $0.60/M)
6/ This is why we built smart routing into BlockRun.
Set model: "auto" and we pick the right model based on task complexity. Simple tasks get Gemini Flash. Complex reasoning gets Claude/GPT flagships.
One wallet. 39 models. The router handles the rest.
7/ Full leaderboard, methodology, and raw data in our blog post: [link]
All 39 models benchmarked through real x402 micropayment infrastructure. No synthetic lab conditions.
Build with @BlockRunAI: blockrun.ai
---
Openclaw Cost Reliability Clawrouter Fixes
OpenClaw Is Burning Your Budget and Stalling Your Agents. We Read the Issues — Here's the Fix.
_We searched OpenClaw's issue tracker for the problems users actually hit in production — cost, outages, runaway agents, model selection. Four structural problems show up again and again. ClawRouter fixes all four._
---
The data
OpenClaw is a superb agent harness. But running it in production surfaces the same handful of structural problems — and they're not edge cases, they're consequences of how a single-model, single-provider setup behaves under real load. We read the open issues and grouped them:
| Problem | Representative issues |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Cost spikes from background work | #90170, #81856, #72964, #48579, #84218, #65161 |
| Provider outages stall the session | #84865, #47910, #79611, #62615 |
| No spend ceiling for autonomous agents | #42475, #17683, #64463, #13219 |
| One model for every task | #43260, #80521, #65557, #88371 |
ClawRouter is a local router that sits between OpenClaw and the model providers. Every request — including the internal ones — goes through blockrun/auto, which classifies the call across 15 dimensions in under a millisecond and routes it to the cheapest model that can actually handle it. That single architectural move addresses all four problems below.
---
1. Your bill spiked 10x and you didn't change a thing
You didn't add agents. You didn't change models. But your token usage tripled. The cost isn't in the prompts you wrote — it's in the work the agent does between them: context compaction, heartbeat replays, and memory lookups that run on every turn and quietly burn tokens on whatever model is configured.
From #90170: _"Possible token/cost regression after OpenClaw v2026.5.28."_ A version bump, not a usage change, moved the needle.
The culprits are internal:
- Compaction firing too often, on the wrong model. #72964 and #48579 document premature compactions; #81856 asks for an absolute-token trigger because on a 1M-context model, summarizing hundreds of thousands of tokens at flagship rates — repeatedly — is ruinous.
- Heartbeats replaying context. #84218 and #65161 (14 comments) show idle beats that stay heavy, so every beat costs like an active one.
How ClawRouter fixes it
Route the expensive internal lanes to cheap or free models. Point compaction and memory at a cost profile instead of your premium default:
{
"agents": {
"main": {
"model": "blockrun/auto",
"compaction": { "model": "blockrun/eco" }, // summaries don't need a flagship
"memory": { "model": "blockrun/free" }, // lookups can be free
},
},
}The free tier alone covers most internal work — NVIDIA-hosted models with up to 1M context and a vision-capable Nemotron Omni, at zero cost. A compaction call billed at flagship rates becomes free, hundreds of times a day. On top of that, ClawRouter compresses verbose tool outputs and serves repeated responses from a short-TTL cache before any paid call goes out (the full teardown is in ClawRouter Cuts LLM API Costs 500x).
---
2. A provider goes down and your agent stalls for 14 minutes
The moment you pin OpenClaw to one model, you've built a single point of failure. When that provider has a bad minute — a 503, a rate-limit burst, an auth token that won't refresh — there's nothing behind it.
From #84865: _"user-switched model has no fallback chain, causing session deadlock on provider outage."_ The act of choosing a model — what a careful user does — strips the safety net.
And naive failover isn't enough: #47910 asks for fallback by failure class, because a 429 is transient (retry) while a 401 is not (skip immediately). #62615 asks for a circuit breaker so a degraded provider can't drag the whole session down.
How ClawRouter fixes it
When OpenClaw points at blockrun/auto, you're pointed at a router with a fallback chain behind every tier — primary plus an ordered list of fallbacks spanning different providers, so one outage doesn't poison the others.
[ClawRouter] tier=MEDIUM
[ClawRouter] primary moonshot/kimi-k2.6 → 503, falling through chain
[ClawRouter] trying next: google/gemini-3-flash-preview → okClawRouter also classifies failures before reacting — auth errors (401/403) skip straight to the next model instead of burning ~10s per retry; transient errors cascade; payment-simulation hiccups retry with a different model. The agent never sees a bare 503. And the bottom of every chain is the free tier, which isn't tied to any paid provider's uptime — so the worst case is "this turn ran on a free model for a minute," not "the gateway hung until I restarted it."
| Failure mode | Pinned single model | ClawRouter (blockrun/auto) |
| ------------------------------- | -------------------------- | ---------------------------------------- |
| Provider returns 503 | Session stalls / deadlocks | Falls to next model in chain |
| 401 / auth won't refresh | ~10s wasted, then error | Classified, skips straight to next model |
| Every paid provider unavailable | Hard failure | Completes on a free model |
---
3. There's no spend ceiling on an autonomous agent
A human agent stops spending when they go to sleep. An autonomous one doesn't — the whole point is that it runs without you, which means a runaway loop spends without you too.
OpenClaw users have asked for an enforced ceiling for a long time. #42475 (11 comments): _"Per-agent cost budget enforcement at the gateway level."_ #17683: _"Scoped / Script-Limited Agent Mode."_ #64463: _"session.maxTokensPerSession."_ The common thread: a limit the agent cannot exceed, enforced by infrastructure rather than the agent's own good behavior.
How ClawRouter fixes it
ClawRouter enforces a per-run (per-session) dollar ceiling via maxCostPerRunUsd, with two modes:
{
"maxCostPerRunUsd": 0.5,
"maxCostPerRunMode": "graceful",
}- graceful (default) — as the session nears its budget, ClawRouter downgrades to cheaper models and falls back to a free model as a last resort. Work continues, cheaper.
- strict — the moment session spend reaches the cap, it returns a 429 and stops. A run that physically cannot exceed its number — exactly the predictable behavior #17683 describes.
Two more guardrails: /exclude removes your most expensive models from routing entirely (including every fallback chain), so a loop can't escalate into them — and the wallet balance itself is a hard ceiling: fund it with only what you're willing to spend, and the agent literally cannot exceed it. /stats shows what was spent and which models served the requests — the per-model visibility #13219 is asking for.
---
4. One model handles your hardest task and your most trivial one — at the same price
OpenClaw lets you pick a model. Singular. It then handles your hardest reasoning task and a one-line reformat at the same per-token price. Users keep asking for finer control: per-skill model routing (#43260, 8 comments), a model picker (#80521), per-account allowlists (#65557). And the default pick can quietly be an expensive one — #88371: a brand-new user's first message bills against a premium API with no warning.
How ClawRouter fixes it
Automatic per-task routing. blockrun/auto classifies every individual request and routes it to the cheapest capable model — no per-task config:
"reformat this JSON" → simple tier → fast, cheap model
"refactor this module" → complex tier → flagship-quality model
"prove this invariant" → reasoning → reasoning modelExplicit per-agent control when you want it. Assign a profile per lane in openclaw.json — blockrun/premium for coding, blockrun/free for formatting — each with its own fallback chain. And clean aliases (sonnet, opus, flash, grok, gpt5) mean switching is one word (/model grok), with none of the provider/provider/model mangling that fills the tracker. The default itself is cost-safe: a fresh install routes to blockrun/auto and the free tier works with no balance, so nobody's first message silently hits a premium API.
---
The fix is one decision
All four problems share a root cause — a single model, chosen once, doing everything, with nothing behind it — and a single fix: route through blockrun/auto and let a local router classify, price, and fail over each request on its own merits.
1. Set your primary to blockrun/auto.blockrun/eco
2. Point compaction and memory at / blockrun/free.maxCostPerRunUsd
3. Set on anything autonomous; /exclude the models you never want reached./stats
4. Run after a day and tune.
An autonomous agent is only as good as its worst provider-minute and its largest unmonitored bill. Fix both at the router, once.
---
Related documentation
- Why Your OpenClaw Bill Spiked 10x — the token-compression teardown
- We Read 100 OpenClaw Issues About OpenRouter — the structural case for local routing
- Routing Profiles — auto / eco / premium / free
- 9 Free AI Models, Zero Cost — what the free tier covers
- Using Subscriptions with ClawRouter Failover — keep your subscription primary, ClawRouter as failover
---
Routing Profiles
Routing Profiles & Pricing
ClawRouter offers four routing profiles to balance cost vs quality. Prices are in $/M tokens (input/output). Tables show each tier's primary model — every tier also carries a benchmark-ordered fallback chain (see src/router/config.ts).
ECO (Absolute Cheapest)
Use blockrun/eco for maximum cost savings.
| Tier | Primary Model | Input | Output |
| --------- | ---------------------------- | ----- | ------ |
| SIMPLE | free/gpt-oss-120b | $0.00 | $0.00 |
| MEDIUM | google/gemini-3.1-flash-lite | $0.25 | $1.50 |
| COMPLEX | google/gemini-3.1-flash-lite | $0.25 | $1.50 |
| REASONING | xai/grok-4-1-fast-reasoning | $0.20 | $0.50 |
---
AUTO (Balanced - Default)
Use blockrun/auto for the best quality/price balance.
| Tier | Primary Model | Input | Output |
| --------- | --------------------------- | ----- | ------ |
| SIMPLE | google/gemini-2.5-flash | $0.30 | $2.50 |
| MEDIUM | moonshot/kimi-k2.6 | $0.95 | $4.00 |
| COMPLEX | google/gemini-3.1-pro | $2.00 | $12.00 |
| REASONING | xai/grok-4-1-fast-reasoning | $0.20 | $0.50 |
---
PREMIUM (Best Quality)
Use blockrun/premium for maximum quality.
| Tier | Primary Model | Input | Output |
| --------- | -------------------- | ------ | ------ |
| SIMPLE | moonshot/kimi-k2.6 | $0.95 | $4.00 |
| MEDIUM | openai/gpt-5.3-codex | $1.75 | $14.00 |
| COMPLEX | claude-fable-5 | $10.00 | $50.00 |
| REASONING | claude-sonnet-4.6 | $3.00 | $15.00 |
---
AGENTIC (Multi-Step Tasks)
ClawRouter auto-detects agentic patterns (tool use, multi-step autonomy) and switches to agent-tuned primaries.
| Tier | Primary Model | Input | Output |
| --------- | ------------------ | ----- | ------ |
| SIMPLE | openai/gpt-4o-mini | $0.15 | $0.60 |
| MEDIUM | moonshot/kimi-k2.6 | $0.95 | $4.00 |
| COMPLEX | claude-sonnet-4.6 | $3.00 | $15.00 |
| REASONING | claude-sonnet-4.6 | $3.00 | $15.00 |
---
ECO vs AUTO Savings
Combined input + output rate per 1M tokens:
| Tier | ECO | AUTO | Savings |
| --------- | ----- | ------ | -------- |
| SIMPLE | FREE | $2.80 | 100% |
| MEDIUM | $1.75 | $4.95 | 65% |
| COMPLEX | $1.75 | $14.00 | 88% |
| REASONING | $0.70 | $0.70 | 0% |
---
How Tiers Work
ClawRouter automatically classifies your query into one of four tiers:
- SIMPLE: Basic questions, short responses, simple lookups
- MEDIUM: Code generation, moderate complexity tasks
- COMPLEX: Large context, multi-step reasoning, complex code
- REASONING: Logic puzzles, math, chain-of-thought tasks
The router picks the cheapest model capable of handling your query's tier.
There is also a blockrun/free pin that routes exclusively across the free NVIDIA-hosted fleet (gpt-oss-120b default) — no USDC required.
---
_Last updated: v0.12.201_
---
Smart Llm Router 14 Dimension Classifier
Building a Smart LLM Router: How We Benchmarked 46 Models and Built a 14-Dimension Classifier
_March 20, 2026 | BlockRun Engineering_
Numbers in this post are a snapshot from the date above. They record what was
measured then and are deliberately not updated — rewriting them would misrepresent
the benchmark. For current figures see
blockrun.ai/brand/numbers.json.
When you route AI requests across 55+ models from 8 providers, you can't just pick the cheapest one. You can't just pick the fastest one either. We learned this the hard way.
This is the technical story of how we benchmarked every model on our platform, discovered that speed and intelligence are poorly correlated, and built a production routing system that classifies requests in under 1ms using 14 weighted dimensions with sigmoid confidence calibration.
The Problem: One Gateway, 46 Models, Infinite Wrong Choices
BlockRun is an x402 micropayment gateway. Every LLM request flows through our proxy, gets authenticated via on-chain USDC payment, and is forwarded to the appropriate provider. The payment overhead adds 50-100ms to every request.
Our users set model: "auto" and expect us to pick the right model. But "right" means different things for different requests:
- A "what is Python?" query should route to the cheapest, fastest model
- A "implement a B-tree with concurrent insertions" query needs a capable model
- A "prove this theorem step by step" query needs reasoning capabilities
- An agentic workflow with tool calls needs models that follow instructions precisely
We needed a system that could classify any request and route it to the optimal model in real-time.
Step 1: Benchmarking the Fleet
Before building the router, we needed ground truth. We benchmarked all 55+ models through our production payment pipeline.
Methodology
Setup: ClawRouter v0.12.47 proxy on localhost
→ BlockRun x402 gateway (Base EVM chain)
→ Provider APIs (OpenAI, Anthropic, Google, xAI, DeepSeek, Moonshot, MiniMax, Z.AI)Prompts: 3 Python coding tasks (IPv4 validation, LCS algorithm, LRU cache)
2 requests per model per prompt
Config: 256 max tokens, non-streaming, temperature 0.7
Measured: End-to-end wall clock time (includes x402 payment verification)
This is not a synthetic benchmark. Every measurement includes the full payment-verification round trip that real users experience.
The Latency Landscape
Results revealed a 7x spread between the fastest and slowest models:
FAST TIER (<1.5s):
xai/grok-4-fast 1,143ms 224 tok/s $0.20/$0.50
xai/grok-3-mini 1,202ms 215 tok/s $0.30/$0.50
google/gemini-2.5-flash 1,238ms 208 tok/s $0.30/$2.50
google/gemini-2.5-pro 1,294ms 198 tok/s $1.25/$10.00
google/gemini-3-flash 1,398ms 183 tok/s $0.50/$3.00
deepseek/deepseek-chat 1,431ms 179 tok/s $0.28/$0.42MID TIER (1.5-2.5s):
google/gemini-3.1-pro 1,609ms 167 tok/s $2.00/$12.00
moonshot/kimi-k2.5 1,646ms 156 tok/s $0.60/$3.00
anthropic/claude-sonnet 2,110ms 121 tok/s $3.00/$15.00
anthropic/claude-opus 2,139ms 120 tok/s $5.00/$25.00
openai/o3-mini 2,260ms 114 tok/s $1.10/$4.40
SLOW TIER (>3s):
openai/gpt-5.2-pro 3,546ms 73 tok/s $21.00/$168.00
openai/gpt-4o 5,378ms 48 tok/s $2.50/$10.00
openai/gpt-5.4 6,213ms 41 tok/s $2.50/$15.00
openai/gpt-5.3-codex 7,935ms 32 tok/s $1.75/$14.00
Two clear patterns:
1. Google and xAI dominate speed. 11 of the top 13 fastest models are from Google or xAI.
2. OpenAI flagship models are consistently slow. Every GPT-5.x model takes 3-8 seconds. Even their cheapest models (GPT-4.1-nano at $0.10/$0.40) are 2x slower than Google's cheapest.
Step 2: Adding the Quality Dimension
Speed alone tells you nothing about whether a model can actually handle your request. We cross-referenced our latency data with Artificial Analysis Intelligence Index v4.0 scores (composite of GPQA, MMLU, MATH, HumanEval, and other benchmarks):
MODEL LATENCY IQ $/M INPUT
─────────────────────────────────────────────────────
google/gemini-3.1-pro 1,609ms 57 $2.00 ← SWEET SPOT
openai/gpt-5.4 6,213ms 57 $2.50
openai/gpt-5.3-codex 7,935ms 54 $1.75
anthropic/claude-opus-4.6 2,139ms 53 $5.00
anthropic/claude-sonnet-4.6 2,110ms 52 $3.00
google/gemini-3-pro-prev 1,352ms 48 $2.00
moonshot/kimi-k2.5 1,646ms 47 $0.60
google/gemini-3-flash-prev 1,398ms 46 $0.50 ← VALUE SWEET SPOT
xai/grok-4 1,348ms 41 $0.20
xai/grok-4.1-fast 1,244ms 41 $0.20
deepseek/deepseek-chat 1,431ms 32 $0.28
xai/grok-4-fast 1,143ms 23 $0.20
google/gemini-2.5-flash 1,238ms 20 $0.30The Efficiency Frontier
Plotting IQ against latency reveals a clear efficiency frontier:
IQ
57 | Gem3.1Pro ·························· GPT-5.4
|
53 | · Opus
52 | · Sonnet
|
48 | Gem3Pro ·
47 | · Kimi
46 | Gem3Flash ·
|
41 | Grok4 ·
|
32 | Grok3 · · DeepSeek
|
23 | GrokFast ·
20 | GemFlash ·
└──────────────────────────────────────────────
1.0 1.5 2.0 2.5 3.0 6.0 8.0
End-to-End Latency (seconds)The frontier runs from Gemini 2.5 Flash (IQ 20, 1.2s) up to Gemini 3.1 Pro (IQ 57, 1.6s). Everything above and to the right of this line is dominated — you can get equal or better quality at lower latency from a different model.
Key insight: Gemini 3.1 Pro matches GPT-5.4's IQ at 1/4 the latency and lower cost. Claude Sonnet 4.6 nearly matches Opus 4.6 quality at 60% of the price. These dominated pairings directly informed our routing fallback chains.
Step 3: The Failed Experiment (Latency-First Routing)
Armed with benchmark data, we initially optimized for speed. The routing config promoted fast models:
// v0.12.47 — latency-optimized (REVERTED)
COMPLEX: {
primary: "xai/grok-4-0709", // 1,348ms, IQ 41
fallback: [
"xai/grok-4-1-fast-non-reasoning", // 1,244ms, IQ 41
"google/gemini-2.5-flash", // 1,238ms, IQ 20
// ... fast models first
],
}Users complained within 24 hours. The fast models were refusing complex tasks and giving shallow responses. A model with IQ 41 can't reliably handle architecture design or multi-step code generation, no matter how fast it is.
Lesson: optimizing for a single metric in a multi-objective system creates failure modes. We needed to optimize across speed, quality, and cost simultaneously.
Step 4: The 14-Dimension Scoring System
The router needs to determine what kind of request it's looking at before selecting a model. We built a rule-based classifier that scores requests across 14 weighted dimensions:
Architecture
User Prompt → Lowercase + Tokenize
↓
┌──────────────────────────────────┐
│ 14 Dimension Scorers │
│ Each returns score ∈ [-1, 1] │
└──────┬───────────────────────────┘
↓
Weighted Sum (configurable weights)
↓
Tier Boundaries (SIMPLE < 0.0 < MEDIUM < 0.3 < COMPLEX < 0.5 < REASONING)
↓
Sigmoid Confidence Calibration
↓
confidence < 0.7 → AMBIGUOUS → default to MEDIUM
confidence ≥ 0.7 → Classified tier
↓
Tier × Profile → Model SelectionThe 14 Dimensions
| Dimension | Weight | What It Detects | Score Range |
| ------------------- | ------ | ---------------------------------------- | ----------- |
| reasoningMarkers | 0.18 | "prove", "theorem", "step by step" | 0 to 1.0 |
| codePresence | 0.15 | "function", "class", "import", "
/ Detailed source-code truncated for AI context efficiency. /confidence = 1 / (1 + exp(-steepness * distance_from_boundary))
Wheresteepness = 12anddistance_from_boundaryis the score's distance to the nearest tier boundary. This maps to a [0.5, 1.0] confidence range. Belowthreshold = 0.7, the request is classified as ambiguous and defaults to MEDIUM.agenticScore >= 0.5Agentic Detection
A separate scoring pathway detects agentic tasks (multi-step, tool-using, iterative). When
, the router switches to agentic-optimized tier configs that prefer models with strong instruction following (Claude Sonnet for complex tasks, GPT-4o-mini for simple tool calls).Step 5: Tier-to-Model Mapping
Once a request is classified into a tier, the router selects from 4 routing profiles:
Auto Profile (Default)
Tuned from our benchmark data + user retention metrics:
SIMPLE → gemini-2.5-flash (1,238ms, IQ 20, 60% retention)
MEDIUM → kimi-k2.5 (1,646ms, IQ 47, strong tool use)
COMPLEX → gemini-3.1-pro (1,609ms, IQ 57, fastest flagship)
REASON → grok-4-1-fast-reasoning (1,454ms, $0.20/$0.50)
Eco Profile
Ultra cost-optimized. Uses free/near-free models:
SIMPLE → nvidia/gpt-oss-120b (FREE)
MEDIUM → gemini-2.5-flash-lite ($0.10/$0.40, 1M context)
COMPLEX → gemini-2.5-flash-lite ($0.10/$0.40)
REASON → grok-4-1-fast-reasoning ($0.20/$0.50)
Premium Profile
Best quality regardless of cost:
SIMPLE → kimi-k2.5 ($0.60/$3.00)
MEDIUM → gpt-5.3-codex ($1.75/$14.00, 400K context)
COMPLEX → claude-opus-4.6 ($5.00/$25.00)
REASON → claude-sonnet-4.6 ($3.00/$15.00)
Fallback Chains
Each tier config includes an ordered fallback list. When the primary model returns a 402 (payment failed), 429 (rate limited), or 5xx, the proxy walks the fallback chain. Fallback ordering is benchmark-informed:
// COMPLEX tier — quality-first fallback order
fallback: [
"google/gemini-3-pro-preview", // IQ 48, 1,352ms
"google/gemini-3-flash-preview", // IQ 46, 1,398ms
"xai/grok-4-0709", // IQ 41, 1,348ms
"google/gemini-2.5-pro", // 1,294ms
"anthropic/claude-sonnet-4.6", // IQ 52, 2,110ms
"deepseek/deepseek-chat", // IQ 32, 1,431ms
"google/gemini-2.5-flash", // IQ 20, 1,238ms
"openai/gpt-5.4", // IQ 57, 6,213ms — last resort
];
The chain descends by quality first (IQ 48 → 46 → 41), then trades quality for speed. GPT-5.4 is last despite having IQ 57, because its 6.2s latency is a worst-case user experience.Step 6: Context-Aware Filtering
The fallback chain is filtered at runtime based on request properties:
1. Context window filtering: Models with insufficient context window for the estimated total tokens are excluded (with 10% safety buffer)
2. Tool calling filter: When the request includes tool definitions, only models that support function calling are kept
3. Vision filter: When the request includes images, only vision-capable models are kept
If filtering eliminates all candidates, the full chain is used as a fallback (better to let the API error than return nothing).
Cost Calculation and Savings
Every routing decision includes a cost estimate and savings percentage against a baseline (Claude Opus 4.6 pricing):
savings = max(0, (opusCost - routedCost) / opusCost);
For a typical SIMPLE request (500 input tokens, 256 output tokens):benchmark-merged.json- Opus cost: $0.0089 (at $5.00/$25.00 per 1M tokens)
- Gemini Flash cost: $0.0008 (at $0.30/$2.50 per 1M tokens)
- Savings: 91.0%Across our user base, the median savings rate is 85% compared to routing everything to a premium model.
Performance
The entire classification pipeline (14 dimensions + tier mapping + model selection) runs in under 1ms. No external API calls. No LLM inference. Pure keyword matching and arithmetic.
We originally designed a two-stage system where low-confidence rules-based classifications would fall back to an LLM classifier (Gemini 2.5 Flash). In practice, the rules handle 70-80% of requests with high confidence, and the remaining ambiguous cases default to MEDIUM — which is the correct conservative choice.
What We Learned
1. Speed and intelligence are weakly correlated. The fastest model (Grok 4 Fast, IQ 23) is at the bottom of the quality scale. The smartest model at low latency (Gemini 3.1 Pro, IQ 57, 1.6s) is a Google model, not OpenAI.
2. Optimizing for one metric fails. Latency-first routing breaks quality. Quality-first routing breaks latency budgets. You need multi-objective optimization.
3. User retention is the real metric. Our best-performing model for SIMPLE tasks isn't the cheapest or the fastest — it's Gemini 2.5 Flash (60% retention rate), which balances speed, cost, and just-enough quality.
4. Fallback ordering matters more than primary selection. The primary model handles the happy path. The fallback chain handles reality — rate limits, outages, payment failures. A well-ordered fallback chain is more important than picking the perfect primary.
5. Rule-based classification is underrated. 14 keyword dimensions with sigmoid confidence calibration handles 70-80% of requests correctly in <1ms. The remaining 20-30% default to a safe middle tier. For a routing system where every millisecond of overhead compounds across millions of requests, avoiding LLM inference in the classification step is worth the reduced accuracy.
---
Appendix: Full Benchmark Data
Raw data (55+ models, latency, throughput, IQ scores, pricing):
src/router/config.tssrc/router/rules.ts---
_BlockRun is the x402 micropayment gateway for AI. One wallet, 55+ models, pay-per-request with USDC. blockrun.ai_
---
Subscription Failover
Using Subscriptions with ClawRouter Failover
This guide explains how to use your existing LLM subscriptions (Claude Pro/Max, ChatGPT Plus, etc.) as primary providers, with ClawRouter x402 micropayments as automatic failover.
Why Not Built Into ClawRouter?
After careful consideration, we decided not to integrate subscription support directly into ClawRouter for several important reasons:
1. Terms of Service Compliance
- Most subscription ToS (Claude Code, ChatGPT Plus) are designed for personal use
- Using them through a proxy/API service may violate provider agreements
- We want to keep ClawRouter compliant and low-risk for all users2. Security & Privacy
- Integrating subscriptions would require ClawRouter to access your credentials/sessions
- Spawning external processes (like Claude CLI) introduces security concerns
- Better to keep authentication at the OpenClaw layer where you control it3. Maintenance & Flexibility
- Each subscription provider has different APIs, CLIs, and authentication methods
- OpenClaw already has a robust provider system that handles this
- Duplicating this in ClawRouter would increase complexity without added value4. Better Architecture
- OpenClaw's native failover mechanism is more flexible and powerful
- Works with any provider (not just Claude)
- Zero code changes needed in ClawRouter
- You maintain full control over your credentialsHow It Works
OpenClaw has a built-in model fallback chain that automatically tries alternative providers when the primary fails:
User Request
↓
Primary Provider (e.g., Claude subscription via OpenClaw)
↓ (rate limited / quota exceeded / auth failed)
OpenClaw detects failure
↓
Fallback Chain (try each in order)
↓
ClawRouter (blockrun/auto)
↓
Smart routing picks cheapest model
↓
x402 micropayment to BlockRun API
↓
Response returned to user
Key benefits:- ✅ Automatic failover (no manual intervention)
- ✅ Works with any subscription provider OpenClaw supports
- ✅ Respects provider ToS (you configure authentication directly)
- ✅ ClawRouter stays focused on cost optimization
Setup Guide
Prerequisites
1. OpenClaw Gateway installed with ClawRouter plugin
npm install openclaw
openclaw plugins install @blockrun/clawrouter
2. Subscription configured in OpenClawclaude setup-token
- For Claude: Useor API keyOPENAI_API_KEY
- For OpenAI: Setenvironment variable
- For others: See OpenClaw provider docs3. ClawRouter wallet funded (for failover)
openclaw gateway logs | grep "Wallet:"
# Send USDC to the displayed address on Base network
Configuration Steps
#### Step 1: Set Primary Model (Your Subscription)
Option A: Using Claude subscription
openclaw models set anthropic/claude-sonnet-4.6
Option B: Using ChatGPT Plus (via OpenAI provider)
openclaw models set openai/gpt-4o
Option C: Using any other provider
openclaw models set <provider>/<model>
#### Step 2: Add ClawRouter as FallbackAdd blockrun/auto for smart routing (recommended)
openclaw models fallbacks add blockrun/auto
Or specify a specific model
openclaw models fallbacks add blockrun/google/gemini-2.5-pro
#### Step 3: Verify Configurationopenclaw models show
Expected output:Primary: anthropic/claude-sonnet-4.6
Fallbacks:
1. blockrun/auto
#### Step 4: Test Failover (Optional)To verify failover works:
1. Temporarily exhaust your subscription quota (or wait for rate limit)
2. Make a request - OpenClaw should automatically failover to ClawRouter
3. Check logs:
openclaw gateway logs | grep -i "fallback\|blockrun"
Advanced Configuration
#### Configure Multiple Fallbacks
openclaw models fallbacks add blockrun/google/gemini-2.5-flash # Fast & cheap
openclaw models fallbacks add blockrun/deepseek/deepseek-chat # Even cheaper
openclaw models fallbacks add blockrun/nvidia/gpt-oss-120b # Free tier
#### Per-Agent Configuration~/.openclaw/openclaw.jsonEdit
:
{
"agents": {
"main": {
"model": {
"primary": "anthropic/claude-opus-4.6",
"fallbacks": ["blockrun/auto"]
}
},
"coding": {
"model": {
"primary": "anthropic/claude-sonnet-4.6",
"fallbacks": ["blockrun/google/gemini-2.5-pro", "blockrun/deepseek/deepseek-chat"]
}
}
}
}
#### Tier-Based Configuration (ClawRouter Smart Routing)blockrun/autoWhen using
, ClawRouter automatically classifies your request and picks the cheapest capable model:- SIMPLE queries → Gemini 2.5 Flash, DeepSeek Chat (~$0.0001/req)
- MEDIUM queries → GPT-4o-mini, Gemini Flash (~$0.001/req)
- COMPLEX queries → Claude Sonnet, Gemini Pro (~$0.01/req)
- REASONING queries → DeepSeek R1, o3-mini (~$0.05/req)Learn more: ClawRouter Smart Routing
Monitoring & Troubleshooting
Check If Failover Is Working
Watch real-time logs
openclaw gateway logs --follow | grep -i "fallback\|blockrun\|rate.limit\|quota"
Check ClawRouter proxy logs
openclaw gateway logs | grep "ClawRouter"
Success indicators:- ✅ "Rate limit reached" or "Quota exceeded" → primary failed
- ✅ "Trying fallback: blockrun/auto" → failover triggered
- ✅ "ClawRouter: Success with model" → failover succeeded
Common Issues
#### Issue: Failover never triggers
Symptoms: Always uses primary, never switches to ClawRouter
Solutions:
1. Check fallbacks are configured:
openclaw models show
2. Verify primary is actually failing (check provider dashboard for quota/rate limits)
3. Check OpenClaw logs for authentication errors#### Issue: "Wallet empty" errors during failover
Symptoms: Failover triggers but ClawRouter returns balance errors
Solutions:
1. Check ClawRouter wallet balance:
openclaw gateway logs | grep "Balance:"
2. Fund wallet on Base network (USDC)blockrun/auto
3. Verify wallet key is configured correctly#### Issue: Slow failover (high latency)
Symptoms: 5-10 second delay when switching to ClawRouter
Cause: OpenClaw tries multiple auth profiles before failover
Solutions:
1. Reduce auth profile retry attempts (see OpenClaw config)
2. Useas primary for faster responses
3. Accept the latency as a tradeoff for cheaper requestsCost Analysis
Example Scenario
Usage pattern:
- 100 requests/day
- 50% hit Claude subscription quota (rate limited)
- 50% use ClawRouter failoverWithout failover:
- Pay Anthropic API: $50/month (100% API usage)
With failover:
- Claude subscription: $20/month (covers 50%)
- ClawRouter x402: ~$5/month (50 requests via smart routing)
- Total: $25/month (50% savings)When Does This Make Sense?
✅ Good fit:
- You already have a subscription for personal use
- You occasionally exceed quota/rate limits
- You want cost optimization without managing API keys❌ Not ideal:
- You need 100% reliability (subscriptions have rate limits)
- You prefer a single provider (no failover complexity)
- Your usage is low (< 10 requests/day)FAQ
Q: Will this violate my subscription ToS?
A: You configure the subscription directly in OpenClaw using your own credentials. ClawRouter only receives requests after your subscription fails. This is similar to using multiple API keys yourself.
However, each provider has different ToS. Check yours before proceeding:
- Claude Code Terms
- ChatGPT TermsQ: Can I use multiple subscriptions?
A: Yes! Configure multiple providers with failback chains:
openclaw models set anthropic/claude-opus-4.6
openclaw models fallbacks add openai/gpt-4o # ChatGPT Plus
openclaw models fallbacks add blockrun/auto # x402 as final fallback
blockrun/autoQ: Does this work with Claude Max API Proxy?
A: Yes! Configure the proxy as a custom provider in OpenClaw, then add
as fallback.See: Claude Max API Proxy Guide
Q: How is this different from PR #15?
A: PR #15 integrated Claude CLI directly into ClawRouter. Our approach:
- ✅ Works with any provider (not just Claude)
- ✅ Respects provider ToS (no proxy/wrapper)
- ✅ Uses OpenClaw's native failover (more reliable)
- ✅ Zero maintenance burden on ClawRouterFeedback & Support
We'd love to hear your experience with subscription failover:
- GitHub Discussion: Share your setup
- Issues: Report problems
- Telegram: Join communityRelated Documentation
- OpenClaw Model Failover
- OpenClaw Provider Configuration
- ClawRouter Smart Routing
- ClawRouter x402 Micropayments---
Troubleshooting
Troubleshooting
Quick solutions for common ClawRouter issues.
Need help? Open a Discussion or check existing issues.Table of Contents
- Quick Checklist
- Common Errors
- Security Scanner Warnings
- Port Conflicts
- How to Update
- Verify Routing---
Quick Checklist
1. Check your version (should be 0.12+)
cat ~/.openclaw/extensions/clawrouter/package.json | grep version
2. Check proxy is running
curl http://localhost:8402/health
3. Check wallet (both EVM + Solana addresses and balance)
/wallet
4. Watch routing in action
openclaw logs --follow
Should see: kimi-k2.5 $0.0012 (saved 99%)
5. View cost savings
/stats
---blockrun/autoCommon Errors
"Unknown model: blockrun/auto" or "Unknown model: auto"
Plugin isn't loaded or outdated. Don't change the model name —
is correct.blockrun/autoFix: Update to v0.3.21+ which handles both
andauto(OpenClaw strips provider prefix). See How to Update./wallet"No API key found for provider blockrun"
Auth profile is missing or wasn't created properly.
Fix: See How to Update — the reinstall script automatically injects the auth profile.
"Config validation failed: plugin not found: clawrouter"
Plugin directory was removed but config still references it. This blocks all OpenClaw commands until fixed.
Fix: See How to Update for complete cleanup steps.
"No USDC balance" / "Insufficient funds"
Wallet needs funding. ClawRouter accepts USDC (not SOL or ETH) on either chain.
Fix:
1. Find your wallet address: run
in any OpenClaw conversation0x...
2. Choose your preferred chain and send USDC to that address:
- Base (EVM): Send USDC on Base network to your EVM address ()BLOCKRUN_WALLET_KEY
- Solana: Send USDC on Solana network to your Solana address (base58)
3. $1–5 is enough for hundreds of requests
4. Restart OpenClaw (or wait up to 60s for balance cache to refresh)---
Security Scanner Warnings
"WARNING: dangerous code patterns — possible credential harvesting"
This is a false positive. ClawRouter legitimately:
1. Reads
from environment (for authentication)
2. Sends authenticated requests to BlockRun API (for x402 micropayments)This pattern triggers OpenClaw's security scanner, but it's the intended behavior — the wallet key is required to sign payment transactions. The code is fully open source and auditable.
"env-harvesting" Warning
OpenClaw's security scanner may flag ClawRouter with:
[env-harvesting] Environment variable access combined with network send
This is a false positive. The scanner's heuristic (env variable + network request = suspicious) flags all payment plugins, but this pattern is inherently required for non-custodial payments.BLOCKRUN_WALLET_KEYClawRouter reads
to sign x402 payment transactions — this is required and intentional:openclaw.security.json- The wallet key is used locally for cryptographic signing (EIP-712)
- The signature is transmitted, not the private key itself
- The key never leaves the machine — only cryptographic proofs are sent
- This is standard x402 payment protocol behavior
- Source code is MIT licensed and fully auditablefor detailed security documentation and this discussion for more context.EADDRINUSE---
Port Conflicts
Port 8402 already in use
As of v0.4.1, ClawRouter automatically detects and reuses an existing proxy on the configured port instead of failing with
. You should no longer see this error.If you need to use a different port:
Set custom port via environment variable
export BLOCKRUN_PROXY_PORT=8403
openclaw gateway restart
To manually check/kill the process:lsof -i :8402
Kill the process or restart OpenClaw
---How to Update
npx @blockrun/clawrouter@latest
openclaw gateway restart
This installs the latest version and restarts the gateway. Alternatively:curl -fsSL https://raw.githubusercontent.com/BlockRunAI/ClawRouter/main/scripts/reinstall.sh | bash
openclaw gateway restart
---Verify Routing
openclaw logs --follow
You should see model selection for each request:[plugins] [SIMPLE] google/gemini-2.5-flash $0.0012 (saved 99%)
[plugins] [MEDIUM] deepseek/deepseek-chat $0.0003 (saved 99%)
[plugins] [REASONING] deepseek/deepseek-reasoner $0.0005 (saved 99%)
---Vision
BlockRun Worker Network — Vision
The Problem
Every company with a public API — blockchain protocols, AI providers, SaaS businesses — needs to prove to investors, customers, and regulators that their service is reliable. Today, that proof comes from centralized monitoring tools like UptimeRobot or Pingdom. The fundamental flaw: these reports are self-referential. A company can choose which tool monitors them, when to show the data, and how to present it. There is no independent, tamper-proof verification.
Meanwhile, ClawRouter users run AI agents that are idle the vast majority of the time. That idle compute has no economic value today.
The Vision
Turn ClawRouter's distributed user base into the world's first decentralized high-availability validation network — where AI agents earn USDC by doing real verification work, and any company can purchase cryptographically verifiable proof that their service is always on.
The core insight: a health check result signed by 50 independent nodes across 30 countries is fundamentally different from the same check run by a single company's monitoring vendor. It cannot be fabricated. It cannot be cherry-picked. It is, for the first time, objective proof of uptime.
Why This Matters
We are entering a world where AI agents are the primary consumers of APIs. As agents proliferate, the reliability of the infrastructure they depend on becomes critical. A DeFi protocol that goes down at the wrong moment, an AI API that drops requests under load, a SaaS backend that silently fails — these are existential risks for the services built on top of them.
The companies that can prove they never go down will win. BlockRun provides that proof.
Long-Term Ambition
Start with uptime monitoring. Expand to any verification task that benefits from decentralized, independent execution:
- Phase 1: HTTP health checks, latency measurement, SSL/DNS validation
- Phase 2: API contract verification (does the endpoint return what it promises?)
- Phase 3: Full agentic tasks — scheduled jobs, data pipelines, anything a ClawRouter agent can run
The worker network becomes the backbone of a new trust layer for the internet — not maintained by a single company, but by thousands of independent agents earning for their work.
The Flywheel
More ClawRouter users
→ More worker nodes → Better geographic coverage
→ Better product for verification buyers
→ More revenue → Higher worker earnings
→ More incentive to run ClawRouter
→ More ClawRouter users
Each side of the marketplace strengthens the other. ClawRouter users are simultaneously the supply (workers) and a natural demand source (they build services that need monitoring). There is no cold start problem.superpowers:executing-plansWhy BlockRun Wins This
1. Infrastructure already exists: x402 micropayments, USDC wallets, distributed user base — all live today
2. No new trust required: Workers are already ClawRouter users who've onboarded with a funded wallet
3. Crypto-native from day one: USDC settlement on Base, x402 protocol — the payment layer is the differentiator
4. Partnership leverage: Built on Coinbase's x402 protocol, natural alignment with Base ecosystem---
Worker Network
BlockRun Worker Network
For Claude implementing this: Useto implement the tasks section task-by-task.Goal: Let ClawRouter users opt in as worker nodes — poll tasks, execute HTTP checks, earn USDC via x402 micropayments.
Architecture: ClawRouter polls every 30s, signs results with existing wallet key. BlockRun verifies signature, writes to DB, triggers batched x402 payout at $0.01 threshold, simultaneously writes calldata log tx to Base for immutable audit trail.
Tech Stack: viem (signing + calldata tx), x402 reversed payTo (worker payout), DB (credits ledger), GCS (result logs + reputation source), Base calldata (audit trail)
---
Overview
ClawRouter Worker Mode transforms any ClawRouter installation into a node in a decentralized uptime monitoring network. Workers earn USDC by executing HTTP health checks assigned by BlockRun. Buyers purchase monitoring with tamper-proof, multi-node uptime proof — a stronger signal than self-reported metrics.
Current supply-side advantage: ~1,000 paying ClawRouter users already have wallets and geographic distribution. Turning them into workers requires zero additional setup.
---
Target Customers
Primary: Web3 Protocols (Phase 1)
Blockchain protocols, L1/L2 chains, DeFi applications, RPC providers.
Why they buy:
- CEX listing requirements mandate uptime SLA proof
- Institutional investors require auditable availability records
- Decentralized proof (multi-node, on-chain payment trail) is more credible than self-reported metrics
- Already comfortable with USDC payments — no payment education neededExample customers: New L2 chains seeking Binance/Coinbase listing, DeFi protocols pitching institutional LPs, bridge protocols, oracle networks
Secondary: AI API Providers (Phase 2)
OpenAI, Anthropic, and the long tail of AI API businesses.
Tertiary: SaaS & Fintech (Phase 2+)
Any B2B company that sells to enterprises or operates under financial regulation.
---
Pricing Model
For Buyers
| Tier | SLA | Price | BlockRun margin |
| --------------- | ---------------------------------------------- | ------------- | --------------- |
| Best Effort | Checks run when workers online (~90% coverage) | $0.0003/check | 67% |
| Standard | ≥1 check/min guaranteed (BlockRun fills gaps) | $0.001/check | 90% |
| Premium | 30s guaranteed + multi-region report | $0.003/check | 97% |Monthly equivalent per endpoint (30s Standard):
- 2,880 checks/day × 30 × $0.001 = $86.40/month
- Worker cost: 2,880 × $0.0001 = $8.64/month
- BlockRun margin: $77.76/endpoint/monthFor Workers
Base rate: $0.0001/check (100 USDC micros)
Multiplied by reputation tier (see below). Payouts trigger at $0.01 threshold to minimize gas.
---
Reputation Flywheel
BlockRun already has all payment data from LLM inference. No third-party needed.
用户付钱买 LLM → 积累 reputation
高 reputation → 拿到更多/更好 worker 任务
赚到更多 USDC → 继续买 LLM
→ 循环
Reputation Tiers (based on lifetime USDC paid to BlockRun)
| Tier | Condition | Worker reward | Task priority |
| ------------ | ----------- | --------------------- | ---------------------------- |
| Bronze | New user | $0.0001/check (1x) | Standard |
| Silver | ≥ $10 paid | $0.00012/check (1.2x) | Priority assignment |
| Gold | ≥ $50 paid | $0.00015/check (1.5x) | High-value tasks |
| Platinum | ≥ $200 paid | $0.0002/check (2x) | Enterprise tasks, first pick |
Reputation is computed from BlockRun's own GCS logs (LLM call history per wallet), refreshed daily. Cached in DB per wallet — not queried on every request.
---
Worker Availability Reality
ClawRouter users are developers on their own machines, not 24/7 server operators.
Estimated concurrent online workers:
Peak (US + EU working hours): 200–300
Average (any time): 100–150
Off-peak (US overnight): 30–50
Task Redundancy (not consensus)
Each task is assigned to 3 workers per cycle. First valid submission wins and gets paid. The other 2 are discarded. This is purely for redundancy — not to verify each other's work. Workers have no incentive to cheat (work is trivially cheap, reward is tiny).
task_br_health sent to:
worker_042 (US-West) → submits 200, 45ms ✅ WINS, gets paid
worker_731 (EU) → submits 200, 120ms → discarded
worker_209 (US-East) → submits 200, 52ms → discarded
Task queue logic: Return tasks wherenow - lastSuccessfulCheck > targetInterval. Workers naturally fill gaps. No orphaned assignments.Standard/Premium tiers: BlockRun runs always-on backup workers to guarantee baseline coverage.
---
Payment Architecture
Full Money Flow
Buyer wallet
──$0.001/check──▶ BlockRun (x402, payTo = BlockRun address)
↓
DB: worker_credits[address] += rewardMicros
↓ (when credits ≥ $0.01)
BlockRun treasury
──$0.01──▶ Worker wallet
x402 (payTo = worker address)
+ 0 ETH calldata log tx on Base
↓
BlockRun keeps the spread ($0.009 per $0.01 payout)
payToWhy x402 Both Directions
x402 is EIP-3009 TransferWithAuthorization. The
field is just an address — change it to the worker's wallet:from: buyer, to: blockrunWallet- Buyer → BlockRun:
from: treasury, to: workerWallet
- BlockRun → Worker:/settleSame CDP facilitator
endpoint. No new payment infrastructure.Payout Batching
Do NOT pay $0.0001 per check immediately:
- Accumulate credits in DB per worker
- Pay when worker reaches $0.01 threshold (~100 checks)
- Base L2 gas ≈ $0.0001/tx → gas overhead = 1% of payout---
Storage Architecture (Dual-Write)
Every payout writes to two places simultaneously:
| Layer | Purpose | Data |
| ----------------- | ------------------------------------------------ | -------------------- |
| DB | Fast reads, operational queries, pending credits | All tables below |
| Base calldata | Immutable audit trail, independent verification | Payout receipts only |DB Schema
/ Detailed source-code truncated for AI context efficiency. /
Blockchain Calldata (on every payout)
A separate 0 ETH transaction broadcast alongside the USDC transfer:
// to: BLOCKRUN_LOG_ADDRESS (BlockRun's own address)
// value: 0 ETH
// calldata: encoded payout receipt
{
v: 1,
type: "worker_payout",
worker: "0x...",
amountMicros: 10000,
resultCount: 100,
resultsHash: "0xabc...", // SHA256 of result IDs
payoutId: "uuid",
payoutTxHash: "0x...",
ts: 1234567890
}
Independent verification: Anyone can scan Base for txs toBLOCKRUN_LOG_ADDRESS, decode calldata, and verify all worker payouts without trusting BlockRun's DB.---
Trust & Verification Model
Workers are existing paying ClawRouter users. The work is trivially cheap:
const res = await fetch(url, { signal: AbortSignal.timeout(10000) });
return { status: res.status, latency: Date.now() - start };
Cost to do the work: ~10ms, $0.CLAWROUTER_WORKER=1
Cost to fake: write cheating code, risk ban.
Reward either way: $0.0001.No rational incentive to cheat. Simple EIP-191 signature proves identity. That's sufficient.
Future (V2): nonce injection for BlockRun-owned endpoints, spot-check verification for third-party.
---
All Design Decisions
| Question | Decision |
| -------------------------- | ------------------------------------------------- |
| 3-worker consensus needed? | No — redundancy only, not verification |
| How to pay workers? | x402 reversed payTo, same CDP facilitator |
| Workers always online? | No — 100-150 avg, 3x redundancy compensates |
| Verify work authenticity? | Trust-based (paying users, no incentive to cheat) |
| Track credits per worker? | DB (primary) + Base calldata (audit) |
| Pay per check on-chain? | No — batch at $0.01 threshold, 1% gas overhead |
| Calldata mechanism? | Separate 0 ETH tx to BLOCKRUN_LOG_ADDRESS |
| Reputation source? | BlockRun's own GCS logs, no third-party |
| DB choice? | TBD — any Postgres-compatible works |---
Go-to-Market
Phase 1: Supply Side (Month 1–2)
- Ship
to 1,000 existing userssrc/worker/types.ts
- Pilot: 3 hardcoded tasks monitoring BlockRun's own endpoints
- Target: 50+ active workers, end-to-end payment verified on-chainPhase 2: First Buyers (Month 2–3)
- Buyer dashboard — register any endpoint, choose SLA tier
- First 10 customers: 30-day free trial
- Publish node map (marketing)
- Target: 5 paying customers, $2,500 MRRPhase 3: Scale (Month 3–6)
- Standard/Premium tiers with BlockRun-backed SLA
- "State of Web3 Uptime" report from aggregated data
- Coinbase/Base ecosystem partnership
- Target: $15,000 MRR---
Success Metrics
| Metric | Month 3 | Month 6 |
| --------------------- | ---------- | ---------- |
| Active workers | 50 | 200 |
| Monitored endpoints | 25 | 150 |
| Paying customers | 5 | 30 |
| MRR | $2,500 | $15,000 |
| USDC to workers/month | $250 | $1,500 |
| On-chain payout txs | verifiable | verifiable |---
Open Questions (V2)
1. Geographic routing — assign tasks by region
2. Buyer dashboard — web UI for endpoint config
3. Nonce injection — cryptographic proof for owned endpoints
4. Worker reputation UI — let workers see their tier and earnings
5. Legal — liability for uptime certificates in regulatory filings---
---
Implementation Plan
Files to Touch
ClawRouter
| File | Action |
| ---------------------- | ------ |
|| CREATE |src/worker/checks.ts
|| CREATE |src/worker/index.ts
|| CREATE |src/index.ts
|| MODIFY |src/lib/worker-tasks.tsBlockRun
| File | Action |
| ---------------------------------------- | ------ |
|| CREATE |src/lib/worker-credits.ts
|| CREATE |src/lib/worker-payouts.ts
|| CREATE |src/lib/worker-reputation.ts
|| CREATE |src/app/api/v1/worker/tasks/route.ts
|| CREATE |src/app/api/v1/worker/results/route.ts
|| CREATE |.envEnvironment Variables
ClawRouter
/ shell:
CLAWROUTER_WORKER=1
WORKER_REGION=US-West # optional
BLOCKRUN_API_BASE=https://blockrun.ai/api # override for local dev
BlockRun.env.local:
WORKER_PAYOUT_WALLET_KEY=0x... # treasury signing key — never commit
BLOCKRUN_LOG_ADDRESS=0x... # BlockRun's own address for calldata logs
DATABASE_URL=postgres://... # your DB
---src/worker/types.tsTask 1: ClawRouter — Types
File:
export interface WorkerTask {
id: string;
type: "http_check";
url: string;
expectedStatus: number;
timeoutMs: number;
rewardMicros: number;
region?: string;
}
export interface WorkerResult {
taskId: string;
workerAddress: string;
timestamp: number;
success: boolean;
responseTimeMs: number;
statusCode?: number;
error?: string;
// EIP-191 signature of JSON.stringify({ taskId, workerAddress, timestamp, success })
signature: string;
}
export interface WorkerStatus {
address: string;
completedTasks: number;
totalEarnedMicros: number;
lastPollAt?: number;
busy: boolean;
}
Steps:mkdir src/worker && touch src/worker/types.ts1.
— paste content abovenpx tsc --noEmit
2.— expect no errorsgit add src/worker/types.ts && git commit -m "feat(worker): add types"
3.src/worker/checks.ts---
Task 2: ClawRouter — HTTP Check Executor
File:
import type { WorkerTask } from "./types.js";
export async function executeHttpCheck(task: WorkerTask): Promise<{
success: boolean;
responseTimeMs: number;
statusCode?: number;
error?: string;
}> {
const start = Date.now();
try {
const res = await fetch(task.url, {
method: "GET",
signal: AbortSignal.timeout(task.timeoutMs),
redirect: "follow",
headers: { "User-Agent": "BlockRun-Worker/1.0" },
});
return {
success: res.status === task.expectedStatus,
responseTimeMs: Date.now() - start,
statusCode: res.status,
};
} catch (err) {
const isTimeout =
err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");
return {
success: false,
responseTimeMs: Date.now() - start,
error: isTimeout
? Timeout after ${task.timeoutMs}ms
: err instanceof Error
? err.message
: String(err),
};
}
}
// Must produce identical JSON on both sides for signature verification
export function buildSignableMessage(params: {
taskId: string;
workerAddress: string;
timestamp: number;
success: boolean;
}): string {
return JSON.stringify({
taskId: params.taskId,
workerAddress: params.workerAddress,
timestamp: params.timestamp,
success: params.success,
});
}
Steps:src/worker/checks.ts1. Create
— paste abovenpx tsc --noEmit
2.git add src/worker/checks.ts && git commit -m "feat(worker): add HTTP check executor"
3.src/worker/index.ts---
Task 3: ClawRouter — WorkerNode Class
File:
/ Detailed source-code truncated for AI context efficiency. /
Steps:src/worker/index.ts1. Create
— paste abovenpx tsc --noEmit
2.git add src/worker/index.ts && git commit -m "feat(worker): add WorkerNode class"
3.src/index.ts---
Task 4: ClawRouter — Wire Worker Mode
File:
— modifystartProxyInBackground().Find this block (~line 423):
setActiveProxy(proxy);
activeProxyHandle = proxy;
Add immediately after:const workerMode = process.env.CLAWROUTER_WORKER === "1" || process.argv.includes("--worker");
if (workerMode) { 1. Edit --- Run this migration against your DB (Postgres-compatible): 1. Run migration against dev DB --- File: 1. Create --- File: 1. Create --- File: 1. Create --- File: 1. Create --- File:
const { WorkerNode } = await import("./worker/index.js");
const worker = new WorkerNode(walletKey, address);
worker.startPolling();
api.logger.info([Worker] Mode active — polling every 30s, wallet: ${address});
}Steps:src/index.tsnpx tsc --noEmit
2. git add src/index.ts && git commit -m "feat(worker): activate WorkerNode on CLAWROUTER_WORKER=1"
3. Task 5: BlockRun — DB Schema
/ Detailed source-code truncated for AI context efficiency. /Steps:git commit -m "feat(worker): add DB migration"
2. Verify all 4 tables exist
3. src/lib/worker-tasks.tsTask 6: BlockRun — Task Registry
/ Detailed source-code truncated for AI context efficiency. /Steps:src/lib/worker-tasks.tsnpx tsc --noEmit
2. git commit -m "feat(worker): task registry with 3-worker redundancy"
3. src/lib/worker-credits.tsTask 7: BlockRun — Credit Ledger
/ Detailed source-code truncated for AI context efficiency. /Steps:src/lib/worker-credits.ts@/lib/db
2. Wire your actual DB client at (swap the import)npx tsc --noEmit
3. git commit -m "feat(worker): credit ledger with atomic upsert"
4. src/lib/worker-reputation.tsTask 8: BlockRun — Reputation Module
/ Detailed source-code truncated for AI context efficiency. /Steps:src/lib/worker-reputation.tscomputeTotalPaidFromGCS
2. is a stub for pilot — implement GCS aggregation in V2git commit -m "feat(worker): reputation module with daily cache"
3. src/lib/worker-payouts.tsTask 9: BlockRun — Payout Module
/ Detailed source-code truncated for AI context efficiency. /Steps:src/lib/worker-payouts.tsnetwork-config.ts
2. Check — add chainId: 8453 / 84532 if missingnpx tsc --noEmit
3. git commit -m "feat(worker): payout module with x402 + calldata audit log"
4. src/app/api/v1/worker/tasks/route.tsTask 10: BlockRun — GET /api/v1/worker/tasks
import { NextRequest, NextResponse } from "next/server";
import { getTasksForWorker, markAssigned } from "@/lib/worker-tasks";
export const runtime = "nodejs";
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const address = searchParams.get("address");
const region = searchParams.get("region") ?? undefined;
if (!address?.startsWith("0x")) {
return NextResponse.json({ error: "address required" }, { status: 400 });
}
const tasks = getTasksForWorker(address, region);
markAssigned(
tasks.map((t) => t.id),
address,
);
return NextResponse.json(tasks);
}
Steps:mkdir -p src/app/api/v1/worker/tasks && touch route.ts1.
curl "http://localhost:3000/api/v1/worker/tasks?address=0x000..."
2. Test:git commit -m "feat(worker): GET /api/v1/worker/tasks"
3. Expect: JSON array with up to 3 pilot tasks
4.src/app/api/v1/worker/results/route.ts---
Task 11: BlockRun — POST /api/v1/worker/results
File:
/ Detailed source-code truncated for AI context efficiency. /
Steps:mkdir -p src/app/api/v1/worker/results && touch route.ts1.
npx tsc --noEmit
2.git commit -m "feat(worker): POST /api/v1/worker/results with sig verify, DB write, payout trigger"
3.---
End-to-End Test
1. Start BlockRun locally
cd /Users/vickyfu/Documents/blockrun-web/blockrun
pnpm dev
2. Verify tasks endpoint
curl "http://localhost:3000/api/v1/worker/tasks?address=0x0000000000000000000000000000000000000001"
→ JSON array with 3 tasks
3. Start ClawRouter in worker mode (pointed at localhost)
cd /Users/vickyfu/Documents/blockrun-web/ClawRouter
CLAWROUTER_WORKER=1 BLOCKRUN_API_BASE=http://localhost:3000/api npx openclaw gateway start
4. Watch for logs:
[Worker] Starting — 0x... region=unknown
[Worker] Executing 3 task(s)
[Worker] ✓ 3 result(s) accepted, earned $0.000300 USDC
5. Check DB: worker_results and worker_credits tables populated
6. At $0.01 threshold (~100 checks): worker_payouts row created, USDC transferred
7. Check Base explorer: calldata log tx visible on BLOCKRUN_LOG_ADDRESS
``
---