Tool Calling Guide

Tool calling allows HelpingAI to execute functions and access external data sources during conversations. This enables the AI to perform actions like fetching real-time information, making calculations, or interacting with external APIs.

How Tool Calling Works

  1. Define Tools: Specify available functions with their parameters
  2. AI Decides: The model determines when and which tools to use
  3. Execute Functions: Your application runs the requested functions
  4. Return Results: Provide function results back to the AI
  5. Generate Response: AI incorporates results into its response

Basic Tool Calling

Python (using requests)

Python
import requests
import json

def get_weather(location):
    # Mock weather function
    return f"The weather in {location} is sunny and 72°F"

url = "https://api.helpingai.co/v1/chat/completions"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city name"
                }
            },
            "required": ["location"]
        }
    }
}]

data = {
    "model": "Dhanishtha-2.0-preview",
    "messages": [
        {"role": "user", "content": "What's the weather like in Tokyo?"}
    ],
    "tools": tools,
    "tool_choice": "auto"
}

response = requests.post(url, headers=headers, json=data)
result = response.json()

# Check if AI wants to call a function {#check-if-ai-wants-to-call-a-function}
message = result['choices'][0]['message']
if message.get('tool_calls'):
    # Execute the function
    tool_call = message['tool_calls'][0]
    function_name = tool_call['function']['name']
    function_args = json.loads(tool_call['function']['arguments'])
    
    if function_name == "get_weather":
        function_result = get_weather(function_args['location'])
    
    # Send function result back to AI
    data['messages'].extend([
        message,  # AI's message with tool call
        {
            "role": "tool",
            "tool_call_id": tool_call['id'],
            "content": function_result
        }
    ])
    
    # Get final response
    final_response = requests.post(url, headers=headers, json=data)
    print(final_response.json()['choices'][0]['message']['content'])

Python (using OpenAI SDK)

Python
from openai import OpenAI
import json

client = OpenAI(
    base_url="https://api.helpingai.co/v1",
    api_key="YOUR_API_KEY"
)

def get_weather(location):
    return f"The weather in {location} is sunny and 72°F"

def get_stock_price(symbol):
    return f"The current price of {symbol} is $150.25"

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City name"}
                },
                "required": ["location"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_stock_price",
            "description": "Get current stock price",
            "parameters": {
                "type": "object",
                "properties": {
                    "symbol": {"type": "string", "description": "Stock symbol"}
                },
                "required": ["symbol"]
            }
        }
    }
]

messages = [
    {"role": "user", "content": "What's the weather in New York and the stock price of AAPL?"}
]

response = client.chat.completions.create(
    model="Dhanishtha-2.0-preview",
    messages=messages,
    tools=tools,
    tool_choice="auto"
)

# Handle tool calls {#handle-tool-calls}
message = response.choices[0].message
if message.tool_calls:
    messages.append(message)
    
    for tool_call in message.tool_calls:
        function_name = tool_call.function.name
        function_args = json.loads(tool_call.function.arguments)
        
        if function_name == "get_weather":
            result = get_weather(function_args['location'])
        elif function_name == "get_stock_price":
            result = get_stock_price(function_args['symbol'])
        
        messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": result
        })
    
    # Get final response
    final_response = client.chat.completions.create(
        model="Dhanishtha-2.0-preview",
        messages=messages
    )
    
    print(final_response.choices[0].message.content)

Python (using HelpingAI SDK)

Python
from helpingai import HelpingAI
import json

client = HelpingAI(api_key="YOUR_API_KEY")

def calculate_tip(bill_amount, tip_percentage):
    tip = bill_amount * (tip_percentage / 100)
    total = bill_amount + tip
    return {
        "tip_amount": tip,
        "total_amount": total,
        "bill_amount": bill_amount,
        "tip_percentage": tip_percentage
    }

tools = [{
    "type": "function",
    "function": {
        "name": "calculate_tip",
        "description": "Calculate tip and total amount for a bill",
        "parameters": {
            "type": "object",
            "properties": {
                "bill_amount": {"type": "number", "description": "The bill amount"},
                "tip_percentage": {"type": "number", "description": "Tip percentage (e.g., 15 for 15%)"}
            },
            "required": ["bill_amount", "tip_percentage"]
        }
    }
}]

messages = [
    {"role": "user", "content": "I have a $85 bill and want to tip 18%. How much should I pay?"}
]

response = client.chat.completions.create(
    model="Dhanishtha-2.0-preview",
    messages=messages,
    tools=tools,
    tool_choice="auto"
)

