ScavioScavio
产品定价文档
登录开始使用
  1. 首页
  2. 教程
  3. 如何使用 USDC 支付层构建代理搜索
教程

如何使用 USDC 支付层构建代理搜索

将 USDC 小额支付层添加到您的 AI 代理搜索管道中。使用稳定币按查询付费,而不是按月订阅。

获取免费API密钥API文档

搜索网络的人工智能代理需要一种以编程方式运行的支付方式。 USDC 稳定币支持按查询小额支付,无需信用卡或每月承诺。本教程围绕搜索 API 调用构建一个支付包装器,用于跟踪 USDC 的支出、设置每个代理的预算并记录每笔交易。搜索本身使用 Scavio,每次查询 0.005 美元,USDC 层增加了透明的成本跟踪。

前置条件

  • 已安装 Python 3.9+
  • 请求已安装库
  • 来自 scavio.dev 的 Scavio API 密钥
  • 对稳定币钱包的基本了解

操作指南

步骤 1: 构建 USDC 预算跟踪器

创建一个预算系统来跟踪 USDC 中的代理支出。每个代理都会获得预算分配,并且不能超过该预算。

Python
from dataclasses import dataclass, field
from datetime import datetime
from typing import List, Dict

@dataclass
class Transaction:
    agent_id: str
    amount_usdc: float
    service: str
    query: str
    timestamp: str = field(default_factory=lambda: datetime.now().isoformat())

class USDCBudget:
    def __init__(self):
        self.balances: Dict[str, float] = {}
        self.transactions: List[Transaction] = []

    def fund_agent(self, agent_id: str, amount_usdc: float):
        self.balances[agent_id] = self.balances.get(agent_id, 0) + amount_usdc
        print(f'Agent {agent_id}: funded ${amount_usdc} USDC (balance: ${self.balances[agent_id]})')

    def can_spend(self, agent_id: str, amount: float) -> bool:
        return self.balances.get(agent_id, 0) >= amount

    def spend(self, agent_id: str, amount: float, service: str, query: str) -> bool:
        if not self.can_spend(agent_id, amount):
            return False
        self.balances[agent_id] -= amount
        self.transactions.append(Transaction(agent_id, amount, service, query))
        return True

    def summary(self, agent_id: str) -> dict:
        agent_txns = [t for t in self.transactions if t.agent_id == agent_id]
        total_spent = sum(t.amount_usdc for t in agent_txns)
        return {'balance': self.balances.get(agent_id, 0),
                'total_spent': total_spent, 'transactions': len(agent_txns)}

budget = USDCBudget()
budget.fund_agent('research-agent', 1.00)  # $1 USDC budget
budget.fund_agent('lead-gen-agent', 5.00)  # $5 USDC budget
print(f'Research agent: ${budget.balances["research-agent"]} USDC')
print(f'Lead gen agent: ${budget.balances["lead-gen-agent"]} USDC')

步骤 2: 使用 USDC 支出完成搜索调用

创建一个搜索函数,在进行 API 调用之前检查代理的 USDC 预算并记录每笔交易。

Python
import requests, os

SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
SEARCH_COST_USDC = 0.005  # $0.005 per query

def budgeted_search(agent_id: str, query: str, budget: USDCBudget) -> dict:
    if not budget.can_spend(agent_id, SEARCH_COST_USDC):
        remaining = budget.balances.get(agent_id, 0)
        return {'error': f'Insufficient USDC balance: ${remaining:.3f} < ${SEARCH_COST_USDC}',
                'results': []}
    resp = requests.post('https://api.scavio.dev/api/v1/search',
        headers={'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json'},
        json={'query': query, 'country_code': 'us', 'num_results': 10})
    results = resp.json().get('organic_results', [])
    budget.spend(agent_id, SEARCH_COST_USDC, 'scavio_search', query)
    return {
        'results': [{'title': r['title'], 'link': r['link']}
                    for r in results],
        'cost_usdc': SEARCH_COST_USDC,
        'remaining_usdc': budget.balances[agent_id]
    }

# Agent makes searches against its budget
result = budgeted_search('research-agent', 'best python frameworks 2026', budget)
print(f'Results: {len(result["results"])}')
print(f'Cost: ${result.get("cost_usdc", 0)} USDC')
print(f'Remaining: ${result.get("remaining_usdc", 0):.3f} USDC')

步骤 3: 添加支出报告和警报

为每个代理生成支出报告,并在预算不足时设置警报。

