Skip to main content
Third-party model integration tutorial

GLM

This topic describes how to use APIs to call GLM series models on the Alibaba Cloud Model Studio platform.

glm-4.6 and glm-4.7 will be delisted on Oct 10, 2026. We recommend migrating to: qwen3.7-plus, qwen3.8-max, and qwen3.8-flash.

Service endpoints

Service endpoints vary by region. Configure the base URL that corresponds to your selected region.
  • OpenAI compatible
  • OpenAI compatible - Responses API
  • DashScope
  • China (Beijing)
  • US (Virginia)
  • Germany (Frankfurt)
  • China (Hong Kong)
  • Singapore
The base_url for SDK calls is: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1HTTP request endpoint: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions
Replace {WorkspaceId} with your actual workspace ID.

Getting started

glm-5.2 and glm-5.2-fast-preview are the latest models in the GLM series. They have a context length of 1M and let you set the thinking mode and non-thinking mode using the enable_thinking parameter. You can run the following code to quickly call the glm-5.2 model in thinking mode. Before you start, obtain an API key and configure it as an environment variable. If you use an SDK, you must also install the OpenAI or DashScope SDK.
  • OpenAI compatible
  • DashScope
  • Anthropic compatible
The enable_thinking parameter is not a standard OpenAI parameter. In the OpenAI Python SDK, it is passed through extra_body. In the Node.js SDK, it is passed as a top-level parameter.
  • Python
  • Node.js
  • HTTP

Sample code

from openai import OpenAI
import os

# Initialize the OpenAI client
client = OpenAI(
    # If the environment variable is not configured, replace the value with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # When you make a call, replace {WorkspaceId} with your actual Workspace ID.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "Who are you?"}]
completion = client.chat.completions.create(
    model="glm-5.2",
    messages=messages,
    # Set enable_thinking in extra_body to enable the thinking mode
    extra_body={"enable_thinking": True},
    stream=True,
    stream_options={
        "include_usage": True
    },
)

reasoning_content = ""  # Complete thinking process
answer_content = ""  # Complete response
is_answering = False  # Indicates whether the response phase has started
print("\n" + "=" * 20 + "Thinking process" + "=" * 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

    # Collect only the thinking content
    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

    # After content is received, start the response
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "Complete response" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

Response

====================Thinking process====================

Let me carefully consider the user's question. It seems simple, but it actually has depth.

From a linguistic perspective, the user is using Chinese, which means I should respond in Chinese. This is a basic self-introduction question, but it may have multiple layers of meaning.

First, I need to be clear that as a language model, I should honestly state my identity and nature. I am not a human, nor do I have real emotional awareness. I am an AI assistant trained with deep learning technology. This is the most basic fact.

Second, considering the user's potential scenarios, they might want to know:
1. What services can I provide?
2. What are my areas of expertise?
3. What are my limitations?
4. How can they interact with me better?

In my answer, I should express a friendly and open attitude while remaining professional and accurate. I should state my main areas of expertise, such as knowledge Q&A, writing assistance, and creative support, but also frankly point out my limitations, such as the lack of real emotional experience.

In addition, to make the answer more complete, I should also express a positive attitude of being willing to help users solve problems. I can appropriately guide users to ask more specific questions to better demonstrate my abilities.

Considering this is an open-ended opening, the answer should be both concise and informative, giving the user a clear understanding of my basic situation and laying a good foundation for subsequent conversations.

Finally, the tone should be humble and professional, neither too technical nor too casual, to make the user feel comfortable and natural.
====================Complete response====================

I am a GLM large language model trained by Zhipu AI, designed to provide users with information and help solve problems. I am designed to understand and generate human language, and I can answer questions, provide explanations, or participate in discussions on various topics.

I do not store your personal data, and our conversations are anonymous. Is there any topic I can help you understand or discuss?
====================Token usage====================

CompletionUsage(completion_tokens=344, prompt_tokens=7, total_tokens=351, completion_tokens_details=None, prompt_tokens_details=None)

Streaming tool calling

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. This parameter is a boolean that defaults to false and takes effect only when stream is set to true. When enabled, the arguments of the tool_call parameter from Function Calling are returned incrementally in a stream, rather than all at once after the full generation is complete. The combined behavior of stream and tool_stream is as follows:

stream

tool_stream

tool_call return method

true

true

The arguments are returned incrementally in multiple chunks.

true

false (default)

The arguments are returned completely in a single chunk.

false

true/false

tool_stream has no effect. The arguments are returned at once in the complete response.

  • OpenAI compatible
  • DashScope
  • Python
  • Node.js
  • HTTP

Sample code

from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the weather information for a specified city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "The name of the city"}
                },
                "required": ["city"]
            }
        }
    }
]

messages = [{"role": "user", "content": "What's the weather like in Beijing?"}]

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}")

Reasoning effort (reasoning_effort)

glm-5.2, glm-5.2-fast-preview, and glm-5.1 have the 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 effort. A higher value indicates more thorough thinking. The supported values vary by model. If you pass an unsupported value, an invalid_parameter_error error is returned. Select a value from the following table.

Model

