If you are already using OpenRouter to manage multiple LLM providers under one API key, you can now add GLM 5.2 to that stack without creating a Z.ai account. The model ID is z-ai/glm-5.2, the base URL is https://openrouter.ai/api/v1, and the code change from any OpenAI-compatible integration is three fields.
This guide walks through the setup end to end — prerequisites, working code in Python and JavaScript, pricing comparison against Z.ai direct, and a troubleshooting table for the errors most people hit on the first call.
The Short Version
GLM 5.2 is a 753B-parameter Mixture of Experts model (40B active) with a 1M-token context window, 158 tokens per second throughput, and an AA Intelligence Index score of 51. It scores 89% on GPQA Diamond and 62.1% on SWE-bench Pro. On Z.ai direct, input costs $1.40/M tokens and output costs $4.40/M tokens. On OpenRouter, the price may carry a small routing margin — check openrouter.ai/models for the live rate.
Use OpenRouter if you want a single API key for GLM 5.2 plus other frontier models, unified billing, or a drop-in model-switch path.
Use Z.ai direct if you want the lowest possible latency (no routing hop), direct pricing with no margin, or access to Z.ai-specific features like cache hits at $0.26/M tokens.
Prerequisites
- An OpenRouter account with an API key from openrouter.ai
- Python 3.8+ with
openaipackage, or Node.js 18+ with theopenainpm package - Basic familiarity with REST APIs or the OpenAI SDK
No Z.ai account is required when routing through OpenRouter.
Quick Specs
| Property | Value |
|---|---|
| OpenRouter model ID | z-ai/glm-5.2 |
| Base URL | https://openrouter.ai/api/v1 |
| Context window | 1,048,576 tokens (1M) |
| Parameters | 753B total / 40B active (MoE) |
| Speed | 158 t/s |
| TTFT | 1.54s |
| Z.ai input price | $1.40/M tokens |
| Z.ai output price | $4.40/M tokens |
| Cache hit (Z.ai) | $0.26/M tokens |
| License | MIT (open weights) |
Step 1 — Get Your OpenRouter API Key
Go to openrouter.ai, create an account, and generate an API key in the dashboard. This is a separate key from a Z.ai key — OpenRouter manages billing on its own.
Add credit to your OpenRouter account. GLM 5.2 is a frontier-class model, so you will need a positive balance to make calls.
Store the key as an environment variable rather than hardcoding it:
export OPENROUTER_API_KEY="sk-or-..."Step 2 — Install the OpenAI SDK
OpenRouter is OpenAI-compatible, so you use the same openai package you likely already have:
pip install openaiOr for Node.js:
npm install openaiStep 3 — Make Your First Call (Python)
The only changes from a standard OpenAI call are api_key, base_url, and model. Everything else — messages format, streaming, system prompts, temperature — works identically.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["OPENROUTER_API_KEY"],
base_url="https://openrouter.ai/api/v1",
)
response = client.chat.completions.create(
model="z-ai/glm-5.2",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain Mixture of Experts in two sentences."},
],
max_tokens=512,
)
print(response.choices[0].message.content)Step 4 — Make Your First Call (JavaScript / TypeScript)
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.OPENROUTER_API_KEY,
baseURL: "https://openrouter.ai/api/v1",
});
const response = await client.chat.completions.create({
model: "z-ai/glm-5.2",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Explain Mixture of Experts in two sentences." },
],
max_tokens: 512,
});
console.log(response.choices[0].message.content);Step 5 — Streaming Responses
For long outputs or chat interfaces, streaming reduces perceived latency significantly. GLM 5.2's 1.54s TTFT means you start seeing tokens in under two seconds.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["OPENROUTER_API_KEY"],
base_url="https://openrouter.ai/api/v1",
)
stream = client.chat.completions.create(
model="z-ai/glm-5.2",
messages=[
{"role": "user", "content": "Write a Python function to parse JSON safely."},
],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)Step 6 — Using the Long Context Window
GLM 5.2 has a 1,048,576-token context window. To use it, set max_tokens for your output and pass a large messages array. OpenRouter supports the full context length, but be aware that very long prompts cost proportionally more.
Practical capacities for the 1M window:
- ~750,000 words of plain text (a full novel)
- ~40,000 lines of code across dozens of files
- Long document QA without chunking or retrieval
response = client.chat.completions.create(
model="z-ai/glm-5.2",
messages=[
{"role": "system", "content": "You are a code reviewer."},
{"role": "user", "content": very_long_codebase_string},
],
max_tokens=4096,
)Step 7 — Switching From Another Model
If you are already calling another model on OpenRouter, the migration is one line:
# Before (e.g., DeepSeek V3)
model="deepseek/deepseek-chat-v3-0324"
# After (GLM 5.2)
model="z-ai/glm-5.2"The messages format, authentication, and everything else stays the same. This is the primary advantage of the OpenRouter routing layer — you can run A/B tests between GLM 5.2 and models like deepseek/deepseek-v3 or moonshotai/kimi-k2 by swapping a single string.
Pricing Comparison
| Route | Input | Output | Cache Hit | Routing overhead |
|---|---|---|---|---|
| Z.ai direct | $1.40/M | $4.40/M | $0.26/M | None |
| OpenRouter | Check live rate | Check live rate | Varies | Small margin possible |
For the current OpenRouter rate, visit openrouter.ai/models and search for z-ai/glm-5.2. Rates update as providers adjust pricing.
When the margin matters: For high-volume workloads — millions of tokens per day — even a small per-token margin adds up. At that scale, Z.ai direct is the cheaper path. For moderate usage or development, the convenience of a single billing account typically outweighs the difference.
Cache hits: Z.ai direct exposes a $0.26/M cache hit rate for repeated prompt prefixes. If your application sends the same system prompt or document to many requests, this can cut effective input cost by over 80%. OpenRouter cache behavior depends on whether it passes cache signals through to the upstream provider.
For a full breakdown of Z.ai pricing, see our GLM 5.2 pricing guide.
Benchmark Performance
| Benchmark | GLM 5.2 Score |
|---|---|
| GPQA Diamond | 89% |
| SWE-bench Pro | 62.1% |
| Terminal-Bench v2.1 | 78% |
| HumanEval | 90%+ |
| AA Intelligence Index | 51 |
These numbers are the same regardless of whether you access the model via OpenRouter or Z.ai direct — the model weights are identical. The routing layer adds no effect on output quality, only on latency (one extra network hop) and pricing.
GLM 5.2's 89% GPQA Diamond score places it in the top tier of currently available frontier models for scientific reasoning. Its 62.1% SWE-bench Pro score makes it competitive for autonomous coding tasks. Both benchmarks are discussed in detail in our GLM 5.2 benchmarks guide.
Speed and Latency
| Metric | Value | Source |
|---|---|---|
| Throughput | 158 t/s | Artificial Analysis |
| TTFT | 1.54s | Artificial Analysis |
| Rank | 3rd fastest frontier model | Artificial Analysis |
OpenRouter adds a small routing hop compared to Z.ai direct. In practice this means an extra ~50–150ms on top of the 1.54s TTFT, depending on your network and OpenRouter's current load. For interactive chat, this is imperceptible. For latency-sensitive pipelines processing thousands of requests per minute, measure both routes in your environment before committing.
Architecture Notes
GLM 5.2 uses a Mixture of Experts (MoE) architecture: 753B total parameters, but only 40B are active per forward pass. Each token routes through 8 of 256 experts per layer, across 78 transformer decoder layers. This design is what enables the 158 t/s throughput at frontier-level quality — MoE is more compute-efficient at inference than a dense model of equivalent size.
The model uses Dynamic Sparse Attention (DSA), which helps maintain quality at the 1M-token context length without quadratic attention cost.
GLM 5.2 is text-only. It does not accept image or audio input. If you need multimodal input, you will need a different model for that step of your pipeline.
Common Issues
| Error | Likely Cause | Fix |
|---|---|---|
401 Unauthorized | Wrong or missing API key | Check OPENROUTER_API_KEY is set and the key is from openrouter.ai, not Z.ai |
404 Not Found on model | Model ID typo | Use exactly z-ai/glm-5.2 (note the hyphen, not underscore) |
402 Payment Required | Insufficient OpenRouter credits | Add credit at openrouter.ai/account |
429 Rate Limited | Too many concurrent requests | Implement exponential backoff; check your OpenRouter plan limits |
| Empty response / timeout | Very long prompt near context limit | Reduce prompt length or increase client timeout |
context_length_exceeded | Output tokens + input tokens > 1,048,576 | Reduce max_tokens or shorten the input |
Frequently Asked Questions
Is the model the same quality through OpenRouter versus Z.ai direct?
Yes. OpenRouter routes your request to the same underlying model. The weights, output, and benchmark performance are identical. The difference is only in latency (one extra network hop), pricing (possible routing margin), and which API key you use.
Do I need a Z.ai account to use GLM 5.2 on OpenRouter?
No. OpenRouter handles the upstream provider relationship. You only need an OpenRouter account and API key. This is the main convenience argument for OpenRouter — one account gives you access to GLM 5.2 alongside DeepSeek, Kimi, and other models.
Can I use the OpenAI Python SDK with OpenRouter?
Yes, that is the standard approach. Set base_url="https://openrouter.ai/api/v1" and pass your OpenRouter API key. The SDK communicates with OpenRouter's OpenAI-compatible endpoint without modification.
Does OpenRouter support the full 1M-token context window?
OpenRouter passes context length constraints through to the upstream provider. GLM 5.2's full 1,048,576-token window is available. However, very long prompts will incur proportionally higher costs — calculate token count before sending large payloads.
Is GLM 5.2 open source? Can I run it myself?
Yes. GLM 5.2 is released under an MIT license with open weights available on Hugging Face at THUDM/GLM-5.2. Self-hosting 753B parameters requires significant GPU infrastructure (multiple H100 or H200 nodes), so most teams use the hosted API for development and production.
How do I pick between GLM 5.2 and other models on OpenRouter?
For coding and scientific reasoning tasks, GLM 5.2's 89% GPQA Diamond and 62.1% SWE-bench Pro are strong signals. For tasks that benefit from extremely long context (full codebase review, long document QA), the 1M-token window is a practical advantage over models with shorter limits. For tasks requiring image input, you will need a multimodal model — GLM 5.2 is text-only.
What other headers does OpenRouter recommend?
OpenRouter accepts optional headers like HTTP-Referer and X-Title for usage attribution in their dashboard. These are not required for the API to work but can help you track usage per application:
client = OpenAI(
api_key=os.environ["OPENROUTER_API_KEY"],
base_url="https://openrouter.ai/api/v1",
default_headers={
"HTTP-Referer": "https://your-app.com",
"X-Title": "Your App Name",
},
)Next Steps
Once your first call works, consider these next steps:
- Benchmark your use case: Run your actual prompts through both Z.ai direct and OpenRouter to measure latency difference in your environment.
- Test long context: If your application handles documents or codebases, test the 1M window — it eliminates chunking complexity for many retrieval tasks.
- Compare models: The single-key advantage of OpenRouter makes it easy to A/B test GLM 5.2 against other frontier models by swapping the
modelstring. - Monitor costs: Set spending limits in your OpenRouter dashboard and log token counts per request to track costs as you scale.
For a comparison of GLM 5.2 against other top models, see our GLM 5.2 vs DeepSeek V3 guide.
Try GLM 5.2 — no API key needed: glm5.app/chat.

