GLM-4.5

本文介绍了在阿里云百炼平台通过API调用 GLM-4.5 系列模型的方法。每个模型各有 100 万免费 Token。

模型列表和计费

GLM-4.5系列模型是智谱AI专为智能体设计的混合推理模型,提供思考与非思考两种模式。

模型名称

上下文长度

最大输入

最大思维链长度

最大回复长度

输入成本

输出成本

免费额度

查看剩余额度

(Token数)

(每千Token)

glm-4.5

131,072

98,304

32,768

16,384

阶梯计费,请参见下方表格

100Token

有效期:百炼开通后180天内

glm-4.5-air

以上模型根据请求输入的 Token数,采取阶梯计费。

模型名称

输入 Token 数

输入成本(每千Token)

输出成本(每千Token)

glm-4.5

0-32K

0.003

0.014

32K-96K

0.004

0.016

glm-4.5-air

0-32K

0.0008

0.006

32K-96K

0.0012

0.008

以上模型非集成第三方服务,均部署在阿里云百炼服务器上。

注意事项

支持功能

支持以下功能:

不支持非流式输出、工具调用联网搜索

默认参数

  • temperature:0.6

  • top_p:0.95

  • top_k:20

  • repetition_penalty:1.0

快速开始

API 使用前提:已获取API Key并完成配置API Key到环境变量。如果通过SDK调用,需要安装 OpenAI 或 DashScope SDK(DashScope Java SDK 版本需要不低于2.19.4)。

运行以下代码,通过流式输出的方式调用模型。通过响应的reasoning_content字段获取思考过程,content字段获取回复内容。

OpenAI兼容

Python

示例代码

from openai import OpenAI
import os

# 初始化OpenAI客户端
client = OpenAI(
    # 如果没有配置环境变量,请用阿里云百炼API Key替换:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "你是谁"}]

completion = client.chat.completions.create(
    model="glm-4.5",
    messages=messages,
    extra_body={"enable_thinking": True},
    stream=True,
    stream_options={
        "include_usage": True
    },
)

reasoning_content = ""  # 完整思考过程
answer_content = ""  # 完整回复
is_answering = False  # 是否进入回复阶段
print("\n" + "=" * 20 + "思考过程" + "=" * 20 + "\n")

for chunk in completion:
    if not chunk.choices:
        print("\n" + "="*20+"Usage"+"="*20)
        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

    # 收到content,开始进行回复
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "完整回复" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

返回结果

====================思考过程====================

让我思考一下用户提出的"你是谁"这个问题。这是一个很基础但重要的问题,需要从多个角度来组织回答。

首先,需要明确自己的身份定位 - 作为GLM大语言模型,这是最核心的身份标识。这个身份包含了几个关键要素:开发方是智谱AI,技术基础是深度学习,以及作为人工智能助手的本质属性。

其次,要考虑如何用简洁明了的方式介绍自己的主要功能和特点。这包括语言理解与生成能力、知识问答、文本创作等核心功能。同时也要说明自己的服务宗旨,即通过对话方式为用户提供帮助和支持。

在回答时,还需要注意以下几点:
1. 保持专业性和友好度的平衡
2. 突出自身的优势和特点
3. 避免使用过于技术性的术语
4. 为后续可能的深入交流预留空间

最后,应该以开放和积极的态度结束回答,表达愿意进一步了解用户需求并提供帮助的意愿。这样的回答既能满足用户的基本询问,又能促进后续的良性互动。
====================完整回复====================

我是GLM,由智谱AI开发的大语言模型。我基于深度学习技术训练,能够理解和生成人类语言,旨在通过对话方式提供信息和帮助。

我可以回答问题、创作内容、解释概念等多种任务,并且会不断学习和改进。很高兴能与你交流,请问有什么我可以帮助你的吗?
====================Usage====================
CompletionUsage(completion_tokens=275, prompt_tokens=7, total_tokens=282, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=None, audio_tokens=None, reasoning_tokens=212, rejected_prediction_tokens=None), prompt_tokens_details=None)

Node.js

示例代码

import OpenAI from "openai";
import process from 'process';

