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

# Tools Module

> Tool system, decorators, and built-in tools for agents

# Tools Module

The tools module provides a comprehensive system for creating and using tools with agents. It includes built-in tools, a decorator for creating custom tools, and a plugin system for extensibility.

## Installation

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
pip install praisonaiagents

# For full tools support
pip install "praisonai[tools]"
```

## Quick Start

### Using the @tool Decorator

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, tool

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

agent = Agent(
    name="Researcher",
    tools=[search_web]
)
```

### Using Built-in Tools

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonaiagents import duckduckgo, wikipedia_tools

agent = Agent(
    name="Researcher",
    tools=[duckduckgo, wikipedia_tools]
)
```

## Classes

### BaseTool

Abstract base class for creating custom tools.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import BaseTool

class MyTool(BaseTool):
    name = "my_tool"
    description = "Does something useful"
    
    def run(self, query: str) -> str:
        return f"Result for {query}"
```

#### Attributes

| Attribute     | Type   | Description                                                 |
| ------------- | ------ | ----------------------------------------------------------- |
| `name`        | `str`  | Unique identifier for the tool                              |
| `description` | `str`  | Human-readable description (used by LLM)                    |
| `version`     | `str`  | Tool version string (default: "1.0.0")                      |
| `parameters`  | `dict` | JSON Schema for parameters (auto-generated if not provided) |

#### Methods

| Method          | Description                            |
| --------------- | -------------------------------------- |
| `run(**kwargs)` | Execute the tool (must be implemented) |
| `get_schema()`  | Get OpenAI-compatible function schema  |
| `validate()`    | Validate tool configuration            |

***

### FunctionTool

A BaseTool wrapper for plain functions, created automatically by the `@tool` decorator.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import FunctionTool

tool_instance = FunctionTool(
    func=my_function,
    name="custom_name",
    description="Custom description"
)
```

***

### ToolResult

Wrapper for tool execution results.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import ToolResult

result = ToolResult(
    output="Success data",
    success=True,
    error=None,
    metadata={"execution_time": 0.5}
)
```

#### Attributes

| Attribute  | Type          | Description                 |
| ---------- | ------------- | --------------------------- |
| `output`   | `Any`         | The tool's output           |
| `success`  | `bool`        | Whether execution succeeded |
| `error`    | `str \| None` | Error message if failed     |
| `metadata` | `dict`        | Additional metadata         |

***

### ToolValidationError

Exception raised when a tool fails validation.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import ToolValidationError

raise ToolValidationError("Invalid tool configuration")
```

## Decorators

### @tool

Convert a function into a tool.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import tool

# Simple usage
@tool
def my_func(x: str) -> str:
    """Does something."""
    return x

# With parameters
@tool(name="custom_name", description="Custom description")
def my_func(x: str) -> str:
    return x
```

#### Parameters

| Parameter     | Type  | Description                                        |
| ------------- | ----- | -------------------------------------------------- |
| `name`        | `str` | Override the tool name (default: function name)    |
| `description` | `str` | Override description (default: function docstring) |
| `version`     | `str` | Tool version (default: "1.0.0")                    |

## Built-in Tools

### Search Tools

| Tool             | Description                    | API Key Required |
| ---------------- | ------------------------------ | ---------------- |
| `duckduckgo`     | DuckDuckGo web search          | No               |
| `tavily_search`  | Tavily AI search               | `TAVILY_API_KEY` |
| `exa_search`     | Exa semantic search            | `EXA_API_KEY`    |
| `ydc_search`     | You.com search                 | `YDC_API_KEY`    |
| `searxng_search` | SearXNG search                 | No               |
| `search_web`     | Unified search (auto-fallback) | Varies           |

### Knowledge Tools

| Tool              | Description             |
| ----------------- | ----------------------- |
| `wiki_search`     | Wikipedia search        |
| `wiki_summary`    | Wikipedia summaries     |
| `search_arxiv`    | arXiv paper search      |
| `get_arxiv_paper` | Get arXiv paper details |

### Web Crawling Tools

| Tool            | Description              |
| --------------- | ------------------------ |
| `crawl4ai`      | Async web crawling       |
| `scrape_page`   | Scrape web pages         |
| `extract_links` | Extract links from pages |
| `get_article`   | Extract article content  |

### File Tools

| Tool         | Description             |
| ------------ | ----------------------- |
| `read_file`  | Read file contents      |
| `write_file` | Write to files          |
| `list_files` | List directory contents |
| `read_csv`   | Read CSV files          |
| `write_csv`  | Write CSV files         |
| `read_json`  | Read JSON files         |
| `write_json` | Write JSON files        |
| `read_yaml`  | Read YAML files         |
| `read_xml`   | Read XML files          |
| `read_excel` | Read Excel files        |

### Data Tools

| Tool          | Description           |
| ------------- | --------------------- |
| `query`       | DuckDB SQL queries    |
| `filter_data` | Pandas data filtering |
| `get_summary` | Data summaries        |
| `pivot_table` | Create pivot tables   |

### Calculator Tools

| Tool                   | Description               |
| ---------------------- | ------------------------- |
| `evaluate`             | Evaluate math expressions |
| `solve_equation`       | Solve equations           |
| `convert_units`        | Unit conversion           |
| `calculate_statistics` | Statistical calculations  |

### Shell Tools

| Tool              | Description            |
| ----------------- | ---------------------- |
| `execute_command` | Execute shell commands |
| `list_processes`  | List running processes |
| `get_system_info` | Get system information |

### Code Tools

| Tool           | Description            |
| -------------- | ---------------------- |
| `execute_code` | Execute Python code    |
| `analyze_code` | Analyze code structure |
| `format_code`  | Format Python code     |
| `lint_code`    | Lint Python code       |

## Usage Examples

### Creating Custom Tools

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, BaseTool, tool

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

# Method 2: Subclassing BaseTool
class StockPriceTool(BaseTool):
    name = "get_stock_price"
    description = "Get current stock price for a symbol"
    
    def run(self, symbol: str) -> dict:
        return {"symbol": symbol, "price": 150.00}

# Use with agent
agent = Agent(
    name="Assistant",
    tools=[get_weather, StockPriceTool()]
)
```

### Using Multiple Built-in Tools

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonaiagents import (
    duckduckgo,
    wiki_search,
    read_file,
    execute_command
)

agent = Agent(
    name="Research Assistant",
    tools=[duckduckgo, wiki_search, read_file, execute_command]
)
```

### Tool Registry

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import get_registry, register_tool, get_tool

# Get the global registry
registry = get_registry()

# Register a tool
@tool
def my_tool(x: str) -> str:
    return x

register_tool(my_tool)

# Retrieve a tool
tool = get_tool("my_tool")
```

## Tool Validation

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import BaseTool, validate_tool, ToolValidationError

class MyTool(BaseTool):
    name = "my_tool"
    description = "My custom tool"
    
    def run(self, query: str) -> str:
        return query

# Validate the tool
try:
    validate_tool(MyTool())
    print("Tool is valid!")
except ToolValidationError as e:
    print(f"Validation failed: {e}")
```

## Related

* [Agent](/docs/sdk/praisonaiagents/agent/agent) - Using tools with agents
* [Task](/docs/sdk/praisonaiagents/task/task) - Task configuration
