このトピックでは、API を使用して Alibaba Cloud Model Studio プラットフォームで GLM シリーズモデルを呼び出す方法について説明します。
`glm-4.6` と `glm-4.7` は 2026 年 7 月 9 日に提供終了となります。 qwen3.7-plus、qwen3.7-max、qwen3.6-flash への移行を推奨します。
Model Studio は、中国 (北京) リージョン向けにワークスペース専用ドメイン https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com をリリースしました。この新しい専用ドメインは、推論リクエストに対してより高いパフォーマンスと安定性を提供します。https://dashscope.aliyuncs.com から新しいドメインへの移行を推奨します。
{WorkspaceId} はご利用のワークスペース ID で、Model Studio コンソールの [ワークスペース詳細] ページで確認できます。既存のドメインも引き続き完全に機能します。
サービスエンドポイント
サービスエンドポイントはリージョンによって異なります。選択したリージョンに対応するベース URL を設定してください。
OpenAI 互換
中国 (北京)
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 をご利用のワークスペース 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 をご利用のワークスペース ID に置き換えてください。
シンガポール
タブ本文
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 をご利用のワークスペース ID に置き換えてください。
DashScope
中国 (北京)
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
-
方法 1:
import com.alibaba.dashscope.protocol.Protocol; Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-us.aliyuncs.com/api/v1"); -
方法 2:
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 をご利用のワークスペース ID に置き換えてください。
SDK 呼び出しの base_url は次のとおりです。
Python
呼び出しを行う際に、WorkspaceId をご利用のワークスペース ID に置き換えてください。
dashscope.base_http_api_url = 'https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1'Java
呼び出しを行う際に、WorkspaceId をご利用のワークスペース ID に置き換えてください。
-
方法 1:
import com.alibaba.dashscope.protocol.Protocol; Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1"); -
方法 2:
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 をご利用のワークスペース ID に置き換えてください。
SDK 呼び出しの base_url は次のとおりです。
Python
呼び出しを行う際に、WorkspaceId をご利用のワークスペース ID に置き換えてください。
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1'Java
呼び出しを行う際に、WorkspaceId をご利用のワークスペース ID に置き換えてください。
-
方法 1:
import com.alibaba.dashscope.protocol.Protocol; Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1"); -
方法 2:
import com.alibaba.dashscope.utils.Constants; Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1";
シンガポール
タブコンテンツ
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 をご利用のワークスペース ID に置き換えてください。
はじめに
glm-5.2 は、GLM シリーズの最新のモデルです。コンテキスト長は 1M で、enable_thinking パラメーターを使用して思考モードとノンシンキングモードを設定できます。次のコードを実行すると、思考モードで glm-5.2 モデルを素早く呼び出すことができます。
開始する前に、API キーを取得し、環境変数として設定してください。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(
# 環境変数が設定されていない場合は、値を Model Studio API キーに置き換えます: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 呼び出しを行う際に、WorkspaceId を実際のワークスペース 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 + "トークン使用量" + "=" * 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 + "完全な応答" + "=" * 20 + "\n")
is_answering = True
print(delta.content, end="", flush=True)
answer_content += delta.content
応答
====================思考プロセス====================
ユーザーの質問を慎重に検討してみましょう。単純に見えますが、実際には深みがあります。
言語的な観点から、ユーザーは中国語を使用しているため、中国語で応答する必要があります。これは基本的な自己紹介の質問ですが、複数の意味合いを持つ可能性があります。
まず、言語モデルとして、自分のアイデンティティと性質を正直に述べる必要があることを明確にする必要があります。私は人間ではなく、本当の感情的な認識も持っていません。私はディープラーニング技術でトレーニングされた AI アシスタントです。これが最も基本的な事実です。
次に、ユーザーの潜在的なシナリオを考慮すると、彼らは次のことを知りたいかもしれません:
1. どのようなサービスを提供できますか?
2. 私の専門分野は何ですか?
3. 私の限界は何ですか?
4. どうすれば私とより良く対話できますか?
私の回答では、プロフェッショナルで正確でありながら、フレンドリーでオープンな態度を表現する必要があります。知識 Q&A、ライティング支援、創造的なサポートなど、私の主な専門分野を述べますが、本当の感情的な経験がないなど、私の限界も率直に指摘する必要があります。
さらに、回答をより完全なものにするために、ユーザーが問題を解決するのを助けたいという前向きな姿勢も表現する必要があります。私の能力をより良く示すために、ユーザーがより具体的な質問をするように適切に誘導することができます。
これはオープンエンドな始まりであるため、回答は簡潔で有益であるべきで、ユーザーに私の基本的な状況を明確に理解させ、その後の会話の良い基盤を築く必要があります。
最後に、トーンは謙虚でプロフェッショナルであるべきで、技術的すぎず、カジュアルすぎず、ユーザーが快適で自然に感じるようにする必要があります。
====================完全な応答====================
私は Zhipu AI によってトレーニングされた GLM 大規模言語モデルで、ユーザーに情報を提供し、問題解決を支援するように設計されています。私は人間の言語を理解し、生成するように設計されており、質問に答えたり、説明を提供したり、さまざまなトピックに関する議論に参加したりできます。
私はあなたの個人データを保存せず、私たちの会話は匿名です。私が理解したり議論したりするのを手伝えるトピックはありますか?
====================トークン使用量====================
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({
// 環境変数が設定されていない場合は、値を Model Studio API キーに置き換えます: apiKey: "sk-xxx"
apiKey: process.env.DASHSCOPE_API_KEY,
// 呼び出しを行う際に、WorkspaceId を実際のワークスペース 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) + 'トークン使用量' + '='.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) + '完全な応答' + '='.repeat(20) + '\n');
isAnswering = true;
}
process.stdout.write(delta.content);
answerContent += delta.content;
}
}
} catch (error) {
console.error('エラー:', error);
}
}
main();
応答
====================思考プロセス====================
ユーザーの質問「あなたは誰ですか?」について、慎重に考えてみましょう。これは複数の観点から分析し、回答する必要があります。
まず、これは基本的なアイデンティティに関する質問です。GLM 大規模言語モデルとして、私は自分のアイデンティティを正確に表現する必要があります。私は Zhipu AI によって開発された AI アシスタントであることを明確に述べるべきです。
次に、この質問をするユーザーの意図を考慮する必要があります。初めてのユーザーで、私の基本的な機能を知りたいのかもしれませんし、特定の助けを提供できるか確認したいのかもしれませんし、単に私の応答スタイルを試しているだけかもしれません。したがって、オープンでフレンドリーな回答をする必要があります。
また、回答の完全性も考慮する必要があります。私のアイデンティティを紹介するだけでなく、Q&A、作成、分析など、私の主な機能も簡単に説明して、ユーザーがこのアシスタントの使い方を理解できるようにする必要があります。
最後に、フレンドリーで親しみやすいトーンを確保し、助けたいという意欲を表現する必要があります。「喜んでお仕えします」のような表現を使って、ユーザーにコミュニケーションの温かさを感じさせることができます。
これらの考えに基づいて、ユーザーの質問に答えるだけでなく、その後のコミュニケーションを導く、簡潔で明確な回答をまとめることができます。
====================完全な応答====================
私は GLM、Zhipu AI によってトレーニングされた大規模言語モデルです。私は膨大な量のテキストデータでトレーニングされており、人間の言語を理解し、生成し、ユーザーが質問に答え、情報を提供し、会話に参加するのを助けます。
より良いサービスを提供するために、私は学び続け、改善していきます。ご質問にお答えしたり、お手伝いできることを嬉しく思います!何かご用はありますか?
====================トークン使用量====================
{ 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(
# 環境変数が設定されていない場合は、値を Model Studio API キーに置き換えます: 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
# コンテンツを受信した後、応答を開始
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 + "トークン使用量" + "=" * 20 + "\n")
print(chunk.usage)
応答
====================思考プロセス====================
ユーザーの質問「あなたは誰ですか?」について慎重に考えてみましょう。まず、ユーザーの意図を分析する必要があります。これは初めてのユーザーの好奇心からくるものかもしれませんし、私の特定の機能や能力を理解したいのかもしれません。
専門的な観点から、私は自分のアイデンティティを明確に述べるべきです - GLM 大規模言語モデルとして、私の基本的な位置づけと主な機能を説明する必要があります。過度に技術的な説明は避け、分かりやすい言葉を使うべきです。
同時に、プライバシー保護やデータセキュリティなど、ユーザーが懸念する可能性のある実際的な問題も考慮する必要があります。これらは、ユーザーが AI サービスを使用する際に非常に懸念する点です。
さらに、プロフェッショナリズムとフレンドリーさを示すために、紹介の後に積極的に会話を誘導し、ユーザーが特定の助けを必要としているかどうかを尋ねることができます。これは、ユーザーが私をより良く理解するのに役立つだけでなく、その後の会話への道を開くことにもなります。
最後に、回答が簡潔で明確であり、要点が強調されていることを確認する必要があります。これにより、ユーザーは私のアイデンティティと目的をすばやく理解できます。このような回答は、ユーザーの好奇心を満たすと同時に、プロフェッショナリズムとサービス指向の態度を示すことができます。
====================完全な応答====================
私は Zhipu AI によって開発された GLM 大規模言語モデルで、自然言語処理技術を通じてユーザーに情報と助けを提供するために設計されています。私は膨大な量のテキストデータでトレーニングされており、人間の言語を理解し、生成し、質問に答え、知識をサポートし、会話に参加することができます。
私の設計目標は、ユーザーのプライバシーとデータセキュリティを確保しながら、役立つ AI アシスタントになることです。私はユーザーの個人情報を保存せず、より良いサービスを提供するために継続的に学習し、改善していきます。
お答えできる質問や、お手伝いできるタスクはありますか?
====================トークン使用量====================
{"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()
// 環境変数が設定されていない場合は、次の行を .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("例外が発生しました: " + e.getMessage());
}
}
}
応答
====================思考プロセス====================
ユーザーの質問にどう答えるか考えてみましょう。まず、これはアイデンティティに関する単純な質問であり、明確で直接的な回答が必要です。
大規模言語モデルとして、私は基本的なアイデンティティ情報を正確に述べるべきです。これには以下が含まれます:
- 名前: GLM
- 開発者: Zhipu AI
- 主な機能: 言語理解と生成
ユーザーの質問が初めての対話から生じている可能性があることを考慮すると、過度に技術的な用語を避け、分かりやすい方法で自己紹介する必要があります。同時に、ユーザーが私とどのように対話するかをより良く理解できるように、私の主な能力も簡単に説明する必要があります。
また、フレンドリーでオープンな態度を表現し、ユーザーがさまざまな質問をすることを歓迎することで、その後の会話の良い基盤を築くことができます。ただし、紹介は簡潔で、過度に詳細にならないようにして、ユーザーに情報過多の負担をかけないようにする必要があります。
最後に、さらなるコミュニケーションを促進するために、ユーザーが特定の助けを必要としているかどうかを積極的に尋ねることで、ユーザーの実際のニーズにより良く応えることができます。
====================完全な応答====================
私は GLM、Zhipu 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(
# 環境変数が設定されていない場合は、値を Model Studio API キーに置き換えます: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 呼び出しを行う際に、WorkspaceId を実際のワークスペース 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.1、glm-5、glm-4.7、および glm-4.6 は tool_stream パラメーターをサポートしています。このパラメーターはブール値で、デフォルトは false です。stream が true に設定されている場合にのみ有効になります。有効にすると、関数呼び出しの tool_call パラメーターの引数は、完全な生成が完了した後に一度に返されるのではなく、ストリームでインクリメンタルに返されます。
stream と tool_stream を組み合わせた場合の動作は次のとおりです:
|
stream |
tool_stream |
tool_call の返却方法 |
|
true |
true |
引数は複数のチャンクでインクリメンタルに返されます。 |
|
true |
false (デフォルト) |
引数は単一のチャンクで完全に返されます。 |
|
false |
true/false |
tool_stream は効果がありません。引数は完全な応答で一度に返されます。 |
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": "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}")
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: "Get the weather information for a specified city",
parameters: {
type: "object",
properties: {
city: { type: "string", description: "The name of the city" }
},
required: ["city"]
}
}
}
];
async function main() {
try {
const stream = await openai.chat.completions.create({
model: 'glm-5.2',
messages: [{ role: 'user', content: "What's the weather like in Beijing?" }],
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": "What's the weather like in Beijing?"
}
],
"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"]
}
}
}
],
"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": "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 = 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": "What's the weather like in Beijing?"
}
]
},
"parameters": {
"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"]
}
}
}
],
"tool_stream": true,
"incremental_output": true,
"result_format": "message"
}
}'
思考の労力 (reasoning_effort)
glm-5.2 と glm-5.1 は、デフォルトで思考モードが有効になっています。モデルはまず思考プロセス (reasoning_content) を出力し、その後に最終的な回答を提供します。reasoning_effort パラメーターを使用して、思考の労力を調整できます。値が大きいほど、より徹底的な思考が行われます。サポートされる値はモデルによって異なります。サポートされていない値を渡すと、invalid_parameter_error エラーが返されます。次の表から値を選択してください。
|
モデル |
reasoning_effort で利用可能な値 |
|
glm-5.2 |
|
|
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": "Which is larger, 9.9 or 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: "Which is larger, 9.9 or 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": "Which is larger, 9.9 or 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": "Which is larger, 9.9 or 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 機能を有効にするには、履歴のreasoning_contentをメッセージ内で完全、未変更、かつ元の順序で渡す必要があります。コンテンツの欠落、クリッピング、書き換え、または順序変更は、パフォーマンスの低下や機能の失敗を引き起こす可能性があります。
このパラメーターは、ターンをまたがる履歴の思考コンテンツにのみ影響し、現在のターンでモデルが思考コンテンツを生成または出力するかどうかは変更しません。
次の例では、同じマルチターンメッセージのセットを使用しており、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 を実際のワークスペース ID に置き換えてください。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
# assistant メッセージが reasoning_content (履歴の思考プロセス) を含むマルチターン対話
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: 履歴の reasoning_content を無視して、コンテキスト長とコストを削減
# false (デフォルト): 履歴の reasoning_content を保持 (Preserved Thinking)
"clear_thinking": True,
},
)
print(completion.usage.prompt_tokens) # 値は、true に設定した場合の方が false に設定した場合よりも小さくなります
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": "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?"}
],
"enable_thinking": true,
"clear_thinking": true
}'
DashScope
import os
from dashscope import Generation
# assistant メッセージが reasoning_content (履歴の思考プロセス) を含むマルチターン対話
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?"},
]
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.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.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 互換 - チャット」をご参照ください。
モデルと課金
GLM シリーズモデルは、Zhipu AI がエージェント向けに設計したハイブリッド推論モデルです。思考モードとノンシンキングモードの両方を提供します。
-
glm-5.2:コンテキスト長が 1M の最新の GLM モデルです。Function Calling、構造化出力、暗黙的キャッシュをサポートしています。OpenAI 互換、DashScope、および Anthropic 互換のインターフェイスを使用して呼び出すことができます。
モデルのコンテキスト長と価格に関する情報については、Model Studio コンソールをご参照ください。
課金は、入力トークンと出力トークンの数に基づきます。
思考モードでは、Chain-of-Thought は出力トークンとして課金されます。
エラーコード
エラーのトラブルシューティングについては、「エラーコード」をご参照ください。