Webhook Integration Guide

Complete API reference for AgenticFlow's webhook system, enabling real-time integration with external systems.

Webhooks provide real-time notifications and triggers for your AgenticFlow agents and workflows. They enable bi-directional communication with external systems, allowing your automations to respond to events and send notifications instantly.


πŸ”— Webhook Overview

What Are AgenticFlow Webhooks?

Webhooks are HTTP endpoints that allow external systems to trigger your AgenticFlow automations or receive notifications when specific events occur.

Two Types of Webhooks

  1. Incoming Webhooks: External systems send data to AgenticFlow

  2. Outgoing Webhooks: AgenticFlow sends data to external systems

Common Use Cases

  • Form submissions: Trigger workflows when users submit forms

  • Payment notifications: Process orders when payments complete

  • Status updates: Notify external systems of workflow completion

  • Real-time sync: Keep data synchronized across systems

  • Event-driven automation: React to external system events


πŸ“₯ Incoming Webhooks

Creating Incoming Webhooks

1. Agent Webhooks

Every agent can receive webhooks to trigger conversations:

POST https://api.agenticflow.ai/webhooks/agents/{agent_id}

2. Workflow Webhooks

Workflows can be triggered via webhooks:

POST https://api.agenticflow.ai/webhooks/workflows/{workflow_id}

Webhook URL Format

https://api.agenticflow.ai/webhooks/{type}/{id}?token={webhook_token}

Parameters:

  • type: agents or workflows

  • id: Your agent or workflow ID

  • webhook_token: Security token for authentication

Authentication Methods

POST https://api.agenticflow.ai/webhooks/agents/abc123?token=wh_1234567890abcdef

2. Header Authentication

POST /webhooks/agents/abc123
Authorization: Bearer wh_1234567890abcdef
Content-Type: application/json

3. Basic Authentication

POST /webhooks/agents/abc123
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Content-Type: application/json

Request Format

Agent Webhook Request

{
  "message": "Hello, I need help with my order #12345",
  "user_id": "user_123",
  "metadata": {
    "source": "contact_form",
    "priority": "high",
    "department": "support"
  },
  "context": {
    "order_id": "12345",
    "customer_email": "[email protected]"
  }
}

Workflow Webhook Request

{
  "input_data": {
    "name": "John Doe",
    "email": "[email protected]",
    "message": "I'm interested in your product"
  },
  "trigger_source": "contact_form",
  "metadata": {
    "form_id": "contact_v2",
    "page_url": "https://example.com/contact",
    "user_agent": "Mozilla/5.0..."
  }
}

Response Format

Successful Response

{
  "success": true,
  "message": "Webhook processed successfully",
  "execution_id": "exec_1234567890",
  "status": "queued",
  "estimated_completion": "2024-01-15T10:30:00Z"
}

Error Response

{
  "success": false,
  "error": {
    "code": "INVALID_INPUT",
    "message": "Required field 'message' is missing",
    "details": {
      "field": "message",
      "expected": "string",
      "received": "null"
    }
  }
}

πŸ“€ Outgoing Webhooks

Configuring Outgoing Webhooks

Set up webhooks to send data to external systems when events occur.

Available Events

  • agent.conversation.started

  • agent.conversation.completed

  • agent.message.received

  • agent.message.sent

  • workflow.execution.started

  • workflow.execution.completed

  • workflow.execution.failed

  • workflow.step.completed

Webhook Configuration

{
  "url": "https://your-app.com/webhooks/agenticflow",
  "events": [
    "workflow.execution.completed",
    "workflow.execution.failed"
  ],
  "authentication": {
    "type": "bearer",
    "token": "your_secret_token"
  },
  "retry_policy": {
    "max_retries": 3,
    "backoff_multiplier": 2
  }
}

Outgoing Webhook Payload

Workflow Completion Event

{
  "event": "workflow.execution.completed",
  "timestamp": "2024-01-15T10:30:00Z",
  "webhook_id": "wh_987654321",
  "data": {
    "workflow_id": "wf_abc123",
    "execution_id": "exec_1234567890",
    "status": "success",
    "started_at": "2024-01-15T10:25:00Z",
    "completed_at": "2024-01-15T10:30:00Z",
    "duration_seconds": 300,
    "input_data": {
      "name": "John Doe",
      "email": "[email protected]"
    },
    "output_data": {
      "result": "Email sent successfully",
      "email_id": "email_567890"
    },
    "credits_used": 4.5,
    "steps_completed": 5
  }
}

