Skip to main content

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()

BackgroundTaskHandle

The run_background() function returns a BackgroundTaskHandle with these methods:
MethodDescription
task_idUnique task identifier
recipe_nameName of the recipe being executed
session_idSession 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 started
  • running - Task is currently executing
  • completed - Task finished successfully
  • failed - Task failed with an error
  • cancelled - 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",
    verbose=True
)

# 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:
SettingDefaultDescription
timeout_sec300Maximum execution time (5 minutes)
max_concurrent5Maximum concurrent tasks
cleanup_delay_sec3600Time 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: 3600

Error 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

  1. Always set timeouts - Prevent tasks from running indefinitely
  2. Use session IDs - Track related tasks across executions
  3. Handle cancellation - Clean up resources when tasks are cancelled
  4. Monitor progress - Use status checks for long-running tasks
  5. Limit concurrency - Don’t overwhelm system resources

See Also