★ 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 ★

Grok Tool Calling: A Complete Request-to-Execution Example

This practical guide explains how to implement tool calling with the Grok API in Python. It clarifies the strict boundary between model requests and application execution, walking through a minimal end-to-end example with validation, logging, and state management. Designed for developers, it ensures reliable tool execution and robust multi-turn conversational workflows.

Grok Tool Calling: A Complete Request-to-Execution Example

The short answer: a tool call is a structured request from the model, not proof that your function ran. You send a description of the available tools, the model may return one or more tool_calls, your application validates the arguments, executes the real function, and then sends the result back. Only after that second round does the model produce a final answer. Keep those steps separate and the whole pattern becomes understandable.

I still remember the first time a tool call “worked” in a demo and then silently did nothing in the real script. The response contained a perfect-looking tool_calls array. My code printed “tool called” and continued. The function itself had never executed. That gap between “the model asked for the tool” and “the application actually ran it” is the entire point of this article.

We will walk through a complete, minimal example: define a tool, send the request, inspect the tool call, execute the function, return the result, and obtain the final answer. Every step stays observable.

What This Solves

You want to see a full tool-calling round-trip in Python without magic. By the end of this post you will have:

  • A clear definition of what a tool call is and is not

  • A minimal working example with one verified tool

  • The exact places where validation and execution must happen

  • A logging habit that shows the boundary between model request and application action

This is the foundation for every later article on invalid arguments, structured output, and small agents.

Who Should Use This Approach

Developers who already know how to make a basic Grok chat request and are ready to add a single external action. If you have not yet authenticated or inspected a normal response, start with the earlier Grok API Starting Point articles. If you are trying to decide whether you need an agent at all, the later “Do You Need an Agent?” post will be more relevant.

The Mental Model (Keep It Strict)

  1. You describe the tools the model is allowed to request.

  2. The model may return a tool_calls array instead of (or in addition to) normal content.

  3. Your application decides whether to honor each call, validates the arguments, and executes the real function.

  4. You send the tool result back to the model in a new message.

  5. The model then produces a final natural-language answer (or another tool call).

A tool call is a request. Execution is an application decision. Never collapse the two.

Minimal Working Example

We will give the model one simple tool: a function that returns the current UTC time. The example uses the OpenAI-compatible client for familiarity; the same flow works with the official xAI SDK.

A documentary photo of a laptop screen displaying terminal logs and tool execution records on a messy desk.

Python

import json
import os
from datetime import datetime, timezone
from openai import OpenAI

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

# 1. Define the tool the model is allowed to request
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_utc_time",
            "description": "Return the current time in UTC as an ISO 8601 string.",
            "parameters": {
                "type": "object",
                "properties": {},
                "additionalProperties": False,
            },
        },
    }
]

def get_current_utc_time() -> str:
    """The real function the application will execute."""
    return datetime.now(timezone.utc).isoformat()

# 2. First request: let the model decide whether to call the tool
messages = [
    {
        "role": "system",
        "content": "You are a precise assistant. Use the provided tool when you need the current UTC time.",
    },
    {
        "role": "user",
        "content": "What is the current UTC time? Please use the tool.",
    },
]

print("=== FIRST REQUEST ===")
completion = client.chat.completions.create(
    model="grok-4-1-fast-reasoning",  # verify current recommended model
    messages=messages,
    tools=tools,
    tool_choice="auto",
)

choice = completion.choices[0]
print("finish_reason:", choice.finish_reason)
print("content:", choice.message.content)
print("tool_calls:", choice.message.tool_calls)