// 初始化 openai 客户端
const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY, // 从环境变量读取
    baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1'
});

let reasoningContent = '';
let answerContent = '';
let isAnswering = false;

async function main() {
    try {
        const messages = [{ role: 'user', content: '你是谁' }];
        const stream = await openai.chat.completions.create({
            model: 'glm-4.5',
            messages,
            stream: true,
            enable_thinking: true
        });
        console.log('\n' + '='.repeat(20) + '思考过程' + '='.repeat(20) + '\n');

        for await (const chunk of stream) {
            if (!chunk.choices?.length) {
                console.log('\nUsage:');
                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;
            }

            // 收到content,开始进行回复
            if (delta.content !== undefined && delta.content) {
                if (!isAnswering) {
                    console.log('\n' + '='.repeat(20) + '完整回复' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();

返回结果

====================思考过程====================

让我思考如何回答这个关于身份的问题。作为一个语言模型,首先需要明确自己的定位和功能。我应该准确介绍自己的本质 - 一个由智谱AI开发的GLM大语言模型。

这个问题看似简单,但需要从多个角度来思考回答。首先要说明自己的开发者和基本属性,这能让用户了解我的背景。其次,要强调我的核心功能 - 即通过自然语言处理技术为用户提供帮助和信息服务。

在回答时,需要注意保持专业和友好的语气。我应该说明自己的主要能力包括回答问题、提供信息和进行对话,但同时也要诚实地指出自己的局限性 - 比如知识范围可能存在限制,并且不具备实时联网的能力。

为了让回答更加完整,还应该表达出帮助用户的意愿和开放态度,鼓励用户提出更多问题。这样的回答既能满足用户的好奇心,又能为后续的交流奠定良好的基础。

最后,要确保回答简洁明了,避免使用过于专业的术语,让所有用户都能轻松理解。
====================完整回复====================

我是智谱AI开发的GLM大语言模型。我被训练用来理解和生成人类语言,以便回答问题、提供信息和进行对话。我的设计目标是帮助用户解决问题并提供有用的信息。

我不会存储您的个人数据,并且我的知识有一定的局限性。有什么我能帮您解答的问题吗?

HTTP

示例代码

curl

curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "glm-4.5",
    "messages": [
        {
            "role": "user", 
            "content": "你是谁"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "enable_thinking": true
}'

返回结果

data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1754481524,"system_fingerprint":null,"model":"glm-4.5","id":"chatcmpl-58b9fb50-1981-9b51-b5ea-8e83b6e1b748"}

data: {"choices":[{"finish_reason":null,"logprobs":null,"delta":{"content":null,"reasoning_content":"让我"},"index":0}],"object":"chat.completion.chunk","usage":null,"created":1754481524,"system_fingerprint":null,"model":"glm-4.5","id":"chatcmpl-58b9fb50-1981-9b51-b5ea-8e83b6e1b748"}

data: {"choices":[{"delta":{"content":null,"reasoning_content":"思考"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1754481524,"system_fingerprint":null,"model":"glm-4.5","id":"chatcmpl-58b9fb50-1981-9b51-b5ea-8e83b6e1b748"}

...

data: {"choices":[{"delta":{"content":"或","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1754481524,"system_fingerprint":null,"model":"glm-4.5","id":"chatcmpl-58b9fb50-1981-9b51-b5ea-8e83b6e1b748"}

data: {"choices":[{"delta":{"content":"探讨","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1754481524,"system_fingerprint":null,"model":"glm-4.5","id":"chatcmpl-58b9fb50-1981-9b51-b5ea-8e83b6e1b748"}

data: {"choices":[{"delta":{"content":"的话题","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1754481524,"system_fingerprint":null,"model":"glm-4.5","id":"chatcmpl-58b9fb50-1981-9b51-b5ea-8e83b6e1b748"}

data: {"choices":[{"delta":{"content":"吗","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1754481524,"system_fingerprint":null,"model":"glm-4.5","id":"chatcmpl-58b9fb50-1981-9b51-b5ea-8e83b6e1b748"}

data: {"choices":[{"delta":{"content":"?","reasoning_content":null},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1754481524,"system_fingerprint":null,"model":"glm-4.5","id":"chatcmpl-58b9fb50-1981-9b51-b5ea-8e83b6e1b748"}

data: {"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1754481524,"system_fingerprint":null,"model":"glm-4.5","id":"chatcmpl-58b9fb50-1981-9b51-b5ea-8e83b6e1b748"}

data: {"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":7,"completion_tokens":290,"total_tokens":297,"completion_tokens_details":{"reasoning_tokens":234}},"created":1754481524,"system_fingerprint":null,"model":"glm-4.5","id":"chatcmpl-58b9fb50-1981-9b51-b5ea-8e83b6e1b748"}

data: [DONE]

DashScope

Python

示例代码

import os
from dashscope import Generation

messages = [{"role": "user", "content": "你是谁?"}]


completion = Generation.call(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="glm-4.5",
    messages=messages,
    result_format="message",
    enable_thinking=True,
    stream=True,
    incremental_output=True,
)

# 定义完整思考过程
reasoning_content = ""
# 定义完整回复
answer_content = ""
# 判断是否结束思考过程并开始回复
is_answering = False

print("=" * 20 + "思考过程" + "=" * 20)

for chunk in completion:
    # 如果思考过程与回复皆为空,则忽略
    if (
        chunk.output.choices[0].message.content == ""
        and chunk.output.choices[0].message.reasoning_content == ""
    ):
        pass
    else:
        # 如果当前为思考过程
        if (
            chunk.output.choices[0].message.reasoning_content != ""
            and chunk.output.choices[0].message.content == ""
        ):
            print(chunk.output.choices[0].message.reasoning_content, end="", flush=True)
            reasoning_content += chunk.output.choices[0].message.reasoning_content
        # 如果当前为回复
        elif chunk.output.choices[0].message.content != "":
            if not is_answering:
                print("\n" + "=" * 20 + "完整回复" + "=" * 20)
                is_answering = True
            print(chunk.output.choices[0].message.content, end="", flush=True)
            answer_content += chunk.output.choices[0].message.content

返回结果

====================思考过程====================
让我思考如何回答这个关于身份的问题。作为一个语言模型,需要准确而清晰地表达自己的定位和功能。

首先,要明确说明自己的本质 - 一个AI语言模型。这是最基础的认知,需要让用户清楚了解他们正在交流的对象是什么。

其次,需要介绍自己的核心功能和用途。我主要服务于对话交互、信息提供和问题解答等领域。这些功能的说明应该具体而实用,让用户了解我能为他们做些什么。

第三,要强调持续学习和进步的特性。作为一个AI模型,知识储备和交互能力都在不断优化提升,这一点对于建立用户信任很重要。

同时,回答要保持谦逊和开放的态度。承认自己的局限性,并表达愿意倾听用户需求、提供帮助的诚意。

最后,组织语言时要简洁明了,避免过于技术性的表述,确保回答易于理解。同时也要保持友好和专业的语调,为后续对话奠定良好的基础。

通过这样的思考,可以给出一个既准确又友好的自我介绍,帮助用户更好地了解和使用这个AI助手。
====================完整回复====================
我是智谱AI训练的GLM大语言模型,通过大规模文本数据训练,能够理解和生成人类语言。我的目标是为您提供有用、准确的信息和帮助,同时尊重您的隐私。

我可以回答问题、参与对话、提供解释和建议,但也有知识范围和能力限制。很高兴能为您服务,有什么我可以帮您的吗?

Java

示例代码

// dashscope SDK的版本 >= 2.19.4
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 com.alibaba.dashscope.utils.Constants;
import io.reactivex.Flowable;
import java.lang.System;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {
    private static final Logger logger = LoggerFactory.getLogger(Main.class);
    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.isEmpty()) {
            reasoningContent.append(reasoning);
            if (isFirstPrint) {
                System.out.println("====================思考过程====================");
                isFirstPrint = false;
            }
            System.out.print(reasoning);
        }

        if (!content.isEmpty()) {
            finalContent.append(content);
            if (!isFirstPrint) {
                System.out.println("\n====================完整回复====================");
                isFirstPrint = true;
            }
            System.out.print(content);
        }
    }
    private static GenerationParam buildGenerationParam(Message userMsg) {
        return GenerationParam.builder()
                // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("glm-4.5")
                .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("你是谁?").build();
            streamCallWithMessage(gen, userMsg);
//             打印最终结果
//            if (reasoningContent.length() > 0) {
//                System.out.println("\n====================完整回复====================");
//                System.out.println(finalContent.toString());
//            }
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
        System.exit(0);
    }
}

返回结果

====================思考过程====================
让我思考一下如何回答这个关于身份的问题。作为一个语言模型,我需要准确清晰地介绍自己的本质和能力。

首先,我应该明确说明自己是一个AI语言模型,这是最基础的身份认知。但同时,我也需要具体说明自己的开发方是智谉AI,这样可以让用户了解我的来源。

接下来,我需要说明自己的核心功能和专长。作为一个大语言模型,我擅长文本理解、生成和处理,这是我的主要能力范围。同时,我应该表达出乐于助人的态度,让用户感受到我是一个友好的助手。

在回答时,我还需要注意表达方式的准确性和专业性。虽然我是一个AI,但我应该用平实易懂的语言来介绍自己,避免使用过于技术性的术语,让所有用户都能理解。

最后,我应该保持开放和谦逊的态度,表明自己虽然能力强大,但也有局限性,并且愿意在能力范围内为用户提供帮助。这样的回答既能展现专业性,又能体现亲和力。

综合这些考虑,我可以给出一个清晰、准确且友好的自我介绍。
====================完整回复====================
我是智谱AI开发的GLM大语言模型。我被训练用于理解和生成人类语言,能够回答问题、提供信息和进行对话交流。

我的知识库涵盖广泛的主题,但我也在不断学习中。有什么我能帮你解答或探讨的问题吗?

HTTP

示例代码

curl

curl -X POST "https://dashscope.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-4.5",
    "input":{
        "messages":[      
            {
                "role": "user",
                "content": "你是谁?"
            }
        ]
    },
    "parameters":{
        "enable_thinking": true,
        "incremental_output": true,
        "result_format": "message"
    }
}'

返回结果

id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"让我","role":"assistant"}}]},"usage":{"total_tokens":9,"output_tokens":1,"input_tokens":8,"output_tokens_details":{"reasoning_tokens":1}},"request_id":"a95464b3-d999-9e38-b58b-eab3d2017065"}

id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"仔细","role":"assistant"}}]},"usage":{"total_tokens":10,"output_tokens":2,"input_tokens":8,"output_tokens_details":{"reasoning_tokens":2}},"request_id":"a95464b3-d999-9e38-b58b-eab3d2017065"}

id:3
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"思考","role":"assistant"}}]},"usage":{"total_tokens":11,"output_tokens":3,"input_tokens":8,"output_tokens_details":{"reasoning_tokens":3}},"request_id":"a95464b3-d999-9e38-b58b-eab3d2017065"}

...

id:295
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"吗","reasoning_content":"","role":"assistant"}}]},"usage":{"total_tokens":304,"output_tokens":296,"input_tokens":8,"output_tokens_details":{"reasoning_tokens":229}},"request_id":"a95464b3-d999-9e38-b58b-eab3d2017065"}

id:296
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"?","reasoning_content":"","role":"assistant"}}]},"usage":{"total_tokens":305,"output_tokens":297,"input_tokens":8,"output_tokens_details":{"reasoning_tokens":229}},"request_id":"a95464b3-d999-9e38-b58b-eab3d2017065"}

id:297
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"stop"}]},"usage":{"total_tokens":306,"output_tokens":298,"input_tokens":8,"output_tokens_details":{"reasoning_tokens":229}},"request_id":"a95464b3-d999-9e38-b58b-eab3d2017065"}

常见问题

Q:如何配置 Dify

A:由于 GLM-4.5 系列模型不支持非流式输出,暂无法通过 OpenAI Compatible 卡片进行配置。推荐您通过通义千问卡片使用 Qwen3 模型。更多细节请参见Dify

错误码

如果执行报错,请参见错误信息进行解决。