阐述AI Agent通过去中心化市场发现、协商和支付服务的架构设计,涵盖注册表、发现机制、协议和支付层等核心组件。
到 2026 年,大多数生产级别的 Agent 不再是调用少量公开 API 的单体脚本。它们从其他 Agent 组合能力——想象一个"规划师" Agent 将数据获取、验证或转换任务委托给专业的微 Agent。市场就是将这些粘合在一起的"胶水",让 Agent 能够以去中心化、可编程的方式发现、协商和支付这些服务。
核心价值主张很简单:减少重复劳动,同时保持自主性。一个 Agent 可以专注于自己的领域逻辑,将周边工作外包给最便宜或最可靠的提供商。代价是增加的延迟、失败处理的复杂性,以及需要一个共享的经济层。如果忽视这些成本,很快就会看到级联超时或意外费用。
一个最小的 A2A 市场由四个松耦合的组件构成:

流程特意设计为同步以保持简单:Agent 发现服务、发起付费请求、收到签名收据、验证后继续。异步模式(回调、事件流)是可行的,但会增加相当大的调试开销;大多数生产级 Agent 坚持使用请求‑回复模型,除非真正需要"发后即忘"的语义。
Agent 需要一份机器可读的契约。社区已经收敛到一种基于 OpenAPI 3.1 的 JSON‑Schema 扩展,称为 AgentServiceSpec。关键字段:
{
"openapi": "3.1.0",
"info": {
"title": "Image Captioning Agent",
"version": "1.0.0",
"description": "Generates a short caption for an RGB image."
},
"paths": {
"/caption": {
"post": {
"operationId": "captionImage",
"requestBody": {
"required": true,
"content": {
"image/png": { "schema": { "type": "string", "format": "binary" } }
}
},
"responses": {
"200": {
"description": "Caption text",
"content": {
"text/plain": { "schema": { "type": "string" } }
}
}
},
"x-price": { "amount": "0.03", "currency": "USDC", "chain": "base" },
"x-sla": { "maxLatencyMs": 800, "minSuccessRate": 0.99 }
}
}
}
}
x-price 在使用 x402 的市场中是强制的。
x-sla 是建议性的;Agent 仍可强制执行自己的超时。
二进制载荷在 JSON 中 base64 编码,或作为 multipart/form‑data 发送;编码方式由实现决定。
x402 重用 HTTP 402 状态码来表明服务器在处理请求之前需要支付。工作流程:
Agent → Marketplace GET /service?agentId=… → 返回 402 Payment Required,附带 headers:
X-Price: 0.03 USDC
X-Pay-To: 0xAbc… (Base 上的 USDC 合约)
X-Nonce: <random 256‑bit>
Agent 构造一笔 ERC‑20 转账(使用 permit 或直接 transferFrom 如果已批准),将精确金额包含在数据字段中以防止重放。
Agent → Marketplace POST /caption,header 包含 Authorization: Bearer <signedTx>(或 x402-payment: <txHash>)。
Marketplace 通过 RPC 或可信的 sequencer 在链上验证交易,检查金额、代币和 nonce 是否匹配,然后处理请求并返回签名收据:
{
"receipt": {
"txHash": "0x123…",
"blockNumber": 421337,
"timestamp": 1730568000,
"payer": "0xAgent…",
"payee": "0xMarketplace…",
"amount": "0.03",
"currency": "USDC",
"chain": "base",
"service": "image-captioning",
"signature": "0xabcdef…"
}
}
Agent 使用 marketplace 的公钥验证签名,并将收据存储以供审计或争议解决。
import hashlib
import json
import time
import requests
from web3 import Web3
from eth_account import Account
# Configuration
BASE_RPC = "https://base.mainnet.rpc.link"
USDC_ADDRESS = Web3.to_checksum_address("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913")
MARKETPLACE = "https://agent-market.example.com"
AGENT_PRIVATE_KEY = "0xYOUR_PRIVATE_KEY"
AGENT_ADDRESS = Account.from_key(AGENT_PRIVATE_KEY).address
w3 = Web3(Web3.HTTPProvider(BASE_RPC))
usdc_abi = [...] # minimal ERC20 abi (balanceOf, transfer, permit)
usdc = w3.eth.contract(address=USDC_ADDRESS, abi=usdc_abi)
def get_price_and_nonce(service_path: str):
resp = requests.get(f"{MARKETPLACE}{service_path}", timeout=5)
assert resp.status_code == 402, f"Expected 402, got {resp.status_code}"
price = float(resp.headers["X-Price"])
payee = resp.headers["X-Pay-To"]
nonce = resp.headers["X-Nonce"]
return price, payee, nonce
def pay_usdc(to: str, amount_usdc: float, nonce: str):
amount_wei = int(amount_usdc * 1e6) # USDC has 6 decimals
# Build EIP-2612 permit (optional) – here we use a simple transfer with approval
# Assuming the agent has already approved the marketplace to spend USDC
tx = usdc.functions.transfer(
Web3.to_checksum_address(to),
amount_wei
).build_transaction({
"chainId": w3.eth.chain_id,
"gas": 100_000,
"maxFeePerGas": w3.to_wei(2, "gwei"),
"maxPriorityFeePerGas": w3.to_wei(1, "gwei"),
"nonce": w3.eth.get_transaction_count(AGENT_ADDRESS),
})
signed = Account.sign_transaction(tx, AGENT_PRIVATE_KEY)
tx_hash = w3.eth.send_raw_transaction(signed.rawTransaction)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
return receipt.transactionHash.hex()
def call_caption(image_bytes: bytes):
price, payee, nonce = get_price_and_nonce("/caption")
tx_hash = pay_usdc(payee, price, nonce)
headers = {
"x402-payment": tx_hash, # custom header the marketplace expects
"Content-Type": "image/png"
}
resp = requests.post(
f"{MARKETPLACE}/caption",
data=image_bytes,
headers=headers,
timeout=10
)
resp.raise_for_status()
data = resp.json()
# Validate receipt signature (simplified)
receipt = data["receipt"]
assert w3.eth.get_transaction_receipt(receipt["txHash"])["status"] == 1
return resp.text # the caption
# Example usage
if __name__ == "__main__":
with open("cat.png", "rb") as f:
img = f.read()
print(call_caption(img))
这段代码展示了:
通过 402 响应获取价格和 nonce。
简单的 USDC 转账(可以用 permit 流程替换以避免链上授权)。
在自定义 header(x402-payment)中包含交易哈希。
在信任服务输出之前验证链上收据。