Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 105 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# BlockRun LLM SDK (Python)

> **blockrun-llm** is a Python SDK for accessing 80+ large language models (GPT-5.x, Claude 4.x, Gemini 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 Pyth-backed market data — all with automatic pay-per-request USDC micropayments via the x402 protocol. No API keys required; your wallet signature is your authentication. Built for AI agents that need to operate autonomously.
> **blockrun-llm** is a Python SDK for accessing 80+ large language models (GPT-5.x, Claude 4.x, Gemini 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 Pyth-backed market data — with account API keys or automatic pay-per-request USDC micropayments via x402 on Solana and Base. Built for AI agents that need to operate autonomously.
>
> 🆓 **Includes 8 fully-free NVIDIA-hosted models** — DeepSeek V4 Flash (1M context), Nemotron Nano Omni (vision), Qwen3 Next + Coder, Llama 4 Maverick, Mistral Small 4, plus `gpt-oss-120b/20b` (hidden from `/v1/models` but direct calls still work). Zero USDC, no rate-limit gimmicks. Use `routing_profile="free"` or call any `nvidia/*` model directly.

Expand All @@ -13,32 +13,92 @@

| Chain | Network | Payment | Status |
|-------|---------|---------|--------|
| **Base** | Base Mainnet (Chain ID: 8453) | USDC | ✅ Primary |
| **Solana** | Solana Mainnet | USDC (SPL) | ✅ Preferred for new wallets |
| **Base** | Base Mainnet (Chain ID: 8453) | USDC | ✅ Supported |
| **Base Testnet** | Base Sepolia (Chain ID: 84532) | Testnet USDC | ✅ Development |
| **Solana** | Solana Mainnet | USDC (SPL) | ✅ New |


**Protocol:** x402 v2

## Installation

> **Release status:** As of September 4, 2026, PyPI `blockrun-llm==1.14.0` does not include the account API support described below. These examples apply to this source checkout; install it with `pip install .` for local evaluation. Use a release containing these changes once published.

```bash
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 # Published release; see API release status above
pip install blockrun-llm[solana] # Solana (preferred) + Base wallet payments
pip install blockrun-llm[dev] # Base + dev tools (pytest, black, ruff, mypy)
pip install blockrun-llm[dev,solana] # Everything
```

For the API-enabled source checkout, run from its repository root:

```bash
python -m pip install .
# Optional Solana wallet dependencies:
python -m pip install '.[solana]'
```

## Quick Start

### Account API key

Register at [user.blockrun.ai](https://user.blockrun.ai), create a key in
[API Keys](https://user.blockrun.ai/dashboard/keys), and add credits in
[Credits](https://user.blockrun.ai/dashboard/credits).

```bash
export BLOCKRUN_API_KEY="brk_live_..."
```

```python
from blockrun_llm import LLMClient

client = LLMClient() # Uses BLOCKRUN_WALLET_KEY (never sent to server)
response = client.chat("openai/gpt-5.2", "Hello!")
with LLMClient() as client: # Also accepts api_key="brk_live_..."
print(client.chat("openai/gpt-5.2", "Hello!"))
```

That's it. The SDK handles x402 payment automatically.
API mode uses `https://api.blockrun.ai/v1`, requires no wallet, and supports
sync/async chat and streaming, media clients (including async job polling),
search, tools, and the optional `AnthropicClient`. Use `APIClient` or
`AsyncAPIClient` for Responses and other account API endpoints:

```python
from blockrun_llm import APIClient

with APIClient() as client:
response = client.post("/v1/responses", {"model": "openai/gpt-5.2", "input": "Hello!"})
```

All native clients accept `api_key`; alternatively set `BLOCKRUN_API_KEY`.
An explicit `private_key` selects wallet mode even if that environment variable
is present. Passing both explicit credentials raises an error. Override the
account endpoint with `api_url` or `BLOCKRUN_API_BASE_URL` (`/v1` is optional).
Account HTTP 402 means insufficient account credits and never triggers a wallet
payment. Check account balance, usage, and billing in the portal; wallet balance
and spending helpers require wallet mode. Wallet spend-limit options and environment
variables are rejected in API mode; configure account limits in the portal. Account requests bypass wallet response
caches. Polling keeps credentials on the configured origin and does not follow
redirects.

### Wallet payments: Solana first

```bash
pip install 'blockrun-llm[solana]'
```

```python
from blockrun_llm import setup_agent_client

client = setup_agent_client()
print(client.chat("openai/gpt-5.2", "Hello!"))
```

This helper uses an API key when configured. Otherwise it preserves your saved
chain or existing Base-only wallet, and defaults new wallets to Solana. Pass
`chain="base"` to choose Base. The existing `LLMClient` and `setup_agent_wallet`
remain Base-specific in wallet mode; `SolanaLLMClient` and
`setup_agent_solana_wallet` remain Solana-specific.

### Try It Free (No USDC Required)

Expand Down Expand Up @@ -232,9 +292,12 @@ string describing why that model won.

## How Payment Works

No API keys, no subscription. You hold USDC on Base in your own wallet, and
**each request pays for itself** with an on-chain micropayment. There are two
phases:
**Account API:** set `BLOCKRUN_API_KEY` to pay from prepaid account credits,
without a wallet. Manage credits and usage in the [account dashboard](https://user.blockrun.ai/dashboard).

**Wallet x402:** pay per request with USDC on Solana (preferred for new wallets)
or Base. A wallet signature authenticates each payment; no account API key is
required. The following funding example uses Base:

### Phase 1 — Fund your wallet once (USDC on Base)

Expand Down Expand Up @@ -767,8 +830,7 @@ client.release_number(bought["phone_number"]) # free

`SurfClient` wraps `/v1/surf/*` — the asksurf.ai partner gateway, ~83 crypto
endpoints across exchanges, on-chain SQL, prediction markets (Polymarket +
Kalshi), wallets, social analytics, and project intelligence. Tiered pricing:
$0.001 / $0.005 / $0.020 per call (tier 1 / 2 / 3).
Kalshi), wallets, social analytics, and project intelligence. All tiers currently cost $0.0075/call.

```python
from blockrun_llm import SurfClient
Expand All @@ -777,7 +839,7 @@ client = SurfClient()

# Discovery
print(SurfClient.endpoints()) # full catalog
print(client.price("market/ranking")) # 0.001
print(client.price("market/ranking")) # 0.0075
print(client.endpoint_info("onchain/sql")) # {'method': 'POST', 'tier': 3, ...}

# GET — pass query params (validated against the catalog)
Expand All @@ -791,6 +853,8 @@ rows = client.post("onchain/sql", {"query": "SELECT count() FROM ethereum.blocks
result = client.call("token/holders", params={"address": "0x...", "chain": "ethereum"})
```

These service prices are estimates; the gateway quote and account Activity receipt are authoritative. Wallet payment-rail fees may apply separately.

## Standalone Search (`SearchClient`)

`SearchClient` wraps `POST /v1/search` — standalone Grok Live Search with
Expand Down Expand Up @@ -846,8 +910,8 @@ Supported stock markets: `us, hk, jp, kr, gb, de, fr, nl, ie, lu, cn, ca`.

Standard JSON-RPC 2.0 access to <!-- br:chains.rpc -->40<!-- /br:chains.rpc --> 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.
more (powered by Tatum's RPC gateway). No separate Tatum API key or per-chain endpoint is needed. Calls use account
credits or the selected x402 wallet; a JSON-RPC batch is priced per element.

```python
from blockrun_llm import RpcClient
Expand Down Expand Up @@ -955,10 +1019,12 @@ 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](https://predexon.com). No API keys needed — pay-per-request via x402. Tier 1 endpoints are $0.001/call, Tier 2 (wallet identity / clustering) are $0.005/call.
Access real-time prediction market data from Polymarket, Kalshi, Limitless, sports, and Binance Futures via [Predexon](https://predexon.com). Use a BlockRun account API key or x402 wallet payments; no separate Predexon key is needed. All tiers currently cost $0.0075/call.

Each method below is available on `LLMClient` (Base), `AsyncLLMClient`, and `SolanaLLMClient`.

These service prices are estimates; the gateway quote and account Activity receipt are authoritative. Wallet payment-rail fees may apply separately.

### Typed helpers

| Method | Endpoint | Tier |
Expand Down Expand Up @@ -1019,7 +1085,7 @@ pairs = client.pm("matching-markets/pairs") # cross-platform p

## Exa Web Search (Powered by Exa)

Access [Exa](https://exa.ai)'s neural web search via x402. No API keys needed — pay-per-request in USDC. Available on both `LLMClient` (Base, recommended) and `SolanaLLMClient` (Solana).
Access [Exa](https://exa.ai)'s neural web search using account credits or x402 wallet payments. No separate Exa key is needed. Use `SolanaLLMClient` for a Solana wallet or `LLMClient` for a Base wallet; availability depends on the selected gateway.

| Endpoint | Method | Price |
|---|---|---|
Expand Down Expand Up @@ -1056,8 +1122,7 @@ result = client.exa("search", {"query": "transformer architecture", "numResults"
```

For Solana payments use `from blockrun_llm import SolanaLLMClient` — same method
names, same call shape; the Solana gateway requires the backend to be configured
with `EXA_API_KEY`, so prefer Base unless you need SOL/SPL settlement.
names and call shape. The selected gateway must support the requested service.

## Standalone Search

Expand Down Expand Up @@ -1462,7 +1527,9 @@ print(format_row(
| Variable | Description | Required |
|----------|-------------|----------|
| `BLOCKRUN_WALLET_KEY` | Your Base chain wallet private key | Yes (or pass to constructor) |
| `BLOCKRUN_API_URL` | API endpoint | No (default: https://blockrun.ai/api) |
| `BLOCKRUN_API_KEY` | Account API key; no payment wallet required | Account mode |
| `BLOCKRUN_API_BASE_URL` | Account gateway override (default: https://api.blockrun.ai/v1) | No |
| `BLOCKRUN_API_URL` | Wallet gateway endpoint | No (default: https://blockrun.ai/api) |

## Setting Up Your Wallet

Expand Down Expand Up @@ -1679,7 +1746,7 @@ print(f"Session: ${spending['total_usd']:.4f} across {spending['calls']} calls")

## Anthropic SDK Compatibility

Use the official Anthropic Python SDK with BlockRun's API gateway and automatic x402 payments:
Use the official Anthropic Python SDK with BlockRun account API credits or automatic x402 wallet payments:

```bash
pip install blockrun-llm[anthropic]
Expand Down Expand Up @@ -1717,10 +1784,10 @@ The `AnthropicClient` wraps `anthropic.Anthropic` with a custom httpx transport
## Frequently Asked Questions

### What is blockrun-llm?
blockrun-llm is a Python SDK that provides pay-per-request access to 43+ large language models from OpenAI, Anthropic, Google, DeepSeek, NVIDIA, ZAI, and more. It uses the x402 protocol for automatic USDC micropayments — no API keys, no subscriptions, no vendor lock-in.
blockrun-llm is a Python SDK for BlockRun models, media, search and data APIs. Authenticate with a BlockRun account API key and use prepaid credits, or pay per request with USDC via x402 on Solana or Base. [Register and get started](https://user.blockrun.ai).

### 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.
With `BLOCKRUN_API_KEY`, calls use bearer authentication and account credits; no wallet is required. In wallet mode, the SDK signs the x402 payment locally and includes payment proof in the request. Wallet payments use USDC on Solana or Base.

### 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 <!-- br:clawrouter.dimensions -->15<!-- /br:clawrouter.dimensions --> 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 <!-- br:savings.autoVsBaselinePct -->84<!-- /br:savings.autoVsBaselinePct -->% on LLM costs compared to using premium models for every request.
Expand All @@ -1734,3 +1801,17 @@ Yes. Install with `pip install blockrun-llm[solana]` and use `SolanaLLMClient` i
## License

MIT


## Account setup, billing, and switching back to wallets

1. [Sign in to BlockRun](https://user.blockrun.ai), open [Billing](https://user.blockrun.ai/dashboard/credits), and add prepaid account credits. The checkout shows both the credit amount and the total card charge, including any processing fee; these amounts can differ.
2. Create a key on [API Keys](https://user.blockrun.ai/dashboard/keys). Keep it in your server or local process environment as `BLOCKRUN_API_KEY`; never put it in browser code, logs, or a repository. Follow this README's client configuration example.
3. Check [Activity](https://user.blockrun.ai/dashboard/activity) after a call. Chat uses reported token usage; media and data services can use per-image, duration, or per-request prices. Account credits and an on-chain USDC wallet are separate balances. Local wallet spend counters are not account receipts.
4. A 401 means check the API key, 402 means check account credits or account status, and 429 means respect `Retry-After`. Poll an accepted media job using the complete returned `poll_url`, including its query parameters, with the same account key. Do not reconstruct the URL from the job ID. If polling times out, check that job and Activity before submitting another paid job.

Accepted account jobs recover from temporary gateway polling errors by querying the same job within the original deadline. They do not resubmit the paid creation request. Authentication, credit, and rate-limit errors remain visible to the caller.

The Anthropic account wrapper defaults to `max_retries=0` to avoid replaying potentially billed POSTs; explicitly overriding this option opts into the upstream SDK's retry behavior. Wallet mode keeps its existing behavior.

To return to wallet billing, unset `BLOCKRUN_API_KEY` and create a new wallet client, or pass an explicit `private_key` to the appropriate wallet client. Existing wallet keys are preserved. Choose Solana for new wallets, or keep an existing Base wallet. Do not pass an explicit API key and private key together.
11 changes: 8 additions & 3 deletions blockrun_llm/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""
BlockRun LLM SDK - Pay-per-request AI via x402 on Base (USDC)
BlockRun SDK - Account API credits or x402 USDC wallets on Solana and Base

For developers (bring your own wallet):
from blockrun_llm import LLMClient

client = LLMClient() # Uses BLOCKRUN_WALLET_KEY from env
client = LLMClient() # BLOCKRUN_API_KEY for account credits; otherwise a Base wallet
response = client.chat("openai/gpt-5.2", "Hello!")
print(response)

Expand Down Expand Up @@ -43,7 +43,7 @@
result = client.generate("Welcome to BlockRun.", voice="sarah")
print(result.data[0].url) # audio URL

Multi-chain RPC (40+ chains, $0.002/call):
Multi-chain RPC (40+ chains; gateway pricing applies):
from blockrun_llm import RpcClient

client = RpcClient()
Expand All @@ -57,6 +57,7 @@
from __future__ import annotations

from .anthropic_client import AnthropicClient
from .api_client import APIClient, AsyncAPIClient
from .cache import (
clear_cache,
export_cost_log_csv,
Expand All @@ -79,6 +80,7 @@
from .realface import RealFaceClient
from .rpc import NETWORK_ALIASES, SUPPORTED_NETWORKS, RpcClient
from .search import SearchClient
from .setup import setup_agent_client
from .solana_client import AsyncSolanaLLMClient, SolanaLLMClient
from .solana_wallet import (
create_solana_wallet,
Expand Down Expand Up @@ -193,8 +195,10 @@
"SUPPORTED_NETWORKS",
"WALLET_DIR",
"WALLET_FILE",
"APIClient",
"APIError",
"AnthropicClient",
"AsyncAPIClient",
"AsyncLLMClient",
"AsyncSolanaLLMClient",
"AudioModel",
Expand Down Expand Up @@ -307,6 +311,7 @@
"save_wallet_qr",
"scan_solana_wallets",
"scan_wallets",
"setup_agent_client",
# Solana wallet utilities
"setup_agent_solana_wallet",
# Entry point for agents (auto-creates wallet)
Expand Down
Loading
Loading