> ## Documentation Index
> Fetch the complete documentation index at: https://docs.upsonic.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Adding Reasoning

> Enable advanced reasoning for complex multi-tool analysis with step-by-step evaluation

Reasoning capabilities extend thinking with **mandatory analysis after each tool execution**. This "Act-then-Analyze" pattern enables the agent to evaluate results and adapt its strategy dynamically, making it ideal for complex scenarios requiring iterative refinement.

## Thinking vs. Reasoning

| Feature        | Thinking                         | Reasoning                             |
| -------------- | -------------------------------- | ------------------------------------- |
| **Planning**   | Creates execution plan           | Creates execution plan                |
| **Execution**  | Runs tools sequentially          | Runs tools sequentially               |
| **Analysis**   | Final synthesis only             | Analyzes after EACH tool              |
| **Adaptation** | Follows original plan            | Can revise plan mid-execution         |
| **Best For**   | Straightforward multi-tool tasks | Complex analysis requiring evaluation |

## Enabling Reasoning

Reasoning requires **both** thinking and reasoning tools to be enabled:

```python theme={null}
from upsonic import Agent, Task
from upsonic.tools import tool

@tool
def get_stock_price(symbol: str) -> str:
    """Get current stock price."""
    return f"Current price of {symbol}: $185.50"

@tool
def get_analyst_ratings(symbol: str) -> str:
    """Get analyst ratings and recommendations."""
    return f"Analyst consensus for {symbol}: Buy (78% recommend)"

@tool
def get_company_news(symbol: str) -> str:
    """Get recent company news."""
    return f"Recent news for {symbol}: Strong Q4 earnings reported"

# Enable reasoning for advanced analysis
agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="InvestmentAnalyst",
    tools=[get_stock_price, get_analyst_ratings, get_company_news],
    enable_thinking_tool=True,      # Required for reasoning
    enable_reasoning_tool=True,     # Enables act-then-analyze
    debug=True
)

# Run the agent with reasoning capabilities
task = Task("Should I invest in AAPL? Analyze the stock thoroughly.")
result = agent.print_do(task)
print(result)
```

**Warning**: `enable_reasoning_tool` requires `enable_thinking_tool` to be `True`. Setting reasoning without thinking will raise a `ValueError`.

## How Reasoning Works

Reasoning follows an advanced "Act-then-Analyze" pattern:

1. **Strategic Planning**: Create initial execution plan
2. **Execute One Step**: Run the next tool in the plan
3. **Mandatory Analysis**: Evaluate the result and decide next action
4. **Dynamic Adaptation**: Continue, revise plan, or finalize answer
5. **Final Synthesis**: Comprehensive conclusion with all insights

```
Example Flow:
1. Agent receives: "Should I invest in AAPL?"
2. Plan: [get_stock_price, get_analyst_ratings, get_company_news]
3. Execute get_stock_price → Analyze: "Price is high, need more context"
4. Execute get_analyst_ratings → Analyze: "Analysts bullish, aligns with price"
5. Execute get_company_news → Analyze: "Strong earnings support the rating"
6. Synthesize: "AAPL shows positive indicators across price, analysts, and news"
```

## Reasoning Configuration

### Agent-Level Reasoning

```python theme={null}
from upsonic import Agent, Task
from upsonic.tools import tool

@tool
def search_market_data(query: str) -> str:
    """Search for market data and trends."""
    return f"Market data for {query}: Upward trend, 15% YoY growth"

@tool
def analyze_competitors(company: str) -> str:
    """Analyze competitive landscape."""
    return f"Competitors of {company}: Strong market position, 35% market share"

@tool
def get_financial_metrics(symbol: str) -> str:
    """Get key financial metrics."""
    return f"Financials for {symbol}: P/E 28, Revenue $394B, Profit margin 25%"

# Enable reasoning for all tasks
agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="StrategicAnalyst",
    tools=[search_market_data, analyze_competitors, get_financial_metrics],
    enable_thinking_tool=True,
    enable_reasoning_tool=True
)

# Execute a strategic analysis task
task = Task("Analyze the competitive position and financials of Apple")
result = agent.print_do(task)
print(result)
```

### Task-Level Reasoning

```python theme={null}
from upsonic import Agent, Task
from upsonic.tools import tool

@tool
def search_market_data(query: str) -> str:
    """Search for market data and trends."""
    return f"Market data for {query}: Upward trend, 15% YoY growth"

@tool
def analyze_competitors(company: str) -> str:
    """Analyze competitive landscape."""
    return f"Competitors of {company}: Strong market position, 35% market share"

# Create agent without reasoning enabled at agent level
agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="MarketAnalyst",
    tools=[search_market_data, analyze_competitors]
)

# Override agent settings for specific task - enable reasoning
task = Task(
    description="Conduct a comprehensive competitive analysis of Apple",
    enable_thinking_tool=True,
    enable_reasoning_tool=True
)

result = agent.print_do(task)
print(result)
```

### Mixed Configuration

