agentbill

N8N node for AgentBill API - AI usage tracking & billing automation

Package Information

Downloads: 58 weekly / 70 monthly
Latest Version: 5.0.2
Author: AgentBill

Documentation

AgentBill N8N Integration

Complete N8N node for AgentBill API with Cost Guard budget protection and 15+ core operations.

🛡️ NEW: Cost Guard - Budget Protection

Prevent AI overspending with pre-validation!

Cost Guard validates budgets BEFORE making expensive AI calls, protecting you from unexpected costs.

How Cost Guard Works:

1. Validate Budget → Check limits BEFORE spending
2. IF allowed → Make AI call → Track usage
3. IF blocked → Stop workflow → Send alert

Key Benefits:

  • Pre-validate requests - Check budget BEFORE API call
  • Block overspending - Request denied if budget exceeded
  • Zero wastage - Never pay for blocked requests
  • Automatic tracking - Usage recorded after completion
  • Daily & monthly limits - Flexible budget controls

→ See examples/cost-guard-workflow.json for complete workflow


Features

🛡️ Cost Guard Operations (NEW)

  1. Validate AI Request - Check budget BEFORE spending
  2. Track AI Usage - Record usage AFTER completion

🎯 Core Operations

  1. Track Signal - Record AI usage events with full metadata
  2. Track Usage - Simple usage logging
  3. Get Usage Summary - Aggregate cost & token metrics
  4. List Customers - View all customers
  5. Create Customer - Add new customers
  6. Get Customer - Retrieve single customer details
  7. List Agents - View all AI agents
  8. Create Agent - Configure new agents

📊 High-Value Operations

  1. Get Analytics - Prompt profitability analytics
  2. List Invoices - Billing history
  3. Get Invoice - Single invoice details
  4. Create Webhook - Event notifications
  5. List Signal Types - Available event types
  6. Get Cost Analysis - Detailed cost breakdown
  7. List Reconciliations - Discrepancy reports

Installation

See INSTALLATION.md for complete setup guide.

Quick Start

Method 1: Install from npm (Recommended)

# Install globally
npm install -g @agentbill/n8n-nodes-agentbill

# Or add to your N8N instance
cd ~/.n8n
npm install @agentbill/n8n-nodes-agentbill

Method 2: Docker

FROM n8nio/n8n:latest
USER root
RUN cd /home/node/.n8n && npm install @agentbill/n8n-nodes-agentbill
USER node

Method 3: Manual Installation

