DEV Community

Cover image for GLM-5.1 APIの使い方: コード例付き完全ガイド
Akira
Akira

Posted on • Originally published at apidog.com

GLM-5.1 APIの使い方: コード例付き完全ガイド

TL;DR (要約)

GLM-5.1は、BigModel API(https://open.bigmodel.cn/api/paas/v4/)を通じて利用可能です。APIはOpenAI互換で、エンドポイント、リクエスト形式、ストリーミングパターンが同じです。必要なのはBigModelアカウント、APIキー、モデル名glm-5.1です。本記事では、認証、リクエスト送信、ストリーミング、ツール呼び出し、そしてApidogを使った統合テストまで、実装手順を解説します。

Apidog を今すぐ試してみよう

GLM-5.1 API構成

はじめに

GLM-5.1はZ.AIのフラッグシップであるエージェントモデルで、2026年4月にリリースされました。SWE-Bench Proで1位を獲得し、主要なコーディングベンチマークも上回っています。AIコーディングアシスタントや自律型エージェント、長期タスク実行アプリを構築するなら、GLM-5.1の統合は非常に有用です。

OpenAI互換APIのため、既存GPT-4やClaudeプロジェクトはベースURLとモデル名をglm-5.1に変更するだけで移行できます。SDKやレスポンス形式の違いはありません。

💡 エージェントAPIの課題はテストです。複数のツール呼び出しやストリーミングをクォータ消費せず検証したい場合、Apidogのテストシナリオを活用してください。各状態のレスポンスをモックでき、本番移行前の検証が効率的に行えます。

前提条件

最初のAPIリクエストには以下が必要です。

  1. bigmodel.cn でのBigModelアカウント(無料登録可)
  2. BigModelコンソールから取得したAPIキー
  3. Python 3.8+ もしくは Node.js 18+(両方のコード例あり)
  4. OpenAI SDK または標準の requests/fetch(GLM-5.1はOpenAI API互換)

APIキーは必ず環境変数で指定しましょう。

export BIGMODEL_API_KEY="your_api_key_here"
Enter fullscreen mode Exit fullscreen mode

ソースコードにAPIキーをハードコードしないでください。

認証

全てのリクエストでAuthorizationヘッダーにBearerトークンが必要です。

Authorization: Bearer YOUR_API_KEY
Enter fullscreen mode Exit fullscreen mode

BigModel APIキーはxxxxxxxx.xxxxxxxxxxxxxxxxの形式です(sk-始まりではありませんが、挙動は同じです)。

ベースURL

https://open.bigmodel.cn/api/paas/v4/
Enter fullscreen mode Exit fullscreen mode

チャット補完エンドポイント:

POST https://open.bigmodel.cn/api/paas/v4/chat/completions
Enter fullscreen mode Exit fullscreen mode

最初のリクエスト

curlを使用する

curl https://open.bigmodel.cn/api/paas/v4/chat/completions \
  -H "Authorization: Bearer $BIGMODEL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "glm-5.1",
    "messages": [
      {
        "role": "user",
        "content": "Write a Python function that finds all prime numbers up to n using the Sieve of Eratosthenes."
      }
    ],
    "max_tokens": 1024,
    "temperature": 0.7
  }'
Enter fullscreen mode Exit fullscreen mode

Python (requestsライブラリ)

import os
import requests

api_key = os.environ["BIGMODEL_API_KEY"]

response = requests.post(
    "https://open.bigmodel.cn/api/paas/v4/chat/completions",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    },
    json={
        "model": "glm-5.1",
        "messages": [
            {
                "role": "user",
                "content": "Write a Python function that finds all prime numbers up to n using the Sieve of Eratosthenes."
            }
        ],
        "max_tokens": 1024,
        "temperature": 0.7
    }
)

result = response.json()
print(result["choices"][0]["message"]["content"])
Enter fullscreen mode Exit fullscreen mode

OpenAI SDKを使う(推奨)

OpenAI SDKはGLM-5.1にも使えます。ベースURLだけ変更します。

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["BIGMODEL_API_KEY"],
    base_url="https://open.bigmodel.cn/api/paas/v4/"
)

response = client.chat.completions.create(
    model="glm-5.1",
    messages=[
        {
            "role": "user",
            "content": "Write a Python function that finds all prime numbers up to n using the Sieve of Eratosthenes."
        }
    ],
    max_tokens=1024,
    temperature=0.7
)

print(response.choices[0].message.content)
Enter fullscreen mode Exit fullscreen mode

