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

Alibaba Cloud Model Studio:GLM-ZHIPU

最終更新日:Dec 02, 2026

本ドキュメントでは、Alibaba Cloud Model Studio で Z.AI モデル推論サービスを呼び出す方法について説明します。

注記本ドキュメントに記載されている機能は、シンガポールリージョンでのみ利用可能です。モデルを使用するには、シンガポールリージョンから呼び出してください。

重要Alibaba Cloud Model Studio は、中国(北京)、シンガポール、および中国(香港)リージョン向けにワークスペース固有のドメインをリリースしました。新しい専用ドメインは、推論リクエストに対して優れたパフォーマンスと高い安定性を提供します。新しいドメインへの移行を推奨します。

  • 中国(北京):https://dashscope.aliyuncs.com から https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com へ
  • シンガポール:https://dashscope-intl.aliyuncs.com から https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com へ
  • 中国(香港):https://cn-hongkong.dashscope.aliyuncs.com から https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com へ

{WorkspaceId}はワークスペースIDであり、Alibaba Cloud Model StudioコンソールのWorkspace Detailsページで確認できます。既存のドメインは引き続き完全に機能します。

サービスの有効化

  1. Model Studio コンソール に移動し、ZHIPU/GLM を検索して、Z.AI GLM-series テキストモデルカードを見つけ、「今すぐ有効化」をクリックします。
  2. ダイアログボックスで、有効化と承認を確認します。

これらの手順を完了すると、Z.AI の GLM モデルサービスを呼び出すことができます。

クイックスタート

ZHIPU/GLM-5.3 は GLM シリーズのモデルであり、1M のコンテキストをサポートしています。以下のコードを実行して、思考モードで ZHIPU/GLM-5.3 モデルを素早く呼び出してください。

API キーを取得 し、API キーを環境変数として設定 している必要があります。SDK を使用してモデルを呼び出す場合は、SDK をインストール する必要もあります。

OpenAI 互換性

注記enable_thinking パラメータは標準的な OpenAI のパラメータではありません。OpenAI Python SDK では、extra_body に渡します。Node.js SDK では、トップレベルのパラメータとして渡します。

Python

サンプルコード

from openai import OpenAI
import os

# Initialize the OpenAI client
client = OpenAI(
    # If the environment variable is not set, replace "sk-xxx" with your Alibaba Cloud Model Studio API Key.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    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="ZHIPU/GLM-5.3",
    messages=messages,
    # Enable thinking mode by setting enable_thinking in extra_body.
    # reasoning_effort controls the reasoning effort. Optional values: max (default), high, low.
    extra_body={"enable_thinking": True},
    reasoning_effort="max",
    stream=True,
    stream_options={
        "include_usage": True
    },
)

