Skip to main content

Overview of an Agent

In the CrewAI framework, an Agent is an autonomous unit that can:
  • Perform specific tasks
  • Make decisions based on its role and goal
  • Use tools to accomplish objectives
  • Communicate and collaborate with other agents
  • Maintain memory of interactions
  • Delegate tasks when allowed
Think of an agent as a specialized team member with specific skills, expertise, and responsibilities. For example, a Researcher agent might excel at gathering and analyzing information, while a Writer agent might be better at creating content.
CrewAI AMP includes a Visual Agent Builder that simplifies agent creation and configuration without writing code. Design your agents visually and test them in real-time.Visual Agent Builder ScreenshotThe Visual Agent Builder enables:
  • Intuitive agent configuration with form-based interfaces
  • Real-time testing and validation
  • Template library with pre-configured agent types
  • Easy customization of agent attributes and behaviors

Agent Attributes

AttributeParameterTypeDescription
RolerolestrDefines the agent’s function and expertise within the crew.
GoalgoalstrThe individual objective that guides the agent’s decision-making.
BackstorybackstorystrProvides context and personality to the agent, enriching interactions.
LLM (optional)llmUnion[str, LLM, Any]Language model that powers the agent. Defaults to the model specified in OPENAI_MODEL_NAME or “gpt-4”.
Tools (optional)toolsList[BaseTool]Capabilities or functions available to the agent. Defaults to an empty list.
Function Calling LLM (optional)function_calling_llmOptional[Any]Language model for tool calling, overrides crew’s LLM if specified.
Max Iterations (optional)max_iterintMaximum iterations before the agent must provide its best answer. Default is 20.
Max RPM (optional)max_rpmOptional[int]Maximum requests per minute to avoid rate limits.
Max Execution Time (optional)max_execution_timeOptional[int]Maximum time (in seconds) for task execution.
Verbose (optional)verboseboolEnable detailed execution logs for debugging. Default is False.
Allow Delegation (optional)allow_delegationboolAllow the agent to delegate tasks to other agents. Default is False.
Step Callback (optional)step_callbackOptional[Any]Function called after each agent step, overrides crew callback.
Cache (optional)cacheboolEnable caching for tool usage. Default is True.
System Template (optional)system_templateOptional[str]Custom system prompt template for the agent.
Prompt Template (optional)prompt_templateOptional[str]Custom prompt template for the agent.
Response Template (optional)response_templateOptional[str]Custom response template for the agent.
Allow Code Execution (optional)allow_code_executionOptional[bool]Enable code execution for the agent. Default is False.
Max Retry Limit (optional)max_retry_limitintMaximum number of retries when an error occurs. Default is 2.
Respect Context Window (optional)respect_context_windowboolKeep messages under context window size by summarizing. Default is True.
Code Execution Mode (optional)code_execution_modeLiteral["safe", "unsafe"]Mode for code execution: ‘safe’ (using Docker) or ‘unsafe’ (direct). Default is ‘safe’.
Multimodal (optional)multimodalboolWhether the agent supports multimodal capabilities. Default is False.
Inject Date (optional)inject_dateboolWhether to automatically inject the current date into tasks. Default is False.
Date Format (optional)date_formatstrFormat string for date when inject_date is enabled. Default is “%Y-%m-%d” (ISO format).
Reasoning (optional)reasoningboolWhether the agent should reflect and create a plan before executing a task. Default is False.
Max Reasoning Attempts (optional)max_reasoning_attemptsOptional[int]Maximum number of reasoning attempts before executing the task. If None, will try until ready.
Embedder (optional)embedderOptional[Dict[str, Any]]Configuration for the embedder used by the agent.
Knowledge Sources (optional)knowledge_sourcesOptional[List[BaseKnowledgeSource]]Knowledge sources available to the agent.
Use System Prompt (optional)use_system_promptOptional[bool]Whether to use system prompt (for o1 model support). Default is True.

Creating Agents

There are two common ways to create agents in CrewAI: using JSONC project configuration (recommended for new crews) or defining them directly in code. New projects created with crewai create crew <name> use JSON-first configuration. Each agent is defined in agents/<agent_name>.jsonc, and crew.jsonc lists which agents are part of the crew. After creating your CrewAI project as outlined in the Installation section, edit the generated files in agents/.
Use {placeholder} values in role, goal, or backstory. Put defaults in crew.jsonc under inputs; crewai run prompts for any missing values.
Here’s an example agents/researcher.jsonc file:
agents/researcher.jsonc
Then include that agent from crew.jsonc:
crew.jsonc
Agent files support any public Agent field. Common fields include role, goal, backstory, llm, tools, function_calling_llm, guardrail, step_callback, and settings. Behavior options such as verbose, allow_delegation, max_iter, max_rpm, memory, cache, planning_config, and use_system_prompt can be placed at the top level or under settings; values in settings take precedence.
JSONC supports comments and trailing commas. If both agents/<name>.jsonc and agents/<name>.json exist, CrewAI uses the JSONC file.

