The smart-routing SDK for 70 models — every request goes to the cheapest model that can handle it, paid per-request in USDC. No API keys. No subscriptions. No vendor lock-in.
Website · Models & Pricing · ClawRouter · Python SDK · Telegram
import { LLMClient } from '@blockrun/llm';
const client = new LLMClient();
const r = await client.smartChat('Prove step by step that the sum of two odd integers is even.');
console.log(r.model); // 'deepseek/deepseek-v4-pro' — the right model, not the $75/M flagship
console.log(r.routing.savings); // 0.96 — this exact request cost 96% less than pinning the baseline
console.log(r.response); // the proof88% cheaper than pinning Claude Opus 5 across a realistic workload on the default auto profile, 98% on eco — and eco's first stop is the free tier, so simple requests cost $0.00 outright. Not an "up to" figure: the baseline, workload mix, and token ratio are published in savings-mix.json so anyone can recompute the claim. Details in Smart Routing.
- 🧠 Smart routing that pays for itself — the bundled Router Core V3 engine (shared with ClawRouter) classifies every request locally in <1ms across 15 dimensions and routes to the cheapest capable model. The main event.
- 🆓 5 genuinely free models — NVIDIA-hosted, $0 in and out, incl. 1M-context DeepSeek V4 Flash and a multimodal Nemotron. No rate-limit gimmicks.
- 🔐 No API keys — your wallet signature is your authentication. No accounts, no dashboards, no key rotation.
- 💸 Pay per request in USDC — x402 micropayments on Base or Solana. $5 covers thousands of requests; agents can pay their own way.
- 🛡️ Automatic failover — transient errors (timeouts, 429, 5xx) walk the router's ranked fallback chain instead of failing your request.
- ⚡ Streaming, OpenAI & Anthropic compat — drop-in
chat.completions/messageslayers, SSE streaming, strict TypeScript. - 🎨 Beyond chat — image, video, music, speech, live search, prediction markets, crypto data, and 40-chain RPC through the same wallet.
| OpenAI SDK | OpenRouter | LiteLLM | @blockrun/llm | |
|---|---|---|---|---|
| Cost routing | ✗ one vendor | Manual selection | Manual selection | Automatic — 88% cheaper |
| Models | GPT only | 200+ | 100+ (BYO keys) | 70, one wallet |
| Free tier | ✗ | Rate-limited | ✗ | 5 models, no signup |
| Auth | API key | Account + API key | Your API keys | Wallet signature |
| Payment | Card + invoice | Credit card | BYO keys | USDC per-request |
| Agent-ready | ✗ | ✗ | ✗ | ✓ — agents fund their own wallet |
npm install @blockrun/llm # Base / EVM payments — smart routing included, nothing else neededSolana payments — two more optional peers
npm install @blockrun/llm @solana/web3.js @solana/spl-tokenWhy they are not automatic: @solana/spl-token pulls in bigint-buffer, whose
native toBigIntLE() has an unpatched buffer overflow
(GHSA-3gc7-fjrx-p6mg) with no
fixed release anywhere. As an optional dependency it landed in the lockfile of
every consumer, including projects that only ever pay on Base. As an optional
peer it reaches only the projects that ask for Solana. Calling a Solana path
without them throws an error naming the exact install command.
Supported chains — Base (primary), Base Sepolia, Solana
| Chain | Network | Payment | Status |
|---|---|---|---|
| Base | Base Mainnet (Chain ID: 8453) | USDC | Primary |
| Base Testnet | Base Sepolia (Chain ID: 84532) | Testnet USDC | Development |
| Solana | Solana Mainnet | USDC (SPL) | New |
Protocol: x402 v2 (CDP Facilitator)
import { LLMClient } from '@blockrun/llm';
const client = new LLMClient(); // Uses BASE_CHAIN_WALLET_KEY (never sent to server)
// Recommended: let the router pick the cheapest capable model
const result = await client.smartChat('Hello!');
// Or pin a model yourself
const response = await client.chat('openai/gpt-4o', 'Hello!');That's it. The SDK handles x402 payment automatically — and smartChat()
keeps the bill down on every request. The router is bundled: no extra
package to install.
Want to kick the tires before funding a wallet? Route to BlockRun's free NVIDIA tier:
import { LLMClient } from '@blockrun/llm';
const client = new LLMClient(); // Wallet still required for signing, but $0 charged
// Option 1: call a free model directly
const reply = await client.chat('nvidia/step-3.7-flash', 'Explain x402 in 1 sentence');
// Option 2: let the smart router pick — 'eco' ranks the free NVIDIA tier first
const result = await client.smartChat('What is 2+2?', { routingProfile: 'eco' });
console.log(result.model); // 'nvidia/step-3.7-flash' ($0 — verified live)
console.log(result.response); // '4'
console.log(result.routing.savings); // 1 (100%)There is no free routing profile in smartChat() — routingProfile accepts
'eco' | 'auto' | 'premium'. (ClawRouter's /model free is a feature of its
own proxy, not of this SDK's router options.) For guaranteed $0, pin a
nvidia/* model; for smart-routed $0-first, use eco.
Available free models (input + output both $0, all NVIDIA-hosted, from the live /v1/models catalog, last refreshed 2026-08-12):
| Model ID | Context | Best For |
|---|---|---|
nvidia/nemotron-3-nano-omni-30b-a3b-reasoning |
256K | Multimodal reasoning — text + images + video + audio (ChartQA 90.3, DocVQA 95.6) |
nvidia/mistral-nemotron |
131K | Mistral × NVIDIA instruction model — fast (~0.2s), strong instruction following |
nvidia/step-3.7-flash |
131K | StepFun Step 3.7 Flash — fast lightweight reasoning |
nvidia/nemotron-nano-9b-v2 |
131K | Compact + fast (~0.7s), good for high-volume light tasks |
nvidia/nemotron-nano-12b-v2-vl |
131K | Vision-language — accepts images, compact + fast |
nvidia/gpt-oss-120b |
128K | OpenAI open-weight 120B. Hidden from /v1/models for privacy but direct calls still work |
nvidia/gpt-oss-20b |
128K | OpenAI open-weight 20B. Hidden from /v1/models but direct calls still work |
Privacy note:
nvidia/gpt-oss-120bandnvidia/gpt-oss-20bare hidden from/v1/modelsbecause NVIDIA's free build.nvidia.com tier reserves the right to use prompts/outputs for service improvement. Direct calls by full model ID still work — opt in only when your data isn't sensitive.
import { SolanaLLMClient } from '@blockrun/llm';
// SOLANA_WALLET_KEY env var (bs58-encoded Solana secret key)
const client = new SolanaLLMClient();
const response = await client.chat('openai/gpt-4o', 'gm Solana');
console.log(response);Set SOLANA_WALLET_KEY to your bs58-encoded Solana secret key. Payments are automatic via x402 — your key never leaves your machine.
Let the SDK automatically pick the cheapest capable model for each request — 88% cheaper than pinning Claude Opus 5 for the same traffic on auto, 98% on eco.
Not an "up to" figure. The baseline, the workload mix and the token ratio are
published in savings-mix.json,
priced against the live catalog, so anyone can recompute the claim and get the
same answer.
Smart routing is powered by the product-neutral
@blockrun/router-core V3 engine —
the same deterministic portfolio router that drives
ClawRouter. It is bundled into
this SDK: no separate router package to install, and routing runs 100%
locally with zero external calls.
Three ways to use it:
// 1. smartChat() — one-line routed chat
const result = await client.smartChat('What is 2+2?');
// 2. smartChatCompletion() — full agent/tool conversations, routed
const agent = await client.smartChatCompletion(messages, { tools, toolChoice: 'auto' });
// 3. blockrun/auto | blockrun/eco | blockrun/premium — model aliases accepted
// by chat(), chatCompletion(), and chatCompletionStream() on both chains
const reply = await client.chatCompletion('blockrun/auto', messages);
// Inspect a decision without paying for anything
const decision = await client.route('Prove the Riemann hypothesis');The aliases are resolved locally by LLMClient, SolanaLLMClient, and the
OpenAI-compat layer. The Anthropic-compat layer proxies straight to the
gateway's /v1/messages and does not resolve them — pass a concrete
model id there.
import { LLMClient } from '@blockrun/llm';
const client = new LLMClient();
// Auto-routes to cheapest capable model
const result = await client.smartChat('What is 2+2?');
console.log(result.response); // '4'
console.log(result.model); // 'moonshot/kimi-k2.5' (cheap, fast)
console.log(`Saved ${(result.routing.savings * 100).toFixed(0)}%`); // 'Saved 88%'
// Complex reasoning task -> routes to reasoning model
const complex = await client.smartChat('Prove the Riemann hypothesis step by step');
console.log(complex.model); // 'xai/grok-4-1-fast-reasoning'
// Inspect how the request was classified and ranked (Router v3.4 portfolio).
console.log(complex.routing.method); // 'portfolio'
console.log(complex.routing.taskType); // 'reasoning'
console.log(complex.routing.candidates); // ranked, capability-eligible models
// Inspect the fallback chain SmartChat will walk on transient errors.
console.log(complex.routing.fallbacks); // ['anthropic/claude-opus-4.7', ...]smartChat() populates a fallback chain from the portfolio ranking and
chat() / chatCompletion() walk it automatically when the primary model
returns a transient error — timeouts, network failures, 429 rate limits, or
5xx responses (502/503/504/522/524). Other 4xx errors and PaymentError
propagate immediately so wallet / auth issues surface fast.
// Manually pass a fallback chain to chat() / chatCompletion()
const reply = await client.chat('nvidia/step-3.7-flash', 'hello', {
fallbackModels: ['nvidia/mistral-nemotron', 'nvidia/gpt-oss-120b'],
});
// If step-3.7-flash times out, the SDK retries against the next model
// and logs each hop to stderr: "[@blockrun/llm] <from> -> <to> (...)".| Profile | Strategy | Savings vs Opus 5 | Best For |
|---|---|---|---|
eco |
Cheapest capable model — ranks the 5-model free NVIDIA tier first | 98% | Cost-sensitive production, zero-cost testing |
auto |
Best balance of cost/quality (default) | 88% | General use |
premium |
Top-tier models (OpenAI, Anthropic) | 0% | Quality-critical tasks |
For guaranteed $0, call a nvidia/* model directly with chat() — see
Try It Free. ClawRouter's /model free
profile belongs to its own proxy; smartChat()'s options are the three above.
// Use premium models for complex tasks
const result = await client.smartChat(
'Write production-grade async TypeScript code',
{ routingProfile: 'premium' }
);
console.log(result.model); // 'anthropic/claude-opus-4.7'flowchart LR
A["prompt"] --> B["classify locally<br/>15 dimensions, <1ms"]
B --> C["hard filters<br/>tools · vision · context ·<br/>structured output"]
C --> D["rank portfolio<br/>quality · cost · speed ·<br/>reliability"]
D --> E["cheapest capable model<br/>+ ranked fallback chain"]
E --> F["x402 USDC payment<br/>for this request only"]
F --> G["response<br/>+ full routing metadata"]
Since ClawRouter v0.12.242, Auto uses the deterministic Router v3.4 portfolio strategy: it classifies the task shape locally across
15 dimensions(token count, code presence, reasoning markers, technical/creative terms,
agentic patterns, …), enforces tool / vision / structured-output / context
constraints as hard filters, then ranks an ordered candidate portfolio.
The winner becomes routing.model; the rest surface as routing.candidates
and feed SmartChat's transient-error fallback chain. Routing stays 100% local
and deterministic — <1ms, no extra model call, no network hop.
Classification still maps to one of four tiers (routing.tier). Each
tier × profile has a designated primary (what the rules strategy —
routing.method: 'rules', the rollback lever — routes to directly, and what
anchors the portfolio's candidate pool):
| Tier | Example Tasks | ECO | AUTO | PREMIUM |
|---|---|---|---|---|
| SIMPLE | "What is 2+2?", definitions | free/gpt-oss-120b † (FREE) | gemini-2.5-flash ($0.30/$2.50) | kimi-k2.7 † ($0.95/$4.00) |
| MEDIUM | Code snippets, explanations | gemini-3.1-flash-lite ($0.25/$1.50) | kimi-k2.7 ($0.95/$4.00) | gpt-5.3-codex ($1.75/$14.00) |
| COMPLEX | Architecture, long documents | gemini-3.1-flash-lite ($0.25/$1.50) | gemini-3.1-pro ($2/$12) | claude-fable-5 ($10/$50) |
| REASONING | Proofs, multi-step reasoning | grok-4-1-fast-reasoning † ($0.20/$0.50) | grok-4-1-fast-reasoning † ($0.20/$0.50) | claude-sonnet-4.6 ($3/$15) |
† Withheld from /v1/models — the router still calls it by direct ID, but you
will not find it on the public pricing page. The published savings claim is
priced on visible models only.
This table mirrors ClawRouter's tier configs at the version this SDK pins; the ClawRouter README is the live source of truth as models and prices move.
Every smartChat() result carries the full decision on result.routing
(type RoutingDecision) — enough to log, audit, or replay why a model was
picked:
| Field | Description |
|---|---|
model |
Selected model id (same as result.model) |
method |
'portfolio' (the Auto default), 'rules' (rollback strategy), or 'llm' |
tier |
Task tier: 'SIMPLE', 'MEDIUM', 'COMPLEX', or 'REASONING' |
taskType |
Portfolio task classification: 'chat', 'extraction', 'code_edit', 'code_agent', 'tool_agent', 'debug', 'reasoning', 'reasoning_math', 'long_context', 'vision', … |
candidates |
Ordered, capability-eligible models ranked by the portfolio router; the first entry is model |
candidateScores |
Per-candidate score breakdown (quality / cost / speed / reliability), ordered with candidates |
fallbacks |
The chain chat() walks on transient errors (timeout / network / 429 / 5xx) — candidates minus the primary, with ClawRouter's proxy-namespace free/* ids mapped to their nvidia/* gateway ids (SDK-computed) |
savings |
0–1 fraction saved vs the premium baseline |
costEstimate / baselineCost |
Estimated cost of the pick vs that baseline, in USD |
confidence |
Sigmoid-calibrated classifier confidence, 0–1 |
routerVersion |
'v3-portfolio' or 'v2-rules' |
profile |
Routing profile applied: 'auto', 'eco', 'premium', or 'agentic' |
reasoning |
Human-readable explanation of the decision |
tierConfigs |
The tier → primary/fallback map the decision was made against |
RoutingDecision, RoutingProfile, RoutingTier, RoutingTaskType,
RoutingTierConfig, SmartChatCompletionOptions, and
SmartChatCompletionResponse are exported from @blockrun/llm. They are
derived from
@blockrun/router-core, pinned
to a reviewed immutable commit, and shipped inlined in this SDK's
declaration files and runtime bundle — you install nothing extra to route
or to typecheck.
- ClawRouter — the router itself: OpenClaw plugin, standalone proxy for Cursor / continue.dev / any OpenAI-compatible client, Telegram integration
- Routing profiles in depth — ECO / AUTO / PREMIUM details
- How the routing engine works — the classifier, dimension by dimension
- Router benchmark — sub-1ms routing across the catalog
- ClawRouter vs OpenRouter — head-to-head comparison
@blockrun/router-core— the deterministic routing engine both share
Pay for AI calls with Solana USDC via sol.blockrun.ai:
import { SolanaLLMClient } from '@blockrun/llm';
// SOLANA_WALLET_KEY env var (bs58-encoded Solana secret key)
const client = new SolanaLLMClient();
// Or pass key directly
const client2 = new SolanaLLMClient({ privateKey: 'your-bs58-solana-key' });
// Same API as LLMClient
const response = await client.chat('openai/gpt-4o', 'gm Solana');
console.log(response);
// Live Search with Grok (Solana payment)
const tweet = await client.chat('xai/grok-3-mini', 'What is trending on X?', { search: true });Setup:
- Export your Solana wallet key:
export SOLANA_WALLET_KEY="your-bs58-key" - Fund with USDC on Solana mainnet
- That's it — payments are automatic via x402
Supported endpoint: https://sol.blockrun.ai/api
Payment: Solana USDC (SPL, mainnet)
No API keys, no subscription. You hold USDC in your own wallet, and every request pays for itself with an on-chain micropayment. Two phases:
You only do this when your balance runs low. Three ways to get USDC into your wallet:
-
(a) Buy with a card (Base USDC). Call the new
onramp()method to mint a one-time Coinbase Onramp link, then open the returnedpay.coinbase.comURL — pay by card/bank in 60+ fiat currencies and the USDC lands in your wallet. The call itself is free. Onramp is Base-only (buying USDC with a card always lands Base USDC), and the funding address must equal your signing wallet:const { url } = await client.onramp(client.getWalletAddress()); console.log(`Fund your wallet: ${url}`); // single-use, expires ~5 min — mint at click time
-
(b) Transfer existing USDC. Send USDC you already hold to your wallet address (
client.getWalletAddress()). On Base, send Base USDC; on Solana (SolanaLLMClient), send Solana SPL USDC. -
(c) Skip funding entirely. Use the free NVIDIA models (e.g.
nvidia/step-3.7-flash) — every call is $0, no balance required.
$5 of USDC covers thousands of paid requests. Check your balance any time:
const balance = await client.getBalance(); // USDC on Base
console.log(`Balance: $${balance.toFixed(2)} USDC`);You just call e.g. client.chat(...) — the payment is invisible:
- You send a request to BlockRun's API.
- The gateway returns 402 Payment Required with the price.
- The SDK signs a USDC payment locally (EIP-712) — on Base for
LLMClient, on Solana forSolanaLLMClient— using your wallet key. - The request is retried automatically with the payment proof.
- The gateway settles on-chain and returns the AI response.
One call, no separate pay step. Free NVIDIA models settle at $0 (no payment signed).
import { getCostSummary } from '@blockrun/llm';
const spent = client.getSpending(); // this session
console.log(`Spent $${spent.totalUsd.toFixed(4)} across ${spent.calls} calls`);
const summary = getCostSummary(); // across sessions (~/.blockrun/data/costs.jsonl)
console.log(`Lifetime: $${summary.totalUsd.toFixed(2)} over ${summary.calls} calls`);Every paid request is a real on-chain USDC transfer — look up your wallet address on Basescan (or a Solana explorer) to verify each settlement independently.
Non-custodial by design: your private key never leaves your machine — it is only used for local signing, and no funds are ever held by BlockRun.
Starting in 2.5.0, the SDK ships a single BlockrunClient that speaks to
every BlockRun endpoint over x402. New API surfaces are intended to be
distributed as Claude Code skills
that drive this primitive — no SDK release required to add an endpoint.
import { BlockrunClient } from '@blockrun/llm';
const br = new BlockrunClient();
// Sync GET — Surf market price (Tier 1, $0.001)
const btc = await br.get('/v1/surf/market/price', { symbol: 'BTC' });
// Sync POST — raw on-chain SQL (Tier 3, $0.020)
const rows = await br.post('/v1/surf/onchain/sql', {
query: 'SELECT block_number FROM ethereum.blocks ORDER BY block_number DESC LIMIT 1',
});
// Submit + poll — long-running video gen (settled only on completion)
const video = await br.poll('/v1/videos/generations', {
model: 'xai/grok-imagine-video',
prompt: 'a red apple spinning',
});
// Streaming SSE — chat completions
for await (const chunk of br.stream('/v1/chat/completions', {
model: 'anthropic/claude-sonnet-4-6',
messages: [{ role: 'user', content: 'Hi' }],
stream: true,
})) {
process.stdout.write(chunk?.choices?.[0]?.delta?.content ?? '');
}Four call shapes cover every endpoint type:
get<T>(path, params?)— synchronous GET (price, ranking, list, news)post<T>(path, body?)— synchronous POST (on-chain SQL, search)poll<T>(path, body?, { budgetMs, intervalMs })— submit + poll (image, video, music, voice)stream<T>(path, body?)— async iterator over SSE chunks (chat)
The per-API client classes (LLMClient, ImageClient, VideoClient,
PortraitClient, VoiceClient, MusicClient, SearchClient, RpcClient,
PriceClient, SurfClient) all remain — they will be soft-deprecated in 2.6 (rewritten as
shims over BlockrunClient) and removed in 3.0.
Released 2026-04-23 — first fully retrained base since GPT-4.5. 1M context, 128K output, native agent + computer use.
| Model | Input Price | Output Price |
|---|---|---|
openai/gpt-5.5 |
$5.00/M | $30.00/M |
| Model | Input Price | Output Price |
|---|---|---|
openai/gpt-5.4 |
$2.50/M | $15.00/M |
openai/gpt-5.4-pro |
$30.00/M | $180.00/M |
openai/gpt-5.4-nano |
$0.20/M | $1.25/M |
| Model | Input Price | Output Price |
|---|---|---|
openai/gpt-5.3 |
$1.75/M | $14.00/M |
openai/gpt-5.2 |
$1.75/M | $14.00/M |
openai/gpt-5-mini |
$0.25/M | $2.00/M |
openai/gpt-5.2-pro |
$21.00/M | $168.00/M |
openai/gpt-5.2-codex |
$1.75/M | $14.00/M |
| Model | Input Price | Output Price |
|---|---|---|
openai/gpt-4.1 |
$2.00/M | $8.00/M |
openai/gpt-4.1-mini |
$0.40/M | $1.60/M |
openai/gpt-4.1-nano |
$0.10/M | $0.40/M |
openai/gpt-4o |
$2.50/M | $10.00/M |
openai/gpt-4o-mini |
$0.15/M | $0.60/M |
| Model | Input Price | Output Price |
|---|---|---|
openai/o1 |
$15.00/M | $60.00/M |
openai/o3 |
$2.00/M | $8.00/M |
openai/o3-mini |
$1.10/M | $4.40/M |
openai/o4-mini |
$1.10/M | $4.40/M |
| Model | Input Price | Output Price | Context | Notes |
|---|---|---|---|---|
anthropic/claude-fable-5 |
$10.00/M | $50.00/M | 1M | Mythos-class flagship above Opus — always-on thinking, 128K output, fallback claude-opus-4.8. Alias: claude-fable-5 |
anthropic/claude-opus-4.8 |
$5.00/M | $25.00/M | 1M | Flagship — agentic coding + adaptive thinking, 128K output |
anthropic/claude-opus-4.7 |
$5.00/M | $25.00/M | 1M | Agentic coding + adaptive thinking, 128K output |
anthropic/claude-opus-4.6 |
$5.00/M | $25.00/M | 200K | Hidden but still callable — kept as in-family hot-swap fallback |
anthropic/claude-opus-4.5 |
$5.00/M | $25.00/M | 200K | |
anthropic/claude-opus-4 |
$15.00/M | $75.00/M | 200K | |
anthropic/claude-sonnet-4.6 |
$3.00/M | $15.00/M | 200K | Best for reasoning/instructions |
anthropic/claude-sonnet-4 |
$3.00/M | $15.00/M | 200K | |
anthropic/claude-haiku-4.5 |
$1.00/M | $5.00/M | 200K |
| Model | Input Price | Output Price |
|---|---|---|
google/gemini-3.1-pro |
$2.00/M | $12.00/M |
google/gemini-3.5-flash |
$0.50/M | $3.00/M |
google/gemini-3.1-flash-lite |
$0.25/M | $1.50/M |
google/gemini-3-flash-preview |
$0.50/M | $3.00/M |
google/gemini-2.5-pro |
$1.25/M | $10.00/M |
google/gemini-2.5-flash |
$0.30/M | $2.50/M |
google/gemini-2.5-flash-lite |
$0.10/M | $0.40/M |
V4 family launched 2026-04-24. DeepSeek upstream now serves the legacy
deepseek-chat / deepseek-reasoner aliases as V4 Flash non-thinking /
thinking modes. V4 Pro is the new flagship paid SKU — 1.6T MoE / 49B active,
1M context, MMLU-Pro 87.5, GPQA 90.1, SWE-bench 80.6, LiveCodeBench 93.5.
| Model | Input Price | Output Price | Context | Notes |
|---|---|---|---|---|
deepseek/deepseek-v4-pro |
$0.435/M | $0.87/M | 1M | V4 flagship — strongest open-weight reasoner. The 75% launch promo became the permanent list price after 2026-05-31 |
deepseek/deepseek-chat |
$0.14/M | $0.28/M | 1M | V4 Flash non-thinking (paid endpoint with 5MB request bodies) |
deepseek/deepseek-reasoner |
$0.20/M | $0.40/M | 1M | V4 Flash thinking (same upstream as deepseek-chat, thinking enabled by default) |
Grok 4.3 and Grok Build are resold through BlockRun's OpenRouter credit pool
(same pattern as deepseek/deepseek-v4-pro and minimax/minimax-m3). The
older Grok chat SKUs (grok-3/3-mini, grok-4-fast / 4-1-fast families,
grok-code-fast-1, grok-4-0709, grok-2-vision) are now hidden from
/v1/models — direct calls by full ID still work, but SmartChat won't
auto-pick them.
| Model | Input Price | Output Price | Context | Notes |
|---|---|---|---|---|
xai/grok-4.3 |
$1.50/M | $4.00/M | 1M | Reasoning model, vision-capable, tuned for agentic workflows |
xai/grok-build-0.1 |
$1.50/M | $3.00/M | 256K | Fast agentic coding model — interactive software-engineering workflows |
| Model | Input Price | Output Price |
|---|---|---|
moonshot/kimi-k2.6 |
$0.95/M | $4.00/M |
moonshot/kimi-k2.5 |
$0.60/M | $3.00/M |
| Model | Input Price | Output Price |
|---|---|---|
minimax/minimax-m3 |
$0.30/M | $1.20/M |
minimax/minimax-m2.7 |
$0.30/M | $1.20/M |
Free tier refreshed 2026-08-12. NVIDIA has retired (HTTP 410 end-of-life)
the entire free DeepSeek family — nvidia/deepseek-v4-flash was the last
to go — along with llama-4-maverick, the qwen3 SKUs, and the free
Mistral small/large SKUs. Retired IDs stay callable: the gateway
auto-redirects them to a healthy free model, so pinned callers still get
a 200. nvidia/gpt-oss-120b and nvidia/gpt-oss-20b remain callable by
direct ID but are hidden from /v1/models over the NVIDIA free tier's
prompt-retention terms (so SmartChat won't auto-pick them).
| Model | Input Price | Output Price | Notes |
|---|---|---|---|
nvidia/step-3.7-flash |
FREE | FREE | Fast general-purpose chat + reasoning, 131K |
nvidia/mistral-nemotron |
FREE | FREE | Fast free Mistral, 131K |
nvidia/nemotron-3-nano-omni-30b-a3b-reasoning |
FREE | FREE | 31B / 3.2B active MoE, 256K — only vision-capable free model |
nvidia/nemotron-nano-9b-v2 |
FREE | FREE | Compact fast chat, 131K |
nvidia/nemotron-nano-12b-v2-vl |
FREE | FREE | Compact vision, 131K |
nvidia/gpt-oss-120b |
FREE | FREE | Hidden from /v1/models for privacy but direct calls still work — 123 tok/s |
nvidia/gpt-oss-20b |
FREE | FREE | Hidden from /v1/models but direct calls still work — 155 tok/s |
moonshot/kimi-k2.5 |
$0.60/M | $3.00/M | Direct from Moonshot — replaces nvidia/kimi-k2.5 |
All models below have been tested end-to-end via the TypeScript SDK (Feb 2026):
| Provider | Model | Status |
|---|---|---|
| OpenAI | openai/gpt-4o-mini |
Passed |
| OpenAI | openai/gpt-5.2-codex |
Passed |
| Anthropic | anthropic/claude-opus-4.6 |
Passed |
| Anthropic | anthropic/claude-sonnet-4 |
Passed |
google/gemini-2.5-flash |
Passed | |
| DeepSeek | deepseek/deepseek-chat |
Passed |
| xAI | xai/grok-3 |
Passed |
| Moonshot | moonshot/kimi-k2.6 |
Passed |
| Model | Price |
|---|---|
openai/dall-e-3 |
$0.04-0.08/image |
openai/gpt-image-1 |
$0.02-0.04/image |
openai/gpt-image-2 |
$0.06-0.12/image (reasoning-driven, multilingual text rendering, character consistency) |
google/nano-banana |
$0.05/image |
google/nano-banana-pro |
$0.10-0.15/image |
xai/grok-imagine-image |
$0.02/image |
xai/grok-imagine-image-pro |
$0.07/image |
zai/cogview-4 |
$0.015/image |
Image editing (client.edit) via /v1/images/image2image: openai/gpt-image-1, openai/gpt-image-2, google/nano-banana, and google/nano-banana-pro. Pass a single base64 data:image/... URI to edit one image, or an array of 2–4 URIs to fuse them (e.g. a subject + a brand logo). Fusion caps: openai/* up to 4 source images, google/* up to 3. A mask cannot be combined with multiple source images.
// Multi-image fusion with Nano Banana
const fused = await client.edit(
"Place the logo on the t-shirt",
[subjectDataUri, logoDataUri],
{ model: "google/nano-banana" }
);
console.log(fused.data[0].url);| Model | Price |
|---|---|
xai/grok-imagine-video |
$0.05/sec (8s default → $0.42/clip) |
bytedance/seedance-1.5-pro |
$0.03/sec (5s default, up to 10s, 720p) |
bytedance/seedance-2.0-fast |
$0.15/sec (~60-80s gen, sweet-spot price/quality) |
bytedance/seedance-2.0 |
$0.30/sec (720p Pro) |
import { VideoClient } from '@blockrun/llm';
const client = new VideoClient();
const result = await client.generate('a red apple slowly spinning on a wooden table');
console.log(result.data[0].url); // permanent MP4 URL
console.log(result.data[0].duration_seconds); // 8
// Image-to-video
const r2 = await client.generate('the subject turns and smiles', {
imageUrl: 'https://example.com/portrait.jpg',
});
// Token360 / Seedance options (silently ignored by xAI Grok video)
const r3 = await client.generate('aerial drone shot over a snowy mountain', {
model: 'bytedance/seedance-2.0-fast',
aspectRatio: '21:9',
resolution: '1080p',
generateAudio: true, // omit to use the model's default
seed: 42,
watermark: false,
returnLastFrame: true, // useful for clip chaining
});
// First-and-last-frame interpolation (Seedance only): the model tweens
// from imageUrl (first frame) to lastFrameUrl (final frame).
// Priced identically to image-to-video.
const r4 = await client.generate('the flower blooms in golden morning light', {
model: 'bytedance/seedance-1.5-pro',
imageUrl: 'https://example.com/bud.jpg',
lastFrameUrl: 'https://example.com/bloom.jpg',
});
// Omni / multi-reference (Seedance 2.0 only): up to 9 reference images
// for character/style consistency. Cite them as "image 1", "image 2" in
// the prompt. Mutually exclusive with imageUrl / lastFrameUrl /
// realFaceAssetId.
const r5 = await client.generate(
'the character from image 1 walks through the city from image 2',
{
model: 'bytedance/seedance-2.0',
referenceImageUrls: [
'https://example.com/character.jpg',
'https://example.com/city.jpg',
],
}
);SpeechClient wraps BlockRun Voice (ElevenLabs): POST /v1/audio/speech
(OpenAI-compatible TTS), POST /v1/audio/sound-effects, and the free
GET /v1/audio/voices. TTS price scales with character count:
(chars / 1000) × model rate, minimum $0.001/request. Synthesis is
synchronous (<1s for Flash).
| Model | Price | Max Input | Notes |
|---|---|---|---|
elevenlabs/flash-v2.5 |
$0.05/1k chars | 40k chars | ~75ms latency, 32 languages (default) |
elevenlabs/turbo-v2.5 |
$0.05/1k chars | 40k chars | ~250ms latency, balanced quality |
elevenlabs/multilingual-v2 |
$0.10/1k chars | 10k chars | Long-form narration, audiobooks |
elevenlabs/v3 |
$0.10/1k chars | 5k chars | Max expressiveness, 70+ languages |
elevenlabs/sound-effects |
$0.05/generation | 1k chars | Sound effects up to 22s |
import { SpeechClient } from '@blockrun/llm';
const client = new SpeechClient();
// Text-to-speech (voice aliases: sarah, george, laura, charlie,
// river, roger, callum, harry — or any raw ElevenLabs voice_id)
const result = await client.generate('Welcome to BlockRun.', { voice: 'george' });
console.log(result.data[0].url); // audio URL (mp3 by default)
// Other formats / speed
const wav = await client.generate('Breaking news from the world of micropayments.', {
model: 'elevenlabs/v3',
responseFormat: 'wav',
speed: 1.1,
});
// Sound effects (flat $0.05/generation)
const fx = await client.soundEffect('rain on a tin roof, distant thunder');
// List voices (free, rate-limited)
const voices = await client.listVoices();PortraitClient wraps POST /v1/portrait/enroll (paid, flat $0.01 promo,
no KYC). Enroll a face image by URL and get back a Token360 asset id (ta_xxxxxx).
Pass that id as realFaceAssetId on a Seedance 2.0 video generation to keep the
same AI character across clips. Payment settles only after Token360 confirms the
enrollment, so a failed enrollment never charges your wallet. The returned
image_url is a gateway-mirrored copy of your source image (see mirrored /
source_image_url). (Real-person likeness is not supported on BlockRun —
enrolled portraits are AI characters.)
import { PortraitClient, VideoClient } from '@blockrun/llm';
const portraits = new PortraitClient();
const { asset_id } = await portraits.enroll({
name: 'Spokesperson',
imageUrl: 'https://example.com/face.jpg', // public https JPG/PNG/WEBP, ≤10 MB
});
// Reuse the same character across Seedance 2.0 clips
const video = new VideoClient();
const clip = await video.generate('she waves and smiles', {
model: 'bytedance/seedance-2.0-fast',
realFaceAssetId: asset_id,
});
console.log(clip.data[0].url);VoiceClient wraps POST /v1/voice/call (paid, $0.54/call) and
GET /v1/voice/call/{callId} (free polling) — AI-powered outbound phone
calls powered by Bland.ai. The agent dials the recipient and runs a real-time
conversation based on your task instructions. US + Canada destinations.
import { VoiceClient } from '@blockrun/llm';
const client = new VoiceClient();
// Initiate (paid $0.54)
const result = await client.call({
to: '+14155552671',
task: 'You are a friendly assistant calling to confirm a 3pm dentist appointment.',
voice: 'maya', // 'nat' | 'josh' | 'maya' | 'june' | 'paige' | 'derek' | 'florian'
max_duration: 5, // minutes (1–30)
});
console.log(result.call_id);
// Poll for transcript + recording (free)
const status = await client.getStatus(result.call_id);
console.log(status.status, status.recording_url);Bring your own caller-ID: pass from: '+14155552671' (must be a BlockRun
phone number you own; buy via /v1/phone/numbers/buy).
SearchClient wraps POST /v1/search — standalone Grok Live Search.
Pricing: $0.025/source + margin (10 sources ≈ $0.26).
import { SearchClient } from '@blockrun/llm';
const client = new SearchClient();
const result = await client.search('Latest news on x402 adoption', {
sources: ['x', 'web'],
maxResults: 10,
});
console.log(result.summary);
for (const url of result.citations ?? []) console.log(url);SurfClient exposes the full /v1/surf/* catalog — 84+ pay-per-call
endpoints across CEX/DEX market data, on-chain SQL, wallet intelligence,
prediction markets (Polymarket + Kalshi), social analytics, news, VC fund
data, and an OpenAI-compatible chat surface. Flat pricing per call:
| Tier | Price/call | Examples |
|---|---|---|
| 1 | $0.001 | /market/price, /market/ranking, /news/feed, prediction-market reads, social tweets |
| 2 | $0.005 | /exchange/depth, /exchange/klines, /wallet/detail, /search/*, /social/ranking |
| 3 | $0.020 | /onchain/sql, /onchain/query, /onchain/schema, /chat/completions |
Because the catalog is broad and evolving, the client deliberately ships a
generic get / post pair instead of 84 typed wrappers. Pass the path
(with or without the /v1/surf prefix), query params, or a JSON body —
type the response via a generic if you want.
import { SurfClient } from '@blockrun/llm';
const surf = new SurfClient();
// Tier 1 — token price ($0.001)
const btc = await surf.get('/market/price', { symbol: 'BTC' });
// Tier 2 — order book depth ($0.005)
const book = await surf.get('/exchange/depth', {
exchange: 'binance',
symbol: 'BTC-USDT',
});
// Tier 3 — raw on-chain SQL against 80+ ClickHouse tables ($0.020)
const rows = await surf.post('/onchain/sql', {
query: 'SELECT block_number FROM ethereum.blocks ORDER BY block_number DESC LIMIT 5',
});
// Typed response via generic
type Price = { symbol: string; price: number; timestamp: string };
const eth = await surf.get<Price>('/market/price', { symbol: 'ETH' });Full endpoint inventory: https://blockrun.ai/marketplace/surf.
Methods: userLookup, userInfo, followers, following, followings,
verifiedFollowers, userTweets, mentions, tweetLookup, tweetReplies,
tweetThread, search, trending, articlesRising.
PriceClient wraps the Pyth-backed market-data endpoints. Crypto, FX and
commodity are fully free (price + history + list); 12 global stock markets
and the usstock legacy alias charge $0.001 for price + history (list is
always free). Pass requireWallet: false to construct a free-only client.
import { PriceClient } from '@blockrun/llm';
const p = new PriceClient({ requireWallet: false });
const btc = await p.price('crypto', 'BTC-USD');
const eur = await p.price('fx', 'EUR-USD');
// Paid — requires a wallet
const p2 = new PriceClient();
const aapl = await p2.price('stocks', 'AAPL', { market: 'us' });
const bars = await p2.history('stocks', 'AAPL', {
market: 'us',
resolution: 'D',
from: 1700000000,
to: 1710000000,
});
const symbols = await p.listSymbols('crypto', { query: 'sol', limit: 20 });Supported StockMarket values: us, hk, jp, kr, gb, de, fr, nl, ie, lu, cn, ca.
Three passthrough families live directly on LLMClient / SolanaLLMClient:
const client = new LLMClient();
// DefiLlama — protocols / TVL / yields / prices ($0.005/call, prices $0.001)
const protocols = await client.defiProtocols();
const aave = await client.defiProtocol('aave');
const prices = await client.defiPrices(['coingecko:bitcoin', 'base:0x833589...']);
// 0x DEX — swap + gasless quotes (FREE; BlockRun takes an on-chain affiliate
// fee on executed swaps instead of x402)
const quote = await client.dexQuote({
chainId: '8453', sellToken: '0x...', buyToken: '0x...',
sellAmount: '1000000', taker: '0xYourWallet',
});
const gq = await client.dexGaslessQuote({ /* ... */ });
const res = await client.dexGaslessSubmit({ trade: { /* signed eip712 */ } });
const status = await client.dexGaslessStatus(res.tradeHash as string);
// Modal — sandboxed compute ($0.01 create CPU / $0.05 GPU, $0.001 exec)
const sb = await client.modalSandboxCreate({ image: 'python:3.11' });
const out = await client.modalSandboxExec(sb.sandbox_id as string, ['python', '-c', 'print(42)']);
await client.modalSandboxTerminate(sb.sandbox_id as string);Generic escape hatches: client.defi(path, params), client.dex(path, params, body?),
client.modal(path, body).
RpcClient wraps POST /v1/rpc/{network} — standard JSON-RPC 2.0 access to
Arbitrum, Optimism, Avalanche, Bitcoin, Sui, and more; powered by Tatum's RPC gateway). No API key, no per-chain endpoints: flat $0.002 per call in USDC; a JSON-RPC batch charges per element.
import { RpcClient } from '@blockrun/llm';
const client = new RpcClient();
// EVM chains speak eth_* JSON-RPC
const block = await client.call('ethereum', 'eth_blockNumber');
console.log(parseInt(block.result as string, 16));
const balance = await client.call('base', 'eth_getBalance', [
'0x4200000000000000000000000000000000000006',
'latest',
]);
// Non-EVM chains speak their native JSON-RPC
const slot = await client.call('solana', 'getSlot');
const tip = await client.call('bitcoin', 'getblockcount');
// Batch: one payment, per-element pricing ($0.002 x N)
const out = await client.batch('polygon', [
{ method: 'eth_blockNumber' },
{ method: 'eth_gasPrice' },
]);
console.log(block.network); // 'ethereum' (canonical key from X-Network)
console.log(block.cacheHit); // true if served from the gateway's hot cache
console.log(block.txHash); // x402 settlement tx40 curated chains are exported as SUPPORTED_NETWORKS; common aliases
(eth, arb, op, matic, bnb, avax, sol, btc, xrp, dot, ...)
resolve server-side (NETWORK_ALIASES). Unknown but well-formed slugs fall
through to a generic {slug}-mainnet gateway attempt, so new chains work
without an SDK update. Hot, low-volatility reads (eth_chainId, mined
blocks/receipts, getTransaction, ...) are served from a method-aware
gateway cache — same price, lower latency.
| Model | Price |
|---|---|
openai/gpt-oss-20b |
$0.001/request |
openai/gpt-oss-120b |
$0.002/request |
Testnet models use flat pricing (no token counting) for simplicity.
Search web, X/Twitter, and news without using a chat model:
import { LLMClient } from '@blockrun/llm';
const client = new LLMClient();
const result = await client.search('latest AI agent frameworks 2026');
console.log(result.summary);
for (const cite of result.citations ?? []) {
console.log(` - ${cite}`);
}
// Filter by source type and date range
const filtered = await client.search('BlockRun x402', {
sources: ['web', 'x'],
fromDate: '2026-01-01',
maxResults: 5,
});Edit existing images with text prompts:
import { LLMClient } from '@blockrun/llm';
const client = new LLMClient();
const result = await client.imageEdit(
'Make the sky purple and add northern lights',
'data:image/png;base64,...', // base64 or URL
{ model: 'openai/gpt-image-1' }
);
console.log(result.data[0].url);import { LLMClient } from '@blockrun/llm';
const client = new LLMClient(); // Uses BASE_CHAIN_WALLET_KEY (never sent to server)
const response = await client.chat('openai/gpt-4o', 'Explain quantum computing');
console.log(response);
// With system prompt
const response2 = await client.chat('anthropic/claude-sonnet-4', 'Write a haiku', {
system: 'You are a creative poet.',
});Save up to 88% on inference costs with intelligent model routing. The bundled Router Core V3 engine classifies each request across 15 dimensions, applies hard capability filters, and ranks the cheapest capable models (<1ms, 100% local). Bundled — nothing extra to install.
import { LLMClient } from '@blockrun/llm';
const client = new LLMClient();
// Auto-route to cheapest capable model
const result = await client.smartChat('What is 2+2?');
console.log(result.response); // '4'
console.log(result.model); // 'google/gemini-2.5-flash'
console.log(result.routing.tier); // 'SIMPLE'
console.log(`Saved ${(result.routing.savings * 100).toFixed(0)}%`); // 'Saved 88%'
// Routing profiles ('eco' | 'auto' | 'premium')
const eco = await client.smartChat('Explain AI', { routingProfile: 'eco' }); // Free tier first, then cheapest paid
const auto = await client.smartChat('Code review', { routingProfile: 'auto' }); // Balanced (default)
const premium = await client.smartChat('Write a legal brief', { routingProfile: 'premium' }); // Best quality
// Guaranteed $0: call a free NVIDIA model directly
const free = await client.chat('nvidia/step-3.7-flash', 'Hello!');Routing Profiles:
| Profile | Description | Best For |
|---|---|---|
eco |
Budget-optimized — ranks the 5-model free NVIDIA tier first | Cost-sensitive workloads, zero-cost testing |
auto |
Intelligent routing (default) | General use |
premium |
Best quality models | Critical tasks |
Tiers:
| Tier | Example Tasks | Typical Models |
|---|---|---|
| SIMPLE | Greetings, math, lookups | Gemini Flash, GPT-4o-mini |
| MEDIUM | Explanations, summaries | GPT-4o, Claude Sonnet |
| COMPLEX | Analysis, code generation | GPT-5.2, Claude Opus |
| REASONING | Multi-step logic, planning | o3, DeepSeek Reasoner |
import { LLMClient, type ChatMessage } from '@blockrun/llm';
const client = new LLMClient(); // Uses BASE_CHAIN_WALLET_KEY (never sent to server)
const messages: ChatMessage[] = [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'How do I read a file in Node.js?' },
];
const result = await client.chatCompletion('openai/gpt-4o', messages);
console.log(result.choices[0].message.content);Stream responses token-by-token with automatic x402 payment. Uses a pre-auth cache to skip the 402 round-trip on repeat calls to the same model (~200ms saved per request after the first).
import { OpenAI } from '@blockrun/llm';
const client = new OpenAI({ walletKey: process.env.BASE_CHAIN_WALLET_KEY });
const stream = await client.chat.completions.create({
model: 'openai/gpt-5.4',
messages: [{ role: 'user', content: 'Write a short story about AI agents' }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || '');
}import { LLMClient, type ChatMessage } from '@blockrun/llm';
const client = new LLMClient();
const messages: ChatMessage[] = [
{ role: 'user', content: 'Explain quantum computing in simple terms' },
];
// Returns a raw fetch Response with SSE body
const response = await client.chatCompletionStream('google/gemini-2.5-flash', messages);
const reader = response.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
for (const line of chunk.split('\n')) {
if (!line.startsWith('data: ') || line === 'data: [DONE]') continue;
const data = JSON.parse(line.slice(6));
process.stdout.write(data.choices?.[0]?.delta?.content || '');
}
}First call (cache miss):
1. Send request → 402 response (BlockRun returns price)
2. Sign USDC payment locally (key never leaves machine)
3. Retry with PAYMENT-SIGNATURE header + stream: true
4. Cache payment requirements for this model (1h TTL)
5. Stream tokens as they arrive
Subsequent calls (cache hit):
1. Pre-sign payment from cache — skip 402 round-trip
2. Send request with PAYMENT-SIGNATURE upfront
3. Stream tokens immediately (~200ms faster)
import { LLMClient } from '@blockrun/llm';
const client = new LLMClient(); // Uses BASE_CHAIN_WALLET_KEY (never sent to server)
const models = await client.listModels();
for (const model of models) {
console.log(`${model.id}: $${model.inputPrice}/M input`);
}import { LLMClient } from '@blockrun/llm';
const client = new LLMClient(); // Uses BASE_CHAIN_WALLET_KEY (never sent to server)
const [gpt, claude, gemini] = await Promise.all([
client.chat('openai/gpt-4o', 'What is 2+2?'),
client.chat('anthropic/claude-sonnet-4', 'What is 3+3?'),
client.chat('google/gemini-2.5-flash', 'What is 4+4?'),
]);Access real-time prediction market data from Polymarket, Kalshi, and Binance Futures via Predexon. No API keys needed — pay-per-request via x402.
import { LLMClient } from '@blockrun/llm';
const client = new LLMClient();
// List markets with optional filters ($0.001/request)
const markets = await client.pm("polymarket/markets");
const filtered = await client.pm("polymarket/markets", { status: "active", limit: 10 });
const searched = await client.pm("polymarket/markets", { search: "bitcoin" });
// List events ($0.001/request)
const events = await client.pm("polymarket/events");
// Historical trades ($0.001/request)
const trades = await client.pm("polymarket/trades");
// OHLCV candlestick data for a specific condition ($0.001/request)
const candles = await client.pm("polymarket/candlesticks/0x1234abcd...");
// Wallet profile ($0.005/request — tier 2)
const profile = await client.pm("polymarket/wallet/0xABC123...");
// Wallet P&L ($0.005/request — tier 2)
const pnl = await client.pm("polymarket/wallet/pnl/0xABC123...");
// Global leaderboard ($0.001/request)
const leaderboard = await client.pm("polymarket/leaderboard");// Kalshi markets ($0.001/request)
const kalshiMarkets = await client.pm("kalshi/markets");
// Kalshi trades ($0.001/request)
const kalshiTrades = await client.pm("kalshi/trades");
// Binance candles for supported pairs ($0.001/request)
const btcCandles = await client.pm("binance/candles/BTCUSDT");
const ethCandles = await client.pm("binance/candles/ETHUSDT");
// Also: SOLUSDT, XRPUSDT// Cross-platform matching pairs ($0.001/request)
const pairs = await client.pm("matching-markets/pairs");All current endpoints are GET. The pmQuery() method is available for future POST endpoints.
Works on both LLMClient (Base) and SolanaLLMClient.
Access Exa's neural web search via x402. No API keys needed — pay-per-request. Available on LLMClient (Base USDC) and SolanaLLMClient (Solana USDC). Use Base as the primary path; the Solana gateway is awaiting EXA_API_KEY provisioning.
| Method | Description | Price |
|---|---|---|
exaSearch(query, options?) |
Neural/keyword web search | $0.01/request |
exaFindSimilar(url, options?) |
Find semantically similar pages | $0.01/request |
exaContents(urls, options?) |
Extract full text from URLs | $0.002/URL |
exaAnswer(query, options?) |
AI answer grounded in web search | $0.01/request |
exa(path, body) |
Generic proxy for any Exa endpoint | varies |
import { LLMClient } from '@blockrun/llm';
const client = new LLMClient();
// Neural web search ($0.01/request)
const results = await client.exaSearch("latest AI safety research", { numResults: 5 });
const news = await client.exaSearch("bitcoin ETF news", { category: "news", numResults: 10 });
// Find similar pages ($0.01/request)
const similar = await client.exaFindSimilar("https://openai.com/research/gpt-4", { numResults: 5 });
// Extract content from URLs ($0.002/URL)
const content = await client.exaContents(["https://arxiv.org/abs/2303.08774"]);
// AI-generated answer from live web ($0.01/request)
const answer = await client.exaAnswer("What is the current state of AI safety research?");
// Generic proxy for any Exa endpoint
const custom = await client.exa("search", { query: "transformer architecture", numResults: 5 });Same surface on SolanaLLMClient once Solana-side EXA_API_KEY is provisioned.
// Default: reads BASE_CHAIN_WALLET_KEY from environment
const client = new LLMClient();
// Or pass options explicitly
const client = new LLMClient({
privateKey: '0x...', // Your wallet key (never sent to server)
apiUrl: 'https://blockrun.ai/api', // Optional
timeout: 60000, // Optional (ms)
});| Variable | Description |
|---|---|
BASE_CHAIN_WALLET_KEY |
Your Base chain wallet private key (for Base / LLMClient) |
SOLANA_WALLET_KEY |
Your Solana wallet secret key - bs58 encoded (for SolanaLLMClient) |
BLOCKRUN_API_URL |
API endpoint (optional, default: https://blockrun.ai/api) |
import { LLMClient, APIError, PaymentError } from '@blockrun/llm';
const client = new LLMClient();
try {
const response = await client.chat('openai/gpt-4o', 'Hello!');
} catch (error) {
if (error instanceof PaymentError) {
console.error('Payment failed - check USDC balance');
} else if (error instanceof APIError) {
console.error(`API error: ${error.message}`);
}
}Unit tests do not require API access or funded wallets:
npm test # Run tests in watch mode
npm test run # Run tests once
npm test -- --coverage # Run with coverage reportIntegration tests call the production API and require:
- A funded Base wallet with USDC ($1+ recommended)
BASE_CHAIN_WALLET_KEYenvironment variable set- Estimated cost: ~$0.05 per test run
export BASE_CHAIN_WALLET_KEY=0x...
npm test -- test/integration # Run integration tests onlyIntegration tests are automatically skipped if BASE_CHAIN_WALLET_KEY is not set.
- Create a wallet on Base (Coinbase Wallet, MetaMask, etc.)
- Get USDC on Base for API payments
- Export your private key and set as
BASE_CHAIN_WALLET_KEY
# .env
BASE_CHAIN_WALLET_KEY=0x...- Create a Solana wallet (Phantom, Backpack, Solflare, etc.)
- Get USDC on Solana for API payments
- Export your secret key and set as
SOLANA_WALLET_KEY
# .env
SOLANA_WALLET_KEY=...your_bs58_secret_keyNote: Solana transactions are gasless for the user - the CDP facilitator pays for transaction fees.
- Private key stays local: Your key is only used for signing on your machine
- No custody: BlockRun never holds your funds
- Verify transactions: All payments are on-chain and verifiable
Private Key Management:
- Use environment variables, never hard-code keys
- Use dedicated wallets for API payments (separate from main holdings)
- Set spending limits by only funding payment wallets with small amounts
- Never commit
.envfiles to version control - Rotate keys periodically
Input Validation: The SDK validates all inputs before API requests:
- Private keys (format, length, valid hex)
- API URLs (HTTPS required for production, HTTP allowed for localhost)
- Model names and parameters (ranges for max_tokens, temperature, top_p)
Error Sanitization: API errors are automatically sanitized to prevent sensitive information leaks.
Monitoring:
const address = client.getWalletAddress();
console.log(`View transactions: https://basescan.org/address/${address}`);Keep Updated:
npm update @blockrun/llm # Get security patchesFull TypeScript support with exported types:
import {
LLMClient,
OpenAI,
type ChatMessage,
type ChatResponse,
type ChatOptions,
type ChatCompletionOptions,
type Model,
// Smart routing types
type SmartChatOptions,
type SmartChatResponse,
type RoutingDecision,
type RoutingProfile,
type RoutingTier,
APIError,
PaymentError,
} from '@blockrun/llm';
// chatCompletionStream returns a standard fetch Response with SSE body
const streamResponse: Response = await client.chatCompletionStream(model, messages, options);
// OpenAI-compat stream returns AsyncIterable
const stream: AsyncIterable<OpenAIChatCompletionChunk> = await openaiClient.chat.completions.create({
model, messages, stream: true
});One-line setup for agent runtimes (Claude Code skills, MCP servers, etc.):
import { setupAgentWallet } from '@blockrun/llm';
// Auto-creates wallet if none exists, returns ready client
const client = setupAgentWallet();
const response = await client.chat('openai/gpt-5.4', 'Hello!');For Solana:
import { setupAgentSolanaWallet } from '@blockrun/llm';
const client = await setupAgentSolanaWallet();
const response = await client.chat('anthropic/claude-sonnet-4.6', 'Hello!');Check wallet status:
import { status } from '@blockrun/llm';
await status();
// Wallet: 0xCC8c...5EF8
// Balance: $5.30 USDCThe SDK can discover compatible wallets for an explicit, user-confirmed migration. It never automatically makes a discovered provider wallet active:
import { scanWallets, scanSolanaWallets } from '@blockrun/llm';
// Scans ~/.<dir>/wallet.json for Base wallets
const baseWallets = scanWallets();
// Scans ~/.<dir>/solana-wallet.json and ~/.brcc/wallet.json
const solWallets = scanSolanaWallets();getOrCreateWallet() always uses ~/.blockrun/.session (or an explicit
wallet environment variable, or the legacy ~/.blockrun/wallet.key). Review
the discovered addresses and import one explicitly if you intend to switch
wallets.
Earlier versions adopted the most recently written provider wallet automatically. If you relied on that, the first run after upgrading creates a fresh BlockRun wallet and prints the addresses it found, so you can import the one you actually own:
NOTICE: BlockRun created a new wallet, but also found existing wallet(s)
belonging to other applications on this system:
0x88f9B82462f6C4bf4a0Fb15e5c3971559a316e7f
...
Adopt one deliberately:
import { listDiscoveredWallets, importWallet } from '@blockrun/llm';
for (const w of listDiscoveredWallets()) {
console.log(w.address, 'from', w.source);
}
importWallet('0x88f9B82462f6C4bf4a0Fb15e5c3971559a316e7f');importWallet() writes your current wallet to
~/.blockrun/.session.backup-<timestamp> before switching, so adopting a wallet
never strands funds in the old one. Solana: listDiscoveredSolanaWallets() and
importSolanaWallet().
Addresses shown are derived from the discovered key itself, and importWallet()
matches on that derived address — so a wallet file cannot claim an address it
cannot sign for, nor be adopted by one. listDiscoveredWallets() never returns
private keys.
Base wallet resolution, discovery, and adoption are implemented in
@blockrun/core, the shared kernel
this SDK, the blockrun CLI, and clawrouter-codex all read. Defining the canonical
order in one place is what keeps them in agreement — when each product carried its
own copy, they drifted, and a fix made here did not reach the CLI.
The kernel is bundled into the SDK at build time (frozen, reviewed bytes — no
floating dependency), so there is nothing extra to install. Set BLOCKRUN_HOME
to override the base directory (~ by default) for test isolation; unset,
behaviour is unchanged. Treat BLOCKRUN_HOME as security-sensitive: it
redirects where the signing key is read from and written to, so an environment
that can set it controls the wallet as surely as one that can set
BLOCKRUN_WALLET_KEY. Set it before importing the SDK — the exported
WALLET_FILE_PATH/WALLET_DIR_PATH constants snapshot at import (all internal
reads and writes resolve per call). Solana resolution is still SDK-local and
does not honor BLOCKRUN_HOME.
For a single run without changing anything, use
export BLOCKRUN_WALLET_KEY=<private-key>.
The SDK caches responses to avoid duplicate payments:
import { getCachedByRequest, saveToCache, clearCache } from '@blockrun/llm';
// Automatic TTLs by endpoint:
// - Search: 15 minutes
// - Models: 24 hours
// - Chat/Image: no cache (every call is unique)
// Manual cache management
clearCache(); // Remove all cached responsesTrack spending across sessions:
import { logCost, getCostSummary } from '@blockrun/llm';
// Costs are logged to ~/.blockrun/data/costs.jsonl
const summary = getCostSummary();
console.log(`Total: $${summary.totalUsd.toFixed(2)}`);
console.log(`Calls: ${summary.calls}`);
console.log(`By model:`, summary.byModel);Use the official Anthropic SDK interface with BlockRun's pay-per-request backend:
import { AnthropicClient } from '@blockrun/llm';
const client = new AnthropicClient(); // Auto-detects wallet, auto-pays
const response = await client.messages.create({
model: 'claude-sonnet-4-6',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello!' }],
});
console.log(response.content[0].text);
// Any model works in Anthropic format
const gptResponse = await client.messages.create({
model: 'openai/gpt-5.4',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello from GPT!' }],
});The AnthropicClient wraps the official @anthropic-ai/sdk with a custom fetch that handles x402 payment automatically. Your private key never leaves your machine. The Mythos-class claude-fable-5 alias is available here too (1M context, always-on thinking).
@blockrun/llm is a TypeScript SDK that cuts LLM costs by up to 88% with built-in smart routing: every request is routed to the cheapest of 70 models (OpenAI, Anthropic, Google, xAI, DeepSeek, Moonshot, and more) that can handle it, then paid per-request in USDC via the x402 protocol — no API keys, no subscriptions, no vendor lock-in.
When you make an API call, the SDK automatically handles x402 payment. It signs a USDC transaction locally using your wallet private key (which never leaves your machine), and includes the payment proof in the request header. Settlement is non-custodial and instant on Base or Solana.
Router Core V3 is bundled into the SDK — the same deterministic routing engine that powers ClawRouter, with nothing extra to install. It analyzes your request across 15 dimensions and automatically picks the cheapest model capable of handling it. Routing happens locally in under 1ms. Use smartChat(), smartChatCompletion(), or the blockrun/auto model alias. It can save up to 88% on LLM costs compared to using premium models for every request.
Yes — as of v1.6.1. Use client.chatCompletionStream() for native streaming or stream: true in the OpenAI-compatible client. Payment is handled automatically: the SDK signs USDC payment before streaming begins, and caches payment requirements per model so subsequent calls skip the 402 round-trip (~200ms faster).
Pay only for what you use. Prices start at $0.0002 per request (GPT-5 Nano). There are no minimums, subscriptions, or monthly fees. $5 in USDC gets you thousands of requests.
Yes. Use LLMClient for Base (EVM) payments and SolanaLLMClient for Solana payments. Same API, different payment chain.
If the router just cut your bill, give it a star ⭐ — it helps more agents pay less.
Website · Models & Pricing · ClawRouter · Python SDK · Telegram
MIT