Text
glm-5-4
Use GLM 5.4 through reAPI Chat Completions. Official Z.AI OpenAPI parameters, forced deep thinking, streaming tool calls, multimodal URLs, and dated checks.
GLM 5.4 uses POST https://api.reapi.ai/v1/chat/completions (OpenAI Chat Completions, primary) and also accepts POST https://api.reapi.ai/v1/messages (Anthropic Messages, for Anthropic SDKs and Claude Code) with the exact model ID glm-5.4. Each request returns a synchronous JSON payload or an SSE stream rather than an asynchronous task ID. Current pricing and playground.
The request surface mirrors Z.AI's official OpenAPI 3.0.1 Chat Completion schema for glm-5.4. Extra fields pass through unchanged; acceptance alone does not guarantee every upstream option changes the output. The dated checks below separate verified behavior from current channel caveats.
Quickstart
Create a key in API keys and keep it on your backend. These snippets send a single request with SDK auto-retries turned off so client retries stay explicit.
curl https://api.reapi.ai/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5.4",
"messages": [{"role": "user", "content": "Design a lock-free ring buffer in Rust and explain its memory ordering."}],
"thinking": {"type": "enabled", "clear_thinking": false},
"reasoning_effort": "low"
}'from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.reapi.ai/v1",
max_retries=0,
)
response = client.chat.completions.create(
model="glm-5.4",
messages=[
{
"role": "user",
"content": "Design a lock-free ring buffer in Rust and explain its memory ordering.",
}
],
extra_body={
"thinking": {"type": "enabled", "clear_thinking": false},
"reasoning_effort": "low",
},
)
print(response.choices[0].message.content)
# Keep the unmodified assistant message (including reasoning_content and tool_calls) for follow-up turns.
assistant_message = response.choices[0].message.model_dump(exclude_none=True)import OpenAI from 'openai';
const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://api.reapi.ai/v1',
maxRetries: 0,
});
const response = await client.chat.completions.create({
model: 'glm-5.4',
messages: [
{
role: 'user',
content: 'Design a lock-free ring buffer in Rust and explain its memory ordering.',
},
],
thinking: { type: 'enabled', clear_thinking: false },
reasoning_effort: 'low',
});
console.log(response.choices[0].message.content);
const assistantMessage = response.choices[0].message;package main
import (
"bytes"
"io"
"net/http"
"os"
"time"
)
func main() {
body := []byte(`{"model":"glm-5.4","messages":[{"role":"user","content":"Design a lock-free ring buffer in Rust and explain its memory ordering."}],"thinking":{"type":"enabled","clear_thinking":false},"reasoning_effort":"low"}`)
req, err := http.NewRequest("POST", "https://api.reapi.ai/v1/chat/completions", bytes.NewReader(body))
if err != nil { panic(err) }
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 120 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }}
res, err := client.Do(req)
if err != nil { panic(err) }
defer res.Body.Close()
if _, err := io.Copy(os.Stdout, res.Body); err != nil { panic(err) }
if res.StatusCode >= 400 { os.Exit(1) }
}Endpoint
POST https://api.reapi.ai/v1/chat/completions
Pass Authorization: Bearer YOUR_API_KEY and Content-Type: application/json. Responses use application/json, or text/event-stream when stream: true. Use the lowercase model ID glm-5.4. There is no task-polling endpoint.
Official input parameters
The table below covers all 16 top-level parameters in Z.AI's OpenAPI 3.0.1 Chat Completion schema for glm-5.4, checked December 4, 2026. Omitted optional fields use Z.AI's defaults.
| Parameter | Type | Required / default | Meaning |
|---|---|---|---|
model | string | Required | Model ID: glm-5.4. |
messages | array | Required | Conversation history (system, user, assistant, tool). user content may be a string or multimodal array (text, image_url, video_url, file). |
do_sample | boolean | true | Enables sampling. Set false for greedy decoding (temperature and top_p will not take effect). |
stream | boolean | false | Set true for Server-Sent Events (SSE) ending with data: [DONE]. |
thinking | object | {"type":"enabled","clear_thinking":false} | Chain-of-thought settings. type only accepts "enabled" on glm-5.4 ("disabled" returns HTTP 400). clear_thinking defaults to false to preserve historical reasoning across turns. |
reasoning_effort | string | "max" | Reasoning depth: "low", "high", or "max". Other strings ("medium", "xhigh", "minimal", "none") return HTTP 400 on glm-5.4. |
temperature | number | 1.0 | Sampling randomness in [0.0, 1.0]. Adjust either temperature or top_p, not both at once. |
top_p | number | 0.95 | Nucleus sampling in [0.01, 1.0]. Adjust either temperature or top_p, not both at once. |
max_tokens | integer | Omitted | Maximum generated tokens (thinking plus visible answer), range 1–131072 (128K). Use max_tokens; upstream ignores max_completion_tokens. |
tool_stream | boolean | false | Streams function-call argument deltas in real time when paired with stream: true. |
tools | array | Omitted | Up to 128 tool definitions. Function tools (type: "function") are live-verified; see channel notes below for built-in web_search and retrieval. |
tool_choice | string | "auto" | Tool selection mode when tools is provided. Only "auto" is supported. |
stop | string[] | Omitted | Up to 4 items in schema (Z.AI currently applies 1 stop string, e.g. ["END"]). |
response_format | object | {"type":"text"} | Output mode: {"type":"text"} or {"type":"json_object"}. |
request_id | string | Omitted | Optional caller-supplied unique ID (6–64 characters). |
user_id | string | Omitted | Optional end-user identifier (6–128 characters). Avoid PII. |
Output cap and passthrough notes
max_tokensvsmax_completion_tokens: Usemax_tokensforglm-5.4. In our December 4, 2026 live checks,max_tokens: 30stopped cleanly at 30 completion tokens (finish_reason: "length"), whilemax_completion_tokens: 30was ignored upstream and generated 610 tokens. reAPI writes the admitted cap ontomax_tokensso billing bounds stay accurate.- Single-choice responses:
nis not part of Z.AI's schema. Sendingn: 2returns HTTP 200 with a single choice (choices.length === 1), so reAPI bills one choice. - Context window: 1,048,576 tokens (1M) shared across input, preserved thinking, tool history, and output. No full 1M-token stress test was run during integration verification.
Preserved thinking and streaming tool calls
Starting with glm-5.4, Z.AI enables Preserved Thinking (thinking.clear_thinking: false) by default across all endpoints. Return the complete, unmodified assistant message from each turn — including reasoning_content and tool_calls — so later turns keep coherent reasoning. Execute tools in your application, then append one role: "tool" message per tool_call_id.
For low-latency agent loops, pass both stream: true and tool_stream: true and concatenate delta.tool_calls[index].function.arguments:
tools = [{
"type": "function",
"function": {
"name": "get_deploy_status",
"description": "Return the latest deployment status for a service.",
"parameters": {
"type": "object",
"properties": {"service": {"type": "string"}},
"required": ["service"],
},
},
}]
stream = client.chat.completions.create(
model="glm-5.4",
messages=[{"role": "user", "content": "Check deployment status for billing-api."}],
tools=tools,
tool_choice="auto",
stream=True,
extra_body={
"thinking": {"type": "enabled", "clear_thinking": False},
"reasoning_effort": "low",
"tool_stream": True,
},
)
reasoning, content, calls = "", "", {}
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta
if getattr(delta, "reasoning_content", None):
reasoning += delta.reasoning_content
if delta.content:
content += delta.content
for tc in delta.tool_calls or []:
slot = calls.setdefault(tc.index, {"id": "", "name": "", "arguments": ""})
if tc.id:
slot["id"] = tc.id
if tc.function and tc.function.name:
slot["name"] = tc.function.name
if tc.function and tc.function.arguments:
slot["arguments"] += tc.function.argumentsImages, video, and files
glm-5.4 accepts text, image_url, video_url, and file content blocks inside user messages.
Supply publicly reachable https:// or http:// URLs only. reAPI does not accept base64 data: URIs or vendor-side uploaded file_id handles.
- Images (
image_url): JPEG or PNG up to 5 MB per image (max6000 × 6000px). Multipleimage_urlblocks are supported. - Video (
video_url): MP4, MKV, or MOV up to 200 MB via public URL. Standard H.264 MP4 clips succeeded in live probes; some container encodings returned upstream HTTP 400 (code: "1210"). - Files (
file): Pass{"type": "file", "file": {"file_url": "https://..."}}(PDF, TXT, Word, JSONL, XLSX, PPTX; up to 50 MB per file, max 50 files). Mutual exclusion: Z.AI does not allowfileparts in the same request asimage_urlorvideo_url.
{
"model": "glm-5.4",
"reasoning_effort": "low",
"messages": [
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": "https://example.com/diagram.png"}},
{"type": "text", "text": "List every stateful boundary shown in this architecture diagram."}
]
}
]
}Replace example URLs with publicly reachable media you control.
Streaming
Set stream: true for SSE output. Accumulate delta.reasoning_content, delta.content, and indexed delta.tool_calls fragments. reAPI adds stream_options.include_usage: true upstream so the final usage frame arrives before data: [DONE]. Treat any connection drop before [DONE] as an incomplete response.
Capability observations — December 4, 2026
These live probes checked integration behavior through the active gateway; they are not an independent quality benchmark.
| Capability | Observation |
|---|---|
| Non-stream text & billing receipt | HTTP 200; returned answer, reasoning_content, usage, and exact per-request billing receipt. |
| Streaming SSE | HTTP 200 text/event-stream; streamed chunks, emitted trailing usage, and closed with data: [DONE]. |
reasoning_effort levels | low (3 reasoning tokens), high (9), and max (27) all returned HTTP 200 with clear depth progression. medium, xhigh, minimal, and none all returned HTTP 400 (code: "1210"). |
thinking options | {"type":"enabled","clear_thinking":false} and {"type":"enabled","clear_thinking":true} returned HTTP 200. {"type":"disabled"} returned HTTP 400 (code: "1210"). |
| Output caps | max_tokens: 30 strictly capped at 30 completion tokens (finish_reason: "length"). 131072 returned HTTP 200; 131073 returned HTTP 400 (code: "1210"). Direct max_completion_tokens: 30 was ignored upstream (610 tokens returned), so reAPI normalizes caps onto max_tokens. |
Sampling & stop | do_sample: false, temperature: 0.2, top_p: 0.8, request_id, and user_id all returned HTTP 200. stop: ["3"] truncated output cleanly at "1 2 ". |
| Structured output | Both response_format: {"type":"json_object"} and json_schema returned valid JSON. Keep application-side schema validation. |
Function tools & tool_stream | Two-turn function loop with preserved assistant message succeeded; stream: true + tool_stream: true emitted finish_reason: "tool_calls" with arguments and trailing usage. |
Built-in web_search tool | Returned HTTP 400 (code: "1214", tools[0].web_search empty) on the current OpenAI-compatible channel. Use your own function tool for web lookup. |
Public image_url | HTTP 200; accurately described a public PNG image (1,404 prompt tokens). |
Public video_url | HTTP 200 on a standard H.264 MP4 clip (2,275 prompt tokens, accurate description); two other test MP4 files returned HTTP 400 (code: "1210" video format/parse error). |
| Prompt cache probe | Two consecutive 4,530-token identical-prefix calls returned cached_tokens: 0; cache hits were not observed in that short probe, though cache-read billing is wired when reported by upstream. |
Multiple choices (n: 2) | Returned HTTP 200 with 1 choice; reAPI treats glm-5.4 as single-choice for billing safety. |
Anthropic Messages (/v1/messages) | Non-stream JSON (thinking + text blocks), SSE streaming (message_start → content_block_delta → message_stop), and tools (input_schema → tool_use) all returned HTTP 200. |
Anthropic Messages compatibility
If your client uses an Anthropic SDK or Claude Code, you can also send glm-5.4 to POST https://api.reapi.ai/v1/messages with x-api-key and anthropic-version: 2023-06-01:
curl https://api.reapi.ai/v1/messages \
-H "x-api-key: YOUR_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5.4",
"max_tokens": 4096,
"messages": [{"role": "user", "content": "Explain hybrid KV caching in three bullets."}]
}'Use /v1/chat/completions when you need Z.AI-specific controls such as thinking.clear_thinking, tool_stream, or do_sample.
Groups
Check live group prices on the GLM 5.4 page. One reAPI key works across all available groups.
The bare glm-5.4 ID routes to the default glm group. If additional groups appear in the price table, select one explicitly with glm-5.4:<group> as described in LLM groups.
Pricing and billing
Input tokens, output tokens (including thinking tokens), and cached input token reads are metered separately. See current rates on the GLM 5.4 page; no numeric SKU prices are hardcoded in this reference.
Settlement uses integer micro-USD: microUSD = ceil(settled_USD_charge × 1,000,000) and credits = microUSD / 1,000, where 1 credit = $0.001.
reAPI sends exactly one upstream request per accepted API call with no automatic retries and no server-side tool execution. Postpaid settlement requires valid delivery and usage evidence; upstream errors or interrupted responses settle with no charge.
Output schema
A non-streaming response uses the Chat Completions envelope (illustrative token counts):
{
"id": "req_0195f0d4b7a270008000123456789abc",
"object": "chat.completion",
"created": 1796359043,
"model": "glm-5.4",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "A lock-free SPSC ring buffer uses Acquire/Release atomics on head and tail indices...",
"reasoning_content": "Check single-producer vs multi-producer memory ordering constraints..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 118,
"completion_tokens": 94,
"total_tokens": 212,
"prompt_tokens_details": {
"cached_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 31
}
}
}Errors
reAPI errors return error.code, error.message, error.request_id, and Chat-compatible error.type:
| HTTP / code | Meaning |
|---|---|
401 / 10001–10005 | Missing, invalid, or revoked API key. |
400 / 20001, 20002, 20003, 20004 | Invalid JSON, missing fields, invalid parameter value (e.g. thinking.type: "disabled", unsupported reasoning_effort, or max_tokens > 131072), or unknown model ID. |
413 / 20008 | Request payload exceeds limit. |
402 / 30001 | Insufficient balance. |
429 / 50001 | Rate or in-flight concurrency limit reached. |
502–503 / 70001 | Upstream inference or pricing service unavailable. |
See the full error-code catalog.
Tips
- Set
reasoning_effort: "low"for straightforward extraction, formatting, or quick tool calls; leaving the default"max"increases thinking tokens and can trigger long reflection chains on open-ended prompts. - Always cap output with
max_tokens(up to131072) rather thanmax_completion_tokens, and adjust only one oftemperatureortop_p. - For multi-turn coding agents, leave
thinking.clear_thinking: falseand pass back the unmodifiedreasoning_contentandtool_callsfrom each assistant turn.
Related
Compare the GLM 5.2 documentation and MiniMax M4 documentation, or check the GLM 5.4 model page for live pricing and interactive testing.