Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Tasks and Handlers

What are Tasks?

In CrewAI, tasks are discrete units of work that can be executed by the system. They represent actions or operations that need to be performed, such as processing data, fetching information, or executing commands. Tasks are essential building blocks in developing efficient and scalable applications.

What are Handlers?

Handlers are specialized functions or methods that are responsible for managing and executing tasks. They define the logic for processing tasks and ensuring that they are executed correctly. Handlers can be considered as the "brains" behind tasks, providing the necessary instructions and control flow.

Creating a Task

To create a task in CrewAI, you need to define the task's properties and the actions it will perform. Here's an example of how to create a simple task:

task = {
    'id': 'task1',
    'description': 'Process data',
    'action': 'process_data'
}
                

In this example, we define a task with an ID of 'task1', a description of 'Process data', and an action 'process_data'.

Creating a Handler

Handlers are created to manage and execute tasks. Here's an example of how to create a handler for the task defined above:

def process_data_handler(task):
    print(f"Processing task: {task['id']} - {task['description']}")
    # Implement the logic to process data here

# Register the handler
handlers = {
    'process_data': process_data_handler
}
                

In this example, we define a function process_data_handler that takes a task as an argument and prints a message indicating that the task is being processed. We then register this handler in a dictionary with the key 'process_data', which corresponds to the action defined in the task.

Executing a Task

To execute a task, you need to invoke the corresponding handler. Here's an example of how to execute the task using the handler:

task = {
    'id': 'task1',
    'description': 'Process data',
    'action': 'process_data'
}

# Retrieve the handler for the task's action
handler = handlers.get(task['action'])

# Execute the handler if it exists
if handler:
    handler(task)
else:
    print(f"No handler found for action: {task['action']}")
                

In this example, we retrieve the handler for the task's action using the handlers dictionary. If the handler exists, we execute it by passing the task as an argument. If no handler is found, we print an error message.

Conclusion

In this tutorial, we've introduced the concepts of tasks and handlers in CrewAI. Tasks represent discrete units of work, while handlers are responsible for managing and executing these tasks. By defining and registering handlers, you can create a flexible and scalable system for processing various tasks.

We hope this tutorial has provided a clear understanding of tasks and handlers and how to implement them in CrewAI. Happy coding!