本文介紹了在阿里雲百鍊平台通過API調用 GLM 系列模型的方法。
模型列表
GLM 系列模型是智譜AI專為智能體設計的混合推理模型,提供思考與非思考兩種模式。
|
模型名稱 |
上下文長度 |
最大輸入 |
最大思維鏈長度 |
最大回複長度 |
|
(Token數) |
||||
|
glm-5 |
202,752 |
202,752 |
32,768 |
16,384 |
|
glm-4.7 |
169,984 |
|||
|
glm-4.6 |
||||
以上模型非整合第三方服務,均部署在阿里雲百鍊伺服器上。
快速開始
glm-5 是 GLM 系列最新模型,支援通過enable_thinking參數設定思考與非思考模式。運行以下代碼快速調用思考模式的 glm-5 模型。
需要已擷取API Key並完成配置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"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "你是誰"}]
completion = client.chat.completions.create(
model="glm-5",
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,
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-5',
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://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5",
"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",
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")
.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://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-5",
"input":{
"messages":[
{
"role": "user",
"content": "你是誰?"
}
]
},
"parameters":{
"enable_thinking": true,
"incremental_output": true,
"result_format": "message"
}
}'
流式工具調用
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://dashscope.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",
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://dashscope.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',
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://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5",
"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",
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://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-5",
"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"
}
}'
模型功能
|
模型 |
||||||
|
glm-5 |
|
|
僅非思考模式 |
|
|
當前僅支援隱式緩衝 |
|
glm-4.7 |
|
|
僅非思考模式 |
|
|
|
|
glm-4.6 |
|
|
僅非思考模式 |
|
|
|
參數預設值
|
模型 |
enable_thinking |
temperature |
top_p |
top_k |
repetition_penalty |
|
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 |
計費說明
按照模型的輸入與輸出 Token 計費,價格詳情請參考GLM。
思考模式下,思維鏈按照輸出 Token 計費。
常見問題
Q:如何配置 Dify?
A:目前暫無法在 Dify 上整合阿里雲百鍊的 GLM 系列模型。推薦您通過通義千問卡片使用 Qwen3 模型。更多細節請參見Dify。
錯誤碼
如果執行報錯,請參見錯誤資訊進行解決。