Skip to content
Build a Self-Verifying Agent With Grok 4.6 in Python — ContentBuffer guide

Build a Self-Verifying Agent With Grok 4.6 in Python

K
Kodetra Technologies··9 min read Intermediate

Summary

Grok 4.6 self-verifies during long agent runs. Build a Python coding agent that checks its own work.

Build a Self-Verifying Agent With Grok 4.6 in Python

xAI shipped Grok 4.6 on August 12, 2026, and the headline for developers is not the benchmark table. It is a behavior change: during long agentic runs, the model now verifies its own work before moving to the next step. It runs the test it just wrote, re-reads the file it just edited, and self-corrects instead of barreling ahead on an unchecked assumption. xAI calls this self-verification, and it is the single most useful thing to build around.

That matters because the expensive failure mode of coding agents is confident wrongness. An agent that edits three files, declares victory, and hands you a broken build costs you more than the tokens it burned. Grok 4.6 leans against that by default, and it does it at $2 per million input / $6 per million output tokens, roughly a fifth of what GPT-5.6 Sol charges on output while tying it on the Artificial Analysis Intelligence Index at 61.

In this guide you will build a small but real coding agent that fixes a bug across files, writes a test, runs it, and only stops once the test passes. The whole thing runs on the OpenAI-compatible xAI endpoint, so if you have ever called chat.completions.create, you already know 90% of the API. We will wire up tools, run the loop, and lean into self-verification with the right system prompt and reasoning effort.


What you will build

A command-line agent that receives a task like "fix the bug in stats.py" and then works autonomously: it reads files, edits them, writes a test, executes that test in a subprocess, reads the failure, and iterates. You supply three tools; Grok 4.6 decides when to call each one. The self-verification behavior shows up as the model choosing to run the test itself before it tells you it is done.

  • read_file — return the contents of a file so the model can inspect code before editing.
  • write_file — overwrite a file with new contents (the edit action).
  • run_python — execute a Python file in a subprocess and return stdout, stderr, and the exit code (the verification action).

Prerequisites

  • Python 3.10 or newer.
  • An xAI API key from console.x.ai. Set it as the XAI_API_KEY environment variable.
  • The OpenAI Python SDK: pip install openai>=1.40. We use it because the xAI endpoint is OpenAI-compatible.
  • A scratch directory you are comfortable letting a program write into and execute code from. Never point this at a real project on the first run.
pip install "openai>=1.40"
export XAI_API_KEY="xai-...your key..."

One safety note up front: this agent executes model-generated Python on your machine. That is the point of the run_python tool, but it also means you should run it inside a container, a VM, or at minimum a throwaway directory. Do not hand it your home folder.


Step 1 — Point the OpenAI client at xAI

The xAI API speaks the OpenAI wire format. You create a normal OpenAI client and change two things: the base URL and the API key. The model name is grok-4.6.

import os
from openai import OpenAI

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

MODEL = "grok-4.6"

# A quick smoke test to confirm auth and the model name.
resp = client.chat.completions.create(
    model=MODEL,
    messages=[{"role": "user", "content": "Reply with exactly: ready"}],
)
print(resp.choices[0].message.content)

Expected output:

ready

If you get a 404 on the model, double-check the string is grok-4.6 (with the dot, not a dash). If you get a 401, your key is missing or wrong. Everything else in this guide is standard Chat Completions.


Step 2 — Define the tools

Tools are declared as JSON schemas and implemented as plain Python functions. The schema is what Grok 4.6 sees; the function is what actually runs when the model asks for it. Keep descriptions concrete, because the quality of tool calls tracks the quality of your descriptions.

import subprocess, pathlib

WORKDIR = pathlib.Path("./agent_workspace").resolve()
WORKDIR.mkdir(exist_ok=True)

def _safe(path: str) -> pathlib.Path:
    # Keep the agent inside WORKDIR; reject path traversal.
    p = (WORKDIR / path).resolve()
    if not str(p).startswith(str(WORKDIR)):
        raise ValueError(f"path escapes workspace: {path}")
    return p

def read_file(path: str) -> str:
    return _safe(path).read_text()

def write_file(path: str, content: str) -> str:
    p = _safe(path)
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(content)
    return f"wrote {len(content)} bytes to {path}"

