GLM 5.2 API: Endpoints, Authentication, and Python Integration Guide
Jul 20, 2026

GLM 5.2 API: Endpoints, Authentication, and Python Integration Guide

GLM 5.2 uses the OpenAI SDK format with a different base_url and model name. Here is the complete guide to endpoints, authentication, streaming, and Python integration.

If you have used the OpenAI Python SDK before, integrating GLM 5.2 takes about five minutes. The model is served through Z.ai's API, which is OpenAI-compatible — meaning you change two lines in your existing code (base_url and model) and everything else works the same. This guide walks through authentication, every available endpoint, streaming, function calling, JSON mode, and how to push the full 1M-token context window into practice.

Prerequisites

Before you start, make sure you have the following:

  • A Z.ai account and API key (sign up at api.z.ai)
  • Python 3.8 or later
  • The openai Python package (pip install openai)
  • Basic familiarity with making HTTP requests or using the OpenAI SDK

No special GLM-specific SDK is required. Because the API surface is OpenAI-compatible, any library or tool that already speaks the OpenAI chat-completions format works with GLM 5.2 out of the box.

Step 1: Get Your API Key

Log in to the Z.ai dashboard at api.z.ai. Navigate to API Keys in the sidebar and create a new secret key. Copy it immediately — the dashboard only shows it once.

Store the key as an environment variable rather than hardcoding it:

export Z_AI_API_KEY="your-api-key-here"

On Windows (PowerShell):

$env:Z_AI_API_KEY = "your-api-key-here"

Step 2: Make Your First Request

The two things that differ from the OpenAI API are the base_url and the model name. Everything else — headers, request body shape, response format — is identical.

Base URL: https://api.z.ai/v1
Model name: glm-5.2

Here is a minimal working example using the openai Python library:

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["Z_AI_API_KEY"],
    base_url="https://api.z.ai/v1",
)

response = client.chat.completions.create(
    model="glm-5.2",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain the Mixture of Experts architecture in two sentences."},
    ],
)

print(response.choices[0].message.content)

If you prefer raw HTTP, the equivalent curl command is:

curl https://api.z.ai/v1/chat/completions \
  -H "Authorization: Bearer $Z_AI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "glm-5.2",
    "messages": [
      {"role": "user", "content": "What is GLM 5.2?"}
    ]
  }'

Authentication is a standard HTTP Bearer token. There are no proprietary headers or signing steps.

Step 3: Enable Streaming

For production applications, streaming dramatically improves perceived latency. GLM 5.2 achieves 158 tokens per second throughput, so streaming lets users see output almost immediately after the first token arrives (TTFT of 1.54s).

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["Z_AI_API_KEY"],
    base_url="https://api.z.ai/v1",
)

stream = client.chat.completions.create(
    model="glm-5.2",
    messages=[
        {"role": "user", "content": "Write a short story about a robot learning to cook."},
    ],
    stream=True,
)

for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)

print()  # newline after stream ends

The stream=True parameter switches the response from a single JSON object to a series of server-sent events. Each chunk contains a partial token or an empty string on the final [DONE] signal — the same format as the OpenAI streaming API.

Step 4: Use Function Calling (Tool Use)

GLM 5.2 supports OpenAI-format function calling via the tools parameter. This lets the model decide when to invoke a function and return structured arguments you can execute on the client side.

import os, json
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["Z_AI_API_KEY"],
    base_url="https://api.z.ai/v1",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city.",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "The city name, e.g. Tokyo",
                    }
                },
                "required": ["city"],
            },
        },
    }
]

response = client.chat.completions.create(
    model="glm-5.2",
    messages=[{"role": "user", "content": "What is the weather in Beijing?"}],
    tools=tools,
    tool_choice="auto",
)

message = response.choices[0].message

if message.tool_calls:
    for call in message.tool_calls:
        args = json.loads(call.function.arguments)
        print(f"Function: {call.function.name}, Args: {args}")

