Applying for and Using the GLM Chat Completion API

GLM (General Language Model) is a new generation of large language models introduced by Zhipu AI (Zhipu AI / Z.ai). It has strong Chinese and English comprehension and generation capabilities and performs exceptionally well in tasks such as Chinese-language scenarios, code generation, reasoning, and multi-turn conversations. New-generation models such as GLM-5.3, GLM-5.2, and GLM-4.7 have been extensively optimized for long contexts, tool calling, and coding tasks, and can be widely applied to scenarios such as intelligent question answering, content creation, coding assistance, and customer service chatbots.

This document primarily introduces the process of using the GLM Chat Completion API, which allows you to easily call GLM series models through a unified OpenAI-compatible interface.

Send a Conversation Message

Sign in to the application list, open the general-purpose application, and copy the API KEY. In the terminal, enter the copied raw value into the environment variable below, then send a user message to GLM:

export ACEDATACLOUD_API_KEY='YOUR_API_KEY'
curl --fail-with-body 'https://api.acedata.cloud/glm/chat/completions' \
  --header "Authorization: Bearer $ACEDATACLOUD_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{"model":"glm-5.2","messages":[{"role":"user","content":"hello"}]}'

Read the reply from choices[0].message.content in the response. Below is an example response:

{
  "id": "msg_202604262252030313862701a04e33",
  "model": "glm-5.2",
  "object": "chat.completion",
  "created": 1777215124,
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! 👋 How can I assist you today?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 23,
    "total_tokens": 33
  }
}

The main fields in the result are described as follows:

  • id: The unique ID of this conversation task.
  • created: The creation time of this conversation task (Unix timestamp, in seconds).
  • model: The public GLM model specified in the request. When compatibility routing is enabled, the platform may process the request using a compatible model in the same tier, while billing according to the requested GLM model.
  • choices: The list of replies generated by the model. choices[i].message.content is the actual text of the model's reply, and finish_reason indicates the reason for completion (stop, length, tool_calls, content_filter, etc.).
  • usage: Token usage statistics for this request, including prompt_tokens, completion_tokens, and total_tokens.

Select a Model and Parameters

In GLM Chat Completion online testing, select an application and enter model and messages to send a request.

  • model: Select the GLM model to call. Currently supported models include:
    • glm-5.3: The latest flagship model, supporting a 1M context and up to 128K output, suitable for complex reasoning, coding, and Agent tasks. Reasoning is always enabled, and reasoning_effort can be set to low, high, or max.
    • glm-5.2: The previous-generation flagship model, with strong overall capabilities.
    • glm-5.1: A mature flagship model, suitable for general complex tasks.
    • glm-5: Suitable for complex reasoning and coding tasks.
    • glm-5-turbo: Designed for low-latency conversations and tool calling.
    • glm-4.7: Performs exceptionally well in reasoning, tool calling, and coding tasks.
    • glm-4.6: A general-purpose conversation model that balances performance and cost.
    • glm-4.5: For general text conversations and code generation.
    • glm-4.5v: Accepts text and images, suitable for chart comprehension, image description, and text recognition. Images are passed through image_url in the message content.
    • glm-3-turbo: A classic conversation model, suitable for general text generation tasks.
  • messages: An array of prompts. Each message contains role and content, and role supports three roles: user, assistant, and system.

Common optional parameters:

  • max_tokens: Limits the maximum number of tokens in a single reply.
  • temperature: Generation randomness, between 0 and 2; higher values produce more diverse results.
  • top_p: The nucleus sampling parameter, which controls the cumulative probability threshold for candidate tokens.
  • n: The number of candidate replies to generate at once.
  • stream: Whether to enable streaming responses; defaults to false.
  • stop: Custom stop sequences.

Python Example

After installing requests, the following code uses the Key saved earlier to send the same message and print the reply.

import os
import requests

response = requests.post(
    "https://api.acedata.cloud/glm/chat/completions",
    headers={"Authorization": f"Bearer {os.environ['ACEDATACLOUD_API_KEY']}"},
    json={"model": "glm-5.2", "messages": [{"role": "user", "content": "hello"}]},
    timeout=120,
)
response.raise_for_status()
print(response.json()["choices"][0]["message"]["content"])