```python theme={null}
from upsonic import Agent, Task
from upsonic.tools import tool

@tool
def search_market_data(query: str) -> str:
    """Search for market data and trends."""
    return f"Market data for {query}: Upward trend, 15% YoY growth"

@tool
def analyze_competitors(company: str) -> str:
    """Analyze competitive landscape."""
    return f"Competitors of {company}: Strong market position, 35% market share"

@tool
def get_financial_metrics(symbol: str) -> str:
    """Get key financial metrics."""
    return f"Financials for {symbol}: P/E 28, Revenue $394B, Profit margin 25%"

# Agent with reasoning enabled
agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="AnalysisAgent",
    tools=[search_market_data, analyze_competitors, get_financial_metrics],
    enable_thinking_tool=True,
    enable_reasoning_tool=True
)

# Simple lookup - disable reasoning for speed
simple_task = Task(
    description="Get the current market data for MSFT",
    enable_thinking_tool=False,
    enable_reasoning_tool=False  # Single tool, no analysis needed
)
result1 = agent.print_do(simple_task)
print("Simple task result:", result1)

# Complex analysis - use full reasoning
complex_task = Task(
    description="Evaluate if GOOGL is a good investment considering market position, competitors, and financials",
    enable_thinking_tool=True,
    enable_reasoning_tool=True
)
result2 = agent.print_do(complex_task)
print("Complex task result:", result2)
```

## When to Use Reasoning

Reasoning is ideal for:

* **Iterative Analysis**: When each step's result affects the next
* **Strategic Decisions**: Complex scenarios requiring evaluation at each step
* **Adaptive Workflows**: When the plan may need mid-course corrections
* **Quality-Critical Tasks**: Where analyzing intermediate results improves accuracy

### Example: Investment Research with Analysis

```python theme={null}
from upsonic import Agent, Task
from upsonic.tools.common_tools.financial_tools import YFinanceTools

# Create comprehensive financial tools
finance_tools = YFinanceTools(enable_all=True)

# Create agent with reasoning for thorough analysis
agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="InvestmentResearcher",
    tools=finance_tools.functions(),
    enable_thinking_tool=True,
    enable_reasoning_tool=True,
    debug=True
)

# Complex multi-step analysis task
task = Task(
    description="""
    Conduct a thorough investment analysis of Tesla (TSLA):
    
    1. Get current stock price and historical trends
    2. Review analyst recommendations  
    3. Examine company fundamentals and financials
    4. Provide a reasoned investment recommendation
    
    At each step, evaluate if the information changes your assessment.
    """
)

# Agent will execute tools with analysis after each step
result = agent.print_do(task)
print(result)
```

### Example: Multi-Source Research

```python theme={null}
from upsonic import Agent, Task
from upsonic.tools import tool

@tool
def search_news(topic: str) -> str:
    """Search for recent news on a topic."""
    return f"News on {topic}: 3 positive articles, 1 neutral, 0 negative"

@tool  
def get_expert_opinions(topic: str) -> str:
    """Get expert opinions and analysis."""
    return f"Experts on {topic}: Generally optimistic with caveats"

@tool
def analyze_social_sentiment(topic: str) -> str:
    """Analyze social media sentiment."""
    return f"Social sentiment for {topic}: 72% positive, trending up"

@tool
def check_regulatory_status(topic: str) -> str:
    """Check regulatory environment."""
    return f"Regulatory status for {topic}: Favorable, no pending actions"

agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="ResearchAnalyst",
    tools=[search_news, get_expert_opinions, analyze_social_sentiment, check_regulatory_status],
    enable_thinking_tool=True,
    enable_reasoning_tool=True,
    debug=True
)

task = Task(
    description="""
    Research the outlook for electric vehicles in 2025.
    Gather information from news, experts, social sentiment, and regulatory sources.
    After each source, assess how it changes the overall picture.
    Provide a balanced conclusion.
    """,
    enable_thinking_tool=True,
    enable_reasoning_tool=True
)

result = agent.print_do(task)
print(result)
```

## Reasoning Output Structure

When reasoning is enabled, the agent provides:

1. **Initial Strategy**: High-level approach to the problem
2. **Step-by-Step Analysis**: Evaluation after each tool execution
3. **Adaptation Decisions**: Whether to continue, revise, or conclude
4. **Evidence Chain**: How each tool's output influenced the conclusion
5. **Final Recommendation**: Synthesized answer with full reasoning

## Performance Considerations

**Warning**: Reasoning consumes significantly more tokens than thinking alone due to the mandatory analysis after each tool call. Use reasoning when the analytical depth justifies the cost.

```python theme={null}
from upsonic import Agent, Task
from upsonic.tools import tool

@tool
def search_news(topic: str) -> str:
    """Search for recent news on a topic."""
    return f"News on {topic}: 3 positive articles, 1 neutral, 0 negative"

@tool
def get_expert_opinions(topic: str) -> str:
    """Get expert opinions and analysis."""
    return f"Experts on {topic}: Generally optimistic with caveats"

# Monitor performance with debug mode
agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="Analyst",
    tools=[search_news, get_expert_opinions],
    enable_thinking_tool=True,
    enable_reasoning_tool=True,
    debug=True  # Shows detailed reasoning steps
)

# Run task to see performance metrics
task = Task("What is the current outlook for renewable energy investments?")
result = agent.print_do(task)
print(result)
```

## Best Practices

1. **Use for Complex Scenarios**: Enable reasoning when intermediate analysis adds value
2. **Requires Thinking**: Always enable `enable_thinking_tool` when using reasoning
3. **Multiple Tools**: Reasoning shines with 3+ tools where results interact
4. **Clear Instructions**: Tell the agent to "evaluate at each step" or "adjust based on findings"
5. **Monitor Costs**: Reasoning uses more tokens than thinking alone
6. **Debug First**: Use `debug=True` to understand the reasoning chain

Reasoning provides the most sophisticated analytical capabilities for complex scenarios, making it essential for applications that require deep analysis and adaptive decision-making based on intermediate results.
