
GLM-5.3-Flash: Let Your Agent See the UI It Built
Summary
Build a render-screenshot-critique loop with GLM-5.3-Flash native vision, for pennies a run.
For six days an unbranded model called ox-alpha sat on OpenRouter and OpenCode charging nothing, accepting text, images and video, and swallowing a million tokens of context. People burned through it. Z.ai says it became the most-used model of the week on both services. On August 26 the mask came off: ox-alpha is GLM-5.3-Flash, a 320B-parameter mixture-of-experts model with 18B active per token, released under the MIT license, and priced at $0.075 per million input tokens during the launch discount.
The benchmark chatter will fade in a week. The part worth learning is quieter and more useful: Z.ai trained this model to look at rendered output and revise its own work from what it sees. Not "describe this photo" vision. Screenshot-of-your-own-code vision. That turns a pattern most people talk about but rarely wire up into something you can actually afford to run in a loop.
This guide builds that loop end to end in Python. You give it broken HTML. It renders the page in headless Chromium, screenshots it, hands the screenshot plus the source back to glm-5.3-flash, gets a structured defect list, patches the HTML, and renders again — until the model reports a clean pass or you run out of rounds. Everything here is checked against the Z.ai OpenAPI spec, including three schema traps that will 400 your first attempt.
What actually shipped
Worth pinning down before writing code, because a lot of secondhand reporting has this wrong.
- Model ID:
glm-5.3-flash. It is listed under the vision request schema, not the text one, which matters for parameter support. - Architecture: 320B total / 18B active MoE, trained on a 30-trillion-token multimodal corpus. Linear attention for local dependencies, sparse attention for global context.
- Context: 1,048,576 tokens in, up to 131,072 tokens out.
- Inputs: text, images, and video, natively. Not a text model with an adapter bolted on.
- Price: $0.15 / $0.25 list per million in/out, currently halved to $0.075 / $0.25 through the launch discount window, with cached input reads cheaper again.
- Weights: MIT, on Hugging Face as
zai-org/GLM-5.3-Flash. SGLang, vLLM and TokenSpeed all serve it.
The multimodal training is the reason this guide exists. Z.ai's own writeup describes training the model to inspect rendered interfaces, gameplay frames and 3D output, then assess and revise its work from that visual feedback. You are not fighting the model to get it to look at a screenshot. That is the job it was shaped for.
Prerequisites
- Python 3.10+.
- A Z.ai API key from the Z.ai open platform, exported as
ZAI_API_KEY. pip install openai playwright, thenplaywright install chromiumto pull the browser binary.- Roughly $0.02 of credit. The full worked example below costs less than a US cent per round.
No new SDK. Z.ai speaks the OpenAI chat-completions dialect, so the official openai package works once you repoint base_url.
Step 1: prove the model can see
Start with the smallest possible call. If this returns text about the image, your key, endpoint and message shape are all correct and everything after is just plumbing.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["ZAI_API_KEY"],
base_url="https://api.z.ai/api/paas/v4",
)
resp = client.chat.completions.create(
model="glm-5.3-flash",
messages=[{
"role": "user",
"content": [
{"type": "image_url",
"image_url": {"url": "https://cdn.bigmodel.cn/static/logo/register.png"}},
{"type": "text", "text": "What is in this image? One sentence."},
],
}],
max_tokens=256,
)
print(resp.choices[0].message.content)
print("cached:", resp.usage.prompt_tokens_details.cached_tokens,
"| in:", resp.usage.prompt_tokens,
"| out:", resp.usage.completion_tokens)
Note the content shape. Multimodal messages are a list of typed parts, and the image part is {"type": "image_url", "image_url": {"url": ...}} — an object wrapping the URL, not a bare string. Get that wrong and you get a 400 with a schema complaint that does not name the field.
Step 2: turn a local render into something the API accepts
Your screenshots live on disk, and the API wants a URL. The url field also accepts a base64 data URL, which is how you avoid standing up a bucket just to show the model a PNG.
Playwright does the rendering. Setting a fixed viewport matters more than it looks — the model judges layout, so the frame it sees has to be the frame you care about.
import base64, pathlib
from playwright.sync_api import sync_playwright
MAX_IMAGE_BYTES = 5 * 1024 * 1024 # Z.ai hard limit: under 5 MB per image
def render(html: str, out: pathlib.Path, width=1280, height=800) -> pathlib.Path:
"""Rasterise an HTML string to PNG at a fixed viewport."""
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(viewport={"width": width, "height": height})
page.set_content(html, wait_until="networkidle")
page.screenshot(path=str(out))
browser.close()
return out
def to_data_url(path: pathlib.Path) -> str:
raw = path.read_bytes()
if len(raw) > MAX_IMAGE_BYTES:
raise ValueError(
f"{path.name} is {len(raw)/1e6:.1f} MB; Z.ai rejects images >= 5 MB. "
"Shrink the viewport or drop full_page=True."
)
return "data:image/png;base64," + base64.b64encode(raw).decode()
The size guard is not decoration. A full_page=True screenshot of a long dashboard clears 5 MB easily, and the API's rejection for an oversized image is not obviously about size. Fail loudly in your own code instead.
Format and dimension limits from the spec: JPG, PNG and JPEG only, no side above 6000 pixels, under 5 MB each. Video, if you go there later, is capped at 200 MB in MP4, MKV or MOV.
Step 3: get a structured verdict without structured outputs
Here is the trap that costs the most time. The Z.ai spec is explicit: response_format is supported on the text request schema only. glm-5.3-flash lives on the vision schema. Send response_format={"type": "json_object"} alongside an image and the request is rejected.
So you ask for a fenced JSON block and parse it. Unglamorous, completely reliable when the schema is small and the instruction is blunt.
import json, re
FENCE = re.compile(r"```(?:json)?\s*(\{.*?\})\s*```", re.S)
def parse_verdict(text: str) -> dict:
"""glm-5.3-flash rejects response_format on vision calls, so pull the fence."""
m = FENCE.search(text)
payload = m.group(1) if m else text[text.index("{"): text.rindex("}") + 1]
return json.loads(payload)
CRITIC = """You are a UI reviewer. You are shown a screenshot of a rendered page
and the HTML that produced it. Judge only what you can see in the image.
Reply with a single fenced ```json block and nothing else:
{"pass": true|false, "defects": ["one concrete visual defect per string"]}
Report a defect only if it is visible: clipped text, overlap, misalignment,
unreadable contrast, an element outside the viewport. Do not invent taste notes."""
def critique(html: str, shot: pathlib.Path) -> dict:
resp = client.chat.completions.create(
model="glm-5.3-flash",
messages=[
{"role": "system", "content": CRITIC},
{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": to_data_url(shot)}},
{"type": "text", "text": f"HTML under review:\n\n{html}"},
]},
],
extra_body={"thinking": {"type": "enabled"}, "reasoning_effort": "high"},
temperature=0.2,
max_tokens=2048,
)
return parse_verdict(resp.choices[0].message.content)
Two things in that call deserve a note.
The fallback in parse_verdict. Models occasionally answer with bare JSON and no fence. Slicing from the first { to the last } catches that without a retry round-trip.
extra_body, not keyword arguments. thinking and reasoning_effort are Z.ai extensions. The OpenAI Python SDK validates its own keyword arguments and will raise TypeError on unknown ones, so vendor parameters have to travel in extra_body. This bites people porting working cURL to Python.
On reasoning: for GLM-5.3 and GLM-5.3-Flash, thinking cannot be turned off — the thinking.type field only accepts enabled. Depth is controlled by reasoning_effort instead, and on the vision path the accepted values are low, high and max, defaulting to max. high is the right trade for critique work; max mostly buys you latency.
Step 4: the patcher and the loop
The patcher gets the same screenshot, the same HTML, and the defect list the critic produced. Giving it the image again matters — a defect described as "the note line overflows" is ambiguous in text and obvious in pixels.
PATCHER = """You fix HTML. You are given the current document, a screenshot of how
it renders, and a defect list. Return the complete corrected document inside a
single ```html fence. Change only what the defects require."""
HTML_FENCE = re.compile(r"```(?:html)?\s*(<.*?>)\s*```", re.S)
def patch(html: str, shot: pathlib.Path, defects: list[str]) -> str:
resp = client.chat.completions.create(
model="glm-5.3-flash",
messages=[
{"role": "system", "content": PATCHER},
{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": to_data_url(shot)}},
{"type": "text", "text":
"Defects:\n- " + "\n- ".join(defects) + f"\n\nCurrent HTML:\n\n{html}"},
]},
],
extra_body={"thinking": {"type": "enabled"}, "reasoning_effort": "high"},
temperature=0.2,
max_tokens=8192,
)
body = resp.choices[0].message.content
m = HTML_FENCE.search(body)
return m.group(1) if m else body
def close_the_loop(html: str, max_rounds: int = 3, workdir="runs") -> str:
d = pathlib.Path(workdir); d.mkdir(exist_ok=True)
for i in range(max_rounds):
shot = render(html, d / f"round{i}.png")
verdict = critique(html, shot)
print(f"round {i}: pass={verdict['pass']} defects={verdict['defects']}")
if verdict["pass"]:
return html
html = patch(html, shot, verdict["defects"])
(d / f"round{i}.html").write_text(html)
print(f"stopped after {max_rounds} rounds without a clean pass")
return html
The critic and patcher are deliberately separate calls with separate system prompts. Ask one call to both judge and fix and you get a model that rationalises its own patch — it will report a pass because it just changed something, not because the render is clean. Splitting the roles means the judgement always happens against a fresh render the patcher has not seen.
The worked example
Here is a pricing card with two real, visible bugs and nothing wrong with the code as text. A linter sees nothing. A type checker sees nothing. You only find these by looking.
BROKEN = """<!doctype html><meta charset=utf-8>
<style>
body { margin:0; font-family: system-ui; background:#0f1115; }
.card { width:260px; height:120px; margin:80px auto; padding:24px;
background:#1b1f27; border-radius:14px; overflow:hidden; }
.price { font-size:64px; color:#2a2f3a; }
.note { font-size:14px; color:#8b93a1; white-space:nowrap; }
</style>
<div class=card>
<div class=price>$0.075</div>
<div class=note>per million input tokens, billed monthly in arrears</div>
</div>"""
final = close_the_loop(BROKEN)
pathlib.Path("runs/final.html").write_text(final)
The bugs: height:120px with overflow:hidden guillotines the note line, and #2a2f3a on #1b1f27 makes the price nearly invisible against the card. Both are legal CSS. Both are obvious in a screenshot.
Typical run:
round 0: pass=False defects=['the note line is cut off at the bottom edge of the card — only the top few pixels of the text are visible', 'the price text is nearly the same colour as the card background and is effectively unreadable', 'the note line does not wrap and extends past the card边界']
round 1: pass=False defects=['the note text now wraps but sits flush against the bottom padding with no breathing room']
round 2: pass=True defects=[]
Two notes on that output, both honest. First, round 0 mixed a Chinese token into an English defect string (边界, "boundary"). GLM models do this occasionally under multilingual pressure; if you route defect strings anywhere user-facing, pin the language in the system prompt with a hard line like "write every defect in English." Second, round 1 found a defect that did not exist before round 0's patch. That is the loop working, not the loop failing — each round judges the current render, so a fix that introduces a new visual problem gets caught on the next pass.
The final HTML from a clean run swaps height:120px for min-height, drops the overflow:hidden, lifts the price to a readable colour, and lets the note wrap. Total cost of three rounds at roughly 1,500 input tokens and 900 output tokens each: about $0.0014.
What this costs to actually run
The economics are the point. A closed vision loop has been buildable for two years; it has not been sensible to run on every commit because a frontier multimodal model at three to five dollars per million input tokens turns "screenshot every PR preview" into a real line item.
| Workload | Calls | Approx. input tokens | Cost at $0.075 / $0.25 |
|---|---|---|---|
| One 3-round fix loop | 5 | ~7,500 in / 4,500 out | ≈ $0.0017 |
| 50 PR previews/day, 2 rounds each | 150 | ~225K in / 90K out | ≈ $0.04 / day |
| Full 1M-token context call | 1 | 1,048,576 in | ≈ $0.079 |
A full million-token call costing about eight cents is the number to sit with. Screenshot-driven regression checking stops being a budget conversation and becomes a CI step.
Two levers make it cheaper still. Cached input reads are billed at roughly a fifth of fresh input, so keeping your system prompts byte-identical across calls pays for itself — check usage.prompt_tokens_details.cached_tokens to confirm you are actually hitting it. And reasoning_effort="low" on the critic roughly halves output tokens when your defect taxonomy is narrow.
Pitfalls worth knowing before you hit them
1. response_format is a 400 on the vision path. The spec restricts it to the text request schema. Parse a fenced block instead. This is the single most common failure when porting a working text pipeline to glm-5.3-flash.
2. file_url does not work on this model. The spec limits PDF, DOCX, XLSX and PPTX input via file_url to GLM-5V-Turbo, GLM-4.6V and GLM-4.5V. glm-5.3-flash takes image_url and video_url only. If you need a PDF reviewed, rasterise the pages yourself and send images.
3. Vendor parameters must go in extra_body. thinking, reasoning_effort, do_sample and tool_stream are not OpenAI SDK keyword arguments. Passing them directly raises TypeError before a request is ever sent.
4. Thinking cannot be disabled. On GLM-5.3 and GLM-5.3-Flash, thinking.type only accepts enabled. If you were relying on a no-reasoning fast path for cheap extraction calls, use reasoning_effort="low" and budget for some reasoning tokens regardless.
5. clear_thinking defaults to true and silently drops prior reasoning. In a multi-turn loop the model will not see its own earlier chain of thought unless you set clear_thinking: false and forward every historical reasoning_content block unmodified and in order. Truncated or reordered blocks degrade quality rather than erroring. For the loop in this guide, the default is what you want — each round should judge fresh.
6. Screenshot the viewport, not the page. full_page=True produces tall images that blow the 5 MB ceiling and, worse, change what "above the fold" means to the critic. Fix a viewport and judge that frame.
7. tool_choice only accepts auto. The model supports function calling with up to 128 tools, but you cannot force a specific function. If your pipeline depends on a guaranteed tool call, put that requirement in the system prompt and validate the response.
8. Watch finish_reason, not just content. Beyond stop and length, Z.ai returns sensitive for filtered content and model_context_window_exceeded when you overflow. Both give you a response object with unusable content. A loop that only checks for a parse failure will retry forever on a sensitive stop.
9. Model IDs are region-split. International traffic goes to https://api.z.ai/api/paas/v4; mainland China uses https://open.bigmodel.cn/api/paas/v4. Same wire format, separate billing. Keep the base URL and model ID in config so a swap is not a deploy.
Quick reference
| Thing | Value | Gotcha |
|---|---|---|
| Model ID | glm-5.3-flash | On the vision schema, not the text one |
| Endpoint | https://api.z.ai/api/paas/v4 | China: open.bigmodel.cn/api/paas/v4 |
| Context / max output | 1,048,576 / 131,072 | Overflow returns model_context_window_exceeded |
| Image input | image_url.url, URL or base64 data URL | < 5 MB, ≤ 6000px, jpg/png/jpeg |
| Video input | video_url.url | ≤ 200 MB, mp4/mkv/mov |
| File input | not supported | file_url is GLM-5V-Turbo / 4.6V / 4.5V only |
response_format | not supported | Text schema only — parse a fenced block |
thinking | {"type": "enabled"} | Cannot be disabled on 5.3 / 5.3-Flash |
reasoning_effort | low / high / max | Defaults to max; send via extra_body |
clear_thinking | defaults true | Drops prior-turn reasoning_content |
tool_choice | auto only | Cannot force a specific function |
| Cache hit counter | usage.prompt_tokens_details.cached_tokens | Byte-identical prefixes only |
| Weights | zai-org/GLM-5.3-Flash, MIT | SGLang / vLLM / TokenSpeed |
Where to take it next
- Wire it into CI. Render your PR preview at three viewport widths, run one critique round each, and post the defect list as a review comment. At four cents a day for fifty previews, this is cheaper than the CI minutes it runs on.
- Swap in video. The model takes
video_urlnatively. Record a Playwright trace of an interaction, hand it over as MP4, and ask what broke mid-flow. Screenshots miss animation and transition bugs entirely. - Give the critic a rubric. Replace the open-ended defect list with your design system's actual rules — spacing scale, contrast floor, allowed type sizes — and the false-positive rate drops sharply.
- Run it locally. The weights are MIT and served by SGLang and vLLM. 320B total with 18B active is server-class, not laptop-class, but the API you build today becomes the regression baseline for a self-hosted deployment.
- Add a diff guard. Have the patcher return a unified diff instead of a whole document, and reject patches that touch more than the defects justify. Whole-document rewrites drift.
The broader shift is small and specific. Agents have been able to write code and read errors for a while. What they mostly could not do is look at the result — and when the result is a rendered interface, that was the entire gap. A model that does this well at $0.075 per million input tokens closes it for anyone, not just for teams with a frontier-model budget.
Sources
- Z.ai chat completions OpenAPI spec — docs.z.ai/api-reference/llm/chat-completion (model IDs, vision schema, parameter limits)
- Z.ai quick start and SDK setup — docs.z.ai/guides/overview/quick-start
- GLM-5.3-Flash launch coverage and architecture details — TestingCatalog
- Pricing and launch discount — OpenRouter model page
- Third-party availability — Cloudflare Workers AI changelog, 26 Aug 2026
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,617 newsletter subscribers.