Skip to content

Instantly share code, notes, and snippets.

@kmjones1979
Last active February 10, 2026 23:57
Show Gist options
  • Select an option

  • Save kmjones1979/9c7239a7ed81b09d305b3d17638446f4 to your computer and use it in GitHub Desktop.

Select an option

Save kmjones1979/9c7239a7ed81b09d305b3d17638446f4 to your computer and use it in GitHub Desktop.
Example script to showcase blockrun x ampersend

Demo Script: Ampersend x BlockRun AgentOps

Presenter notes for a live demo. Assumes wallets are funded and .env is configured.


Setup Checklist (before going live)

  • .env populated with seller + buyer wallet credentials
  • Buyer wallet funded with testnet USDC on Base Sepolia
  • Seller wallet funded with testnet USDC on Base Sepolia (to pay BlockRun)
  • Ampersend dashboard open with buyer wallet's daily spend limit visible
  • Daily spend limit set low enough to trigger during the load test (e.g. $0.01)
  • uv sync has been run
  • Two terminal windows ready (seller + buyer)

Part 1: The Problem

Talking point:

A multi-agent system ran up $47,000 in costs when two AI agents entered a recursive loop for 11 days — with no monitoring, no budget cap, and no way to stop it.

"What if every AI agent request required a real payment — one that could be capped, monitored, and stopped on-chain?"

That's what we built. Ampersend wallets + x402 payments + BlockRun's LLM API — together they create a system where AI agents cannot overspend because the wallet itself enforces the budget.


Part 2: Architecture Walkthrough

Show the diagram:

Buyer Agent → A2A (x402 payment) → Seller Agent → X402Transport → BlockRun API
     │                                    │                              │
     │  Ampersend Treasurer               │  Ampersend HTTP Client       │  LLM Inference
     │  (signs payments)                  │  (signs payments)            │  (pay-per-query)
     └────────────────────────────────────┴──────────────────────────────┘
                        All payments settle on Base (USDC)

Talking points:

  • Two on-chain wallets: one for the buyer, one for the seller. Both are Ampersend smart accounts.
  • The buyer pays the seller for access to the LLM (via x402 over A2A protocol).
  • The seller pays BlockRun for the actual inference (also via x402, transparently).
  • Every payment is a real USDC transfer on Base — verifiable on-chain.
  • The Ampersend dashboard lets you set daily spending limits per wallet. When the limit is hit, the wallet refuses to sign — the agent is stopped at the protocol level, not the application level.

Part 3: Code Walkthrough — Seller

Open src/blockrun_agent/seller.py

3a. The Big Picture — Zero Custom Logic

Talking point: Before we look at the code, notice what the seller doesn't have. No custom payment logic. No token handling. No receipt verification. The entire seller is just four existing primitives composed together. Let's walk through them.

3b. The Payment Stack (_create_agent)

Scroll to _create_agent (line 79)

Layer 1 — Outbound payments (seller pays BlockRun):

self._httpx_client = create_ampersend_http_client(
    smart_account_address=...,
    session_key_private_key=...,
)

Talking point: One function from the Ampersend SDK. This wraps httpx so that when BlockRun returns a 402 Payment Required, the client automatically signs a USDC payment and retries. The seller's code never sees the 402 — it's handled at the transport layer.

Layer 2 — api_key="x402" (pause here):

openai_client = openai.AsyncOpenAI(
    http_client=self._httpx_client,
    base_url="https://testnet.blockrun.ai/api/v1",
    api_key="x402",
)

Point at api_key="x402" — let this land.

Talking point: "There is no API key. That string is a placeholder — BlockRun doesn't check it. Payment is the authentication. You don't need a key when you're paying per request on-chain. That's the whole x402 thesis in one line."

Layer 3 — ADK adapter (quick):

litellm_model = LiteLlm(model="openai/gpt-oss-20b", client=openai_client)

Talking point: LiteLLM wraps the OpenAI client so Google ADK can use it. Standard glue — nothing payment-specific here.

Layer 4 — Inbound payments (buyer pays seller):

Agent(
    model=litellm_model,
    instruction="You are a helpful AI assistant.",
    before_agent_callback=make_x402_before_agent_callback(
        price="$0.002",
        network="base-sepolia",
        pay_to_address="0x...",
    ),
)

