すべてのプロダクト
Search
ドキュメントセンター

Alibaba Cloud Model Studio:GLM

最終更新日:Oct 30, 2026

このトピックでは、Alibaba Cloud Model Studio プラットフォームで API を使用して GLM シリーズモデルを呼び出す方法について説明します。

サービスエンドポイント

サービスエンドポイントはリージョンによって異なります。選択したリージョンに対応するベース URL を設定してください。

OpenAI 互換

中国 (北京)

SDK 呼び出しの base_url は次のとおりです: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1

HTTP リクエストエンドポイント: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions

米国 (バージニア)

SDK 呼び出しの base_url は次のとおりです: https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1

HTTP リクエストエンドポイント: POST https://{WorkspaceId}.us-east-1.maas.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

中国 (香港)

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

シンガポール

タブ本文

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

OpenAI 互換 - Responses API

注記現在、Responses API は glm-5.2 のみをサポートしており、中国 (北京) およびシンガポールリージョンでのみ利用可能です。

シンガポール

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/responses

中国 (北京)

SDK 呼び出しの base_url: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1

HTTP エンドポイント: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses

DashScope

中国 (北京)

HTTP リクエストエンドポイント: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation

SDK 呼び出しの base_url は次のとおりです:

Python

import dashscope

client = dashscope.Client(workspace="{WorkspaceId}", region="cn-beijing")

Java

  • 方法 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1");
  • 方法 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";

米国 (バージニア)

HTTP リクエストエンドポイント: POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation

SDK 呼び出しの base_url は次のとおりです:

Python

import dashscope

client = dashscope.Client(workspace="{WorkspaceId}", region="us-east-1")

Java

  • 方法 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1");
  • 方法 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1";

ドイツ (フランクフルト)

HTTP リクエストエンドポイント: POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation

SDK 呼び出しの base_url は次のとおりです:

Python

import dashscope

client = dashscope.Client(workspace="{WorkspaceId}", region="eu-central-1")

Java

  • 方法 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

SDK 呼び出しの base_url は次のとおりです:

Python

import dashscope

client = dashscope.Client(workspace="{WorkspaceId}", region="cn-hongkong")

Java

  • 方法 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 呼び出しの region は次のとおりです: dashscope.Client(workspace="{WorkspaceId}", region="ap-southeast-1")

{WorkspaceId} を実際のワークスペース ID に置き換えてください。

はじめに

glm-5.2 と glm-5.2-fast-preview は、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": "Who are you?"}]
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 + "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

    # 思考コンテンツのみを収集
    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 + "Complete response" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

応答

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

ユーザーの質問を慎重に検討してみましょう。単純に見えますが、実際には奥が深いです。

言語学的な観点から、ユーザーは中国語を使用しているため、中国語で応答する必要があります。これは基本的な自己紹介の質問ですが、複数の意味合いを持つ可能性があります。

まず、言語モデルとして、自分のアイデンティティと性質を正直に述べる必要があることを明確にする必要があります。私は人間ではなく、本当の感情的な認識もありません。私はディープラーニング技術でトレーニングされた AI アシスタントです。これが最も基本的な事実です。

次に、ユーザーの潜在的なシナリオを考慮すると、彼らは次のことを知りたいかもしれません:
1. どのようなサービスを提供できますか?
2. 私の専門分野は何ですか?
3. 私の限界は何ですか?
4. どうすれば私とより良く対話できますか?

私の回答では、プロフェッショナルで正確でありながら、フレンドリーでオープンな態度を表現する必要があります。知識 Q&A、執筆支援、クリエイティブサポートなどの主要な専門分野を述べ、同時に、本当の感情体験の欠如などの限界も率直に指摘する必要があります。

さらに、回答をより完全にするために、ユーザーが問題を解決するのを手伝いたいという前向きな態度も表現する必要があります。私の能力をより良く示すために、ユーザーがより具体的な質問をするように適切に誘導することができます。

これはオープンエンドの始まりであることを考慮すると、回答は簡潔で有益であるべきで、ユーザーに私の基本的な状況を明確に理解させ、その後の会話のための良い基盤を築くべきです。

