Background Tasks Agent
This example demonstrates how to implement background processing in your agent functions. Background tasks allow you to perform time-consuming operations like data processing, API calls, or complex calculations without blocking the main conversation flow. Users can continue talking naturally while work happens behind the scenes.
Features
- Demonstrates how to run long-running tasks in the background without blocking the main conversation
- Shows how to use context.create_task() to spawn background processes
- Illustrates proper task management and state tracking across background operations
- Demonstrates automatic task restart when previous tasks complete
- Shows how to maintain conversation flow while processing happens asynchronously
Code Example
# In background task
import asyncio
import time
import random
async def background_task(context: Context):
yield LogEvent("Processing background task...")
# Set initial state
context.set_data("task_completed", False)
# Do work...
await asyncio.sleep(random.random() * 10)
# Update state
context.set_data("task_completed", True)
context.set_data("completion_time", time.time())
yield LogEvent("Background task done")
async def handler(event: Event, context: Context):
if isinstance(event, StartEvent):
yield TextToSpeechEvent(
text="Hello! I'll start processing your data in the background.",
voice="brooke"
)
context.create_task(background_task(context))
if isinstance(event, TextEvent):
user_message = event.data.get("text", "").lower()
if context.get_data("task_completed", False):
completion_seconds_ago = int(time.time() - context.get_data("completion_time", 0))
yield TextToSpeechEvent(
text=f"The data is done processing. Completion was {completion_seconds_ago} seconds ago.",
voice="brooke"
)
yield TextToSpeechEvent(
text="Starting new task...",
voice="brooke"
)
context.create_task(background_task(context))
else:
yield TextToSpeechEvent(
text="The data is still processing.",
voice="brooke"
)How It Works
Background Task Definition
The background_task function is defined as an async generator that yields LogEvent. It's designed to run independently without blocking the main conversation flow. The function simulates work with random sleep times and tracks completion state.
Task Creation with context.create_task()
When the conversation starts, the handler calls context.create_task(background_task(context)) to spawn the background task. This immediately returns control to the main conversation while the background task runs asynchronously.
Non-Blocking Conversation Flow
The main conversation continues immediately after launching the background task. The agent can respond to user input, handle other requests, and maintain natural conversation flow while background processing happens simultaneously.
State Management Across Tasks
The background task uses context.set_data() to track task completion status and completion time. The main handler checks this state with context.get_data() to provide appropriate responses based on whether the task is still running or completed.
Task Restart Logic
When a task completes, the handler automatically starts a new background task. This demonstrates how to chain background operations and maintain continuous processing while keeping the conversation responsive.
Background tasks are essential for creating responsive, professional agents that can handle complex workflows while maintaining natural conversation flow. Use them for any operation that might take more than a few seconds to complete.