Quick start
glm-5.2 and glm-5.2-fast-preview are the latest GLM models with 1M context length. They support thinking and non-thinking modes via the enable_thinking parameter. Run the following code to call glm-5.2 in thinking mode.
Prerequisites: obtain an API key and configure it as an environment variable. If calling via SDK, install the OpenAI or DashScope SDK.
The enable_thinking parameter is not a standard OpenAI parameter. In the OpenAI Python SDK, pass it via extra_body; in the Node.js SDK, pass it as a top-level parameter.
Example codefrom openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "Who are you?"}]
completion = client.chat.completions.create(
model="glm-5.2",
messages=messages,
extra_body={"enable_thinking": True},
stream=True,
stream_options={"include_usage": True},
)
reasoning_content = ""
answer_content = ""
is_answering = False
print("\n" + "=" * 20 + " Thinking " + "=" * 20 + "\n")
for chunk in completion:
if not chunk.choices:
print("\n" + "=" * 20 + " Token Usage " + "=" * 20 + "\n")
print(chunk.usage)
continue
delta = chunk.choices[0].delta
if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
if not is_answering:
print(delta.reasoning_content, end="", flush=True)
reasoning_content += delta.reasoning_content
if hasattr(delta, "content") and delta.content:
if not is_answering:
print("\n" + "=" * 20 + " Response " + "=" * 20 + "\n")
is_answering = True
print(delta.content, end="", flush=True)
answer_content += delta.content
Example codeimport OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'
});
let reasoningContent = '';
let answerContent = '';
let isAnswering = false;
async function main() {
const messages = [{ role: 'user', content: 'Who are you?' }];
const stream = await openai.chat.completions.create({
model: 'glm-5.2',
messages,
enable_thinking: true,
stream: true,
stream_options: { include_usage: true },
});
console.log('\n' + '='.repeat(20) + ' Thinking ' + '='.repeat(20) + '\n');
for await (const chunk of stream) {
if (!chunk.choices?.length) {
console.log('\n' + '='.repeat(20) + ' Token Usage ' + '='.repeat(20) + '\n');
console.log(chunk.usage);
continue;
}
const delta = chunk.choices[0].delta;
if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
if (!isAnswering) {
process.stdout.write(delta.reasoning_content);
}
reasoningContent += delta.reasoning_content;
}
if (delta.content !== undefined && delta.content) {
if (!isAnswering) {
console.log('\n' + '='.repeat(20) + ' Response ' + '='.repeat(20) + '\n');
isAnswering = true;
}
process.stdout.write(delta.content);
answerContent += delta.content;
}
}
}
main();
Example codecurl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5.2",
"messages": [
{
"role": "user",
"content": "Who are you?"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"enable_thinking": true
}'
Example codeimport os
from dashscope import Generation
messages = [{"role": "user", "content": "Who are you?"}]
completion = Generation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="glm-5.2",
messages=messages,
result_format="message",
enable_thinking=True,
stream=True,
incremental_output=True,
)
reasoning_content = ""
answer_content = ""
is_answering = False
print("\n" + "=" * 20 + " Thinking " + "=" * 20 + "\n")
for chunk in completion:
message = chunk.output.choices[0].message
if "reasoning_content" in message:
if not is_answering:
print(message.reasoning_content, end="", flush=True)
reasoning_content += message.reasoning_content
if message.content:
if not is_answering:
print("\n" + "=" * 20 + " Response " + "=" * 20 + "\n")
is_answering = True
print(message.content, end="", flush=True)
answer_content += message.content
print("\n" + "=" * 20 + " Token Usage " + "=" * 20 + "\n")
print(chunk.usage)
Example codeDashScope Java SDK version must be 2.19.4 or later.
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import java.lang.System;
import java.util.Arrays;
public class Main {
private static StringBuilder reasoningContent = new StringBuilder();
private static StringBuilder finalContent = new StringBuilder();
private static boolean isFirstPrint = true;
private static void handleGenerationResult(GenerationResult message) {
String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
String content = message.getOutput().getChoices().get(0).getMessage().getContent();
if (reasoning != null && !reasoning.isEmpty()) {
reasoningContent.append(reasoning);
if (isFirstPrint) {
System.out.println("==================== Thinking ====================");
isFirstPrint = false;
}
System.out.print(reasoning);
}
if (content != null && !content.isEmpty()) {
finalContent.append(content);
if (!isFirstPrint) {
System.out.println("\n==================== Response ====================");
isFirstPrint = true;
}
System.out.print(content);
}
}
private static GenerationParam buildGenerationParam(Message userMsg) {
return GenerationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("glm-5.2")
.enableThinking(true)
.incrementalOutput(true)
.resultFormat("message")
.messages(Arrays.asList(userMsg))
.build();
}
public static void streamCallWithMessage(Generation gen, Message userMsg)
throws NoApiKeyException, ApiException, InputRequiredException {
GenerationParam param = buildGenerationParam(userMsg);
Flowable<GenerationResult> result = gen.streamCall(param);
result.blockingForEach(message -> handleGenerationResult(message));
}
public static void main(String[] args) {
try {
Generation gen = new Generation();
Message userMsg = Message.builder().role(Role.USER.getValue()).content("Who are you?").build();
streamCallWithMessage(gen, userMsg);
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("An exception occurred: " + e.getMessage());
}
}
}
Example codecurl -X POST "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
"model": "glm-5.2",
"input":{
"messages":[
{
"role": "user",
"content": "Who are you?"
}
]
},
"parameters":{
"enable_thinking": true,
"incremental_output": true,
"result_format": "message"
}
}'
Example codeimport anthropic
import os
client = anthropic.Anthropic(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope-intl.aliyuncs.com/apps/anthropic",
)
message = client.messages.create(
model="glm-5.2",
max_tokens=1024,
messages=[
{"role": "user", "content": "Who are you?"}
],
stream=True,
)
for event in message:
if event.type == "content_block_delta":
if hasattr(event.delta, "thinking"):
print(event.delta.thinking, end="", flush=True)
if hasattr(event.delta, "text"):
print(event.delta.text, end="", flush=True)
Example codecurl -X POST https://dashscope-intl.aliyuncs.com/apps/anthropic/v1/messages \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "glm-5.2",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "Who are you?"
}
]
}'
glm-5.2, glm-5.2-fast-preview, glm-5.1, glm-5, glm-4.7, and glm-4.6 support the tool_stream parameter (boolean, default false), effective only when stream is true. When enabled, function calling arguments are returned incrementally across multiple chunks rather than all at once.
| stream | tool_stream | tool_call behavior |
|---|
| true | true | arguments returned incrementally across chunks |
| true | false (default) | arguments returned in a single chunk |
| false | true/false | tool_stream has no effect |
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather information for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"}
},
"required": ["city"]
}
}
}
]
messages = [{"role": "user", "content": "What's the weather like in Singapore?"}]
completion = client.chat.completions.create(
model="glm-5.2",
tools=tools,
messages=messages,
extra_body={"tool_stream": True},
stream=True,
stream_options={"include_usage": True},
)
for chunk in completion:
if chunk.choices:
delta = chunk.choices[0].delta
if hasattr(delta, 'content') and delta.content:
print(f"[content] {delta.content}")
if hasattr(delta, 'tool_calls') and delta.tool_calls:
for tc in delta.tool_calls:
print(f"[tool_call] id={tc.id}, name={tc.function.name}, args={tc.function.arguments}")
if chunk.choices[0].finish_reason:
print(f"[finish_reason] {chunk.choices[0].finish_reason}")
if not chunk.choices and chunk.usage:
print(f"[usage] {chunk.usage}")
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'
});
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "Get weather information for a city",
parameters: {
type: "object",
properties: {
city: { type: "string", description: "City name" }
},
required: ["city"]
}
}
}
];
async function main() {
const stream = await openai.chat.completions.create({
model: 'glm-5.2',
messages: [{ role: 'user', content: "What's the weather like in Singapore?" }],
tools: tools,
tool_stream: true,
stream: true,
stream_options: { include_usage: true },
});
for await (const chunk of stream) {
if (!chunk.choices?.length) {
if (chunk.usage) {
console.log(`[usage] ${JSON.stringify(chunk.usage)}`);
}
continue;
}
const delta = chunk.choices[0].delta;
if (delta.content) {
console.log(`[content] ${delta.content}`);
}
if (delta.tool_calls) {
for (const tc of delta.tool_calls) {
console.log(`[tool_call] id=${tc.id}, name=${tc.function.name}, args=${tc.function.arguments}`);
}
}
if (chunk.choices[0].finish_reason) {
console.log(`[finish_reason] ${chunk.choices[0].finish_reason}`);
}
}
}
main();
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5.2",
"messages": [
{
"role": "user",
"content": "What is the weather like in Singapore?"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather information for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"}
},
"required": ["city"]
}
}
}
],
"stream": true,
"stream_options": {"include_usage": true},
"tool_stream": true
}'
import os
from dashscope import Generation
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather information for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"}
},
"required": ["city"]
}
}
}
]
messages = [{"role": "user", "content": "What's the weather like in Singapore?"}]
completion = Generation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="glm-5.2",
messages=messages,
tools=tools,
result_format="message",
stream=True,
tool_stream=True,
incremental_output=True,
)
for chunk in completion:
msg = chunk.output.choices[0].message
if msg.content:
print(f"[content] {msg.content}")
if "tool_calls" in msg and msg.tool_calls:
for tc in msg.tool_calls:
fn = tc.get("function", {})
print(f"[tool_call] id={tc.get('id','')}, name={fn.get('name','')}, args={fn.get('arguments','')}")
finish = chunk.output.choices[0].get("finish_reason", "")
if finish and finish != "null":
print(f"[finish_reason] {finish}")
curl -X POST "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
"model": "glm-5.2",
"input": {
"messages": [
{
"role": "user",
"content": "What is the weather like in Singapore?"
}
]
},
"parameters": {
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather information for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"}
},
"required": ["city"]
}
}
}
],
"tool_stream": true,
"incremental_output": true,
"result_format": "message"
}
}'
Reasoning effort (reasoning_effort)
glm-5.2, glm-5.2-fast-preview, and glm-5.1 have thinking mode enabled by default. The model first outputs the thinking process (reasoning_content) and then provides the final answer. You can use the reasoning_effort parameter to adjust the reasoning depth. A higher value indicates more thorough thinking. Supported values vary by model. Passing an unsupported value returns an invalid_parameter_error error.
| Model | Available values |
|---|
| glm-5.2 | none (no reasoning), minimal, low, medium, high, xhigh, max (highest) |
| glm-5.2-fast-preview | none (no reasoning), minimal, low, medium, high, xhigh, max (highest) |
| glm-5.1 | none, minimal, low, medium, high, xhigh (highest, max is not supported) |
To disable thinking mode, set enable_thinking to false in OpenAI compatible or DashScope mode. This parameter has higher priority than reasoning_effort.
Anthropic compatible mode does not support the reasoning_effort parameter. To obtain thinking content, use the native Anthropic thinking parameter: {"thinking":{"type":"enabled","budget_tokens":1024}}.
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="glm-5.2",
messages=[{"role": "user", "content": "Which is larger, 9.9 or 9.11?"}],
reasoning_effort="high",
)
print(completion.choices[0].message.content)
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
});
const completion = await openai.chat.completions.create({
model: "glm-5.2",
messages: [{ role: "user", content: "Which is larger, 9.9 or 9.11?" }],
reasoning_effort: "high",
});
console.log(completion.choices[0].message.content);
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5.2",
"messages": [{"role": "user", "content": "Which is larger, 9.9 or 9.11?"}],
"reasoning_effort": "high"
}'
import os
from dashscope import Generation
response = Generation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="glm-5.2",
messages=[{"role": "user", "content": "Which is larger, 9.9 or 9.11?"}],
reasoning_effort="high",
result_format="message",
)
print(response.output.choices[0].message.content)
Clear thinking history (clear_thinking)
The clear_thinking parameter controls whether the reasoning_content (thinking process) from previous turns is included as context input for the model in multi-turn conversations. Only GLM series models support this parameter.
true: Ignore reasoning_content from previous turns. Only visible text, tool calls, and results are used as context, reducing context length and cost.
false (default): Retain reasoning_content from previous turns and pass it to the model as part of the context. To enable Preserved Thinking, you must pass the complete, unmodified reasoning_content from previous turns in the original order. Missing, trimmed, rewritten, or reordered content may degrade effectiveness or prevent it from working.
This parameter only affects the thinking content from previous turns. It does not change whether the model generates or outputs thinking in the current turn.
The following example uses the same multi-turn messages (with reasoning_content in the assistant messages). When clear_thinking is set to true, the historical thinking content is excluded from context, resulting in fewer prompt_tokens compared to false (default). The actual difference depends on the length of the historical reasoning_content.
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [
{"role": "user", "content": "What is 15 * 23?"},
{"role": "assistant", "content": "15 times 23 equals 345.", "reasoning_content": "15 * 23 = 345"},
{"role": "user", "content": "Now add 55 to that."},
{"role": "assistant", "content": "345 plus 55 equals 400.", "reasoning_content": "345 + 55 = 400"},
{"role": "user", "content": "What were the intermediate results?"},
]
completion = client.chat.completions.create(
model="glm-5.2",
messages=messages,
extra_body={
"thinking": {
"type": "enabled",
"clear_thinking": False # False = retain thinking content
}
}
)
print(completion.usage.prompt_tokens) # fewer when true vs false
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5.2",
"messages": [
{"role": "user", "content": "What is 15 * 23?"},
{"role": "assistant", "content": "15 times 23 equals 345.", "reasoning_content": "15 * 23 = 345"},
{"role": "user", "content": "Now add 55 to that."},
{"role": "assistant", "content": "345 plus 55 equals 400.", "reasoning_content": "345 + 55 = 400"},
{"role": "user", "content": "What were the intermediate results?"}
],
"thinking": {
"type": "enabled",
"clear_thinking": false
}
}'
Responses API
glm-5.2 supports calls through the OpenAI-compatible Responses API. When calling the Responses API, you can add the web_search (Web search), web_extractor (Web extractor), and code_interpreter (Code interpreter) tools to the tools parameter.
Example codefrom openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
response = client.responses.create(
model="glm-5.2",
input="Hello! Please introduce yourself in one sentence.",
# Optional: enable the web search, web extractor, and code interpreter tools
tools=[
{"type": "web_search"},
{"type": "web_extractor"},
{"type": "code_interpreter"},
],
)
# Get the model response
print(response.output_text)
Example codeimport OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
});
const response = await openai.responses.create({
model: "glm-5.2",
input: "Hello! Please introduce yourself in one sentence.",
// Optional: enable the web search, web extractor, and code interpreter tools
tools: [
{ type: "web_search" },
{ type: "web_extractor" },
{ type: "code_interpreter" },
],
});
// Get the model response
console.log(response.output_text);
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5.2",
"input": "Hello! Please introduce yourself in one sentence.",
"tools": [
{"type": "web_search"},
{"type": "web_extractor"},
{"type": "code_interpreter"}
]
}'
Other features
| Model | Multi-turn | Function calling | Web search | Context cache |
|---|
| glm-5.2 | ✓ | ✓ | ✓ (non-thinking mode only) | ✓ (implicit only) |
| glm-5.2-fast-preview | ✓ | ✓ | ✓ (non-thinking mode only) | ✓ (implicit only) |
| glm-5.1 | ✓ | ✓ | ✓ (non-thinking mode only) | ✓ (explicit and implicit) |
Parameter defaults
| Model | enable_thinking | temperature | top_p | top_k | repetition_penalty |
|---|
| glm-5.2 | true | 1.0 | 0.95 | 20 | 1.0 |
| glm-5.1 | true | 1.0 | 0.95 | 20 | 1.0 |
Precautions
Cloud-deployed third-party open-source models (such as glm-5.2) handle hyperparameters differently from the model's official version: the official version performs threshold validation on hyperparameters and falls back to default values when thresholds are exceeded; the cloud-deployed version directly passes through user-provided parameter values without threshold validation. Therefore, improper hyperparameter settings (such as setting repetition_penalty to 0.1) may cause unexpected output (such as repeated printing). We recommend using the default hyperparameter values (see the default parameter values table above) for third-party open-source models and avoiding custom parameters.