最後に、トーンは謙虚でプロフェッショナルであるべきで、技術的すぎず、カジュアルすぎず、ユーザーが快適で自然に感じるようにする必要があります。
====================Complete response====================

私は Zhipu AI によってトレーニングされた GLM 大規模言語モデルで、ユーザーに情報を提供し、問題解決を支援するために設計されています。私は人間の言語を理解し生成するように設計されており、質問に答えたり、説明を提供したり、さまざまなトピックに関する議論に参加したりできます。

私はあなたの個人データを保存せず、私たちの会話は匿名です。私が理解したり議論したりするのを手伝えるトピックはありますか?
====================Token usage====================

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: 'Who are you?' }];

        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) + 'Thinking process' + '='.repeat(20) + '\n');

        for await (const chunk of stream) {
            if (!chunk.choices?.length) {
                console.log('\n' + '='.repeat(20) + 'Token usage' + '='.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) + 'Complete response' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();

応答

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

ユーザーの質問「あなたは誰ですか?」について慎重に考えてみましょう。これは複数の視点から分析し、回答する必要があります。

まず、これは基本的なアイデンティティに関する質問です。GLM 大規模言語モデルとして、私は自分のアイデンティティを正確に表現する必要があります。私は Zhipu AI によって開発された AI アシスタントであることを明確に述べるべきです。

次に、この質問をするユーザーの意図を考慮する必要があります。初めてのユーザーで、私の基本的な機能を知りたいのかもしれませんし、特定の助けを提供できるか確認したいのかもしれませんし、単に私の応答スタイルを試しているだけかもしれません。したがって、オープンでフレンドリーな回答をする必要があります。

また、回答の完全性も考慮する必要があります。自分のアイデンティティを紹介するだけでなく、Q&A、作成、分析などの主要な機能も簡単に説明し、ユーザーがこのアシスタントの使い方を理解できるようにする必要があります。

最後に、フレンドリーで親しみやすいトーンを確保し、手伝う意欲を表現する必要があります。「喜んでお仕えします」のような表現を使って、ユーザーにコミュニケーションの温かさを感じさせることができます。

これらの考えに基づいて、ユーザーの質問に答えるだけでなく、その後のコミュニケーションを導く簡潔で明確な回答をまとめることができます。
====================Complete response====================

私は GLM、Zhipu AI によってトレーニングされた大規模言語モデルです。私は膨大な量のテキストデータでトレーニングされ、人間の言語を理解し生成し、ユーザーが質問に答え、情報を提供し、会話に参加するのを助けます。

より良いサービスを提供するために、私は学習と改善を続けます。ご質問にお答えしたり、お手伝いできることを嬉しく思います!何かお手伝いできることはありますか?
====================Token usage====================

{ prompt_tokens: 7, completion_tokens: 248, total_tokens: 255 }

HTTP

サンプルコード

curl

# シンガポールリージョン。 {WorkspaceId} をお使いの Model Studio ワークスペース ID に置き換えてください。 URL はリージョンによって異なります。
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": "Who are you?"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "enable_thinking": true
}'

DashScope

Python

サンプルコード

import os
import dashscope

# 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください: api_key="sk-xxx"
client = dashscope.Client(api_key=os.getenv("DASHSCOPE_API_KEY"))

# リクエストパラメーターを初期化
messages = [{"role": "user", "content": "Who are you?"}]

completion = client.chat.completions.create(
    model="glm-5.2",
    messages=messages,
    enable_thinking=True,     # 思考モードを有効にする
    stream=True,              # ストリーミング出力を有効にする
)

reasoning_content = ""  # 完全な思考プロセス
answer_content = ""     # 完全な応答
is_answering = False    # 応答フェーズが開始されたかどうかを示します

print("\n" + "=" * 20 + "Thinking process" + "=" * 20 + "\n")

for chunk in completion:
    message = chunk.choices[0].delta
    # 思考コンテンツのみを収集
    if message.reasoning_content:
        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 + "Complete response" + "=" * 20 + "\n")
            is_answering = True
        print(message.content, end="", flush=True)
        answer_content += message.content