message = response.choices[0].message
if message.tool_calls:
    messages.append(message)
    
    for tool_call in message.tool_calls:
        function_args = json.loads(tool_call.function.arguments)
        result = calculate_tip(function_args['bill_amount'], function_args['tip_percentage'])
        
        messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": json.dumps(result)
        })
    
    final_response = client.chat.completions.create(
        model="Dhanishtha-2.0-preview",
        messages=messages
    )
    
    print(final_response.choices[0].message.content)

JavaScript (using axios)

JavaScript
const axios = require('axios');

async function getWeather(location) {
    return `The weather in ${location} is sunny and 72°F`;
}

async function toolCallingExample() {
    const tools = [{
        type: "function",
        function: {
            name: "get_weather",
            description: "Get current weather for a location",
            parameters: {
                type: "object",
                properties: {
                    location: {
                        type: "string",
                        description: "The city name"
                    }
                },
                required: ["location"]
            }
        }
    }];

    let messages = [
        {role: "user", content: "What's the weather like in London?"}
    ];

    // Initial request
    let response = await axios.post(
        'https://api.helpingai.co/v1/chat/completions',
        {
            model: 'Dhanishtha-2.0-preview',
            messages: messages,
            tools: tools,
            tool_choice: "auto"
        },
        {
            headers: {
                'Authorization': 'Bearer YOUR_API_KEY',
                'Content-Type': 'application/json'
            }
        }
    );

    const message = response.data.choices[0].message;
    
    if (message.tool_calls) {
        messages.push(message);
        
        for (const toolCall of message.tool_calls) {
            const functionName = toolCall.function.name;
            const functionArgs = JSON.parse(toolCall.function.arguments);
            
            let result;
            if (functionName === "get_weather") {
                result = await getWeather(functionArgs.location);
            }
            
            messages.push({
                role: "tool",
                tool_call_id: toolCall.id,
                content: result
            });
        }
        
        // Get final response
        const finalResponse = await axios.post(
            'https://api.helpingai.co/v1/chat/completions',
            {
                model: 'Dhanishtha-2.0-preview',
                messages: messages
            },
            {
                headers: {
                    'Authorization': 'Bearer YOUR_API_KEY',
                    'Content-Type': 'application/json'
                }
            }
        );
        
        console.log(finalResponse.data.choices[0].message.content);
    }
}

toolCallingExample();

JavaScript (using OpenAI package)

JavaScript
import OpenAI from 'openai';

const openai = new OpenAI({
  baseURL: 'https://api.helpingai.co/v1',
  apiKey: 'YOUR_API_KEY'
});

async function searchWeb(query) {
    return `Search results for "${query}": Found 3 relevant articles about ${query}.`;
}

async function main() {
    const tools = [{
        type: "function",
        function: {
            name: "search_web",
            description: "Search the web for information",
            parameters: {
                type: "object",
                properties: {
                    query: {
                        type: "string",
                        description: "Search query"
                    }
                },
                required: ["query"]
            }
        }
    }];

    let messages = [
        {role: "user", content: "Can you search for information about climate change?"}
    ];

    const response = await openai.chat.completions.create({
        model: 'Dhanishtha-2.0-preview',
        messages: messages,
        tools: tools,
        tool_choice: "auto"
    });

    const message = response.choices[0].message;
    
    if (message.tool_calls) {
        messages.push(message);
        
        for (const toolCall of message.tool_calls) {
            const functionArgs = JSON.parse(toolCall.function.arguments);
            const result = await searchWeb(functionArgs.query);
            
            messages.push({
                role: "tool",
                tool_call_id: toolCall.id,
                content: result
            });
        }
        
        const finalResponse = await openai.chat.completions.create({
            model: 'Dhanishtha-2.0-preview',
            messages: messages
        });
        
        console.log(finalResponse.choices[0].message.content);
    }
}

main();

JavaScript (using HelpingAI SDK)

JavaScript
import { HelpingAI } from 'helpingai';

const client = new HelpingAI({
  apiKey: 'YOUR_API_KEY'
});

async function sendEmail(to, subject, body) {
    return `Email sent to ${to} with subject "${subject}"`;
}

