Skip to Content
🚀 {xpay✦} is building the future of x402 payments - Join the developer beta →
ProductsSmart Proxy

x402 Smart Proxy

The x402 Smart Proxy is a cost control dashboard that provides developers with peace of mind when deploying autonomous agents. It acts as a proxy between your agents and x402-powered APIs, ensuring agents never overspend while maintaining full functionality.

The Problem

Developers are terrified their agent will get stuck in a loop and spend thousands of dollars on x402-powered APIs.

Autonomous agents can make hundreds of API calls per minute. Without proper controls, a bug or unexpected behavior could result in:

  • 💸 Runaway spending from infinite loops
  • 📈 Unexpected cost spikes during high-traffic periods
  • 🚫 No visibility into real-time spending
  • ⏰ No way to stop spending once it starts

The Solution

The Smart Proxy provides an AWS-hosted proxy endpoint that sits between your agents and x402 APIs. It offers:

🛡️ Hard Spending Limits

  • Per-request limits: Maximum spend per API call
  • Daily/monthly budgets: Automatic shutoffs when limits reached
  • Per-agent budgets: Individual spending controls for each agent
  • Global limits: Organization-wide spending controls

📊 Real-time Monitoring

  • Live spending dashboard: Track costs as they happen
  • Usage analytics: Detailed breakdowns by agent, API, and time
  • Cost forecasting: Predict monthly costs based on current usage
  • Anomaly detection: Alerts for unusual spending patterns

⚡ Instant Alerts

  • Slack/Discord notifications: Real-time spending alerts
  • Email alerts: Daily/weekly spending summaries
  • Webhook integration: Custom alert handling
  • Emergency shutoffs: Automatic agent pausing when limits exceeded

Features

Multi-Agent Management

Manage multiple agents from a single dashboard with complete lifecycle control:

import { SmartProxy } from '@xpaysh/agent-kit' const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: 'xpay_fw_...' }) // Create agents with complete configuration await smartProxy.createAgent({ id: 'customer-support-bot', name: 'Customer Support Agent', description: 'Handles customer inquiries and support tickets', walletAddress: '0x742d35Cc6634C0532925a3b8D3Ac2d00fBc1d555', dailyLimit: 50, // $50 USDC per day perCallLimit: 2, // $2 USDC per API call monthlyLimit: 1000, // $1000 USDC per month allowedAPIs: ['openai.com', 'anthropic.com'], status: 'active' }) await smartProxy.createAgent({ id: 'data-analysis-bot', name: 'Data Analysis Agent', description: 'Processes large datasets and generates reports', walletAddress: '0x853d46Dd7744C3dC23c3e8F3Bd2dF1e6fc1e8666', dailyLimit: 200, perCallLimit: 10, monthlyLimit: 5000, allowedAPIs: ['*'], // Allow all x402-enabled APIs status: 'active' }) // Update agent configuration await smartProxy.updateAgent('customer-support-bot', { dailyLimit: 75, // Increase daily limit perCallLimit: 3 }) // Pause agent temporarily await smartProxy.pauseAgent('data-analysis-bot') // Get agent status and spending const agent = await smartProxy.getAgent('customer-support-bot') console.log(`Agent spent: $${agent.totalSpent} / $${agent.dailyLimit}`)

Intelligent Routing

The smart proxyintelligently routes requests based on agent configuration:

// Agent requests are automatically routed through smart proxy const response = await fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { 'X-Agent-ID': 'customer-support-bot', 'X-SmartProxy-Token': smartProxy.getToken(), 'Authorization': 'Bearer sk-...' }, body: JSON.stringify({ model: 'gpt-4', messages: [{ role: 'user', content: 'Hello' }] }) })

Real-World Configuration Examples

Here are common agent configuration patterns for different use cases:

Customer Service Agent