Talking points:

  • The instruction is one generic line. The seller adds no intelligence — it's a payment wrapper around BlockRun's model. That's the point: you can monetize any LLM with ~20 lines of glue.
  • make_x402_before_agent_callback is the inbound payment gate. When the buyer sends a request via A2A, this callback returns a 402 requiring $0.002 USDC before the request is processed.

"So this one file has two payment flows: the seller charges the buyer via the callback, and then pays BlockRun via the HTTP client. Two hops, fully automatic."

3c. One Line to Serve It (to_a2a)

Scroll to get_a2a_app (line 121)

self._a2a_app = to_a2a(agent, port=self.config.port)

Talking point: "One function call — to_a2a — takes a normal ADK agent and turns it into an A2A server with x402 payment gating. That's it. The agent card, the payment negotiation, the protocol handling — all handled by the SDK."

3d. Three SDK Functions, Entire Payment Flow

Pause for emphasis.

Ampersend SDK function Role Used by
create_ampersend_http_client Outbound: auto-pays 402s on HTTP requests Seller (pays BlockRun)
make_x402_before_agent_callback Inbound: charges callers via 402 Seller (charges buyer)
create_ampersend_treasurer Signs 402 payment responses Buyer (pays seller)

Talking point: "Three functions from the Ampersend SDK. That's the entire payment infrastructure for a two-hop agent-to-agent payment flow settling in USDC on Base."


Part 4: Code Walkthrough — Buyer

Open src/blockrun_agent/buyer_a2a/agent.py — this is intentionally short (35 lines)

_treasurer = create_ampersend_treasurer(
    smart_account_address=os.environ["BUYER_SMART_ACCOUNT_ADDRESS"],
    session_key_private_key=os.environ["BUYER_SESSION_KEY"],
)

root_agent = X402RemoteA2aAgent(
    treasurer=_treasurer,
    agent_card=f"{_agent_url}/.well-known/agent.json",
)

Talking points:

  • The buyer has no local LLM. It's a thin proxy — sends prompts to the seller and gets responses back. The entire file is 35 lines.
  • The treasurer is the third and final Ampersend primitive. When the seller returns a 402, the treasurer checks with the Ampersend backend: "Am I allowed to sign this payment?"
  • That check is where the daily spending limit lives. It's configured in the Ampersend dashboard — not in this code. The application can't override it, bypass it, or even see it.
  • If the daily limit hasn't been reached, the treasurer signs and the request goes through.
  • If the limit has been reached, the treasurer refuses to sign — the request fails. The agent is dead in the water.

"The safety net isn't in the application code. It's in the wallet. The agent literally cannot pay for more than you allow — no matter what its code does."


Part 5: Live Demo — Single Request

Switch to terminal

Terminal 1: Start the seller

uv run python examples/a2a_communication.py --seller

Expected output:

============================================================
BlockRun Seller Agent (A2A Server)
============================================================
  Wallet: 0x...
  Network: base-sepolia
  Model: openai/gpt-oss-20b via https://testnet.blockrun.ai/api/v1
  Price: $0.002
  Port: 8001

  AgentCard: http://localhost:8001/.well-known/agent.json
  A2A:       http://localhost:8001/a2a

Talking point: The seller is now listening. It advertises its price and wallet address in the AgentCard — any buyer can discover it and pay to use it.

Terminal 2: Send a buyer request

uv run python examples/a2a_communication.py --buyer --prompt "What is 2+2?"

Talking points while waiting for response:

  • The buyer discovers the seller's AgentCard at /.well-known/agent.json
  • Sends the prompt via A2A protocol
  • Seller returns 402 → buyer's treasurer signs a $0.002 USDC payment → seller verifies → seller forwards to BlockRun (paying via its own x402 transport) → response comes back

Expected output:

============================================================
BlockRun Buyer Agent (A2A Client)
============================================================
  Seller: http://localhost:8001
  Prompt: What is 2+2?
------------------------------------------------------------
4

============================================================

"That one request triggered two on-chain payments. Buyer paid seller, seller paid BlockRun. Both verifiable on Base Sepolia."


Part 6: Live Demo — Runaway Agent Simulator (The Safety Net)

