本文介紹了在阿里雲百鍊平台通過API調用 GLM 系列模型的方法。
glm-4.6、glm-4.7 將於2026年7月9日下架。推薦轉用:qwen3.7-plus、qwen3.7-max、qwen3.6-flash。
服務接入地址
不同地區的服務接入地址不同,請根據您選擇的地區配置對應的 Base URL。
OpenAI相容
華北2(北京)
SDK 調用配置的base_url:https://dashscope.aliyuncs.com/compatible-mode/v1
HTTP 要求地址:POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
美國(維吉尼亞)
SDK 調用配置的base_url:https://dashscope-us.aliyuncs.com/compatible-mode/v1
HTTP 要求地址:POST https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
德國(法蘭克福)
SDK 調用配置的base_url:https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/compatible-mode/v1
HTTP 要求地址:POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
調用時請將WorkspaceId替換為真實的Workspace ID。
中國香港
SDK 調用配置的base_url:https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1
HTTP 要求地址:POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1/chat/completions
調用時請將WorkspaceId替換為真實的Workspace ID。
新加坡
Tab 本文
SDK 調用配置的base_url:https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
HTTP 要求地址:POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
調用時請將WorkspaceId替換為真實的 Workspace ID。
DashScope
華北2(北京)
HTTP 要求地址:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
SDK 調用無需配置 base_url。
美國(維吉尼亞)
HTTP 要求地址:POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/text-generation/generation
SDK 調用配置的base_url:
Python
dashscope.base_http_api_url = 'https://dashscope-us.aliyuncs.com/api/v1'Java
方式一:
import com.alibaba.dashscope.protocol.Protocol; Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-us.aliyuncs.com/api/v1");方式二:
import com.alibaba.dashscope.utils.Constants; Constants.baseHttpApiUrl="https://dashscope-us.aliyuncs.com/api/v1";
德國(法蘭克福)
HTTP 要求地址:POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
調用時請將WorkspaceId替換為真實的Workspace ID。
SDK 調用配置的base_url:
Python
調用時請將WorkspaceId替換為真實的Workspace ID。
dashscope.base_http_api_url = 'https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1'Java
調用時請將WorkspaceId替換為真實的Workspace ID。
方式一:
import com.alibaba.dashscope.protocol.Protocol; Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1");方式二:
import com.alibaba.dashscope.utils.Constants; Constants.baseHttpApiUrl="https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1";
中國香港
HTTP 要求地址:POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
調用時請將WorkspaceId替換為真實的Workspace ID。
SDK 調用配置的base_url:
Python
調用時請將WorkspaceId替換為真實的Workspace ID。
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1'Java
調用時請將WorkspaceId替換為真實的Workspace ID。
方式一:
import com.alibaba.dashscope.protocol.Protocol; Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1");方式二:
import com.alibaba.dashscope.utils.Constants; Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1";
新加坡
Tab 本文
HTTP 要求地址為POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
SDK 調用配置的base_url:dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
調用時請將WorkspaceId替換為真實的 Workspace ID。
快速開始
glm-5.2 、glm-5.2-us 和 glm-5.2-fast-preview 是 GLM 系列最新模型,上下文長度 1M,支援通過enable_thinking參數設定思考與非思考模式。運行以下代碼快速調用思考模式的 glm-5.2 模型。
需要已擷取API Key並完成配置API Key到環境變數。如果通過SDK調用,需要安裝 OpenAI 或 DashScope SDK。
OpenAI相容
enable_thinking非 OpenAI 標準參數,OpenAI Python SDK 通過 extra_body傳入,Node.js SDK 作為頂層參數傳入。
Python
範例程式碼
from openai import OpenAI
import os
# 初始化OpenAI用戶端
client = OpenAI(
# 如果沒有配置環境變數,請用阿里雲百鍊API Key替換:api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 調用時請將WorkspaceId替換為真實的Workspace ID。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "你是誰"}]
completion = client.chat.completions.create(
model="glm-5.2",
messages=messages,
# 通過 extra_body 設定 enable_thinking 開啟思考模式
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 + "Token 消耗" + "=" * 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
# 收到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返回結果
====================思考過程====================
讓我仔細思考使用者提出的這個看似簡單但實際上很有深度的問題。
從語言特點來看,使用者使用的是中文,這意味著我應該用中文來回應。這是一個最基礎的自我介紹問題,但背後可能包含著多層次的含義。
首先需要明確的是,作為一個語言模型,我應該誠實地說明自己的身份和本質。我既不是人類,也不具備真正的情感意識,而是一個由深度學習技術訓練的AI助手。這是最基本的事實。
其次,考慮到使用者可能的需求情境,他們或許想瞭解:
1. 我能提供什麼樣的服務
2. 我的專業領域是什麼
3. 我的局限性在哪裡
4. 如何與我更好地互動
在回答中,我應該既表達友好和開放的態度,又保持專業和準確。要說明自己擅長的主要領域,比如知識問答、寫作輔助、創意支援等,但同時也要坦誠地指出自己的局限性,比如缺乏真實的情感體驗。
此外,為了讓回答更加完整,我還應該表達出願意協助使用者解決問題的積極態度。可以適當引導使用者提出更具體的問題,這樣可以更好地展現自己的能力。
考慮到這是一個開放式的開場白,回答時既要簡潔明了,又要包含足夠的資訊量,讓使用者對我的基本情況有一個清晰的認識,同時為後續的對話奠定良好的基礎。
最後,語氣應該保持謙遜和專業,既不過於技術化,也不顯得過分隨意,讓使用者感到舒適和自然。
====================完整回複====================
我是智譜AI訓練的GLM大語言模型,旨在為使用者提供資訊和協助解決問題。我被設計用來理解和產生人類語言,可以回答問題、提供解釋或參與各類話題討論。
我不會儲存您的個人資料,我們的對話是匿名的。有什麼我能幫您瞭解或探討的話題嗎?
====================Token 消耗====================
CompletionUsage(completion_tokens=344, prompt_tokens=7, total_tokens=351, completion_tokens_details=None, prompt_tokens_details=None)Node.js
範例程式碼
import OpenAI from "openai";
import process from 'process';
// 初始化OpenAI用戶端
const openai = new OpenAI({
// 如果沒有配置環境變數,請用阿里雲百鍊API Key替換:apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// 調用時請將WorkspaceId替換為真實的Workspace ID。
baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.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-5.2',
messages,
// 注意:在 Node.js SDK,enable_thinking 這樣的非標準參數作為頂層屬性傳遞,無需放在 extra_body 中
enable_thinking: true,
stream: true,
stream_options: {
include_usage: true
},
});
console.log('\n' + '='.repeat(20) + '思考過程' + '='.repeat(20) + '\n');
for await (const chunk of stream) {
if (!chunk.choices?.length) {
console.log('\n' + '='.repeat(20) + 'Token 消耗' + '='.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;
}
// 收到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();返回結果
====================思考過程====================
讓我仔細思考使用者的問題"你是誰"。這需要從多個角度來分析和回應。
首先,這是一個基礎的身份認知問題。作為GLM大語言模型,需要準確表達自己的身份定位。應該清晰地說明自己是由智譜AI開發的AI助手。
其次,思考使用者提出這個問題的可能意圖。他們可能是初次接觸,想瞭解準系統;也可能想確認是否能提供特定協助;或者只是想測試回應方式。因此需要給出一個開放且友好的回答。
還要考慮回答的完整性。除了身份介紹,也應該簡要說明主要功能,如問答、創作、分析等,讓使用者瞭解可以如何使用這個助手。
最後,要確保語氣友好親和,表達出樂於協助的態度。可以用"很高興為您服務"這樣的表達,讓使用者感受到交流的溫暖。
基於這些思考,可以組織一個簡潔明了的回答,既能回答使用者問題,又能引導後續交流。
====================完整回複====================
我是GLM,由智譜AI訓練的大語言模型。我通過大規模文本資料訓練,能夠理解和產生人類語言,協助使用者回答問題、提供資訊和進行對話交流。
我會持續學習和改進,以提供更好的服務。很高興能為您解答問題或提供協助!有什麼我能為您做的嗎?
====================Token 消耗====================
{ prompt_tokens: 7, completion_tokens: 248, total_tokens: 255 }HTTP
範例程式碼
curl
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.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": "你是誰"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"enable_thinking": true
}'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-5.2",
messages=messages,
result_format="message", # 設定結果格式為 message
enable_thinking=True, # 開啟思考模式
stream=True, # 開啟流式輸出
incremental_output=True, # 開啟增量輸出
)
reasoning_content = "" # 完整思考過程
answer_content = "" # 完整回複
is_answering = False # 是否進入回複階段
print("\n" + "=" * 20 + "思考過程" + "=" * 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
# 收到 content,開始進行回複
if message.content:
if not is_answering:
print("\n" + "=" * 20 + "完整回複" + "=" * 20 + "\n")
is_answering = True
print(message.content, end="", flush=True)
answer_content += message.content
print("\n" + "=" * 20 + "Token 消耗" + "=" * 20 + "\n")
print(chunk.usage)返回結果
====================思考過程====================
讓我仔細思考使用者提出的"你是誰"這個問題。首先需要分析使用者提問的意圖,這可能是初次接觸時的好奇,也可能是想瞭解我的具體功能和能力。
從專業角度,我應該清晰地表達自己的身份 - 作為一個GLM大語言模型,需要說明自己的基本定位和主要功能。要避免過於技術化的表述,而是用通俗易懂的方式解釋。
同時,也要考慮到使用者可能關心的一些實際問題,比如隱私保護、資料安全等。這些都是使用者在使用AI服務時非常關注的點。
另外,為了展現專業性和友好度,可以在介紹的基礎上主動引導對話方向,詢問使用者是否需要特定的協助。這樣既能讓使用者更好地瞭解我,也能為後續對話做好鋪墊。
最後,要確保回答簡潔明了,重點突出,讓使用者快速理解我的身份和用途。這樣的回答既能滿足使用者的好奇心,又能展現專業性和服務意識。
====================完整回複====================
我是智譜AI開發的GLM大語言模型,旨在通過自然語言處理技術為使用者提供資訊和協助。我通過大規模文本資料訓練,能夠理解和產生人類語言,回答問題、提供知識支援和參與對話。
我的設計目標是成為有用的AI助手,同時確保使用者隱私和資料安全。我不儲存使用者的個人資訊,並且會持續學習和改進以提供更優質的服務。
有什麼我能幫您解答的問題或需要協助的任務嗎?
====================Token 消耗====================
{"input_tokens": 8, "output_tokens": 269, "total_tokens": 277}Java
範例程式碼
DashScope Java SDK 版本需要不低於2.19.4。
// 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 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("====================思考過程====================");
isFirstPrint = false;
}
System.out.print(reasoning);
}
if (content != null && !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-5.2")
.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);
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("An exception occurred: " + e.getMessage());
}
}
}返回結果
====================思考過程====================
讓我思考一下如何回答使用者的問題。首先,這是一個關於身份識別的簡單問題,需要清晰直接地回答。
作為一個大語言模型,我應該準確說明自己的基本身份資訊。這包括:
- 名稱:GLM
- 開發人員:智譜AI
- 主要功能:語言理解和產生
考慮到使用者的提問可能源於初次接觸,我需要用通俗易懂的方式介紹自己,避免使用過於技術性的術語。同時,也應該簡要說明自己的主要能力,這樣可以協助使用者更好地瞭解如何與我互動。
我還應該以友好開放的態度表達,歡迎使用者提出各種問題,這樣可以為後續對話打下良好基礎。不過介紹要簡潔明了,不需要過於詳細,以免給使用者造成資訊負擔。
最後,為了促進進一步交流,可以主動詢問使用者是否需要特定協助,這樣能夠更好地服務於使用者的實際需求。
====================完整回複====================
我是GLM,由智譜AI開發的大語言模型。我通過海量文本資料訓練而成,能夠理解和產生人類語言,回答問題、提供資訊和進行對話。
我的設計目的是協助使用者解決問題、提供知識和支援各類語言任務。我會不斷學習和更新,以提供更準確、有用的回答。
有什麼我能幫您解答或探討的問題嗎?HTTP
範例程式碼
curl
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.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": "你是誰?"
}
]
},
"parameters":{
"enable_thinking": true,
"incremental_output": true,
"result_format": "message"
}
}'Anthropic相容
Python
範例程式碼
import anthropic
import os
client = anthropic.Anthropic(
# 如果沒有配置環境變數,請用阿里雲百鍊API Key替換:api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 調用時請將WorkspaceId替換為真實的Workspace ID。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
)
message = client.messages.create(
model="glm-5.2",
max_tokens=1024,
messages=[
{"role": "user", "content": "你是誰"}
],
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)HTTP
範例程式碼
curl
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.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": "你是誰"
}
]
}'流式工具調用
glm-5.2、glm-5.2-us、glm-5.2-fast-preview、glm-5.1、glm-5、glm-4.7、glm-4.6 支援tool_stream參數(boolean,預設false),僅在stream為true時生效。開啟後,Function Calling 返回的 tool_call 參數(arguments)會以流式增量方式逐步返回,而非等待完整產生後一次性返回。
stream與tool_stream的組合行為如下:
stream | tool_stream | tool_call 返回方式 |
true | true | arguments 以增量方式分多個 chunk 返回 |
true | false(預設) | arguments 在一個 chunk 中完整返回 |
false | true/false | tool_stream 不生效,arguments 在完整響應中一次性返回 |
OpenAI相容
Python
範例程式碼
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "擷取指定城市的天氣資訊",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名稱"}
},
"required": ["city"]
}
}
}
]
messages = [{"role": "user", "content": "北京天氣怎麼樣"}]
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}")Node.js
範例程式碼
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "擷取指定城市的天氣資訊",
parameters: {
type: "object",
properties: {
city: { type: "string", description: "城市名稱" }
},
required: ["city"]
}
}
}
];
async function main() {
try {
const stream = await openai.chat.completions.create({
model: 'glm-5.2',
messages: [{ role: 'user', content: '北京天氣怎麼樣' }],
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}`);
}
}
} catch (error) {
console.error('Error:', error);
}
}
main();HTTP
範例程式碼
curl
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.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": "北京天氣怎麼樣"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "擷取指定城市的天氣資訊",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名稱"}
},
"required": ["city"]
}
}
}
],
"stream": true,
"stream_options": {"include_usage": true},
"tool_stream": true
}'DashScope
Python
範例程式碼
import os
from dashscope import Generation
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "擷取指定城市的天氣資訊",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名稱"}
},
"required": ["city"]
}
}
}
]
messages = [{"role": "user", "content": "北京天氣怎麼樣"}]
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}")HTTP
範例程式碼
curl
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.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": "北京天氣怎麼樣"
}
]
},
"parameters": {
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "擷取指定城市的天氣資訊",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名稱"}
},
"required": ["city"]
}
}
}
],
"tool_stream": true,
"incremental_output": true,
"result_format": "message"
}
}'推理強度(reasoning_effort)
glm-5.2、glm-5.2-fast-preview 和 glm-5.1 預設開啟思考模式,模型會先輸出思考過程(reasoning_content),再給出最終回答。通過 reasoning_effort 參數可以調整推理強度,取值越高思考越充分。不同模型支援的可選取值不同,傳入不支援的取值會返回 invalid_parameter_error 錯誤,請按下表選擇。
模型 | reasoning_effort 可選取值 |
glm-5.2 |
|
glm-5.2-us |
|
glm-5.2-fast-preview |
|
glm-5.1 |
|
如需關閉思考,可在 OpenAI 相容與 DashScope 方式中傳入 enable_thinking=false,該參數優先順序高於 reasoning_effort。
Anthropic 相容方式不支援 reasoning_effort 參數。如需擷取思考內容,請使用 Anthropic 原生 thinking 參數:{"thinking":{"type":"enabled","budget_tokens":1024}},開啟後響應 content 中會返回 type 為 thinking 的思考塊。
OpenAI相容
Python
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
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": "9.9和9.11哪個大"}],
reasoning_effort="high",
)
print(completion.choices[0].message.content)Node.js
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
});
const completion = await openai.chat.completions.create({
model: "glm-5.2",
messages: [{ role: "user", content: "9.9和9.11哪個大" }],
reasoning_effort: "high",
});
console.log(completion.choices[0].message.content);curl
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.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": "9.9和9.11哪個大"}],
"reasoning_effort": "high"
}'DashScope
import os
from dashscope import Generation
response = Generation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="glm-5.2",
messages=[{"role": "user", "content": "9.9和9.11哪個大"}],
reasoning_effort="high",
result_format="message",
)
print(response.output.choices[0].message.content)清除歷史思考(clear_thinking)
clear_thinking 參數用於控制多輪對話中是否將歷史輪次的 reasoning_content(思考過程)作為上下文輸入給模型。僅 GLM 系列模型支援。
true:忽略歷史輪次的reasoning_content,僅使用可見文本、工具調用與結果等非推理內容作為上下文輸入,可降低上下文長度與成本。false(預設):保留歷史輪次的reasoning_content並隨上下文一同提供給模型。若希望啟用 Preserved Thinking,必須在 messages 中完整、未修改、按原順序透傳歷史reasoning_content,缺失、裁剪、改寫或重排會導致效果下降或無法生效。
該參數隻影響跨輪次的歷史思考內容,不改變模型在當前輪次內是否產生/輸出思考。
以下樣本使用同一組多輪 messages(assistant 訊息中攜帶 reasoning_content)。設定 clear_thinking=true 後,歷史思考內容不會被計入上下文,因此 prompt_tokens 少於 false(預設)的情況,實際數值取決於歷史 reasoning_content 的長度。
OpenAI相容
Python
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 調用時請將WorkspaceId替換為真實的Workspace ID。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
# 多輪對話,assistant 訊息中攜帶 reasoning_content(歷史思考過程)
messages = [
{"role": "user", "content": "請計算 15 * 23 是多少?"},
{"role": "assistant", "content": "15 乘以 23 等於 345。", "reasoning_content": "15 * 23 = 345"},
{"role": "user", "content": "那再加上 55 呢?"},
{"role": "assistant", "content": "345 加上 55 等於 400。", "reasoning_content": "345 + 55 = 400"},
{"role": "user", "content": "剛才的中間結果是多少?"},
]
completion = client.chat.completions.create(
model="glm-5.2",
messages=messages,
extra_body={
"enable_thinking": True,
# true:忽略歷史 reasoning_content,降低上下文長度與成本
# false(預設):保留歷史 reasoning_content(Preserved Thinking)
"clear_thinking": True,
},
)
print(completion.usage.prompt_tokens) # true 時少於 falsecurl
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.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": "請計算 15 * 23 是多少?"},
{"role": "assistant", "content": "15 乘以 23 等於 345。", "reasoning_content": "15 * 23 = 345"},
{"role": "user", "content": "那再加上 55 呢?"},
{"role": "assistant", "content": "345 加上 55 等於 400。", "reasoning_content": "345 + 55 = 400"},
{"role": "user", "content": "剛才的中間結果是多少?"}
],
"enable_thinking": true,
"clear_thinking": true
}'DashScope
import os
from dashscope import Generation
# 多輪對話,assistant 訊息中攜帶 reasoning_content(歷史思考過程)
messages = [
{"role": "user", "content": "請計算 15 * 23 是多少?"},
{"role": "assistant", "content": "15 乘以 23 等於 345。", "reasoning_content": "15 * 23 = 345"},
{"role": "user", "content": "那再加上 55 呢?"},
{"role": "assistant", "content": "345 加上 55 等於 400。", "reasoning_content": "345 + 55 = 400"},
{"role": "user", "content": "剛才的中間結果是多少?"},
]
response = Generation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="glm-5.2",
messages=messages,
result_format="message",
enable_thinking=True,
# true:忽略歷史 reasoning_content,降低上下文長度與成本
# false(預設):保留歷史 reasoning_content(Preserved Thinking)
clear_thinking=True,
)
print(response.usage.input_tokens)其它功能
模型 | ||||||
glm-5.2 | 僅非思考模式 | 僅支援隱式緩衝 | ||||
glm-5.2-us | 僅非思考模式 | 僅支援隱式緩衝 | ||||
glm-5.2-fast-preview | 僅非思考模式 | 僅支援隱式緩衝 | ||||
glm-5.1 | 僅非思考模式 | 支援顯式與隱式緩衝 | ||||
glm-5 | 僅非思考模式 | 僅支援隱式緩衝 | ||||
glm-4.7 | 僅非思考模式 | 僅支援隱式緩衝 | ||||
glm-4.6 | 僅非思考模式 | 僅支援隱式緩衝 |
參數預設值
模型 | enable_thinking | temperature | top_p | top_k | repetition_penalty |
glm-5.2 | true | 1.0 | 0.95 | 20 | 1.0 |
glm-5.2-us | true | 1.0 | 0.95 | 20 | 1.0 |
glm-5.2-fast-preview | 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 |
參數含義請參見OpenAI相容-Chat。
模型列表與計費
GLM 系列模型是智譜AI專為智能體設計的混合推理模型,提供思考與非思考兩種模式。
glm-5.2 與 glm-5.2-us:GLM 最新模型,上下文長度 1M,支援 Function Calling、結構化輸出及隱式緩衝。支援 OpenAI 相容、DashScope 及 Anthropic 相容介面調用。
glm-5.2-fast-preview:glm-5.2模型的快速模式,詳情請參考快速模式(Fast mode)。
模型上下文長度與價格資訊請參見百鍊控制台。
按照模型的輸入與輸出 Token 計費。
思考模式下,思維鏈按照輸出 Token 計費。
錯誤碼
如果執行報錯,請參見錯誤碼進行解決。