When the model decides to call a tool, message.tool_calls is populated with the function name and a JSON string of arguments. You execute the function on your end, append the result to the conversation history with role: "tool", and send the next request — the same multi-turn tool loop as the OpenAI API.

Step 5: Request Structured JSON Output

For pipelines that need machine-readable output — classification labels, extracted entities, structured reports — use JSON mode. Pass response_format={"type": "json_object"} and instruct the model in the system prompt to respond with JSON:

import os, json
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["Z_AI_API_KEY"],
    base_url="https://api.z.ai/v1",
)

response = client.chat.completions.create(
    model="glm-5.2",
    messages=[
        {
            "role": "system",
            "content": "You are a data extraction assistant. Always respond with valid JSON.",
        },
        {
            "role": "user",
            "content": "Extract the company name, founding year, and headquarters from: "
                       "'Anthropic was founded in 2021 and is headquartered in San Francisco.'",
        },
    ],
    response_format={"type": "json_object"},
)

data = json.loads(response.choices[0].message.content)
print(data)
# {"company_name": "Anthropic", "founding_year": 2021, "headquarters": "San Francisco"}

JSON mode guarantees the response is valid JSON. You still need to tell the model the schema you expect — put that in the system prompt or the user message.

Step 6: Use the Full 1M-Token Context Window

GLM 5.2 has a 1,048,576-token context window — one of the largest available at this price point. At $1.40 per million input tokens and $0.26 per million for cache hits, processing very long documents is economical.

Practical example — summarizing a large codebase or document:

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["Z_AI_API_KEY"],
    base_url="https://api.z.ai/v1",
)

# Read a large file (e.g., a full codebase or long document)
with open("large_document.txt", "r") as f:
    document = f.read()

response = client.chat.completions.create(
    model="glm-5.2",
    messages=[
        {
            "role": "system",
            "content": "You are a technical analyst. Summarize the following document.",
        },
        {"role": "user", "content": document},
    ],
    max_tokens=4096,
)

print(response.choices[0].message.content)

At ~750 words per 1,000 tokens, 1M tokens accommodates roughly 750,000 words — equivalent to ten full novels, a large monorepo, or a complete legal case file. For repeated analysis of the same large document, prompt caching brings the effective input cost down to $0.26/M tokens on cache hits.

Step 7: List Available Models

To confirm connectivity and see which models are available under your API key:

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["Z_AI_API_KEY"],
    base_url="https://api.z.ai/v1",
)

models = client.models.list()
for m in models.data:
    print(m.id)

This calls GET /models and returns a list of model identifiers. glm-5.2 should appear in the list when your key has access.

API Reference Summary

PropertyValue
Base URLhttps://api.z.ai/v1
AuthenticationAuthorization: Bearer <api_key>
Primary model nameglm-5.2
OpenRouter model namez-ai/glm-5.2
Chat completions endpointPOST /chat/completions
List models endpointGET /models
Streamingstream: true
Function callingtools: [] (OpenAI format)
JSON moderesponse_format: {"type": "json_object"}
Max output tokensUp to 4096 (default); larger values supported
Context window1,048,576 tokens

Pricing at a Glance

Understanding costs before you scale is essential. GLM 5.2 is priced competitively for a frontier-class model:

Token typePrice per 1M tokens
Input (cache miss)$1.40
Output$4.40
Input (cache hit)$0.26

For workloads that repeatedly send the same system prompt or large document, cache hits reduce effective input cost by ~81%. A pipeline that processes 10M input tokens per day with a 70% cache hit rate would pay roughly: (3M × $1.40) + (7M × $0.26) = $4.20 + $1.82 = $6.02/day rather than $14.00/day without caching.

For a full pricing breakdown and comparison with other frontier models, see the GLM 5.2 pricing guide.

Common Issues

