Skip to main content
The Background Agent API provides comprehensive task management capabilities for automated workflow execution. All endpoints require enterprise authentication and proper authorization.
To get access to Background Agent APIs, contact enterprise@context.ai

Base URL & Authentication

Base URL: https://agents.yourcompany.com:8443/api/v1

Authentication

All API requests require a valid JWT token obtained through enterprise SSO:
// Get authentication token
const response = await fetch('https://agents.yourcompany.com:8443/auth/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    username: 'user@yourcompany.com',
    password: 'password'
    // OR use SSO token
    // sso_token: 'your_sso_token'
  })
});

const { access_token } = await response.json();

Task Management Endpoints

Submit Background Task

Create and submit a new background task for automated processing.
const response = await fetch('/api/v1/tasks', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${access_token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    task_type: "research_agent",
    priority: 5,
    input: {
      query: "Analyze Q3 financial performance for tech sector",
      sources: ["financial_reports", "market_data", "earnings_calls"],
      analysis_depth: "comprehensive",
      output_format: "executive_summary"
    },
    webhook_url: "https://yourcompany.com/webhooks/tasks",
    metadata: {
      department: "finance",
      project: "quarterly_analysis",
      requester: "jane.doe@company.com"
    }
  })
});

const result = await response.json();
console.log(result);

Response Format

{
  "task_id": "task_123e4567-e89b-12d3-a456-426614174000",
  "status": "accepted",
  "task_type": "research_agent",
  "priority": 5,
  "estimated_completion": "2024-01-15T11:30:00Z",
  "created_at": "2024-01-15T10:30:00Z",
  "webhook_configured": true,
  "metadata": {
    "department": "finance",
    "project": "quarterly_analysis",
    "requester": "jane.doe@company.com"
  }
}

Get Task Status

Retrieve the current status and progress of a background task.
const response = await fetch(`/api/v1/tasks/${task_id}`, {
  headers: {
    'Authorization': `Bearer ${access_token}`
  }
});

const taskStatus = await response.json();

Response Format

{
  "task_id": "task_123e4567-e89b-12d3-a456-426614174000",
  "status": "processing",
  "task_type": "research_agent",
  "priority": 5,
  "progress": {
    "percentage": 65,
    "current_stage": "analyzing_market_data",
    "stages_completed": ["data_collection", "source_validation"],
    "estimated_remaining_minutes": 8
  },
  "created_at": "2024-01-15T10:30:00Z",
  "started_at": "2024-01-15T10:32:00Z",
  "last_updated": "2024-01-15T10:45:00Z",
  "output_preview": {
    "key_insights": [
      "Tech sector showed 12% growth in Q3",
      "Cloud services leading performance"
    ]
  }
}

List Tasks

Retrieve a list of background tasks with filtering and pagination options.
const params = new URLSearchParams({
  status: 'processing,completed',
  task_type: 'research_agent',
  limit: '20',
  offset: '0',
  sort_by: 'created_at',
  sort_order: 'desc'
});

const response = await fetch(`/api/v1/tasks?${params}`, {
  headers: {
    'Authorization': `Bearer ${access_token}`
  }
});

const tasks = await response.json();

Response Format

{
  "tasks": [
    {
      "task_id": "task_123e4567-e89b-12d3-a456-426614174000",
      "status": "completed",
      "task_type": "research_agent",
      "priority": 5,
      "progress_percentage": 100,
      "created_at": "2024-01-15T10:30:00Z",
      "completed_at": "2024-01-15T11:15:00Z",
      "duration_minutes": 45,
      "metadata": {
        "department": "finance",
        "project": "quarterly_analysis"
      }
    }
  ],
  "pagination": {
    "total_count": 150,
    "offset": 0,
    "limit": 20,
    "has_next": true
  }
}

Cancel Task

Cancel a pending or processing background task.
const response = await fetch(`/api/v1/tasks/${task_id}/cancel`, {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${access_token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    reason: "Task no longer needed",
    force: false
  })
});

Get Task Results

Retrieve the complete results of a completed background task.
const response = await fetch(`/api/v1/tasks/${task_id}/results`, {
  headers: {
    'Authorization': `Bearer ${access_token}`,
    'Accept': 'application/json'
  }
});

const results = await response.json();

Response Format

{
  "task_id": "task_123e4567-e89b-12d3-a456-426614174000",
  "status": "completed",
  "results": {
    "executive_summary": {
      "title": "Q3 Tech Sector Financial Analysis",
      "key_findings": [
        "Overall sector growth of 12% compared to Q2",
        "Cloud services segment leading with 18% growth",
        "Hardware segment showing slower 6% growth"
      ],
      "recommendations": [
        "Increase investment in cloud infrastructure companies",
        "Monitor hardware sector for potential consolidation"
      ]
    },
    "detailed_analysis": {
      "market_segments": {
        "cloud_services": {
          "growth_rate": 0.18,
          "market_size_billion": 156.8,
          "key_players": ["MSFT", "AMZN", "GOOGL"]
        },
        "hardware": {
          "growth_rate": 0.06,
          "market_size_billion": 89.3,
          "key_players": ["AAPL", "NVDA", "AMD"]
        }
      },
      "sources_analyzed": 47,
      "confidence_score": 0.94
    }
  },
  "processing_details": {
    "sources_processed": 47,
    "processing_time_minutes": 43,
    "context_engine_queries": 156,
    "confidence_scores": {
      "data_quality": 0.96,
      "analysis_completeness": 0.91,
      "source_reliability": 0.98
    }
  },
  "completed_at": "2024-01-15T11:15:00Z"
}

