> ## 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 Thinking

> Enable thinking capabilities for structured multi-tool orchestration

Thinking capabilities enable your agent to **plan and orchestrate multiple tool calls** in a structured, step-by-step manner. This feature is essential when tasks require coordinating several tools to reach a comprehensive conclusion.

## Why Use Thinking?

Thinking is most valuable when your agent has **multiple tools** and needs to:

* Create an execution plan before acting
* Call tools in a specific sequence
* Synthesize results from multiple sources

Without thinking, agents make ad-hoc tool calls. With thinking, agents strategically plan their approach first.

## Enabling Thinking

To enable thinking capabilities, set `enable_thinking_tool=True` when creating your agent:

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

# Define tools the agent can use
@tool
def get_weather(city: str) -> str:
    """Get current weather for a city."""
    return f"Weather in {city}: Sunny, 25°C"

@tool
def get_population(city: str) -> str:
    """Get population for a city."""
    return f"Population of {city}: 2.1 million"

# Enable thinking for multi-tool orchestration
agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="CityAnalyst",
    tools=[get_weather, get_population],
    enable_thinking_tool=True,
    debug=True
)

# Create task and execute
task = Task("Tell me about Paris's weather and population")
result = agent.do(task)
print(result)
```

## How Thinking Works

When thinking is enabled, the agent follows a structured "blueprint" approach:

1. **Strategic Planning**: The agent creates a complete, sequential plan of tool calls
2. **Orchestrated Execution**: Tools are executed step-by-step according to the plan
3. **Final Synthesis**: Results from all tools are combined into a comprehensive answer

```
Example Flow:
1. Agent receives: "Tell me about Paris's weather and population"
2. Agent creates plan: [get_weather("Paris"), get_population("Paris")]
3. Orchestrator executes: get_weather → get_population
4. Agent synthesizes: "Paris has sunny weather at 25°C and 2.1 million residents"
```

### Thinking vs. Basic Mode

| Feature       | Basic Mode            | Thinking Mode                       |
| ------------- | --------------------- | ----------------------------------- |
| **Planning**  | Ad-hoc tool calls     | Structured blueprint creation       |
| **Execution** | Direct tool execution | Orchestrated step-by-step execution |
| **Best For**  | Single tool tasks     | Multi-tool coordination             |

## Thinking Configuration

### Agent-Level Thinking

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

@tool
def search_web(query: str) -> str:
    """Search the web for information."""
    return f"Search results for: {query}"

@tool
def analyze_sentiment(text: str) -> str:
    """Analyze sentiment of text."""
    return "Sentiment: Positive (85% confidence)"

# Enable thinking for all tasks
agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="ResearchAgent",
    tools=[search_web, analyze_sentiment],
    enable_thinking_tool=True
)

# Execute a research task
task = Task("Search for information about AI trends and analyze the sentiment")
result = agent.do(task)
print(result)
```

### Task-Level Thinking

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

@tool
def search_web(query: str) -> str:
    """Search the web for information."""
    return f"Search results for: {query} - Found 5 relevant articles"

@tool
def analyze_sentiment(text: str) -> str:
    """Analyze sentiment of text."""
    return "Sentiment: Positive (85% confidence)"

# Create agent without thinking enabled by default
agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="ResearchAgent",
    tools=[search_web, analyze_sentiment]
)

# Override agent settings for specific task - enable thinking
task = Task(
    description="Search for recent AI news and analyze the sentiment",
    enable_thinking_tool=True  # Enable thinking for this specific task
)

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

### Mixed Configuration

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

@tool
def search_web(query: str) -> str:
    """Search the web for information."""
    return f"Search results for: {query}"

@tool
def analyze_sentiment(text: str) -> str:
    """Analyze sentiment of text."""
    return "Sentiment: Positive (85% confidence)"

# Agent with thinking enabled
agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="AnalysisAgent",
    tools=[search_web, analyze_sentiment],
    enable_thinking_tool=True
)

# Simple task without thinking (single tool)
simple_task = Task(
    description="What time is it in Tokyo?",
    enable_thinking_tool=False  # Disable thinking for simple queries
)
result1 = agent.do(simple_task)
print("Simple result:", result1)

