What to Do When a Tool Call Has Invalid Arguments

What to Do When a Tool Call Has Invalid Arguments

Published on

0

views

This article explains how a FastAPI service should handle invalid tool-call arguments from language models. It covers rejecting bad arguments instead of auto-correcting, implementing Pydantic validation checks, structuring error responses, and logging exact failure details. This ensures predictable application behavior and maintains strict control over execution boundaries during AI tool interactions.

The model decided to call a tool. The name is correct. The arguments are not.

Maybe a required field is missing. Maybe a string is the wrong shape. Maybe a number is out of range. The schema you registered is clear; the model simply did not follow it.

This article covers the practical responses available to a FastAPI service when tool-call arguments fail validation. We stay inside a single request. No automatic multi-step repair loops, no hidden agents, no “just ask the model again and hope.”

The Short Answer

Reject the call. Log the exact validation errors, the tool name, and a truncated copy of the raw arguments. Return a clear status to the caller so the rest of the application can decide what to do next. Do not execute the function. Do not silently coerce bad values. Treat an invalid argument list as a failed request, not as a prompt for improvisation.

Low-angle shot of a backend engineer reviewing a failed FastAPI tool-call validation on a laptop.

What Product Problem This Solves

Invalid arguments are common. Models occasionally omit fields, invent extra ones, or produce values that look plausible but violate the constraints you declared. If the application executes the call anyway, you risk:

  • database errors

  • incorrect side effects

  • leaked internal exceptions

  • silent data corruption

A deliberate rejection path turns those failures into observable, recoverable events instead of production incidents.

Minimal Working Implementation

We will reuse the tool-calling endpoint from the previous article and focus on the validation-failure branch. The key addition is structured logging of the validation errors and a consistent response shape that callers can rely on.

Python

from pydantic import BaseModel, Field, ValidationError
from typing import Any, Dict, List, Literal, Optional
from fastapi import HTTPException
import logging
import json

logger = logging.getLogger(__name__)

class OrderStatusArgs(BaseModel):
    order_id: str = Field(..., min_length=3, max_length=32, pattern=r"^[A-Za-z0-9\-_]+$")

# ... TOOL_REGISTRY and other setup from previous article ...

class ToolCallResponse(BaseModel):
    status: Literal["executed", "rejected", "no_tool_called"]
    tool_name: Optional[str] = None
    arguments: Optional[dict] = None
    result: Optional[dict] = None
    rejection_reason: Optional[str] = None
    validation_errors: Optional[List[dict]] = None  # structured details
    finish_reason: str
    usage: dict
    request_id: Optional[str] = None


def format_validation_errors(exc: ValidationError) -> List[dict]:
    """Turn Pydantic errors into a simple, loggable list."""
    return [
        {
            "loc": list(err["loc"]),
            "msg": err["msg"],
            "type": err["type"],
        }
        for err in exc.errors()
    ]


@app.post("/v1/tool-call", response_model=ToolCallResponse)
async def tool_call(
    body: ToolCallRequest,
    openai_client: OpenAI = Depends(get_client),
):
    # ... model call and extraction of tool_call as before ...

    tool_name = tool_call.function.name
    raw_args = tool_call.function.arguments

    logger.info(
        "Model requested tool=%s raw_args=%s request_id=%s",
        tool_name,
        raw_args[:200],
        response.id,
    )

    if tool_name not in TOOL_REGISTRY:
        return ToolCallResponse(
            status="rejected",
            tool_name=tool_name,
            rejection_reason=f"Unknown tool: {tool_name}",
            finish_reason=finish_reason,
            usage=usage,
            request_id=response.id,
        )

    meta = TOOL_REGISTRY[tool_name]
    if not meta["allowed"]:
        return ToolCallResponse(
            status="rejected",
            tool_name=tool_name,
            rejection_reason=f"Tool not permitted: {tool_name}",
            finish_reason=finish_reason,
            usage=usage,
            request_id=response.id,
        )

    # ----- Argument validation -----
    try:
        args = meta["args_model"].model_validate_json(raw_args)
    except ValidationError as e:
        errors = format_validation_errors(e)
        reason = "Invalid tool arguments"
        logger.warning(
            "Tool argument validation failed | tool=%s | errors=%s | raw_args=%s",
            tool_name,
            json.dumps(errors),
            raw_args[:300],
        )
        return ToolCallResponse(
            status="rejected",
            tool_name=tool_name,
            arguments={"raw": raw_args},
            rejection_reason=reason,
            validation_errors=errors,
            finish_reason=finish_reason,
            usage=usage,
            request_id=response.id,
        )

    # ----- Execution only after validation passes -----
    try:
        result = meta["function"](**args.model_dump())
    except Exception as e:
        logger.error("Tool execution failed: %s", e)
        return ToolCallResponse(
            status="rejected",
            tool_name=tool_name,
            arguments=args.model_dump(),
            rejection_reason=f"Execution failed: {e}",
            finish_reason=finish_reason,
            usage=usage,
            request_id=response.id,
        )

    return ToolCallResponse(
        status="executed",
        tool_name=tool_name,
        arguments=args.model_dump(),
        result=result,
        finish_reason=finish_reason,
        usage=usage,
        request_id=response.id,
    )