print("\n" + "=" * 20 + "Token usage" + "=" * 20 + "\n")
print(chunk.usage)

応答

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

ユーザーの質問「あなたは誰ですか?」を慎重に検討してみましょう。まず、ユーザーの意図を分析する必要があります。これは初めてのユーザーの好奇心からくるものかもしれませんし、私の特定の機能や能力を理解したいのかもしれません。

専門的な観点から、私は自分のアイデンティティを明確に述べるべきです - GLM 大規模言語モデルとして、私は自分の基本的な位置づけと主な機能を説明する必要があります。過度に技術的な説明は避け、分かりやすい言葉を使うべきです。

同時に、プライバシー保護やデータセキュリティなど、ユーザーが懸念する可能性のある実際的な問題も考慮する必要があります。これらは、ユーザーが AI サービスを使用する際に非常に懸念する点です。

さらに、プロフェッショナリズムとフレンドリーさを示すために、紹介の後に積極的に会話を導き、ユーザーが特定の助けを必要としているかどうかを尋ねることができます。これは、ユーザーが私をより良く理解するのに役立つだけでなく、その後の会話の道筋をつけることにもなります。

最後に、回答が簡潔で明確であり、要点が強調されていることを確認する必要があります。これにより、ユーザーは私のアイデンティティと目的を迅速に理解できます。このような回答は、ユーザーの好奇心を満たすと同時に、プロフェッショナリズムとサービス指向の態度を示すことができます。
====================Complete response====================

私は Zhipu AI によって開発された GLM 大規模言語モデルで、自然言語処理技術を通じてユーザーに情報を提供し、支援するために設計されています。私は膨大な量のテキストデータでトレーニングされており、人間の言語を理解し生成し、質問に答え、知識をサポートし、会話に参加することができます。

私の設計目標は、ユーザーのプライバシーとデータセキュリティを確保しながら、役立つ AI アシスタントになることです。私はユーザーの個人情報を保存せず、より良いサービスを提供するために学習と改善を続けます。

お答えできる質問や、お手伝いできるタスクはありますか?
====================Token usage====================

{"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("====================Thinking process====================");
                isFirstPrint = false;
            }
            System.out.print(reasoning);
        }
        if (content != null && !content.isEmpty()) {
            finalContent.append(content);
            if (!isFirstPrint) {
                System.out.println("\n====================Complete response====================");
                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("Who are you?").build();
            streamCallWithMessage(gen, userMsg);
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("An exception occurred: " + e.getMessage());
        }
    }
}

応答

====================Thinking process====================
ユーザーの質問にどう答えるか考えてみましょう。まず、これはアイデンティティに関する単純な質問であり、明確で直接的な回答が必要です。

大規模言語モデルとして、私は自分の基本的なアイデンティティ情報を正確に述べるべきです。これには以下が含まれます:
- 名前:GLM
- 開発者:Zhipu AI
- 主な機能:言語の理解と生成

ユーザーの質問が初めての対話から来ている可能性があることを考慮すると、過度に専門的な用語を避け、分かりやすい方法で自己紹介する必要があります。同時に、ユーザーが私とどのように対話するかをより良く理解できるように、私の主な能力も簡単に説明すべきです。

また、フレンドリーでオープンな態度を表現し、ユーザーがさまざまな質問をすることを歓迎することで、その後の会話の良い基盤を築くことができます。ただし、紹介は簡潔で、過度に詳細にならないようにし、ユーザーに情報過多の負担をかけないようにする必要があります。

最後に、さらなるコミュニケーションを促進するために、ユーザーが特定の助けを必要としているかどうかを積極的に尋ねることで、ユーザーの実際のニーズにより良く応えることができます。
====================Complete response====================
私は GLM、Zhipu AI によって開発された大規模言語モデルです。私は膨大な量のテキストデータでトレーニングされており、人間の言語を理解し生成し、質問に答え、情報を提供し、会話に参加することができます。