Agent Type Endpoints

Research Agent Tasks

Submit specialized research tasks for market intelligence and analysis.
const researchTask = {
  task_type: "research_agent",
  input: {
    research_type: "market_intelligence",
    query: "Emerging trends in fintech for 2024",
    sources: ["industry_reports", "news_feeds", "analyst_reports"],
    geographic_scope: ["north_america", "europe"],
    depth: "comprehensive",
    deliverables: ["executive_summary", "detailed_report", "key_metrics"]
  },
  priority: 7,
  webhook_url: "https://yourcompany.com/webhooks/research"
};

Processing Agent Tasks

Submit document processing and data extraction tasks.
const processingTask = {
  task_type: "processing_agent",
  input: {
    processing_type: "document_analysis",
    documents: [
      {
        url: "https://yourcompany.com/documents/contract_123.pdf",
        type: "legal_contract"
      },
      {
        url: "https://yourcompany.com/documents/financial_report.xlsx",
        type: "financial_data"
      }
    ],
    extraction_rules: [
      "contract_terms",
      "key_dates",
      "financial_metrics",
      "risk_factors"
    ],
    output_format: "structured_json"
  }
};

Notification Agent Tasks

Configure automated notification and reporting workflows.
const notificationTask = {
  task_type: "notification_agent",
  input: {
    notification_type: "scheduled_report",
    schedule: {
      frequency: "weekly",
      day_of_week: "monday",
      time: "09:00:00",
      timezone: "America/New_York"
    },
    content: {
      data_sources: ["sales_dashboard", "financial_metrics"],
      recipients: ["executives@company.com", "board@company.com"],
      format: "pdf_report",
      include_charts: true
    }
  }
};

WebSocket Integration

For real-time task updates, establish a WebSocket connection.

WebSocket Connection

// Get WebSocket authentication token
const wsAuthResponse = await fetch('/api/v1/websocket-auth', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${access_token}`,
    'Content-Type': 'application/json'
  }
});

const { websocket_token } = await wsAuthResponse.json();

// Connect to WebSocket
const ws = new WebSocket('wss://agents.yourcompany.com:8443/ws/tasks');

ws.onopen = () => {
  // Authenticate WebSocket connection
  ws.send(JSON.stringify({
    type: 'authenticate',
    token: websocket_token
  }));
  
  // Subscribe to task updates
  ws.send(JSON.stringify({
    type: 'subscribe',
    channels: ['task_updates', 'system_notifications']
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  handleTaskUpdate(data);
};

function handleTaskUpdate(data) {
  switch(data.type) {
    case 'task_started':
      console.log(`Task ${data.task_id} started processing`);
      break;
      
    case 'task_progress':
      console.log(`Task ${data.task_id} progress: ${data.progress}%`);
      break;
      
    case 'task_completed':
      console.log(`Task ${data.task_id} completed successfully`);
      break;
      
    case 'task_failed':
      console.error(`Task ${data.task_id} failed: ${data.error}`);
      break;
  }
}

Webhook Configuration

Configure webhooks to receive task notifications at your endpoints.

Webhook Payload Format

{
  "event_type": "task_completed",
  "task_id": "task_123e4567-e89b-12d3-a456-426614174000",
  "timestamp": "2024-01-15T11:15:00Z",
  "data": {
    "status": "completed",
    "duration_minutes": 43,
    "results_available": true,
    "results_url": "/api/v1/tasks/task_123e4567-e89b-12d3-a456-426614174000/results"
  },
  "metadata": {
    "department": "finance",
    "project": "quarterly_analysis",
    "requester": "jane.doe@company.com"
  }
}

Webhook Signature Verification

const crypto = require('crypto');

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

// Express.js webhook handler example
app.post('/webhooks/background-tasks', express.raw({type: 'application/json'}), (req, res) => {
  const signature = req.headers['x-context-signature'];
  const payload = req.body;
  
  if (!verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }
  
  const event = JSON.parse(payload);
  console.log('Received webhook:', event);
  
  res.status(200).send('OK');
});

Error Handling

Error Response Format

{
  "error": {
    "code": "TASK_VALIDATION_FAILED",
    "message": "Invalid task configuration",
    "details": {
      "invalid_fields": ["task_type", "input.sources"],
      "valid_task_types": ["research_agent", "processing_agent", "notification_agent"],
      "valid_sources": ["financial_reports", "market_data", "news_feeds"]
    },
    "request_id": "req_1234567890",
    "timestamp": "2024-01-15T10:30:00Z"
  }
}

Common Error Codes

CodeDescriptionResolution
UNAUTHORIZEDInvalid or expired authentication tokenRefresh authentication token
TASK_VALIDATION_FAILEDInvalid task configurationCheck task parameters against API docs
RATE_LIMIT_EXCEEDEDToo many requestsImplement exponential backoff
INSUFFICIENT_RESOURCESSystem at capacityRetry later or contact support
TASK_TIMEOUTTask exceeded maximum processing timeReduce task complexity or increase timeout

Rate Limits

Background Agent API implements rate limiting per organization:
EndpointRate LimitBurst Limit
POST /tasks100 requests/hour10 requests/minute
GET /tasks1000 requests/hour50 requests/minute
GET /tasks/{id}500 requests/hour25 requests/minute
WebSocket connections5 concurrent connectionsN/A

JavaScript SDK

Official JavaScript SDK is available exclusively for enterprise customers. To get access to the Background Agents SDK, contact enterprise@context.ai with your integration requirements.

Next Steps

I