Z.ai’s GLM-5.2 arrived in mid-June 2026 with the kind of spec sheet that makes coding-agent people briefly forget their backlog: 1 million tokens of context, 128K maximum output, OpenAI-compatible API calls, tool use, streaming, structured output, MCP support, and official pricing at $1.40 per million input tokens and $4.40 per million output tokens.
The model was covered as a June 2026 launch by The Economic Times, but the useful question is not whether GLM-5.2 wins a vendor leaderboard. The useful question is whether you can wire it into an agent stack without losing a weekend.
This GLM-5.2 API tutorial starts there: first call, migration settings, streaming gotchas, tool-call handling, pricing math, and the point where a 1M-token window becomes a liability instead of a superpower. Big context is not magic. It is a larger room. You can still fill it with garbage.
What you need before the first API call
The official GLM-5.2 documentation gives you two practical paths: use Z.ai’s own SDK, or use the OpenAI Python SDK with a different base URL. For most teams, the OpenAI-compatible route is the lower-friction test because it fits existing wrappers, tracing, retries, and eval harnesses.
Set an API key in your environment first. Keep the actual key out of source control, because “we only leaked the eval key” is still a very dumb incident report.
export ZAI_API_KEY="your-zai-api-key"
The three identifiers that matter:
- Base URL:
https://api.z.ai/api/paas/v4/ - Chat endpoint:
/chat/completions - Model:
glm-5.2
Make your first GLM-5.2 API call
Install the OpenAI SDK if you do not already have it:
python -m pip install --upgrade "openai>=1.0"
Then call GLM-5.2 like any other chat-completions model, with the base URL changed:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["ZAI_API_KEY"],
base_url="https://api.z.ai/api/paas/v4/",
)
response = client.chat.completions.create(
model="glm-5.2",
messages=[
{
"role": "system",
"content": "You are a senior backend engineer. Be concise and specific.",
},
{
"role": "user",
"content": "Review this API design and list the three riskiest assumptions.",
},
],
max_tokens=1200,
)
print(response.choices[0].message.content)
If you are migrating a simple chat endpoint, that may be the whole diff. If you are migrating an agent, keep reading. The model’s long-context and reasoning controls are where subtle breakage hides.

