π‘οΈ AgentGuard
π¨ The Problem
Your AI agent has a bug. It makes 1000 API calls in a loop. Your $2000 credit card gets charged.
This happens to developers every week:
Infinite loops in AI workflows
Testing with production API keys
Agents that don't know when to stop
One typo = hundreds of dollars gone
Existing tools only tell you after the damage is done.
π‘ The Solution
AgentGuard automatically kills your process before it burns through your budget.
// Add 2 lines to any AI project: const agentGuard = require ( 'agent-guard' ) ; await agentGuard . init ( { limit : 50 } ) ; // $50 budget limit // Your code runs normally until it hits $50, then AgentGuard stops it const response = await openai . chat . completions . create ( { ... } ) ;
Result: Instead of losing $2000, you lose $50 and get a detailed report.
π How It Works
graph TD A["π€ Your AI Agent Starts"] --> B["π¦ AgentGuard.init({ limit: $50 })"] B --> C["π Monitors All AI API Calls"] C --> D["π° Tracks Real-Time Costs"] D --> E{"πΈ Cost β₯ $50?"} E -->|No| F["β
Continue Running"] E -->|Yes| G["π Emergency Stop"] F --> C G --> H["π Show Savings Report"] H --> I["πΎ Log Final Statistics"] style A fill:#e1f5fe style B fill:#f3e5f5 style C fill:#fff3e0 style D fill:#fff3e0 style E fill:#ffebee style G fill:#ffcdd2 style H fill:#e8f5e8 Loading
Real-Time Monitoring
sequenceDiagram participant App as π€ Your App participant AG as π‘οΈ AgentGuard participant API as π AI API participant User as π€ Developer App->>AG: init({ limit: $50, mode: "throw" }) AG->>App: β
Protection Active loop Every AI Call App->>API: API Request (OpenAI/Anthropic) API->>App: Response + Usage Data AG->>AG: π° Calculate Cost ($0.0243) AG->>AG: π Update Total ($47.23 / $50) alt Cost Under Limit AG->>App: β
Continue else Cost Exceeds Limit AG->>App: π throw AgentGuardError AG->>User: π± Webhook Notification AG->>User: π° "Saved you ~$200!" end end Loading
Protection Modes
graph LR subgraph "π οΈ Protection Modes" A["mode: 'throw'
π‘οΈ Safest"] B["mode: 'notify'
β οΈ Warning"] C["mode: 'kill'
π Nuclear"] end subgraph "π― When Limit Exceeded" A --> D["β Throws recoverable error
π Allows cleanup
π Graceful shutdown"] B --> E["β οΈ Logs warning
π Continues monitoring
π¨ Sends notifications"] C --> F["π process.exit(1)
π« Immediate termination
β‘ No cleanup"] end style A fill:#e8f5e8 style B fill:#fff3e0 style C fill:#ffebee style D fill:#e8f5e8 style E fill:#fff3e0 style F fill:#ffebee Loading Why AgentGuard vs Other Tools? Tool What It Does When You Find Out About Problems OpenAI Dashboard Shows usage after it happens Hours later via email LangChain Callbacks Tracks tokens in your code After script finishes tokencost Estimates costs beforehand Before you make calls AgentGuard Stops execution when limit hit Immediately, mid-execution AgentGuard is the only tool that actually prevents runaway costs in real-time. Quick Start 1. Install npm install agent-guard 2. Add Protection const agentGuard = require ( 'agent-guard' ) ; await agentGuard . init ( { limit : 50 } ) ; // $50 budget // Your existing AI code works unchanged const response = await openai . chat . completions . create ( { ... } ) ; 3. Watch It Work π‘οΈ AgentGuard v1.2.1 initialized π° Budget protection: $50 (mode: throw) π $12.34 / $50.00 (24.7%) | OpenAI API tracked π COST LIMIT EXCEEDED - Saved you ~$2000! Quick Start // Step 1: Add these two lines to your AI agent const agentGuard = require ( 'agent-guard' ) ; await agentGuard . init ( { limit : 25 } ) ; // $25 budget limit // Step 2: Your existing code works unchanged const response = await openai . chat . completions . create ( { model : 'gpt-4' , messages : [ { role : 'user' , content : 'Hello world' } ] } ) ; console . log ( 'Response:' , response ) ; // β AgentGuard automatically tracks this // Real-time protection: π‘οΈ $12.34 / $25.00 49.4% Production Configuration try { const guard = await agentGuard . init ( { limit : 100 , // Budget limit in USD mode : 'throw' , // Safe error vs 'kill' (hard exit) webhook : 'https://hooks.slack.com/...' , // Slack/Discord alerts redis : 'redis://localhost:6379' , // Multi-process shared budgets privacy : true // Redact sensitive data } ) ; // Your AI agent code here... } catch ( error ) { if ( error . message . includes ( 'AGENTGUARD_LIMIT_EXCEEDED' ) ) { console . log ( 'Budget protection activated:' , error . agentGuardData ) ; // Handle gracefully: save state, notify, switch to cheaper model, etc. } } What You'll See -------------------------------------------------- π‘οΈ AgentGuard v1.2.0 initialized π° Budget protection: $2 5 (mode: throw) π‘ Monitoring: console.log, fetch, axios, undici, got -------------------------------------------------- $0 .23 / $2 5.00 0.9% # Real-time cost tracking $2 .45 / $2 5.00 9.8% # Updates with each API call $2 0.10 / $2 5.00 80.4% # Warning at 80% $2 4.89 / $2 5.00 99.6% # Danger at 90% π AGENTGUARD: COST LIMIT EXCEEDED - Saved you ~ $7 5.00 π° Total cost when stopped: $2 4.89 π Budget used: 99.6% π‘οΈ Mode: throw - gracefully stopping with recoverable error π‘ Real-World Examples Development Protection // Protect development scripts from expensive mistakes await agentGuard . init ( { limit : 10 , mode : 'throw' } ) ; // Safely experiment with AI without surprise bills Production Deployment // Multi-process protection with Redis await agentGuard . init ( { limit : 1000 , mode : 'throw' , redis : 'redis://production:6379' , webhook : 'https://hooks.slack.com/alerts' } ) ; Browser Applications < script src =" https://unpkg.com/agent-guard@latest/dist/agent-guard.min.js " > script > < script > AgentGuard . init ( { limit : 50 , mode : 'notify' } ) ; // Your browser AI agent runs with cost protection script > Dynamic Budget Management const guard = await agentGuard . init ( { limit : 100 } ) ; // Check costs anytime console . log ( `Spent: $ ${ guard . getCost ( ) } ` ) ; // Adjust for high-priority tasks if ( urgentTask ) guard . setLimit ( 500 ) ; // Reset for new session await guard . reset ( ) ; π― Live Protection Examples See AgentGuard prevent real runaway costs: # Runaway loop protection (simulates infinite AI loop) node examples/runaway-loop-demo.js # Real customer workflow with budget protection node examples/real-customer-demo.js # LangChain integration example node examples/langchain-example.js # Interactive browser demo open examples/test-browser.html What you'll see: Real-time cost tracking, automatic protection activation, and graceful error handling that saves money. π§ How Real-Time Protection Works Automatic AI API Interception No code changes needed - AgentGuard automatically monitors: fetch() - Global HTTP request interception - Global HTTP request interception axios - Automatic response processing - Automatic response processing undici/got - Modern Node.js HTTP clients - Modern Node.js HTTP clients console.log() - API response detection in logs - API response detection in logs http/https - Raw Node.js request monitoring Accurate Cost Calculation Real tokenizers : OpenAI's tiktoken + Anthropic's official tokenizer : OpenAI's + Anthropic's official tokenizer Live pricing : Fetches current rates from community sources : Fetches current rates from community sources Streaming support : Accumulates tokens from partial responses : Accumulates tokens from partial responses Multimodal : Handles images, audio, and complex content : Handles images, audio, and complex content Smart fallback: Accurate estimation when tokenizers unavailable Protection Activation Real-time tracking: Every API call updates budget Threshold warnings: Visual alerts at 80% and 90% Limit enforcement: Automatic protection when budget exceeded Graceful handling: Throws catchable error vs hard process exit Cost data: Detailed breakdown for recovery decisions Supports all major providers: OpenAI, Anthropic, auto-detected from URLs π What Gets Protected π‘οΈ Infinite loops calling AI APIs calling AI APIs π‘οΈ Expensive model calls (GPT-4, Claude Opus) (GPT-4, Claude Opus) π‘οΈ Recursive agent calls with bugs with bugs π‘οΈ Development workflows with cost oversight with cost oversight π‘οΈ Runaway RAG document processing π Security & Reliability Privacy Protection await agentGuard . init ( { privacy : true , // Redacts request/response content from logs silent : true // Disables cost display for sensitive environments } ) ; Data redaction : Request/response bodies marked as [REDACTED] : Request/response bodies marked as URL filtering : Sensitive API endpoints optionally hidden : Sensitive API endpoints optionally hidden Local operation : No data sent to external services : No data sent to external services Memory safety: Automatic cleanup of sensitive data Failure Mode Safety // Graceful degradation (recommended) mode: 'throw' // Throws catchable AgentGuardError mode: 'notify' // Warns but continues execution mode: 'kill' // Hard process termination (use sparingly) Why soft failures matter: β Preserves database transactions β Allows graceful cleanup β Enables error recovery β Protects worker threads Multi-Process Protection await agentGuard . init ( { redis : 'redis://localhost:6379' , // Shared budget across processes limit : 100 // Combined limit for all instances } ) ; π οΈ API Reference Initializes AgentGuard with the specified options. const agentGuard = require ( 'agent-guard' ) ; const guard = await agentGuard . init ( { limit : 50 , // Cost limit in USD mode : 'throw' , // 'throw' | 'notify' | 'kill' webhook : null , // Webhook URL for notifications redis : null , // Redis URL for multi-process tracking privacy : false , // Redact sensitive data silent : false // Hide cost updates } ) ; Guard Instance Methods // Cost monitoring guard . getCost ( ) // Current total cost guard . getLimit ( ) // Current budget limit guard . getLogs ( ) // Detailed API call history // Budget management guard . setLimit ( 200 ) // Update budget limit guard . reset ( ) // Reset costs to $0 // Configuration guard . setMode ( 'notify' ) // Change protection mode guard . updatePrices ( ) // Refresh live pricing data π€ Contributing We love contributions! See our Contributing Guide for details. git clone https://github.com/dipampaul17/AgentGuard.git cd AgentGuard node verify-installation.js π License MIT - Use anywhere, even commercial projects. π Support π¦ What's Included β Real-time protection - Autonomous cost prevention that actually works - Autonomous cost prevention that actually works β Production ready - TypeScript definitions, browser support, Redis integration - TypeScript definitions, browser support, Redis integration β Live examples - LangChain integration, runaway protection demos - LangChain integration, runaway protection demos β Comprehensive docs - API reference, security guide, comparison analysis AgentGuard: The only tool that stops AI runaway costs before they happen. Real-time budget enforcement β’ Graceful error handling β’ Zero code changes β Star on GitHub β’ π¦ Install from NPM β’ π See Comparison
π‘οΈ Safest"] B["mode: 'notify'
β οΈ Warning"] C["mode: 'kill'
π Nuclear"] end subgraph "π― When Limit Exceeded" A --> D["β Throws recoverable error
π Allows cleanup
π Graceful shutdown"] B --> E["β οΈ Logs warning
π Continues monitoring
π¨ Sends notifications"] C --> F["π process.exit(1)
π« Immediate termination
β‘ No cleanup"] end style A fill:#e8f5e8 style B fill:#fff3e0 style C fill:#ffebee style D fill:#e8f5e8 style E fill:#fff3e0 style F fill:#ffebee Loading Why AgentGuard vs Other Tools? Tool What It Does When You Find Out About Problems OpenAI Dashboard Shows usage after it happens Hours later via email LangChain Callbacks Tracks tokens in your code After script finishes tokencost Estimates costs beforehand Before you make calls AgentGuard Stops execution when limit hit Immediately, mid-execution AgentGuard is the only tool that actually prevents runaway costs in real-time. Quick Start 1. Install npm install agent-guard 2. Add Protection const agentGuard = require ( 'agent-guard' ) ; await agentGuard . init ( { limit : 50 } ) ; // $50 budget // Your existing AI code works unchanged const response = await openai . chat . completions . create ( { ... } ) ; 3. Watch It Work π‘οΈ AgentGuard v1.2.1 initialized π° Budget protection: $50 (mode: throw) π $12.34 / $50.00 (24.7%) | OpenAI API tracked π COST LIMIT EXCEEDED - Saved you ~$2000! Quick Start // Step 1: Add these two lines to your AI agent const agentGuard = require ( 'agent-guard' ) ; await agentGuard . init ( { limit : 25 } ) ; // $25 budget limit // Step 2: Your existing code works unchanged const response = await openai . chat . completions . create ( { model : 'gpt-4' , messages : [ { role : 'user' , content : 'Hello world' } ] } ) ; console . log ( 'Response:' , response ) ; // β AgentGuard automatically tracks this // Real-time protection: π‘οΈ $12.34 / $25.00 49.4% Production Configuration try { const guard = await agentGuard . init ( { limit : 100 , // Budget limit in USD mode : 'throw' , // Safe error vs 'kill' (hard exit) webhook : 'https://hooks.slack.com/...' , // Slack/Discord alerts redis : 'redis://localhost:6379' , // Multi-process shared budgets privacy : true // Redact sensitive data } ) ; // Your AI agent code here... } catch ( error ) { if ( error . message . includes ( 'AGENTGUARD_LIMIT_EXCEEDED' ) ) { console . log ( 'Budget protection activated:' , error . agentGuardData ) ; // Handle gracefully: save state, notify, switch to cheaper model, etc. } } What You'll See -------------------------------------------------- π‘οΈ AgentGuard v1.2.0 initialized π° Budget protection: $2 5 (mode: throw) π‘ Monitoring: console.log, fetch, axios, undici, got -------------------------------------------------- $0 .23 / $2 5.00 0.9% # Real-time cost tracking $2 .45 / $2 5.00 9.8% # Updates with each API call $2 0.10 / $2 5.00 80.4% # Warning at 80% $2 4.89 / $2 5.00 99.6% # Danger at 90% π AGENTGUARD: COST LIMIT EXCEEDED - Saved you ~ $7 5.00 π° Total cost when stopped: $2 4.89 π Budget used: 99.6% π‘οΈ Mode: throw - gracefully stopping with recoverable error π‘ Real-World Examples Development Protection // Protect development scripts from expensive mistakes await agentGuard . init ( { limit : 10 , mode : 'throw' } ) ; // Safely experiment with AI without surprise bills Production Deployment // Multi-process protection with Redis await agentGuard . init ( { limit : 1000 , mode : 'throw' , redis : 'redis://production:6379' , webhook : 'https://hooks.slack.com/alerts' } ) ; Browser Applications < script src =" https://unpkg.com/agent-guard@latest/dist/agent-guard.min.js " > script > < script > AgentGuard . init ( { limit : 50 , mode : 'notify' } ) ; // Your browser AI agent runs with cost protection script > Dynamic Budget Management const guard = await agentGuard . init ( { limit : 100 } ) ; // Check costs anytime console . log ( `Spent: $ ${ guard . getCost ( ) } ` ) ; // Adjust for high-priority tasks if ( urgentTask ) guard . setLimit ( 500 ) ; // Reset for new session await guard . reset ( ) ; π― Live Protection Examples See AgentGuard prevent real runaway costs: # Runaway loop protection (simulates infinite AI loop) node examples/runaway-loop-demo.js # Real customer workflow with budget protection node examples/real-customer-demo.js # LangChain integration example node examples/langchain-example.js # Interactive browser demo open examples/test-browser.html What you'll see: Real-time cost tracking, automatic protection activation, and graceful error handling that saves money. π§ How Real-Time Protection Works Automatic AI API Interception No code changes needed - AgentGuard automatically monitors: fetch() - Global HTTP request interception - Global HTTP request interception axios - Automatic response processing - Automatic response processing undici/got - Modern Node.js HTTP clients - Modern Node.js HTTP clients console.log() - API response detection in logs - API response detection in logs http/https - Raw Node.js request monitoring Accurate Cost Calculation Real tokenizers : OpenAI's tiktoken + Anthropic's official tokenizer : OpenAI's + Anthropic's official tokenizer Live pricing : Fetches current rates from community sources : Fetches current rates from community sources Streaming support : Accumulates tokens from partial responses : Accumulates tokens from partial responses Multimodal : Handles images, audio, and complex content : Handles images, audio, and complex content Smart fallback: Accurate estimation when tokenizers unavailable Protection Activation Real-time tracking: Every API call updates budget Threshold warnings: Visual alerts at 80% and 90% Limit enforcement: Automatic protection when budget exceeded Graceful handling: Throws catchable error vs hard process exit Cost data: Detailed breakdown for recovery decisions Supports all major providers: OpenAI, Anthropic, auto-detected from URLs π What Gets Protected π‘οΈ Infinite loops calling AI APIs calling AI APIs π‘οΈ Expensive model calls (GPT-4, Claude Opus) (GPT-4, Claude Opus) π‘οΈ Recursive agent calls with bugs with bugs π‘οΈ Development workflows with cost oversight with cost oversight π‘οΈ Runaway RAG document processing π Security & Reliability Privacy Protection await agentGuard . init ( { privacy : true , // Redacts request/response content from logs silent : true // Disables cost display for sensitive environments } ) ; Data redaction : Request/response bodies marked as [REDACTED] : Request/response bodies marked as URL filtering : Sensitive API endpoints optionally hidden : Sensitive API endpoints optionally hidden Local operation : No data sent to external services : No data sent to external services Memory safety: Automatic cleanup of sensitive data Failure Mode Safety // Graceful degradation (recommended) mode: 'throw' // Throws catchable AgentGuardError mode: 'notify' // Warns but continues execution mode: 'kill' // Hard process termination (use sparingly) Why soft failures matter: β Preserves database transactions β Allows graceful cleanup β Enables error recovery β Protects worker threads Multi-Process Protection await agentGuard . init ( { redis : 'redis://localhost:6379' , // Shared budget across processes limit : 100 // Combined limit for all instances } ) ; π οΈ API Reference Initializes AgentGuard with the specified options. const agentGuard = require ( 'agent-guard' ) ; const guard = await agentGuard . init ( { limit : 50 , // Cost limit in USD mode : 'throw' , // 'throw' | 'notify' | 'kill' webhook : null , // Webhook URL for notifications redis : null , // Redis URL for multi-process tracking privacy : false , // Redact sensitive data silent : false // Hide cost updates } ) ; Guard Instance Methods // Cost monitoring guard . getCost ( ) // Current total cost guard . getLimit ( ) // Current budget limit guard . getLogs ( ) // Detailed API call history // Budget management guard . setLimit ( 200 ) // Update budget limit guard . reset ( ) // Reset costs to $0 // Configuration guard . setMode ( 'notify' ) // Change protection mode guard . updatePrices ( ) // Refresh live pricing data π€ Contributing We love contributions! See our Contributing Guide for details. git clone https://github.com/dipampaul17/AgentGuard.git cd AgentGuard node verify-installation.js π License MIT - Use anywhere, even commercial projects. π Support π¦ What's Included β Real-time protection - Autonomous cost prevention that actually works - Autonomous cost prevention that actually works β Production ready - TypeScript definitions, browser support, Redis integration - TypeScript definitions, browser support, Redis integration β Live examples - LangChain integration, runaway protection demos - LangChain integration, runaway protection demos β Comprehensive docs - API reference, security guide, comparison analysis AgentGuard: The only tool that stops AI runaway costs before they happen. Real-time budget enforcement β’ Graceful error handling β’ Zero code changes β Star on GitHub β’ π¦ Install from NPM β’ π See Comparison