---
title: Reasoning
description: "Learn how to enable and use agent reasoning to improve task execution."
icon: brain
---

## Overview

Agent reasoning is a feature that allows agents to reflect on a task and create a plan before and during execution. This helps agents approach tasks more methodically and adapt their strategy as they progress through complex tasks.

## Usage

To enable reasoning for an agent, set `reasoning=True` when creating the agent:

```python
from crewai import Agent

agent = Agent(
    role="Data Analyst",
    goal="Analyze complex datasets and provide insights",
    backstory="You are an experienced data analyst with expertise in finding patterns in complex data.",
    reasoning=True,  # Enable basic reasoning
    max_reasoning_attempts=3  # Optional: Set a maximum number of reasoning attempts
)
```

### Interval-based Reasoning

To enable periodic reasoning during task execution, set `reasoning_interval` to specify how often the agent should re-evaluate its plan:

```python
agent = Agent(
    role="Research Analyst",
    goal="Find comprehensive information about a topic",
    backstory="You are a skilled research analyst who methodically approaches information gathering.",
    reasoning=True,
    reasoning_interval=3,  # Re-evaluate plan every 3 steps
)
```

### Adaptive Reasoning

For more dynamic reasoning that adapts to the execution context, enable `adaptive_reasoning`:

```python
agent = Agent(
    role="Strategic Advisor",
    goal="Provide strategic advice based on market research",
    backstory="You are an experienced strategic advisor who adapts your approach based on the information you discover.",
    reasoning=True,
    adaptive_reasoning=True,  # Agent decides when to reason based on context
)
```

## How It Works

### Initial Reasoning

When reasoning is enabled, before executing a task, the agent will:

1. Reflect on the task and create a detailed plan
2. Evaluate whether it's ready to execute the task
3. Refine the plan as necessary until it's ready or max_reasoning_attempts is reached
4. Inject the reasoning plan into the task description before execution

### Mid-execution Reasoning

During task execution, the agent can re-evaluate and adjust its plan based on:

1. **Interval-based reasoning**: The agent reasons after a fixed number of steps (specified by `reasoning_interval`)
2. **Adaptive reasoning**: The agent decides when to reason based on execution context:
   - When multiple different tools are used recently (indicating a change in approach)
   - When the task is taking longer than expected (iterations > max_iter/2)
   - When recent errors or failures are detected in the execution

This mid-execution reasoning helps agents adapt to new information, overcome obstacles, and optimize their approach as they work through complex tasks.

## Configuration Options

<ParamField body="reasoning" type="bool" default="False"> 
    Enable or disable reasoning 
</ParamField>

<ParamField body="max_reasoning_attempts" type="int" default="None"> 
    Maximum number of attempts to refine the plan before proceeding with execution. If None (default), the agent will continue refining until it's ready. 
</ParamField>

<ParamField body="reasoning_interval" type="int" default="None"> 
    Interval of steps after which the agent should reason again during execution. If None, reasoning only happens before execution.
</ParamField>

<ParamField body="adaptive_reasoning" type="bool" default="False"> 
    Whether the agent should adaptively decide when to reason during execution based on context.
</ParamField>

## Technical Implementation

### Interval-based Reasoning

The interval-based reasoning feature works by:

1. Tracking the number of steps since the last reasoning event
2. Triggering reasoning when `steps_since_reasoning >= reasoning_interval`
3. Resetting the counter after each reasoning event
4. Generating an updated plan based on current progress

This creates a predictable pattern of reflection during task execution, which is useful for complex tasks where periodic reassessment is beneficial.

### Adaptive Reasoning

The adaptive reasoning feature uses LLM function calling to determine when reasoning should occur:

1. **LLM-based decision**: The agent's LLM evaluates the current execution context (task description, expected output, steps taken so far) to decide if reasoning is needed
2. **Error detection fallback**: When recent messages contain error indicators like "error", "exception", "failed", etc., reasoning is automatically triggered

This creates an intelligent reasoning pattern where the agent uses its own judgment to determine when strategic reassessment would be most beneficial, while maintaining automatic error recovery.

### Mid-execution Reasoning Process

When mid-execution reasoning is triggered, the agent:

1. Summarizes current progress (steps taken, tools used, recent actions)
2. Evaluates the effectiveness of the current approach
3. Adjusts the plan based on new information and challenges encountered
4. Continues execution with the updated plan

## Error Handling

The reasoning process is designed to be robust, with error handling built in. If an error occurs during reasoning, the agent will proceed with executing the task without the reasoning plan. This ensures that tasks can still be executed even if the reasoning process fails.

Here's how to handle potential errors in your code:

```python
from crewai import Agent, Task
import logging

# Set up logging to capture any reasoning errors
logging.basicConfig(level=logging.INFO)

# Create an agent with reasoning enabled
agent = Agent(
    role="Data Analyst",
    goal="Analyze data and provide insights",
    reasoning=True,
    reasoning_interval=5  # Re-evaluate plan every 5 steps
)

# Create a task
task = Task(
    description="Analyze the provided sales data and identify key trends.",
    expected_output="A report highlighting the top 3 sales trends.",
    agent=agent
)

# Execute the task
# If an error occurs during reasoning, it will be logged and execution will continue
result = agent.execute_task(task)
```

## Example Reasoning Output

Here's an example of what a reasoning plan might look like for a data analysis task:

```
Task: Analyze the provided sales data and identify key trends.

Reasoning Plan:
I'll analyze the sales data to identify the top 3 trends.

1. Understanding of the task:
   I need to analyze sales data to identify key trends that would be valuable for business decision-making.

2. Key steps I'll take:
   - First, I'll examine the data structure to understand what fields are available
   - Then I'll perform exploratory data analysis to identify patterns
   - Next, I'll analyze sales by time periods to identify temporal trends
   - I'll also analyze sales by product categories and customer segments
   - Finally, I'll identify the top 3 most significant trends

3. Approach to challenges:
   - If the data has missing values, I'll decide whether to fill or filter them
   - If the data has outliers, I'll investigate whether they're valid data points or errors
   - If trends aren't immediately obvious, I'll apply statistical methods to uncover patterns

4. Use of available tools:
   - I'll use data analysis tools to explore and visualize the data
   - I'll use statistical tools to identify significant patterns
   - I'll use knowledge retrieval to access relevant information about sales analysis

5. Expected outcome:
   A concise report highlighting the top 3 sales trends with supporting evidence from the data.

READY: I am ready to execute the task.
```

During execution, the agent might generate an updated plan:

```
Based on progress so far (3 steps completed):

Updated Reasoning Plan:
After examining the data structure and initial exploratory analysis, I need to adjust my approach:

1. Current findings:
   - The data shows seasonal patterns that need deeper investigation
   - Customer segments show varying purchasing behaviors
   - There are outliers in the luxury product category

2. Adjusted approach:
   - Focus more on seasonal analysis with year-over-year comparisons
   - Segment analysis by both demographics and purchasing frequency
   - Investigate the luxury product category anomalies

3. Next steps:
   - Apply time series analysis to better quantify seasonal patterns
   - Create customer cohorts for more precise segmentation
   - Perform statistical tests on the luxury category data

4. Expected outcome:
   Still on track to deliver the top 3 sales trends, but with more precise quantification and actionable insights.

READY: I am ready to continue executing the task.
```

This mid-execution reasoning helps the agent adapt its approach based on what it has learned during the initial steps of the task.
