Skip to main content
z-ai avatar

GLM-5.2 API

z-ai/glm-5.2

Open-weight (MIT) thinking model for agentic coding and long-horizon reasoning, with a 1M-token context, seven levels of thinking effort, tool calling and streaming over an OpenAI-compatible chat endpoint.

Context window
1M tokens
Max output
131.1K tokens
Input
$1.4 / 1M tokens
Output
$4.4 / 1M tokens
Cached input
$0.35 / 1M tokens
Modalities
text → text
Features
reasoningtool callingjson modestreaming

Connect to GLM-5.2

GLM-5.2 is served through an OpenAI-compatible chat completions API. Point any OpenAI SDK or OpenAI-compatible tool at the base URL below with a ModelRunner API key — no polling, the reply comes back in the response (or streams).

base_url
https://queue.modelrunner.run/z-ai/glm-5.2
model
z-ai/glm-5.2
auth
Authorization: Bearer <MODELRUNNER_API_KEY>get a key
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://queue.modelrunner.run/z-ai/glm-5.2",
    api_key=os.environ["MODELRUNNER_API_KEY"],
)

completion = client.chat.completions.create(
    model="z-ai/glm-5.2",
    messages=[
      {
        "role": "user",
        "content": "Explain what an API rate limit is in two sentences."
      }
    ],
    reasoning_effort="medium",  # low | medium | high — thinking bills as output tokens
)
print(completion.choices[0].message.content)

# Streaming: add stream=True and iterate the chunks
# for chunk in client.chat.completions.create(..., stream=True):
#     print(chunk.choices[0].delta.content or "", end="")
Works withCline · Continue · Claude Code · LangChain · Vercel AI SDK · LiteLLM · Aider

Cline → Settings → API Configuration (or the CLI line below)

API Provider:  OpenAI Compatible
Base URL:      https://queue.modelrunner.run/z-ai/glm-5.2
API Key:       <your ModelRunner API key>
Model ID:      z-ai/glm-5.2

# Cline CLI equivalent
cline auth --provider openai --baseurl https://queue.modelrunner.run/z-ai/glm-5.2 --modelid z-ai/glm-5.2 --apikey <your ModelRunner API key>

Streaming via SSE (stream: true; ends with data: [DONE]) · Non-streaming calls time out at ~290 s — stream long generations · 10 MB request body · Errors use the OpenAI error envelope · Optional metadata object for your own tags, never sent to the model · Many models, one provider entry: base_url https://queue.modelrunner.run/v1 (GET /v1/models lists ids; model field required)

From an MCP client (Claude Desktop, Cursor, Claude Code): connect the ModelRunner MCP server once and its run_model tool runs GLM-5.2 with a messages input — the reply comes back in the same call.

Machine-readable: OpenAPI schema · llms.txt

Example conversation

A real run of GLM-5.2 on ModelRunner · charged $0.0094 · 98 in / 2,110 out / 1,577 reasoning tokens

Find every bug in this function, explain each one, then give a corrected version with its time and space complexity. def merge_intervals(intervals): intervals.sort() merged = [intervals[0]] for start, end in intervals[1:]: if start < merged[-1][1]: merged[-1][1] = end else: merged.append([start, end]) return merged

The function `merge_intervals` contains several bugs. Here’s a breakdown:

### 1. **No handling of empty input** If `intervals` is an empty list, `merged = [intervals[0]]` raises an `IndexError`.

### 2. **Incorrect overlap condition** The condition `if start < merged[-1][1]` only checks if the current interval’s start is strictly less than the last merged interval’s end. - It misses intervals that just touch (e.g., `[1,2]` and `[2,3]`) when the problem expects them to be merged. - Even if changed to `<=`, the logic only sets `merged[-1][1] = end`, which **shrinks** the merged interval when the current end is smaller than the existing one (e.g., `[1,5]` and `[2,3]` would become `[1,3]` instead of staying `[1,5]`). The correct update is `merged[-1][1] = max(merged[-1][1], end)`.

### 3. **Mutates the input list in-place** `intervals.sort()` reorders the original list. Callers may not expect their input to be modified.

### 4. **Aliases and modifies the original interval objects** `merged = [intervals[0]]` stores a reference to the very first interval object (after sorting). When the code does `merged[-1][1] = end`, it directly changes the original interval’s end value. This is a side effect that can corrupt the caller’s data.

---

## Corrected Version

