How to define a task in CrewAI
Quick answer
To define a task in
CrewAI, you create a task object specifying its name, description, and input/output schema using the CrewAI SDK. This task can then be registered and executed within the CrewAI platform to automate workflows.PREREQUISITES
Python 3.8+CrewAI SDK installed via pipCrewAI API key set in environment variable CREWAI_API_KEY
Setup
Install the CrewAI SDK and set your API key as an environment variable to authenticate requests.
pip install crewai-sdk Step by step
Define a task by creating a Task object with a name, description, and input/output schema, then register it with the CrewAI client.
import os
from crewai_sdk import CrewAIClient, Task
# Initialize client with API key from environment
client = CrewAIClient(api_key=os.environ["CREWAI_API_KEY"])
# Define the task
my_task = Task(
name="SummarizeText",
description="Summarizes input text into a concise summary.",
inputs={"text": "string"},
outputs={"summary": "string"}
)
# Register the task
client.register_task(my_task)
# Example usage: execute the task
result = client.execute_task(
task_name="SummarizeText",
inputs={"text": "CrewAI helps automate AI workflows efficiently."}
)
print("Summary:", result["summary"]) output
Summary: CrewAI automates AI workflows efficiently.
Common variations
You can define tasks with different input/output types, use async execution, or switch to different CrewAI models by specifying parameters in the Task or execute_task methods.
import asyncio
async def run_async_task():
result = await client.execute_task_async(
task_name="SummarizeText",
inputs={"text": "Async execution example in CrewAI."}
)
print("Async Summary:", result["summary"])
asyncio.run(run_async_task()) output
Async Summary: Async execution example in CrewAI.
Troubleshooting
- If you get authentication errors, verify your
CREWAI_API_KEYenvironment variable is set correctly. - For schema validation errors, ensure your input/output types match the expected definitions in the
Task. - If task registration fails, check network connectivity and API endpoint availability.
Key Takeaways
- Use the CrewAI SDK to define tasks with clear input/output schemas.
- Always set your API key securely via environment variables.
- Leverage async task execution for improved performance in workflows.