Real-world implementation examples and best practices for Background Agent integration
class QuarterlyReportGenerator {
constructor(apiToken) {
this.apiToken = apiToken;
this.baseUrl = 'https://agents.yourcompany.com:8443/api/v1';
}
async generateQuarterlyReport(quarter, year) {
const taskConfig = {
task_type: "research_agent",
priority: 8,
input: {
research_type: "financial_analysis",
query: `Generate comprehensive quarterly report for Q${quarter} ${year}`,
sources: [
"financial_reports",
"market_data",
"earnings_calls",
"analyst_reports",
"regulatory_filings"
],
analysis_scope: {
competitors: ["MSFT", "GOOGL", "AMZN", "AAPL"],
metrics: ["revenue", "profit_margin", "market_share", "growth_rate"],
geographic_regions: ["north_america", "europe", "asia_pacific"]
},
deliverables: {
executive_summary: true,
detailed_analysis: true,
comparative_charts: true,
risk_assessment: true,
forward_projections: true
}
},
webhook_url: "https://yourcompany.com/webhooks/quarterly-reports",
metadata: {
department: "finance",
report_type: "quarterly",
quarter: quarter,
year: year,
requester: "cfo@company.com"
}
};
try {
const response = await fetch(`${this.baseUrl}/tasks`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(taskConfig)
});
const result = await response.json();
console.log(`Quarterly report task submitted: ${result.task_id}`);
// Set up progress monitoring
this.monitorTask(result.task_id);
return result;
} catch (error) {
console.error('Failed to submit quarterly report task:', error);
throw error;
}
}
async monitorTask(taskId) {
const checkProgress = async () => {
try {
const response = await fetch(`${this.baseUrl}/tasks/${taskId}`, {
headers: {
'Authorization': `Bearer ${this.apiToken}`
}
});
const task = await response.json();
console.log(`Task ${taskId} progress: ${task.progress.percentage}%`);
if (task.status === 'completed') {
console.log('Report generation completed!');
await this.handleCompletedReport(taskId);
clearInterval(progressInterval);
} else if (task.status === 'failed') {
console.error('Report generation failed:', task.error_message);
clearInterval(progressInterval);
}
} catch (error) {
console.error('Error checking task progress:', error);
}
};
const progressInterval = setInterval(checkProgress, 30000); // Check every 30 seconds
}
async handleCompletedReport(taskId) {
try {
const response = await fetch(`${this.baseUrl}/tasks/${taskId}/results`, {
headers: {
'Authorization': `Bearer ${this.apiToken}`,
'Accept': 'application/json'
}
});
const results = await response.json();
// Process results - save to database, send notifications, etc.
await this.saveReportToDatabase(results);
await this.notifyStakeholders(results);
console.log('Report processed and stakeholders notified');
} catch (error) {
console.error('Error handling completed report:', error);
}
}
async saveReportToDatabase(results) {
// Implementation to save report data to your database
console.log('Saving report to database...');
}
async notifyStakeholders(results) {
// Implementation to notify stakeholders via email/Slack
console.log('Notifying stakeholders...');
}
}
// Usage
const reportGenerator = new QuarterlyReportGenerator(process.env.CONTEXT_API_TOKEN);
await reportGenerator.generateQuarterlyReport(4, 2024);
class ContractAnalyzer {
constructor(apiToken) {
this.apiToken = apiToken;
this.baseUrl = 'https://agents.yourcompany.com:8443/api/v1';
}
async analyzeContract(contractUrl, contractType) {
const taskConfig = {
task_type: "processing_agent",
priority: 6,
input: {
processing_type: "legal_document_analysis",
documents: [{
url: contractUrl,
type: contractType,
security_level: "confidential"
}],
analysis_requirements: {
extract_key_terms: true,
identify_risks: true,
compliance_check: true,
financial_terms: true,
renewal_clauses: true,
termination_conditions: true
},
compliance_frameworks: ["SOC2", "GDPR", "HIPAA"],
risk_categories: [
"financial_risk",
"operational_risk",
"legal_risk",
"reputational_risk"
],
output_format: "structured_analysis"
},
webhook_url: "https://yourcompany.com/webhooks/contract-analysis"
};
const response = await fetch(`${this.baseUrl}/tasks`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(taskConfig)
});
return await response.json();
}
async batchAnalyzeContracts(contracts) {
const tasks = contracts.map(contract =>
this.analyzeContract(contract.url, contract.type)
);
const results = await Promise.all(tasks);
console.log(`Submitted ${results.length} contract analysis tasks`);
return results;
}
}
// Usage
const analyzer = new ContractAnalyzer(process.env.CONTEXT_API_TOKEN);
// Analyze single contract
await analyzer.analyzeContract(
"https://yourcompany.com/contracts/vendor-agreement-2024.pdf",
"vendor_agreement"
);
// Batch analyze multiple contracts
const contracts = [
{ url: "https://yourcompany.com/contracts/nda-acme.pdf", type: "nda" },
{ url: "https://yourcompany.com/contracts/service-agreement-xyz.pdf", type: "service_agreement" },
{ url: "https://yourcompany.com/contracts/employment-john-doe.pdf", type: "employment_contract" }
];
await analyzer.batchAnalyzeContracts(contracts);
class MarketMonitor {
constructor(apiToken) {
this.apiToken = apiToken;
this.baseUrl = 'https://agents.yourcompany.com:8443/api/v1';
}
async setupMarketMonitoring(portfolio) {
const monitoringConfigs = portfolio.map(asset => ({
task_type: "notification_agent",
priority: 9, // High priority for market alerts
input: {
notification_type: "market_monitoring",
asset: {
symbol: asset.symbol,
name: asset.name,
current_position: asset.position
},
monitoring_parameters: {
price_change_threshold: 0.05, // 5% change
volume_spike_threshold: 2.0, // 2x average volume
news_sentiment_threshold: -0.3, // Negative sentiment
analyst_rating_changes: true,
earnings_announcements: true
},
alert_channels: {
email: ["traders@company.com", "portfolio-manager@company.com"],
slack: "#trading-alerts",
webhook: "https://yourcompany.com/webhooks/market-alerts"
},
frequency_limits: {
max_alerts_per_hour: 5,
cooldown_period_minutes: 15
}
},
metadata: {
portfolio_id: portfolio.id,
asset_class: asset.class,
risk_level: asset.riskLevel
}
}));
const tasks = await Promise.all(
monitoringConfigs.map(config =>
fetch(`${this.baseUrl}/tasks`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(config)
}).then(res => res.json())
)
);
console.log(`Set up monitoring for ${tasks.length} assets`);
return tasks;
}
async createCustomAlert(alertConfig) {
const taskConfig = {
task_type: "research_agent",
priority: 7,
input: {
research_type: "market_event_analysis",
trigger_conditions: alertConfig.conditions,
analysis_depth: "immediate_assessment",
context_sources: [
"real_time_market_data",
"news_feeds",
"social_sentiment",
"technical_indicators"
],
output_requirements: {
impact_assessment: true,
recommended_actions: true,
confidence_score: true,
supporting_evidence: true
}
},
webhook_url: alertConfig.webhook_url
};
const response = await fetch(`${this.baseUrl}/tasks`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(taskConfig)
});
return await response.json();
}
}
// Usage
const monitor = new MarketMonitor(process.env.CONTEXT_API_TOKEN);
const portfolio = [
{ symbol: "AAPL", name: "Apple Inc.", position: 1000, class: "tech", riskLevel: "medium" },
{ symbol: "GOOGL", name: "Alphabet Inc.", position: 500, class: "tech", riskLevel: "medium" },
{ symbol: "TSLA", name: "Tesla Inc.", position: 200, class: "automotive", riskLevel: "high" }
];
await monitor.setupMarketMonitoring(portfolio);
const { WebClient } = require('@slack/web-api');
class SlackIntegration {
constructor(slackToken, contextApiToken) {
this.slack = new WebClient(slackToken);
this.contextApiToken = contextApiToken;
this.baseUrl = 'https://agents.yourcompany.com:8443/api/v1';
}
async handleWebhook(webhookPayload) {
const { event_type, task_id, data, metadata } = webhookPayload;
switch (event_type) {
case 'task_started':
await this.notifyTaskStarted(task_id, metadata);
break;
case 'task_completed':
await this.notifyTaskCompleted(task_id, data, metadata);
break;
case 'task_failed':
await this.notifyTaskFailed(task_id, data, metadata);
break;
}
}
async notifyTaskStarted(taskId, metadata) {
const channel = this.getChannelForDepartment(metadata.department);
await this.slack.chat.postMessage({
channel: channel,
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: `*Background Task Started*\n*Task ID:* \`${taskId}\`\n*Type:* ${metadata.task_type}\n*Requester:* ${metadata.requester}`
}
}
]
});
}
async notifyTaskCompleted(taskId, data, metadata) {
const channel = this.getChannelForDepartment(metadata.department);
// Get task results for summary
const response = await fetch(`${this.baseUrl}/tasks/${taskId}/results`, {
headers: { 'Authorization': `Bearer ${this.contextApiToken}` }
});
const results = await response.json();
await this.slack.chat.postMessage({
channel: channel,
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: `*Task Completed Successfully*\n*Task ID:* \`${taskId}\`\n*Duration:* ${data.duration_minutes} minutes\n*Confidence:* ${Math.round(results.processing_details.confidence_scores.analysis_completeness * 100)}%`
}
},
{
type: "section",
text: {
type: "mrkdwn",
text: `*Key Insights:*\n${results.results.executive_summary.key_findings.slice(0, 3).map(finding => `• ${finding}`).join('\n')}`
}
},
{
type: "actions",
elements: [
{
type: "button",
text: { type: "plain_text", text: "View Full Results" },
url: `https://yourcompany.com/tasks/${taskId}/results`
}
]
}
]
});
}
getChannelForDepartment(department) {
const channelMap = {
'finance': '#finance-automation',
'legal': '#legal-reviews',
'operations': '#ops-alerts',
'research': '#research-updates'
};
return channelMap[department] || '#general-automation';
}
}
// Express.js webhook handler
app.use('/webhooks/background-tasks', express.json());
app.post('/webhooks/background-tasks', async (req, res) => {
const slackIntegration = new SlackIntegration(
process.env.SLACK_BOT_TOKEN,
process.env.CONTEXT_API_TOKEN
);
try {
await slackIntegration.handleWebhook(req.body);
res.status(200).send('OK');
} catch (error) {
console.error('Webhook processing error:', error);
res.status(500).send('Error');
}
});
class WorkflowOrchestrator {
constructor(apiToken) {
this.apiToken = apiToken;
this.baseUrl = 'https://agents.yourcompany.com:8443/api/v1';
}
async executeCompanyAnalysisWorkflow(companySymbol) {
try {
// Stage 1: Initial company research
const stage1 = await this.submitTask({
task_type: "research_agent",
priority: 8,
input: {
research_type: "company_profile",
target: companySymbol,
sources: ["sec_filings", "financial_statements", "press_releases"],
depth: "comprehensive"
},
metadata: {
workflow_id: `company_analysis_${companySymbol}`,
stage: "initial_research",
next_stages: ["financial_analysis", "market_positioning"]
}
});
console.log(`Stage 1 submitted: ${stage1.task_id}`);
// Monitor stage 1 completion
const stage1Results = await this.waitForCompletion(stage1.task_id);
// Stage 2: Financial deep-dive (conditional on stage 1 results)
if (stage1Results.results.company_profile.financial_health_score > 0.7) {
const stage2 = await this.submitTask({
task_type: "research_agent",
priority: 7,
input: {
research_type: "financial_analysis",
target: companySymbol,
context_data: stage1Results.results,
analysis_focus: ["profitability", "growth_trends", "debt_analysis"],
benchmark_against: "industry_peers"
},
metadata: {
workflow_id: `company_analysis_${companySymbol}`,
stage: "financial_analysis",
parent_task: stage1.task_id
}
});
// Stage 3: Market positioning analysis
const stage3 = await this.submitTask({
task_type: "research_agent",
priority: 7,
input: {
research_type: "competitive_analysis",
target: companySymbol,
context_data: stage1Results.results,
competitive_factors: ["market_share", "competitive_advantages", "threats"],
geographic_scope: stage1Results.results.company_profile.primary_markets
},
metadata: {
workflow_id: `company_analysis_${companySymbol}`,
stage: "market_positioning",
parent_task: stage1.task_id
}
});
// Wait for both stage 2 and 3 to complete
const [stage2Results, stage3Results] = await Promise.all([
this.waitForCompletion(stage2.task_id),
this.waitForCompletion(stage3.task_id)
]);
// Stage 4: Final synthesis
const stage4 = await this.submitTask({
task_type: "processing_agent",
priority: 9,
input: {
processing_type: "data_synthesis",
input_data: {
company_profile: stage1Results.results,
financial_analysis: stage2Results.results,
market_positioning: stage3Results.results
},
synthesis_requirements: {
investment_recommendation: true,
risk_assessment: true,
price_target: true,
confidence_intervals: true
},
output_format: "investment_memo"
},
metadata: {
workflow_id: `company_analysis_${companySymbol}`,
stage: "final_synthesis",
parent_tasks: [stage1.task_id, stage2.task_id, stage3.task_id]
}
});
const finalResults = await this.waitForCompletion(stage4.task_id);
console.log(`Workflow completed for ${companySymbol}`);
return finalResults;
} else {
console.log(`Company ${companySymbol} does not meet financial health criteria`);
return { recommendation: "skip", reason: "insufficient_financial_health" };
}
} catch (error) {
console.error(`Workflow failed for ${companySymbol}:`, error);
throw error;
}
}
async submitTask(taskConfig) {
const response = await fetch(`${this.baseUrl}/tasks`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(taskConfig)
});
if (!response.ok) {
throw new Error(`Failed to submit task: ${response.statusText}`);
}
return await response.json();
}
async waitForCompletion(taskId, maxWaitMinutes = 60) {
const startTime = Date.now();
const maxWaitTime = maxWaitMinutes * 60 * 1000;
while (Date.now() - startTime < maxWaitTime) {
const response = await fetch(`${this.baseUrl}/tasks/${taskId}`, {
headers: { 'Authorization': `Bearer ${this.apiToken}` }
});
const task = await response.json();
if (task.status === 'completed') {
// Get full results
const resultsResponse = await fetch(`${this.baseUrl}/tasks/${taskId}/results`, {
headers: { 'Authorization': `Bearer ${this.apiToken}` }
});
return await resultsResponse.json();
} else if (task.status === 'failed') {
throw new Error(`Task ${taskId} failed: ${task.error_message}`);
}
// Wait 30 seconds before checking again
await new Promise(resolve => setTimeout(resolve, 30000));
}
throw new Error(`Task ${taskId} timed out after ${maxWaitMinutes} minutes`);
}
}
// Usage
const orchestrator = new WorkflowOrchestrator(process.env.CONTEXT_API_TOKEN);
// Execute complex analysis workflow
const companies = ['AAPL', 'GOOGL', 'MSFT'];
const analysisPromises = companies.map(company =>
orchestrator.executeCompanyAnalysisWorkflow(company)
);
const results = await Promise.allSettled(analysisPromises);
console.log('All company analyses completed:', results);
class RobustTaskSubmitter {
constructor(apiToken) {
this.apiToken = apiToken;
this.baseUrl = 'https://agents.yourcompany.com:8443/api/v1';
}
async submitTaskWithRetry(taskConfig, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(`${this.baseUrl}/tasks`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(taskConfig)
});
if (response.ok) {
return await response.json();
}
// Check if error is retryable
const error = await response.json();
if (this.isRetryableError(error.error.code)) {
console.log(`Attempt ${attempt} failed, retrying...`);
await this.exponentialBackoff(attempt);
continue;
} else {
throw new Error(`Non-retryable error: ${error.error.message}`);
}
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
console.log(`Attempt ${attempt} failed: ${error.message}`);
await this.exponentialBackoff(attempt);
}
}
}
isRetryableError(errorCode) {
const retryableErrors = [
'RATE_LIMIT_EXCEEDED',
'INSUFFICIENT_RESOURCES',
'TEMPORARY_SERVICE_UNAVAILABLE'
];
return retryableErrors.includes(errorCode);
}
async exponentialBackoff(attempt) {
const delay = Math.min(1000 * Math.pow(2, attempt - 1), 30000);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
class TaskPerformanceMonitor {
constructor(apiToken) {
this.apiToken = apiToken;
this.baseUrl = 'https://agents.yourcompany.com:8443/api/v1';
this.metrics = {
taskCounts: new Map(),
averageDurations: new Map(),
successRates: new Map()
};
}
async getTaskMetrics(timeRange = '24h') {
const response = await fetch(
`${this.baseUrl}/tasks?status=completed,failed&created_since=${timeRange}`,
{
headers: { 'Authorization': `Bearer ${this.apiToken}` }
}
);
const data = await response.json();
// Calculate metrics
const tasksByType = new Map();
const durationsByType = new Map();
const successByType = new Map();
data.tasks.forEach(task => {
const type = task.task_type;
// Count tasks
tasksByType.set(type, (tasksByType.get(type) || 0) + 1);
// Track durations for completed tasks
if (task.status === 'completed' && task.duration_minutes) {
if (!durationsByType.has(type)) durationsByType.set(type, []);
durationsByType.get(type).push(task.duration_minutes);
}
// Track success rates
if (!successByType.has(type)) successByType.set(type, { total: 0, successful: 0 });
successByType.get(type).total++;
if (task.status === 'completed') {
successByType.get(type).successful++;
}
});
// Calculate averages and rates
const metrics = {};
for (const [type, count] of tasksByType) {
metrics[type] = {
total_tasks: count,
average_duration_minutes: durationsByType.has(type) ?
durationsByType.get(type).reduce((a, b) => a + b, 0) / durationsByType.get(type).length : 0,
success_rate: successByType.get(type).successful / successByType.get(type).total
};
}
return metrics;
}
async generatePerformanceReport() {
const metrics = await this.getTaskMetrics('7d');
console.log('=== Background Agent Performance Report ===');
for (const [taskType, stats] of Object.entries(metrics)) {
console.log(`\n${taskType.toUpperCase()}:`);
console.log(` Total Tasks: ${stats.total_tasks}`);
console.log(` Average Duration: ${stats.average_duration_minutes.toFixed(1)} minutes`);
console.log(` Success Rate: ${(stats.success_rate * 100).toFixed(1)}%`);
}
}
}
// Usage
const monitor = new TaskPerformanceMonitor(process.env.CONTEXT_API_TOKEN);
await monitor.generatePerformanceReport();