Skip to content

100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.

feat: add AI x402 Paying Agent β€” pays a local seller you run yourself (testnet, no vendor) (#1106)

GTCC7779a33b9266abe
diff --git a/README.md b/README.md
index ffd8545a..62a3497c 100644
--- a/README.md
+++ b/README.md
@@ -126,6 +126,7 @@ streamlit run travel_agent.py
* [πŸ˜‚ AI Meme Generator Agent (Browser)](starter_ai_agents/ai_meme_generator_agent_browseruse/) - Makes memes by driving a real browser, not an image API
* [🎡 AI Music Generator Agent](starter_ai_agents/ai_music_generator_agent/) - Prompt in, MP3 track out
* [πŸ›« AI Travel Agent (Local & Cloud)](starter_ai_agents/ai_travel_agent/) - Personalized day-by-day travel itineraries
+* [πŸ’Έ AI x402 Paying Agent](starter_ai_agents/ai_x402_paying_agent/) - An agent with a wallet that pays per-call for the data it needs β€” no API keys
* [✨ Gemini Multimodal Agent](starter_ai_agents/multimodal_ai_agent/) - Video analysis plus web search in one agent
* [πŸ”„ Mixture of Agents](starter_ai_agents/mixture_of_agents/) - Multiple LLMs answer, one aggregates the best response
* [πŸ“Š xAI Finance Agent](starter_ai_agents/xai_finance_agent/) - Real-time stock analysis powered by Grok
diff --git a/starter_ai_agents/ai_x402_paying_agent/README.md b/starter_ai_agents/ai_x402_paying_agent/README.md
new file mode 100644
index 00000000..1550be20
--- /dev/null
+++ b/starter_ai_agents/ai_x402_paying_agent/README.md
@@ -0,0 +1,93 @@
+## πŸ’Έ AI x402 Paying Agent
+
+An AI agent with its own crypto wallet that **pays for the data it needs** β€” no API keys, no subscriptions, no signup.
+
+Ask a question in plain English. Claude decides which paid API answers it and calls a fetch tool. The API responds `402 Payment Required` with a price quote; the agent automatically pays it in USDC via the open [x402](https://www.x402.org/) standard (now under the Linux Foundation) and answers from the data it just bought.
+
+**Everything in this tutorial is free and self-contained.** You run the paid API yourself (`seller.py`, ~60 lines), payments settle in *testnet* USDC on Base Sepolia through the public [x402.org facilitator](https://www.x402.org/), and the buyer wallet is funded from a free faucet. You are both the buyer and the seller, so you watch the full payment loop with zero real money involved. The exact same agent code works on mainnet against any live x402 API.
+
+### Features
+
+- **Agent-driven tool use** β€” Claude picks the right paid endpoint for the question and quotes the returned data
+- **Automatic 402 payment** β€” the `x402` SDK signs a USDC payment when an API challenges; the demo endpoints cost $0.001–0.002 in testnet USDC
+- **Hard budget cap** β€” a per-call price ceiling (`MAX_PRICE_USDC`, default $0.05) so a misconfigured agent can never overspend
+- **No-LLM mode** β€” `--direct <URL>` pays and fetches any x402 URL with just a wallet, so you can see the payment flow in isolation
+- **Your own seller** β€” `seller.py` is a complete pay-per-call API in ~60 lines of FastAPI; reprice it, add endpoints, or point the agent at any other x402 seller
+
+### How to get Started?
+
+1. Clone the GitHub repository
+
+```bash
+git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
+cd awesome-llm-apps/starter_ai_agents/ai_x402_paying_agent
+```
+
+2. Install the required dependencies:
+
+```bash
+pip install -r requirements.txt
+```
+
+3. Create two throwaway wallets (buyer and seller)
+
+Any EVM wallet works (MetaMask, or `python -c "from eth_account import Account; a=Account.create(); print(a.address, a.key.hex())"`). You need:
+
+- a **buyer** wallet the agent spends from β€” export its private key
+- a **seller** address that receives the payments β€” any second address you control (it only receives; it needs no funds and no key on the server)
+
+```bash
+export X402_PRIVATE_KEY='0x...' # buyer wallet private key
+export SELLER_ADDRESS='0x...' # seller receive address
+```
+
+⚠️ Use dedicated throwaway wallets for this β€” never your main wallet.
+
+4. Fund the buyer with free testnet USDC
+
+Go to [faucet.circle.com](https://faucet.circle.com), pick **Base Sepolia**, paste the buyer address. You get test USDC instantly; no gas token is needed anywhere (x402 payments are gasless for both sides).
+
+5. Start your paid API (terminal 1)
+
+```bash
+uvicorn seller:app --port 4021
+```
+
+Try it unpaid and watch the 402 challenge: `curl -i http://localhost:4021/api/fortune`
+
+6. Set your Anthropic API key (skip for `--direct` mode)
+
+```bash
+export ANTHROPIC_API_KEY='your-api-key-here'
+```
+
+7. Run the agent (terminal 2)
+
+```bash
+# Full agent: natural-language question β†’ paid data β†’ answer
+python x402_paying_agent.py "Roll me a d20 and read me my fortune"
+
+# Payment flow only, no LLM needed:
+python x402_paying_agent.py --direct "http://localhost:4021/api/fortune"
+```
+
+### How it works
+
+```
+you ──question──▢ Claude ──tool call──▢ GET your local paid API
+ β”‚ 402 Payment Required ($0.001)
+ β–Ό
+ x402 SDK signs USDC payment
+ β”‚ retry with payment header
+ β–Ό
+ facilitator verifies + settles on Base Sepolia
+ β”‚
+ 200 OK + data ──▢ Claude answers
+```
+
+The whole payment negotiation is 3 HTTP requests and settles on-chain in seconds β€” and because you run the seller, you can watch both sides of it.
+
+### Beyond the demo
+
+- **Point it at the real economy** β€” swap the URL for any live x402-enabled API on a mainnet network; the agent code is identical. Directories of live x402 endpoints are linked from [x402.org](https://www.x402.org/).
+- **Going to production: managed wallets** β€” this demo keeps the wallet as a raw private key so you can see every moving part. For a production agent, Coinbase's [CDP x402 SDK](https://docs.cdp.coinbase.com/x402/core-concepts/cdp-sdk) wraps the same open standard with managed wallets (no private key to store), client-side spend controls (per-payment caps, rolling daily limits, payee allowlists), and hosted settlement. The `MAX_PRICE_USDC` guard in this tutorial is a minimal version of the same idea β€” cap what an autonomous spender can spend before it spends it.
diff --git a/starter_ai_agents/ai_x402_paying_agent/requirements.txt b/starter_ai_agents/ai_x402_paying_agent/requirements.txt
new file mode 100644
index 00000000..cd902bf1
--- /dev/null
+++ b/starter_ai_agents/ai_x402_paying_agent/requirements.txt
@@ -0,0 +1,6 @@
+anthropic
+x402[evm,httpx,fastapi]
+eth-account
+httpx
+fastapi
+uvicorn
diff --git a/starter_ai_agents/ai_x402_paying_agent/seller.py b/starter_ai_agents/ai_x402_paying_agent/seller.py
new file mode 100644
index 00000000..0be927a8
--- /dev/null
+++ b/starter_ai_agents/ai_x402_paying_agent/seller.py
@@ -0,0 +1,71 @@
+"""Local x402 seller β€” a tiny paid API you run yourself.
+
+Two endpoints, priced in fractions of a cent, paid in testnet USDC on Base Sepolia
+through the public x402.org facilitator. Nothing here costs real money: the buyer
+funds their wallet from a free faucet, and you are the seller, so every payment in
+this tutorial goes from your test wallet to your own address.
+
+Usage:
+ export SELLER_ADDRESS='0x...' # any EVM address you control (it just receives)
+ uvicorn seller:app --port 4021
+
+SPDX-License-Identifier: Apache-2.0
+"""
+from __future__ import annotations
+
+import os
+import random
+import sys
+from datetime import datetime, timezone
+
+from fastapi import FastAPI
+from x402 import x402ResourceServer
+from x402.http import HTTPFacilitatorClient # defaults to https://x402.org/facilitator (testnet)
+from x402.http.middleware.fastapi import payment_middleware
+from x402.mechanisms.evm.exact.server import ExactEvmScheme
+
+PAY_TO = os.environ.get("SELLER_ADDRESS")
+if not PAY_TO:
+ sys.exit("Set SELLER_ADDRESS to an EVM address that should receive the (testnet) payments.")
+
+NETWORK = "eip155:84532" # Base Sepolia; the facilitator settles testnet USDC for free
+
+server = x402ResourceServer(HTTPFacilitatorClient())
+server.register(NETWORK, ExactEvmScheme())
+
+ROUTES = {
+ "GET /api/fortune": {"accepts": {"scheme": "exact", "network": NETWORK, "payTo": PAY_TO, "price": "$0.001"}},
+ "GET /api/dice": {"accepts": {"scheme": "exact", "network": NETWORK, "payTo": PAY_TO, "price": "$0.002"}},
+}
+
+app = FastAPI(title="x402 demo seller")
+app.middleware("http")(payment_middleware(ROUTES, server))
+
+FORTUNES = [
+ "The bug you are hunting is in the file you refuse to reopen.",
+ "A small refactor today prevents a large rewrite in December.",
+ "Your next deploy will be boring. This is the highest compliment.",
+ "Trust the failing test; it is the only one telling the truth.",
+ "You will receive a pull request you actually enjoy reviewing.",
+ "An agent that can pay for data never has to beg for API keys.",
+]
+
+
[email protected]("/api/fortune")
+def fortune():
+ return {
+ "fortune": random.choice(FORTUNES),
+ "issued_at": datetime.now(timezone.utc).isoformat(),
+ "paid": True,
+ }
+
+
[email protected]("/api/dice")
+def dice(sides: int = 20):
+ sides = max(2, min(sides, 1000))
+ return {
+ "roll": random.randint(1, sides),
+ "sides": sides,
+ "rolled_at": datetime.now(timezone.utc).isoformat(),
+ "paid": True,
+ }
diff --git a/starter_ai_agents/ai_x402_paying_agent/x402_paying_agent.py b/starter_ai_agents/ai_x402_paying_agent/x402_paying_agent.py
new file mode 100644
index 00000000..7781f177
--- /dev/null
+++ b/starter_ai_agents/ai_x402_paying_agent/x402_paying_agent.py
@@ -0,0 +1,184 @@
+"""AI x402 Paying Agent β€” an agent that pays for its own data with USDC micropayments.
+
+Ask a question β†’ Claude picks a paid API β†’ the agent hits it, gets an HTTP 402
+Payment Required challenge, pays the quoted price in USDC from its own wallet,
+and answers with the data. No API keys, no subscriptions, no signup.
+
+The demo pays a seller YOU run locally (see seller.py), settled in testnet USDC
+on Base Sepolia through the public x402.org facilitator, so following along is
+completely free. The payment code is identical on mainnet against any x402 API.
+
+Usage:
+ uvicorn seller:app --port 4021 # terminal 1: your own paid API
+ python x402_paying_agent.py "Roll me a d20 and read me my fortune"
+ python x402_paying_agent.py --direct "http://localhost:4021/api/fortune"
+
+SPDX-License-Identifier: Apache-2.0
+"""
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import os
+import sys
+from decimal import Decimal
+
+import httpx
+from eth_account import Account
+from x402 import x402Client
+from x402.http.clients.httpx import x402HttpxClient
+from x402.mechanisms.evm import EthAccountSigner
+from x402.mechanisms.evm.exact import ExactEvmScheme
+
+USDC_DECIMALS = 6 # 1 USDC = 10**6 atomic units; x402 amounts are atomic strings
+
+# Demo catalog: the paid API you run yourself with seller.py (testnet USDC on Base
+# Sepolia, fractions of a cent). The payment code is generic β€” swap in any x402 API.
+SELLER = os.environ.get("SELLER_URL", "http://localhost:4021")
+
+DEMO_ENDPOINTS = f"""
+Available paid data endpoints (x402, USDC on Base Sepolia testnet):
+
+1. Fortune of the day β€” $0.001/call
+ GET {SELLER}/api/fortune
+ A paid fortune with an issue timestamp.
+
+2. Certified dice roll β€” $0.002/call
+ GET {SELLER}/api/dice?sides=<n>
+ A random roll of an n-sided die (default 20).
+"""
+
+SYSTEM_PROMPT = f"""You are a data agent with a crypto wallet. You can call paid APIs β€” when one
+responds with HTTP 402 Payment Required, your fetch tool automatically pays the quoted price
+in USDC and retrieves the data.
+
+{DEMO_ENDPOINTS}
+
+When the user's question maps to one of these endpoints, call fetch_paid_api with the full URL
+(including query parameters). Answer from the returned data only β€” quote the key numbers.
+If the question doesn't match any endpoint, say so instead of guessing."""
+
+TOOLS = [
+ {
+ "name": "fetch_paid_api",
+ "description": (
+ "Fetch a URL, automatically paying an x402 HTTP 402 challenge in USDC if the API "
+ "requires payment. Call this when the user's question requires paid data. "
+ "Returns the response body as JSON text."
+ ),
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "Full URL to fetch, including any query parameters.",
+ }
+ },
+ "required": ["url"],
+ },
+ }
+]
+
+
+def build_paying_client(private_key: str, max_price_usdc: Decimal) -> httpx.AsyncClient:
+ """httpx client that auto-pays 402 challenges, refusing anything above max_price_usdc."""
+ signer = EthAccountSigner(Account.from_key(private_key))
+ client = x402Client()
+ cap_atomic = int(max_price_usdc * (10**USDC_DECIMALS))
+
+ def _budget_cap(version, accepts):
+ allowed = [
+ a
+ for a in accepts
+ if int(getattr(a, "amount", None) or getattr(a, "max_amount_required", 0) or 0) <= cap_atomic
+ ]
+ if not allowed:
+ raise ValueError(
+ f"Refusing to pay: cheapest payment option exceeds the ${max_price_usdc} per-call cap. "
+ "Raise MAX_PRICE_USDC if this is intentional."
+ )
+ return allowed
+
+ client.register_policy(_budget_cap)
+ client.register("eip155:*", ExactEvmScheme(signer))
+ return x402HttpxClient(client, follow_redirects=True, timeout=60.0)
+
+
+async def paid_fetch(url: str, private_key: str, max_price_usdc: Decimal) -> str:
+ async with build_paying_client(private_key, max_price_usdc) as client:
+ resp = await client.get(url)
+ if resp.status_code != 200:
+ return f"Request failed: HTTP {resp.status_code}: {resp.text[:300]}"
+ return resp.text
+
+
+def run_agent(question: str, private_key: str, max_price_usdc: Decimal) -> None:
+ import anthropic
+
+ client = anthropic.Anthropic()
+ model = os.environ.get("CLAUDE_MODEL", "claude-opus-4-8")
+ messages = [{"role": "user", "content": question}]
+
+ while True:
+ response = client.messages.create(
+ model=model,
+ max_tokens=2048,
+ system=SYSTEM_PROMPT,
+ tools=TOOLS,
+ messages=messages,
+ )
+ if response.stop_reason != "tool_use":
+ for block in response.content:
+ if block.type == "text":
+ print(block.text)
+ return
+
+ messages.append({"role": "assistant", "content": response.content})
+ tool_results = []
+ for block in response.content:
+ if block.type == "tool_use":
+ url = block.input["url"]
+ print(f"β†’ fetching (paying if challenged): {url}", file=sys.stderr)
+ try:
+ result = asyncio.run(paid_fetch(url, private_key, max_price_usdc))
+ except Exception as exc: # payment refused, network error, etc.
+ result = f"Error: {exc}"
+ tool_results.append(
+ {"type": "tool_result", "tool_use_id": block.id, "content": result}
+ )
+ messages.append({"role": "user", "content": tool_results})
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="AI agent that pays for its own data via x402")
+ parser.add_argument("question", nargs="?", help="Question for the agent")
+ parser.add_argument(
+ "--direct",
+ metavar="URL",
+ help="Skip the LLM: pay-and-fetch this URL directly and print the JSON (wallet only, no Anthropic key needed)",
+ )
+ args = parser.parse_args()
+
+ private_key = os.environ.get("X402_PRIVATE_KEY")
+ if not private_key:
+ sys.exit("Set X402_PRIVATE_KEY to a wallet private key holding testnet USDC on Base Sepolia (free from https://faucet.circle.com).")
+ max_price = Decimal(os.environ.get("MAX_PRICE_USDC", "0.05"))
+
+ if args.direct:
+ body = asyncio.run(paid_fetch(args.direct, private_key, max_price))
+ try:
+ print(json.dumps(json.loads(body), indent=2))
+ except json.JSONDecodeError:
+ print(body)
+ return
+
+ if not args.question:
+ parser.error("Provide a question, or use --direct <URL>")
+ if not os.environ.get("ANTHROPIC_API_KEY"):
+ sys.exit("Set ANTHROPIC_API_KEY (or use --direct <URL> for the no-LLM payment demo).")
+ run_agent(args.question, private_key, max_price)
+
+
+if __name__ == "__main__":
+ main()