★ INDIE MAGAZINE · CULTURE · LONG-READS · NO ADS · NO ALGORITHMS ★ INDIE MAGAZINE · CULTURE · LONG-READS · NO ADS · NO ALGORITHMS ★ INDIE MAGAZINE · CULTURE · LONG-READS · NO ADS · NO ALGORITHMS ★ INDIE MAGAZINE · CULTURE · LONG-READS · NO ADS · NO ALGORITHMS ★

Build a Small Grok Agent That Uses One Verified Tool

This practical guide explains how to build a minimal, verifiable AI agent using the Grok API with exactly one tool. It emphasizes deterministic control flow, explicit argument validation, bounded loop turns, and clear execution logging. By keeping agent architecture small and observable, developers can harness agency without sacrificing reliability or inviting hidden failure modes.

Build a Small Grok Agent That Uses One Verified Tool

The short answer: if you truly need a little agency, give the model exactly one well-defined tool, keep the loop short and visible, require the application to validate and execute every tool call, and terminate as soon as you have a final answer or hit a clear limit. One tool. Explicit validation. Observable steps. That is the minimum viable agent worth building.

I have built larger agents that looked impressive in a demo and then became unmaintainable the moment real edge cases appeared. The version that survived in my own home-lab tooling is the small one: a single verified tool, a bounded loop, and logs that show every decision. This article walks through that minimal pattern so you can see agency without the usual fog.

What This Solves

You have already confirmed that a purely deterministic workflow is not enough, and you need the model to decide when to use a tool. By the end of this post you will have:

  • A complete, readable agent loop that uses exactly one tool

  • Clear separation between the model’s request and the application’s execution

  • Termination conditions that prevent runaway calls

  • Logging that makes every step auditable

This sits in Agents and Automation. It deliberately stays small so the later articles on failure recovery remain grounded in something you can actually understand.

Who Should Use This Approach

Developers who have worked through the earlier tool-calling and “Do You Need an Agent?” articles and have a concrete reason to let the model choose when to act. If you can still solve the problem with a fixed sequence of steps, prefer that. Agency is a cost; pay it only when necessary.

Design Rules for a Small Agent

  1. Exactly one tool (or one tightly related family of tools)

  2. The application always validates arguments before execution

  3. Every tool call and every result is logged

  4. The loop has a hard maximum number of model turns

  5. The agent stops when the model produces a normal final answer or when the limit is hit

  6. No hidden memory beyond the message list you control

These rules keep the system inspectable. If you need more tools or open-ended planning, you can grow from this base later—after you have measured that the growth is justified.

The One Tool

We will reuse a simple, verifiable tool: fetch the current UTC time. In real systems you would replace this with a search function, an internal status check, or whatever single action the agent actually needs. The important property is that the function is real, side-effecting (or at least observable), and under your control.

Python

from datetime import datetime, timezone

def get_current_utc_time() -> str:
    """Real function the application will execute."""
    now = datetime.now(timezone.utc).isoformat()
    print(f"EXECUTING get_current_utc_time → {now}")
    return now

Minimal Agent Implementation

A documentary photo of a laptop screen displaying terminal logs and AI agent turn execution details on a desk.

Python

import json
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
)

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_current_utc_time",
            "description": "Return the current time in UTC as an ISO 8601 string. Use when the user asks for the current time.",
            "parameters": {
                "type": "object",
                "properties": {},
                "additionalProperties": False,
            },
        },
    }
]

MAX_TURNS = 4  # hard safety limit