This is the smallest version that still answers the product question: “What happens when the model’s arguments are wrong?”

Why Rejection Is the Default

Executing a function with invalid arguments is almost never the right choice. Coercing values (turning a missing field into a default, or a bad string into an empty string) hides the problem and can produce incorrect side effects. Asking the model to “try again” inside the same request raises cost and latency without a guarantee of improvement.

A clear rejection gives the caller—whether that is a frontend, another service, or a human—enough information to decide the next step. Sometimes the right next step is to show the user an error. Sometimes it is to reformulate the original request. Sometimes it is to log the case for later prompt improvement. None of those decisions require the tool to run with bad data.

What to Log

At minimum log:

  • tool name

  • structured validation errors (location, message, type)

  • a truncated copy of the raw arguments

  • request id and token usage

I keep the full raw arguments only behind a debug flag or in a secure reject store. Application logs should stay short and free of sensitive values. The structured error list is far more useful for later analysis than a single concatenated string.

What Not to Do in the First Version

  • Do not automatically retry the model with the validation errors appended to the prompt unless you have measured that the retry actually improves the acceptance rate.

  • Do not coerce or “repair” arguments on the fly.

  • Do not fall back to a different tool or a free-text answer without an explicit product decision.

  • Do not expose internal exception details to external callers.

Each of those behaviors can be added later if data shows they are necessary. They are not required for a safe baseline.

A Small Personal Note

Early in one project I let invalid arguments through with a warning log and a best-effort default. The defaults were wrong often enough that we spent more time cleaning up the resulting data than we would have spent simply rejecting the calls. Rejection is not harsh; it is honest. The model can suggest the arguments; your application still has to decide whether they are usable.

What Was Tested and What Remains Uncertain

I tested the rejection path with missing fields, wrong types, values that violate the regex, and extra unexpected fields. Each case returned status="rejected", a populated validation_errors list, and a clear log line. Valid argument sets continued to execute normally.

I have not measured the long-term rate of argument validation failures under real traffic, nor have I tested every possible malformed JSON the model might emit. Exact tool-calling response shapes and error-field details must still be verified against current official documentation. Real tool implementations must apply their own authorization checks in addition to the argument schema.

When a Simpler Approach Is Enough

If the tool takes no arguments, or the arguments are so simple that validation almost never fails, the extra error-detail fields may be unnecessary. The moment you have more than one required field or any non-trivial constraint, the structured rejection path becomes the smaller useful version.

Before adding an agent that “repairs” its own arguments, see whether clearer tool descriptions and ordinary validation already keep the failure rate acceptable. The extra complexity has to earn its place.

Wide-angle shot of an engineer monitoring tool-calling error logs and service status in a dim operations room.

Practical Conclusion

When a tool call arrives with invalid arguments, reject it. Log the precise validation errors, return a consistent status, and leave the decision about what to do next to the caller. Do not execute. Do not coerce. Do not silently recover inside the same request.

Start with the smallest version that can answer the product question. In this case the question is “What does the application do when the model’s arguments are wrong?” The rejection path above is that version.

The model can propose the call; your application still has to verify every argument before anything runs.

Build real applications. Verify every step.

Last updated:

Share:

Leave a comment

Related Articles

Structured Outputs with GPT-6.1 Sol

Structured Outputs with GPT-6.1 Sol

This article demonstrates how to request and validate structured JSON outputs from the GPT-6.1 Sol model using FastAPI and Pydantic. It highlights minimal implementation details, schema enforcement, application-side validation, and essential logging practices, helping you turn unstructured model responses into reliable, typed application data without unnecessary agent complexity.

1
Validate Model-Generated Data Before Saving It

Validate Model-Generated Data Before Saving It

This article explains why schema validation alone is not enough to ensure AI data quality. It demonstrates how to implement a practical second validation layer using business rules and Pydantic validators in Python. By checking domain logic, checking for placeholder text, and logging rejections before database persistence, you can keep bad data out of your system.

0
Build a Safe Tool-Calling Workflow with FastAPI

Build a Safe Tool-Calling Workflow with FastAPI

This article demonstrates how to build a safe, production-ready tool-calling workflow inside a FastAPI service. It covers essential security practices including explicit tool registries, permission flags, Pydantic argument validation, and strict four-gate execution checks, ensuring the model only proposes actions while your application retains full control over execution and logging.

0