Agent Conversation Event

{
  "event": "agent.conversation.completed",
  "timestamp": "2024-01-15T10:30:00Z",
  "webhook_id": "wh_987654321",
  "data": {
    "agent_id": "agent_abc123",
    "conversation_id": "conv_1234567890",
    "user_id": "user_123",
    "status": "resolved",
    "started_at": "2024-01-15T10:20:00Z",
    "completed_at": "2024-01-15T10:30:00Z",
    "message_count": 8,
    "satisfaction_score": 4.5,
    "credits_used": 12.0,
    "resolution": {
      "type": "solved",
      "category": "technical_support",
      "tags": ["password_reset", "account_access"]
    }
  }
}

πŸ”§ Webhook Management API

Create Webhook

POST /api/v1/webhooks
Authorization: Bearer your_api_key
Content-Type: application/json

{
  "name": "Order Processing Webhook",
  "url": "https://your-app.com/webhooks/orders",
  "events": ["workflow.execution.completed"],
  "authentication": {
    "type": "bearer",
    "token": "your_secret"
  }
}

List Webhooks

GET /api/v1/webhooks
Authorization: Bearer your_api_key

Response:

{
  "webhooks": [
    {
      "id": "wh_123456789",
      "name": "Order Processing Webhook",
      "url": "https://your-app.com/webhooks/orders",
      "events": ["workflow.execution.completed"],
      "status": "active",
      "created_at": "2024-01-15T09:00:00Z",
      "last_delivery": "2024-01-15T10:30:00Z",
      "delivery_stats": {
        "total_deliveries": 245,
        "successful_deliveries": 242,
        "failed_deliveries": 3
      }
    }
  ]
}

Update Webhook

PUT /api/v1/webhooks/{webhook_id}
Authorization: Bearer your_api_key
Content-Type: application/json

{
  "url": "https://new-app.com/webhooks/orders",
  "events": [
    "workflow.execution.completed",
    "workflow.execution.failed"
  ]
}

Delete Webhook

DELETE /api/v1/webhooks/{webhook_id}
Authorization: Bearer your_api_key

Test Webhook

POST /api/v1/webhooks/{webhook_id}/test
Authorization: Bearer your_api_key

{
  "event": "workflow.execution.completed",
  "test_data": {
    "workflow_id": "test_workflow",
    "status": "success"
  }
}

πŸ”’ Security & Authentication

Webhook Signature Verification

AgenticFlow signs all outgoing webhook payloads for security verification.

Signature Header

X-AgenticFlow-Signature: sha256=1234567890abcdef...

Verification Example (Node.js)

const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  
  const providedSignature = signature.replace('sha256=', '');
  
  return crypto.timingSafeEqual(
    Buffer.from(expectedSignature),
    Buffer.from(providedSignature)
  );
}

// Usage in Express.js
app.post('/webhooks/agenticflow', (req, res) => {
  const signature = req.headers['x-agenticflow-signature'];
  const payload = JSON.stringify(req.body);
  
  if (!verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }
  
  // Process webhook...
  res.status(200).send('OK');
});

Verification Example (Python)

import hmac
import hashlib

