Build a Small GPT-6.1 Sol Agent with One Verified Tool

Build a Small GPT-6.1 Sol Agent with One Verified Tool

Published on

0

views

This article demonstrates how to build a minimal, highly secure AI agent within a FastAPI service using the GPT-6.1 Sol model. It covers registering a single verified tool, enforcing hard stop conditions, validating arguments with Pydantic, and managing explicit permissions. This ensures the model only proposes actions while your application retains full control over execution and termination.

You have already seen that most features do not need an agent. Sometimes, however, the product really does require the model to decide whether a tool should be used and then act on the result. When that happens, the safest place to start is the smallest possible agent: one tool, hard stop conditions, full validation, and no hidden loops.

This article shows how to build that minimal agent inside a FastAPI service. The model may choose to call the single registered tool or may answer directly. Everything else—argument checking, permission, execution, and termination—stays in ordinary application code.

The Short Answer

Register one tool with a strict argument schema. Give the model a clear system prompt and a hard maximum of one tool call. Validate the tool name and arguments before any execution. Run the function only if the checks pass. Return the tool result or the model’s direct answer, then stop. Log every decision. Do not let the model continue after the tool has run unless you later prove that a second step is required.

Low-angle shot of a backend engineer reviewing a minimal single-tool agent code and configuration on a laptop.

What Product Problem This Solves

Some user requests genuinely need a lookup or side-effect before a useful answer can be produced. A pure deterministic workflow forces you to guess whether the tool is needed on every request. A tiny agent lets the model make that binary choice while you retain full control over whether the chosen action ever executes.

The goal is not autonomy. The goal is a single, observable decision point with every safety gate still in place.

Minimal Working Implementation

We will reuse the tool registry and validation patterns from earlier articles and wrap them in the smallest agent loop that still deserves the name.

Python

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

logger = logging.getLogger(__name__)

# ---------- One verified tool ----------

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:
    """Replace with a real, permission-checked lookup."""
    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. Use only when the user asks about an order.",
        "allowed": True,
    },
}

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

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

class AgentResponse(BaseModel):
    status: Literal["answered", "tool_executed", "rejected"]
    final_answer: Optional[str] = None
    tool_name: Optional[str] = None
    tool_arguments: Optional[dict] = None
    tool_result: Optional[dict] = None
    rejection_reason: Optional[str] = None
    finish_reason: str
    usage: dict
    request_id: Optional[str] = None

# ---------- The small agent ----------