def run_agent(user_question: str) -> str:
    messages = [
        {
            "role": "system",
            "content": (
                "You are a precise assistant. "
                "You have access to exactly one tool: get_current_utc_time. "
                "Use it when you need the current UTC time. "
                "When you have enough information, give a final answer and stop."
            ),
        },
        {"role": "user", "content": user_question},
    ]

    for turn in range(1, MAX_TURNS + 1):
        print(f"\n=== MODEL TURN {turn} ===")
        completion = client.chat.completions.create(
            model="grok-4-1-fast-reasoning",  # verify current model
            messages=messages,
            tools=TOOLS,
            tool_choice="auto",
        )

        choice = completion.choices[0]
        finish_reason = choice.finish_reason
        print(f"finish_reason={finish_reason}")
        print(f"usage={completion.usage}")

        # Case 1: model produced a final answer
        if not choice.message.tool_calls:
            content = choice.message.content or ""
            print(f"FINAL CONTENT: {content}")
            return content

        # Case 2: model requested the tool
        messages.append(choice.message)  # keep the tool-call turn

        for tool_call in choice.message.tool_calls:
            name = tool_call.function.name
            raw_args = tool_call.function.arguments or ""
            print(f"TOOL_REQUEST name={name} id={tool_call.id} args={raw_args}")

            if name != "get_current_utc_time":
                result = f"Error: unknown tool '{name}'. Only get_current_utc_time is available."
            else:
                # Validate (even empty schema)
                try:
                    args = json.loads(raw_args) if raw_args else {}
                    if args:
                        result = "Error: this tool accepts no arguments."
                    else:
                        result = get_current_utc_time()
                except json.JSONDecodeError:
                    result = "Error: arguments were not valid JSON."

            print(f"TOOL_RESULT id={tool_call.id} → {result}")
            messages.append(
                {
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": result,
                }
            )

    # Safety exit
    return "Agent stopped: maximum turns reached without a final answer."

if __name__ == "__main__":
    answer = run_agent("What is the current UTC time? Please use the tool if needed.")
    print("\n=== AGENT ANSWER ===")
    print(answer)

Run it. You should see the model request the tool, the application execute it (with a visible log line), the result returned, and a final natural-language answer. If you ask a question that does not need the time, the model should answer directly on the first turn.

Why This Version Stays Understandable

  • Only one tool exists, so the model cannot wander into an unknown action space.

  • The application still owns validation and execution.

  • The message list is the only memory; there is no hidden scratchpad.

  • MAX_TURNS guarantees the loop cannot run forever.

  • Every turn prints finish_reason, usage, tool requests, and tool results.

If something goes wrong, the log tells you exactly which turn and which step failed.

Extending Without Losing Control

Useful, still-small extensions:

  • Replace the time tool with a real internal search or status check.

  • Add a second, equally well-validated tool only after the first one is solid.

  • Persist the message list for a single user session, still with a turn limit.

  • Add a cheap pre-check: if the question clearly does not need the tool, skip the agent and use a plain completion.

Resist the urge to add a general planner, a long-term memory store, or dynamic tool loading until you have evidence that the one-tool version is insufficient.

Common Ways Small Agents Go Wrong

  • Letting the model call tools that the application does not implement

  • Swallowing validation errors instead of returning them as tool results

  • Omitting the hard turn limit

  • Treating the first tool-call response as the final answer

  • Adding “just one more tool” until the decision space is no longer reviewable

  • Logging only the final answer and discarding the intermediate tool evidence

Any of these re-introduces the opacity that the small-agent pattern is meant to avoid.

A Note from the Home Lab

I keep a tiny agent that can decide whether to query a local status endpoint before answering questions about system health. It has exactly one tool. The loop is limited to three turns. Every execution of the real status function is logged. When it misbehaves—which is rare—I can open the log and see the exact tool request, the validation outcome, and the result that was returned. That visibility is the reason I am willing to keep the agent at all. Larger, less observable agents I built earlier were retired for the opposite reason.

A documentary photo of a small home lab server blinking with status LED lights in a tech workspace.

Practical Checklist

  • The agent has exactly one (or one tightly scoped) tool

  • Every tool call is validated before execution

  • The real function contains a log line that proves it ran

  • A hard maximum turn count is enforced

  • The message list is the only conversation memory

  • finish_reason, usage, tool requests, and tool results are all visible

  • There is a clear path back to a deterministic workflow if the agent proves unnecessary

When a Simpler Approach Is Better

If the model does not need to decide whether to use the tool—if your code already knows the tool should be used—then a deterministic tool-calling round-trip is simpler and usually better. Reach for even this small agent only when the decision “should I use the tool?” itself requires model judgment.

Closing

A small agent is just a bounded loop around capabilities you already understand: a model call, a tool request, validation, execution, and a final answer. Keep the tool count at one, keep the loop visible, and keep the termination conditions strict. You will get most of the benefit of agency and almost none of the usual mess.

Build the loop with one verified tool.
Explain every turn and every hand-off.
Verify that the real function ran and that the agent actually stops.

Build it. Explain it. Verify it.

Next we will look at what happens when the small agent fails—retries, timeouts, and the practical places to insert human review.

Comments

No comments yet — be the first to share a thought.

Leave a comment