def verify_webhook_signature(payload, signature, secret):
    expected_signature = hmac.new(
        secret.encode('utf-8'),
        payload.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()
    
    provided_signature = signature.replace('sha256=', '')
    
    return hmac.compare_digest(expected_signature, provided_signature)

# Usage in Flask
@app.route('/webhooks/agenticflow', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-AgenticFlow-Signature')
    payload = request.get_data(as_text=True)
    
    if not verify_webhook_signature(payload, signature, os.environ['WEBHOOK_SECRET']):
        return 'Invalid signature', 401
    
    # Process webhook...
    return 'OK', 200

IP Whitelisting

Restrict webhook access to AgenticFlow's IP ranges:

Webhook Source IPs:
- 52.70.124.191
- 54.164.23.45
- 18.208.139.52
- 35.174.76.89

⚑ Advanced Features

Conditional Webhooks

Set up webhooks that only trigger based on specific conditions:

{
  "url": "https://your-app.com/webhooks/high-priority",
  "events": ["agent.conversation.completed"],
  "conditions": {
    "satisfaction_score": {"lt": 3},
    "message_count": {"gt": 10}
  }
}

Webhook Filters

Filter webhook payloads to include only specific fields:

{
  "url": "https://your-app.com/webhooks/orders",
  "events": ["workflow.execution.completed"],
  "filters": {
    "include_fields": [
      "workflow_id",
      "status",
      "output_data.order_id",
      "credits_used"
    ]
  }
}

Batch Webhooks

Combine multiple events into a single webhook delivery:

{
  "url": "https://your-app.com/webhooks/batch",
  "events": ["workflow.execution.completed"],
  "batch_settings": {
    "max_events": 100,
    "max_wait_seconds": 300
  }
}

πŸ“Š Monitoring & Debugging

Webhook Logs

Access detailed logs of webhook deliveries:

GET /api/v1/webhooks/{webhook_id}/logs
Authorization: Bearer your_api_key

Response:

{
  "logs": [
    {
      "id": "log_123456789",
      "timestamp": "2024-01-15T10:30:00Z",
      "event": "workflow.execution.completed",
      "status": "success",
      "response_code": 200,
      "response_time_ms": 145,
      "attempts": 1,
      "payload_size": 1024
    }
  ]
}

Delivery Statistics

Monitor webhook performance and reliability:

GET /api/v1/webhooks/{webhook_id}/stats
Authorization: Bearer your_api_key

Failed Delivery Handling

AgenticFlow automatically retries failed webhook deliveries:

  • Retry Schedule: 1min, 5min, 15min, 1hr, 6hr, 24hr

  • Max Retries: 6 attempts

  • Backoff Strategy: Exponential with jitter

  • Failure Notifications: Email alerts for persistent failures


πŸ› οΈ Integration Examples

Slack Notifications

// Webhook endpoint to send workflow completions to Slack
app.post('/webhooks/agenticflow', (req, res) => {
  const { event, data } = req.body;
  
  if (event === 'workflow.execution.completed') {
    const message = {
      text: `Workflow ${data.workflow_id} completed successfully!`,
      attachments: [{
        color: data.status === 'success' ? 'good' : 'danger',
        fields: [
          { title: 'Duration', value: `${data.duration_seconds}s`, short: true },
          { title: 'Credits Used', value: data.credits_used, short: true }
        ]
      }]
    };
    
    // Send to Slack webhook
    fetch(process.env.SLACK_WEBHOOK_URL, {
      method: 'POST',
      body: JSON.stringify(message)
    });
  }
  
  res.status(200).send('OK');
});

Database Synchronization

@app.route('/webhooks/agenticflow', methods=['POST'])
def sync_to_database():
    data = request.json
    
    if data['event'] == 'agent.conversation.completed':
        conversation = data['data']
        
        # Save to database
        db.conversations.insert_one({
            'agent_id': conversation['agent_id'],
            'conversation_id': conversation['conversation_id'],
            'user_id': conversation['user_id'],
            'completed_at': conversation['completed_at'],
            'satisfaction_score': conversation['satisfaction_score'],
            'credits_used': conversation['credits_used']
        })
    
    return 'OK', 200

πŸ“‹ Best Practices

Webhook Design

  • Idempotency: Handle duplicate deliveries gracefully

  • Fast Response: Respond within 30 seconds

  • Error Handling: Return appropriate HTTP status codes

  • Logging: Log all webhook events for debugging

  • Security: Always verify webhook signatures

Performance Optimization

  • Async Processing: Queue webhook processing for heavy operations

  • Batch Updates: Combine multiple events when possible

  • Timeout Handling: Set appropriate timeouts for external calls

  • Monitoring: Track webhook performance metrics

Error Handling

app.post('/webhooks/agenticflow', async (req, res) => {
  try {
    // Verify signature first
    if (!verifySignature(req)) {
      return res.status(401).send('Invalid signature');
    }
    
    // Process webhook asynchronously
    await processWebhookAsync(req.body);
    
    // Respond immediately
    res.status(200).send('OK');
  } catch (error) {
    console.error('Webhook processing failed:', error);
    
    // Return 500 to trigger retry
    res.status(500).send('Internal server error');
  }
});

Webhooks provide the real-time connectivity that makes AgenticFlow a powerful integration platform. Whether you're triggering workflows from external events or notifying systems of automation results, webhooks enable seamless bi-directional communication with your existing infrastructure.

Need help setting up webhooks? Join our Discord community or contact our support team at [email protected] for personalized assistance.

Last updated

Was this helpful?