Python
def spending_report(budget: USDCBudget):
    print('Agent Spending Report')
    print('=' * 50)
    for agent_id, balance in budget.balances.items():
        summary = budget.summary(agent_id)
        print(f'\nAgent: {agent_id}')
        print(f'  Balance: ${balance:.3f} USDC')
        print(f'  Spent: ${summary["total_spent"]:.3f} USDC')
        print(f'  Transactions: {summary["transactions"]}')
        # Alert if low balance
        if balance < 0.10:
            print(f'  WARNING: Low balance! Fund this agent to continue.')
        # Queries remaining estimate
        queries_left = int(balance / SEARCH_COST_USDC)
        print(f'  Queries remaining: ~{queries_left}')

# Simulate some agent activity
for i in range(5):
    budgeted_search('research-agent', f'query {i}', budget)

spending_report(budget)

Python 示例

Python
import requests, os

SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
balances = {'agent-1': 1.0}
txns = []

def search(agent_id, query, cost=0.005):
    if balances.get(agent_id, 0) < cost:
        return {'error': 'Insufficient USDC'}
    resp = requests.post('https://api.scavio.dev/api/v1/search',
        headers={'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json'},
        json={'query': query, 'country_code': 'us', 'num_results': 10})
    balances[agent_id] -= cost
    txns.append({'agent': agent_id, 'cost': cost, 'query': query})
    results = resp.json().get('organic_results', [])
    print(f'${cost} USDC | Balance: ${balances[agent_id]:.3f} | Results: {len(results)}')
    return results

search('agent-1', 'best CRM tools 2026')
print(f'Total spent: ${sum(t["cost"] for t in txns):.3f} USDC')

JavaScript 示例

JavaScript
const SCAVIO_KEY = process.env.SCAVIO_API_KEY;
const balances = { 'agent-1': 1.0 };

async function search(agentId, query, cost = 0.005) {
  if ((balances[agentId] || 0) < cost) return { error: 'Insufficient USDC' };
  const resp = await fetch('https://api.scavio.dev/api/v1/search', {
    method: 'POST',
    headers: { 'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query, country_code: 'us', num_results: 10 })
  });
  balances[agentId] -= cost;
  const results = (await resp.json()).organic_results || [];
  console.log(`$${cost} USDC | Balance: $${balances[agentId].toFixed(3)} | Results: ${results.length}`);
  return results;
}

search('agent-1', 'best CRM tools 2026');

预期输出

JSON
Agent research-agent: funded $1.00 USDC (balance: $1.0)
Agent lead-gen-agent: funded $5.00 USDC (balance: $5.0)

Results: 10
Cost: $0.005 USDC
Remaining: $0.995 USDC

Agent Spending Report
==================================================
Agent: research-agent
  Balance: $0.970 USDC
  Spent: $0.030 USDC
  Transactions: 6
  Queries remaining: ~194

相关教程

  • How to Secure Financial MCP Agent Tools
  • 如何计算每个代理搜索查询的实际成本
  • 如何跟踪多个代理的搜索 API 成本

常见问题

大多数开发者在15到30分钟内完成本教程。您需要一个Scavio API密钥(免费套餐即可)和可用的Python或JavaScript环境。

已安装 Python 3.9+. 请求已安装库. 来自 scavio.dev 的 Scavio API 密钥. 对稳定币钱包的基本了解. Scavio API密钥注册即送50个免费积分。

可以。免费套餐注册即送50个积分,完全足够完成本教程并构建一个可运行的原型解决方案。

Scavio提供原生LangChain包(langchain-scavio)、MCP服务器以及适用于任何HTTP客户端的REST API。本教程使用 the raw REST API, 但您可以根据需要适配您选择的框架。

相关资源

Best Of

Google I/O 2026 AI模式变化后最佳搜索API

Read more
Glossary

搜索 API 供应商格局(2026)

Read more
Best Of

2026 年最佳 SERP API 提供商按价格排名

Read more
Glossary

免费搜索API层级对比

Read more
Comparison

Search APIs (Scavio, Tavily, SerpAPI) vs Headless Browser (Playwright, Puppeteer, Browserbase)

Read more
Comparison

Google Places API vs SERP Local Pack API

Read more

开始构建

将 USDC 小额支付层添加到您的 AI 代理搜索管道中。使用稳定币按查询付费,而不是按月订阅。

获取免费API密钥阅读文档
ScavioScavio

面向AI智能体的实时搜索API。搜索所有平台,不仅仅是Google。

产品

  • 功能
  • 定价
  • 控制台
  • 联盟计划

开发者

  • 文档
  • API参考
  • 快速开始
  • MCP集成
  • Python SDK

替代方案

  • Tavily替代方案
  • SerpAPI替代方案
  • Firecrawl替代方案
  • Exa替代方案

工具

  • JSON格式化
  • cURL转代码
  • Token计数器
  • 全部工具

© 2026 Scavio. 保留所有权利。

Featured on TAAFT
服务条款隐私政策