Claude Agent SDK 入門

Claude Agent SDK を使用して AI Agent アプリケーションを構築する方法を学ぶ

最終更新 2026-09-03
目次

Claude Agent SDK は、Claude モデルに基づいた AI Agent アプリケーションを構築するための Anthropic 公式開発キットです。Claude Code(CLI ツール)とは異なり、SDK は開発者を対象としており、Claude の能力を自分のアプリケーションに統合できます。

Claude Agent SDK とは?

Claude Agent SDK は、以下を作成できるアプリケーションを構築するためのビルディングブロックを提供します:

  • 自然言語の指示を理解し、複雑なタスクを実行
  • ツールを使用(検索、コード実行、ファイル操作など)
  • マルチターン対話のコンテキストを維持
  • 外部サービスに接続(MCP サーバー経由)

SDK のインストール

Python SDK

pip install anthropic

TypeScript SDK

npm install @anthropic-ai/sdk

クイックスタート

基本的なメッセージ呼び出し

from anthropic import Anthropic

# QCode.cc API 経由
client = Anthropic(
    base_url="https://api.qcode.cc/api",
    api_key="cr_your_api_key"
)

message = client.messages.create(
    model="claude-opus-5",
    max_tokens=4096,
    messages=[
        {"role": "user", "content": "RESTful API について説明してください"}
    ]
)

print(message.content[0].text)

ストリーミング応答

with client.messages.stream(
    model="claude-opus-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Python のクイックソート関数を書いてください"}
    ]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

ツールの使用(Tool Use)

Tool Use は Agent のコア機能で、モデルが外部ツールを呼び出すことを可能にします。

ツールの定義

from anthropic import Anthropic

client = Anthropic(
    base_url="https://api.qcode.cc/api",
    api_key="cr_your_api_key"
)

# 検索ツールを定義
tools = [
    {
        "name": "search_web",
        "description": "ウェブで検索して情報を取得",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "検索キーワード"
                }
            },
            "required": ["query"]
        }
    }
]

# ツール付きでメッセージを送信
message = client.messages.create(
    model="claude-opus-5",
    max_tokens=4096,
    messages=[
        {"role": "user", "content": "(15 + 25) * 2 を計算してください"}
    ],
    tools=tools
)

# ツール呼び出しを処理
for content in message.content:
    if content.type == "text":
        print(content.text)
    elif content.type == "tool_use":
        print(f"ツール呼び出し: {content.name}")
        print(f"引数: {content.input}")

        # ツールの実行をシミュレート
        if content.name == "calculate":
            result = eval(content.input["expression"])
            tool_result = str(result)
        elif content.name == "search_web":
            tool_result = f"検索結果 '{content.input['query']}' ..."

        # 結果をモデルに返す
        message = client.messages.create(
            model="claude-opus-5",
            max_tokens=4096,
            messages=[
                {"role": "user", "content": "(15 + 25) * 2 を計算してください"},
                message,
                {
                    "role": "user",
                    "content": None,
                    "type": "tool_result",
                    "tool_use_id": content.id,
                    "content": tool_result
                }
            ],
            tools=tools
        )

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

with client.messages.stream(
    model="claude-opus-5",
    max_tokens=4096,
    messages=[
        {"role": "user", "content": "Create a file named hello.py that prints 'Hello, World!'"}
    ],
    tools=[
        {
            "name": "write_file",
            "description": "Write content to a file",
            "input_schema": {
                "type": "object",
                "properties": {
                    "filename": {"type": "string"},
                    "content": {"type": "string"}
                },
                "required": ["filename", "content"]
            }
        }
    ]
) as stream:
    for event in stream:
        if event.type == "content_block_delta":
            if event.delta.type == "text_delta":
                print(event.delta.text, end="", flush=True)
            elif event.delta.type == "tool_use_delta":
                print(f"\n[Tool Call] {event.delta.name}")

Prompt Caching

Prompt Caching は長い会話のコストを大きく下げられます:

# システムプロンプト(キャッシュされる)
system_prompt = """You are a professional code review assistant.
Your responsibilities:
1. Check code security
2. Identify performance issues
3. Verify code standards
4. Provide improvement suggestions
"""

# cache_control でキャッシュ対象を指定する
message = client.messages.create(
    model="claude-opus-5",
    max_tokens=4096,
    system=[
        {
            "type": "text",
            "text": system_prompt,
            "cache_control": {"type": "ephemeral"}
        }
    ],
    messages=[
        {"role": "user", "content": "Review @src/auth/login.ts"}
    ]
)

Agent の構築例

from anthropic import Anthropic
from typing import List

class CodeReviewAgent:
    def __init__(self, api_key: str):
        self.client = Anthropic(
            base_url="https://api.qcode.cc/api",
            api_key=api_key
        )
        self.system_prompt = """You are a professional code review assistant.
Focus on: security, performance, readability, best practices.
Output for each review: issue list, severity, fix suggestions."""

    def review(self, code_snippet: str) -> str:
        message = self.client.messages.create(
            model="claude-opus-5",
            max_tokens=4096,
            system=self.system_prompt,
            messages=[
                {"role": "user", "content": f"Review this code:\n\n{code_snippet}"}
            ]
        )
        return message.content[0].text

# Usage
agent = CodeReviewAgent("cr_your_api_key")
result = agent.review("SELECT * FROM users WHERE id = " + user_id)

Claude Code との違い

項目 Claude Agent SDK Claude Code
対象ユーザー 開発者 個人の開発者
実行場所 あなたのアプリケーション コマンドライン
ファイル操作 自分で実装する 内蔵
ターミナルコマンド 自分で実装する 内蔵
Git 連携 自分で実装する 内蔵
用途 AI アプリを作る プログラミングの支援

QCode.cc 設定

import os

# 方法 1: 環境変数
os.environ["ANTHROPIC_BASE_URL"] = "https://api.qcode.cc/api"
os.environ["ANTHROPIC_AUTH_TOKEN"] = "cr_your_key"

client = Anthropic()  # 環境変数を自動読み取り

# 方法 2: アジアノード(中国大陸推奨)
client = Anthropic(
    base_url="https://api.qcode.cc/api",
    api_key="cr_your_key"
)

次のステップ

関連ドキュメント

安全ベストプラクティス
Claude Code のセキュリティの仕組みを総合的に理解する — 権限制御、機密ファイル保護、コマンド傍受、API キー管理
自動化と CI/CD
Claude Code のヘッドレスモードを完全習得 — パラメータ一覧、5 つの CI/CD 実例、Docker 隔離、セッション復元、Codex との比較
プラグインシステム
Claude Code プラグインシステムでカスタムコマンド、エージェント、ワークフローを作成
🚀
QCode を始めよう — Claude Code & Codex
1つのプランで Claude Code と Codex の両方を加速、アジア太平洋低遅延
料金プランを見る → アカウント登録
3人以上のチーム?
企業版:専用ドメイン + サブKey管理 + 封禁保護、¥250/人/月〜
企業版を見る →