ScavioScavio
ProductoPreciosDocumentación
Iniciar sesionComenzar
  1. Inicio
  2. Tutoriales
  3. Cómo realizar un seguimiento del gasto en API del agente con presupuestos
Tutorial

Cómo realizar un seguimiento del gasto en API del agente con presupuestos

Cree un rastreador de presupuesto para el gasto de API de los agentes de IA. Establezca límites por agente, alerte sobre excesos y realice un seguimiento del costo por tarea.

Obtener clave API gratisDocumentacion API

Los agentes de IA pueden consumir rápidamente los presupuestos de API si no se los supervisa. Este rastreador de presupuesto incluye sus llamadas a la API de búsqueda con seguimiento de costos, establece límites de gasto por agente, alertas antes de que se exceda el presupuesto y registra el costo por tarea para su optimización. Funciona con cualquier API que cobre por llamada.

Requisitos previos

  • Python 3.8+
  • solicita biblioteca
  • Una clave API de Scavio de scavio.dev
  • Al menos un agente realizando llamadas API

Guia paso a paso

Paso 1: Cree el contenedor de API con seguimiento del presupuesto

Complete las llamadas API con seguimiento de costos y cumplimiento de presupuesto.

Python
import os, requests, json, time
from datetime import datetime
from collections import defaultdict

API_KEY = os.environ['SCAVIO_API_KEY']
SH = {'x-api-key': API_KEY, 'Content-Type': 'application/json'}

class BudgetTracker:
    def __init__(self, cost_per_call=0.005):
        self.cost_per_call = cost_per_call
        self.agents = {}  # agent_id -> {budget, spent, calls}
        self.log = []

    def register_agent(self, agent_id, daily_budget):
        self.agents[agent_id] = {
            'budget': daily_budget,
            'spent': 0.0,
            'calls': 0,
            'created': datetime.now().strftime('%Y-%m-%d')
        }
        print(f'Registered: {agent_id} (budget: ${daily_budget}/day)')

    def can_spend(self, agent_id):
        agent = self.agents.get(agent_id)
        if not agent:
            return False
        remaining = agent['budget'] - agent['spent']
        return remaining >= self.cost_per_call

    def search(self, agent_id, query, **kwargs):
        if not self.can_spend(agent_id):
            remaining = self.agents[agent_id]['budget'] - self.agents[agent_id]['spent']
            print(f'BUDGET EXCEEDED: {agent_id} (${remaining:.3f} remaining)')
            return {'error': 'budget_exceeded', 'remaining': remaining}
        data = requests.post('https://api.scavio.dev/api/v1/search',
            headers=SH, json={'query': query, 'country_code': 'us', **kwargs}).json()
        self.agents[agent_id]['spent'] += self.cost_per_call
        self.agents[agent_id]['calls'] += 1
        self.log.append({'agent': agent_id, 'query': query, 'cost': self.cost_per_call,
                         'time': datetime.now().isoformat()})
        return data

tracker = BudgetTracker()
tracker.register_agent('research-agent', daily_budget=0.50)
tracker.register_agent('seo-agent', daily_budget=1.00)
tracker.register_agent('lead-agent', daily_budget=0.25)

Paso 2: Utilice la búsqueda rastreada en los flujos de trabajo de los agentes

Reemplace las llamadas API directas con versiones con seguimiento del presupuesto.

Python
# Simulate agent usage
queries = {
    'research-agent': ['best python framework 2026', 'fastapi vs django', 'python testing tools'],
    'seo-agent': ['serp api comparison', 'search api pricing', 'mcp search tool', 'ai agent search'],
    'lead-agent': ['saas companies hiring 2026', 'startup funding round'],
}

for agent_id, agent_queries in queries.items():
    print(f'\n--- {agent_id} ---')
    for q in agent_queries:
        result = tracker.search(agent_id, q)
        if 'error' in result:
            print(f'  BLOCKED: {q}')
        else:
            count = len(result.get('organic_results', []))
            print(f'  "{q}" -> {count} results')

# Check remaining budgets
print(f'\n=== Budget Status ===')
for agent_id, data in tracker.agents.items():
    remaining = data['budget'] - data['spent']
    pct = data['spent'] / data['budget'] * 100
    bar = '#' * int(pct / 5)
    print(f'  {agent_id:20} | ${data["spent"]:.3f}/${data["budget"]:.2f} ({pct:.0f}%) | {bar}')

Paso 3: Generar informes de gastos

Analice patrones de gasto y optimice los presupuestos de los agentes.

Python
def spending_report(tracker):
    print(f'\n=== Agent Spending Report - {datetime.now().strftime("%Y-%m-%d")} ===')
    total_spent = sum(a['spent'] for a in tracker.agents.values())
    total_budget = sum(a['budget'] for a in tracker.agents.values())
    total_calls = sum(a['calls'] for a in tracker.agents.values())
    print(f'  Total spent: ${total_spent:.3f} / ${total_budget:.2f} budget')
    print(f'  Total calls: {total_calls}')
    print(f'  Avg cost/call: ${total_spent/total_calls:.4f}' if total_calls else '')
    print(f'\n  Per-Agent Breakdown:')
    for agent_id, data in sorted(tracker.agents.items(), key=lambda x: x[1]['spent'], reverse=True):
        efficiency = data['spent'] / data['calls'] if data['calls'] else 0
        print(f'    {agent_id:20} | {data["calls"]:3} calls | ${data["spent"]:.3f} spent | ${efficiency:.4f}/call')
    # Monthly projection
    monthly = total_spent * 30
    print(f'\n  Monthly projection: ${monthly:.2f}')
    print(f'  Annual projection: ${monthly * 12:.2f}')
    # Optimization suggestions
    print(f'\n  Optimization Suggestions:')
    for agent_id, data in tracker.agents.items():
        usage = data['spent'] / data['budget'] * 100
        if usage < 30:
            print(f'    {agent_id}: Budget underused ({usage:.0f}%). Consider reducing to ${data["spent"] * 2:.2f}/day.')
        elif usage > 90:
            print(f'    {agent_id}: Near limit ({usage:.0f}%). Consider increasing budget.')

