第3章 · Claude API Basics

Messages API の基本

Messages API Basics
→ で次のスライド · F でフルスクリーン · N で講師ノート · Esc で終了

重要キーワード

Messages API
メッセージAPI
Claude API の中心エンドポイント
Stateless
ステートレス
サーバーが会話状態を保持しない設計
Content Block
コンテンツブロック
応答の構成要素 (text/image/tool_use 等)
stop_reason
停止理由
応答が終了した理由 (end_turn / max_tokens / tool_use ...)

Messages API

Claude API の中心は Messages API です。 messages.create() を呼ぶことで応答を得ます。

リクエストの構造

history = []
def chat(user_msg):
    history.append({"role": "user", "content": user_msg})
    res = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        messages=history,
    )
    text = res.content[0].text
    history.append({"role": "assistant", "content": text})
    return text

レスポンスの構造

for block in msg.content:
    if block.type == "text":
        print(block.text)
    elif block.type == "tool_use":
        print("Tool call:", block.name, block.input)
    elif block.type == "thinking":
        print("Internal thought:", block.thinking)

マルチターン会話

会話履歴は すべてのターンを送り直す のが基本ルールです。 モデル側に状態は保持されません (stateless)。

history = []
def chat(user_msg):
    history.append({"role": "user", "content": user_msg})
    res = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        messages=history,
    )
    text = res.content[0].text
    history.append({"role": "assistant", "content": text})
    return text

content の中身

contentテキスト・画像・ツール呼び出し などの「ブロック」の配列です。 複雑な応答ではブロックが複数返ることがあります。

for block in msg.content:
    if block.type == "text":
        print(block.text)
    elif block.type == "tool_use":
        print("Tool call:", block.name, block.input)
    elif block.type == "thinking":
        print("Internal thought:", block.thinking)

user メッセージも構造化できる

content は文字列だけでなく 配列 で渡せます。画像や複数テキストブロックが混在可能。

messages=[{
    "role": "user",
    "content": [
        {"type": "text", "text": "この画像を説明して"},
        {"type": "image", "source": {"type": "url", "url": "https://example.com/cat.jpg"}},
    ],
}]

stop_reason の意味

意味
end_turn 自然終了 (ふつうの完了)
max_tokens max_tokens に到達した (途中切断)
stop_sequence stop_sequences のいずれかが出現
tool_use ツール呼び出しを要求 (Tool Use 中)
pause_turn 長時間処理 (Claude Code on the web 等) で一時停止

試してみる: マルチターン

簡単な対話を Playground で再現してみましょう。

▶ ターンの感覚を掴む
私は今 Python の入門書を選んでいます。3 冊おすすめしてください。 (↑ の応答を見たら、続けて「2 冊目について、対象読者をもっと詳しく」と聞いてみましょう)
Hands-on Exercise

演習: シンプルな CLI チャット

Python で 20 行程度の CLI チャットボット を作ってください。仕様: - ユーザーが quit と入力するまでループ - 履歴を保持してマルチターンに対応 - usage を毎回末尾に表示

▶ Playground を開いて実行

理解度チェック

4 問のクイズで理解度を確認しましょう。

クイズを開く
🎉

まとめ

お疲れ様でした!