IssueCauseFix
401 UnauthorizedAPI key missing or invalidCheck Z_AI_API_KEY env var; regenerate key in dashboard
404 Not FoundWrong base_url or model name typoUse https://api.z.ai/v1 and "glm-5.2" exactly
model_not_found errorPassing an OpenAI model nameChange model="gpt-4o" to model="glm-5.2"
Empty stream chunksConsuming delta.content before checking for NoneAdd if delta: guard before printing
JSON mode returns proseMissing JSON instruction in system promptAdd "respond with valid JSON" to the system prompt
Context length errorInput exceeds 1,048,576 tokensChunk the document or use a retrieval step
Slow first tokenNetwork routing, not model speedTTFT is 1.54s by benchmark; longer times suggest network latency

Frequently Asked Questions

Is GLM 5.2 a drop-in replacement for the OpenAI API?

For the endpoints this guide covers — chat completions, streaming, function calling, and JSON mode — yes. You change base_url to https://api.z.ai/v1 and model to "glm-5.2". Any library built on top of the OpenAI SDK (LangChain, LlamaIndex, Instructor, etc.) works with those two substitutions. Features specific to OpenAI's platform (Assistants API, fine-tuning, embeddings, images) are not available.

Can I use GLM 5.2 through OpenRouter instead of Z.ai directly?

Yes. On OpenRouter the model identifier is z-ai/glm-5.2. Set your base_url to https://openrouter.ai/api/v1 and use your OpenRouter API key. OpenRouter adds a small markup over Z.ai's direct pricing, but it lets you switch between providers without changing your integration code.

How do I handle rate limits?

The API returns HTTP 429 when you exceed your rate limit. Implement exponential backoff: wait 1s, then 2s, then 4s between retries. The openai library has built-in retry support — pass max_retries=3 to the OpenAI client constructor.

Does GLM 5.2 support multimodal inputs (images, audio)?

No. GLM 5.2 is a text-only model. It does not accept image URLs or base64-encoded images in the content field. If you need vision capabilities, you will need a different model.

What is the maximum output length?

The default ceiling is 4096 output tokens per request. You can request a higher max_tokens value, though very long single-turn outputs may not always be fully honored. For long-form content generation, break the task into sequential turns rather than relying on a single massive output.

Is the model available for self-hosting?

Yes. GLM 5.2 is released under the MIT license with open weights on Hugging Face at THUDM/GLM-5.2. Self-hosting the full 753B-parameter model requires substantial GPU infrastructure. The model uses a Mixture of Experts architecture — 78 transformer decoder layers with 256 experts per layer, 8 activated per token — which means only 40B parameters are active per forward pass, making inference more efficient than a dense model of equivalent parameter count.

How do I migrate from an existing OpenAI integration?

The minimal change is two lines:

# Before
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(model="gpt-4o", ...)

# After
client = OpenAI(
    api_key=os.environ["Z_AI_API_KEY"],
    base_url="https://api.z.ai/v1",
)
response = client.chat.completions.create(model="glm-5.2", ...)

All other parameters — messages, temperature, max_tokens, stream, tools, response_format — remain unchanged.

Next Steps

  • Explore benchmarks: GLM 5.2 scores 89% on GPQA Diamond and 62.1% on SWE-bench Pro. See how it compares to other frontier models in the GLM 5.2 benchmark breakdown.
  • Understand the architecture: The 753B-parameter MoE design with 40B active parameters per token is what enables 158 t/s throughput. Read more in the GLM 5.2 overview.
  • Check pricing in detail: Cache hit pricing at $0.26/M tokens changes the economics for high-volume pipelines. See the full pricing guide.
  • No-code access: If you want to test GLM 5.2 before writing any code, the chat interface at glm5.app/chat requires no API key and no setup.

Try GLM 5.2 — no API key needed: glm5.app/chat.

Sources

Comece a Usar o GLM 5 Hoje

Experimente o GLM 5 gratuitamente — raciocínio, programação, agentes e geração de imagens em uma única plataforma.