This is the key demo moment. Simulate the $47K disaster — and show the wallet stopping it.

Before running: Show the Ampersend dashboard

  • Open the buyer wallet in the Ampersend dashboard
  • Point out the daily spending limit (e.g. $0.01)
  • At $0.002 per request, that's roughly 5 requests before the wallet cuts off

Talking point: "We've set the buyer's daily budget to one cent. Now let's simulate what happened in the $47K disaster — an agent stuck in an infinite loop, firing requests as fast as it can."

Run the runaway agent simulator

uv run python examples/load_test.py --loop -c 10

What the audience sees:

  1. The header says "RUNAWAY AGENT SIMULATOR" — sets the tone
  2. Requests start firing — PASS results stream by with a live spend counter ($0.002 spent, $0.004 spent, climbing...)
  3. The spend counter climbs to the daily limit
  4. Suddenly: every request starts FAIL-ing — and they fail fast (no payment round-trip)
  5. After 10 consecutive failures the script auto-detects the block and stops
  6. Big red banner: "WALLET BLOCKED — daily spend limit reached"
  7. Summary shows exactly how much was spent before the wallet cut it off

Expected output (approximate):

====================================================
 RUNAWAY AGENT SIMULATOR
   Requests:    infinite (until blocked)
   Concurrency: 10
   Price/req:   $0.002
   Prompt:      What is 2+2?
   Seller:      http://localhost:8001
   Buyer:       0x1a3c9b...fd35b
====================================================

  Simulating an agent stuck in a loop...
  Wallet will block when daily spend limit is hit.
  Press Ctrl+C to stop manually.

  [PASS] #1      820ms  $0.0020 spent
  [PASS] #3      845ms  $0.0040 spent
  [PASS] #2      910ms  $0.0060 spent
  [PASS] #5      870ms  $0.0080 spent
  [PASS] #4      920ms  $0.0100 spent
  [FAIL] #6       45ms  (spend limit exceeded)
  [FAIL] #7       42ms  (spend limit exceeded)
  [FAIL] #8       38ms  (spend limit exceeded)
  ... (10 consecutive failures)

  >>> WALLET BLOCKED — daily spend limit reached <<<

====================================================
 Results
   Total:       15
   Passed:      5
   Failed:      10
   Total spent: $0.0100
   Wall time:   2.1s
   Avg (all):   85ms
   Avg (pass):  873ms
   Avg (fail):  41ms
   Min:         38ms
   Max:         920ms

   Without Ampersend's spending limit, this agent
   would have kept running — and kept paying — forever.
====================================================

After: Show the dashboard again

  • The daily spend shows exactly the limit amount consumed
  • No overspend — the wallet enforced the cap at the protocol level

Talking points:

"That agent was stuck in an infinite loop — just like the real $47K disaster. It would have kept going forever. But the wallet said no."

"The spend counter hit exactly one cent and stopped. Not because we wrote a break statement. Not because of a rate limiter. The wallet itself refused to sign any more payments."

"This is the difference between software safety and infrastructure safety. Software can have bugs. The wallet can't be overridden — it's enforced by the session key policy in the Ampersend dashboard."

"If those $47K agents had been paying through Ampersend wallets, someone would have set a $100 daily cap, and the damage would have stopped at $100. Not $47,000."

Bonus: Fixed mode for benchmarks

The same script also supports a fixed request count for benchmarking:

# Fire exactly 50 requests, 5 at a time
uv run python examples/load_test.py -n 50 -c 5

Part 7: Wrap-Up

Key takeaways:

  1. x402 replaces API keys with payments. Every LLM call is a real USDC transaction on Base. No credit card bills arriving 30 days later.

  2. Ampersend wallets enforce spending limits on-chain. The daily cap is set in the dashboard and enforced by the wallet's session key policy. Application code cannot override it.

  3. The safety net is at the infrastructure level. It doesn't matter if the agent's code has a bug, enters a loop, or gets prompt-injected into making thousands of calls. The wallet is the final authority.

  4. Two payments, fully composable. Buyer pays seller, seller pays BlockRun — each hop is an independent x402 flow. You can chain as many agent-to-agent hops as you want, each with its own pricing and budget.

Resources:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment