Why AI Needs Tool Calling Capabilities

Large language models, while powerful, have inherent limitations: they cannot access real-time information, execute code, or operate external systems. Function Calling is designed to address these issues—it enables AI to autonomously select and call external APIs and functions, just as humans use tools, thereby breaking through the model's boundaries.

Imagine a scenario: a user asks, "What's the weather in Beijing today?" A pure text model cannot answer because its training data has a cutoff date. But an AI with Function Calling would do this: recognize the need to call a weather API → construct the correct API request → parse the returned JSON data → reply to the user in natural language. This is the beauty of the tool calling loop.

How Function Calling Works

Function Calling is not about AI actually calling functions; it's a carefully designed protocol:

  1. Define Tools: Developers describe available functions to the model (name, parameters, purpose)
  2. Model Decision: AI analyzes user input, decides whether to call a tool, which tool, and what parameters to pass
  3. Developer Execution: Developer code executes the actual function call
  4. Result Feedback: The execution result is returned to the model, which generates the final response based on it

The elegance of this protocol lies in: AI is responsible for "deciding what to do," but the actual execution power always remains with the developer, ensuring safety and controllability.

Skill Chain Breakdown: Tool Orchestration Chain

Let's take the "Tool Orchestration Chain" skill chain as an example to break down the role of each node in the tool calling process:

Node 1: Requirement Understanding (sp-188)—AI first needs to accurately understand the user's intent. When the user says "Help me check the nearest flights," AI needs to recognize this as a task requiring external tool calls, not a simple text Q&A.

Node 2: Tool Selection (sp-179)—Select the most appropriate tool from the available tool set. If the user wants to check flights, the flight query API should be called, not the weather API. This node requires AI to have "tool matching" capability.

Node 3: Tool Invocation (sp-181)—Construct correct parameters and execute the call. AI needs to convert the user's vague request (e.g., "nearest flights") into precise API parameters (e.g., date=2026-07-13, from=Beijing, to=Shanghai).

Node 4: Result Parsing (sp-187)—Convert the structured data returned by the API into user-friendly natural language responses. A flight query might return dozens of JSON records, but the user only needs the most relevant 2-3 options.

Hands-On: Building a Multi-Tool Agent

The following code demonstrates an Agent Loop implementation with multiple tools:

import json
from openai import OpenAI
import requests

client = OpenAI(
    api_key="your-deepseek-api-key",
    base_url="https://api.deepseek.com"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get real-time weather information for a specified city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "City name, e.g., Beijing"}
                },
                "required": ["city"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "search_web",
            "description": "Search the internet for the latest information",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "Search keywords"},
                    "num_results": {"type": "integer", "description": "Number of results to return"}
                },
                "required": ["query"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "calculate",
            "description": "Perform mathematical calculations",
            "parameters": {
                "type": "object",
                "properties": {
                    "expression": {"type": "string", "description": "Mathematical expression"}
                },
                "required": ["expression"]
            }
        }
    }
]

# Tool implementation functions
def execute_tool(tool_name, arguments):
    if tool_name == "get_weather":
        city = arguments.get("city")
        # In a real project, call the weather API
        return f"{city} is sunny today, temperature 25°C, humidity 60%"
    elif tool_name == "search_web":
        query = arguments.get("query")
        return f"Search results for '{query}': found 3 relevant pieces of information..."
    elif tool_name == "calculate":
        expression = arguments.get("expression")
        try:
            result = eval(expression)
            return f"Calculation result: {expression} = {result}"
       except:
            return "Invalid expression"
    return "Unknown tool"

class ToolCallingAgent:
    def __init__(self, max_iterations=5):
        self.max_iterations = max_iterations
        self.messages = []

    def run(self, user_input):
        self.messages = [{
            "role": "system",
            "content": "You are an intelligent assistant that can use tools to complete tasks. Please think step by step and use tools appropriately."
        }, {
            "role": "user",
            "content": user_input
        }]

        for i in range(self.max_iterations):
            print(f"=== Round {i+1} ===")

            response = client.chat.completions.create(
                model="deepseek-chat",
                messages=self.messages,
                tools=tools
            )

            msg = response.choices[0].message

            # If the model decides to reply directly
            if msg.content and not msg.tool_calls:
                return msg.content

            # If the model decides to call a tool
            if msg.tool_calls:
                self.messages.append(msg)

                for tool_call in msg.tool_calls:
                    func_name = tool_call.function.name
                    func_args = json.loads(tool_call.function.arguments)
                    print(f"Calling tool: {func_name}({func_args})")

                    result = execute_tool(func_name, func_args)

                    self.messages.append({
                        "role": "tool",
                        "tool_call_id": tool_call.id,
                        "content": result
                    })

        return "Maximum iterations reached"

# Usage example
agent = ToolCallingAgent(max_iterations=5)
result = agent.run("What's the weather in Beijing today? Also, calculate 156 * 23 + 89 for me.")
print(f"Final reply: {result}")

re>

Best Practices for Tool Calling

Precise Tool Descriptions: The model's tool selection relies entirely on your tool descriptions. The clearer the description, the more accurate the selection. It is recommended that each tool description includes: function description, applicable scenarios, parameter details, and return value format.

Parameter Validation is Essential: The model may generate unreasonable parameters. Always perform parameter validation in execute_tool to prevent tool call failures due to parameter errors.

Feedback Errors to the Model: When a tool call fails, do not simply return an error message. Instead, return a structured error description to the model, giving it a chance to adjust its strategy. For example: "Weather API call failed: city name '北惊' does not exist, suggest using 'Beijing'."

Control the Number of Tools: Too many available tools increase the difficulty of model selection. It is recommended to keep the number of tools within 10, or group tools and provide them dynamically based on context.

Deep Integration of Tool Calling with Agent Loop

Tool calling is not a one-time operation but a continuous process integrated into the Agent Loop. The result of one tool call may trigger the next tool call—for example, first search for "latest papers in AI field", then based on the paper titles in the search results, call a PDF parsing tool to get paper details. This chained tool calling is a manifestation of the powerful capability of Agent Loop.

Want to orchestrate this skill chain yourself?

Open in Skill Chain →