DEV Community

Cover image for Kimi K2.6 API の使い方
Akira
Akira

Posted on • Originally published at apidog.com

Kimi K2.6 API の使い方

Moonshot AIのKimi K2.6の発表は、これをコーディング、長期的実行、エージェントスウォームにおける新しいオープンソースの最先端技術として位置付けています。これを動かすAPIはOpenAI互換で、https://api.moonshot.ai/v1でホストされており、プラットフォームでドキュメントが提供されています。OpenAI SDKがインストールされていれば、約5分で実際の要求を送信できます。

Apidogを今すぐ試す

このガイドでは、認証、初回のリクエスト、ストリーミング、ツール呼び出し、ビジョンおよびビデオ入力、思考モード、そして300個のサブエージェントでエージェントスウォームを駆動する方法を順を追って解説します。また、統合コードを記述する前にApidogで全APIエンドポイントをテストする手順も示します。

💡 近道: 統合コードをコミットする前に、ApidogでKimi K2.6 APIを視覚的にテストしましょう。1回のインポート、1つのBearerトークンで、完全な履歴とスキーマ検証を備えた実際のストリーミングリクエストを行えます。Apidogは無料でダウンロード可能です。

TL;DR: 60秒でわかるKimi K2.6 API

  • ベースURL: https://api.moonshot.ai/v1
  • エンドポイント: POST /chat/completions
  • モデルID: kimi-k2.6, kimi-k2.6-thinking
  • 認証: Authorization: Bearer $KIMI_API_KEY
  • 形式: OpenAIチャット補完スキーマ(messages, tools, streamなど)
  • コンテキスト: 入力トークン262,144、推論用出力トークン最大98,304
  • デフォルト設定: temperature 1.0, top-p 1.0(Moonshotの公式ガイダンス

最小限のcurl例:

curl https://api.moonshot.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $KIMI_API_KEY" \
  -d '{
    "model": "kimi-k2.6",
    "messages": [{"role": "user", "content": "Write a Python function that reverses a string."}]
  }'
Enter fullscreen mode Exit fullscreen mode

このガイドでは、エージェントスウォームや、Moonshotが設定する4,000ステップの実行上限も含め、さらに詳細な使い方を解説します。

Kimi K2.6 メイン画像

このAPIで実際にできること

Kimi K2.6の発表によれば、このAPIは以下のプロダクション用途をカバーします。

  • コーディングエージェント: 12時間以上稼働可能(Qwen3.5-0.8B Mac推論デモ: 4,000以上のツール呼び出し、スループット大幅向上)
  • 自律的なインフラ管理: 自動インシデント対応含むマルチデイセッション
  • マルチ言語長期信頼性: Rust/Go/Python/Zig対応
  • エージェントスウォーム: 最大300サブエージェント、4,000+協調ステップ
  • デザイン駆動開発: 単一プロンプトで認証・DB・トランザクション付きフルスタックアプリ生成
  • ビジョン+Pythonツール: MathVision(Python経由で93.2%)

Claude Codeのコンピューター使用独自Claude Code構築Cursor Composer 2等と同カテゴリのツールを開発中なら、K2.6 APIはモデル層の置き換えに即投入可能です。


ステップ1: APIキーの取得

  1. platform.moonshot.ai または platform.kimi.ai にアクセスし、サインアップ(メールまたはGoogle OAuth)。
  2. アカウント確認(海外ユーザーはSMS認証が必要な場合あり)。
  3. 請求情報登録。新規アカウントには無料残高が付与されることが多いです。
  4. ダッシュボードで API KeysCreate Key
  5. キーをその場でコピー(再表示不可)。
  6. 環境変数にエクスポート:
export KIMI_API_KEY="sk-..."
Enter fullscreen mode Exit fullscreen mode

.zshrc.bashrc、またはシークレットマネージャーに保存し、絶対にコードにコミットしないようにしましょう。

開発中に料金を抑えたい場合は、Kimi K2.6を無料で利用する方法(Cloudflare Workers AI/セルフホスト/無料クレジット)を参照。


ステップ2: SDKの選択

APIはOpenAI互換なので、ベースURLだけ差し替えれば公式OpenAI SDKがそのまま使えます。

オプション インストール 最適用途
curl 標準搭載 クイックテスト・CI
OpenAI Python pip install openai Pythonサービス
OpenAI Node npm install openai JS/TSアプリ

Python

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("KIMI_API_KEY"),
    base_url="https://api.moonshot.ai/v1",
)

response = client.chat.completions.create(
    model="kimi-k2.6",
    messages=[{"role": "user", "content": "What is the capital of France?"}],
)

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