OpenAI SDKはリトライ・タイムアウト・レスポンス解析を自動化します。BigModelのベースURLを指定するだけで利用可能です。

レスポンス形式

レスポンス構造はOpenAIと同一です。

{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1744000000,
  "model": "glm-5.1",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "def sieve_of_eratosthenes(n):\n    ..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 32,
    "completion_tokens": 215,
    "total_tokens": 247
  }
}
Enter fullscreen mode Exit fullscreen mode

レスポンステキストは result["choices"][0]["message"]["content"] で取得できます。

usageはトークン消費量です。GLM-5.1はピーク時間帯(UTC+8 14:00〜18:00)でクォータ3倍消費なので、usageで消費量を管理してください。

ストリーミングレスポンス

長いコード生成タスクでは、ストリーミングでトークンが到着するたびに結果を受け取れます。

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["BIGMODEL_API_KEY"],
    base_url="https://open.bigmodel.cn/api/paas/v4/"
)

stream = client.chat.completions.create(
    model="glm-5.1",
    messages=[
        {
            "role": "user",
            "content": "Explain how a B-tree index works in a database, with a code example."
        }
    ],
    stream=True,
    max_tokens=2048
)

for chunk in stream:
    if chunk.choices[0].delta.content is not None:
        print(chunk.choices[0].delta.content, end="", flush=True)

print()
Enter fullscreen mode Exit fullscreen mode

各チャンクは新しいトークンのみを含みます。最後のチャンクのfinish_reason"stop"または"length"となります。

生のHTTPリクエストでのストリーミング

OpenAI SDKを使わない場合:

import os
import json
import requests

api_key = os.environ["BIGMODEL_API_KEY"]

response = requests.post(
    "https://open.bigmodel.cn/api/paas/v4/chat/completions",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    },
    json={
        "model": "glm-5.1",
        "messages": [{"role": "user", "content": "Write a merge sort in Python."}],
        "stream": True,
        "max_tokens": 1024
    },
    stream=True
)

for line in response.iter_lines():
    if line:
        line = line.decode("utf-8")
        if line.startswith("data: "):
            data = line[6:]
            if data == "[DONE]":
                break
            chunk = json.loads(data)
            delta = chunk["choices"][0]["delta"]
            if "content" in delta:
                print(delta["content"], end="", flush=True)
Enter fullscreen mode Exit fullscreen mode

ツール呼び出し

GLM-5.1はツール呼び出し(関数実行リクエスト)をサポートしています。これは外部APIやシステム連携の自動化に必須です。

ツールの定義

import os
import json
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["BIGMODEL_API_KEY"],
    base_url="https://open.bigmodel.cn/api/paas/v4/"
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "run_python",
            "description": "Execute Python code and return the output. Use this to test, profile, or benchmark code.",
            "parameters": {
                "type": "object",
                "properties": {
                    "code": {
                        "type": "string",
                        "description": "The Python code to execute"
                    }
                },
                "required": ["code"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "read_file",
            "description": "Read the contents of a file",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "File path to read"
                    }
                },
                "required": ["path"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="glm-5.1",
    messages=[
        {
            "role": "user",
            "content": "Write a function to compute Fibonacci numbers, test it for n=10, and show me the output."
        }
    ],
    tools=tools,
    tool_choice="auto"
)

message = response.choices[0].message
print(f"完了理由: {response.choices[0].finish_reason}")

if message.tool_calls:
    for tool_call in message.tool_calls:
        print(f"\n呼び出されたツール: {tool_call.function.name}")
        print(f"引数: {tool_call.function.arguments}")
Enter fullscreen mode Exit fullscreen mode

ツール呼び出しレスポンスの処理

GLM-5.1が関数実行をリクエストしたら、実際にその関数を呼び、結果をメッセージとして返します。

import subprocess

def execute_tool(tool_call):
    """ツールを実行し、結果を返します。"""
    name = tool_call.function.name
    args = json.loads(tool_call.function.arguments)

    if name == "run_python":
        result = subprocess.run(
            ["python3", "-c", args["code"]],
            capture_output=True,
            text=True,
            timeout=10
        )
        return result.stdout or result.stderr

    elif name == "read_file":
        try:
            with open(args["path"]) as f:
                return f.read()
        except FileNotFoundError:
            return f"エラー: ファイル {args['path']} が見つかりません"

    return f"不明なツール: {name}"