# Complex task with thinking (multiple tools)
complex_task = Task(
    description="Research the topic of electric vehicles and analyze public sentiment",
    enable_thinking_tool=True  # Keep thinking for complex analysis
)
result2 = agent.do(complex_task)
print("Complex result:", result2)
```

## When to Use Thinking

Thinking is ideal for:

* **Multi-source Research**: Gathering data from multiple tools and synthesizing
* **Step-by-Step Analysis**: Tasks requiring sequential tool execution
* **Complex Workflows**: When tool outputs feed into subsequent tool calls
* **Data Aggregation**: Combining results from several sources

### Example: Financial Analysis with Multiple Tools

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

# Create financial tools
finance_tools = YFinanceTools(
    stock_price=True,
    analyst_recommendations=True,
    company_news=True
)

# Create agent with thinking for multi-step analysis
agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="FinancialAnalyst",
    tools=finance_tools.functions(),
    enable_thinking_tool=True,
    debug=True
)

# Task requiring multiple tool calls
task = Task(
    description="""
    Analyze Apple (AAPL) stock:
    1. Get the current stock price
    2. Fetch analyst recommendations
    3. Get recent company news
    4. Provide a comprehensive investment summary
    """
)

# Agent will plan and execute: get_current_stock_price, get_analyst_recommendations, get_company_news
# Then synthesize results into investment summary
result = agent.do(task)
print(result)
```

### Example: Multi-City Research

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

@tool
def get_weather(city: str) -> str:
    """Get current weather for a city."""
    return f"Weather in {city}: Sunny, 25°C"

@tool
def get_population(city: str) -> str:
    """Get population statistics for a city."""
    return f"Population of {city}: 2.1 million"

@tool
def get_attractions(city: str) -> str:
    """Get top attractions in a city."""
    return f"Top attractions in {city}: Museums, Parks, Historic sites"

agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="TravelAdvisor",
    tools=[get_weather, get_population, get_attractions],
    enable_thinking_tool=True,
    debug=True
)

task = Task(
    description="Give me a complete travel briefing for Paris including weather, population, and attractions",
    enable_thinking_tool=True
)

# Agent creates plan: [get_weather, get_population, get_attractions]
# Executes each tool, then synthesizes into travel briefing
result = agent.do(task)
print(result)
```

## Thinking Output Structure

When thinking is enabled, the agent provides:

1. **Reasoning**: Detailed strategy for approaching the task
2. **Execution Plan**: Step-by-step tool call sequence
3. **Criticism**: Self-assessment identifying potential issues
4. **Final Synthesis**: Comprehensive answer combining all tool results

## Performance Considerations

**Important**: Thinking capabilities consume more tokens and processing time than basic mode due to the planning and synthesis steps. Use thinking when the orchestration value outweighs the cost.

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

@tool
def get_weather(city: str) -> str:
    """Get current weather for a city."""
    return f"Weather in {city}: Sunny, 25\u00b0C"

@tool
def get_population(city: str) -> str:
    """Get population for a city."""
    return f"Population of {city}: 2.1 million"

# Monitor performance with debug mode
agent = Agent(
    model="anthropic/claude-sonnet-4-5",
    name="Analyst",
    tools=[get_weather, get_population],
    enable_thinking_tool=True,
    debug=True  # Shows detailed execution metrics
)

# Run task to see performance metrics
task = Task("Compare the weather and populations of London and Paris")
result = agent.do(task)
print(result)
```

## Best Practices

1. **Use for Multi-Tool Tasks**: Enable thinking when you have 2+ tools that need coordination
2. **Disable for Simple Queries**: Use basic mode for single-tool or no-tool tasks
3. **Provide Clear Instructions**: Help the agent plan by being specific about what you need
4. **Include Multiple Tools**: Thinking shines when there are tools to orchestrate
5. **Monitor with Debug Mode**: Use `debug=True` to understand the planning process

Thinking provides a powerful way to handle complex scenarios that require multiple tools working together, making it essential for sophisticated multi-step analysis and research tasks.