reasoning_content = ""  # Full reasoning process
answer_content = ""  # Full response
is_answering = False  # Tracks if the model is in the answering phase
print("\n" + "=" * 20 + " Reasoning 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

    # Collect only the reasoning content
    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

    # When content is received, start generating the response
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + " Full Response " + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

レスポンス

==================== Reasoning Process ====================

Let me carefully consider the user's question. It seems simple, but it is actually quite profound.

From a linguistic perspective, the user is using English, which means I should respond in English. This is a fundamental self-introduction question, but it may have multiple layers of meaning.

First, I need to be clear that as a language model, I should honestly state my identity and nature. I am not a human, nor do I possess true emotions or consciousness. I am an AI assistant trained with deep learning technology. This is a basic fact.

Second, considering the user's potential needs, they might want to know:
1. What services can I provide?
2. What are my areas of expertise?
3. What are my limitations?
4. How can they interact with me more effectively?

In my answer, I should express a friendly and open attitude while maintaining professionalism and accuracy. I should state my main areas of expertise, such as knowledge Q&A, writing assistance, and creative support, while also frankly pointing out my limitations, such as the lack of real emotional experience.

Furthermore, to make the answer more complete, I should also express a positive attitude and willingness to help users solve problems. I can guide the user to ask more specific questions to better showcase my abilities.

Considering this is an open-ended opening, the answer should be concise and clear, yet contain enough information to give the user a clear understanding of my basic situation and lay a good foundation for subsequent conversations.

Finally, the tone should remain humble and professional, neither too technical nor too casual, to make the user feel comfortable and natural.
==================== Full Response ====================

I am a GLM large language model trained by ZHIPU AI, designed to provide users with information and help solve problems. I am designed to understand and generate human language, and I can answer questions, provide explanations, or participate in discussions on various topics.

I do not store your personal data, and our conversations are anonymous. Is there any topic I can help you understand or explore?
==================== 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';

// Initialize the OpenAI client
const openai = new OpenAI({
    // If the environment variable is not set, replace "sk-xxx" with your Alibaba Cloud Model Studio API Key.
    apiKey: process.env.DASHSCOPE_API_KEY,
    // Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});

let reasoningContent = ''; // Full reasoning process
let answerContent = ''; // Full response
let isAnswering = false; // Tracks if the model is in the answering phase

async function main() {
    try {
        const messages = [{ role: 'user', content: 'Who are you?' }];

        const stream = await openai.chat.completions.create({
            model: 'ZHIPU/GLM-5.3',
            messages,
            // Note: In the Node.js SDK, non-standard parameters like enable_thinking are passed as top-level properties, not within extra_body.
            enable_thinking: true,
            // reasoning_effort controls the reasoning effort. Optional values: max (default), high, low.
            reasoning_effort: 'max',
            stream: true,
            stream_options: {
                include_usage: true
            },
        });

        console.log('\n' + '='.repeat(20) + ' Reasoning 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;

            // Collect only the reasoning content
            if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
                if (!isAnswering) {
                    process.stdout.write(delta.reasoning_content);
                }
                reasoningContent += delta.reasoning_content;
            }

            // When content is received, start generating the response
            if (delta.content !== undefined && delta.content) {
                if (!isAnswering) {
                    console.log('\n' + '='.repeat(20) + ' Full Response ' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();

レスポンス

==================== Reasoning Process ====================

Let me carefully consider the user's question, "Who are you?" This requires analysis and a response from multiple perspectives.

First, this is a basic identity question. As a GLM large language model, I need to accurately state my identity. I should clearly state that I am an AI assistant developed by ZHIPU AI.

Second, I need to consider the user's possible intentions. They might be first-time users wanting to understand basic functions, or they might want to confirm if I can provide specific help, or they might just be testing my response style. Therefore, I need to give an open and friendly answer.

I also need to consider the completeness of the answer. In addition to introducing my identity, I should briefly explain my main functions, such as Q&A, content creation, and analysis, so the user knows how to use this assistant.

Finally, I need to ensure a friendly and approachable tone, expressing a willingness to help. I can use expressions like "I'm happy to help" to make the user feel the warmth of the interaction.

Based on these considerations, I can craft a concise and clear answer that both addresses the user's question and guides future interaction.
==================== Full Response ====================

I am GLM, a large language model trained by ZHIPU AI. Trained on massive text data, I can understand and generate human language to help users answer questions, provide information, and engage in conversations.

I am continuously learning and improving to provide better services. I'm happy to answer your questions or provide assistance! What can I do for you?
==================== Token Usage ====================

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

HTTP

サンプルコード

curl

# Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
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": "ZHIPU/GLM-5.3",
    "messages": [
        {
            "role": "user",
            "content": "Who are you?"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "enable_thinking": true,
    "reasoning_effort": "max"
}'

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

ZHIPU/GLM-5.3、ZHIPU/GLM-5.2 の各モデルは tool_stream パラメータをサポートしています。このパラメータはブール値で、デフォルトは false であり、stream が true の場合にのみ機能します。有効にすると、Function calling の tool_call パラメータの arguments がストリームとして増分的に返されます。

stream パラメータと tool_stream パラメータは、以下のように連動します。

stream

tool_stream

tool_calltool_callの返し方

true

true

arguments が複数のチャンクに分割されて増分的に返されます。

true

false(デフォルト)

arguments は単一のチャンクで完全に返されます。

false

true/false

tool_stream は効果がありません。arguments は完全なレスポンス内で一度にすべて返されます。

OpenAI 互換

Python

サンプルコード

from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get 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 is the weather like in Beijing"}]

completion = client.chat.completions.create(
    model="ZHIPU/GLM-5.3",
    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,
    // Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
    baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});

const tools = [
    {
        type: "function",
        "function": {
            name: "get_weather",
            description: "Get 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: 'ZHIPU/GLM-5.3',
            messages: [{ role: 'user', content: 'What is 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();

curl

# Singapore region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region.
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": "ZHIPU/GLM-5.3",
    "messages": [
        {
            "role": "user",
            "content": "What is the weather like in Beijing"
        }
    ],
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get 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
}'

思考制御(thinking.type および reasoning_effort)

ZHIPU/GLM-5.3 は常に思考モードで実行され、思考の無効化はサポートされていません。thinking.type を enabled に設定したままにする(または enable_thinking を true に設定したままにする)ことで、reasoning_effort を使用して推論の深さを制御してください。

パラメーター

説明

サポートされている値

thinking.type

思考を有効にするかどうかを制御します。デフォルト値は enabled です。ZHIPU/GLM-5.3 は disabled をサポートしなくなりました。disabled を渡すと API リクエストが失敗します。

enabled

reasoning_effort

モデルの推論の深さを制御します。このパラメータが指定されていない場合、デフォルト値は max です。max を使用することを推奨します。

  • max(デフォルト):深層推論

  • high:強化推論

  • low:軽量推論

過去の推論内容のクリア(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 互換

from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following is the URL for the Singapore region. Replace {WorkspaceId} with your Model Studio workspace ID. URLs differ by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

# Multi-turn conversation. The assistant messages carry reasoning_content (historical reasoning process).
messages = [
    {"role": "user", "content": "What is 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="ZHIPU/GLM-5.3",
    messages=messages,
    extra_body={
    "thinking": {
        "type": "enabled",
        "clear_thinking": False  # False = retain reasoning content
      }
  }
)
print(completion.usage.prompt_tokens)  # Lower with true than with false
# The following is the URL for the Singapore region. Replace {WorkspaceId} with your Model Studio workspace ID. URLs differ by region.
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": "ZHIPU/GLM-5.3",
    "messages": [
        {"role": "user", "content": "What is 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?"}
    ],
    "thinking": {
        "type": "enabled",
        "clear_thinking": false
    }
}'

構造化出力

構造化出力(JSON モード)は、モデルが標準形式の JSON 文字列を返すことを保証し、プログラムから直接解析できます。情報抽出や構造化データ生成などのシナリオに適しています。

ZHIPU/GLM-5.3 は構造化出力をサポートしています。ZHIPU/GLM-5.2 は非思考モードでのみサポートしており、呼び出し時に enable_thinking を false に設定する必要があります。

ZHIPU/GLM シリーズは JSON Object モードのみをサポートしています。response_format を {"type": "json_object"} に設定すると、モデルは有効な JSON 出力を保証しますが、指定された構造に厳密に従うことは保証しません。JSON Schema モード(json_schema)はサポートされていません。2 つのモードの違いについては、構造化出力をご参照ください。

以下の例では感情分析を行い、System Message で期待する JSON 構造を定義し、response_format で JSON モードを有効にします。構造を指定しない場合、有効な JSON 出力のみが保証されます。

OpenAI 互換

from openai import OpenAI
import os
import json

client = OpenAI(
    # If the environment variable is not configured, replace with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following is the URL for the Singapore region. Replace {WorkspaceId} with your Model Studio workspace ID. URLs differ by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="ZHIPU/GLM-5.3",
    messages=[
        {
            "role": "system",
            "content": """You are a sentiment analysis expert. Return the analysis result in the following JSON format:
{
    "sentiment": "positive/negative/neutral",
    "confidence": 0.95,
    "emotions": ["joy", "excitement"],
    "keywords": ["weather", "mood"],
    "analysis": "detailed analysis"
}"""
        },
        {
            "role": "user",
            "content": "Analyze the sentiment of this sentence: 'The weather is great today, and I feel happy!'"
        }
    ],
    response_format={"type": "json_object"}
)

result = json.loads(completion.choices[0].message.content)
print(f"Sentiment: {result['sentiment']}")
print(f"Confidence: {result['confidence']}")
print(f"Emotions: {result['emotions']}")
# The following is the URL for the Singapore region. Replace {WorkspaceId} with your Model Studio workspace ID. URLs differ by region.
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": "ZHIPU/GLM-5.3",
    "messages": [
        {
            "role": "system",
            "content": "You are a sentiment analysis expert. Return the analysis result in the following JSON format: {\"sentiment\": \"positive/negative/neutral\", \"confidence\": 0.95, \"emotions\": [\"joy\", \"excitement\"], \"keywords\": [\"weather\", \"mood\"], \"analysis\": \"detailed analysis\"}"
        },
        {
            "role": "user",
            "content": "Analyze the sentiment of this sentence: 'The weather is great today, and I feel happy!'"
        }
    ],
    "response_format": {"type": "json_object"}
}'

JSON Schema による検証

JSON Object モードは、出力が指定された構造に厳密に準拠することを保証しません。クライアント側で jsonschema ライブラリ(pip install jsonschema)を使用して結果を検証できます。スキーマをプロンプトに含め、呼び出し後に解析結果を検証します。検証に失敗すると例外がスローされるため、再試行やフォールバックのトリガーとして利用できます。

from openai import OpenAI
import os
import json
from jsonschema import validate

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following is the URL for the Singapore region. Replace {WorkspaceId} with your Model Studio workspace ID. URLs differ by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

schema = {
    "type": "object",
    "properties": {
        "sentiment": {"type": "string", "enum": ["positive", "negative", "neutral"]},
        "confidence": {"type": "number", "minimum": 0, "maximum": 1},
        "emotions": {"type": "array", "items": {"type": "string"}}
    },
    "required": ["sentiment", "confidence"]
}

completion = client.chat.completions.create(
    model="ZHIPU/GLM-5.3",
    messages=[
        {
            "role": "system",
            "content": f"Return the sentiment analysis result according to the following JSON Schema: {json.dumps(schema, ensure_ascii=False)}"
        },
        {
            "role": "user",
            "content": "Analyze the sentiment of this sentence: 'The weather is great today, and I feel happy!'"
        }
    ],
    response_format={"type": "json_object"}
)

result = json.loads(completion.choices[0].message.content)
validate(instance=result, schema=schema)  # Raises ValidationError if validation fails
print(result)

情報抽出の例

以下の例は、テキストから連絡先情報を抽出し、ネストされた配列構造の指定方法を示します。入力テキストの品質と形式は抽出結果に影響します。

from openai import OpenAI
import os
import json

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following is the URL for the Singapore region. Replace {WorkspaceId} with your Model Studio workspace ID. URLs differ by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

schema = {
    "type": "object",
    "properties": {
        "contacts": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "phone": {"type": "string"},
                    "email": {"type": "string"},
                    "company": {"type": "string"},
                    "position": {"type": "string"}
                },
                "required": ["name"]
            }
        },
        "total_count": {"type": "integer"}
    },
    "required": ["contacts", "total_count"]
}

text = """Alice Brown, mobile: +1-555-0100, email: alice@example.com, Technical Director at Example Technology Co., Ltd.
Bob Smith, phone: +1-555-0101, work email: bob@example.com, Product Manager at Example Innovation Inc."""

completion = client.chat.completions.create(
    model="ZHIPU/GLM-5.3",
    messages=[
        {
            "role": "system",
            "content": f"""You are an information extraction expert. Extract all contact information from the text and return it in the following JSON format:
{json.dumps(schema, ensure_ascii=False)}

Notes:
- If a field has no information, do not include it
- The phone field should be a standardized phone number
- The email field should be a valid email address"""
        },
        {
            "role": "user",
            "content": f"Extract the contact information from the following text:\n\n{text}"
        }
    ],
    response_format={"type": "json_object"}
)

result = json.loads(completion.choices[0].message.content)
print(f"Extracted {result['total_count']} contacts")
for contact in result["contacts"]:
    print(f"Name: {contact['name']}")
    if "phone" in contact:
        print(f"Phone: {contact['phone']}")

ベストプラクティス

  • スキーマ設計:フィールド名と型を明確にし、必要な検証ルールを含め、将来の拡張を考慮します。単純な構造から始めて徐々に複雑さを増し、主要フィールドには詳細な説明と例を提供します。
  • エラー処理:スキーマ検証とビジネスロジック検証を組み合わせ、簡略化したフォールバックスキーマを用意し、詳細なエラー情報をログに記録します。
  • 出力の自然さ:JSON モードはモデルに形式の厳密な遵守を求めるため、複雑なシナリオでは応答の自然さに影響する場合があります。機能性とユーザー体験のバランスを取ってください。

その他の機能

モデル

マルチターン会話

Function calling

構造化出力

インターネット検索

プレフィックス補完

コンテキストキャッシュ

推論強度の制御

ZHIPU/GLM-5.3

サポート済み

サポート済み

サポート済み

未サポート

サポート済み

サポート済み

サポート済み

reasoning_effort

ZHIPU/GLM-5.2

サポート済み

サポート済み

サポート済み

非思考モードのみ

未サポート

サポート済み

サポート済み

サポート済み

reasoning_effort

コンテキストキャッシュは暗黙的キャッシュを使用し、デフォルトで有効になっています。これは Alibaba Cloud Model Studio の 暗黙的キャッシュ サービスと以下の点で異なります。

  • キャッシュされるトークンの最小数は 512 で、Model Studio の 1024 と異なります。

デフォルトパラメータ値

モデル

enable_thinking

temperature

top_p

top_k

repetition_penalty

ZHIPU/GLM-5.3

true(無効化不可)

1.0

0.95

-

-

ZHIPU/GLM-5.2

true

1.0

0.95

-

-

ハイフン(-)は、パラメータにデフォルト値がなく、サポートされていないことを示します。

モデル一覧と課金

GLM シリーズのモデルは Z.AI のハイブリッド推論モデルです。これらはインテリジェントエージェント向けに設計されており、思考モードと非思考モードの2つのモードを提供します。ZHIPU/GLM-5.3 は思考モードのみをサポートしています。

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

課金はモデルの入力トークンと出力トークンに基づきます。

思考モードでは、思考連鎖は出力トークンに基づいて課金されます。

エラーコード

エラーが発生した場合は、エラーコードを参照して問題を解決してください。

以下は Z.AI 固有のサービスエラーコードです。HTTP エラーコードは Model Studio の一般的なエラーコードと同じです。上記のリンクを参照してください。

エラーカテゴリ

エラーコード

エラーメッセージ

基本エラー

500

内部エラー

認証エラー

1000

認証に失敗しました

1001

ヘッダーで Authentication パラメータが受信されませんでした。認証を実行できません。

1002

認証トークンが無効です。認証トークンが正しく渡されていることを確認してください。

1003

認証トークンの有効期限が切れています。再生成するか、新しいトークンを取得してください。

1004

認証トークンの検証に失敗しました。

1100

アカウント読み取り/書き込み

アカウントエラー

1110

アカウントが非アクティブです。アカウント情報を確認してください。

1111

アカウントが存在しません。

1112

アカウントがロックされています。ロックを解除するにはカスタマーサービスにお問い合わせください。

1113

アカウントの残高が不足しています。アカウントに入金してから再試行してください。

1120

アカウントにアクセスできません。後でもう一度お試しください。

1121

ポリシー違反によりアカウントがロックされました。

API呼び出しエラー

1200

API呼び出しエラー

1210

API呼び出しパラメータが無効です。ドキュメントを確認してください。

1211

モデルが存在しません。モデルコードを確認してください。

1212

現在のモデルは ${method} 呼び出し方式をサポートしていません。

1213

${field} パラメータが受信されませんでした。

1214

${field} パラメータが無効です。ドキュメントを確認してください。

1215

${field1} と ${field2} を同時に設定することはできません。ドキュメントを確認してください。

1220

${API_name} にアクセスする権限がありません。

1221

API ${API_name} は利用できなくなりました。

1222

API ${API_name} は存在しません。

1230

API呼び出しプロセスエラー。

1231

すでにリクエストが存在します:${request_id}

1234

ネットワークエラー。エラー ID:${error_id}。カスタマーサービスにお問い合わせください。

1261

プロンプトが長すぎます。

APIポリシーブロックエラー

1300

API呼び出しがポリシーによってブロックされました。

1301

システムが入力または出力に潜在的に安全でない、あるいは機微なコンテンツを検出しました。機微なコンテンツを生成する可能性のあるプロンプトの使用は避けてください。ご協力ありがとうございます。

1302

この API の同時実行数が高すぎます。同時実行数を減らすか、カスタマーサービスに連絡して上限を引き上げてください。

1303

この API のリクエストレートが高すぎます。リクエストレートを下げるか、カスタマーサービスに連絡して上限を引き上げてください。

1304

この API の日次呼び出し上限に達しました。上限を引き上げるには、カスタマーサービスにお問い合わせください。

1305

このAPIのトラフィック制限に達しました。

1308

${number} ${unit} の使用量上限に達しました。上限は ${next_flush_time} にリセットされます。

1309

お客様の GLM Coding Plan は有効期限切れのため利用できません。サービスを復旧するには、https://bigmodel.cn/claude-code でプランを更新してください。

1310

週間または月間の使用量上限に達しました。上限は ${next_flush_time} にリセットされます。

1311

現在のご契約プランには ${model_name} へのアクセスが含まれていません。

1312

このモデルはトラフィックが集中しています。後でもう一度お試しいただくか、${model_name} などの別のモデルに切り替えてください。

1313

アカウントの使用状況がフェアユースポリシーに違反しており、リクエストレートが制限されています。詳細については、「利用規約 - サブスクリプションおよび自動更新契約」を参照してください。フルアクセスを復旧するには、パーソナルセンター > プログラミングプラン概要 に移動し、制限解除を申請してください。