def run_agent_loop(user_message, tools, max_iterations=20):
    """ツール呼び出しを含む完全なエージェントループを実行します。"""
    messages = [{"role": "user", "content": user_message}]

    for i in range(max_iterations):
        response = client.chat.completions.create(
            model="glm-5.1",
            messages=messages,
            tools=tools,
            tool_choice="auto",
            max_tokens=4096
        )

        message = response.choices[0].message
        messages.append(message.model_dump())

        if response.choices[0].finish_reason == "stop":
            return message.content

        if response.choices[0].finish_reason == "tool_calls":
            for tool_call in message.tool_calls:
                tool_result = execute_tool(tool_call)
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": tool_result
                })

    return "最大イテレーション数に達しました"


result = run_agent_loop(
    "Write a quicksort implementation, test it with a random list of 1000 integers, and report the time.",
    tools
)
print(result)
Enter fullscreen mode Exit fullscreen mode

このエージェントパターンは、複数のツール呼び出しと結果フィードバックを繰り返しながら自律的に問題解決を進めます。

主要なパラメータ

パラメータ タイプ デフォルト 説明
model 文字列 必須 "glm-5.1" を使用
messages 配列 必須 会話履歴
max_tokens 整数 1024 生成する最大トークン数 (最大163,840)
temperature 浮動小数点数 0.95 ランダム性。低いほど決定論的。範囲: 0.0-1.0
top_p 浮動小数点数 0.7 ニュークリアスサンプリング(推奨: 0.7)
stream 真偽値 false ストリーミングレスポンスを有効
tools 配列 null ツール呼び出し用関数定義
tool_choice 文字列/obj "auto" "auto" "none" または特定ツール
stop 文字列/配列 null カスタム停止シーケンス

コーディングタスクの推奨設定:

{
    "model": "glm-5.1",
    "temperature": 1.0,
    "top_p": 0.95,
    "max_tokens": 163840  # フルコンテキスト
}
Enter fullscreen mode Exit fullscreen mode

決定論的な出力が必要な場合はtemperatureを0.2〜0.4へ調整してください。

GLM-5.1をコーディングアシスタントで使う

Z.AIコーディングプランでは、Claude Code、Cline、Kilo CodeなどのAIコーディングアシスタントからBigModel API経由でGLM-5.1を利用できます。高機能コーディングモデルを低コストで使いたい場合に有効です。

Claude Codeのセットアップ

~/.claude/settings.json などの設定ファイル:

{
  "model": "glm-5.1",
  "baseURL": "https://open.bigmodel.cn/api/paas/v4/",
  "apiKey": "your_bigmodel_api_key"
}
Enter fullscreen mode Exit fullscreen mode

Cline / Roo Codeのセットアップ

VS CodeやCline拡張の設定例:

{
  "cline.apiProvider": "openai",
  "cline.openAIBaseURL": "https://open.bigmodel.cn/api/paas/v4/",
  "cline.openAIApiKey": "your_bigmodel_api_key",
  "cline.openAIModelId": "glm-5.1"
}
Enter fullscreen mode Exit fullscreen mode

クォータ消費量

GLM-5.1はトークン課金ではなくクォータ制です。

  • ピーク(UTC+8 14:00〜18:00):クォータ3倍消費
  • オフピーク:クォータ2倍
  • 2026年4月までのプロモ:オフピーク時1倍

大量のエージェント処理・長期タスクはオフピークのスケジューリング推奨です。

ApidogでGLM-5.1 APIをテストする

エージェントAPI統合テストでは、補完・ストリーミング・ツール呼び出し・エラーなど複数のレスポンス型を検証する必要があります。実APIで行うとクォータ消費やライブ接続が必要です。

ApidogでのエージェントAPIテスト

Apidogのスマートモックを使えば、各状態をモック化して効率的にテストできます。