私の設計目的は、ユーザーが問題を解決し、知識を提供し、さまざまな言語タスクをサポートすることです。より正確で有用な回答を提供するために、継続的に学習し、更新していきます。

お答えできる質問や、一緒に議論できることはありますか?

HTTP

サンプルコード

curl

# シンガポールリージョン。 {WorkspaceId} をお使いの Model Studio ワークスペース ID に置き換えてください。 URL はリージョンによって異なります。
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": "Who are you?"
            }
        ]
    },
    "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": "Who are you?"}
    ],
    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

# シンガポールリージョン。{WorkspaceId} をお使いの Bailian ワークスペース ID に置き換えてください。URL はリージョンによって異なります。
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": "Who are you?"
        }
    ]
}'

ストリーミングツール呼び出し

glm-5.2、glm-5.2-fast-preview、glm-5.1、glm-5 は、tool_stream パラメーターをサポートしています。このパラメーターは、デフォルトで false となるブール値で、stream が true に設定されている場合にのみ有効になります。有効にすると、Function Calling の tool_call パラメーターの引数は、完全な生成が完了した後に一度にすべて返されるのではなく、ストリームで増分的に返されます。

stream と tool_stream の組み合わせの動作は次のとおりです:

stream

tool_stream

tool_call の返却方法

true

true

引数は複数のチャンクで増分的に返されます。

true

false (デフォルト)

引数は 1 つのチャンクで完全に返されます。

false

true/false

tool_stream は効果がありません。引数は完全な応答で一度に返されます。

OpenAI 互換

Python

サンプルコード

from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # シンガポールリージョン。 {WorkspaceId} をお使いの Model Studio ワークスペース ID に置き換えてください。 URL はリージョンによって異なります。
    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,
    // シンガポールリージョン。 {WorkspaceId} をお使いの Model Studio ワークスペース ID に置き換えてください。 URL はリージョンによって異なります。
    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

# シンガポールリージョン。 {WorkspaceId} をお使いの Model Studio ワークスペース ID に置き換えてください。 URL はリージョンによって異なります。
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
import dashscope

client = dashscope.Client(api_key=os.getenv("DASHSCOPE_API_KEY"))

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",
    messages=messages,
    tools=tools,
    stream=True,
    parameters={"tool_stream": True},
)

for chunk in completion:
    msg = chunk.choices[0].delta
    if msg.content:
        print(f"[content] {msg.content}")
    if msg.tool_calls:
        for tc in msg.tool_calls:
            print(f"[tool_call] id={tc.id or ''}, name={tc.function.name}, args={tc.function.arguments}")
    finish = chunk.choices[0].finish_reason
    if finish and finish != "null":
        print(f"[finish_reason] {finish}")

HTTP

サンプルコード

curl

# シンガポールリージョン。 {WorkspaceId} をお使いの Model Studio ワークスペース ID に置き換えてください。 URL はリージョンによって異なります。
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

none (推論なし、reasoning_tokens=0)、minimal、low、medium、high、xhigh、max (最高)

glm-5.2-fast-preview

none (推論なし、reasoning_tokens=0)、minimal、low、medium、high、xhigh、max (最高)

glm-5.1

none、minimal、low、medium、high、xhigh (最高、max は非サポート)

注記思考モードを無効にするには、OpenAI 互換または DashScope モードで enable_thinking パラメーターを false に設定します。このパラメーターは reasoning_effort よりも優先度が高いです。

注記Anthropic 互換モードは reasoning_effort パラメーターをサポートしていません。思考コンテンツを取得するには、ネイティブの Anthropic thinking パラメーターを使用します: {"thinking":{"type":"enabled","budget_tokens":1024}}。有効にすると、応答の content には、type が thinking に設定された思考ブロックが含まれます。

OpenAI 互換

from openai import OpenAI
import os
client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # シンガポールリージョン。 {WorkspaceId} をお使いの Model Studio ワークスペース ID に置き換えてください。 URL はリージョンによって異なります。
    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)
import OpenAI from "openai";
const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // シンガポールリージョン。 {WorkspaceId} をお使いの Model Studio ワークスペース ID に置き換えてください。 URL はリージョンによって異なります。
    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);
