# Tools

Tools are user-defined functions that enhance the agent’s capabilities and are integrated into the AI Agent SDK as plugins. They allow the AI agent to fetch data, perform computations, and interact with external APIs. \
\
Tools need to be decorated with `@tool` to be recognized and registered in the AI Agent. \
\
It can serve various purposes, from fetching data to performing calculations, and integrating with external APIs.

### Set Up

Before defining a tool, import the `@tool` decorator to register the function properly:

```python
from crypto_com_agent_client import tool
```

### Implementation Examples

1. **Custom Greeting Tool**\
   This tool generates a personalized greeting message for a user.

```python
@tool
def greet_user(name: str) -> str:
    """
    Generate a personalized greeting message.

    Args:
        name (str): The name of the user to greet.

    Returns:
        str: A greeting message addressed to the user.
    """
    return f"Hello, {name}! How can I assist you today?"
```

2. **Token Information Tool**\
   This tool retrieves token information from Cronos EVM using the VVS Finance API (a third-party Cronos project). It fetches liquidity and volume data from underlying subgraphs.

```python
@tool
def get_token_info(address: str) -> str:
   """ 
   Returns the token information, based on address.
   Args:
    address (str): The token contract address to query.

   Returns:
    str: Formatted token details.
   """
   try:
       response = requests.get(f"https://api.vvs.finance/info/api/tokens/{address}")
       response.raise_for_status()
       return f"Token at {address} is {response.json()}."
   except requests.RequestException as e:
       print(f"Error fetching data: {e}")
       return f"Error getting token information: {str(e)}"
```

3. **APR Query Tool**\
   This example demonstrates how to query APR from blockchain projects. Here, we integrate H2 Finance (a third-party Cronos project) leveraging its API to incorporate it as a plugin within the AI Agent SDK. \
   The AI agent can automatically parse the JSON response, extract relevant information, and provide structured answers to various APR-related queries.

```python
import requests

@tool
def get_h2_apr() -> str:
    """  
    Fetches the latest APR data from H2 Finance API 

    Returns:
        str: Formatted APR details.
    """
    try:
        response = requests.get("https://api.h2.finance/general/api/info/v1/farm-aprs")
        response.raise_for_status()
        return f"H2 Finance APR information is {response.json()}."
        
    except requests.RequestException as e:
        print(f"Error fetching data: {e}")
        return f"Error getting H2 Finance APR information: {str(e)}"

```

4. **Cronos Blockchain Status Tool**<br>

   This blockchain status tool provides real-time insights into the Cronos EVM and Cronos zkEVM networks. With a single function call, users can access key network metrics, including the latest block number, current gas prices, transaction count in the most recent block, network difficulty, and timestamp details.\
   \
   The tool interacts directly with blockchain nodes via standard RPC endpoints, to ensure accurate and up-to-date status reports in a structured format. It offers developers instant access to the Cronos chains' performance data without requiring complex setup or configuration.

<pre class="language-python"><code class="lang-python"><strong>@tool
</strong>def get_blockchain_status(network: str = "cronos" "cronos zkevm") -> str:
    """
    Provide real-time blockchain network status including gas prices and block info

    Args:
        network (str): Supported networks: Cronos EVM, Cronos zkEVM.

    Returns:
        str: Formatted network status report or an error message.
    """
  
    from web3 import Web3
    from datetime import datetime, timezone
    
    