Streaming Responses

This interface supports streaming responses (Server-Sent Events), which is very useful for web integration and allows web pages to display text character by character.

To receive a streaming response, set the stream parameter in the request body to true.

Python sample calling code:

import requests

url = "https://api.acedata.cloud/glm/chat/completions"

headers = {
    "accept": "application/json",
    "authorization": "Bearer {token}",
    "content-type": "application/json"
}

payload = {
    "model": "glm-4.7",
    "messages": [{"role": "user", "content": "hi"}],
    "stream": True
}

response = requests.post(url, json=payload, headers=headers, stream=True)
for line in response.iter_lines():
    if line:
        print(line.decode("utf-8"))

The output is as follows (excerpt):

data: {"id": "msg_2026042622521271f765bbc3734ce1", "object": "chat.completion.chunk", "created": 1777215133, "model": "glm-4.7", "choices": [{"delta": {"content": "", "role": "assistant"}, "finish_reason": null, "index": 0}], "usage": null}

data: {"id": "msg_2026042622521271f765bbc3734ce1", "object": "chat.completion.chunk", "created": 1777215133, "model": "glm-4.7", "choices": [{"delta": {"content": "你好!有什么我可以"}, "finish_reason": null, "index": 0}], "usage": null}

data: {"id": "msg_2026042622521271f765bbc3734ce1", "object": "chat.completion.chunk", "created": 1777215133, "model": "glm-4.7", "choices": [{"delta": {"content": "帮助你的"}, "finish_reason": null, "index": 0}], "usage": null}

data: {"id": "msg_2026042622521271f765bbc3734ce1", "object": "chat.completion.chunk", "created": 1777215133, "model": "glm-4.7", "choices": [{"delta": {"content": "吗?"}, "finish_reason": null, "index": 0}], "usage": null}

data: {"id": "msg_2026042622521271f765bbc3734ce1", "object": "chat.completion.chunk", "created": 1777215133, "model": "glm-4.7", "choices": [{"delta": {}, "finish_reason": "stop", "index": 0}], "usage": null}

data: {"id": "msg_2026042622521271f765bbc3734ce1", "object": "chat.completion.chunk", "created": 1777215133, "model": "glm-4.7", "choices": [], "usage": {"prompt_tokens": 1420, "completion_tokens": 18, "total_tokens": 1438}}

data: [DONE]

As you can see, the response contains many data entries, each containing an incremental fragment. choices[i].delta.content is the new text fragment added by the current chunk, and you can concatenate these fragments to form the complete response. When the content of data is [DONE], it indicates that the streaming response has ended. The last chunk containing usage summarizes the token usage for this request.

JavaScript (Node.js) example:

const options = {
  method: "POST",
  headers: {
    accept: "application/json",
    authorization: "Bearer {token}",
    "content-type": "application/json"
  },
  body: JSON.stringify({
    model: "glm-4.7",
    messages: [{ role: "user", content: "hi" }],
    stream: true
  })
};

const response = await fetch("https://api.acedata.cloud/glm/chat/completions", options);
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  process.stdout.write(decoder.decode(value));
}

Java example code:

JSONObject jsonObject = new JSONObject();
jsonObject.put("model", "glm-4.7");
jsonObject.put("messages", new JSONArray().put(new JSONObject().put("role", "user").put("content", "hi")));
jsonObject.put("stream", true);
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonObject.toString(), mediaType);
Request request = new Request.Builder()
  .url("https://api.acedata.cloud/glm/chat/completions")
  .post(body)
  .addHeader("accept", "application/json")
  .addHeader("authorization", "Bearer {token}")
  .addHeader("content-type", "application/json")
  .build();

OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());

You can adapt the code yourself for other languages; the principle is the same.

Multi-Turn Conversations

If you want to implement multi-turn conversations, you need to place the conversation history in the messages array in sequence, preserving the alternating order of user and assistant.

