Build a Safe Tool-Calling Workflow with FastAPI

Build a Safe Tool-Calling Workflow with FastAPI

Published on

0

views

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.

You can already request structured JSON and validate it before saving. The next practical step is letting the model suggest a function call—and then deciding, in ordinary application code, whether that call should ever run.

This article shows a minimal, safe tool-calling workflow inside a FastAPI service. The model proposes; the application validates arguments, checks permissions, executes only what is allowed, and records the outcome. No autonomous agents, no hidden loops, no “the model will figure it out.”

The Short Answer

Expose a small set of explicitly registered tools. Ask the model to return a tool call in a structured form. Validate the tool name and every argument against a schema and a permission list. Execute the function only after those checks pass. Log the proposal, the validation result, and the execution outcome. Treat every tool call as a request that must still be approved by your code.

Low-angle shot of a backend engineer reviewing FastAPI tool registry and security validation code on a laptop.

What Product Problem This Solves

Many useful features need the model to choose an action: look up a record, calculate a value, format a report, or trigger a side-effect. Letting the model emit free-text instructions and then scraping them is brittle. Letting the model call arbitrary code is dangerous.

A safe tool-calling workflow gives you the flexibility of model-selected actions while keeping every execution behind ordinary validation, permission checks, and logging. The model suggests; the application still decides.

Minimal Working Implementation

We will add one carefully controlled tool to the existing FastAPI service. The example uses a simple “fetch_order_status” function so the pattern is concrete. Replace it with any deterministic function you actually need.

Python

import logging
from typing import Any, Callable, Dict, Literal, Optional
from pydantic import BaseModel, Field, ValidationError
from fastapi import FastAPI, HTTPException, Depends
from openai import OpenAI, APIError, APITimeoutError

logger = logging.getLogger(__name__)

# ---------- Tool registry ----------

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

def fetch_order_status(order_id: str) -> dict:
    """Deterministic stub – replace with real lookup."""
    # In real code this would hit a database or internal service
    return {
        "order_id": order_id,
        "status": "shipped",
        "estimated_delivery": "2026-11-05",
    }

TOOL_REGISTRY: Dict[str, Dict[str, Any]] = {
    "fetch_order_status": {
        "function": fetch_order_status,
        "args_model": OrderStatusArgs,
        "description": "Fetch the current status of an order by its ID.",
        "allowed": True,  # explicit permission flag
    },
}

# ---------- Request / response models ----------

class ToolCallRequest(BaseModel):
    user_message: str = Field(..., min_length=5, max_length=2000)

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
    finish_reason: str
    usage: dict
    request_id: Optional[str] = None

# ---------- The endpoint ----------

@app.post("/v1/tool-call", response_model=ToolCallResponse)
async def tool_call(
    body: ToolCallRequest,
    openai_client: OpenAI = Depends(get_client),
):
    tools_for_model = [
        {
            "type": "function",
            "function": {
                "name": name,
                "description": meta["description"],
                "parameters": meta["args_model"].model_json_schema(),
            },
        }
        for name, meta in TOOL_REGISTRY.items()
        if meta["allowed"]
    ]

    try:
        response = openai_client.chat.completions.create(
            model="gpt-6.1-sol",
            messages=[
                {
                    "role": "system",
                    "content": (
                        "You may call the provided tools when they help answer the user. "
                        "Only use the exact tool names and argument shapes given. "
                        "If no tool is needed, answer normally."
                    ),
                },
                {"role": "user", "content": body.user_message},
            ],
            tools=tools_for_model,
            tool_choice="auto",
            temperature=0.0,
            max_tokens=300,
            timeout=25.0,
        )
    except APITimeoutError:
        raise HTTPException(status_code=504, detail="Model request timed out")
    except APIError as e:
        logger.error("Model API error: %s", str(e))
        raise HTTPException(status_code=502, detail="Upstream model error")

    choice = response.choices[0]
    finish_reason = choice.finish_reason or "unknown"
    usage = {
        "prompt_tokens": response.usage.prompt_tokens,
        "completion_tokens": response.usage.completion_tokens,
        "total_tokens": response.usage.total_tokens,
    }

    # No tool call requested
    if not choice.message.tool_calls:
        logger.info("No tool called, finish_reason=%s", finish_reason)
        return ToolCallResponse(
            status="no_tool_called",
            finish_reason=finish_reason,
            usage=usage,
            request_id=response.id,
        )

    # We only handle the first tool call in this minimal version
    tool_call = choice.message.tool_calls[0]
    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,
    )

    # ----- Safety checks -----
    if tool_name not in TOOL_REGISTRY:
        reason = f"Unknown tool: {tool_name}"
        logger.warning(reason)
        return ToolCallResponse(
            status="rejected",
            tool_name=tool_name,
            rejection_reason=reason,
            finish_reason=finish_reason,
            usage=usage,
            request_id=response.id,
        )

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

    # Validate arguments against the registered schema
    try:
        args = meta["args_model"].model_validate_json(raw_args)
    except ValidationError as e:
        reason = f"Invalid arguments: {e}"
        logger.warning(reason)
        return ToolCallResponse(
            status="rejected",
            tool_name=tool_name,
            arguments={"raw": raw_args},
            rejection_reason=reason,
            finish_reason=finish_reason,
            usage=usage,
            request_id=response.id,
        )

    # ----- Execute only after all checks pass -----
    try:
        result = meta["function"](**args.model_dump())
    except Exception as e:
        reason = f"Execution failed: {e}"
        logger.error(reason)
        return ToolCallResponse(
            status="rejected",
            tool_name=tool_name,
            arguments=args.model_dump(),
            rejection_reason=reason,
            finish_reason=finish_reason,
            usage=usage,
            request_id=response.id,
        )

    logger.info("Tool %s executed successfully", tool_name)
    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: “Can the model suggest an action while my application retains full control over whether and how it runs?”