Classic YAML Configuration

Classic projects created with crewai create crew <name> --classic use config/agents.yaml and a @CrewBase class in crew.py. This remains supported for teams that want Python decorators or existing YAML projects.

Direct Code Definition

You can create agents directly in code by instantiating the Agent class. Here’s a comprehensive example showing all available parameters:
Code
Let’s break down some key parameter combinations for common use cases:

Basic Research Agent

Code

Code Development Agent

Code

Long-Running Analysis Agent

Code

Custom Template Agent

Code

Date-Aware Agent with Reasoning

Code

Reasoning Agent

Code

Multimodal Agent

Code

Parameter Details

Critical Parameters

  • role, goal, and backstory are required and shape the agent’s behavior
  • llm determines the language model used (default: OpenAI’s GPT-4)

Memory and Context

  • memory: Enable to maintain conversation history
  • respect_context_window: Prevents token limit issues
  • knowledge_sources: Add domain-specific knowledge bases

Execution Control

  • max_iter: Maximum attempts before giving best answer
  • max_execution_time: Timeout in seconds
  • max_rpm: Rate limiting for API calls
  • max_retry_limit: Retries on error

Code Execution

allow_code_execution and code_execution_mode are deprecated. CodeInterpreterTool has been removed from crewai-tools. Use a dedicated sandbox service such as E2B or Modal for secure code execution.
  • allow_code_execution (deprecated): Previously enabled built-in code execution via CodeInterpreterTool.
  • code_execution_mode (deprecated): Previously controlled execution mode ("safe" for Docker, "unsafe" for direct execution).

Advanced Features

  • multimodal: Enable multimodal capabilities for processing text and visual content
  • reasoning: Enable agent to reflect and create plans before executing tasks
  • inject_date: Automatically inject current date into task descriptions

Templates

  • system_template: Defines agent’s core behavior
  • prompt_template: Structures input format
  • response_template: Formats agent responses
When using custom templates, ensure that both system_template and prompt_template are defined. The response_template is optional but recommended for consistent output formatting.
When using custom templates, you can use variables like {role}, {goal}, and {backstory} in your templates. These will be automatically populated during execution.

Agent Tools

Agents can be equipped with various tools to enhance their capabilities. CrewAI supports tools from: Here’s how to add tools to an agent:
Code

Agent Memory and Context

Agents can maintain memory of their interactions and use context from previous tasks. This is particularly useful for complex workflows where information needs to be retained across multiple tasks.
Code
When memory is enabled, the agent will maintain context across multiple interactions, improving its ability to handle complex, multi-step tasks.

Context Window Management

CrewAI includes sophisticated automatic context window management to handle situations where conversations exceed the language model’s token limits. This powerful feature is controlled by the respect_context_window parameter.

How Context Window Management Works

When an agent’s conversation history grows too large for the LLM’s context window, CrewAI automatically detects this situation and can either:
  1. Automatically summarize content (when respect_context_window=True)
  2. Stop execution with an error (when respect_context_window=False)

Automatic Context Handling (respect_context_window=True)

This is the default and recommended setting for most use cases. When enabled, CrewAI will:
Code
What happens when context limits are exceeded:
  • ⚠️ Warning message: "Context length exceeded. Summarizing content to fit the model context window."
  • 🔄 Automatic summarization: CrewAI intelligently summarizes the conversation history
  • Continued execution: Task execution continues seamlessly with the summarized context
  • 📝 Preserved information: Key information is retained while reducing token count

Strict Context Limits (respect_context_window=False)

When you need precise control and prefer execution to stop rather than lose any information:
Code
What happens when context limits are exceeded:
  • Error message: "Context length exceeded. Consider using smaller text or RAG tools from crewai_tools."
  • 🛑 Execution stops: Task execution halts immediately
  • 🔧 Manual intervention required: You need to modify your approach

Choosing the Right Setting

Use respect_context_window=True (Default) when:

  • Processing large documents that might exceed context limits
  • Long-running conversations where some summarization is acceptable
  • Research tasks where general context is more important than exact details
  • Prototyping and development where you want robust execution
Code

Use respect_context_window=False when:

  • Precision is critical and information loss is unacceptable
  • Legal or medical tasks requiring complete context
  • Code review where missing details could introduce bugs
  • Financial analysis where accuracy is paramount
Code

Alternative Approaches for Large Data