spending_report(tracker)

Ejemplo en Python

Python
import os, requests
SH = {'x-api-key': os.environ['SCAVIO_API_KEY'], 'Content-Type': 'application/json'}

class Budget:
    def __init__(self, limit): self.limit = limit; self.spent = 0
    def search(self, q):
        if self.spent + 0.005 > self.limit:
            return print(f'Budget exceeded: ${self.spent:.3f}/${self.limit}')
        data = requests.post('https://api.scavio.dev/api/v1/search',
            headers=SH, json={'query': q, 'country_code': 'us'}).json()
        self.spent += 0.005
        print(f'{q}: {len(data.get("organic_results", []))} results (${self.spent:.3f}/${self.limit})')

b = Budget(0.025)
for q in ['api 1', 'api 2', 'api 3', 'api 4', 'api 5', 'api 6']:
    b.search(q)

Ejemplo en JavaScript

JavaScript
const SH = { 'x-api-key': process.env.SCAVIO_API_KEY, 'Content-Type': 'application/json' };
let spent = 0; const limit = 0.025;
async function budgetSearch(q) {
  if (spent + 0.005 > limit) { console.log(`Budget exceeded`); return; }
  const data = await fetch('https://api.scavio.dev/api/v1/search', {
    method: 'POST', headers: SH, body: JSON.stringify({ query: q, country_code: 'us' })
  }).then(r => r.json());
  spent += 0.005;
  console.log(`${q}: ${(data.organic_results||[]).length} results ($${spent.toFixed(3)}/$${limit})`);
}
for (const q of ['test 1', 'test 2', 'test 3']) await budgetSearch(q);

Salida esperada

JSON
Registered: research-agent (budget: $0.5/day)
Registered: seo-agent (budget: $1.0/day)
Registered: lead-agent (budget: $0.25/day)

--- research-agent ---
  "best python framework 2026" -> 10 results
  "fastapi vs django" -> 10 results

=== Budget Status ===
  research-agent       | $0.015/$0.50 (3%) | 
  seo-agent            | $0.020/$1.00 (2%) | 
  lead-agent           | $0.010/$0.25 (4%) | 

=== Agent Spending Report ===
  Total spent: $0.045 / $1.75 budget
  Total calls: 9
  Monthly projection: $1.35

Tutoriales relacionados

  • Cómo configurar presupuestos de tokens para llamadas a la API de búsqueda
  • Cómo realizar un seguimiento de los costos de la API de búsqueda entre varios agentes
  • Cómo optimizar el presupuesto de búsqueda de su agente de IA

Preguntas frecuentes

La mayoria de los desarrolladores completan este tutorial en 15 a 30 minutos. Necesitaras una clave API de Scavio (el plan gratuito funciona) y un entorno de Python o JavaScript.

Python 3.8+. solicita biblioteca. Una clave API de Scavio de scavio.dev. Al menos un agente realizando llamadas API. Una clave API de Scavio te da 50 creditos gratuitos al registrarte.

Si. El plan gratuito incluye 50 creditos al registrarte, mas que suficiente para completar este tutorial y crear un prototipo funcional.

Scavio tiene un paquete nativo de LangChain (langchain-scavio), un servidor MCP y una API REST simple que funciona con cualquier cliente HTTP. Este tutorial usa the raw REST API, pero puedes adaptarlo al framework que prefieras.

Recursos relacionados

Best Of

Las mejores API de búsqueda después de los cambios en el modo AI de Google I/O 2026

Read more
Glossary

Panorama de proveedores de API de búsqueda (2026)

Read more
Best Of

Los mejores proveedores de API SERP clasificados por precio en 2026

Read more
Glossary

Comparación gratuita de niveles de API de búsqueda

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

Empieza a construir

Cree un rastreador de presupuesto para el gasto de API de los agentes de IA. Establezca límites por agente, alerte sobre excesos y realice un seguimiento del costo por tarea.

Obtener clave API gratuitaLeer la documentacion
ScavioScavio

API de busqueda en tiempo real para agentes de IA. Busca en todas las plataformas, no solo en Google.

Producto

  • Funciones
  • Precios
  • Panel
  • Afiliados

Desarrolladores

  • Documentacion
  • Referencia de API
  • Inicio rapido
  • Integracion MCP
  • Python SDK

Alternativas

  • Alternativa a Tavily
  • Alternativa a SerpAPI
  • Alternativa a Firecrawl
  • Alternativa a Exa

Herramientas

  • Formateador JSON
  • cURL a codigo
  • Contador de tokens
  • Todas las herramientas

© 2026 Scavio. Todos los derechos reservados.

Featured on TAAFT
Terminos de servicioPolitica de privacidad