Tool Argument Validation

Ma Mahalakshmi V Updated 19 Sep 2026
8 min read ·Lesson 159 of 224

Validating tool arguments before execution

Unit 8, Lesson 5 introduced the idea that a tool call's arguments must be treated as untrusted — the model generates them from a probabilistic process shaped partly by a prompt that may itself contain adversarial content, so they cannot be assumed correct just because they arrive as neatly structured JSON. That lesson focused on wrapping tool execution in error handling and returning curated error messages back to the model. This lesson goes further: it builds a complete validation discipline for tool arguments, applied before any execution happens at all, so that a malformed, out-of-range, or maliciously crafted argument is rejected outright rather than reaching your business logic.

Why "the model returned valid JSON" is not enough

When you define a tool, you give the model a JSON schema describing its expected arguments, and the API does real work to encourage the model to return arguments matching that shape. But schema conformance and safety are different things. A schema saying "amount": {"type": "number"} guarantees you get a number — it does not guarantee that number is positive, within a sane range, or appropriate for the specific account making the request. A schema saying "file_path": {"type": "string"} guarantees a string — it does not guarantee that string points somewhere your application is allowed to read.

This gap exists because a JSON schema describes shape, not business rules. Closing that gap is the job of an explicit validation layer that runs after the arguments are parsed and before your tool's actual logic executes.

The four layers of tool-argument validation

1. Type checking. Confirm each argument is actually the type your code expects, even though the schema requested it — defensively, because you should not assume every consumer of your tool definitions (including future code you write) upholds the schema perfectly.

2. Allow-lists for categorical or identifier-like values. When an argument should be one of a known, finite set of values (a filename, a resource ID, an action name), check it against an explicit allow-list rather than accepting any string. This is stricter, and safer, than a schema enum alone, because it lets you change the allow-list independently of the tool's public schema and apply additional context (like per-user permissions, covered in Lesson 9).

3. Range and bound checks. Numeric arguments — amounts, quantities, page counts, timeouts — need explicit minimum and maximum bounds appropriate to your domain, not just "is this a number."

4. Structural sanitization. String arguments that will be used to construct a file path, a URL, or a query need to be checked for patterns that indicate an attempt to escape the intended scope — most classically, path traversal sequences like ../.

A worked example: a read_file tool

Consider a tool that lets the model read a file from a fixed, sanctioned directory of documents — for example, a knowledge base the assistant is allowed to search.

import os

ALLOWED_BASE_DIR = "/srv/app/knowledge_base"


class ToolValidationError(Exception):
    """Raised when tool arguments fail validation, before execution."""


def validate_read_file_args(args: dict) -> str:
    """
    Validates arguments for a read_file tool.
    Returns the safe, absolute path to read on success.
    Raises ToolValidationError on any validation failure.
    """
    if "file_path" not in args:
        raise ToolValidationError("Missing required argument: file_path")

    file_path = args["file_path"]
    if not isinstance(file_path, str):
        raise ToolValidationError("file_path must be a string")

    if not file_path or len(file_path) > 256:
        raise ToolValidationError("file_path has an invalid length")

    # Reject path traversal and absolute-path attempts outright.
    if ".." in file_path or file_path.startswith("/") or file_path.startswith("~"):
        raise ToolValidationError("file_path must be a relative path with no traversal")

    # Resolve against the allowed base directory and confirm the result
    # still lives inside it — the strongest guarantee against traversal.
    candidate = os.path.normpath(os.path.join(ALLOWED_BASE_DIR, file_path))
    if not candidate.startswith(os.path.normpath(ALLOWED_BASE_DIR) + os.sep):
        raise ToolValidationError("file_path resolves outside the allowed directory")

    return candidate

Notice this function does two related but distinct checks: it rejects obviously suspicious substrings (.., a leading /) as a fast first filter, and then it independently resolves the final path with os.path.normpath and verifies the result is still inside ALLOWED_BASE_DIR. The second check is the one that actually matters for security — string-pattern blocklists are notoriously easy to bypass with encoding tricks or unusual path constructions, while confirming the final resolved path's location is a structural guarantee that doesn't depend on anticipating every possible bypass string.

def test_valid_relative_path_is_accepted():
    result = validate_read_file_args({"file_path": "guides/setup.md"})
    assert result == os.path.join(ALLOWED_BASE_DIR, "guides/setup.md")
    print("PASS: a normal relative path resolves inside the allowed directory")


def test_path_traversal_is_rejected():
    for attempt in ["../../etc/passwd", "guides/../../../etc/passwd", "/etc/passwd"]:
        try:
            validate_read_file_args({"file_path": attempt})
            raised = False
        except ToolValidationError:
            raised = True
        assert raised, f"expected rejection for: {attempt}"
    print("PASS: path traversal and absolute-path attempts are rejected")


def test_missing_argument_is_rejected():
    try:
        validate_read_file_args({})
        raised = False
    except ToolValidationError:
        raised = True
    assert raised
    print("PASS: a missing file_path argument is rejected")