Node.js

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.KIMI_API_KEY,
  baseURL: "https://api.moonshot.ai/v1",
});

const response = await client.chat.completions.create({
  model: "kimi-k2.6",
  messages: [{ role: "user", content: "What is the capital of France?" }],
});

console.log(response.choices[0].message.content);
Enter fullscreen mode Exit fullscreen mode

curl

curl https://api.moonshot.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $KIMI_API_KEY" \
  -d '{
    "model": "kimi-k2.6",
    "messages": [{"role": "user", "content": "What is the capital of France?"}]
  }'
Enter fullscreen mode Exit fullscreen mode

どの方法でも同じレスポンス形式が返ります。


ステップ3: リクエストボディを理解する

OpenAIチャット補完との互換フィールド:

{
  "model": "kimi-k2.6",
  "messages": [
    { "role": "system", "content": "You are a helpful assistant." },
    { "role": "user", "content": "Your prompt here." }
  ],
  "temperature": 1.0,
  "top_p": 1.0,
  "max_tokens": 8192,
  "stream": false,
  "tools": [],
  "tool_choice": "auto",
  "thinking": { "type": "disabled" }
}
Enter fullscreen mode Exit fullscreen mode

Moonshot特有のポイント2つ:

  • デフォルト値が高い: 公式ブログ推奨はtemperature 1.0, top-p 1.0。OpenAI流のtemperature 0.2の癖は不要。
  • thinkingフィールド: kimi-k2.6-thinkingで推論トレースを切替。{"type": "disabled"}で抑制可能。

ステップ4: ストリーミング

ストリーミングは長い出力やUI用途のデフォルト推奨。最大98,304トークンまで出るため、全体を一括で待つのは非効率です。

Python

stream = client.chat.completions.create(
    model="kimi-k2.6",
    messages=[{"role": "user", "content": "Write a 500-word essay on MoE models."}],
    stream=True,
)

for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)
Enter fullscreen mode Exit fullscreen mode

Node.js

const stream = await client.chat.completions.create({
  model: "kimi-k2.6",
  messages: [{ role: "user", content: "Write a 500-word essay on MoE models." }],
  stream: true,
});

for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta?.content;
  if (delta) process.stdout.write(delta);
}
Enter fullscreen mode Exit fullscreen mode

ツール呼び出し時もストリーミング対応。引数はJSONデルタで受信。


ステップ5: ツール呼び出し

MoonshotはToolathlonスコア50.0%ツール呼び出し成功率96.60%と高水準。スキーマはOpenAI関数呼び出しと同一なので、QAエンジニア向けAPIテストワークフローがそのまま使えます。

ツール定義例

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather in a location.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City name"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                },
                "required": ["location"]
            }
        }
    }
]
Enter fullscreen mode Exit fullscreen mode

初回呼び出し(モデルがツール利用を判断)

import json

messages = [{"role": "user", "content": "What's the weather in Tokyo?"}]

resp = client.chat.completions.create(
    model="kimi-k2.6",
    messages=messages,
    tools=tools,
    tool_choice="auto",
)

msg = resp.choices[0].message
messages.append(msg)

if msg.tool_calls:
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        result = fetch_weather(args["location"], args.get("unit", "celsius"))
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })
Enter fullscreen mode Exit fullscreen mode

2回目呼び出し(最終回答)

final = client.chat.completions.create(
    model="kimi-k2.6",
    messages=messages,
    tools=tools,
)
print(final.choices[0].message.content)
Enter fullscreen mode Exit fullscreen mode

K2.6は多段階ツールチェーンにも強く、Kimi Codeのような長時間エージェントも構築できます。Claude Codeワークフローとも同様のループ構造です。


ステップ6: ビジョン入力

K2.6はMMMU-Proで79.4%、V*(Python使用)で96.9%のスコア。画像はOpenAI標準のimage_url形式で入力:

response = client.chat.completions.create(
    model="kimi-k2.6",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Describe this image in one sentence."},
                {"type": "image_url", "image_url": {"url": "https://example.com/photo.jpg"}}
            ]
        }
    ],
)
Enter fullscreen mode Exit fullscreen mode

ローカルファイルはbase64エンコードで送信:

import base64
with open("photo.jpg", "rb") as f:
    b64 = base64.b64encode(f.read()).decode("utf-8")

image_url = f"data:image/jpeg;base64,{b64}"
Enter fullscreen mode Exit fullscreen mode

OCRや図の解釈は明示的なテキスト指示+画像で精度向上。数学問題にはPythonツール追加が有効(MathVisionスコアはPython有効時のもの)。


