Skip to main content Switch to mobile version blockrun-llm 1.24.0 BlockRun SDK - Pay-per-request AI (LLM, Image, Video, Music, Voice) via x402 on Base and Solana
pip install blockrun-llm==1.24.0 Copy PIP instructions
blockrun-llm is a Python SDK for accessing 97 large language models (GPT-6, GPT-5.x, Claude 5.x, Gemini 4 / 3.x, DeepSeek, Grok 4.x, GLM, MiniMax, Moonshot and more) plus image / video / music generation, Grok Live Search, prediction-market data (Predexon), Exa neural web search, and free crypto / FX / commodity price data (daily closes). Paid calls are billed per request — no subscription, no seats, no minimum. Built for AI agents that need to operate autonomously.
Two ways to pay, same SDK, same catalogue. Sign up at user.blockrun.ai for an API key and prepaid credit (top up with a card), or hold USDC in your own wallet and let each request settle itself over x402 — on Solana or Base. Every client takes either credential in the same first argument.
🆓 Includes 9 free models — Nemotron 3.5 Lightning (1M context), Nemotron 3 Ultra 550B, MiniMax M3.1 Flash (1M context), Nemotron 3 Nano Omni, Nemotron 3.5 Bolt (vision) and Poolside Laguna XS 2.1. Zero USDC, no rate-limit gimmicks. Use routing_profile="free" or pin one of the models listed under Try It Free.
BlockRun assumes Claude Code as the agent runtime.
Protocol: x402 v2 on the wallet rails; plain bearer auth on the API-key rail.
pip install blockrun-llm # Base chain (EVM/USDC) — includes all core deps pip install blockrun-llm[solana] # Base + Solana (USDC SPL) payments pip install blockrun-llm[dev] # Base + dev tools (pytest, black, ruff, mypy) pip install blockrun-llm[dev,solana] # Everything Quick Start
from blockrun_llm import LLMClient # Reads BLOCKRUN_API_KEY if set, otherwise BLOCKRUN_WALLET_KEY for x402. client = LLMClient() response = client.chat("openai/gpt-5.2", "Hello!") # API key — sign up at https://user.blockrun.ai, then: export BLOCKRUN_API_KEY=brk_live_... # …or a wallet, and every call pays itself in USDC: export SOLANA_WALLET_KEY=... # with SolanaLLMClient export BLOCKRUN_WALLET_KEY=0x... # with LLMClient (Base) That's it. Either credential can also be passed directly — LLMClient("brk_live_…") or LLMClient("0x…") — and client.payment_mode reports which rail you ended up on.
Try It Free (No Balance Required)
Want to kick the tires before topping up or funding a wallet? Route to BlockRun's free tier — it settles $0 on both rails, so an unfunded wallet or a $0 credit account is enough:
from blockrun_llm import LLMClient client = LLMClient() # a credential is still needed; a balance is not # Option 1: call a free model directly response = client.chat("nvidia/nemotron-3.5-lightning", "Explain x402 in 1 sentence") # Option 2: let the smart router pick the best free model per request result = client.smart_chat("What is 2+2?", routing_profile="free") print(result.model) # e.g. 'nvidia/nemotron-3-nano-omni-30b-a3b-reasoning' (free SIMPLE tier) print(result.response) # '4' Available free models (input + output both $0; the live list is GET /v1/models filtered on $0 pricing):
For free image input use nemotron-3.5-bolt. nemotron-3-nano-omni is catalogued as vision-capable but failed earlier image probes on Solana, so the router never sends it images.
Do not pin these free ids: nvidia/llama-3.2-11b-vision, nvidia/nemotron-3-super-120b, cohere/north-mini-code and nvidia/muse-glimmer-30b. They still answer 200, but since 2026-11 the gateway serves them with a different model, so a pinned call does not get the model it names.
Need V4-Pro-class reasoning? Use the paid deepseek/deepseek-v4-pro. The free nvidia/deepseek-v4-pro is retired and no longer in the catalog; calls to it are redirected to a free NVIDIA Nemotron model.
Retired: NVIDIA has EOL'd most of its early free lineup — the free DeepSeek family (last: nvidia/deepseek-v4-flash, 2026-08-12), step-3.7-flash, mistral-nemotron, nemotron-nano-9b-v2 / -12b-v2-vl (2026-08-30), gpt-oss-120b/20b (2026-09-03), nemotron-3-nano-30b (2026-09-08), llama-4-maverick, the qwen3 SKUs, free Mistral small/large, and more. The gateway auto-redirects pinned callers to a live model, so old model IDs still return 200 — from a different model.
Solana is the recommended chain for x402 payments: settlement is sub-second and BlockRun's facilitator co-signs as fee payer, so a transfer costs you no SOL and you hold nothing but USDC. Base works identically and remains what the bare LLMClient uses, so nothing existing changes — but if you are choosing today, choose Solana.
Pay for AI calls with Solana USDC via sol.blockrun.ai:
from blockrun_llm import SolanaLLMClient # SOLANA_WALLET_KEY env var (bs58-encoded Solana secret key) client = SolanaLLMClient() # Or pass key directly client = SolanaLLMClient(private_key="your-bs58-solana-key") # A BlockRun API key works here too — on the account rail there is no transfer # to sign, so the chain stops being a question. client = SolanaLLMClient(private_key="brk_live_...") # Same API as LLMClient response = client.chat("openai/gpt-5.2", "gm Solana") print(response) # DeepSeek on Solana answer = client.chat("deepseek/deepseek-chat", "Explain Solana consensus", temperature=0.5) Agent setup (auto-loads or creates a wallet):
from blockrun_llm import setup_agent_solana_wallet client = setup_agent_solana_wallet() # uses ~/.blockrun/.solana-session, env, or creates one client.chat("openai/gpt-5.2", "gm Solana") Setup:
pip install blockrun-llm[solana] export SOLANA_WALLET_KEY="your-bs58-solana-key" Endpoint: https://sol.blockrun.ai/api Payment: Solana USDC (SPL Token, mainnet)
Base vs Solana keys are not interchangeable. A Solana key is base58 (~44 chars for a seed, ~88 for a full keypair); a Base/EVM key is 0x + 64 hex chars. Pass a Solana key to SolanaLLMClient — not LLMClient / setup_agent_wallet(). If you do mix them up, the SDK now tells you exactly what to switch to instead of failing with a cryptic "must be 66 characters" error.
Polling slow media jobs. video(), slow image() / image_edit() models and slow music() tracks answer 202 + poll_url, and the client polls until the job finishes. On Solana a payment dies with its blockhash in ~60-90s, so instead of signing a payment on every poll the client proves it owns the job: each poll carries x-poll-wallet, x-poll-timestamp and x-poll-signature, an ed25519 signature by your wallet over blockrun-poll:v1:
Video is charged once, when it is ready: the finished-but-unpaid poll answers 402, the client signs one payment from that challenge and re-sends the poll, which settles the clip. A poll budget that runs out costs nothing.
Images and music were paid at submit, so their polls never sign a payment.
If the gateway refuses the proof, the client falls back once, for that job, to signing a payment per poll (logged as a warning on blockrun_llm.solana_client).
The account rail (API key) and Base are unchanged: an API key is its own proof, and a Base authorization lives for hours.
The same LLMClient pays on Circle's Arc via arc.blockrun.ai — point api_url at it and hold USDC on Arc in the same EVM wallet:
Same wallet key as Base: export BLOCKRUN_WALLET_KEY="0x..."
Fund it with USDC on Arc (Arc's native token, shown as the ERC-20 at 0x3600…0000)
api_url="https://arc.blockrun.ai/api" — payments are automatic via x402
llama-index-llms-blockrun makes any BlockRun chat model a LlamaIndex LLM — chat, streaming, async, tool calling and agents — paying through this SDK on the chain you pick:
pip install llama-index-llms-blockrun # pay on Base pip install "llama-index-llms-blockrun[solana]" # pay on Solana from llama_index.llms.blockrun import BlockRun llm = BlockRun(model="openai/gpt-5.5") # USDC on Base llm = BlockRun(model="openai/gpt-5.5", chain="solana") # USDC on Solana Smart Routing (Router Core)
Let the SDK automatically pick the cheapest capable model for each request:
# Route a full message list — tools and response_format shape the decision, # not just the request result = client.smart_chat_completion( [{"role": "user", "content": "Cancel order B-42"}], tools=[{"type": "function", "function": {"name": "cancel_order", "parameters": {}}}], tool_choice="required", ) print(result.model) # a tool-capable model print(result.routing.task_type) # 'tool_agent' # Or opt in from OpenAI-compatible code by changing one string response = client.chat_completion("blockrun/auto", messages) Want to see the decision without paying for a call? client.route(...) runs the same routing locally and returns the decision only:
decision = client.route("Prove the Riemann hypothesis step by step") print(decision.model) # 'deepseek/deepseek-v4-pro' print(decision.tier) # 'REASONING' print(decision.task_type) # 'reasoning' print(decision.candidates) # ordered chain; smart_chat walks it on a 5xx/timeout print(decision.reasoning) # human-readable explanation of the pick Routing Profiles
# Use premium models for complex tasks result = client.smart_chat( "Write production-grade async Python code", routing_profile="premium" ) print(result.model) # 'openai/gpt-5.3-codex' How It Works
Routing runs on Router Core — the same product-neutral engine the TypeScript SDK and the BlockRun gateway use, so an identical request routes identically across all three. It is 100% local and takes <1ms; no extra model call is made to decide.
Classify — a 15-dimension weighted scorer maps the request onto a capability tier (token count, code presence, reasoning markers, technical terms, creative markers, agentic patterns, and more), and a task classifier labels the shape of the work: chat, code_edit, code_agent, tool_agent, reasoning_math, long_context, extraction, vision, …
Filter — capability constraints are hard filters, not preferences. A model that cannot hold the conversation, emit the requested output length, call tools, or read images is dropped before scoring, so the router never picks a model the request would fail on.
Rank — surviving candidates are scored on task affinity, cost, speed and reliability. The winner serves the request; the rest become the ordered fallback chain that smart_chat walks on a timeout or 5xx.
The four capability tiers:
These are the picks client.route() returned against the live catalog on 2026-10-02. The task ranker can move a tier's fallback ahead of its configured primary — REASONING's primary is deepseek/deepseek-reasoner, but proofs and step-by-step math rank deepseek/deepseek-v4-pro first — so check decision.model rather than relying on this table.
Every decision is explainable — result.routing carries the tier, the task type, the confidence, the ranked candidates, the per-candidate candidate_scores (quality / cost / speed / reliability) and a reasoning string describing why that model won.
Two front doors onto the same gateway, the same catalogue and the same response shapes. You choose one with the credential you hand the client.
Free models are free on both.
Option A — API key (user.blockrun.ai)
Sign in at user.blockrun.ai with Google.
Mint a key on the API Keys page. It is shown once — copy it then.
Top up on the Billing page with a card. Minimum $5. The processing fee (5.5% + $0.30) is charged once, at purchase — never on a call — so $10.85 buys $10.00 of credit and every model then bills at the published list price, with no per-call minimum and no per-call fee.
export BLOCKRUN_API_KEY=brk_live_... from blockrun_llm import LLMClient client = LLMClient() # picks up BLOCKRUN_API_KEY print(client.payment_mode) # 'apikey' print(client.chat("openai/gpt-5.2", "What is 2+2?")) Requests go to https://api.blockrun.ai/v1 with the key as Authorization: Bearer …. There is no 402 round trip and nothing is signed — the gateway meters the call at exact usage and draws it from your credit. Spending, per-call activity and remaining balance are on user.blockrun.ai/dashboard.
Precedence, since it decides whether a call spends credit or on-chain USDC:
an explicit argument — LLMClient("brk_live_…") or LLMClient("0x…");
BLOCKRUN_API_KEY, which beats BLOCKRUN_WALLET_KEY / BASE_CHAIN_WALLET_KEY / SOLANA_WALLET_KEY;
the wallet variables.
An existing wallet setup is untouched until you set BLOCKRUN_API_KEY, and passing a wallet key explicitly always opts back out. BLOCKRUN_API_KEY_URL overrides the account-rail host; it is deliberately not BLOCKRUN_API_URL, which names an x402 gateway — an API-key client following that would send your key to a host configured for a different rail.
What changes. get_balance(), get_balance_testnet() and onramp() raise a ValueError pointing at the dashboard rather than answering: returning 0 is indistinguishable from an empty wallet, and an agent gating on it would stop calling a well-funded account. get_wallet_address() returns "". Running out of credit raises a PaymentError naming the top-up page, not a wallet error. setup_agent_wallet() mints nothing and hands back an API-key client, so a skill can call it unconditionally. Everything else is identical.
Option B — wallet + x402
You hold USDC in your own wallet — on Solana or Base — and each request pays for itself with an on-chain micropayment. No signup, nothing custodial.
Phase 1 — Fund your wallet once
You only do this when your balance runs low. Three ways:
print(f"Balance: ${client.get_balance():.2f} USDC") Phase 2 — Every request pays itself (automatic x402)
reply = client.chat("anthropic/claude-sonnet-4.6", "Explain x402 in one line") That single call does all of this under the hood:
You send the request to BlockRun's gateway.
The gateway returns 402 Payment Required with the price.
The SDK signs a USDC payment on Base locally (EIP-712) — your private key never leaves your machine.
The request is retried with the signed payment proof.
The gateway settles on-chain and returns the AI response.
One call, no separate pay step.
Pay the actual cost: x402 upto (Base)
Upto is opt-in: build the client with payment_scheme="auto" (or set BLOCKRUN_PAYMENT_SCHEME=auto), and a chat call whose 402 also offers the x402 upto scheme pays with a Permit2 signature for a ceiling instead of an exact EIP-3009 transfer for a fixed quote. The gateway then settles the actual cost after the call — never more than the ceiling — so discounts it only learns afterwards, such as prompt-cache hits, reach you.
Upto is not always cheaper. The exact quote prices output at a tenth of your max_tokens; under upto you pay for the output you actually got. A short or cache-hit answer costs less than exact, a long one costs more (up to the ceiling, which prices the full max_tokens), and a stream counts its full ceiling against your spend limits. That is why the default stays "exact", the fixed quote. With "auto", the gateway lists exact first; upto is taken only when all of these hold:
the 402 offers an EVM upto requirement with extra.facilitatorAddress, for USDC on a network the SDK signs on (Base, Base Sepolia);
your wallet holds at least the ceiling in USDC;
Permit2 can already pull the ceiling from your wallet, or the gateway declares the eip2612GasSponsoring extension. In that case the SDK also signs a gasless EIP-2612 permit approving the canonical Permit2 contract (0x0000…78BA3) for exactly the ceiling, and the facilitator submits it — no ETH needed;
the ceiling fits your max_cost_per_call / max_session_cost.
Otherwise — or on any RPC or signing error — the SDK signs exact exactly as before. If the gateway rejects an upto payment before serving anything, the request is retried once with exact, and that client pays exact on that network for the next 10 minutes. It is never retried with exact after a 502/503 replay of the same upto payment, because the first send may already have settled. A 402 that offers only upto, when upto cannot be used, raises instead of being signed as exact. Solana is unchanged (exact only).
Per wallet, only one gas-sponsored upto payment can be in flight. Its permit lands only when that call settles, and until then the chain still shows the old USDC permit nonce — a second permit over the same nonce would revert on-chain. So concurrent or not-yet-settled calls that would need a permit pay exact (the SDK watches the on-chain nonce, and gives up on a permit at its deadline; concurrent calls in one client claim the permit slot before reading the chain). A call that Permit2 can already pull for without a permit also pays exact while a permit is in flight, and a permit waits while such a call is unsettled: a landing permit resets the allowance the other call would pull. These guards are per process: several processes paying from one wallet can still collide (a call fails; nobody is overcharged), so run one paying process per wallet or use exact there.
LLMClient(payment_scheme="auto") # opt in; or BLOCKRUN_PAYMENT_SCHEME=auto The signed ceiling is an upper bound, not a charge. ChatResponse.payment_scheme says which scheme paid; when the gateway's PAYMENT-RESPONSE reports the settled amount, cost_usd is that amount; when it does not (always, for streams, whose header arrives before settlement), cost_usd is the ceiling and cost_is_ceiling is True. get_spending()["ceiling_usd"] is the part of total_usd booked at a ceiling, cost-log rows carry cost_basis (upto_settled / upto_ceiling), and transactions.log marks ceiling rows. Spend limits count ceilings in full, so they err on the safe side.
What it costs, and how to verify it
Pay-as-you-go, per call. You pay only the gateway price of each request (see Available Models). The free NVIDIA models are $0.
Track spend. client.get_spending() returns this session's {total_usd, calls, ceiling_usd} (ceiling_usd: see upto). On the API-key rail the gateway does not tell the client what a call cost, so treat that total as a floor and user.blockrun.ai/dashboard as the authority. Every paid call also appends a line to ~/.blockrun/cost_log.jsonl; summarize/export it with blockrun_llm.billing (get_cost_log_summary, export_cost_log_csv) — see Billing & Cost Tracking.
Verify settlements on-chain. Each settlement returns a tx hash you can inspect on BaseScan — https://basescan.org/tx/
Non-custodial. Your wallet is yours; the key is only used for local signing and never leaves your machine. No deposits held by BlockRun.
Prices are not listed here. They change often, and a number copied into a README is wrong the day after it lands. See blockrun.ai/models for live rates, or read them from the catalog at runtime — client.list_models() and client.list_image_models() return exactly what the gateway is charging.
The GPT-6 generation: Astra is the flagship for long-horizon agentic work and computer use, Sol the cost-efficient tier for complex coding (gpt-6.1-sol is the refreshed Sol), Luna the fast low-cost tier.
OpenAI GPT-5.6 Family
Three tiers on one 1.05M-context base — Sol (deepest reasoning), Terra (balanced), Luna (cheap and fast). Each has a -pro sibling that thinks longer at the same token price.
OpenAI GPT-5.5 / 5.4 / 5.2 / 5.1 Families
OpenAI O-Series (Reasoning)
DeepSeek upstream serves the legacy deepseek-chat / deepseek-reasoner aliases as V4 Flash non-thinking / thinking modes. V4 Pro is the flagship paid SKU; V4.1 Flash is the newer Flash in non-thinking mode; the vision SKU is an experimental preview.
The older Grok chat SKUs (grok-3/3-mini, the grok-4 fast families, grok-code-fast-1, grok-2-vision) have left the catalog. Retired ids stay callable — the gateway redirects them to a healthy model — but smart_chat only ranks what /v1/models lists.
Moonshot, MiniMax, Z.ai, Qwen
Mistral, Tencent, Poolside
The 9 free models are listed under Try It Free. Pin them by full model id, or use routing_profile="free".
Testnet Models (Base Sepolia)
Live per-model prices: blockrun.ai/pricing (agents: GET https://blockrun.ai/api/v1/models). Prices are not copied here, so this page never goes stale on a reprice.
Testnet models use flat pricing (no token counting) for simplicity.
Verifying Models End-to-End
The SDK ships two runnable sweep scripts under examples/:
# Chat LLMs — every chat model the SDK exposes python examples/sweep_all_chat_models.py --output-json sweep-results.json # Image + music models (video excluded — long polling, expensive per clip) python examples/sweep_all_media_models.py --output-json sweep-media-results.json Each script captures per-model status, latency, token counts, and per-call cost, prints a grouped report, and exits non-zero if any expected-to-work model fails. Useful before a release or after router/catalog changes.
smart_chat() and chat() accept an optional fallback_models=[...] list — on timeout / 5xx / network error the SDK transparently walks the chain before raising. smart_chat() populates this from the tier's fallback list automatically.
Image editing (client.edit / client.image_edit) hits the /v1/images/image2image endpoint and supports openai/gpt-image-1, openai/gpt-image-2, google/nano-banana, and google/nano-banana-pro. Pass a list of source images to fuse multiple inputs (openai/* up to 4, google/* up to 3).
quality (Solana only). On Solana, image and image_edit accept quality="low" | "medium" | "high" | "auto" for openai/gpt-image-* — low meaningfully cuts generation time:
sol = SolanaLLMClient() result = sol.image("a red apple", model="openai/gpt-image-2", quality="low") This is deliberately absent from the Base ImageClient: the Base gateway has no quality field and would silently ignore the value, so passing it there raises TypeError rather than quietly doing nothing.
Live video prices: blockrun.ai/pricing (agents: GET https://blockrun.ai/api/v1/models); every call's exact price is in its 402 quote before you pay.
Seedance defaults to 720p with synced audio on every input (text, image, first/last frame, reference media, RealFace); pass generate_audio=False for a silent clip. resolution="480p" costs about half as much, 1080p / 4K more. Grok ignores resolution and generate_audio.
from blockrun_llm import VideoClient client = VideoClient() result = client.generate("a red apple slowly spinning on a wooden table") print(result.data[0].url) # permanent MP4 URL print(result.data[0].duration_seconds) # 8 # Image-to-video result = client.generate( "the subject turns its head and smiles", image_url="https://example.com/portrait.jpg", ) # Character-consistency video (Seedance 2.0 fast/pro). Pass a ta_xxxxxx # asset to keep the same face across clips — either a Virtual Portrait # (AI character, PortraitClient, $0.01) or a RealFace (real person, # RealFaceClient, $0.01, no KYC). Mutually exclusive with image_url. result = client.generate( "the subject smiles warmly and waves at the camera", model="bytedance/seedance-2.0", real_face_asset_id="ta_abc123xyz", resolution="1080p", generate_audio=True, ) # First-and-last-frame interpolation (Seedance only): the model tweens # from image_url (first frame) to last_frame_url (final frame). # Priced identically to image-to-video. result = client.generate( "the flower blooms in golden morning light", model="bytedance/seedance-1.5-pro", image_url="https://example.com/bud.jpg", last_frame_url="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 image_url / last_frame_url / # real_face_asset_id. result = client.generate( "the character from image 1 walks through the city from image 2", model="bytedance/seedance-2.0", reference_image_urls=[ "https://example.com/character.jpg", "https://example.com/city.jpg", ], ) # input_type — declare the seed mode you intend, and get an error instead of # a surprise. The gateway infers the mode from the seed fields above; if your # declared value disagrees it returns 400 WITHOUT charging. # # Worth it when the seed fields are built dynamically: if `image_url` comes # back empty, the request quietly degrades to text-to-video and you still pay # for the clip. Declaring input_type="image" turns that into a 400 instead. result = client.generate( "the portrait turns to face the camera", model="bytedance/seedance-2.0", image_url=maybe_empty_url, # if this is falsy... input_type="image", # ...you get a 400, not a text-to-video bill ) Text-to-Speech & Sound Effects (SpeechClient)
BlockRun Voice (ElevenLabs) — OpenAI-compatible TTS plus cinematic sound effects. TTS price scales with character count: (chars / 1000) × model rate, minimum $0.001/request. Synthesis is synchronous (<1s for Flash).
from blockrun_llm import SpeechClient client = SpeechClient() # Text-to-speech (voice aliases: sarah, george, laura, charlie, # river, roger, callum, harry — or any raw ElevenLabs voice_id) result = client.generate("Welcome to BlockRun.", voice="george") print(result.data[0].url) # audio URL (mp3 by default) # Other formats / speed result = client.generate( "Breaking news from the world of micropayments.", model="elevenlabs/v3", response_format="wav", speed=1.1, ) # Sound effects (flat price per generation) result = client.sound_effect("rain on a tin roof, distant thunder") # List voices (free, rate-limited) voices = client.list_voices() Virtual Portraits (PortraitClient)
PortraitClient wraps POST /v1/portrait/enroll ($0.01 USDC, one-time, no KYC) and the free GET /v1/wallet/
/portraits listing endpoint. Enroll an AI-generated character image, get back a ta_xxxxxxxx asset id, then reuse it as real_face_asset_id on Seedance 2.0 / 2.0-fast to keep the same character across as many videos as you want.Need a real person's likeness instead? Use RealFaceClient below — it enrolls a real face for $0.01 via a quick on-phone liveness check, no KYC. Virtual Portraits are for AI-generated personas, mascots, avatars, and virtual spokespeople; RealFace is for real people. Both return a ta_xxxxxx id usable as real_face_asset_id on Seedance 2.0 / 2.0-fast.
from blockrun_llm import PortraitClient, VideoClient portraits = PortraitClient() portrait = portraits.enroll( name="My Spokesperson", image_url="https://example.com/character.jpg", ) print(portrait.asset_id) # ta_abcdef1234567890 print(portrait.settlement.tx_hash) # 0x9f3a… (BaseScan-verifiable) # Reuse the same ta_ id on any Seedance 2.0 / 2.0-fast call video = VideoClient() clip = video.generate( "the character smiles warmly and waves at the camera", model="bytedance/seedance-2.0-fast", real_face_asset_id=portrait.asset_id, ) print(clip.data[0].url) # Browse this wallet's enrolled portraits (free, rate-limited) listing = portraits.list_portraits() for p in listing.portraits: print(p.assetId, p.name, p.enrollmentTxHash) Settlement is held until the upstream registration succeeds — if the image fails the content filter or exceeds 10 MB, the route returns 502 and no payment is taken, safe to retry with a different image.
Real-Person Faces (RealFaceClient)
RealFaceClient enrolls a real person's likeness so you can keep the same human face across multiple Seedance 2.0 / 2.0-fast videos. Unlike a Virtual Portrait (an AI-generated character), RealFace proves the enroller is the person in the photo via a brief on-phone liveness check (nod + blink, ~1 minute) — no KYC, no government ID, no account login.
Enrollment is a three-step flow:
init(name) — free. Returns a group_id and an h5_link the real person opens on their phone (render it as a QR code).
phone liveness — the rights-holder opens the link, allows camera access, nods + blinks (~60s). Nothing is sent to BlockRun in this step.
enroll(name, image_url, group_id) — $0.01 USDC, one-time. Uploads the face photo, matches it against the live capture, and returns a ta_xxxxxxxx asset id.
from blockrun_llm import RealFaceClient, VideoClient faces = RealFaceClient() # 1. Start enrollment (free). Show init.h5_link as a QR for the person. init = faces.init(name="Jane — Q3 spokesperson") print(init.h5_link) # they scan + do the liveness check # 2. Block until they finish the phone liveness check. faces.wait_for_active(init.group_id) # 3. Finalize ($0.01) with the person's face photo. rf = faces.enroll( name="Jane — Q3 spokesperson", image_url="https://example.com/jane.jpg", group_id=init.group_id, ) print(rf.asset_id) # ta_abcdef1234567890 print(rf.settlement.tx_hash) # 0x9f3a… (BaseScan-verifiable) # Reuse the ta_ id on any Seedance 2.0 / 2.0-fast call video = VideoClient() clip = video.generate( "she smiles warmly and waves at the camera", model="bytedance/seedance-2.0-fast", real_face_asset_id=rf.asset_id, ) print(clip.data[0].url) # Browse this wallet's enrolled RealFaces (free, rate-limited) listing = faces.list_realfaces() for r in listing.realfaces: print(r.assetId, r.name, r.enrollmentTxHash) Settlement happens only after the face is successfully matched and registered, so failed enrollments return an error with no charge: 425 = group not active yet (finish the phone check first), 422 = the photo did not match the live capture (use a clearer front-facing photo), 502 = upstream upload failure (safe to retry). The H5 session expires ~120s after each init; call init(group_id=…) to refresh an expired link.
Voice Calls (VoiceClient)
VoiceClient wraps POST /v1/voice/call (paid, $0.54/call) and GET /v1/voice/call/{call_id} (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.
from blockrun_llm import VoiceClient client = VoiceClient() # Initiate (paid $0.54) result = 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) ) print(result["call_id"]) # Poll for transcript + recording (free) status = client.get_status(result["call_id"]) print(status.get("status"), status.get("recording_url")) Bring your own caller-ID: pass from_="+14155552671" (must be a BlockRun phone number you own; buy via PhoneClient.buy_number() or /v1/phone/numbers/buy). If you omit from_ and your wallet owns exactly one active number, the backend auto-picks it; with multiple active numbers you'll get a 400 ambiguous_from and the error body lists your candidates.
Phone Numbers (PhoneClient)
PhoneClient wraps /v1/phone/* — Twilio-backed phone lookup and wallet-bound number provisioning. Buy a number once to use it as caller ID in VoiceClient; the number is leased for 30 days and tied to your wallet.
from blockrun_llm import PhoneClient client = PhoneClient() # Carrier + line-type lookup ($0.01) info = client.lookup("+14155552671") # Carrier + SIM-swap/forwarding fraud signals ($0.05) fraud = client.lookup_fraud("+14155552671") # Buy a number — 30-day lease, wallet-bound ($5.00). # Payment is held until Twilio confirms the purchase, so failed buys never charge you. bought = client.buy_number(country="US", area_code="415") print(bought["phone_number"], bought["expires_at"]) # List, renew, release print(client.list_numbers()) # $0.001 client.renew_number(bought["phone_number"]) # $5.00, +30 days client.release_number(bought["phone_number"]) # free Surf (SurfClient) — retired
Deprecated. The gateway retired /v1/surf/* on 2026-09-06: every Surf endpoint answers 410 endpoint_retired on both blockrun.ai and sol.blockrun.ai, before any payment is asked for. SurfClient is still importable, but constructing it emits a DeprecationWarning, and every call that reaches the gateway fails with that 410 as an APIError. It will be removed in a future release.
Prices: PriceClient (crypto, FX, commodities).
Prediction markets: client.pm_*.
Protocol TVL and yields: client.defi_*.
DEX quotes and swaps: client.dex_*.
Standalone Search (SearchClient)
SearchClient wraps POST /v1/search — standalone Grok Live Search with automatic x402 payment. The exact price is in each call's 402 quote before you pay.
from blockrun_llm import SearchClient client = SearchClient() result = client.search( "Latest news on x402 adoption", sources=["x", "web"], max_results=10, ) print(result.summary) for url in result.citations or []: print(url) Decisions — typed judgments (decisions())
decisions() asks gpt-6-luna questions with a fixed answer space and gets one typed answer per question instead of text: a predicate (probability that it holds), a choice (one of your values, with per-value probabilities) or a score (position on an ordered rubric). Request and response match OpenAI's Decisions API. It is on LLMClient, AsyncLLMClient, SolanaLLMClient and AsyncSolanaLLMClient, with an API key or a wallet.
Pass model="gemini-decision-1" to use Google's Gemini Decision 1 (same price, up to 1,000 questions). It needs a description string on every choice and every score level; an empty string is fine. The SDK raises ValueError before sending when one is missing. gpt-6-luna accepts descriptions too, so the example above works on both models.
A score answer is the probability-weighted position on the rubric (0 = the first level), so it can be fractional: Gemini answered the example above with 1.43 (2% calm, 53% annoyed, 45% furious) where luna, all on "annoyed", gave 1. For a single level, take the entry in probabilities with the highest probability, or round.
Market Data (PriceClient)
Crypto, FX and commodity prices, OHLC history and symbol lists — all free, no payment and no wallet needed. Prices are daily closes, not realtime: responses carry realtime: false (delayed: true on sol.blockrun.ai) and name their source (Chainlink or Backpack). Pass require_wallet=False so the client does not insist on a wallet it never uses.
import time from blockrun_llm import PriceClient p = PriceClient(require_wallet=False) btc = p.price("crypto", "BTC-USD") print(btc.price, btc.source, btc.realtime) # e.g. 64712.9 backpack False eur = p.price("fx", "EUR-USD") gold = p.price("commodity", "XAU-USD") now = int(time.time()) bars = p.history("crypto", "BTC-USD", resolution="D", from_ts=now - 30 * 86400, to_ts=now) symbols = p.list_symbols("crypto", q="sol", limit=20) Equities are not served. stocks/{market} and the usstock alias still list symbols (p.list_symbols("stocks", market="us") answers normally; markets us, hk, jp, kr, gb, de, fr, nl, ie, lu, cn, ca), but price and history answer HTTP 501 ("We do not currently serve equity prices") on both blockrun.ai and sol.blockrun.ai, without a payment request. PriceClient raises that as an APIError with status_code == 501 and the gateway's error title as the message (e.g. API error: 501: US Stock price is not available):
from blockrun_llm import APIError try: p.price("stocks", "AAPL", market="us") except APIError as e: if e.status_code == 501: ... # equity prices are not available from the gateway Multi-chain RPC (RpcClient)
Standard JSON-RPC 2.0 access to 40 chains through one endpoint — Ethereum, Base, Solana, Polygon, BSC, 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.
from blockrun_llm import RpcClient client = RpcClient() # EVM chains speak eth_* JSON-RPC block = client.call("ethereum", "eth_blockNumber") print(int(block.result, 16)) balance = client.call( "base", "eth_getBalance", ["0x4200000000000000000000000000000000000006", "latest"], ) # Non-EVM chains speak their native JSON-RPC slot = client.call("solana", "getSlot") utxo_tip = client.call("bitcoin", "getblockcount") # Batch: one payment, per-element pricing ($0.002 x N) out = client.batch("polygon", [ {"method": "eth_blockNumber"}, {"method": "eth_gasPrice"}, ]) print(block.network) # "ethereum" (canonical key from X-Network) print(block.cache_hit) # True if served from the gateway's hot cache print(block.tx_hash) # x402 settlement tx 40 curated chains are exported as blockrun_llm.SUPPORTED_NETWORKS; common aliases (eth, arb, op, matic, bnb, avax, sol, btc, xrp, dot, ...) resolve server-side (blockrun_llm.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.
DeFi Data (Powered by DefiLlama)
GET passthrough to DefiLlama — protocols, TVL, yields, token prices. $0.005/call ($0.001 for price lookups). Methods live on LLMClient / AsyncLLMClient / SolanaLLMClient:
client = LLMClient() protocols = client.defi_protocols() # all protocols + TVL aave = client.defi_protocol("aave") # one protocol + historical TVL chains = client.defi_chains() # TVL by chain pools = client.defi_yields() # yield pools (APY/TVL) prices = client.defi_prices(["coingecko:bitcoin", "base:0x833589..."]) # Generic escape hatch data = client.defi("protocol/uniswap-v3") DEX Swaps (Powered by 0x)
Free passthrough to the 0x Swap + Gasless APIs — no x402 payment (BlockRun takes an on-chain affiliate fee on executed swaps instead).
# Indicative price, then firm quote (Permit2) price = client.dex_price(chainId=8453, sellToken="0x...", buyToken="0x...", sellAmount="1000000") quote = client.dex_quote(chainId=8453, sellToken="0x...", buyToken="0x...", sellAmount="1000000", taker="0xYourWallet") # Gasless flow: quote -> sign trade.eip712 -> submit -> poll gq = client.dex_gasless_quote(chainId=8453, sellToken="0x...", buyToken="0x...", sellAmount="1000000", taker="0xYourWallet") res = client.dex_gasless_submit({"trade": {...signed...}}) status = client.dex_gasless_status(res["tradeHash"]) client.dex_chains() # supported swap chains client.dex_gasless_chains() # supported gasless chains Cloud Compute (Powered by Modal)
Pay-per-call sandboxed compute — create a sandbox, run commands, tear it down. A small sandbox (up to 300 s, 1 CPU, 1024 MB) is a flat $0.01 to create on CPU, $0.05-$0.40 with a GPU; a longer-lived sandbox is billed hourly for its requested lifetime, upfront. Exec / status / terminate are $0.001 each. The 402 quote is the exact price.
sb = client.modal_sandbox_create(image="python:3.11") out = client.modal_sandbox_exec(sb["sandbox_id"], ["python", "-c", "print(40+2)"]) print(out["stdout"]) # 42 client.modal_sandbox_terminate(sb["sandbox_id"]) Fund a Wallet with Fiat (Coinbase Onramp)
Mint a one-time pay.coinbase.com link to buy Base USDC with a card or bank (60+ fiat currencies) — FREE (no x402 payment). The signature only authenticates the wallet, so the funding address must equal the signing wallet. Base / USDC only. The returned URL is single-use and expires in ~5 min, so mint it at click time and never cache it.
link = client.onramp(client.get_wallet_address()) print(link["url"]) # https://pay.coinbase.com/... — open to buy USDC on Base Prediction Markets (Powered by Predexon v2)
Access real-time prediction market data from Polymarket, Kalshi, Limitless, sports, and Binance Futures via Predexon. No Predexon account needed — pay per request with an API key or x402. Each call's exact price is in its 402 quote before you pay; live rates are at blockrun.ai/pricing.
Each method below is available on LLMClient (Base), AsyncLLMClient, and SolanaLLMClient.
For endpoints without a typed helper, drop down to pm() (GET) or pm_query() (POST). Same pricing, same return shape:
candles = client.pm("polymarket/candlesticks/0x1234abcd...") # OHLCV btc = client.pm("binance/candles/BTCUSDT") # crypto candles pairs = client.pm("matching-markets/pairs") # cross-platform pairs Exa Web Search (Powered by Exa)
Access Exa's neural web search via x402. No API keys needed — pay-per-request in USDC. Available on both LLMClient (Base, recommended) and SolanaLLMClient (Solana).
Search web, X/Twitter, and news without using a chat model:
Edit existing images with text prompts. The source image must be a data:image/...;base64,... data URI (plain URLs are not accepted):
from blockrun_llm import LLMClient, ImageClient # Via LLMClient client = LLMClient() result = client.image_edit( prompt="Make the sky purple and add northern lights", image="data:image/png;base64,...", # base64 data URI model="openai/gpt-image-1", ) print(result.data[0].url) # Via ImageClient img_client = ImageClient() result = img_client.edit("Add a rainbow", image="data:image/png;base64,...") # Multi-image fusion — pass a list of data URIs (e.g. a reference + a logo). # openai/* accepts up to 4 source images, google/* up to 3. result = img_client.edit( "Place the logo on the model's t-shirt", image=["data:image/png;base64,...", "data:image/png;base64,..."], model="google/nano-banana", ) print(result.data[0].url) Usage Examples
response_format and stop are OpenAI-compatible and honored across all providers by the gateway — native for OpenAI/Azure, and emulated for Anthropic/Bedrock (a raw-JSON system instruction with code-fence stripping for JSON mode, stop mapped to stop_sequences).
import json from blockrun_llm import LLMClient client = LLMClient() # JSON mode — guaranteed parseable JSON, no markdown fences response = client.chat( "openai/gpt-4o", "List 3 primary colors as a JSON array under key 'colors'.", response_format={"type": "json_object"}, ) print(json.loads(response)) # {'colors': ['red', 'green', 'blue']} # Stop sequences (str or list, up to 4) result = client.chat_completion( "openai/gpt-5.2", [{"role": "user", "content": "Count: Alpha Beta Gamma"}], stop=["Beta"], ) print(result.choices[0].message.content) # "Count: Alpha " Real-time Search (Live Search)
Note: Live Search can take 30-120+ seconds as it searches multiple sources. The SDK automatically uses a 5-minute timeout for search requests.
import asyncio from blockrun_llm import AsyncLLMClient async def main(): async with AsyncLLMClient() as client: # Simple chat response = await client.chat("openai/gpt-5.2", "Hello!") print(response) # Multiple requests concurrently tasks = [ client.chat("openai/gpt-5.2", "What is 2+2?"), client.chat("anthropic/claude-sonnet-4.6", "What is 3+3?"), client.chat("google/gemini-2.5-flash", "What is 4+4?"), ] responses = await asyncio.gather(*tasks) for r in responses: print(r) asyncio.run(main()) List Available Models
For development and testing without real USDC, use the testnet:
from blockrun_llm import testnet_client # Create testnet client (uses Base Sepolia) client = testnet_client() # Uses BLOCKRUN_WALLET_KEY # Chat with testnet model response = client.chat("openai/gpt-oss-20b", "Hello!") print(response) # Check testnet USDC balance balance = client.get_balance() print(f"Testnet USDC: ${balance:.4f}") Testnet Setup
Get testnet ETH from Alchemy Base Sepolia Faucet
Get testnet USDC from Circle USDC Faucet
Set your wallet key: export BLOCKRUN_WALLET_KEY=0x...
Available Testnet Models
openai/gpt-oss-20b (flat price per request)
openai/gpt-oss-120b (flat price per request)
Manual Testnet Configuration
from blockrun_llm import LLMClient # Or configure manually client = LLMClient(api_url="https://testnet.blockrun.ai/api") response = client.chat("openai/gpt-oss-20b", "Hello!") Billing & Cost Tracking
Every paid call appends one line to ~/.blockrun/cost_log.jsonl capturing timestamp, endpoint, cost, and (when available) model, wallet, network, and client_kind. The SDK ships a small reader / exporter on top so you can audit spending without leaving the Python ecosystem.
# Aggregated summary, default grouped by endpoint python -m blockrun_llm.billing summary # Group by model / month / wallet / network / client_kind / day python -m blockrun_llm.billing summary --group-by model python -m blockrun_llm.billing summary --group-by month --from 2026-04-01 # Filter by wallet (when one machine drives multiple keys) python -m blockrun_llm.billing summary --wallet 0xCC8c... --network base-mainnet # Export per-call records python -m blockrun_llm.billing export csv --from 2026-05-01 --output may.csv python -m blockrun_llm.billing export json --to 2026-05-09 Python API
from blockrun_llm import ( get_cost_log_summary, export_cost_log_csv, export_cost_log_json, ) summary = get_cost_log_summary(group_by="model", from_date="2026-04-01") print(summary["total_usd"], summary["calls"]) for model, slot in summary["groups"].items(): print(f" {model:40s} {slot['calls']:>5} ${slot['cost_usd']:.4f}") # Returns CSV / JSON text; pass output_path to also write to disk csv_text = export_cost_log_csv("bill.csv", from_date="2026-05-01") json_text = export_cost_log_json(from_date="2026-05-01") Example output
Real session — four cheap chat calls across providers, then queried by model:
$ python -m blockrun_llm.billing summary --from 2026-05-10 --group-by model ================================================================ BLOCKRUN — LOCAL COST LOG SUMMARY ================================================================ log file : /Users/me/.blockrun/cost_log.jsonl from : 2026-05-10 group_by : model total : $0.0070 (9 calls) KEY CALLS COST ---------------------------- ------- ---------- deepseek/deepseek-chat 2 $0.0020 google/gemini-2.5-flash-lite 1 $0.0010 anthropic/claude-haiku-4.5 1 $0.0010 zai/glm-5-turbo 1 $0.0010 unknown 4 $0.0020 The four unknown rows are pre-existing entries from before this release — they had only {ts, endpoint, cost_usd} so the model column reads unknown. Calls made after upgrading carry the full metadata (wallet / network / client_kind / model). CSV export shows it directly:
$ python -m blockrun_llm.billing export csv --from 2026-05-10 | head -3 ts_iso,endpoint,model,wallet,network,client_kind,cost_usd 2026-05-10T03:38:28.198937+00:00,/v1/chat/completions,deepseek/deepseek-chat,0xCC8c...5EF8,base-mainnet,LLMClient,0.001 2026-05-10T03:38:31.192060+00:00,/v1/chat/completions,google/gemini-2.5-flash-lite,0xCC8c...5EF8,base-mainnet,LLMClient,0.001 Scope
The cost log is per-machine. It records calls made by this Python SDK only — calls from other clients (TS SDK, MCP, raw curl) are not included. For organization-wide billing, query the gateway's authoritative ledger.
Transaction Log (project-local, on-chain match)
The cost log above lives in ~/.blockrun/ and is hash-keyed JSON. When you'd rather have an eyeballable text log next to your code that matches the chain row-for-row, opt into the per-transaction log:
from blockrun_llm import LLMClient # Default: writes ./log/transactions.log client = LLMClient(transaction_log=True) # Or pick a path client = LLMClient(transaction_log="./var/blockrun.log") # Or via env var: BLOCKRUN_TX_LOG=1 (default dir) # BLOCKRUN_TX_LOG=./var/blockrun.log Works the same on AsyncLLMClient, SolanaLLMClient, and AsyncSolanaLLMClient.
Every paid call appends one row. Example:
2026-05-21 15:44:46 chat anthropic/claude-sonnet-4.6 in= 3 out=4 $0.034137 0x6513d128… 2026-05-20 04:34:17 chat openai/gpt-5.5 in= 14 out=18 $0.001000 0x421796a3… Columns: timestamp · endpoint tag (chat/image/video/search/…) · model (padded to 30) · in= prompt tokens · out= completion tokens · $cost to 6 decimals · first 10 chars of the on-chain settlement hash.
Why it matches the chain
The hash comes from the X-PAYMENT-RESPONSE header the x402 facilitator returns after settlement — Base txs use transaction, Solana uses signature. Both normalise to the truncated 0x… / signature shown in the row, so each line is verifiable in one click:
Base mainnet → https://basescan.org/tx/
Solana mainnet → https://solscan.io/tx/
Cached / free responses don't hit the chain, so they show (no-tx) instead.
Scope and trade-offs
Independent of the cache layer. Enabling the log does not change ~/.blockrun/cache/, ~/.blockrun/data/, or ~/.blockrun/cost_log.jsonl.
Best-effort writes. OSErrors are swallowed; a read-only filesystem can't break a paid call.
Plain text only. If you need a structured ledger as well, query ~/.blockrun/cost_log.jsonl via blockrun_llm.billing.
from blockrun_llm import TransactionLogger, format_row # Tail the project log logger = TransactionLogger("./log") for row in logger.entries()[-5:]: print(row) # Build your own row (e.g. for tests or custom adapters) print(format_row( endpoint="/v1/chat/completions", model="openai/gpt-5.5", in_tokens=14, out_tokens=18, cost_usd=0.001, tx_hash="0x421796a3deadbeef", )) Environment Variables
One credential is required — an API key or a wallet key. Everything else is optional.
BLOCKRUN_API_KEY_URL is deliberately not BLOCKRUN_API_URL: that one names an x402 gateway, and an API-key client must never follow it and send your key to a host you configured for a different rail.
Setting Up Your Wallet
Create a wallet on Base network (Coinbase Wallet, MetaMask, etc.)
Get some ETH on Base for gas (small amount, ~$1)
Get USDC on Base for API payments
Export your private key and set it as BLOCKRUN_WALLET_KEY
# .env file BLOCKRUN_WALLET_KEY=0x...your_private_key_here Error Handling
from blockrun_llm import LLMClient, APIError, PaymentError client = LLMClient() try: response = client.chat("openai/gpt-5.2", "Hello!") except PaymentError as e: print(f"Payment failed: {e}") # Check your USDC balance except APIError as e: print(f"API error ({e.status_code}): {e}") Testing
Unit tests do not require API access or funded wallets:
pytest tests/unit # Run unit tests only pytest tests/unit --cov # Run with coverage report pytest tests/unit -v # Verbose output Running Integration Tests
Integration tests call the production API and require:
A funded Base wallet with USDC ($1+ recommended)
BLOCKRUN_WALLET_KEY environment variable set
Estimated cost: ~$0.05 per test run
export BLOCKRUN_WALLET_KEY=0x... pytest tests/integration # Run integration tests only pytest # Run all tests Integration tests are automatically skipped if BLOCKRUN_WALLET_KEY is not set.
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 .env files 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.
address = client.get_wallet_address() print(f"View transactions: https://basescan.org/address/{address}") Keep Updated:
pip install --upgrade blockrun-llm # Get security patches Agent Wallet Setup
One-line setup for agent runtimes (Claude Code skills, MCP servers, etc.):
from blockrun_llm import setup_agent_wallet # Auto-creates wallet if none exists, returns ready client client = setup_agent_wallet() response = client.chat("openai/gpt-5.4", "Hello!") For Solana:
from blockrun_llm import status status() # Wallet: 0xCC8c...5EF8 # Balance: $5.30 USDC Wallet Discovery and Migration
The SDK can discover compatible wallets for an explicit, user-confirmed migration. It never automatically makes a discovered provider wallet active:
from blockrun_llm.wallet import scan_wallets from blockrun_llm.solana_wallet import scan_solana_wallets # Scans ~/.
Upgrading from a provider wallet
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:
from blockrun_llm import list_discovered_wallets, import_wallet for w in list_discovered_wallets(): print(w["address"], "from", w["source"]) import_wallet("0x88f9B82462f6C4bf4a0Fb15e5c3971559a316e7f") import_wallet() writes your current wallet to ~/.blockrun/.session.backup-
Addresses shown are derived from the discovered key itself, and import_wallet() matches on that derived address — so a wallet file cannot claim an address it cannot sign for, nor be adopted by one. list_discovered_wallets() never returns private keys.
For a single run without changing anything, use export BLOCKRUN_WALLET_KEY=
The SDK caches responses to avoid duplicate payments:
from blockrun_llm import clear_cache # Automatic TTLs by endpoint: # - Prediction Markets: 30 minutes # - Search: 15 minutes # - Models: 24 hours # - Chat/Image: no cache (every call is unique) # Manual cache management removed = clear_cache() # Remove all cached responses Per-session spending is also available on any client (see also Billing & Cost Tracking for the full surface):
Use the official Anthropic Python SDK with BlockRun's API gateway and automatic x402 payments:
pip install blockrun-llm[anthropic] from blockrun_llm import AnthropicClient client = AnthropicClient() # Auto-detects wallet, auto-pays response = client.messages.create( model="claude-sonnet-4-6", max_tokens=1024, messages=[{"role": "user", "content": "Hello!"}] ) print(response.content[0].text) # Works with any BlockRun model in Anthropic format response = client.messages.create( model="openai/gpt-5.4", max_tokens=1024, messages=[{"role": "user", "content": "Hello from GPT!"}] ) The AnthropicClient wraps anthropic.Anthropic with a custom httpx transport that handles x402 payment signing transparently. Your private key never leaves your machine.
Frequently Asked Questions
What is blockrun-llm?
blockrun-llm is a Python SDK that provides pay-per-request access to 97 large language models from OpenAI, Anthropic, Google, DeepSeek, NVIDIA, ZAI, and more. Pay with a BlockRun API key (prepaid credit from user.blockrun.ai) or with automatic x402 USDC micropayments from your own wallet — no subscriptions, no vendor lock-in.
How does payment work?
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.
What is smart routing / Router Core?
Router Core is BlockRun's built-in routing engine — shared with the TypeScript SDK and the gateway, so the same request routes the same way everywhere. It scores your request across 15 dimensions, drops every model that can't actually handle it (context, output length, tools, vision), then picks the cheapest capable one and keeps the rest as a fallback chain. Routing happens locally in under 1ms and makes no extra model call. It can save up to 84% on LLM costs compared to using premium models for every request.
How much does it cost?
Pay only for what you use. Prices start at FREE (9 free models). Live per-model prices are at blockrun.ai/pricing. There are no minimums, subscriptions, or monthly fees. $5 in USDC gets you thousands of requests.
Can I use it with Solana?
Yes. Install with pip install blockrun-llm[solana] and use SolanaLLMClient instead of LLMClient. Same API, different payment chain.
Changing payment methods safely
Register at user.blockrun.ai, add credit in Credits, and create a key in API keys. Set BLOCKRUN_API_KEY or pass the key as the client's credential. Check activity and actual charges in the dashboard; local cost summaries may omit charges without a gateway receipt.
An explicit wallet credential chooses wallet payments even when BLOCKRUN_API_KEY is set. Choose the Solana wallet client for Solana, or the Base wallet client for Base. A BLOCKRUN_API_KEY set to something that is not a brk_ key fails instead of silently selecting a wallet and spending USDC you meant to keep. Blank counts as unset, so BLOCKRUN_API_KEY= in a .env file or an unpopulated CI secret still falls back to the wallet. Create a new client when changing credentials; an existing client keeps its original account.
The optional AnthropicClient also accepts a BlockRun API key as its credential or through BLOCKRUN_API_KEY (pip install 'blockrun-llm[anthropic]'). Automatic retries are disabled by default on both payment rails, because a failed response may follow a billable request. It matters most on the wallet rail, where the x402 transport signs a fresh payment for every 402 it sees: at the Anthropic SDK's own default of 2 retries, one messages.create() that 5xxs after the gateway settled would sign and settle three separate on-chain transfers. Pass max_retries= explicitly to opt back in.
The optional integration currently supports Anthropic SDK 0.x. The extra pins <1 because Anthropic 1.x moved to a different HTTP transport; upgrading that dependency independently would break both account and wallet clients.
Released: Nov 28, 2026
Both files in this release have provenance metadata.
View provenance details
MIT View SPDX License List
anthropic dev solana
ai base claude dall-e free-models gemini image-generation llm micropayments nvidia openai usdc x402 zai
Development Status 4 - Beta
Intended Audience Developers
License OSI Approved :: MIT License
Programming Language Python :: 3
Topic Scientific/Engineering :: Artificial Intelligence
Release files for blockrun-llm 1.24.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
Built distribution (wheel)
Total release size: 986.1 kB
Release files / blockrun_llm-1.24.0.tar.gz
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Release files / blockrun_llm-1.24.0-py3-none-any.whl
Security for blockrun-llm 1.24.0
Both files in this release have been uploaded with provenance metadata.
With provenance blockrun_llm-1.24.0.tar.gz Nov 28, 2026
With provenance blockrun_llm-1.24.0-py3-none-any.whl Nov 28, 2026
Attestation for blockrun_llm-1.24.0.tar.gz
Attestation for blockrun_llm-1.24.0-py3-none-any.whl
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.
Release history Release notifications | RSS feed
Nov 28, 2026 2 release files Full provenance
Nov 18, 2026 2 release files Full provenance
Nov 16, 2026 2 release files Full provenance
Nov 14, 2026 2 release files Full provenance
Nov 12, 2026 2 release files Full provenance
Nov 10, 2026 2 release files Full provenance
Nov 8, 2026 2 release files Full provenance
Nov 7, 2026 2 release files Full provenance
Oct 27, 2026 2 release files Full provenance
Oct 20, 2026 2 release files Full provenance
Oct 12, 2026 2 release files Full provenance
Oct 11, 2026 2 release files Full provenance
Oct 2, 2026 2 release files Loss of provenance
Sep 30, 2026 2 release files Full provenance
Sep 16, 2026 2 release files Full provenance
Sep 8, 2026 2 release files Full provenance
Sep 5, 2026 2 release files Full provenance
Aug 31, 2026 2 release files Full provenance
Aug 26, 2026 2 release files Loss of provenance
Aug 19, 2026 2 release files Full provenance
Aug 16, 2026 2 release files Loss of provenance
Aug 12, 2026 2 release files Full provenance
Jul 28, 2026 2 release files Full provenance
Jul 21, 2026 2 release files Full provenance
Jul 19, 2026 2 release files Loss of provenance
Jul 16, 2026 2 release files Loss of provenance
Jul 15, 2026 2 release files Full provenance
Jul 15, 2026 2 release files No provenance
Jul 8, 2026 2 release files No provenance
Jul 6, 2026 2 release files No provenance
Jun 26, 2026 2 release files Loss of provenance
Jun 24, 2026 2 release files Loss of provenance
Jun 19, 2026 2 release files Loss of provenance
Jun 18, 2026 2 release files Loss of provenance
Jun 17, 2026 2 release files Loss of provenance
Jun 15, 2026 2 release files Full provenance
Jun 14, 2026 2 release files Full provenance
Jun 11, 2026 2 release files No provenance
Jun 9, 2026 2 release files No provenance
Jun 8, 2026 2 release files No provenance
Jun 7, 2026 2 release files No provenance
Jun 6, 2026 2 release files No provenance
Jun 2, 2026 2 release files No provenance
Jun 1, 2026 2 release files No provenance
May 31, 2026 2 release files No provenance
May 29, 2026 2 release files No provenance
May 28, 2026 2 release files No provenance
May 27, 2026 2 release files No provenance
May 26, 2026 2 release files No provenance
May 25, 2026 2 release files No provenance
May 23, 2026 2 release files No provenance
May 22, 2026 2 release files No provenance
May 18, 2026 2 release files No provenance
May 16, 2026 2 release files No provenance
May 14, 2026 2 release files No provenance
May 12, 2026 2 release files No provenance
May 8, 2026 2 release files No provenance
Apr 25, 2026 2 release files No provenance
Apr 19, 2026 1 release file No provenance
Apr 7, 2026 2 release files No provenance
Mar 24, 2026 2 release files Loss of provenance
Mar 23, 2026 2 release files Loss of provenance
Mar 13, 2026 2 release files Loss of provenance
Mar 13, 2026 2 release files Full provenance
Mar 12, 2026 2 release files Full provenance
Feb 27, 2026 2 release files No provenance
Feb 8, 2026 2 release files No provenance
Jan 28, 2026 2 release files No provenance
Jan 27, 2026 2 release files No provenance
Jan 18, 2026 2 release files No provenance
Jan 15, 2026 2 release files No provenance
Jan 14, 2026 2 release files No provenance
Dec 29, 2025 2 release files Full provenance
"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.
© 2026 Python Software Foundation
Deployed from fc0d8e6