Python example call code:

import requests

url = "https://api.acedata.cloud/glm/chat/completions"

headers = {
    "accept": "application/json",
    "authorization": "Bearer {token}",
    "content-type": "application/json"
}

payload = {
    "model": "glm-4.7",
    "messages": [
        {"role": "user", "content": "Hello"},
        {"role": "assistant", "content": "Hi! How can I assist you today?"},
        {"role": "user", "content": "What did I say just now?"}
    ]
}

response = requests.post(url, json=payload, headers=headers)
print(response.text)

By submitting multiple prompts, you can easily implement multi-turn conversations and receive a response like the following:

{
  "id": "msg_20260426225208b95324e9945a48d3",
  "model": "glm-4.7",
  "object": "chat.completion",
  "created": 1777215128,
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "You said: **\"Hello\"** 😊\n\nLet me know if you need anything else!"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 48,
    "completion_tokens": 37,
    "total_tokens": 85
  }
}

As you can see, the information contained in choices is consistent with the basic usage, and the model responds based on the complete conversation history, thereby supporting multi-turn contextual interactions.

System Prompt

You can add a message with the role set to system at the beginning of messages to constrain the model's role, style, or behavior:

payload = {
    "model": "glm-4.7",
    "messages": [
        {"role": "system", "content": "你是一名资深的中文写作助手,请用简洁专业的语气回复。"},
        {"role": "user", "content": "请用三句话介绍一下 GLM 模型。"}
    ]
}

Tool Calling (Function Calling)

GLM models support OpenAI-compatible Function Calling. You can declare callable functions through the tools parameter, and the model will return structured function call information in choices[i].message.tool_calls when needed.

payload = {
    "model": "glm-4.7",
    "messages": [
        {"role": "user", "content": "北京今天天气怎么样?"}
    ],
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "查询指定城市的天气",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": {"type": "string", "description": "城市名称"}
                    },
                    "required": ["city"]
                }
            }
        }
    ]
}

If the model decides to call a tool, finish_reason in the response will become tool_calls, and the function name and arguments in JSON string format will be provided in message.tool_calls. You can execute the function and return the result to the model as a message with the role set to tool, thereby completing the full tool-calling loop.

Model Selection Recommendations

Model Applicable scenarios
glm-5.3 Latest flagship, 1M context and up to 128K output, recommended for complex reasoning, code, and Agent tasks
glm-5.2 Previous-generation flagship, suitable for complex reasoning, code, and Agent tasks
glm-5.1 Mature flagship, suitable for complex reasoning and long-document analysis
glm-4.7 Tasks such as tool calling, code generation, and Agent orchestration
glm-4.6 A balanced choice for general conversation and content creation
glm-3-turbo General text generation tasks and cost-sensitive scenarios

Error Handling

When calling the API, if an error occurs, the API will return the corresponding error code and message. For example:

  • 400 token_mismatched: Request parameters are missing or invalid.
  • 400 api_not_implemented: An unsupported parameter or model was used.
  • 401 invalid_token: Unauthorized, Bearer Token is missing or invalid.
  • 429 too_many_requests: Rate limit reached, please retry later.
  • 500 api_error: Service error or temporarily unavailable.

Error Response Example

{
  "trace_id": "69ea9bcf-c5da-41a3-be97-c80912a08523",
  "error": {
    "code": "api_error",
    "message": "Service is temporarily unavailable, please retry later."
  }
}

When api_error is returned and the message is Service is temporarily unavailable, please retry later., it usually indicates that the GLM service is temporarily unavailable. It is recommended to retry with exponential backoff or switch to another available GLM model (for example, temporarily switch from glm-5.1 to glm-4.7 or glm-4.6).

Conclusion

Through this document, you have learned how to use the GLM Chat Completion API to call Zhipu AI's GLM series models, including typical usage such as basic calls, streaming responses, multi-turn conversations, system prompts, and tool calling. We hope this document helps you better integrate and use the API. If you have any questions, please feel free to contact our technical support team.