ステップ7: ビデオ入力

ビデオURLまたはフレームシーケンスをvideo_urlで送信:

response = client.chat.completions.create(
    model="kimi-k2.6",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Summarize what happens in this video."},
                {"type": "video_url", "video_url": {"url": "https://example.com/clip.mp4"}}
            ]
        }
    ],
)
Enter fullscreen mode Exit fullscreen mode

30秒未満の短いクリップは一括処理可。長い動画はフレームごと推論となり、ストリーミング推奨。


ステップ8: 思考モード

kimi-k2.6-thinkingは推論トレースを出力(OpenAIのo1系に近い)。AIME 2026で96.4%、GPQA-Diamondで90.5%のスコア。

思考モードON(デフォルト)

response = client.chat.completions.create(
    model="kimi-k2.6-thinking",
    messages=[{"role": "user", "content": "Prove sqrt(2) is irrational."}],
)
Enter fullscreen mode Exit fullscreen mode

思考モードOFF

response = client.chat.completions.create(
    model="kimi-k2.6-thinking",
    messages=[{"role": "user", "content": "Quick: what's 17 * 23?"}],
    extra_body={"thinking": {"type": "disabled"}},
)
Enter fullscreen mode Exit fullscreen mode

推論トレースはレスポンスのreasoningフィールド。UI非表示やデバッグログへのパイプ処理も可能。


ステップ9: エージェントスウォーム

エージェントスウォームは最大300サブエージェント、4,000ステップ超の協調が可能。APIでパラメータ指定するだけで利用できます。

response = client.chat.completions.create(
    model="kimi-k2.6",
    messages=[{
        "role": "user",
        "content": "Build a 5-page marketing site for a coffee brand with responsive design and a newsletter signup."
    }],
    extra_body={
        "agent": {
            "type": "swarm",
            "max_agents": 30,
            "max_steps": 4000
        }
    },
)
Enter fullscreen mode Exit fullscreen mode

スウォームは数分~数時間動作するため:

  1. ストリーミング必須:進捗監視や途中停止を迅速に。
  2. max_agentsを制限:ほとんどのタスクは10-30程度で十分。
  3. 予算管理usageを常時ログし、コスト急増にアラート。

Kimiブログでは13時間連続・4,000行超のコード変更デモを掲載。APIフラグ指定のみで同等の実行が可能です。


ステップ10: Apidogで全てをテストする

各セクションのAPIリクエストはボディ・ヘッダー・レスポンス形式が異なります。Apidogはこれをビジュアルワークフローで検証・デバッグできます。

Apidogスクリーンショット

ApidogでのKimi K2.6セットアップ手順

  1. Apidogをダウンロードし、プロジェクト作成
  2. BASE_URL = https://api.moonshot.ai/v1, KIMI_API_KEY = sk-... の2変数でkimi-prod環境を作成
  3. 新規APIリクエスト: POST {{BASE_URL}}/chat/completions
  4. ヘッダー: Authorization: Bearer {{KIMI_API_KEY}}, Content-Type: application/json
  5. ボディ例(ストリーミング):
{
  "model": "kimi-k2.6",
  "messages": [{ "role": "user", "content": "Hello, Kimi K2.6!" }],
  "stream": true
}
Enter fullscreen mode Exit fullscreen mode
  1. Sendをクリック。リアルタイムでトークンがストリーミング表示されます。

Apidogの追加機能

  • スキーマ検証: OpenAIチャット補完仕様でフィールド不足を即発見
  • リクエスト履歴: すべての呼び出しを再現
  • 環境切り替え: 本番/開発/ステージングのトークンをワンクリックでスイッチ
  • チーム共有: プロジェクトエクスポートで即共有。詳しくは50人以上のエンジニア向けAPIテスト参照
  • モックサーバー: Moonshot障害時やオフラインテスト用
  • SSEストリームサポート: Kimiのストリーミング形式もそのまま表示

VS Code内テストにはVS Code拡張、Postmanからの移行はAPIテストをPostmanなしで行う方法に詳細あり。


手間のかからないエラーハンドリング

Moonshotは標準HTTPステータスコードを返します:

  • 400: 不正なリクエスト(ボディ不備・モデル名ミス等)
  • 401: 認証失敗(キー不正・期限切れ)
  • 429: レート制限またはクォータ超過
  • 500: サーバーエラー(指数バックオフで再試行)
  • 529: 過負荷(数秒後リトライ)

リトライラッパー例:

import time
from openai import OpenAI, RateLimitError, APIError