# シンガポールリージョン。 {WorkspaceId} をお使いの Model Studio ワークスペース ID に置き換えてください。 URL はリージョンによって異なります。
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
import dashscope

client = dashscope.Client(api_key=os.getenv("DASHSCOPE_API_KEY"))
response = client.chat.completions.create(
    model="glm-5.2",
    messages=[{"role": "user", "content": "9.9 と 9.11 ではどちらが大きいですか?"}],
    parameters={"reasoning_effort": "high"},
)
print(response.choices[0].message.content)

思考履歴のクリア (clear_thinking)

clear_thinking パラメーターは、マルチターン対話における前のターンの reasoning_content (思考プロセス) をコンテキストとしてモデルに渡すかどうかを制御します。このパラメーターは GLM シリーズモデルでのみサポートされています。

  • true:前のターンの reasoning_content を無視します。表示されるテキスト、ツール呼び出し、結果などの非推論コンテンツのみがコンテキスト入力として使用されます。これにより、コンテキスト長とコストが削減されます。
  • false (デフォルト):前のターンの reasoning_content を保持し、コンテキストとともにモデルに提供します。思考の維持を有効にするには、過去の reasoning_content をメッセージ内で完全、未変更、かつ元の順序で渡す必要があります。コンテンツの欠落、切り取り、書き換え、または順序変更を行うと、パフォーマンスが低下したり、機能が失敗したりする可能性があります。

注記このパラメーターは、ターン間の過去の思考コンテンツにのみ影響し、現在のターンでモデルが思考コンテンツを生成または出力するかどうかは変更しません。

次の例では、同じマルチターンメッセージのセットを使用しており、assistant メッセージには reasoning_content が含まれています。clear_thinking が true に設定されている場合、過去の思考コンテンツはコンテキストに含まれません。したがって、prompt_tokens の数は、false (デフォルト) に設定されている場合よりも少なくなります。実際の値は、過去の reasoning_content の長さに依存します。

OpenAI 互換

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

# アシスタントメッセージが 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 を保持 (思考の維持)
        "clear_thinking": True,
    },
)
print(completion.usage.prompt_tokens)  # 値は true に設定すると false に設定した場合よりも小さくなります
# シンガポールリージョン。 {WorkspaceId} をお使いの Model Studio ワークスペース ID に置き換えてください。 URL はリージョンによって異なります。
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
import dashscope

client = dashscope.Client(api_key=os.getenv("DASHSCOPE_API_KEY"))

# アシスタントメッセージが 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 = client.chat.completions.create(
    model="glm-5.2",
    messages=messages,
    enable_thinking=True,
    # true: 過去の reasoning_content を無視してコンテキスト長とコストを削減
    # false (デフォルト): 過去の reasoning_content を保持 (思考の維持)
    parameters={"clear_thinking": True},
)
print(response.usage.input_tokens)

Responses API

glm-5.2 は、OpenAI 互換の Responses API を介した呼び出しをサポートしています。中国 (北京) およびシンガポールリージョンのみがサポートされています。エンドポイントについては、「サービスエンドポイント」をご参照ください。

Responses API を呼び出す際、tools パラメーターに web_search (Web 検索)、web_extractor (Web エクストラクター)、および code_interpreter (コードインタープリター) ツールを追加できます。

from openai import OpenAI
import os

client = OpenAI(
    # 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 次の URL はシンガポールリージョン用です。他のリージョンについては、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="こんにちは!一文で自己紹介してください。",
    # オプション: Web 検索、Web 抽出、Code Interpreter ツールを有効にする
    tools=[
        {"type": "web_search"},
        {"type": "web_extractor"},
        {"type": "code_interpreter"},
    ],
)

# モデルの応答を取得
print(response.output_text)
import OpenAI from "openai";

const openai = new OpenAI({
    // 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください: apiKey: "sk-xxx"
    apiKey: process.env.DASHSCOPE_API_KEY,
    // 次の URL はシンガポールリージョン用です。他のリージョンについては、https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1 を使用してください
    baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});

