Tool Definition and Schemas

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 10 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Module: Tool Use and Environment

Lesson: Tool Definition and Schemas

Introduction: The Bridge Between Reasoning and Action

In the rapidly evolving landscape of artificial intelligence, the ability for a model to "reason" is only half the battle. While large language models excel at processing text, summarizing information, and generating creative content, they are inherently limited by the static data they were trained on. To move beyond this limitation, we must equip these systems with the ability to interact with the world. This is where "Tool Use" comes into play. By providing a model with a defined set of tools—such as calculators, database queries, or API endpoints—we transform a passive text generator into an active agent capable of performing work.

However, a model cannot simply "guess" how to use a tool. If you ask a model to fetch weather data without a clear structure, it might produce an unstructured sentence that a computer cannot parse. To bridge the gap between human language and machine execution, we use "Tool Definitions" and "Schemas." A tool definition acts as a formal contract between the agent and the environment. It tells the model exactly what the tool does, what parameters it requires, and what format the output will take. Mastering the creation of these schemas is the fundamental skill required to build reliable, scalable AI agents. Without precise schemas, your agents will fail to execute tasks, leading to hallucinations, runtime errors, and broken workflows.


Not read yet

Understanding the Anatomy of a Tool Definition

A tool definition is essentially a structured description of a function. When we provide a tool to an AI model, we are essentially giving it a manual that describes how to perform a specific action. The industry standard for defining these tools is JSON Schema, a vocabulary that allows you to annotate and validate JSON documents. By using JSON Schema, we ensure that the model understands the data types (integers, strings, booleans, arrays) and the constraints (required fields, value ranges) associated with each tool.

Every tool definition typically consists of four primary components:

  1. Name: A unique identifier for the tool. This should be concise and descriptive, such as get_weather or query_database.
  2. Description: A clear, natural language explanation of what the tool does. The model uses this description to decide when to use the tool. If the description is vague, the model will struggle to determine if the tool is relevant to the user's request.
  3. Parameters (The Schema): A structured object that defines the inputs the tool expects. This is the most critical part, as it defines the "input shape" the model must adhere to.
  4. Return Type (Optional but Recommended): An explanation of what the tool will return. While not always strictly enforced by the model's interface, providing this helps the model understand the context of the result it will receive.

Callout: Why Schema Matters Think of the schema as the "API specification" for your AI. Just as a web developer relies on a Swagger or OpenAPI document to understand how to interact with a backend service, the AI model relies on the tool schema to understand how to interact with your code. If the schema is poorly defined, the model will pass the wrong arguments, leading to failed function calls.


Not read yet

Designing Effective Schemas: A Step-by-Step Guide

To create a tool that is both reliable and usable by a model, you should follow a systematic approach. Let’s walk through the creation of a tool designed to retrieve current stock market prices.

Step 1: Define the Purpose

Before writing any code, define the scope. Our tool, get_stock_price, should take a stock ticker symbol and return the current price. We should also consider if it needs optional parameters, such as a currency conversion or a specific exchange.

Step 2: Draft the JSON Schema

We will structure the parameters using the JSON Schema standard. Notice how we define the type for each field and mark mandatory fields as required.

{
  "name": "get_stock_price",
  "description": "Retrieves the current market price for a given stock ticker symbol.",
  "parameters": {
    "type": "object",
    "properties": {
      "ticker": {
        "type": "string",
        "description": "The stock ticker symbol, e.g., 'AAPL' or 'GOOGL'."
      },
      "currency": {
        "type": "string",
        "enum": ["USD", "EUR", "GBP"],
        "description": "The currency in which to return the price."
      }
    },
    "required": ["ticker"]
  }
}

Step 3: Implement the Logic

Once the schema is defined, you must map it to an actual function in your programming language of choice (e.g., Python). The function name must match the name defined in the schema to ensure the orchestration layer can route the call correctly.

def get_stock_price(ticker: str, currency: str = "USD"):
    # Simulated API call
    prices = {"AAPL": 175.50, "GOOGL": 140.20}
    price = prices.get(ticker.upper(), 0.0)
    return {"ticker": ticker, "price": price, "currency": currency}

Tip: Descriptive Descriptions The description fields within your schema are not just for documentation; they are active prompts. If you have a parameter like limit, don't just write "the limit." Write "the maximum number of search results to return, between 1 and 50." This helps the model make informed decisions about what values are valid before it even attempts the call.