```python def merge_intervals(intervals): if not intervals: return [] # Work on a sorted copy to avoid mutating the input sorted_intervals = sorted(intervals, key=lambda x: x[0]) # Copy the first interval so we don't modify the original merged = [list(sorted_intervals[0])] for start, end in sorted_intervals[1:]: last = merged[-1] if start <= last[1]: # overlapping or touching last[1] = max(last[1], end) # extend only if needed else: merged.append([start, end]) return merged ```

### Complexity - **Time:** O(n log n) due to sorting (n = number of intervals). The subsequent loop is O(n). - **Space:** O(n) for the sorted copy and the output list of merged intervals.

Model Pricing

Pricing

This model is billed per token, at separate rates for what you send and what it produces.

Input tokens
$1.4
per 1M tokens
Cached input tokens
$0.35
per 1M tokens
Output tokens
$4.4
per 1M tokens

If a run reports no token usage, it bills a flat $0.02.

Real run: the example conversation above was charged $0.0094 for 98 input and 2,110 output tokens (of which 1,577 thinking).

Cost estimator

Estimate from the rates above — your bill is the model's reported usage × rate, exact to 6 decimals.

Per request$0.00500
Per day$5.001,000 requests

This model thinks before it answers. Thinking tokens bill at the output rate and are often several times the visible reply — count them in the output figure, or set a lower reasoning effort.

Compare tiers and related models

ModelInput / 1MOutput / 1MContextMax outputFeatures
GLM-5.2z-ai/glm-5.2$1.4$4.41M131.1Kreasoning, tool calling, json mode
GLM-5.2 Fast Previewz-ai/glm-5.2-fast-preview$2.8$8.81M131.1Kreasoning, tool calling, json mode
DeepSeek V4 Prodeepseek/v4$2.4$4.81M393.2Kreasoning, tool calling, json mode
Gemini 3.5 Flashgoogle/gemini-3.5-flash$1.5$91M65.5Kreasoning, tool calling, json mode
Gemini 3.5 Flash-Litegoogle/gemini-3.5-flash-lite$0.3$2.51M65.5Ktool calling, json mode
Gemini 3.7 Flashgoogle/gemini-3.7-flash$0.75$3.751M65.5Kreasoning, tool calling, json mode
Qwen3.8-Maxalibaba/qwen3.8-max$2$61M131.1Kreasoning, tool calling, json mode

Request parameters

The body follows OpenAI’s chat completions shape. Fields below are the ones this model documents; anything else the platform does not interpret is forwarded to the model unchanged, and the model is the authority on what it accepts.

Request parameters of GLM-5.2
NameTypeRequiredDescription
messagesarrayyesOpenAI-style conversation history. Each item is an object with a role (system, user, assistant or tool) and content.
streambooleannoReturn the reply as a Server-Sent Events stream of deltas terminated by data: [DONE]. Default: false.
reasoning_effortenumnoHow hard the model thinks before answering, across seven levels. Defaults to max, the highest — lower it to cut cost, because thinking tokens bill as output tokens. none disables reasoning entirely. One of: none, minimal, low, medium, high, xhigh, max. Default: "max".
max_tokensintegernoUpper bound on generated tokens, up to the documented 131,072-token output ceiling. Thinking consumes this budget, so allow generous headroom.
toolsarraynoOpenAI-format tool definitions the model may call.
tool_choicenoauto, none, required, or a specific tool.
response_formatobjectnoStructured-output control. Set its type to json_object to force a JSON reply.
stopnoUp to 4 stop sequences.
seedintegernoBest-effort determinism hint.

Response

An OpenAI ChatCompletion object: id, object, created, model, choices[] and usage. Cache hits surface at usage.prompt_tokens_details.cached_tokens; thinking, where the model reports it, at usage.completion_tokens_details.reasoning_tokens — thinking tokens are billed as output tokens. The id is chatcmpl-<requestId>, and the same request appears in your dashboard.

About GLM-5.2

GLM-5.2 is an open-weight **thinking model**, MIT-licensed, built for agentic engineering. It reasons internally before answering, and the brand publishes results close to the closed frontier on long-horizon coding work: **62.1 on SWE-Bench Pro** and **81.0 on Terminal-Bench 2.1**, plus second place across FrontierSWE, PostTrainBench and SWE-Marathon and the highest-ranked open-source model on all three. You send `messages`, you get a chat completion.

Best for

  • Agentic coding: multi-step bug fixing, refactoring and terminal tasks
  • Long-context code review across an entire repository in one prompt
  • Open-weight MIT model when a closed frontier model is not an option
  • Dial thinking effort up or down to trade answer quality against cost
  • Tool calling and structured JSON output inside an autonomous agent loop

How it thinks