def run_python(path: str) -> str:
    proc = subprocess.run(
        ["python", str(_safe(path))],
        capture_output=True, text=True, timeout=30, cwd=WORKDIR,
    )
    return json.dumps({
        "exit_code": proc.returncode,
        "stdout": proc.stdout[-4000:],
        "stderr": proc.stderr[-4000:],
    })

IMPL = {"read_file": read_file, "write_file": write_file, "run_python": run_python}

TOOLS = [
    {"type": "function", "function": {
        "name": "read_file",
        "description": "Read and return the full text contents of a file in the workspace.",
        "parameters": {"type": "object", "properties": {
            "path": {"type": "string", "description": "Path relative to the workspace root."}
        }, "required": ["path"]},
    }},
    {"type": "function", "function": {
        "name": "write_file",
        "description": "Overwrite a file with new contents. Creates the file if it does not exist.",
        "parameters": {"type": "object", "properties": {
            "path": {"type": "string"},
            "content": {"type": "string", "description": "The full new file contents."}
        }, "required": ["path", "content"]},
    }},
    {"type": "function", "function": {
        "name": "run_python",
        "description": "Run a Python file in a subprocess. Returns exit_code, stdout, stderr as JSON. Use this to verify your changes before finishing.",
        "parameters": {"type": "object", "properties": {
            "path": {"type": "string", "description": "Path to the .py file to execute."}
        }, "required": ["path"]},
    }},
]

Notice the last line of the run_python description: it explicitly tells the model this is how it verifies work. Grok 4.6 already tends to self-verify, but naming the tool's purpose in the schema nudges it to reach for the test rather than declaring success blind.


Step 3 — The agent loop

The loop is the classic tool-calling cycle: send messages, if the model returns tool calls, execute them, append the results, and send again. You stop when the model returns a normal text message with no tool calls. The system prompt is where you turn self-verification from a tendency into a rule.

SYSTEM = """You are a coding agent working inside a sandboxed workspace.
Rules:
1. Inspect files with read_file before you edit them.
2. After any edit, write a small test file and run it with run_python.
3. If a test fails, read the error, fix the code, and run the test again.
4. Only give a final answer once run_python reports exit_code 0.
Be concise in your final message."""

def run_agent(task: str, max_steps: int = 12) -> str:
    messages = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": task},
    ]
    for step in range(max_steps):
        resp = client.chat.completions.create(
            model=MODEL,
            messages=messages,
            tools=TOOLS,
            tool_choice="auto",
            temperature=0,
            # xAI extension: raise this to "high" for long, multi-file tasks.
            extra_body={"reasoning_effort": "high"},
        )
        msg = resp.choices[0].message
        messages.append(msg.model_dump(exclude_none=True))

        if not msg.tool_calls:
            return msg.content  # model is done

        for call in msg.tool_calls:
            name = call.function.name
            args = json.loads(call.function.arguments)
            try:
                result = IMPL[name](**args)
            except Exception as e:
                result = f"ERROR: {e}"
            print(f"  [step {step}] {name}({args}) -> {str(result)[:120]}")
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": str(result),
            })
    return "Stopped: hit max_steps without a final answer."

Two details worth calling out. temperature=0 keeps edits deterministic, which you want for code. And reasoning_effort is an xAI-specific field passed via extra_body; Grok 4.6 accepts settings from low through xhigh. For a one-file fix, the default is fine. For a multi-file refactor, bump it to high so the model spends more of its budget planning and verifying.


Step 4 — A worked example: fix a real bug

Seed the workspace with a buggy function. The classic off-by-one median bug: it uses integer-ish indexing that breaks on even-length lists and never sorts a copy, mutating the caller's input.

BUGGY = """
def median(nums):
    nums.sort()              # mutates the caller's list
    mid = len(nums) / 2      # float index; wrong for even lengths
    return nums[mid]
"""

# Create the buggy file the agent will fix.
write_file("stats.py", BUGGY)

answer = run_agent(
    "There is a bug in stats.py. median([3,1,2,4]) should return 2.5 but it "
    "crashes. Fix median so it works for odd and even length lists and does "
    "not mutate the input. Prove it with a test."
)
print("\n=== FINAL ===\n" + answer)

A representative run (your exact trace will vary, but the shape is consistent):

  [step 0] read_file({'path': 'stats.py'}) -> def median(nums): ...
  [step 1] write_file({'path': 'stats.py', 'content': '...'}) -> wrote 214 bytes to stats.py
  [step 2] write_file({'path': 'test_stats.py', 'content': '...'}) -> wrote 190 bytes
  [step 3] run_python({'path': 'test_stats.py'}) -> {"exit_code": 0, "stdout": "ok\n", ...}

=== FINAL ===
Fixed. median now sorts a copy and averages the two middle values on even-length
lists. Test covers [3,1,2,4] -> 2.5 and [5,1,3] -> 3, and confirms the input
list is unchanged. run_python reported exit_code 0.

The interesting step is step 3. Nothing in your Python code forced the model to run the test. Grok 4.6 chose to call run_python and gate its final answer on exit_code 0, because the system prompt told it to and self-verification is baked into how the model works during long runs. That is the payoff: the loop does not declare success on faith.


Common pitfalls and gotchas

The 200K pricing cliff. Grok 4.6 has a 500K context window, but pricing is banded. Below 200K prompt tokens you pay $2 input / $6 output per million. Cross 200K in a single request and the rate doubles to $4 / $12 for every token in that request, not just the overflow. Long agent transcripts creep toward that line. Trim old tool outputs from the message history, or use the model's context compaction, before you drift over 200K.

Append the assistant message before the tool results. The API requires the assistant message that contains tool_calls to appear in the history immediately before the matching tool messages. If you execute tools but forget to append msg first, the next request 400s with a mismatched-tool-call error. The loop above appends msg.model_dump(...) first for exactly this reason.

Every tool call needs a reply. If the model returns three tool calls, you must append three tool messages with matching tool_call_id values before the next turn, even for calls that errored. Send the error text back as the tool result; do not silently drop it. A missing reply also produces a 400.

Guard against runaway loops. Self-verification reduces confident-wrong endings but can produce verify-fix-verify cycles on genuinely hard bugs. The max_steps cap is your circuit breaker. Log each step so you can see whether the model is converging or spinning.

reasoning_effort is an xAI extra, not standard OpenAI. Pass it through extra_body, not as a top-level keyword, or the OpenAI SDK will reject it. If you route the same code through a gateway that does not forward unknown fields, the setting is silently ignored, so verify it reaches xAI when latency or cost surprises you.

Sandbox the run_python tool. You are executing model-generated code. Use a container or VM, set the subprocess timeout (we used 30s), and keep the path guard so the agent cannot read or write outside the workspace. Treat the workspace as untrusted.


Quick reference

ItemValue
Model stringgrok-4.6
Base URLhttps://api.x.ai/v1
Auth env varXAI_API_KEY
Context window500,000 tokens
Price (<200K tokens)$2 in / $6 out per 1M
Price (>=200K tokens)$4 in / $12 out per 1M (whole request)
Cached input$0.50 per 1M
Fast variant2x base price ($4 / $12)
Reasoning effortlow, medium, high, xhigh (via extra_body)
Knowledge cutoffFebruary 1, 2026
API surfacesChat Completions, Responses API, xai_sdk

Next steps

  • Add a list_dir tool so the agent can explore an unfamiliar repository before editing.
  • Swap the subprocess runner for a real test command like pytest -q and let the agent gate on the pytest exit code.
  • Turn on prompt caching for the system prompt and tool schemas to cut input cost on repeated runs.
  • Compare the same loop against GPT-5.6 Sol and Claude Fable 5 by only changing the base URL and model, then measure cost per completed task, not per token.
  • Stream responses with stream=True to surface the model's reasoning and tool calls live in a CLI.

The takeaway: Grok 4.6 makes self-verification a default rather than a prompt trick, and it does it at the cheapest output price at the current frontier. Build your agent loop so the model can act on that, gate the final answer on a real test, and you get an agent that is both cheaper and less likely to lie to you about being done.

Sources

  • xAI, Introducing Grok 4.6 — x.ai/news/grok-4-6
  • xAI Docs, Grok 4.6 model reference — docs.x.ai/developers/grok-4-6
  • Grok 4.6 Model Card (August 12, 2026) — media.x.ai
  • Apidog, What Is Grok 4.6? Features, Benchmarks, Pricing, and API Access — apidog.com/blog/what-is-grok-4-6

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,605 newsletter subscribers.

Also get