# Copy to your n8n custom nodes directory
cp -r integrations/n8n/* ~/.n8n/custom/
cd ~/.n8n/custom && npm install && npm run build

Restart N8N

# Local installation
systemctl restart n8n

# Docker
docker restart n8n_container

# npm
npm run start

Add Credentials

  1. Open N8N interface
  2. Go to CredentialsNew
  3. Search for AgentBill API
  4. Enter your API key (starts with agb_)
  5. Save

Usage Examples

💡 Tip: Find complete workflow JSON files in the examples/ directory. Import them directly into N8N!

Example 1: 🛡️ Cost Guard - Protected AI Workflow

Validate budget BEFORE making AI calls to prevent overspending:

{
  "nodes": [
    {
      "name": "1. Validate Budget",
      "type": "agentBill",
      "parameters": {
        "resource": "costGuard",
        "operation": "validateRequest",
        "customerId": "customer-123",
        "model": "gpt-4o-mini",
        "messages": "[{\"role\": \"user\", \"content\": \"Hello\"}]",
        "estimatedInputTokens": 50,
        "estimatedOutputTokens": 100,
        "dailyBudget": 10.00,
        "monthlyBudget": 200.00
      }
    },
    {
      "name": "2. Check If Allowed",
      "type": "if",
      "parameters": {
        "conditions": {
          "boolean": [
            { "value1": "={{ $json.allowed }}", "value2": true }
          ]
        }
      }
    },
    {
      "name": "3. Make AI Call (if allowed)",
      "type": "httpRequest",
      "parameters": {
        "url": "https://api.openai.com/v1/chat/completions",
        "method": "POST"
      }
    },
    {
      "name": "4. Track Usage",
      "type": "agentBill",
      "parameters": {
        "resource": "costGuard",
        "operation": "trackUsage",
        "customerId": "customer-123",
        "model": "gpt-4o-mini",
        "provider": "openai",
        "inputTokens": "={{ $json.usage.prompt_tokens }}",
        "outputTokens": "={{ $json.usage.completion_tokens }}"
      }
    },
    {
      "name": "5. Send Alert (if blocked)",
      "type": "emailSend",
      "parameters": {
        "message": "Budget exceeded: {{ $json.reason }}"
      }
    }
  ]
}

Import full workflow


Example 2: Track AI Chat Completion

{
  "nodes": [
    {
      "name": "AgentBill",
      "type": "agentBill",
      "parameters": {
        "resource": "signal",
        "operation": "trackSignal",
        "eventName": "chat.completion",
        "agentExternalId": "chatbot-001",
        "customerExternalId": "customer-123",
        "revenue": 0.05,
        "model": "gpt-4",
        "provider": "openai",
        "inputTokens": 150,
        "outputTokens": 50,
        "latencyMs": 1200
      }
    }
  ]
}

Example 2: Create Customer → Track Usage

{
  "nodes": [
    {
      "name": "Create Customer",
      "type": "agentBill",
      "parameters": {
        "resource": "customer",
        "operation": "create",
        "customerName": "Acme Corp",
        "email": "billing@acme.com",
        "phone": "+1234567890"
      }
    },
    {
      "name": "Track Signal",
      "type": "agentBill",
      "parameters": {
        "resource": "signal",
        "operation": "trackSignal",
        "eventName": "api.call",
        "customerExternalId": "={{$node['Create Customer'].json.id}}",
        "revenue": 0.10
      }
    }
  ]
}

Example 3: Get Analytics with Webhook

{
  "nodes": [
    {
      "name": "Get Analytics",
      "type": "agentBill",
      "parameters": {
        "resource": "analytics",
        "operation": "getAnalytics",
        "startDate": "2025-01-01T00:00:00Z",
        "endDate": "2025-01-31T23:59:59Z"
      }
    },
    {
      "name": "Send to Slack",
      "type": "slack",
      "parameters": {
        "message": "Monthly Analytics:\nTotal Revenue: $={{$json.total_revenue}}\nTotal Cost: $={{$json.total_cost}}"
      }
    }
  ]
}

Example 4: Automated Invoice Processing

{
  "nodes": [
    {
      "name": "Schedule Trigger",
      "type": "scheduleTrigger",
      "parameters": {
        "rule": {
          "interval": [
            { "field": "cronExpression", "expression": "0 0 1 * *" }
          ]
        }
      }
    },
    {
      "name": "List Invoices",
      "type": "agentBill",
      "parameters": {
        "resource": "invoice",
        "operation": "list"
      }
    },
    {
      "name": "Filter Unpaid",
      "type": "filter",
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{$json.status}}",
              "operation": "equals",
              "value2": "pending"
            }
          ]
        }
      }
    }
  ]
}

API Coverage

Operation Endpoint Method Description
🛡️ Validate AI Request /functions/v1/validate-ai-request POST Check budget BEFORE spending
🛡️ Track AI Usage /functions/v1/track-ai-usage POST Record usage AFTER completion
Track Signal /record-signals POST Record AI usage events
Track Usage /track-usage POST Simple usage tracking
Get Usage Summary /api-usage GET Aggregate metrics
List Customers /api-customers GET All customers
Create Customer /api-customers POST New customer
Get Customer /api-customers?id= GET Single customer
List Agents /api-agents GET All agents
Create Agent /api-agents POST New agent
Get Analytics /api-prompt-analytics GET Prompt analytics
List Invoices /api-invoices GET Invoice history
Get Invoice /api-invoices?id= GET Single invoice
Create Webhook /create-webhook POST Webhook endpoint
List Signal Types /signal-types GET Event types
Get Cost Analysis /api-prompt-analytics GET Cost breakdown
List Reconciliations /reconciliation-runs GET Reconciliation runs

Authentication

All requests require:

  • Header: X-API-Key: agb_your_api_key_here
  • Base URL: https://bgwyprqxtdreuutzpbgw.supabase.co/functions/v1

Get your API key from AgentBill Dashboard

Error Handling

The node includes built-in error handling:

// Continue on fail
{
  "continueOnFail": true,
  "alwaysOutputData": true
}

Errors return:

{
  "error": "Error message here",
  "statusCode": 400
}

Rate Limits

  • 100 requests/minute per API key
  • Batch operations count as 1 request
  • Use webhooks for high-frequency updates

Support

Version History

v1.1.0 (2025-01-28)

  • 🛡️ NEW: Cost Guard - Budget validation BEFORE spending
  • ✅ Added Validate AI Request operation
  • ✅ Added Track AI Usage operation
  • ✅ Comprehensive input validation (max lengths, ranges)
  • ✅ Example workflow with budget protection
  • ✅ Security hardening with proper error handling

v1.0.0 (2025-01-27)

  • ✅ Initial release with 15 core operations
  • ✅ Complete API coverage for common use cases
  • ✅ Authentication via API key
  • ✅ Error handling & validation
  • ✅ Webhook support

Discussion