Background Tasks
Run recipes and agents as background tasks with progress tracking
Background Tasks
Background tasks allow you to run recipes and agents asynchronously without blocking your main application. Tasks run in the background with full progress tracking, cancellation support, and result retrieval.
Python API
Running a Recipe in Background
from praisonai import recipe
# Submit recipe as background task
task = recipe.run_background(
"my-recipe",
input={"query": "What is AI?"},
config={"max_tokens": 1000},
session_id="session_123",
timeout_sec=300,
)
print(f"Task ID: {task.task_id}")
print(f"Session: {task.session_id}")
# Check status
status = await task.status()
print(f"Status: {status}")
# Wait for completion
result = await task.wait(timeout=600)
print(f"Result: {result}")
# Cancel if needed
await task.cancel()Async callers (FastAPI / Jupyter)
arun_background is the async-native form. Use it from any running event loop — the sync run_background raises RuntimeError there instead of deadlocking. Both share the same signature (name, input, config, session_id, timeout_sec, max_concurrent, on_complete):
from praisonai import recipe
async def handler():
task = await recipe.arun_background(
"my-recipe",
input={"query": "What is AI?"},
config={"max_tokens": 1000},
)
return await task.wait()BackgroundTaskHandle
The run_background() function returns a BackgroundTaskHandle with these methods:
| Method | Description |
|---|---|
task_id | Unique task identifier |
recipe_name | Name of the recipe being executed |
session_id | Session ID for conversation continuity |
status() | Get current task status (async) |
wait(timeout) | Wait for completion and return result (async) |
cancel() | Cancel the running task (async) |
Task Status Values
pending– Task is queued but not startedrunning– Task is currently executingcompleted– Task finished successfullyfailed– Task failed with an errorcancelled– Task was cancelled
Using with Agents Directly
from praisonaiagents import Agent
from praisonaiagents.background import BackgroundRunner
# Create agent
agent = Agent(
instructions="You are a helpful assistant",
)
# Create background runner
runner = BackgroundRunner(max_concurrent_tasks=5)
# Submit task
task = await runner.submit(
lambda: agent.start("Analyze this data"),
name="analysis-task",
timeout=300,
)
# Wait for result
result = await runner.wait_for_task(task.id)Configuration
Safe Defaults
Background tasks use safe defaults to prevent runaway execution:
| Setting | Default | Description |
|---|---|---|
timeout_sec | 300 | Maximum execution time (5 minutes) |
max_concurrent | 5 | Maximum concurrent tasks |
cleanup_delay_sec | 3600 | Time before completed tasks are cleaned up |
TEMPLATE.yaml Runtime Block
Configure background task defaults in your recipe’s TEMPLATE.yaml:
runtime:
background:
enabled: true
max_concurrent: 3
cleanup_delay_sec: 3600Error Handling
from praisonai import recipe
from praisonai.recipe import RecipeError
try:
task = recipe.run_background("my-recipe", input="test")
result = await task.wait(timeout=60)
except RecipeError as e:
print(f"Recipe error: {e}")
except TimeoutError:
print("Task timed out")
await task.cancel()Best Practices
- Always set timeouts – Prevent tasks from running indefinitely
- Use session IDs – Track related tasks across executions
- Handle cancellation – Clean up resources when tasks are cancelled
- Monitor progress – Use status checks for long-running tasks
- Limit concurrency – Don’t overwhelm system resources
See Also
- Background Tasks CLI – CLI commands for background tasks
- Async Jobs – Server-based job execution
- Scheduler – Periodic task scheduling