await smartProxy.createAgent({ id: 'customer-service-v1', name: 'Customer Service Bot', description: 'Handles customer inquiries during business hours', walletAddress: '0x...', dailyLimit: 25, // Conservative limit for customer interactions perCallLimit: 0.50, // Small cost per interaction monthlyLimit: 500, // Monthly budget control allowedAPIs: ['openai.com'], // Only trusted LLM provider emergencyContact: 'devops@company.com', businessHours: { enabled: true, timezone: 'America/New_York', schedule: '09:00-17:00' // Only active during business hours } })

Data Processing Agent

await smartProxy.createAgent({ id: 'data-processor-prod', name: 'Production Data Processor', description: 'Processes customer data and generates reports', walletAddress: '0x...', dailyLimit: 100, // Higher limit for data processing perCallLimit: 5, // Larger requests for bulk processing monthlyLimit: 2000, // Monthly budget for data operations allowedAPIs: ['*'], // Allow various data processing APIs rateLimiting: { maxConcurrentRequests: 3, // Prevent overwhelming APIs requestsPerMinute: 30 } })

Development/Testing Agent

await smartProxy.createAgent({ id: 'dev-test-agent', name: 'Development Testing Agent', description: 'Agent for development and testing purposes', walletAddress: '0x...', dailyLimit: 10, // Low limit for testing perCallLimit: 1, // Small requests during development monthlyLimit: 200, // Development budget allowedAPIs: ['openai.com', 'anthropic.com'], autoShutoff: { enabled: true, threshold: 0.9 // Auto-pause at 90% of daily limit } })

Advanced Controls

Time-based Limits

await smartProxy.setScheduledLimits('trading-bot', { // Higher limits during market hours '09:00-16:00': { maxPerRequest: 5, maxHourly: 100 }, // Lower limits overnight '16:00-09:00': { maxPerRequest: 1, maxHourly: 20 } })

API-specific Limits

await smartProxy.setAPILimits('data-bot', { 'openai.com': { maxPerRequest: 2, maxDaily: 50 }, 'anthropic.com': { maxPerRequest: 1, maxDaily: 30 }, 'huggingface.co': { maxPerRequest: 0.5, maxDaily: 20 } })

Cost-based Routing

await smartProxy.setCostRouting('smart-bot', { // Use cheaper APIs first strategy: 'cost-optimized', fallbacks: [ { api: 'huggingface.co', maxCost: 0.01 }, { api: 'openai.com', maxCost: 0.05 }, { api: 'anthropic.com', maxCost: 0.10 } ] })

Dashboard Features

Real-time Overview

The web dashboard provides instant visibility into agent spending:

  • Live spending meter: Current daily/monthly spend vs limits
  • Active agents: Which agents are currently making requests
  • Top spenders: Agents consuming the most budget
  • Recent transactions: Live feed of x402 payments

Analytics & Insights

Deep analytics help optimize agent performance:

  • Cost per response: Average cost by model and API
  • Request patterns: Usage patterns throughout the day
  • Efficiency metrics: Cost vs quality analysis
  • Budget utilization: How efficiently agents use their budgets

Alert Configuration

Flexible alerting keeps you informed:

// Configure alerts in dashboard or via API { "alerts": [ { "trigger": "daily_spend_80_percent", "channels": ["slack", "email"], "message": "Agent {agent_id} has spent 80% of daily budget" }, { "trigger": "unusual_spending_pattern", "channels": ["discord"], "message": "Anomalous spending detected for {agent_id}" } ] }

Pricing

The Smart Proxy uses a freemium SaaS model:

Free Tier

  • Up to 3 agents
  • $100/month total spending limit
  • Basic analytics (7-day history)
  • Email alerts only
  • Community support

Pro Tier - $49/month

  • Up to 25 agents
  • $10,000/month total spending limit
  • Advanced analytics (90-day history)
  • All alert channels (Slack, Discord, webhooks)
  • Priority support
  • Custom API integrations

Enterprise Tier - Custom pricing

  • Unlimited agents
  • Custom spending limits
  • 1-year+ analytics retention
  • White-label dashboard
  • SSO integration
  • Dedicated support
  • On-premise deployment options

Getting Started

1. Create Smart Proxy Instance

Sign up and create your first smart proxy:

npx @xpaysh/cli smart-proxy create --name "my-agents"

This creates a unique endpoint: https://smart-proxy-abc123.xpay.sh

2. Configure Your First Agent

import { SmartProxy } from '@xpaysh/agent-kit' const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: process.env.XPAY_SMART_PROXY_KEY }) await smartProxy.configureAgent('my-first-agent', { maxDailySpend: 25, maxPerRequest: 1, alertThreshold: 0.8 // Alert at 80% })

3. Route Agent Requests

Update your agent to use the smart proxy:

// Before: Direct API calls const response = await fetch('https://api.openai.com/v1/chat/completions', { // ... request config }) // After: Smart Proxy-protected calls const response = await smartProxy.protectedFetch('https://api.openai.com/v1/chat/completions', { agentId: 'my-first-agent', // ... request config })

4. Monitor in Dashboard

Visit your dashboard to see real-time spending: https://dashboard.xpay.sh/smart-proxy/abc123

Error Handling & Recovery

Handling Spending Limit Errors

import { SmartProxy, SpendingLimitError } from '@xpaysh/agent-kit' async function makeProtectedRequest(agentId: string, apiCall: () => Promise<Response>) { try { return await smartProxy.protectedFetch(apiCall, { agentId }) } catch (error) { if (error instanceof SpendingLimitError) { switch (error.limitType) { case 'daily': console.log(`Agent ${agentId} hit daily limit. Retry tomorrow.`) // Queue request for next day await scheduleRetryTomorrow(agentId, apiCall) break case 'per_request': console.log(`Request too expensive for agent ${agentId}`) // Try with a cheaper model or reduce request size return await fallbackToSmallerModel(agentId, apiCall) case 'monthly': console.log(`Agent ${agentId} hit monthly budget`) // Alert administrators and pause agent await notifyAdmins(agentId, 'monthly_limit_exceeded') await smartProxy.pauseAgent(agentId) break } } throw error } }

Automatic Fallback Strategies

// Configure agents with fallback chains await smartProxy.createAgent({ id: 'smart-agent', name: 'Cost-Optimized Agent', walletAddress: '0x...', dailyLimit: 50, fallbackChain: [ { provider: 'openai.com', model: 'gpt-3.5-turbo', maxCost: 0.01 }, { provider: 'anthropic.com', model: 'claude-haiku', maxCost: 0.02 }, { provider: 'openai.com', model: 'gpt-4', maxCost: 0.05 } ], onLimitExceeded: 'pause_and_notify' })

Real-time Monitoring

// Set up webhooks for real-time monitoring await smartProxy.configureWebhooks({ endpoint: 'https://your-app.com/webhooks/xpay', events: [ 'agent.spending.warning', // 80% of limit reached 'agent.spending.exceeded', // Limit exceeded 'agent.paused', // Agent automatically paused 'agent.request.failed', // Request failed 'agent.unusual_pattern' // Unusual spending pattern detected ], secret: 'webhook_secret_key' }) // Handle webhook in your application app.post('/webhooks/xpay', (req, res) => { const { event, data } = req.body switch (event) { case 'agent.spending.warning': // Notify team that agent is approaching limits notifySlack(`Agent ${data.agentId} at ${data.percentUsed}% of daily limit`) break case 'agent.spending.exceeded': // Log incident and review agent configuration logger.warn('Agent spending limit exceeded', data) reviewAgentLimits(data.agentId) break } res.status(200).send('OK') })

Best Practices

Agent Configuration

  • Start conservative: Begin with low limits and increase as needed
  • Use agent-specific limits: Different agents have different cost profiles
  • Monitor for a week: Establish baseline spending patterns before setting final limits
  • Enable all alerts: Early detection prevents costly surprises
  • Set up webhooks: Get real-time notifications for spending events
  • Use descriptive names: Clear agent names help with monitoring and debugging

Cost Optimization

  • Implement retries: Handle temporary payment failures gracefully
  • Cache responses: Avoid repeated API calls for identical requests
  • Use cheaper models: Start with smaller models, escalate to larger ones only when needed
  • Batch requests: Combine multiple operations when APIs support it

Security

  • Rotate API keys: Regular key rotation prevents unauthorized usage
  • Use separate wallets: Don’t use your personal wallet for agent payments
  • Monitor for unusual patterns: Set up anomaly detection alerts
  • Regular audits: Review agent spending patterns monthly

Integration Examples

LangChain Integration

import { LLMChain } from 'langchain/chains' import { OpenAI } from 'langchain/llms/openai' import { SmartProxy } from '@xpaysh/agent-kit' const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: process.env.XPAY_SMART_PROXY_KEY }) // Create protected LLM const llm = new OpenAI({ openAIApiKey: process.env.OPENAI_API_KEY, // Override fetch to use smart proxy fetch: (url, init) => smartProxy.protectedFetch(url, { ...init, agentId: 'langchain-agent' }) }) const chain = new LLMChain({ llm, prompt })

AutoGPT Integration

# Python example for AutoGPT from xpay import SmartProxy smartProxy = SmartProxy( endpoint='https://smart-proxy-abc123.xpay.sh', api_key=os.getenv('XPAY_SMART_PROXY_KEY') ) # Configure AutoGPT agent smartProxy.configure_agent('autogpt-main', { 'max_daily_spend': 100, 'max_per_request': 5, 'allowed_apis': ['openai.com', 'anthropic.com'] }) # Override HTTP client import requests session = requests.Session() session.request = smartProxy.protected_request

FAQ

How does the smart proxyhandle API keys?

The smart proxyacts as a transparent proxy - your API keys are passed through securely and never stored. The smart proxyonly adds spending controls and monitoring.

What happens when limits are exceeded?

When a limit is exceeded, the smart proxyreturns a 429 Too Many Requests response with details about which limit was hit and when the agent can retry.

Can I use the smart proxywith non-x402 APIs?

Currently, the smart proxyis designed specifically for x402-enabled APIs. Support for traditional APIs with custom billing may be added in the future.

Is there latency overhead?

The smart proxyadds approximately 10-50ms of latency per request, depending on your geographic location and our nearest edge server.


Ready to protect your agents? Get started with the Smart Proxy → 

Last updated on: