Crypto.com AI Agent SDK
  • Getting Started
    • Introduction
    • Quick Start Guide: Simulation Entry Point
  • Core Concepts Overview
    • Plugins
    • Tools
    • Blockchain Functions
      • Wallet Management
      • Token Interaction
      • Transaction Queries
      • Block Information
      • Contract Operations
      • CronosID Operations
      • Defi Operations
      • Crypto.com Exchange
    • Built-in Telegram Feature
    • Advanced Usage: Custom Instructions
    • Dynamic AI Model Manager
  • Crypto.com On-Chain Developer Platform
    • Developer Platform API Methods
  • On-Chain Functions and Examples
    • AI Agent Chatbot
    • "Magic Link" Signer
  • Resources for Developers
Powered by GitBook
On this page
  • Set Up
  • Implementation Examples
  • Using Tools in the Agent
  • Query and Response

Was this helpful?

  1. Core Concepts Overview

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:

from crypto_com_agent_client import tool

Implementation Examples

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

@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?"
  1. 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.

@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)}"
  1. 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.

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)}"
  1. Cronos Blockchain Status Tool

    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.

@tool
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)}"

Using Tools in the Agent

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

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",
    },
    blockchain_config={
         "chainId": "chain-id",
         "explorer-api-key": "your-api-key",
         "private-key": "your-private-key",
         "sso-wallet-url": "your-sso-wallet-url",
    },
    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)

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

Response

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)

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

Response

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.

PreviousPluginsNextBlockchain Functions

Last updated 22 days ago

Was this helpful?