When dealing with very large datasets, consider these strategies:

1. Use RAG Tools

Code

2. Use Knowledge Sources

Code

Context Window Best Practices

  1. Monitor Context Usage: Enable verbose=True to see context management in action
  2. Design for Efficiency: Structure tasks to minimize context accumulation
  3. Use Appropriate Models: Choose LLMs with context windows suitable for your tasks
  4. Test Both Settings: Try both True and False to see which works better for your use case
  5. Combine with RAG: Use RAG tools for very large datasets instead of relying solely on context windows

Troubleshooting Context Issues

If you’re getting context limit errors:
Code
If automatic summarization loses important information:
Code
The context window management feature works automatically in the background. You don’t need to call any special functions - just set respect_context_window to your preferred behavior and CrewAI handles the rest!

Direct Agent Interaction with kickoff()

Agents can be used directly without going through a task or crew workflow using the kickoff() method. This provides a simpler way to interact with an agent when you don’t need the full crew orchestration capabilities.

How kickoff() Works

The kickoff() method allows you to send messages directly to an agent and get a response, similar to how you would interact with an LLM but with all the agent’s capabilities (tools, reasoning, etc.).
Code

Parameters and Return Values

ParameterTypeDescription
messagesUnion[str, List[Dict[str, str]]]Either a string query or a list of message dictionaries with role/content
response_formatOptional[Type[Any]]Optional Pydantic model for structured output
The method returns a LiteAgentOutput object with the following properties:
  • raw: String containing the raw output text
  • pydantic: Parsed Pydantic model (if a response_format was provided)
  • agent_role: Role of the agent that produced the output
  • usage_metrics: Token usage metrics for the execution

Structured Output

You can get structured output by providing a Pydantic model as the response_format:
Code

Multiple Messages

You can also provide a conversation history as a list of message dictionaries:
Code

Async Support

An asynchronous version is available via kickoff_async() with the same parameters:
Code
The kickoff() method uses a LiteAgent internally, which provides a simpler execution flow while preserving all of the agent’s configuration (role, goal, backstory, tools, etc.).

Important Considerations and Best Practices

Security and Code Execution

allow_code_execution and code_execution_mode are deprecated and CodeInterpreterTool has been removed. Use a dedicated sandbox service such as E2B or Modal for secure code execution.

Performance Optimization

  • Use respect_context_window: true to prevent token limit issues
  • Set appropriate max_rpm to avoid rate limiting
  • Enable cache: true to improve performance for repetitive tasks
  • Adjust max_iter and max_retry_limit based on task complexity

Memory and Context Management

  • Leverage knowledge_sources for domain-specific information
  • Configure embedder when using custom embedding models
  • Use custom templates (system_template, prompt_template, response_template) for fine-grained control over agent behavior

Advanced Features

  • Enable reasoning: true for agents that need to plan and reflect before executing complex tasks
  • Set appropriate max_reasoning_attempts to control planning iterations (None for unlimited attempts)
  • Use inject_date: true to provide agents with current date awareness for time-sensitive tasks
  • Customize the date format with date_format using standard Python datetime format codes
  • Enable multimodal: true for agents that need to process both text and visual content

Agent Collaboration

  • Enable allow_delegation: true when agents need to work together
  • Use step_callback to monitor and log agent interactions
  • Consider using different LLMs for different purposes:
    • Main llm for complex reasoning
    • function_calling_llm for efficient tool usage

Date Awareness and Reasoning

  • Use inject_date: true to provide agents with current date awareness for time-sensitive tasks
  • Customize the date format with date_format using standard Python datetime format codes
  • Valid format codes include: %Y (year), %m (month), %d (day), %B (full month name), etc.
  • Invalid date formats will be logged as warnings and will not modify the task description
  • Enable reasoning: true for complex tasks that benefit from upfront planning and reflection

Model Compatibility

  • Set use_system_prompt: false for older models that don’t support system messages
  • Ensure your chosen llm supports the features you need (like function calling)

Troubleshooting Common Issues

  1. Rate Limiting: If you’re hitting API rate limits:
    • Implement appropriate max_rpm
    • Use caching for repetitive operations
    • Consider batching requests
  2. Context Window Errors: If you’re exceeding context limits:
    • Enable respect_context_window
    • Use more efficient prompts
    • Clear agent memory periodically
  3. Code Execution Issues: If code execution fails:
    • Verify Docker is installed for safe mode
    • Check execution permissions
    • Review code sandbox settings
  4. Memory Issues: If agent responses seem inconsistent:
    • Check knowledge source configuration
    • Review conversation history management
Remember that agents are most effective when configured according to their specific use case. Take time to understand your requirements and adjust these parameters accordingly.