Available values for reasoning_effort

glm-5.2

none (no reasoning, reasoning_tokens=0), minimal, low, medium, high, xhigh, max (highest)

glm-5.2-fast-preview

none (no reasoning, reasoning_tokens=0), minimal, low, medium, high, xhigh, max (highest)

glm-5.1

none, minimal, low, medium, high, xhigh (highest, max is not supported)

To disable the thinking mode, set the enable_thinking parameter to false in OpenAI compatible or DashScope mode. This parameter has a higher priority than reasoning_effort.
The Anthropic compatible mode does not support the reasoning_effort parameter. To obtain the thinking content, use the native Anthropic thinking parameter: {"thinking":{"type":"enabled","budget_tokens":1024}}. When enabled, the response content will include a thinking block with type set to thinking.
  • OpenAI compatible
  • DashScope
Python
from openai import OpenAI
import os
client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.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)

Clear thinking history (clear_thinking)

The clear_thinking parameter controls whether the reasoning_content (thinking process) from previous turns in a multi-turn conversation is passed to the model as context. This parameter is supported only by GLM series models.
  • true: Ignores the reasoning_content from previous turns. Only non-reasoning content such as visible text, tool calls, and results is used as context input. This reduces the context length and cost.
  • false (default): Retains the reasoning_content from previous turns and provides it to the model along with the context. To enable Preserved Thinking, you must pass the historical reasoning_content completely, unmodified, and in the original order within the messages. Missing, clipping, rewriting, or reordering the content may degrade performance or cause the feature to fail.
This parameter only affects the historical thinking content across turns and does not change whether the model generates or outputs thinking content in the current turn.
The following example uses the same set of multi-turn messages, where the assistant message contains reasoning_content. When clear_thinking is set to true, the historical thinking content is not included in the context. Therefore, the prompt_tokens count is lower than when it is set to false (default). The actual value depends on the length of the historical reasoning_content.
  • OpenAI compatible
  • DashScope
Python
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # When you make a call, replace {WorkspaceId} with your actual Workspace ID.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

# Multi-turn conversation where the assistant message carries reasoning_content (historical thinking process)
messages = [
    {"role": "user", "content": "Please calculate 15 * 23."},
    {"role": "assistant", "content": "15 multiplied by 23 equals 345.", "reasoning_content": "15 * 23 = 345"},
    {"role": "user", "content": "What if you add 55 to that?"},
    {"role": "assistant", "content": "345 plus 55 equals 400.", "reasoning_content": "345 + 55 = 400"},
    {"role": "user", "content": "What was the intermediate result?"},
]

completion = client.chat.completions.create(
    model="glm-5.2",
    messages=messages,
    extra_body={
        "enable_thinking": True,
        # true: Ignores historical reasoning_content to reduce context length and cost
        # false (default): Retains historical reasoning_content (Preserved Thinking)
        "clear_thinking": True,
    },
)
print(completion.usage.prompt_tokens)  # The value is smaller when set to true than when set to false

Responses API

glm-5.2 supports calls through the OpenAI-compatible Responses API. Only the China (Beijing) and Singapore regions are supported. For endpoints, see Service endpoints. 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.
Python
from openai import OpenAI
import os

client = OpenAI(
    # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following URL is for the Singapore region. For the other region, use https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.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)

Other features

ModelMulti-turn conversationFunction CallingStructured outputWeb searchPartial modeContext cache
glm-5.2SupportedSupportedSupported
Only in non-thinking mode
Not supportedNot supportedSupported
Only implicit cache is supported
glm-5.2-fast-previewSupportedSupportedSupported
Only in non-thinking mode
Not supportedNot supportedSupported
Only implicit cache is supported
glm-5.1SupportedSupportedSupported
Only in non-thinking mode
Not supportedNot supportedSupported
Both explicit and implicit cache are supported
glm-5SupportedSupportedSupported
Only in non-thinking mode
Not supportedNot supportedSupported
Only implicit cache is supported
glm-4.7SupportedSupportedSupported
Only in non-thinking mode
Not supportedNot supportedSupported
Only implicit cache is supported
glm-4.6SupportedSupportedSupported
Only in non-thinking mode
Not supportedNot supportedSupported
Only implicit cache is supported

Default parameter values

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

glm-5

true

1.0

0.95

20

1.0

glm-4.7

true

1.0

0.95

20

1.0

glm-4.6

true

1.0

0.95

20

1.0

For more information about the parameters, see OpenAI compatible - Chat.

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.

Models and billing

The GLM series models are hybrid reasoning models designed by Zhipu AI for agents. They provide both thinking and non-thinking modes.
  • glm-5.2: The latest GLM model with a context length of 1M. It supports Function Calling, structured output, and implicit cache. You can call it using OpenAI compatible, DashScope, and Anthropic compatible interfaces.
For information about model context length and pricing, see the Model Studio console. Billing is based on the number of input and output tokens.
In thinking mode, the chain-of-thought is billed as output tokens.

Error codes

If an error occurs, see Error codes for troubleshooting information.
Token Plan
Model Playground
  • Music generation
Statistics and Monitoring
Support