Skip to main content

@on_task Decorator

The @on_task decorator provides a simple way to register functions as event-driven task handlers for agent deployment and background task processing.

Overview

The @on_task decorator automatically:
  • Registers your function as a task handler
  • Sets up event listening for incoming task execution requests
  • Handles both synchronous and asynchronous functions
  • Validates that the decorated function has a task parameter
  • Works with default configuration from environment variables

Syntax

Parameters

The decorator itself takes no parameters, but the decorated function must:
  • Accept a task parameter as its first argument
  • Return the modified task object

Usage Examples

Basic Synchronous Handler

Asynchronous Handler

Task Processing with Error Handling

Processing Different Input Types

Using Optional Internal Status for Context Information

Using Internal Status with Explicit Saving

Behavior

Automatic Event Listening

When you use the @on_task decorator, it automatically:
  1. Sets up event listening for your agent
  2. Waits for incoming task execution requests
  3. Calls your decorated function when tasks arrive
  4. Handles the task lifecycle (status updates, result saving)

Function Requirements

Your decorated function must:
  • Accept a task parameter
  • Return the modified task object
  • Handle any exceptions internally (recommended)

Configuration

The decorator uses:
  • Environment variables for SDK configuration (XPANDER_API_KEY, XPANDER_ORGANIZATION_ID, etc.)
  • Default agent ID from XPANDER_AGENT_ID environment variable

Task Object Properties

The task parameter passed to your function contains:

Best Practices

1. Always Return the Task

2. Handle Errors Gracefully

3. Set Appropriate Status

4. Validate Input

5. Use Internal Status Optionally for Context Information

  • [AgentExecutionStatus](/API reference/types#agentexecutionstatus): Task execution statuses
  • [AgentExecutionInput](/API reference/types#agentexecutioninput): Task input structure
  • [OutputFormat](/API reference/types#outputformat): Output format options
  • [Events Module](/API reference/events): Full events module documentation
  • [Tasks Module](/API reference/tasks): Task management and execution
  • [Agents Module](/API reference/agents): Agent creation and management