Not read yet

Best Practices for Tool Integration

Building tools for AI is a unique challenge because you are dealing with a non-deterministic actor. Unlike a standard unit test where input A always results in output B, an LLM might interpret your tool description in ways you didn't anticipate. Follow these best practices to maintain stability.

1. Keep Tool Names Unique and Semantic

Use clear, verb-noun naming conventions. For example, use send_email instead of email_helper. If you have multiple versions of a tool, use versioning in the name (e.g., send_email_v2) rather than relying on the model to guess which one is current.

2. Use Enums for Constrained Inputs

If a parameter only accepts a specific set of values, always use the enum property in your JSON schema. This prevents the model from hallucinating invalid input values. For example, if you have a sort_order parameter, define it as ["asc", "desc"]. This forces the model to choose from the provided list, drastically reducing errors.

3. Provide Defaults for Optional Parameters

If a tool has parameters that are not strictly required, provide sensible defaults. If the model doesn't have enough information to fill a field, it will often omit it. If your code expects that field but doesn't have a default, the tool execution will crash.

4. Validate Inputs at the Runtime Level

Never assume that the model will perfectly adhere to your schema. Even with strict prompting, models can occasionally output malformed JSON or invalid types. Always implement a validation layer that checks the arguments passed by the model against your schema before passing them to the underlying function.

5. Handle Errors Gracefully

When a tool fails—perhaps the database is down or the ticker symbol doesn't exist—do not let the code throw a raw exception that kills your agent. Catch the error and return a helpful message to the model. For instance, return {"error": "Ticker symbol not found"} rather than a stack trace. This allows the agent to "see" the failure and potentially try a different approach or inform the user.


Not read yet

Common Pitfalls and How to Avoid Them

Even experienced developers encounter issues when integrating tools. Here are the most common mistakes and how to sidestep them.

  • The "Vague Description" Trap: If you describe a tool as "a tool to help with data," the model will have no idea when to use it. Be specific: "A tool to calculate the moving average of a list of numbers over a specified window size."
  • Overloading Tools: Do not try to make one "God Tool" that does everything. If you have a tool called process_data that takes 20 different parameters, the model will become confused. Break this down into smaller, specialized tools like calculate_mean, calculate_median, and sort_data.
  • Ignoring Token Limits: Tool definitions consume tokens. If you provide 500 tools to a model, you will quickly hit context limits and increase latency. Only provide the tools that are relevant to the current conversation context.
  • Lack of Feedback Loops: If a tool modifies a system state (like deleting a file), ensure the tool returns a confirmation message. Without this, the model might assume the action failed and try to repeat it, leading to unintended consequences.

Callout: The "Human-in-the-Loop" Distinction For high-stakes tools—such as those that send emails, execute financial transactions, or delete database records—always implement a "Human-in-the-Loop" (HITL) step. The model should generate the tool call, but the system should pause and request user confirmation before executing the actual function.


Not read yet

Comparison: Schema Definition Approaches

Different frameworks handle tool definitions in varying ways. Below is a comparison of how different approaches impact development.

Approach Pros Cons
Manual JSON Schema Maximum control, standard across all providers. Verbose, easy to make syntax errors.
Library-Based (e.g., Pydantic) Type-safe, auto-generates schema from code. Requires dependency on specific libraries.
Annotation/Decorator Clean, readable code, tightly coupled. Can be harder to export to other platforms.

Example: Using Pydantic for Schema Generation

Using a library like Pydantic is often preferred in the Python ecosystem because it allows you to define your tools as Python classes. This ensures that your code and your schema are always in sync.

from pydantic import BaseModel, Field

class WeatherRequest(BaseModel):
    city: str = Field(..., description="The city name, e.g., 'London'")
    unit: str = Field("celsius", description="The unit of temperature, either 'celsius' or 'fahrenheit'")

# The library can then automatically convert this class into a JSON schema
# that the AI model can understand.

This approach eliminates the need to manually write JSON, which is prone to missing commas or mismatched brackets. It also provides runtime validation, ensuring the data passed into your functions matches your models.


Not read yet

Advanced Concepts: Multi-Step Tool Chaining

