GLM Chat Completion API Application and Usage
GLM (General Language Model) is a new-generation large language model series launched by Zhipu AI (Zhipu AI / Z.ai). It features powerful Chinese and English understanding and generation capabilities, delivering excellent performance in tasks such as Chinese-language scenarios, code generation, reasoning, and multi-turn conversations. The new-generation models, including GLM-5.3, GLM-5.2, and GLM-4.7, have undergone extensive optimizations for long-context processing, tool calling, and coding tasks, making them widely applicable to scenarios such as intelligent question answering, content creation, coding assistance, and customer service chatbots.
This document mainly introduces the usage process of the GLM Chat Completion API, which allows you to easily call GLM series models through a unified OpenAI-compatible interface.
¶ Application Process
To use the GLM Chat Completion API, first visit the jiasmart Console to obtain your API Token for later use.
If you are not logged in or registered, you will automatically be redirected to the login page, where you will be prompted to register and log in. Once completed, you will automatically return to the current page.
One API Token is sufficient to access all services on the platform; there is no need to apply for each service separately. A free quota is provided upon the first application, allowing you to try the service for free. When the quota is insufficient, you can recharge your general balance in the Console.
📘 Complete Documentation: GLM Chat Completion API →
¶ Basic Usage
The request URL for the GLM Chat Completion API is https://api.jiasmart.asia/glm/chat/completions. It uses Bearer Token authentication, and the request body is compatible with the OpenAI Chat Completions protocol.
When using this interface for the first time, we need to fill in at least three fields:
authorization: Simply select Bearer Token from the dropdown list.model: Select the GLM model you want to call. Currently supported models include:glm-5.3: The latest flagship model, supporting a 1M context window and up to 128K output tokens, suitable for complex reasoning, coding, and Agent tasks. Reasoning is always enabled, and you can selectlow,high, ormaxthroughreasoning_effort.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: Delivers excellent performance in reasoning, tool calling, and coding tasks.glm-4.6: A general-purpose conversational model that balances performance and cost.glm-4.5: General-purpose text conversations and code generation.glm-4.5v: Accepts both text and images, making it suitable for chart understanding, image description, and text recognition. Images are passed throughimage_urlin the message content.glm-3-turbo: A classic conversational model suitable for general text generation tasks.
messages: An array of prompts, where each message containsroleandcontent. Therolesupports three roles:user,assistant, andsystem.
Common optional parameters:
max_tokens: Limits the maximum number of tokens in a single response.temperature: Controls generation randomness, ranging from 0 to 2. Higher values produce more diverse outputs.top_p: A nucleus sampling parameter that controls the cumulative probability threshold of candidate tokens.n: Specifies how many candidate responses to generate at once.stream: Specifies whether to enable streaming responses. The default isfalse.stop: Custom stopping sequences.
Below is the simplest Python API call example:
import requests
url = "https://api.jiasmart.asia/glm/chat/completions"
headers = {
"accept": "application/json",
"authorization": "Bearer {token}",
"content-type": "application/json"
}
payload = {
"model": "glm-5.2",
"messages": [
{"role": "user", "content": "hello"}
]
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
After making the call, we find that the returned result is as follows:
{
"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 returned result are explained 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 compatible routing is enabled, the platform may use a compatible model of the same tier to process the request, while billing is still based on the requested GLM model.choices: The list of responses generated by the model.choices[i].message.contentcontains the specific text of the model's response, whilefinish_reasonindicates the reason for termination (stop,length,tool_calls,content_filter, etc.).usage: Token usage statistics for this request, includingprompt_tokens,completion_tokens, andtotal_tokens.
¶ Streaming Responses
This interface supports streaming responses (Server-Sent Events), which is very useful for web integration and allows webpages to display text character by character.
To return responses in streaming mode, simply set the stream parameter in the request body to true.
Python example code:
import requests
url = "https://api.jiasmart.asia/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": "Hello! Is there anything I can"}, "finish_reason": null, "index": 0}], "usage": null}
data: {"id": "msg_2026042622521271f765bbc3734ce1", "object": "chat.completion.chunk", "created": 1777215133, "model": "glm-4.7", "choices": [{"delta": {"content": "help you with"}, "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 multiple data entries, and each data entry contains an incremental fragment. choices[i].delta.content is the new text fragment added by the current chunk. You can concatenate these fragments to form the complete response. When the data content is [DONE], it indicates that the streaming response has ended. The final 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.jiasmart.asia/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 sample 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.jiasmart.asia/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());
Other languages can be adapted independently; the principle is the same.
¶ Multi-turn Conversations
If you want to implement multi-turn conversation functionality, you need to place the conversation history in sequence into the messages array and preserve the alternating order of user and assistant messages.
Python sample code:
import requests
url = "https://api.jiasmart.asia/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 uploading multiple prompts, you can easily implement multi-turn conversations and obtain the following response:
{
"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 basic usage. The model provides a response 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": "You are an experienced Chinese writing assistant. Please respond in a concise and professional tone."},
{"role": "user", "content": "Please introduce the GLM model in three sentences."}
]
}
¶ Tool Calling (Function Calling)
GLM models support OpenAI-compatible Function Calling. You can declare callable functions through the tools parameter. When needed, the model returns structured function call information in choices[i].message.tool_calls.
payload = {
"model": "glm-4.7",
"messages": [
{"role": "user", "content": "What's the weather like in Beijing today?"}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Query the weather in a specified city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"}
},
"required": ["city"]
}
}
}
]
}
If the model decides to call a tool, finish_reason in the returned result will change to tool_calls, and the function name and parameters 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 cycle.
¶ Model Selection Recommendations
| Model | Applicable Scenarios |
| ------------- | -------------------------------------------- |
| `glm-5.3` | Latest flagship, 1M context window, maximum 128K output, recommended for complex reasoning, coding, and Agent tasks |
| `glm-5.2` | Previous-generation flagship, suitable for complex reasoning, coding, 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 conversations 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 triggered; please try again later.
- `500 api_error`: Service error or temporarily unavailable.
### Error Response Example
```json
{
"trace_id": "69ea9bcf-c5da-41a3-be97-c80912a08523",
"error": {
"code": "api_error",
"message": "Service is temporarily unavailable, please retry later."
}
}
When api_error is returned with the message 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 switching 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 use cases such as basic calls, streaming responses, multi-turn conversations, system prompts, and tool calling. We hope this document helps you better integrate with and use this API. If you have any questions, please feel free to contact our technical support team.

