How to run a crew in CrewAI
Quick answer
To run a crew in
CrewAI, you instantiate a Crew object with your agents, then call its run() method to execute the coordinated tasks. This manages multiple AI agents working together on complex workflows using simple Python code.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install crewai>=0.1
Setup
Install the crewai Python package and set your OpenAI API key as an environment variable.
- Run
pip install crewai>=0.1to install. - Set your API key in your shell:
export OPENAI_API_KEY='your_api_key'(Linux/macOS) orsetx OPENAI_API_KEY "your_api_key"(Windows).
pip install crewai>=0.1 Step by step
This example creates two simple agents and runs them as a crew to complete a task collaboratively.
import os
from crewai import Crew, Agent
# Define two simple agents
class AgentA(Agent):
def run(self, input_text):
return f"AgentA processed: {input_text}"
class AgentB(Agent):
def run(self, input_text):
return f"AgentB enhanced: {input_text.upper()}"
# Instantiate the crew with the agents
crew = Crew(agents=[AgentA(), AgentB()])
# Run the crew with an input
result = crew.run("Hello CrewAI")
print(result) output
['AgentA processed: Hello CrewAI', 'AgentB enhanced: HELLO CREWAI']
Common variations
You can run crews asynchronously, use different AI models per agent, or stream outputs for real-time interaction.
import asyncio
from crewai import Crew, Agent
class AsyncAgent(Agent):
async def run(self, input_text):
await asyncio.sleep(1) # simulate async work
return f"AsyncAgent got: {input_text}"
async def main():
crew = Crew(agents=[AsyncAgent()])
result = await crew.run_async("Async input")
print(result)
asyncio.run(main()) output
['AsyncAgent got: Async input']
Troubleshooting
If you see errors about missing API keys, ensure OPENAI_API_KEY is set in your environment. For timeout errors, increase agent timeout settings or check network connectivity.
Key Takeaways
- Use the
Crewclass to coordinate multiple agents easily in CrewAI. - Define agents by subclassing
Agentand implementing therun()method. - Run crews synchronously or asynchronously depending on your workflow needs.
- Always set your OpenAI API key in the environment to avoid authentication errors.
- CrewAI supports flexible agent orchestration for complex multi-agent AI workflows.