How to pass context between tasks in CrewAI
Quick answer
In
CrewAI, pass context between tasks by storing relevant data in the shared context object, which is accessible across tasks. Update this context dictionary with outputs or variables from one task to be used as inputs in subsequent tasks, enabling seamless state management.PREREQUISITES
Python 3.8+CrewAI SDK installed (pip install crewai)API key or environment setup for CrewAI
Setup
Install the crewai Python package and set your API key as an environment variable to authenticate your requests.
pip install crewai Step by step
This example demonstrates passing context between two tasks in a CrewAI workflow. The first task generates a greeting, and the second task uses that greeting from the shared context.
import os
from crewai import CrewAI, Task
# Initialize CrewAI client
client = CrewAI(api_key=os.environ["CREWAI_API_KEY"])
# Define first task: generate greeting
class GreetingTask(Task):
def run(self, context):
context['greeting'] = "Hello from CrewAI!"
return context['greeting']
# Define second task: use greeting from context
class UseGreetingTask(Task):
def run(self, context):
greeting = context.get('greeting', 'No greeting found')
return f"Received message: {greeting}"
# Create workflow and add tasks
workflow = client.create_workflow(name="ContextPassingWorkflow")
workflow.add_task(GreetingTask())
workflow.add_task(UseGreetingTask())
# Run workflow
result = workflow.run()
print(result) output
Received message: Hello from CrewAI!
Common variations
You can pass complex data structures like dictionaries or lists in the context object. For asynchronous workflows, ensure tasks await context updates properly. Different CrewAI SDK versions may have slight API differences, so always check the latest docs.
import asyncio
class AsyncGreetingTask(Task):
async def run(self, context):
await asyncio.sleep(1) # simulate async operation
context['greeting'] = "Hello asynchronously!"
return context['greeting'] Troubleshooting
- If context data is missing in a task, verify that previous tasks correctly updated the
contextdictionary. - Ensure tasks run sequentially if they depend on context from prior tasks.
- Check for typos in context keys to avoid key errors.
Key Takeaways
- Use the shared
contextdictionary to pass data between CrewAI tasks. - Update
contextin one task to make data available for subsequent tasks. - For async tasks, handle context updates with proper async/await syntax.
- Always verify task execution order to maintain context integrity.
- Check CrewAI SDK docs for any API changes affecting context handling.