The Four Gates Every Tool Call Must Pass

  1. Known name – the tool must exist in the registry.

  2. Explicit permission – the registry entry must be marked allowed.

  3. Valid arguments – every field must pass the Pydantic model.

  4. Successful execution – the function itself must not raise.

Any failure stops the workflow and returns a clear rejection. The model never gets a second chance inside the same request unless you deliberately add that logic later.

I once watched a prototype that trusted the model’s tool name and arguments without a registry check. A single malformed response attempted to call a function that did not exist and crashed the worker. The four gates above turn that class of failure into a logged rejection instead of an exception.

Why the Registry Lives in Application Code

The list of tools, their schemas, and their permission flags belong in your service, not in a prompt. Prompts can be ignored or creatively reinterpreted. A dictionary that your code consults cannot. When you need to disable a tool, you change one boolean; you do not have to re-prompt the model and hope it notices.

Logging That Actually Helps

Log the tool name, a truncated version of the raw arguments, the validation outcome, and the final status. In early development it is useful to keep the full argument payload (gated behind a debug flag). In production the logs should stay short and free of sensitive values.

The same task-persistence pattern from earlier articles can store the tool name, arguments, and result (or rejection reason) so you can answer “what did the model try to do last Tuesday?” without digging through application logs.

Wide-angle shot of an engineer monitoring structured tool-calling request logs and warning messages in a dim operations room.

What Was Tested and What Remains Uncertain

I tested the endpoint with messages that correctly trigger the tool, messages that request an unknown tool, messages that supply invalid arguments, and messages that need no tool at all. Each path returned the expected status and left a clear log line.

I have not tested concurrent tool calls, multi-tool responses, or every possible argument injection attempt. Exact tool-calling parameter names, strict-mode behavior, and rate-limit handling must still be verified against current official documentation before production use. The stub fetch_order_status function is illustrative only; real implementations must apply their own authorization and data-access controls.

When a Simpler Approach Is Enough

If the feature only needs structured data extraction, stay with the previous structured-output endpoint. Tool calling is worth the extra surface area only when the model must choose among real side-effecting or lookup actions.

Before adding an agent or a multi-step loop, see whether a single validated tool call already solves the product problem. The extra complexity has to earn its place.

Practical Conclusion

A safe tool-calling workflow with FastAPI is ordinary request handling plus four explicit gates: known tool, permitted tool, valid arguments, successful execution. The model can propose the action; your application still has to validate and execute it.

Start with the smallest version that can answer the product question. In this case the question is “Can the model suggest a function call while I retain full control over whether it runs?” The code above is that version.

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
What to Do When a Tool Call Has Invalid Arguments

What to Do When a Tool Call Has Invalid Arguments

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.

0