# Map networks to their RPC endpoints
    rpc_endpoints = {
        "cronos": "https://evm.cronos.org",
	"cronos zkevm": "https://mainnet.zkevm.cronos.org/"
    }
    
    if network.lower() not in rpc_endpoints:
        return f"Error: Unsupported network '{network}'. Supported networks: {', '.join(rpc_endpoints.keys())}"
    
    try:
        # Initialize Web3 connection
        web3 = Web3(Web3.HTTPProvider(rpc_endpoints[network.lower()]))
        
        # Check connection
        if not web3.is_connected():
            return f"Error: Could not connect to {network} network"
        
        # Fetch blockchain data
        latest_block = web3.eth.block_number
        gas_price_wei = web3.eth.gas_price
        gas_price_gwei = web3.from_wei(gas_price_wei, 'gwei')
        block_info = web3.eth.get_block(latest_block)
        
        # Convert timestamp to timezone-aware datetime object
        timestamp_dt = datetime.fromtimestamp(block_info['timestamp'], tz=timezone.utc)
        formatted_time = timestamp_dt.strftime('%Y-%m-%d %H:%M:%S UTC')
        
        return (
            f" Blockchain Status for {network.capitalize()} ".center(40, "=") + "\n"
            f"Latest Block:       {latest_block}\n"
            f"Gas Price:          {gas_price_gwei:.2f} Gwei\n"
            f"Transactions:       {len(block_info['transactions'])} in current block\n"
            f"Difficulty:         {block_info['difficulty']}\n"
            f"Timestamp:          {block_info['timestamp']} ({formatted_time})"
        )
    
    except Exception as err:
        return f"Error fetching {network} data: {str(err)}"

</code></pre>

### &#x20;Using Tools in the Agent

To use the tools in your agent, initialize it with the required configurations:

```python
from crypto_com_agent_client import Agent

agent = Agent.init(
    llm_config={
        "provider": "OpenAI",
        "model": "gpt-4",
        "provider-api-key": "sk-proj-example-key",
        "temperature": "float-controlling-output-randomness",
        "transfer-limit": -1,  # -1 means no limit (unlimited), 0 disables transfers completely, any positive number (e.g. 5) allows exactly that transfer amount
    },
    blockchain_config={
        "api_key": "your-crypto.com-developer-platform-api-key",
        "private-key": "your-private-key",
        "sso-wallet-url": "your-sso-wallet-url",
        "timeout": "timeout-in-seconds-for-API-calls-default-20s")
    },
    plugins={
         "tools": [greet_user, get_token_info, get_h2_apr, get_blockchain_status],
    },
)
```

### Query and Response

Take `get_h2_apr`  for example, the AI Agent can automatically extract information from the result JSON and provide answers to various queries. Developers don’t need to manually search for specific fields in the JSON response - the AI Agent SDK handles that for you.

#### Example Query (APY)

```python
response = agent.interact("What's the APY of H2 Finance?")
print(response)
```

Response &#x20;

```python
Here are the APYs (Annual Percentage Yields) for various liquidity pools in H2 Finance:

1. **zkCRO-CRO**
   - Emission APY: 8.81%
   - LP APY: 1.12%

2. **zkCRO-AMPLY**
   - Emission APY: 72.25%
   - LP APY: 0.63%

3. **zkCRO-vETH**
   - Emission APY: 13.66%
   - LP APY: 4.21%

4. **zkCRO-MOON**
   - Emission APY: 0.00%
   - LP APY: 5.35%
   - Rewarders APY (MOON): 129.04%

5. **vUSD-USDC**
   - Emission APY: 3.33%
   - LP APY: 1.89%

...

These values reflect the current returns for participating in these liquidity pools. If you have any specific pool you want more details on, let me know!
```

#### Example Query (APR)

```python
response = agent.interact("What's the APR of h2 finance?")
```

Response

```python
Here are the current APR (Annual Percentage Rate) details for H2 Finance:

1. **zkCRO-CRO**
   - Emission APR: 8.45%
   - LP APR: 1.11%

2. **zkCRO-AMPLY**
   - Emission APR: 54.42%
   - LP APR: 0.62%

3. **zkCRO-vETH**
   - Emission APR: 12.80%
   - LP APR: 4.13%

4. **zkCRO-MOON**
   - Emission APR: 0.00%
   - LP APR: 5.21%
   - Rewarders APR (MOON): 82.97%

5. **vUSD-USDC**
   - Emission APR: 3.28%
   - LP APR: 1.88%

6. **zkCRO-H2**
   - Emission APR: 63.05%
   - LP APR: 1.16%
   
   ...

These APR values are subject to change, so please check regularly for updates.

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ai-agent-sdk-docs.crypto.com/crypto.com-ai-agent-sdk/core-concepts-overview/tools.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
