Velamuvi AIAcademy

Lesson 2 of 9 · How It Works

Defining a Tool With JSON Schema

Describe tool arguments with JSON Schema: types, required fields, enums, ranges, arrays, nested objects and additionalProperties, generated from Python.

  • 5 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Write a tool's input schema with types and required fields
  • Constrain arguments with enum, minimum, maximum and additionalProperties
  • Describe arrays and nested objects
  • Generate a tool definition from a Python function's signature

The schema is the contract

A tool definition has a name, a description and an input schema. The schema tells the model exactly which arguments exist, what type each one is, which are required and what values are allowed. The tighter the schema, the fewer bad calls.

The building blocks

KeywordMeaningExample
typestring, number, integer, boolean, array or object"type": "integer"
descriptionWhat the argument means, with format and an example"Date in YYYY-MM-DD format"
enumOnly these values are allowed"enum": ["none", "1_hour", "1_day"]
minimum, maximumNumber range"minimum": 5, "maximum": 480
itemsWhat each element of an array looks like"items": {"type": "string"}
requiredArguments the model must always send["title", "date"]
additionalPropertiesfalse forbids arguments you didn't definefalse

Here's a complete definition for a calendar tool, and a summary of what the model is allowed to send:

Try it yourselfPython
import json

# A tool definition: everything the model needs to call create_event correctly
create_event = {
    "name": "create_event",
    "description": "Add an event to the user's calendar. Use only after the user has confirmed the details.",
    "input_schema": {
        "type": "object",
        "properties": {
            "title": {"type": "string", "description": "Short event title, e.g. 'Dentist'"},
            "date": {"type": "string", "description": "Date in YYYY-MM-DD format, e.g. 2026-12-03"},
            "start_time": {"type": "string", "description": "24-hour time HH:MM, e.g. 14:30"},
            "duration_minutes": {"type": "integer", "minimum": 5, "maximum": 480},
            "reminder": {"type": "string", "enum": ["none", "10_minutes", "1_hour", "1_day"]},
            "attendees": {
                "type": "array",
                "description": "Email addresses of people to invite",
                "items": {"type": "string"},
            },
        },
        "required": ["title", "date", "start_time"],
        "additionalProperties": False,
    },
}

schema = create_event["input_schema"]
print("Arguments the model may send:")
for name, spec in schema["properties"].items():
    extra = ""
    if "enum" in spec:
        extra = f" one of {spec['enum']}"
    elif "minimum" in spec:
        extra = f" from {spec['minimum']} to {spec['maximum']}"
    required = "required" if name in schema["required"] else "optional"
    print(f"  {name:<17} {spec['type']:<8} {required}{extra}")

print("\nAs JSON, about", len(json.dumps(create_event)), "characters sent with every request")

Every request carries this definition, so it costs tokens each time: a few hundred characters per tool is typical. That's one reason to keep schemas tight and tool lists focused.

Generate definitions from your functions

Writing schemas by hand gets repetitive. Many libraries build them from a Python function's signature, type hints and docstring. Here's the idea in a few lines:

Try it yourselfPython
import inspect
import json
from typing import Literal, get_args, get_origin

PY_TO_JSON = {str: "string", int: "integer", float: "number", bool: "boolean", list: "array"}

def tool_from_function(fn):
    """Build a tool definition from a Python function's signature and docstring."""
    properties, required = {}, []
    for name, param in inspect.signature(fn).parameters.items():
        hint = param.annotation
        if get_origin(hint) is Literal:
            properties[name] = {"type": "string", "enum": list(get_args(hint))}
        else:
            properties[name] = {"type": PY_TO_JSON[hint]}
        if param.default is inspect.Parameter.empty:
            required.append(name)          # no default value -> the model must provide it
    return {
        "name": fn.__name__,
        "description": inspect.getdoc(fn),
        "input_schema": {"type": "object", "properties": properties, "required": required},
    }

def search_products(query: str, max_price: float = 1000.0,
                    sort: Literal["relevance", "price_low", "price_high"] = "relevance"):
    """Search the shop's products by keyword. Returns up to 10 matches with name and price in euros."""

print(json.dumps(tool_from_function(search_products), indent=2))

The type hints became types, Literal[...] became an enum, the docstring became the description, and only query is required because the others have defaults. Libraries such as Pydantic do this more completely, including nested objects, number ranges and per-field descriptions, and some SDKs and frameworks can turn a decorated function into a tool directly.

Common mistakes

Practice exercise

Describe a thermostat tool's arguments with JSON Schema, including a range and a fixed set of choices.

Your solutionPython
import json

# Write the input schema for set_thermostat(room, temperature_c, mode):
#   room: string, required
#   temperature_c: number between 10 and 30, required
#   mode: one of "heat", "cool", "auto" (optional)
schema = {
    "type": "object",
    "properties": {},
    "required": [],
}

print(json.dumps(schema["properties"]["temperature_c"]))
print(json.dumps(schema["properties"]["mode"]))
print(schema["required"])
Knowledge check

Which schema keyword restricts an argument to a fixed list of allowed values?

Summary

  • The input schema is the contract between the model and your tool.
  • Use types, descriptions with formats, enum, ranges, items and required; set additionalProperties to false.
  • Tighter schemas mean fewer bad calls, and less validation code.
  • Definitions can be generated from typed Python functions; strict modes can guarantee schema-valid arguments.

Next: the full round trip of a tool call, message by message.

Finished reading? Tick it off to track your progress.