モックエンドポイントのセットアップ

  1. Apidogで新規エンドポイント(POST https://open.bigmodel.cn/api/paas/v4/chat/completions)を作成
  2. 標準レスポンスのモックを追加
{
  "id": "chatcmpl-test123",
  "object": "chat.completion",
  "created": 1744000000,
  "model": "glm-5.1",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "def sieve(n): ..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 32,
    "completion_tokens": 120,
    "total_tokens": 152
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. ツール呼び出しレスポンスも追加
{
  "id": "chatcmpl-tool456",
  "object": "chat.completion",
  "created": 1744000001,
  "model": "glm-5.1",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_abc",
            "type": "function",
            "function": {
              "name": "run_python",
              "arguments": "{\"code\": \"print(2+2)\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 48,
    "completion_tokens": 35,
    "total_tokens": 83
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. レート制限(HTTP 429)レスポンスも追加
{
  "error": {
    "message": "Rate limit exceeded. Please retry after 60 seconds.",
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded"
  }
}
Enter fullscreen mode Exit fullscreen mode

完全なエージェントループのテスト

Apidogのテストシナリオで複数リクエストを連鎖できます。

  1. ステップ1: /chat/completionsにPOSTし、finish_reason == "tool_calls"を検証
  2. ステップ2: ツール結果をmessagesに含めて再POSTし、finish_reason == "stop"を検証
  3. ステップ3: 最終出力を検証

429などのエラーもモックで再現できるので、リトライやエラー処理も本番同様に検証可能です。

複数ステップのエージェントワークフローもテストシナリオの変数でIDなどを受け渡せます。本番前にバグを検出できます。

エラー処理

APIは標準のHTTPステータスを返します。

ステータス 意味 アクション
200 成功 通常通り処理
400 不正なリクエスト リクエスト形式を確認
401 認証エラー APIキーを確認
429 レート制限 Retry-Afterに従ってリトライ
500 サーバーエラー 指数バックオフでリトライ
503 サービス利用不可 指数バックオフでリトライ

例:レート制限・タイムアウトの自動リトライ

import time
import requests

def call_with_retry(payload, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = requests.post(
                "https://open.bigmodel.cn/api/paas/v4/chat/completions",
                headers={"Authorization": f"Bearer {os.environ['BIGMODEL_API_KEY']}",
                         "Content-Type": "application/json"},
                json=payload,
                timeout=120
            )

            if response.status_code == 429:
                retry_after = int(response.headers.get("Retry-After", 60))
                print(f"レート制限。{retry_after}秒待機しています...")
                time.sleep(retry_after)
                continue

            response.raise_for_status()
            return response.json()

        except requests.exceptions.Timeout:
            wait = 2 ** attempt
            print(f"試行 {attempt + 1} でタイムアウトしました。{wait}秒後に再試行します...")
            time.sleep(wait)

    raise Exception("最大再試行回数を超えました")
Enter fullscreen mode Exit fullscreen mode

エージェント実行が長時間かかる場合(30~60秒/step以上)、timeoutは120~300秒など十分に設定してください。

まとめ

GLM-5.1のOpenAI互換APIにより、GPTやClaudeアプリの統合・移行はベースURLとモデル名変更のみで完了します。トークン課金ではなくクォータ制なのが主な違いです。

エージェントアプリの長期タスクや複雑な自動化ではGLM-5.1のパワーが活きます。Apidogのスマートモック・テストシナリオで事前検証することで、実運用前にすべてのケースを安全にカバーできます。

GLM-5.1の概要やベンチマーク比較はGLM-5.1モデルの概要を、AIエージェントワークフローの構築とテスト詳細はAIエージェントメモリの仕組みを参照してください。

よくある質問 (FAQ)

GLM-5.1 APIはOpenAI互換ですか?

はい。リクエスト・レスポンス・ストリーミング・ツール呼び出しはOpenAIチャット補完APIと同一です。ベースURLをhttps://open.bigmodel.cn/api/paas/v4/に設定すればOpenAI SDKや互換クライアントで動作します。

APIリクエストで使うモデル名は?

"glm-5.1"を指定してください。バージョン番号なしのglm-5.1でOKです。

GLM-5.1 APIの料金体系は?

BigModel APIはクォータ制です。ピーク時(UTC+8 14:00〜18:00)は3倍、オフピークは2倍消費。2026年4月末までオフピークは1倍。

最大コンテキスト長は?

入力200,000トークン、出力最大163,840トークン。長期エージェントタスクではmax_tokensを大きめ(32,768以上)に指定してください。

GLM-5.1で関数呼び出し/ツール利用可能?

はい。OpenAI APIと同じツール呼び出し形式をサポート。tools配列に関数を定義し、finish_reason: "tool_calls"時に処理してください。

クォータ消費せずAPI呼び出しをテストするには?

Apidogのスマートモックで各API状態(成功/ツール呼び出し/エラーなど)を定義し、開発中はモックでテスト、本番前のみ実API利用を推奨します。

GLM-5.1のモデルウェイトは?

HuggingFaceのzai-org/GLM-5.1でMITライセンスで公開されています。ローカル推論用にvLLMやSGLangも利用可能です。

Top comments (0)