Prompt Engineering

Mastering Tool Use in LLMs: Building Capable AI Agents with Function Calling

In the rapidly evolving landscape of Large Language Models (LLMs), the ability to generate coherent text is just the beginning. The true power of modern AI systems lies in their capacity to interact with the external world. This capability, known as "tool use" or "function calling," transforms static text generators into dynamic agents that can query databases, execute code, send emails, or control smart devices. For intermediate and advanced developers, mastering tool use is no longer optional—it is a fundamental requirement for building production-grade AI applications.

Understanding the Mechanics of Tool Use

At its core, tool use is a structured communication protocol between the LLM and external software components. When an LLM determines that a task requires external data or action, it does not execute the action itself. Instead, it generates a structured output—typically a JSON object—that specifies which tool should be called and what arguments should be passed.

Think of the LLM as a sophisticated brain that can reason about its limitations. If asked for the current stock price of a company, the model cannot "know" this real-time data. Therefore, it recognizes the need for an external API and outputs a request to call a get_stock_price function. The application developer's job is to intercept this request, execute the function, and feed the result back to the model to complete the user's request.

Defining Tools with JSON Schema

To enable tool use, you must first define the tools available to the model. Most major LLM providers (such as OpenAI, Anthropic, and Google) use JSON Schema to define these tools. A well-defined schema acts as the contract between your application and the model.


{
  "name": "get_weather",
  "description": "Get the current weather for a specific location",
  "parameters": {
    "type": "object",
    "properties": {
      "location": {
        "type": "string",
        "description": "The city and state, e.g. San Francisco, CA"
      },
      "unit": {
        "type": "string",
        "enum": ["celsius", "fahrenheit"],
        "description": "Temperature unit"
      }
    },
    "required": ["location"]
  }
}

Notice the importance of clear descriptions. The LLM relies on these descriptions to decide when to use the tool. Ambiguous descriptions lead to incorrect tool selection or missing parameters.

The Tool Use Loop

Implementing tool use requires a loop pattern in your application code. The general workflow is as follows:

  1. Initial Prompt: The user sends a message to the LLM.
  2. Decision: The LLM decides if it needs to use a tool or can answer directly.
  3. Tool Call: If a tool is needed, the LLM returns a tool call object with arguments.
  4. Execution: Your backend executes the specified function with the provided arguments.
  5. Feedback: The result of the function execution is appended to the conversation history.
  6. Final Response: The LLM processes the result and generates the final response for the user.

Here is a simplified Python example using a hypothetical SDK:


def run_agent(user_input):
    messages = [{"role": "user", "content": user_input}]
    
    while True:
        response = llm.chat(messages, tools=tool_definitions)
        
        # Check if the model wants to use a tool
        if response.has_tool_calls:
            for tool_call in response.tool_calls:
                # Execute the tool
                result = execute_tool(tool_call.name, tool_call.arguments)
                
                # Append tool result to messages
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": str(result)
                })
            # Loop back to let the model process the result
            continue
        else:
            # No more tools needed, return final answer
            return response.content

Best Practices for Production Systems

When deploying tool use in production, consider the following best practices:

  • Limit Tool Scope: Do not expose all available functions to the LLM. Only provide tools relevant to the current task context to reduce hallucination risk and improve accuracy.
  • Error Handling: Always catch exceptions during tool execution. If a tool fails, feed the error message back to the LLM. This allows the model to adjust its approach or inform the user politely.
  • Validation: Validate tool arguments before execution. The LLM may generate invalid data types or out-of-range values, even with schema constraints.
  • Security: Treat LLM-generated tool arguments as untrusted input. Never pass them directly into SQL queries or shell commands without sanitization.

Conclusion

Tool use is the bridge that connects the linguistic capabilities of LLMs with the real-world actions needed for practical automation. By carefully defining tools, implementing robust loops, and adhering to security best practices, developers can build AI agents that are not only intelligent but also reliable and useful. As models continue to improve, the complexity of tool orchestration will grow, making these foundational skills increasingly critical for the next generation of AI developers.

Share: