
Grok 4.5 Tool Loops: Tune Effort and Cache to Cut Cost
Summary
Build an agentic Grok 4.5 tool loop in Python: route reasoning_effort and cache to slash cost.
Grok 4.5 Tool Loops: Tune Effort and Cache to Cut Cost
xAI shipped Grok 4.5 on July 8, 2026, and developers moved fast because the numbers are hard to ignore: $2 per 1M input tokens and $6 per 1M output, roughly half of comparable frontier models, served at about 80 tokens/second with a 500K-token context window. xAI also says it solves engineering tasks in far fewer tokens than rivals (about 4x fewer output tokens per SWE-Bench Pro task), so the real bill is lower than the sticker price suggests.
The part that matters for builders: the xAI API is OpenAI-compatible. You point your existing OpenAI client at https://api.x.ai/v1, set the model to grok-4.5, and everything you already wrote for Chat Completions or the Responses API keeps working. No new SDK to learn.
This guide builds a small but real agentic tool loop: a bug-triage agent that reads files from a repo and proposes a fix. Along the way you learn the two levers that decide whether a Grok 4.5 agent is cheap or expensive - the reasoning_effort parameter and prompt caching. Both are easy to get wrong, and both quietly multiply your bill when you do.
Prerequisites
- Python 3.9+ and the official OpenAI SDK:
pip install openai(version 1.40+). - An xAI API key from
console.x.ai, exported asXAI_API_KEY. - Basic familiarity with function/tool calling in the OpenAI style.
- Note: at launch Grok 4.5 was not yet available to EU API accounts (xAI expected mid-July). A region error is why.
Step 1 - Your first Grok 4.5 call
Start with the smallest possible program. The only xAI-specific detail is base_url; drop it and your call silently hits OpenAI instead.
import os
from openai import OpenAI
# The xAI API is OpenAI-compatible: same client, different base_url.
client = OpenAI(
api_key=os.environ["XAI_API_KEY"],
base_url="https://api.x.ai/v1",
)
resp = client.responses.create(
model="grok-4.5",
input="Find and fix the bug, then explain it: "
"function median(a){a.sort();return a[a.length/2]}",
)
print(resp.output_text)
The Responses API returns a convenient output_text string. Under the hood Grok 4.5 always reasons before answering (more on that next), so even this tiny call spends some hidden reasoning tokens.
Step 2 - The reasoning_effort lever
Grok 4.5 is a reasoning model, and reasoning cannot be disabled. What you can control is how hard it thinks with reasoning_effort, which takes low, medium, or high. It defaults to high - the most expensive and slowest setting - so leaving it unset is the single most common way to overpay.
| Effort | What it's for | Use it when |
|---|---|---|
| low | Some reasoning, still fast | Tool-calling turns, routing, simple classification, latency-sensitive agents |
| medium | More thinking, moderate latency | Data analysis, long-context summarization, multi-file reads |
| high (default) | Deep thinking, most tokens | Hard math, proofs, competition-level or tricky multi-step logic |
A rule of thumb for agents: run the tool-calling turns at low and only escalate to high for the final synthesis when the task is genuinely hard. Here is a helper that dials effort per call. The parameter shape differs slightly by API: the Responses API takes reasoning={"effort": ...}, while Chat Completions takes a flat reasoning_effort=....
def ask(prompt, effort="high"):
"""effort is one of: 'low', 'medium', 'high' (default 'high')."""
r = client.responses.create(
model="grok-4.5",
reasoning={"effort": effort}, # Responses API shape
input=[{"role": "user", "content": prompt}],
)
return r.output_text
# Cheap + fast for a trivial classification:
print(ask("Bug or feature request? 'App crashes on export'", effort="low"))
# Deep thinking for a hard proof:
print(ask("Find all primes p where p^2 + 2 is prime. Prove it.", effort="high"))
Step 3 - Build the agentic tool loop
Now the real thing. An agent loop is just: call the model, if it asks for a tool then run the tool and feed the result back, repeat until it stops asking. We use Chat Completions here because the tool-call/tool-result handshake is the one most developers already know. Two production details are baked in from the start: reasoning_effort="low" for speed and an x-grok-conv-id header so caching works (Step 4 explains why).
import json, os
from openai import OpenAI
client = OpenAI(api_key=os.environ["XAI_API_KEY"], base_url="https://api.x.ai/v1")
# 1) A real tool the model can call.
def read_file(path):
with open(path, "r", encoding="utf-8") as f:
return f.read()
TOOLS = [{
"type": "function",
"function": {
"name": "read_file",
"description": "Read a source file from the repo and return its contents.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Relative path to the file"}
},
"required": ["path"],
},
},
}]
messages = [
{"role": "system", "content": "You are a bug-triage agent. "
"Call read_file to inspect code before you answer."},
{"role": "user", "content": "There is an off-by-one bug in utils/median.py. "
"Find it and propose a one-line fix."},
]
# 2) The agent loop. reasoning_effort='low' keeps the tool-calling phase fast + cheap.
# x-grok-conv-id pins every turn to the same server so prompt caching actually hits.
while True:
r = client.chat.completions.create(
model="grok-4.5",
reasoning_effort="low",
messages=messages,
tools=TOOLS,
extra_headers={"x-grok-conv-id": "triage-session-1"},
)
msg = r.choices[0].message
messages.append(msg) # keep the assistant turn in history
if not msg.tool_calls: # no tool call -> final answer
print(msg.content)
break
for tc in msg.tool_calls: # run each requested tool
args = json.loads(tc.function.arguments)
result = read_file(args["path"])
messages.append({
"role": "tool",
"tool_call_id": tc.id,
"content": result,
})
Two things people trip on. First, append the assistant message (msg) back into messages before you append the tool results, otherwise the tool replies have nothing to attach to. Second, every tool result needs the matching tool_call_id and role: "tool"; a plain user message will confuse the model.
Step 4 - Cut the bill with prompt caching
In an agent loop the same system prompt, tool schema, and growing history get resent on every turn. That input is what you pay for repeatedly. xAI caches input tokens, but the cache lives on a specific server. If your five turns bounce across five machines, you pay full input price five times. Pinning the conversation to one server is what makes cache hits reliable, and cached input is billed at $0.50 / 1M instead of $2.00 - a 4x discount on the repeated part.
On Chat Completions you pin with the x-grok-conv-id header (any stable string per conversation). On the Responses API you pass prompt_cache_key instead:
# Responses API: use prompt_cache_key instead of the x-grok-conv-id header.
r = client.responses.create(
model="grok-4.5",
prompt_cache_key="triage-session-1", # routes to a warm server -> cheap cached input
reasoning={"effort": "low"},
input=messages,
)
Rule: use one stable key per conversation, and do not reuse the same key across unrelated conversations or you pollute each other's cache routing.
Worked example: what the agent returns
Run the loop against a repo containing a buggy utils/median.py. The agent makes one read_file call, gets the source back, then answers. Trimmed output:
# --- turn 1: the model asks to read the file ---
[tool_call] read_file(path="utils/median.py")
# --- turn 2: after we return the file, it answers ---
The bug is on line 4:
return sorted(a)[len(a) // 2]
For an even-length list, len(a)//2 skips the lower-middle element, so the
"median" is off by one toward the upper half. One-line fix that also
averages the two middle values:
return (sorted(a)[(len(a)-1)//2] + sorted(a)[len(a)//2]) / 2
Reasoning tokens used: 512 | Output tokens: 143
Notice the effort trade-off in action: the tool-calling turn spent only about 512 reasoning tokens because we set low. At the default high the same two turns can burn several thousand reasoning tokens for an answer that is no better on an easy bug like this.
Cost math you can feel
Say your triage agent carries a 12K-token context (system + tool schema + file) and runs 5 turns in a session. The comparison below shows why the two levers matter: reasoning tokens are billed as output, and repeated input is where caching pays off.
| Scenario | Repeated input cost | Rough session cost |
|---|---|---|
| No cache key, effort=high | 5 x 12K @ $2/1M = $0.12 input | ~$0.15-0.20 with heavy reasoning output |
| Cache key, effort=low | 1 x 12K @ $2 + 4 x 12K @ $0.50 = $0.048 input | ~$0.06-0.08 with lean reasoning output |
Same task, roughly 2-3x cheaper, and faster too. Multiply that across thousands of sessions and the levers stop being a rounding error.
Common pitfalls
- Forgetting
base_url. Withouthttps://api.x.ai/v1your OpenAI client calls OpenAI and you wonder why the model 'doesn't know it's Grok'. - Leaving
reasoning_effortat the default. It ishigh, the priciest setting. Explicitly setlowfor tool-calling and routing turns. - Using
presence_penalty,frequency_penalty, orstop. Reasoning models reject these; the request errors out. Remove them. - No cache key. Without
x-grok-conv-id(Chat Completions) orprompt_cache_key(Responses), you pay full input price every turn instead of the $0.50/1M cached rate. - Trying to disable reasoning. You can't. You can only lower effort. Budget for reasoning tokens - they count as output.
- Dropping the assistant message before tool results. Append
msgfirst, then each tool result with itstool_call_id. - Assuming EU access at launch. Grok 4.5 was not in the EU API console on day one; availability was slated for mid-July.
- Treating 500K context as free. It is large, not infinite. For very long agent runs, use xAI's context compaction rather than blindly growing history.
Quick reference
| Item | Value |
|---|---|
| Model name | grok-4.5 |
| Base URL | https://api.x.ai/v1 |
| Input / Output price | $2.00 / $6.00 per 1M tokens |
| Cached input price | $0.50 per 1M tokens |
| Context window | 500K tokens |
| Speed | ~80 tokens/sec |
| reasoning_effort | low / medium / high (default high) |
| APIs | Responses API + Chat Completions (OpenAI-compatible) |
| Cache key | prompt_cache_key (Responses) or x-grok-conv-id header (Chat) |
| Built-in tools | function calling, web search, X search, code execution |
Next steps
- Swap the local
read_filetool for xAI's built-in code execution or web search tools to give the agent live capabilities. - Add structured outputs so the triage verdict comes back as validated JSON you can route programmatically.
- For long-running agents, wire in context compaction to keep sessions under the 500K ceiling.
- Try the same loop in Grok Build (xAI's CLI coding agent) or Cursor, where grok-4.5 is the default, to compare against your API version.
Code verified against the official xAI docs (docs.x.ai) as of July 10, 2026. Prices and EU availability can change - check the pricing page before you ship.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,617 newsletter subscribers.