Execute long-running agent tasks asynchronously with status tracking and result retrieval
Background Tasks enable agents to execute long-running operations asynchronously, allowing your application to remain responsive while complex work continues in the background.
The Background Tasks primitive allows agents to perform time-intensive operations without blocking your application. Instead of waiting for completion, you can initiate a background task, receive a task ID, and check status or retrieve results later.Background tasks are essential for:
Long-Running Operations: Multi-hour data processing, analysis, or generation tasks
Async Workflows: Decouple request initiation from result consumption
Batch Processing: Process large datasets without timeout constraints
Scheduled Jobs: Execute recurring agent tasks on a schedule
Resource-Intensive Tasks: Complex computations without blocking other operations
Non-Blocking Execution
Initiate tasks and continue without waiting for completion
Status Tracking
Monitor progress, check status, and receive notifications when complete
Reliable Completion
Tasks continue running even if client disconnects or crashes
Result Retrieval
Fetch results when ready, with full session context preserved
import { Agentbase } from '@agentbase/sdk';const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY});// Start long-running task in backgroundconst task = await agentbase.runAgent({ message: "Analyze all customer feedback from the past year and create comprehensive report", background: true // Run asynchronously});console.log('Task ID:', task.taskId);console.log('Status:', task.status); // 'queued' or 'running'// Continue with other work...// Task executes in background// Later, check statusconst status = await agentbase.getTaskStatus(task.taskId);console.log('Current status:', status.state);console.log('Progress:', status.progress);// When complete, get resultsif (status.state === 'completed') { const result = await agentbase.getTaskResult(task.taskId); console.log('Result:', result.message);}
from agentbase import Agentbaseimport timeagentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY'])# Start long-running task in backgroundtask = agentbase.run_agent( message="Analyze all customer feedback from the past year and create comprehensive report", background=True # Run asynchronously)print(f"Task ID: {task.task_id}")print(f"Status: {task.status}") # 'queued' or 'running'# Continue with other work...# Task executes in background# Later, check statusstatus = agentbase.get_task_status(task.task_id)print(f"Current status: {status.state}")print(f"Progress: {status.progress}")# When complete, get resultsif status.state == 'completed': result = agentbase.get_task_result(task.task_id) print(f"Result: {result.message}")
# Start background taskcurl -X POST https://api.agentbase.sh \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Analyze all customer feedback from the past year", "background": true }'# Response: { "taskId": "task_abc123", "status": "queued" }# Check statuscurl https://api.agentbase.sh/tasks/task_abc123 \ -H "Authorization: Bearer $AGENTBASE_API_KEY"# Get results when completecurl https://api.agentbase.sh/tasks/task_abc123/result \ -H "Authorization: Bearer $AGENTBASE_API_KEY"
// Process multiple items in backgroundasync function batchProcess(items: string[]): Promise<string[]> { // Start all tasks const tasks = await Promise.all( items.map(item => agentbase.runAgent({ message: `Process item: ${item}`, background: true }) ) ); console.log(`Started ${tasks.length} background tasks`); // Collect results as they complete const results = []; for (const task of tasks) { const result = await waitForTask(task.taskId); results.push(result); console.log(`Completed ${results.length}/${tasks.length}`); } return results;}// Process 100 items in parallelconst items = Array.from({ length: 100 }, (_, i) => `item-${i}`);const results = await batchProcess(items);
# Process multiple items in backgroundasync def batch_process(items: list) -> list: # Start all tasks tasks = await asyncio.gather(*[ agentbase.run_agent( message=f"Process item: {item}", background=True ) for item in items ]) print(f"Started {len(tasks)} background tasks") # Collect results as they complete results = [] for task in tasks: result = await wait_for_task(task.task_id) results.append(result) print(f"Completed {len(results)}/{len(tasks)}") return results# Process 100 items in parallelitems = [f"item-{i}" for i in range(100)]results = await batch_process(items)
// Good: Complete instructions with all contextconst task = await agentbase.runAgent({ message: ` Process dataset located at: s3://bucket/data.csv Credentials: Use IAM role arn:aws:iam::123:role/processor Output: Save results to s3://bucket/results/ Notification: Email team@company.com when complete `, background: true});// Avoid: Incomplete instructions requiring interactionconst bad = await agentbase.runAgent({ message: "Process the dataset", // Which dataset? Where? background: true});
// Design tasks with progress reportingconst task = await agentbase.runAgent({ message: ` Process 10,000 records. Report progress after every 1,000 records: - Log completion count - Update progress percentage - Report any errors encountered - Estimate time remaining `, background: true});
Implement Error Recovery
// Design for resilienceconst task = await agentbase.runAgent({ message: ` Process all files in directory. Error handling: - If file fails, log error and continue - Save progress after each file - If total errors exceed 10%, stop and report - Create summary of successful and failed files `, background: true});
Remember: Background tasks are perfect for operations that take more than a few seconds. Use webhooks for notifications and implement proper monitoring for production workloads.