test_valid_relative_path_is_accepted()
test_path_traversal_is_rejected()
test_missing_argument_is_rejected()

A worked example: range checks for a financial action

Range checks matter most for tools that have real-world consequences. Consider a tool that lets an assistant apply a discount to an order — an action with direct financial impact if abused.

def validate_apply_discount_args(args: dict, order_total: float) -> float:
    """
    Validates arguments for an apply_discount tool.
    Returns the validated discount percentage on success.
    """
    if "discount_percent" not in args:
        raise ToolValidationError("Missing required argument: discount_percent")

    discount = args["discount_percent"]
    if not isinstance(discount, (int, float)) or isinstance(discount, bool):
        raise ToolValidationError("discount_percent must be a number")

    if discount < 0 or discount > 25:
        # Business rule: agents may never apply more than a 25% discount
        # autonomously, regardless of what the model "decides" is reasonable.
        raise ToolValidationError("discount_percent must be between 0 and 25")

    max_discount_value = order_total * (discount / 100)
    if max_discount_value > 500:
        # A hard ceiling on absolute discount value, independent of percentage,
        # to bound worst-case impact on very large orders.
        raise ToolValidationError("Resulting discount exceeds the $500 cap")

    return discount

The isinstance(discount, bool) check exists because in Python, bool is a subclass of intTrue and False pass an isinstance(x, int) check and would silently become 1 and 0 if not explicitly excluded. This is a small but real gotcha worth knowing when validating numeric arguments that arrive as loosely-typed JSON values.

The two range checks here — a percentage ceiling and a separate absolute-value ceiling — illustrate an important idea: the model's job is to decide the tool should be called and with roughly what values; your code's job is to enforce the actual business limits, and those limits are things only your application knows. No prompt engineering substitutes for this. The model does not reliably know your company's discount policy is exactly 25%, nor should you rely on a prompt instruction as your only enforcement of a hard financial ceiling.

def test_discount_within_bounds_is_accepted():
    result = validate_apply_discount_args({"discount_percent": 10}, order_total=1000)
    assert result == 10
    print("PASS: an in-bounds discount percentage is accepted")


def test_discount_percentage_ceiling_is_enforced():
    try:
        validate_apply_discount_args({"discount_percent": 40}, order_total=1000)
        raised = False
    except ToolValidationError:
        raised = True
    assert raised
    print("PASS: a discount above the percentage ceiling is rejected")


def test_absolute_discount_cap_is_enforced():
    # 20% of a $10,000 order is $2,000 — well above the $500 absolute cap,
    # even though 20% is within the percentage ceiling.
    try:
        validate_apply_discount_args({"discount_percent": 20}, order_total=10000)
        raised = False
    except ToolValidationError:
        raised = True
    assert raised
    print("PASS: the absolute dollar cap catches large orders that pass the percent check")


test_discount_within_bounds_is_accepted()
test_discount_percentage_ceiling_is_enforced()
test_absolute_discount_cap_is_enforced()

That last test is the most important one in this lesson: it demonstrates why a single validation rule is often insufficient. A percentage-only check would have let a 20% discount through on any order size, even though a 20% discount on a $10,000 order is a very different risk than on a $50 order. Real validation logic usually needs more than one independent constraint, each catching a different failure mode.

Where validation fits relative to authorization

Validation, as covered in this lesson, answers "are these arguments well-formed and within acceptable bounds for this tool, in general?" It does not answer "is this specific user allowed to invoke this tool at all?" That is a distinct question, covered in Lesson 9 of this unit, and it should be checked separately — typically before validation even runs, since there's no reason to validate arguments for an action the caller isn't permitted to take in the first place.

Common Mistakes

  • Trusting the JSON schema alone as validation. The schema shapes what the model is encouraged to produce; it is not enforced server-side the way a validation function is, and it cannot express business rules like "no more than a 25% discount" or "must resolve inside this directory."
  • Using string blocklists as the only defense against path or injection-style attacks. Blocking ".." alone misses encoded variants and unusual constructions; always pair pattern checks with a structural verification (like confirming the resolved path's final location).
  • Validating only the "obviously dangerous" argument and skipping the rest. Every argument that influences a side effect deserves a check — a quantity field is just as capable of causing harm (through an absurd value) as a file_path field.

Best Practices

  • Validate before execution, not during or after — reject invalid arguments before any tool logic runs, and return a clear, curated error (per Unit 8, Lesson 5) so the model can attempt a corrected call.
  • Use allow-lists over blocklists wherever the set of valid values is knowable in advance.
  • Enforce business-rule ceilings (percentages, absolute amounts, rate limits) in code, never rely on the model to self-limit based on prompt instructions alone.
  • Write a validation test for every rejection path you intend to enforce, including the "obviously fine" cases, so you can refactor validation logic later with confidence.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Tool Argument Validation and get answers drawn from it.

Signed-in readers only.