As you advance in building AI agents, you will likely encounter scenarios where a single tool call is insufficient. For instance, if a user asks for the "current exchange rate of the stock I bought yesterday," the agent must perform two steps:

  1. Call get_user_purchases to find the ticker.
  2. Call get_stock_price with that ticker.

This is known as "Tool Chaining." The model identifies that it needs to call a tool, receives the output, and then decides which tool to call next. To support this, your tool definitions must be clear enough that the model can understand the dependency between tool outputs.

Designing for Chaining

To make chaining effective:

  • Consistent Output Formats: Ensure all your tools return structured data (JSON). If one tool returns a string and another returns a complex object, the model will struggle to extract the necessary information.
  • Concise Results: Only return the data necessary for the next step. If your tool returns a massive JSON blob of metadata, you will waste tokens and confuse the model.

Not read yet

Best Practices for Error Handling and Feedback

When an agent uses a tool, it expects a response. If the tool fails, the error message becomes part of the conversation history. It is vital that this error message is readable by the model, not just by a developer.

Bad Error Message: 500 Internal Server Error: Connection reset by peer. The model will not know what to do with this. It might try to call the tool again, resulting in an infinite loop of failures.

Good Error Message: Error: The weather service is currently unavailable. Please try again later or ask for the weather in a different region. The model can interpret this. It can then inform the user, "I'm sorry, I can't check the weather in London right now because the service is down. Would you like me to check Paris instead?"


Security Considerations for Tool Use

Tool use introduces significant security risks. If you give a model the ability to run SQL queries or access a filesystem, you must ensure it cannot perform unauthorized actions.

  1. Principle of Least Privilege: The credentials or API keys provided to the tool should have the absolute minimum permissions required. If a tool only needs to read a database, it should not have write or delete permissions.
  2. Input Sanitization: Never pass raw input from the model directly into a shell command or a raw SQL query. Always use parameterized queries or input validation to prevent injection attacks.
  3. Sandboxing: Whenever possible, run your tool executions in a restricted environment, such as a Docker container or a serverless function with limited network access.

Not read yet

Troubleshooting Common Issues

If your agent is consistently failing to call the right tool, or calling it with the wrong arguments, use this checklist:

  • Check the System Prompt: Does your system prompt explicitly tell the agent that it has access to tools? Some models need a reminder: "You have access to the following tools: [Tool list]."
  • Analyze the Model's Reasoning: If your model supports "Chain of Thought" (CoT), look at its reasoning process. It might be saying, "I need to check the weather, but I don't know the city." This tells you that your prompt or your tool description is missing context.
  • Verify the JSON Format: Use a linter to ensure your tool definitions are valid JSON. A single missing quote can cause the entire tool-calling mechanism to fail silently.
  • Temperature Settings: If the model is being too creative and hallucinating arguments, lower the temperature parameter (e.g., set it to 0.1 or 0.2). This makes the model more deterministic and likely to stick to the provided schema.

Not read yet

Summary and Key Takeaways

Mastering tool definition and schemas is the bridge between building a simple chatbot and building a powerful, functional agent. By treating your tools as formal software contracts, you create a system that is predictable, maintainable, and robust.

Key Takeaways:

  1. Schemas are Contracts: Treat your JSON Schema definitions as the source of truth for how the model communicates with your backend code.
  2. Description is Prompting: The description fields in your tool schema are critical for the model's decision-making process. Be precise and descriptive to avoid misinterpretation.
  3. Input Validation is Mandatory: Never trust the output of a model. Validate all arguments against your schema before executing any code to prevent runtime errors and security vulnerabilities.
  4. Use Enums and Defaults: Constrain the input space as much as possible using enums and provide sensible defaults to help the model make better decisions.
  5. Error Messages are User-Facing: Design your tool error messages so that the model can understand them, allowing it to recover from failures gracefully.
  6. Security First: Always adhere to the principle of least privilege. Assume that an agent could be tricked into using a tool maliciously and build your systems accordingly.
  7. Iterate and Test: Tool use is an iterative process. Monitor the logs, identify where the model is struggling, and refine your tool descriptions to improve performance over time.

By following these principles, you will be well on your way to building sophisticated AI agents that can reliably interact with the real world, providing value far beyond simple text generation. Start small, define your schemas clearly, and always build with the assumption that the agent is an active, evolving participant in your system.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.