const response = await openai.responses.create({
    model: "glm-5.2",
    input: "こんにちは!一文で自己紹介してください。",
    // オプション: Web 検索、Web 抽出、Code Interpreter ツールを有効にする
    tools: [
        { type: "web_search" },
        { type: "web_extractor" },
        { type: "code_interpreter" },
    ],
});

// モデルの応答を取得
console.log(response.output_text);
# 次の URL はシンガポールリージョン用です。他のリージョンについては、https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses を使用してください
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "glm-5.2",
    "input": "こんにちは!一文で自己紹介してください。",
    "tools": [
        {"type": "web_search"},
        {"type": "web_extractor"},
        {"type": "code_interpreter"}
    ]
}'

その他の機能

モデル

マルチターン対話

Function Calling

構造化出力

Web 検索

部分モード

コンテキストキャッシュ

glm-5.2

サポート済み

サポート済み

サポート済み

ノンシンキングモードでのみ

非サポート

非サポート

サポート済み

暗黙的キャッシュのみサポート

glm-5.2-fast-preview

サポート済み

サポート済み

サポート済み

ノンシンキングモードでのみ

非サポート

非サポート

サポート済み

暗黙的キャッシュのみサポート

glm-5.1

サポート済み

サポート済み

サポート済み

ノンシンキングモードでのみ

非サポート

非サポート

サポート済み

明示的キャッシュと暗黙的キャッシュの両方をサポート

glm-5

サポート済み

サポート済み

サポート済み

ノンシンキングモードでのみ

非サポート

非サポート

サポート済み

暗黙的キャッシュのみサポート

デフォルトのパラメーター値

モデル

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

パラメーターの詳細については、「OpenAI 互換 - チャット」をご参照ください。

注意事項

警告クラウドにデプロイされたサードパーティのオープンソースモデル (glm-5.2 など) は、モデルの公式バージョンとはハイパーパラメーターの処理方法が異なります。公式バージョンはハイパーパラメーターにしきい値検証を行い、しきい値を超えるとデフォルト値にフォールバックします。クラウドデプロイバージョンは、ユーザーが提供したパラメーター値をしきい値検証なしで直接渡します。そのため、不適切なハイパーパラメーター設定 (repetition_penalty を 0.1 に設定するなど) は、予期しない出力 (繰り返し印刷など) を引き起こす可能性があります。サードパーティのオープンソースモデルには、デフォルトのハイパーパラメーター値 (上記のデフォルトパラメーター値の表を参照) を使用し、カスタムパラメーターを避けることを推奨します。

モデルを呼び出す際は、使用する API のパラメーターの型と必須フィールドの要件に従ってください。特に、以下の点に注意してください。

  • max_tokens には 1024 などの整数を指定し、ブール値 true は指定しないでください。glm-5.3 を呼び出す際に true を指定すると、1 として処理され、パラメーターエラーが返されることなく出力が 1 トークンで切り捨てられる場合があります。その結果、思考内容のみが出力され、最終回答が含まれない場合があります。
  • Anthropic 互換 API を使用する際は、tools 配列内の各ツールに "name": "get_weather" などの name を含める必要があります。name を省略するとリクエストが失敗します。リクエストを送信する前にツール名を指定してください。

モデルと課金

GLM シリーズモデルは、Zhipu AI がエージェント向けに設計したハイブリッド推論モデルです。思考モードとノンシンキングモードの両方を提供します。

  • glm-5.2:コンテキスト長が 1M のGLM モデルです。Function Calling、構造化出力、暗黙的キャッシュをサポートしています。OpenAI 互換、DashScope、および Anthropic 互換のインターフェイスを使用して呼び出すことができます。

モデルのコンテキスト長と価格については、Model Studio コンソールをご参照ください。

課金は、入力トークンと出力トークンの数に基づいています。

思考モードでは、Chain-of-Thought は出力トークンとして課金されます。

エラーコード

エラーが発生した場合は、「エラーコード」でトラブルシューティング情報をご参照ください。