# 3. Application decides to execute
if choice.message.tool_calls:
    # Append the assistant message that requested the tool
    messages.append(choice.message)

    for tool_call in choice.message.tool_calls:
        fn_name = tool_call.function.name
        arguments = tool_call.function.arguments  # JSON string

        print(f"\n=== APPLICATION EXECUTION ===")
        print(f"model requested: {fn_name}")
        print(f"raw arguments: {arguments}")

        if fn_name == "get_current_utc_time":
            # Validate (even for an empty schema)
            try:
                args = json.loads(arguments) if arguments else {}
            except json.JSONDecodeError:
                result = "Error: arguments were not valid JSON"
            else:
                # Execute the real function
                result = get_current_utc_time()
                print(f"executed → {result}")
        else:
            result = f"Error: unknown tool {fn_name}"

        # 4. Send the tool result back
        messages.append(
            {
                "role": "tool",
                "tool_call_id": tool_call.id,
                "content": result,
            }
        )

    # 5. Second request: model produces the final answer
    print("\n=== SECOND REQUEST (with tool result) ===")
    final = client.chat.completions.create(
        model="grok-4-1-fast-reasoning",
        messages=messages,
        tools=tools,
    )
    final_choice = final.choices[0]
    print("finish_reason:", final_choice.finish_reason)
    print("final content:", final_choice.message.content)
    print("usage (second call):", final.usage)
else:
    print("Model did not request a tool. Content was:", choice.message.content)

Run the script. You should see the model request the tool, the application execute it, and the model then answer with the real timestamp.

What Each Step Actually Proves

  • The first completion’s tool_calls array proves only that the model asked for the tool.

  • The print statement inside get_current_utc_time (or a log line) proves that the application ran the function.

  • The second completion’s content proves that the model saw the tool result and incorporated it.

If any of those three pieces of evidence is missing, the round-trip is incomplete.

Validation Is Not Optional

Even with a tool that takes no arguments, parse the JSON. For tools that do take arguments, validate types, required fields, and ranges before execution. A schema-valid tool call can still contain nonsense values. Schema validation is necessary; it is never sufficient by itself.

Logging the Boundary

On every tool-using call, log at least:

  • The tool name the model requested

  • The raw arguments string

  • Whether validation passed

  • Whether the function was actually executed

  • The value (or error) that was returned to the model

  • The finish_reason of both the first and second completions

That log line is the difference between “it works on my machine” and “I can prove what happened.”

Common First Mistakes

  • Treating the presence of tool_calls as proof of execution

  • Forgetting to append both the assistant tool-call message and the tool-result message

  • Sending the tool result with the wrong tool_call_id

  • Letting the model call a tool that the application does not actually implement

  • Skipping argument validation because “the schema already checked it”

  • Printing only the final content and discarding the intermediate tool-call evidence

All of these produce demos that look fine and production behavior that is impossible to debug.

A Note from the Home Lab

One of my early internal tools used a tool call to fetch a short status summary from a local service. The model requested the tool correctly. My code logged “tool called” and then used a cached value instead of executing the function. For two weeks the dashboard looked reasonable while the underlying service was intermittently down. The moment I added an explicit log line inside the real function, the discrepancy became obvious. The model had done its job. The application had quietly skipped the work.

That experience is why every tool example on this site includes a visible execution step.

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

Practical Checklist

  • Tools are described with clear names and parameter schemas

  • The first response is inspected for tool_calls before any execution

  • Arguments are parsed and validated before the real function runs

  • The real function contains a log or print that proves it executed

  • Both the assistant tool-call message and the tool-result message are appended

  • The second completion is checked for a normal finish_reason and final content

  • Failure paths (unknown tool, bad JSON, execution exception) return a clear message to the model

When a Simpler Approach Is Better

If the task can be solved with a single ordinary chat completion and no external action, do not add a tool. Tool calling introduces a second round-trip, argument validation, and error handling. Use it only when the application genuinely needs to perform an action or fetch data that the model cannot know.

Closing

Tool calling is a conversation with a clear division of labor. The model requests. The application validates and executes. The model then answers with the benefit of the real result. Keep those responsibilities separate, log the boundary, and the pattern stays reliable.

Build the request that offers the tool.
Explain every message that travels between model and application.
Verify that the function actually ran and that the final answer reflects the real result.

Build it. Explain it. Verify it.

Next we will look at the common case where the model returns a tool call but the function never runs—and how to diagnose exactly where the chain broke.

Comments

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

Leave a comment