GLM-5.4 is Z.ai’s new flagship model. Z.ai’s documentation, as read on December 2, 2026, calls it “the first built on the Loop Transformer architecture”: instead of adding parameters, it “loops 28 layers of the GLM-5 base model for two iterations” so the model gets a second pass of reasoning depth at the same size. Nebius Token Factory serves it through the same OpenAI-compatible API as every other model in the catalog, with a 1M-token context.
On Token Factory, GLM-5.4 is the model for multi-step software engineering. It can hold source code, test output and tool results in one context, call functions, and return JSON that matches a schema. This cookbook makes a first call, covers the request settings that matter, and ends with an agent that uses all of those together: it fixes a project with five failing tests and returns a typed report of every bug.
What GLM-5.4 is good at
Z.ai frames the release as the start of “Generalized Coding”, where the model writes and edits code for a wider range of work than application software; its examples include games, 3D models and mechanical designs. The same page names one limit: on some tasks the model “tends to get caught in overly long 'marathon thinking' loops”. Z.ai’s documentation gives no benchmark scores in text, so this page quotes none. Treat the vendor’s framing as a claim until you have run your own evaluation; the measured run below is a start.
A few facts that shape how you use it on Token Factory, from the model catalog on December 2, 2026:
- Reasoning is on by default. The model thinks before it answers and returns the thinking in a separate field. You control how much with
reasoning_effort, covered below. - Tools and typed output. The catalog lists function calling, JSON mode and structured outputs for this model.
- Long context. The hosted context is 1,048,576 tokens.
- Text in, text out. Z.ai’s own API accepts images and video for GLM-5.4. The Token Factory endpoint was text-only on December 2, 2026.
Prerequisites
- A Nebius Token Factory account and an API key.
- Python 3.10 or newer, or
curl. The Python examples use theopenaipackage. - The model ID
zai-org/GLM-5.4from the Token Factory model catalog. On December 2, 2026 the catalog listed a context of 1,048,576 tokens and a list price of $1.40 per 1M input tokens, $0.26 per 1M cached input tokens, and $4.40 per 1M output tokens. Prices can change, so check the catalog before you plan a budget around them.
Store the key in an environment variable. Never paste it into a notebook or commit it.
export NEBIUS_API_KEY="your-key"
export NEBIUS_BASE_URL="https://api.tokenfactory.nebius.com/v1"
Your first call
Token Factory speaks the OpenAI chat completions protocol, so the first request is one curl.
curl "$NEBIUS_BASE_URL/chat/completions" \
-H "Authorization: Bearer $NEBIUS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "zai-org/GLM-5.4",
"messages": [
{"role": "user", "content": "In two sentences, explain what a race condition is."}
],
"max_tokens": 4000
}'
The answer is in choices[0].message.content. The model’s thinking comes back separately in choices[0].message.reasoning_content, so the visible answer stays clean. Keep the token cap generous: reasoning tokens count against max_tokens.
The same call from Python, with the official OpenAI client pointed at Token Factory. The client does not know the reasoning_content field, so read it from model_extra.
import os
from openai import OpenAI
client = OpenAI(
base_url=os.environ["NEBIUS_BASE_URL"],
api_key=os.environ["NEBIUS_API_KEY"],
)
response = client.chat.completions.create(
model="zai-org/GLM-5.4",
messages=[
{"role": "user", "content": "In two sentences, explain what a race condition is."}
],
max_tokens=4000,
)
message = response.choices[0].message
print("reasoning:", (message.model_extra or {}).get("reasoning_content"))
print("answer:", message.content)
usage = response.usage
print("prompt:", usage.prompt_tokens)
print("completion:", usage.completion_tokens)
print("of which reasoning:", usage.completion_tokens_details.reasoning_tokens)
Measured on December 2, 2026 at the default effort, this call used 23 prompt tokens and 369 completion tokens, 286 of them reasoning, for $0.0017 at list price.
Settings that matter
Reasoning effort
Token Factory passes the reasoning_effort field to the model. It accepted none, low, medium, high and max on December 2, 2026. The OpenAI Python client does not know the field, so it goes through extra_body.
response = client.chat.completions.create(
model="zai-org/GLM-5.4",
messages=messages,
max_tokens=4000,
extra_body={"reasoning_effort": "low"},
)
The same short question at each level, measured once per level on December 2, 2026:
reasoning_effort |
Prompt tokens | Completion tokens | Reasoning tokens |
|---|---|---|---|
| not set | 23 | 369 | 286 |
none |
24 | 83 | 0 |
low |
23 | 71 | 1 |
medium |
23 | 380 | 314 |
high |
23 | 75 | 7 |
max |
23 | 307 | 208 |
On a question this short the model decides for itself how much to think, and the levels do not line up in order. Measure on your own workload before you pick one. thinking: {"type": "disabled"} also turned reasoning off, with 0 reasoning tokens.
Turning reasoning off is fine for a short answer. It is a poor fit for an agent loop: see the measured run below, where the none run cost five times more than the default.
Budget output tokens
Reasoning tokens count against max_tokens and are billed as output. With max_tokens set to 100 on December 2, 2026, the call returned empty content and finish_reason: "length", with all 100 tokens spent on reasoning. Use 4,000 or more for a single answer and more for an agent that writes files, and watch usage.completion_tokens_details.reasoning_tokens in your logs.
Send the whole assistant message back
In a multi-turn or tool-calling conversation, send every earlier assistant turn back with its content, tool_calls and reasoning_content. Z.ai’s documentation recommends keeping the model’s earlier thinking in the conversation (clear_thinking: false on their API).
message = response.choices[0].message
turn = {
"role": "assistant",
"content": message.content or "",
"reasoning_content": (message.model_extra or {}).get("reasoning_content"),
}
if message.tool_calls:
turn["tool_calls"] = [
{
"id": call.id,
"type": "function",
"function": {"name": call.function.name, "arguments": call.function.arguments},
}
for call in message.tool_calls
]
messages.append(turn)
Token Factory accepted a turn without reasoning_content on December 2, 2026 and still answered, so you will not see an error if a framework strips the field. Many agent frameworks drop it by default, so check yours.
Schema-constrained JSON
Pass a JSON schema in response_format and the answer is a JSON string that matches it. Reasoning still happens first and still counts against max_tokens.
schema = {
"name": "review",
"strict": True,
"schema": {
"type": "object",
"properties": {
"severity": {"type": "string", "enum": ["low", "medium", "high"]},
"line": {"type": "integer"},
"problem": {"type": "string"},
},
"required": ["severity", "line", "problem"],
"additionalProperties": False,
},
}
response = client.chat.completions.create(
model="zai-org/GLM-5.4",
messages=[{"role": "user", "content": "Review this function and report the most serious bug.\n\n" + code}],
max_tokens=4000,
response_format={"type": "json_schema", "json_schema": schema},
)
On December 2, 2026, a five-line average() function sent this way came back as an object with "severity": "high", "line": 5 and a problem string describing the division by zero on an empty list. The call used 55 prompt tokens and 1,108 completion tokens, 866 of them reasoning.
Prompt caching
Put the stable part of the prompt first: the system prompt, tool definitions and long files, with the changing question at the end. A cache hit reports the reused tokens in usage.prompt_tokens_details.cached_tokens and bills them at the cached price. On December 2, 2026, the day after launch, three identical calls with a 10,072-token prompt all reported 0 cached tokens, and one of the four agent runs below reported 384. Budget for the uncached price and treat hits as savings.
Fix a failing test suite and get a typed report
The agent below gives GLM-5.4 a small shopping-cart project in which five of six tests fail. The model gets four tools: list_files, read_file, write_file and run_tests. It reads the code, runs the tests, rewrites the source and runs the tests again until they pass. One more request then asks for the report as JSON that matches a schema. The script does not take the model’s word for the result: it runs the tests itself, prints the diff, and adds up the tokens and the cost.
Get the code from the companion project, which also has tests that run the whole loop against a fake client:
git clone --depth 1 https://github.com/nebius/token-factory-cookbook.git
cd token-factory-cookbook/models/glm-5.4-debug-agent
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt
The tools stay inside a scratch copy
The model never touches sample/. The script copies the project to a temporary folder, and every tool resolves its path inside that copy. Test files are read-only, so the model cannot make the suite pass by editing the tests.
class Workspace:
"""A scratch copy of the project. Every tool is confined to it."""
def __init__(self, source: Path, root: Path):
self.root = root.resolve()
shutil.copytree(source, self.root, dirs_exist_ok=True, ignore=shutil.ignore_patterns("__pycache__", ".pytest_cache"))
self.original = {path: self.read_file(path) for path in self.list_files()}
def _resolve(self, path: str) -> Path:
target = (self.root / path).resolve()
if target != self.root and self.root not in target.parents:
raise ValueError(f"{path} is outside the project")
return target
def list_files(self) -> list[str]:
return sorted(
str(p.relative_to(self.root))
for p in self.root.rglob("*")
if p.is_file() and "__pycache__" not in p.parts and ".pytest_cache" not in p.parts
)
def read_file(self, path: str) -> str:
return self._resolve(path).read_text()
def write_file(self, path: str, content: str) -> str:
target = self._resolve(path)
if target.name.startswith("test_") or target.name == "conftest.py":
raise ValueError("test files are read-only; fix the source instead")
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content)
return f"wrote {path} ({len(content)} characters)"
run_tests runs pytest in the scratch copy with a 120-second timeout and returns the exit code and the last 6,000 characters of output. That is code the model wrote, running on your machine with your permissions. The sample project is harmless; use a container before you point PROJECT_DIR at code you do not trust.
The loop, then the typed report
The loop sends each assistant turn back whole, appends every tool result with its tool_call_id, and stops when the model answers without a tool call. The last request drops the tools and adds response_format.
def run(client, model: str, workspace: Workspace, reasoning_effort: str | None = None, max_rounds: int = 20):
"""Run the fix loop, then ask for the typed report. Return (summary, report, totals)."""
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": "The test suite is failing. Find out why and fix it."},
]
extra_body = {"reasoning_effort": reasoning_effort} if reasoning_effort else {}
totals = {"requests": 0, "prompt_tokens": 0, "cached_tokens": 0, "completion_tokens": 0, "reasoning_tokens": 0}
for _ in range(max_rounds):
response = client.chat.completions.create(
model=model, messages=messages, tools=TOOLS, max_tokens=16000, extra_body=extra_body
)
message = response.choices[0].message
add_usage(totals, response.usage)
messages.append(assistant_turn(message))
if not message.tool_calls:
break
for call in message.tool_calls:
result, line = call_tool(workspace, call.function.name, call.function.arguments)
print(f"tool {line}")
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
else:
raise RuntimeError(f"the model was still calling tools after {max_rounds} rounds")
summary = message.content or ""
messages.append({"role": "user", "content": REPORT_REQUEST})
response = client.chat.completions.create(
model=model,
messages=messages,
max_tokens=16000,
response_format={"type": "json_schema", "json_schema": REPORT_SCHEMA},
extra_body=extra_body,
)
add_usage(totals, response.usage)
report = json.loads(response.choices[0].message.content)
return summary, report, totals
The schema asks for one entry per bug, whether the tests pass, and any risk the model wants a reviewer to look at:
REPORT_SCHEMA = {
"name": "fix_report",
"strict": True,
"schema": {
"type": "object",
"properties": {
"bugs": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file": {"type": "string"},
"root_cause": {"type": "string"},
"fix": {"type": "string"},
},
"required": ["file", "root_cause", "fix"],
"additionalProperties": False,
},
},
"tests_passing": {"type": "boolean"},
"follow_up_risks": {"type": "array", "items": {"type": "string"}},
},
"required": ["bugs", "tests_passing", "follow_up_risks"],
"additionalProperties": False,
},
}
Run it
.venv/bin/python -m pytest -q
.venv/bin/python app.py
The first command is free: it runs the offline tests and prints 8 passed. The second calls the model. Set GLM_REASONING_EFFORT to low, medium, high, max or none to change the effort. NEBIUS_MODEL overrides the model ID, so unset it if your shell already exports one for another model.
Measured on December 2, 2026 with zai-org/GLM-5.4 at the default effort:
tool list_files
tool read_file cart.py
tool read_file pricing.py
tool read_file test_cart.py
tool run_tests -> exit 1 (5 failed, 1 passed in 0.02s)
tool write_file cart.py
tool write_file pricing.py
tool run_tests -> exit 0 (6 passed in 0.01s)
--- a/cart.py
+++ b/cart.py
@@ -6,8 +6,9 @@
class Cart:
- def __init__(self, items=[], tax_rate="0.08"):
- self.items = items
+ def __init__(self, items=None, tax_rate="0.08"):
+ # A new list per cart: a mutable default would be shared by every cart.
+ self.items = [] if items is None else list(items)
self.tax_rate = Decimal(tax_rate)
def add(self, name: str, price: str, quantity: int = 1) -> None:
@@ -17,5 +18,6 @@
return sum((price * quantity for _, price, quantity in self.items), Decimal("0"))
def total(self, coupon: dict | None = None) -> Decimal:
- taxed = self.subtotal() * (1 + self.tax_rate)
- return round_money(apply_coupon(taxed, coupon))
+ discounted = apply_coupon(self.subtotal(), coupon)
+ taxed = discounted * (1 + self.tax_rate)
+ return round_money(taxed)
--- a/pricing.py
+++ b/pricing.py
@@ -1,11 +1,11 @@
"""Money helpers for the cart."""
-from decimal import Decimal
+from decimal import Decimal, ROUND_HALF_UP
def round_money(amount: Decimal) -> Decimal:
"""Round to cents, half up: 2.675 becomes 2.68."""
- return Decimal(str(round(float(amount), 2)))
+ return Decimal(amount).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
def apply_coupon(subtotal: Decimal, coupon: dict | None) -> Decimal:
@@ -16,5 +16,7 @@
if coupon is None:
return subtotal
if coupon["type"] == "percent":
- return subtotal - subtotal * Decimal(str(coupon["value"])) / 100
- return subtotal - Decimal(str(coupon["value"]))
+ discounted = subtotal - subtotal * Decimal(str(coupon["value"])) / 100
+ else:
+ discounted = subtotal - Decimal(str(coupon["value"]))
+ return max(discounted, Decimal("0"))
tests: passed (6 passed in 0.01s)
GLM response: All 6 tests pass. There were four distinct bugs:
The model’s summary went on to list the four bugs. The typed report followed:
{
"bugs": [
{
"file": "cart.py",
"root_cause": "Cart.__init__ used a mutable default argument, so every instance appended items to the same shared list and new carts inherited earlier items",
"fix": "Accept items=None and create a new list per cart"
},
{
"file": "cart.py",
"root_cause": "Cart.total applied the coupon after adding tax, although the documented order is discount on the subtotal first, then tax",
"fix": "Apply the coupon to the subtotal before multiplying by (1 + tax_rate)"
},
{
"file": "pricing.py",
"root_cause": "round_money rounded via float, which loses precision (2.675 is stored as 2.67499...) and rounds half to even, so half-up cases rounded down",
"fix": "Use Decimal.quantize with ROUND_HALF_UP"
},
{
"file": "pricing.py",
"root_cause": "apply_coupon did not enforce the documented zero floor, so an oversized fixed coupon produced a negative total that was then taxed",
"fix": "Clamp the discounted amount with max(discounted, Decimal(\"0\"))"
}
],
"tests_passing": true,
"follow_up_risks": []
}
And the totals for the whole loop:
usage: requests=7 prompt=12995 cached=384 completion=1569 reasoning=546
cost: $0.0247 at list price, wall 41 s
The order of tool calls, the wording and the token counts vary between runs.
Verify the result
You have a working agent when:
- The line
tests: passed (6 passed in ...)prints. It comes from the script’s own pytest run after the model has finished, so it does not depend on what the model says. - The diff touches
cart.pyandpricing.pyand no test file. - The JSON report parses and has
"tests_passing": true. - The script exits with code 0. It exits with 1 if the tests still fail.
The same run at each setting on December 2, 2026, one run each:
GLM_REASONING_EFFORT |
Requests | Prompt tokens | Completion tokens | Reasoning tokens | Cost at list price | Wall time | Tests |
|---|---|---|---|---|---|---|---|
| not set | 7 | 12,995 | 1,569 | 546 | $0.0247 | 41 s | 6 passed |
low |
6 | 11,500 | 848 | 28 | $0.0198 | 17 s | 6 passed |
max |
7 | 14,438 | 1,859 | 903 | $0.0284 | 34 s | 6 passed |
none |
6 | 37,364 | 19,667 | 0 | $0.1388 | 228 s | 6 passed |
All four runs found the same four bugs and ended with a green suite. The run with reasoning off is the one to learn from. Its code fix was correct, but the model never ran the tests again, and its closing summary repeated one sentence for about 19,000 tokens and claimed a test count it had not seen. The script’s own test run is what showed the fix was good. Keep reasoning on for agent loops, cap max_tokens, and verify results in code.
The default-effort cost is 12,611 uncached input tokens at $1.40/M, 384 cached at $0.26/M and 1,569 output tokens at $4.40/M.
Troubleshooting
- 404 or model not found. The ID is
zai-org/GLM-5.4, and case matters. CheckNEBIUS_MODELtoo, since it overrides the default. - 401. The key is missing or the
Authorizationheader is malformed. Check thatNEBIUS_API_KEYis exported in the shell you run from. - 429 with a tokens quota message. Your project has used its quota for the model. Request more quota for the model on the Token Factory console.
- Empty content with
finish_reason: "length". The whole budget went to reasoning. Raisemax_tokensor lower the effort. tests: FAILEDand exit code 1. The model stopped before the suite was green. Run it again or raise the effort.the model was still calling tools after 20 rounds. Run it again, or raisemax_roundsinrun()for a larger project.- A long, repetitive answer. This happened with
reasoning_effort: "none"in the agent loop. Leave reasoning on. - An image is rejected. The Token Factory endpoint was text-only on December 2, 2026.
Clean up
The agent creates no cloud resources, and its scratch copy is deleted when the script exits. Unset the key and remove the virtual environment when you are done, and rotate the key if it was ever printed.
unset NEBIUS_API_KEY NEBIUS_BASE_URL
rm -rf .venv
Going further
-
Point the agent at your own code with
PROJECT_DIR=/path/to/project. It needs a pytest suite that fails; run it in a container. -
Put the model behind a coding agent. For OpenCode, add Token Factory as a provider in
~/.config/opencode/opencode.json:{ "$schema": "https://opencode.ai/config.json", "provider": { "nebius": { "npm": "@ai-sdk/openai-compatible", "name": "Nebius Token Factory", "options": { "baseURL": "https://api.tokenfactory.nebius.com/v1", "apiKey": "{env:NEBIUS_API_KEY}" }, "models": { "zai-org/GLM-5.4": { "name": "GLM-5.4" } } } } }Then run it from a repository:
opencode --model nebius/zai-org/GLM-5.4The OpenCode on Token Factory cookbook has the full setup. This configuration was not run for this page.
-
The prompt caching cookbook shows how to lay out a long prompt so repeated calls hit the cache.
-
For typed decisions without generated text, see the typed decision model on GLM-5.3 Flash.
-
For steady production traffic, run the model on a Token Factory dedicated endpoint.
-
Z.ai’s GLM-5.4 guide covers the model from the vendor’s side.