@app.post("/v1/small-agent", response_model=AgentResponse)
async def small_agent(
    body: AgentRequest,
    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"]
    ]

    messages = [
        {
            "role": "system",
            "content": (
                "You are a helpful assistant with access to one tool: fetch_order_status. "
                "Use the tool only when the user is clearly asking about an order status. "
                "If the tool is not needed, answer directly. "
                "You may call the tool at most once. After the tool result is provided, give a final answer and stop."
            ),
        },
        {"role": "user", "content": body.user_message},
    ]

    total_usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
    request_id = None

    # ----- First model call (decide whether to use the tool) -----
    try:
        response = openai_client.chat.completions.create(
            model="gpt-6.1-sol",
            messages=messages,
            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")

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

    # Case 1 – model answers directly
    if not choice.message.tool_calls:
        answer = (choice.message.content or "").strip()
        if not answer:
            return AgentResponse(
                status="rejected",
                rejection_reason="Model returned empty answer",
                finish_reason=finish_reason,
                usage=total_usage,
                request_id=request_id,
            )
        logger.info("Agent answered directly, request_id=%s", request_id)
        return AgentResponse(
            status="answered",
            final_answer=answer,
            finish_reason=finish_reason,
            usage=total_usage,
            request_id=request_id,
        )

    # Case 2 – model requested the tool (we allow only the first call)
    tool_call = choice.message.tool_calls[0]
    tool_name = tool_call.function.name
    raw_args = tool_call.function.arguments

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

    if tool_name not in TOOL_REGISTRY or not TOOL_REGISTRY[tool_name]["allowed"]:
        return AgentResponse(
            status="rejected",
            tool_name=tool_name,
            rejection_reason=f"Tool not permitted: {tool_name}",
            finish_reason=finish_reason,
            usage=total_usage,
            request_id=request_id,
        )

    meta = TOOL_REGISTRY[tool_name]
    try:
        args = meta["args_model"].model_validate_json(raw_args)
    except ValidationError as e:
        logger.warning("Invalid tool arguments: %s", e)
        return AgentResponse(
            status="rejected",
            tool_name=tool_name,
            tool_arguments={"raw": raw_args},
            rejection_reason="Invalid tool arguments",
            finish_reason=finish_reason,
            usage=total_usage,
            request_id=request_id,
        )

    # Execute the single verified tool
    try:
        tool_result = meta["function"](**args.model_dump())
    except Exception as e:
        logger.error("Tool execution failed: %s", e)
        return AgentResponse(
            status="rejected",
            tool_name=tool_name,
            tool_arguments=args.model_dump(),
            rejection_reason=f"Execution failed: {e}",
            finish_reason=finish_reason,
            usage=total_usage,
            request_id=request_id,
        )

    # ----- Optional second model call to turn the tool result into a final answer -----
    messages.append(choice.message)  # includes the tool call
    messages.append(
        {
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": str(tool_result),
        }
    )

    try:
        response2 = openai_client.chat.completions.create(
            model="gpt-6.1-sol",
            messages=messages,
            temperature=0.0,
            max_tokens=300,
            timeout=25.0,
        )
    except (APITimeoutError, APIError) as e:
        logger.error("Second model call failed: %s", e)
        # Still return the tool result so the caller is not left empty-handed
        return AgentResponse(
            status="tool_executed",
            tool_name=tool_name,
            tool_arguments=args.model_dump(),
            tool_result=tool_result,
            final_answer=None,
            rejection_reason="Failed to generate final answer after tool execution",
            finish_reason=finish_reason,
            usage=total_usage,
            request_id=request_id,
        )

    total_usage["prompt_tokens"] += response2.usage.prompt_tokens
    total_usage["completion_tokens"] += response2.usage.completion_tokens
    total_usage["total_tokens"] += response2.usage.total_tokens

    final_answer = (response2.choices[0].message.content or "").strip()
    logger.info("Agent completed with tool, request_id=%s", request_id)

    return AgentResponse(
        status="tool_executed",
        final_answer=final_answer or None,
        tool_name=tool_name,
        tool_arguments=args.model_dump(),
        tool_result=tool_result,
        finish_reason=response2.choices[0].finish_reason or "unknown",
        usage=total_usage,
        request_id=request_id,
    )

This is the smallest agent that still answers the product question: “Can the model decide to use one verified tool while I keep full control over execution and termination?”

Hard Limits That Keep the Agent Small

  • Exactly one registered tool

  • Maximum of one tool call per request

  • Argument validation before any execution

  • Explicit permission flag in the registry

  • No further tool calls after the first result is returned

  • Clear status values so callers know what happened

These limits are not theoretical. They are the difference between a controllable feature and an open-ended loop that can burn tokens and produce surprising side effects.

Why the Second Model Call Is Optional

After the tool runs you often want a natural-language answer that incorporates the result. That second call is useful but not mandatory. If it fails, the endpoint still returns the tool result and a rejection reason for the missing final answer. The caller is never left with silence.

I once shipped a version that treated a failed second call as a total failure. Users who only needed the order status lost the data they had already paid for. Returning the tool result even when the final phrasing fails is the more honest behavior.

Logging and Observability

Log the decision path (direct answer vs tool request), the tool name, truncated arguments, validation outcome, and total token usage across both calls. The same task-persistence pattern from earlier articles can store the full trajectory so you can later answer “did the agent use the tool, and what did it receive?”

What Was Tested and What Remains Uncertain

I tested three paths: direct answers, valid tool calls, and invalid tool arguments. Each path returned the expected status and left clear log lines. Token usage was summed correctly across the optional second call.

I have not tested concurrent requests, model versions that emit multiple tool calls in one response, or long-running tool functions. Exact tool-calling response shapes, parallel-tool behavior, and rate-limit handling must still be verified against current official documentation. The stub fetch_order_status function is illustrative; real tools must enforce their own authorization.

When a Simpler Approach Is Enough

If the tool is required on every request, go back to the deterministic workflow. If the model never needs to choose, the agent adds unnecessary surface area. Use the small agent only when the binary decision “tool or no tool” is genuinely valuable and cannot be made by ordinary code.

Before adding more tools or multi-step loops, see whether one verified tool already solves the product problem. The extra complexity has to earn its place.

Practical Conclusion

Wide-angle shot of an engineer testing a secure FastAPI small-agent endpoint and structured logs in a dim environment.

A small GPT-6.1 Sol agent with one verified tool is ordinary request handling plus a single, well-guarded decision point. The model may propose the tool; your application still validates the name, the arguments, the permission, and the termination condition.

Start with the smallest version that can answer the product question. In this case the question is “Can the model decide to use one tool while I retain full control?” The code above is that version.

Build real applications. Verify every step.

Last updated:

Share:

Leave a comment

Related Articles

Do You Need an Agent? Start with a Deterministic Workflow
Agents & Automation |

Do You Need an Agent? Start with a Deterministic Workflow

This article argues that most AI features do not require complex, unpredictable agent loops. Instead, it advocates for starting with a deterministic workflow—a clear, sequential set of steps combining narrow model calls, ordinary Python validation, explicit error handling, and robust logging. This approach ensures lower latency, predictable token costs, and easier debugging before adding agentic complexity.

0
Add Stop Conditions, Retries, and Human Approval
Agents & Automation |

Add Stop Conditions, Retries, and Human Approval

This article explains how to transition a small AI agent into a production-ready application by adding three essential operational controls: hard stop conditions to prevent infinite loops, bounded exponential retries for transient network errors, and explicit human-approval gates for side-effecting tools. These measures ensure predictable behavior, auditable execution, and strict safety without relying on model prompts.

0