Turn on thinking without making output weird
Z.ai’s migration guide says GLM-5.2 supports larger context and output, a reasoning_effort parameter, deep thinking, normal streaming, and streaming output during tool calls through tool_stream=true. The same guide lists defaults worth noticing: temperature defaults to 1.0, top_p defaults to 0.95, and Z.ai recommends tuning one, not both.
For production coding agents, start boring. Use a low temperature or deterministic sampling, cap output, and only raise reasoning effort when the task actually needs it.
response = client.chat.completions.create(
model="glm-5.2",
messages=[
{"role": "system", "content": "Follow repository rules. Do not invent APIs."},
{"role": "user", "content": "Plan a safe migration from Flask blueprints to FastAPI routers."},
],
thinking={"type": "enabled"},
reasoning_effort="high",
temperature=0.2,
max_tokens=3000,
)
The core parameter docs list thinking as enabled by default for GLM-4.5 and above, while the GLM-5.2 migration guide documents reasoning_effort for GLM-5.2. Translation: do not blindly copy a creative-writing preset into a refactoring agent. A model with a 1M-token room and a high-variance sampling setup can produce an impressive amount of chaos.
Stream responses and tool calls correctly
Streaming has two separate concerns. First, normal response streaming: you need to handle both reasoning deltas and answer deltas. Second, tool-call streaming: when tool_stream=true, function arguments can arrive in pieces, so your client must concatenate partial argument strings before parsing JSON.
stream = client.chat.completions.create(
model="glm-5.2",
messages=[
{"role": "user", "content": "Summarize the risk in this migration plan."}
],
stream=True,
thinking={"type": "enabled"},
reasoning_effort="high",
max_tokens=1500,
)
reasoning = []
answer = []
for chunk in stream:
delta = chunk.choices[0].delta
if getattr(delta, "reasoning_content", None):
reasoning.append(delta.reasoning_content)
if getattr(delta, "content", None):
answer.append(delta.content)
print(delta.content, end="", flush=True)
For tool calls, treat the stream as an assembly job. Do not parse until the call is complete.
tools = [{
"type": "function",
"function": {
"name": "lookup_issue",
"description": "Fetch a GitHub issue by number.",
"parameters": {
"type": "object",
"properties": {"number": {"type": "integer"}},
"required": ["number"],
},
},
}]
stream = client.chat.completions.create(
model="glm-5.2",
messages=[{"role": "user", "content": "Find the issue blocking the release."}],
tools=tools,
stream=True,
tool_stream=True,
)
tool_args = {}
for chunk in stream:
delta = chunk.choices[0].delta
for call in getattr(delta, "tool_calls", []) or []:
index = call.index
piece = call.function.arguments or ""
tool_args[index] = tool_args.get(index, "") + piece
# Parse tool_args[index] only after the stream finishes.
This is the kind of detail benchmark posts skip. It is also the kind of detail that makes an agent fail at 2:13 a.m. because your JSON parser tried to parse half a function argument.
Use the 1M context window like an engineer
The most tempting GLM-5.2 demo is “paste the whole repo.” Sometimes that is correct. The official docs explicitly position the model for project-level codebase understanding, long-horizon refactoring, production-standard stress tests, mobile debugging loops, and research reproduction. That maps cleanly to real agent tasks where local snippets are not enough.
Start with an audit prompt before asking it to write code:
Read the repository context and produce:
1. Core modules and ownership boundaries
2. Public API contracts that must not change
3. Data flows and side effects
4. Build, test, and lint commands
5. Risky files to avoid editing without review
6. A safe implementation plan with rollback points
Then scope the actual task. Big context should reduce re-discovery, not eliminate engineering boundaries. The cautionary lesson from SWE-CI’s maintenance benchmark still applies: coding agents can pass a local task and damage future maintainability. More context helps, but tests, diffs, and review are not optional decorations.
GLM-5.2 pricing math
Z.ai’s pricing page lists the GLM-5.2 text-model rates per 1 million tokens:
| Token type | GLM-5.2 price | Why it matters |
|---|---|---|
| Input | $1.40 / 1M tokens | Large repo prompts get expensive quickly. |
| Cached input | $0.26 / 1M tokens | Repeated project context is where caching matters. |
| Output | $4.40 / 1M tokens | Long plans and generated patches cost more than reads. |
A 600K-token repository audit with 20K output is not terrifying: about $0.84 of input plus $0.09 of output before cache effects. Repeat that prompt carelessly 50 times and the joke becomes an invoice. Cache stable context, keep task prompts small, and do not ask for 20-page essays when you need a patch plan.
Should you migrate to GLM-5.2?
Migrate a small slice first if your stack already uses chat completions, you need long-context coding runs, or you are comparing alternatives to Claude Code, Codex, Cursor, and Windsurf. Our AI coding assistant comparison is still the broader workflow map; GLM-5.2 is another model option inside that larger toolchain decision.
Do not migrate blindly if your agent depends on exact output shape, deterministic tool arguments, or deeply tuned prompts from another model. Run regression tests around tool calls, max-token behavior, latency, and cost. If you already tested Moonshot’s coding stack through our Kimi Code CLI tutorial, the same lesson carries over: Chinese model labs are no longer just cheap benchmark noise. They are becoming practical developer infrastructure.
The GLM-5.2 API is easiest to try through the OpenAI-compatible client. The hard part is not the first request. The hard part is designing an agent loop that uses 1M context with discipline. Give the model the whole map when it needs the map. Do not hand it the entire warehouse because you misplaced a screwdriver.
Get the Daily Pulse
Sharp analysis on what's actually moving in AI. No hype, no filler, no weekly digest.



