Velamuvi AIAcademy

Lesson 6 of 9 · Doing It Well

Validating Arguments

Never trust an LLM's tool arguments: validate types, required fields, enums and ranges, return errors the model can fix, use Pydantic and add permission checks.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain why tool arguments must be validated
  • Check arguments against a schema: required, types, enums, ranges and patterns
  • Return validation errors the model can act on
  • Add business rules and permission checks beyond the schema

Arguments are suggestions

A tool call is text generated by a model. Most of the time it's right, but it can have a missing field, a number sent as a word, a value outside the allowed range, or an argument you never defined. If the model read untrusted content, an argument could even be deliberately harmful.

A schema validator

This validator checks the most common JSON Schema rules and returns a list of readable problems:

Try it yourselfPython
import re

SCHEMA = {
    "type": "object",
    "properties": {
        "email": {"type": "string", "pattern": r"^[^@\s]+@[^@\s]+\.[a-z]{2,}$"},
        "plan": {"type": "string", "enum": ["free", "pro", "team"]},
        "seats": {"type": "integer", "minimum": 1, "maximum": 50},
    },
    "required": ["email", "plan"],
    "additionalProperties": False,
}
TYPES = {"string": str, "integer": int, "number": (int, float), "boolean": bool, "array": list, "object": dict}

def validate(args, schema):
    """Return a list of problems; an empty list means the arguments are valid."""
    errors = []
    for name in schema["required"]:
        if name not in args:
            errors.append(f"'{name}' is required")
    for name, value in args.items():
        spec = schema["properties"].get(name)
        if spec is None:
            if not schema.get("additionalProperties", True):
                errors.append(f"'{name}' is not an allowed argument")
            continue
        if not isinstance(value, TYPES[spec["type"]]) or (spec["type"] == "integer" and isinstance(value, bool)):
            errors.append(f"'{name}' must be of type {spec['type']}, got {value!r}")
            continue
        if "enum" in spec and value not in spec["enum"]:
            errors.append(f"'{name}' must be one of {spec['enum']}, got {value!r}")
        if "minimum" in spec and value < spec["minimum"]:
            errors.append(f"'{name}' must be at least {spec['minimum']}")
        if "maximum" in spec and value > spec["maximum"]:
            errors.append(f"'{name}' must be at most {spec['maximum']}")
        if "pattern" in spec and not re.match(spec["pattern"], value):
            errors.append(f"'{name}' doesn't look valid: {value!r}")
    return errors

# Arguments as different model replies might send them
for args in [
    {"email": "[email protected]", "plan": "pro", "seats": 3},
    {"email": "ana@example", "plan": "premium"},
    {"plan": "team", "seats": "five"},
    {"email": "[email protected]", "plan": "free", "seats": 0, "discount": 50},
]:
    problems = validate(args, SCHEMA)
    print("OK " if not problems else "BAD", args)
    for p in problems:
        print("      ", p)

Each bad call gets specific messages: an email without a domain ending, a plan that doesn't exist, a missing field, a word where a number belongs, a value below the minimum, and an extra argument (discount) that nobody defined. Sent back as a tool result, these messages let the model correct its call on the next turn.

In real projects: Pydantic

Writing validators by hand is a good way to understand them, but in real code a library does it better. Pydantic models describe the arguments once, generate the JSON Schema for the model, and validate incoming arguments:

from typing import Literal
from pydantic import BaseModel, Field, ValidationError

class CreateAccount(BaseModel):
    email: str = Field(pattern=r"^[^@\s]+@[^@\s]+\.[a-z]{2,}$", description="The user's email address")
    plan: Literal["free", "pro", "team"]
    seats: int = Field(default=1, ge=1, le=50)
    model_config = {"extra": "forbid"}

print(CreateAccount.model_json_schema())          # the JSON Schema to send to the model

try:
    args = CreateAccount.model_validate({"email": "ana@example", "plan": "premium"})
except ValidationError as error:
    print(error.error_count(), "problems:")
    for e in error.errors():
        print("  ", e["loc"], e["msg"])

model_json_schema() produces the schema to send in the tool definition, and model_validate checks the model's arguments, giving precise error messages you can return as the tool result. (The jsonschema package validates against a plain schema dictionary in a similar way.)

Beyond the schema

A schema can't express everything. After it passes, check the rules of your business and your security:

  • Business rules: the date is in the future; the refund isn't more than the order total; the product is in stock.
  • Permissions: the order belongs to this user; the user's plan allows this action.
  • Safety: never insert arguments into SQL, shell commands or file paths directly; use parameters and allow-lists.

Common mistakes

Practice exercise

Validate a model's tool arguments before running the tool: a number range and a fixed set of choices.

Your solutionPython
def check(args):
    errors = []
    # quantity must be an integer from 1 to 10; size must be "S", "M" or "L".
    # Add a message to errors for each problem, exactly like:
    # quantity must be from 1 to 10
    # size must be S, M or L
    return errors

print(check({"quantity": 3, "size": "M"}))
print(check({"quantity": 12, "size": "XL"}))
Knowledge check

A model's tool call passes schema validation. Is the call safe to run?

Summary

  • Tool arguments are model-generated text: always validate before running.
  • Check required fields, types, enums, ranges, patterns and unknown fields, and return clear errors.
  • Use Pydantic (or jsonschema) in real projects.
  • Add business rules, permission checks and safe handling of SQL, shells and paths.

Next: handling errors when tools fail.

Finished reading? Tick it off to track your progress.