def call_kimi(messages, max_retries=5):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="kimi-k2.6",
                messages=messages,
            )
        except RateLimitError:
            time.sleep(2 ** attempt)
        except APIError as e:
            if e.status_code >= 500 and attempt < max_retries - 1:
                time.sleep(2 ** attempt)
            else:
                raise
    raise RuntimeError("Kimi K2.6 failed after retries")
Enter fullscreen mode Exit fullscreen mode

ストリーム途中で切断された場合は受信済みトークンを記録し、「ここから続行」でリカバリ可能。98,304トークン上限による長大出力も正常動作です。


コスト管理

公式価格表に基づいたコスト管理Tips:

  • max_tokensに上限指定: チャット返信用途なら2048程度で十分
  • システムプロンプトキャッシュ: 繰り返し使う指示は最初に
  • usageをログ化: レスポンスのprompt_tokens,completion_tokens,total_tokensをPrometheus等にパイプし監視・アラート

本番パターン: GitHubイシューフィクサー

Kimi K2.6ツール呼び出しループを使い、GitHubイシュー→関連コード特定→修正→テスト実行まで自動化するエージェント例:

from openai import OpenAI
import os, json

client = OpenAI(
    api_key=os.getenv("KIMI_API_KEY"),
    base_url="https://api.moonshot.ai/v1",
)

tools = [
    {"type": "function", "function": {
        "name": "read_file",
        "description": "Read a file in the repo.",
        "parameters": {
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"]
        }
    }},
    {"type": "function", "function": {
        "name": "search_code",
        "description": "Ripgrep the codebase for a pattern.",
        "parameters": {
            "type": "object",
            "properties": {"query": {"type": "string"}},
            "required": ["query"]
        }
    }},
    {"type": "function", "function": {
        "name": "run_tests",
        "description": "Run the project test suite.",
        "parameters": {"type": "object", "properties": {}}
    }},
]

def tool_dispatch(name, args):
    if name == "read_file":
        with open(args["path"]) as f:
            return f.read()
    if name == "search_code":
        return run_ripgrep(args["query"])
    if name == "run_tests":
        return run_pytest()
    raise ValueError(f"Unknown tool: {name}")

messages = [
    {"role": "system", "content": "You are a senior engineer. Fix the described bug."},
    {"role": "user", "content": "Issue: login form submits twice on slow networks."}
]

while True:
    resp = client.chat.completions.create(
        model="kimi-k2.6",
        messages=messages,
        tools=tools,
    )
    msg = resp.choices[0].message
    messages.append(msg)

    if not msg.tool_calls:
        print(msg.content)
        break

    for call in msg.tool_calls:
        result = tool_dispatch(call.function.name, json.loads(call.function.arguments))
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": result,
        })
Enter fullscreen mode Exit fullscreen mode

extra_bodyでスウォーム設定を追加すれば大規模化も可能。人間の介入ポイントが必要な場合はHermesマルチエージェントスタックと組み合わせてください。


よくある質問

Moonshot固有SDKは必要?

必要ありません。base_urlを差し替えればOpenAI Python/Node SDKでそのまま使えます。

APIのレート制限は?

あり。利用ティアと履歴で変動。ダッシュボードで確認。

Kimi K2.6はLangChain/LlamaIndex/Vercel AI SDKと連携可能?

はい。OpenAI互換のベースURLを受け入れるすべてのフレームワークで動作します。

Kimi K2.6はJSONモード対応?

対応。response_format: {"type": "json_object"}で有効なJSON出力、{"type": "json_schema", "json_schema": {...}}で厳密スキーマ。

コンテキストウィンドウサイズは?

公式ブログによれば入力262,144トークン、推論出力最大98,304。

API経由でファインチューニング可能?

現時点では不可。ファインチューニングはオープンウェイトを自前ハードで実行。

kimi-k2.6kimi-k2.6-thinkingの違いは?

kimi-k2.6は高速エージェント。kimi-k2.6-thinkingは推論プロセスを出力し、数学・論理・難易度高タスク向け。

無料枠はある?

Cloudflare Workers AI、kimi.comチャット、セルフホスト等は無料アクセスガイド参照。


まとめ

Kimi K2.6 APIは、ベースURLとAPIキーの2点を切り替えるだけで、OpenAI互換ツールチェーンに即統合できます。262Kコンテキスト、最大300サブエージェントのスウォーム、ツール呼び出し成功率96.60%、必要に応じてオープンウェイトも利用可能。

新しい統合構築時は、まずApidogで各エンドポイントを徹底テスト。スキーマ・ストリーミング・認証エラーをコード投入前に検出し、動作確認済みリクエストをPython/Nodeサービスへ移植しましょう。


参考文献およびさらに読む

Top comments (0)