async function main() {
    const tools = [{
        type: "function",
        function: {
            name: "send_email",
            description: "Send an email",
            parameters: {
                type: "object",
                properties: {
                    to: {type: "string", description: "Recipient email"},
                    subject: {type: "string", description: "Email subject"},
                    body: {type: "string", description: "Email body"}
                },
                required: ["to", "subject", "body"]
            }
        }
    }];

    let messages = [
        {role: "user", content: "Send an email to john@example.com about the meeting tomorrow"}
    ];

    const response = await client.chat.completions.create({
        model: 'Dhanishtha-2.0-preview',
        messages: messages,
        tools: tools,
        tool_choice: "auto"
    });

    const message = response.choices[0].message;
    
    if (message.tool_calls) {
        messages.push(message);
        
        for (const toolCall of message.tool_calls) {
            const functionArgs = JSON.parse(toolCall.function.arguments);
            const result = await sendEmail(
                functionArgs.to,
                functionArgs.subject,
                functionArgs.body
            );
            
            messages.push({
                role: "tool",
                tool_call_id: toolCall.id,
                content: result
            });
        }
        
        const finalResponse = await client.chat.completions.create({
            model: 'Dhanishtha-2.0-preview',
            messages: messages
        });
        
        console.log(finalResponse.choices[0].message.content);
    }
}

main();

Tool Choice Options

Control when tools are used with the tool_choice parameter:

Auto (Default)

Python
response = client.chat.completions.create(
    model="Dhanishtha-2.0-preview",
    messages=messages,
    tools=tools,
    tool_choice="auto"  # AI decides when to use tools
)

None

Python
response = client.chat.completions.create(
    model="Dhanishtha-2.0-preview",
    messages=messages,
    tools=tools,
    tool_choice="none"  # Never use tools
)

Required

Python
response = client.chat.completions.create(
    model="Dhanishtha-2.0-preview",
    messages=messages,
    tools=tools,
    tool_choice="required"  # Must use a tool
)

Specific Function

Python
response = client.chat.completions.create(
    model="Dhanishtha-2.0-preview",
    messages=messages,
    tools=tools,
    tool_choice={
        "type": "function",
        "function": {"name": "get_weather"}
    }
)

Advanced Examples

Multiple Tool Calls

Python
from openai import OpenAI
import json

client = OpenAI(
    base_url="https://api.helpingai.co/v1",
    api_key="YOUR_API_KEY"
)

def get_user_info(user_id):
    return {"name": "John Doe", "email": "john@example.com", "role": "developer"}

def get_project_status(project_id):
    return {"status": "in_progress", "completion": "75%", "deadline": "2024-01-15"}

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_user_info",
            "description": "Get user information",
            "parameters": {
                "type": "object",
                "properties": {
                    "user_id": {"type": "string"}
                },
                "required": ["user_id"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_project_status",
            "description": "Get project status",
            "parameters": {
                "type": "object",
                "properties": {
                    "project_id": {"type": "string"}
                },
                "required": ["project_id"]
            }
        }
    }
]

messages = [
    {"role": "user", "content": "Get info for user 123 and status for project ABC"}
]

response = client.chat.completions.create(
    model="Dhanishtha-2.0-preview",
    messages=messages,
    tools=tools,
    tool_choice="auto"
)

message = response.choices[0].message
if message.tool_calls:
    messages.append(message)
    
    for tool_call in message.tool_calls:
        function_name = tool_call.function.name
        function_args = json.loads(tool_call.function.arguments)
        
        if function_name == "get_user_info":
            result = get_user_info(function_args['user_id'])
        elif function_name == "get_project_status":
            result = get_project_status(function_args['project_id'])
        
        messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": json.dumps(result)
        })
    
    final_response = client.chat.completions.create(
        model="Dhanishtha-2.0-preview",
        messages=messages
    )
    
    print(final_response.choices[0].message.content)

Error Handling

Function Execution Errors

Python
def safe_function_call(function_name, function_args):
    try:
        if function_name == "get_weather":
            return get_weather(function_args['location'])
        elif function_name == "calculate_tip":
            return calculate_tip(function_args['bill_amount'], function_args['tip_percentage'])
        else:
            return {"error": f"Unknown function: {function_name}"}
    except Exception as e:
        return {"error": f"Function execution failed: {str(e)}"}

# Use in tool call handling {#use-in-tool-call-handling}
for tool_call in message.tool_calls:
    function_name = tool_call.function.name
    function_args = json.loads(tool_call.function.arguments)
    
    result = safe_function_call(function_name, function_args)
    
    messages.append({
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": json.dumps(result)
    })

Best Practices

  1. Clear Function Descriptions: Write detailed descriptions for better AI understanding
  2. Validate Parameters: Always validate function arguments
  3. Handle Errors Gracefully: Return meaningful error messages
  4. Use Appropriate Types: Define parameter types accurately
  5. Limit Function Scope: Keep functions focused and specific
  6. Secure Function Calls: Validate and sanitize all inputs

Next Steps