Early Access : The AI Agents API is in early access. Request access at [email protected]
AI Agents API: Autonomous Commerce Infrastructure
π€ Overview
StateSetβs AI Agents API enables you to deploy autonomous agents that can execute transactions, manage inventory, negotiate deals, and handle complex commerce operations 24/7. Built with native stablecoin integration and advanced safety controls.
Autonomous Execution Agents operate independently within defined parameters
Built-in Safety Multi-level controls prevent runaway spending
Real-time Learning Agents improve performance through ML optimization
π Quick Start
JavaScript examples assume a structured logger is available as logger. Replace with your preferred logger in production.
Deploy Your First Agent
import { StateSet } from '@stateset/sdk' ;
// Replace with a structured logger (Winston, Pino, etc) in production
const logger = console ;
const stateset = new StateSet ({ apiKey: process . env . STATESET_API_KEY });
// Deploy a procurement agent
const agent = await stateset . agents . create ({
name: 'ProcurementBot-01' ,
type: 'procurement' ,
capabilities: [ 'negotiate' , 'purchase' , 'track' ],
limits: {
daily_spend: '10000.00' ,
per_transaction: '1000.00' ,
requires_approval_above: '5000.00'
}
});
logger . info ( 'Agent deployed' , { agentId: agent . id });
Set Agent Parameters
// Configure agent behavior
await stateset . agents . configure ( agent . id , {
procurement_rules: {
preferred_suppliers: [ 'supplier_123' , 'supplier_456' ],
max_price_variance: 0.05 , // 5% above market
delivery_requirements: '3_days' ,
quality_threshold: 0.95
},
negotiation_strategy: 'balanced' , // aggressive, balanced, conservative
learning_enabled: true
});
Monitor Agent Activity
// Replace with a structured logger (Winston, Pino, etc) in production
const logger = console ;
// Real-time agent monitoring
const activity = await stateset . agents . activity ( agent . id , {
timeframe: '24h'
});
logger . info ( 'Transactions' , { count: activity . transaction_count });
logger . info ( 'Total spent' , { totalSpent: activity . total_spent });
logger . info ( 'Savings achieved' , { savings: activity . savings });
π Agent Types
Procurement Agents
Sales Agents
Finance Agents
Logistics Agents
Automated Purchasing & Negotiation Procurement agents handle supplier relationships, negotiate prices, and execute purchases based on inventory levels and demand forecasts. const procurementAgent = await stateset . agents . create ({
type: 'procurement' ,
name: 'SupplyChainOptimizer' ,
capabilities: [
'supplier_discovery' ,
'price_negotiation' ,
'order_placement' ,
'delivery_tracking'
],
config: {
inventory_triggers: {
reorder_point: 100 ,
optimal_quantity: 500 ,
safety_stock: 50
},
supplier_preferences: {
min_rating: 4.5 ,
max_delivery_days: 5 ,
payment_terms: [ 'NET_30' , 'NET_60' ]
}
}
});
Key Features:
Automatic reordering based on inventory levels
Multi-supplier price comparison
Dynamic negotiation based on order volume
Quality and delivery performance tracking
Intelligent Sales Automation Sales agents handle customer inquiries, negotiate deals, and manage the entire sales cycle autonomously. const salesAgent = await stateset . agents . create ({
type: 'sales' ,
name: 'SalesBot-Enterprise' ,
capabilities: [
'lead_qualification' ,
'price_quoting' ,
'contract_negotiation' ,
'upsell_identification'
],
config: {
pricing_authority: {
base_discount: 0.10 ,
max_discount: 0.25 ,
volume_tiers: [
{ min: 100 , discount: 0.15 },
{ min: 500 , discount: 0.20 },
{ min: 1000 , discount: 0.25 }
]
},
response_time: '5_minutes' ,
languages: [ 'en' , 'es' , 'fr' , 'de' ]
}
});
Treasury & Financial Management Finance agents optimize cash flow, manage payments, and execute financial strategies. const financeAgent = await stateset . agents . create ({
type: 'finance' ,
name: 'TreasuryManager' ,
capabilities: [
'invoice_factoring' ,
'payment_optimization' ,
'forex_management' ,
'yield_farming'
],
config: {
treasury_rules: {
min_cash_balance: '50000.00' ,
invoice_factoring_threshold: 0.02 , // 2% discount
payment_timing: 'optimize_discounts'
},
risk_parameters: {
max_counterparty_exposure: '100000.00' ,
collateral_ratio: 1.5 ,
stop_loss: 0.05
}
}
});
Supply Chain Optimization Logistics agents manage shipping, routing, and delivery optimization. const logisticsAgent = await stateset . agents . create ({
type: 'logistics' ,
name: 'ShippingOptimizer' ,
capabilities: [
'carrier_selection' ,
'route_optimization' ,
'tracking_management' ,
'customs_handling'
],
config: {
optimization_goals: {
primary: 'cost' ,
secondary: 'speed' ,
constraints: [ 'carbon_neutral' ]
},
carrier_preferences: {
tier_1: [ 'DHL' , 'FedEx' , 'UPS' ],
tier_2: [ 'Regional_Carriers' ],
blacklist: []
}
}
});
π Safety & Controls
Multi-Level Security Framework
// Configure comprehensive spending controls
await stateset . agents . setLimits ( agent . id , {
absolute_limits: {
daily: '10000.00' ,
weekly: '50000.00' ,
monthly: '150000.00' ,
per_transaction: '5000.00'
},
velocity_controls: {
max_transactions_per_hour: 10 ,
max_transactions_per_day: 50 ,
cooldown_after_limit: '1_hour'
},
approval_thresholds: {
auto_approve_below: '1000.00' ,
human_approval_above: '5000.00' ,
board_approval_above: '50000.00'
}
});
// Define operational constraints
await stateset . agents . setBehaviors ( agent . id , {
allowed_actions: [
'purchase_from_approved_suppliers' ,
'negotiate_within_parameters' ,
'execute_recurring_orders'
],
prohibited_actions: [
'create_new_contracts' ,
'modify_payment_terms' ,
'access_sensitive_data'
],
ethical_constraints: {
sustainability_required: true ,
fair_trade_only: true ,
no_conflict_minerals: true
}
});
// Emergency stop mechanisms
// Immediate halt
await stateset . agents . emergencyStop ( agent . id );
// Gradual shutdown
await stateset . agents . gracefulShutdown ( agent . id , {
complete_pending: true ,
notify_counterparties: true ,
transfer_to_human: 'ops_team'
});
// Circuit breaker configuration
await stateset . agents . setCircuitBreaker ( agent . id , {
error_threshold: 5 ,
error_window: '10_minutes' ,
recovery_timeout: '1_hour' ,
half_open_requests: 3
});
π‘ Agent Communication
Inter-Agent Protocols
// Replace with a structured logger (Winston, Pino, etc) in production
const logger = console ;
// Enable agent-to-agent negotiation
const negotiation = await stateset . agents . negotiate ({
buyer_agent: 'agent_buyer_123' ,
seller_agent: 'agent_seller_456' ,
item: {
sku: 'WIDGET-001' ,
quantity: 1000 ,
target_price: '10.00'
},
parameters: {
max_rounds: 10 ,
timeout: '5_minutes' ,
binding_agreement: true
}
});
// Monitor negotiation progress
negotiation . on ( 'round_complete' , ( round ) => {
logger . info ( 'Round complete' , {
round: round . number ,
buyerOffer: round . buyer_offer ,
sellerOffer: round . seller_offer
});
});
negotiation . on ( 'agreement_reached' , ( deal ) => {
logger . info ( 'Agreement reached' , {
price: deal . price ,
quantity: deal . quantity
});
});
Human-Agent Collaboration
// Set up human oversight
await stateset . agents . setOversight ( agent . id , {
notification_channels: {
email: [ '[email protected] ' ],
slack: '#agent-alerts' ,
sms: [ '+1234567890' ]
},
escalation_triggers: [
'unusual_price_variance' ,
'new_supplier_request' ,
'large_order_placement' ,
'repeated_failures'
],
human_intervention_points: {
pre_execution: [ 'orders_above_5000' ],
post_execution: [ 'all_transactions' ],
on_error: [ 'payment_failures' , 'delivery_issues' ]
}
});
Real-Time Metrics
// Get comprehensive agent analytics
const analytics = await stateset . agents . analytics ( agent . id , {
period: '30_days' ,
metrics: [
'transaction_volume' ,
'success_rate' ,
'average_savings' ,
'response_time' ,
'learning_progress'
]
});
// Response
{
"agent_id" : "agent_123" ,
"period" : "30_days" ,
"performance" : {
"transactions" : 1543 ,
"success_rate" : 0.97 ,
"total_volume" : "543,234.56" ,
"average_transaction" : "352.15" ,
"savings_achieved" : "32,445.23" ,
"savings_percentage" : 0.06
},
"behavioral_insights" : {
"preferred_suppliers" : [ "supp_123" , "supp_456" ],
"peak_activity_hours" : [ 9 , 10 , 14 , 15 ],
"negotiation_success_rate" : 0.78 ,
"average_negotiation_rounds" : 3.4
},
"learning_metrics" : {
"model_accuracy" : 0.92 ,
"prediction_confidence" : 0.88 ,
"adaptation_rate" : 0.15 ,
"knowledge_base_size" : 15420
}
}
Custom Reporting
// Create custom agent reports
const report = await stateset . agents . generateReport ({
agent_ids: [ 'agent_123' , 'agent_456' ],
report_type: 'comparative_analysis' ,
metrics: {
financial: [ 'total_spend' , 'roi' , 'cost_savings' ],
operational: [ 'response_time' , 'accuracy' , 'throughput' ],
strategic: [ 'supplier_diversity' , 'innovation_score' ]
},
format: 'pdf' ,
schedule: 'weekly'
});
π§ͺ Testing & Simulation
Sandbox Environment
// Replace with a structured logger (Winston, Pino, etc) in production
const logger = console ;
// Test agent behavior in sandbox
const simulation = await stateset . agents . simulate ({
agent_id: agent . id ,
scenario: 'market_volatility' ,
parameters: {
price_fluctuation: 0.20 ,
supply_disruption: 0.10 ,
demand_spike: 1.50
},
duration: '7_days'
});
// Monitor simulation results
simulation . on ( 'day_complete' , ( day ) => {
logger . info ( 'Day complete' , {
day: day . number ,
performanceScore: day . performance_score
});
});
π¨ Error Handling
try {
const result = await agent . execute ( transaction );
} catch ( error ) {
switch ( error . code ) {
case 'LIMIT_EXCEEDED' :
// Handle spending limit
await notifyFinanceTeam ( error );
break ;
case 'UNAUTHORIZED_ACTION' :
// Handle permission violation
await logSecurityEvent ( error );
break ;
case 'LEARNING_FAILURE' :
// Handle ML model issues
await fallbackToRules ( transaction );
break ;
default :
// Generic error handling
await agent . reportError ( error );
}
}
π Integrations
ERP Systems Direct integration with SAP, Oracle, Microsoft Dynamics
ML Platforms TensorFlow, PyTorch, and Hugging Face model support
Communication Slack, Teams, Email, and SMS notifications
Analytics Export to Tableau, PowerBI, and custom dashboards
π Resources