GLM-5.2 reasons before it answers. Set reasoning_effort to none, minimal, low, medium, high, xhigh or max (default max) to trade answer quality against latency and cost. Thinking tokens are billed at the output rate and reported as usage.completion_tokens_details.reasoning_tokens.

Notesshow the full description ›

Thinking is tunable through `reasoning_effort` across **seven** levels — `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` — a wider range than the usual three. **The default is `max`, the most expensive setting**: it gives the strongest answers and the largest bill, because thinking tokens are billed as output tokens. Drop to `low` or `medium` for routine work; `none` turns reasoning off entirely and returns zero reasoning tokens. It also accepts its own `enable_thinking: false` switch, which overrides `reasoning_effort` — unknown fields are forwarded verbatim — but prefer `reasoning_effort` alone, since the two overlap. A live call also returned the chain of thought in a `message.reasoning_content` field beside `content` — observed behaviour, not a documented guarantee.

The context window is 1M tokens and a single reply can run to 131,072 tokens; the brand describes the context as stably sustaining long-horizon work — large-scale implementation, automated research, performance optimisation and complex debugging. Repeated prompt prefixes are cached automatically and bill at the reduced cached-input rate.

## Choose another model when - Your input includes images, audio or video — this is a text-only model - A single reply has to exceed 131,072 tokens — that is the published output ceiling, and thinking tokens count against it - You want the cheapest possible tokens for bulk classification, tagging or translation — this model thinks at `max` by default and bills that thinking as output tokens - Wall-clock latency is your binding constraint — `z-ai/glm-5.2-fast-preview` runs the same weights on throughput-tuned serving at twice the token price

## Tips - Structured output works in non-thinking mode only — pair `response_format` with `reasoning_effort: "none"` - Budget `max_tokens` generously — at `max` effort most of it goes to thinking, and too small a budget returns an empty reply you still pay for

Behaviour & limits

Context window
1M tokens (input + output)
Max output
131.1K tokens per reply — thinking counts against this budget
Structured calls
OpenAI-format tools + tool_choice · response_format JSON mode
Transport
OpenAI-compatible chat completions · SSE streaming · ~290 s non-stream ceiling · 10 MB body

FAQ

How do I connect to GLM-5.2 through the API?

GLM-5.2 is served by an OpenAI-compatible chat completions endpoint. Point any OpenAI SDK or OpenAI-compatible tool at base_url https://queue.modelrunner.run/z-ai/glm-5.2 with a ModelRunner API key (Authorization: Bearer <key>) and model z-ai/glm-5.2; the SDK appends /chat/completions itself. The call is synchronous — the reply comes back in the response body, or streams as Server-Sent Events with "stream": true. Do not submit it to the asynchronous queue path, which returns HTTP 400 for this model.

How much does GLM-5.2 cost?

GLM-5.2 is billed per token from the usage the model reports: $1.4 per 1M input tokens, $0.35 per 1M cached input tokens, $4.4 per 1M output tokens. Thinking (reasoning) tokens bill at the output rate. There is no per-request minimum — a short call bills a fraction of a cent, exact to six decimals.

What is GLM-5.2's context window?

GLM-5.2 supports a 1M-token context window and up to 131.1K output tokens per reply — thinking tokens count against the output budget, so leave headroom in max_tokens.

Can I use GLM-5.2 in GitHub Copilot or another tool that requires a /models endpoint?

Yes. Custom-provider flows that probe GET {base_url}/models before first use (GitHub Copilot's BYOK flow does) work with either base URL: https://queue.modelrunner.run/z-ai/glm-5.2 self-describes at https://queue.modelrunner.run/z-ai/glm-5.2/models, and the platform base https://queue.modelrunner.run/v1 covers every public chat model with one provider entry — GET /v1/models lists the ids and the request's model field selects z-ai/glm-5.2.

Does GLM-5.2 support streaming?

Yes. Set "stream": true and the reply arrives as Server-Sent Events (data: frames ending with data: [DONE]); stream_options: {"include_usage": true} adds a final usage frame. Non-streaming calls are cut off at about 290 seconds, so stream long generations.

Does GLM-5.2 support tool calling or JSON mode?

GLM-5.2 supports function calling via an OpenAI-format tools array with tool_choice and JSON mode via response_format {"type": "json_object"}. Both are passed through to the model in the standard OpenAI chat completions shape, so existing client code works unchanged.

What happens if my ModelRunner balance runs out while calling GLM-5.2?

The request is refused with HTTP 429 and an OpenAI-style error whose code is insufficient_quota — the convention OpenAI SDKs already understand — and nothing is charged. Top up in the dashboard and retry. (Disconnecting from a stream after output has started is not a refund — the platform finishes the upstream call and bills its exact usage.)