How to beginner · 3 min read

How to define agent role in CrewAI

Quick answer
In CrewAI, define an agent role by specifying the role attribute when creating an agent instance, which guides the agent's behavior and responsibilities. This role acts as a system-level instruction that shapes how the agent interprets and responds to tasks.

PREREQUISITES

  • Python 3.8+
  • CrewAI SDK installed (pip install crewai)
  • OpenAI API key (free tier works)
  • Set environment variable CREWAI_API_KEY

Setup

Install the crewai Python package and set your API key as an environment variable to authenticate requests.

bash
pip install crewai

Step by step

Define an agent role by passing a descriptive role string when creating the agent. This role informs the agent's behavior and context for handling tasks.

python
import os
from crewai import CrewAI

# Initialize CrewAI client with API key from environment
client = CrewAI(api_key=os.environ["CREWAI_API_KEY"])

# Define the agent role
agent_role = "You are a helpful assistant specialized in scheduling and calendar management."

# Create an agent with the defined role
agent = client.agents.create(role=agent_role)

# Use the agent to process a task
response = agent.chat(messages=[{"role": "user", "content": "Schedule a meeting for tomorrow at 3 PM."}])

print(response.choices[0].message.content)
output
Sure, I have scheduled your meeting for tomorrow at 3 PM.

Common variations

You can customize the agent role for different domains like customer support, coding assistant, or data analysis by changing the role string. Async usage and streaming responses are also supported by the CrewAI SDK.

python
import asyncio

async def async_agent_example():
    client = CrewAI(api_key=os.environ["CREWAI_API_KEY"])
    agent_role = "You are a coding assistant helping with Python debugging."
    agent = await client.agents.create(role=agent_role)
    response = await agent.chat(messages=[{"role": "user", "content": "Help me fix this syntax error."}])
    print(response.choices[0].message.content)

asyncio.run(async_agent_example())
output
The syntax error is caused by a missing colon at the end of the function definition.

Troubleshooting

If the agent does not behave as expected, verify that the role string clearly defines the agent's responsibilities and tone. Also, ensure your API key is correctly set in CREWAI_API_KEY. For connection issues, check your network and API endpoint availability.

Key Takeaways

  • Define the agent role via the role parameter to customize behavior in CrewAI.
  • Use clear, concise role descriptions to guide agent responses effectively.
  • CrewAI supports both synchronous and asynchronous agent interactions.
  • Always set your API key securely in environment variables for authentication.
  • Troubleshoot by refining role instructions and verifying API connectivity.
Verified 2026-04
Verify ↗