Messages APIの使用
Messages APIを効果的に使用するための実践的なパターンと例
Anthropicは、Claudeを使って構築するための2つの方法を提供しており、それぞれ異なるユースケースに適しています。
| Messages API | Claude Managed Agents | |
|---|---|---|
| 概要 | モデルへの直接的なプロンプトアクセス | マネージドインフラストラクチャ上で動作する、事前構築済みで設定可能なエージェントハーネス |
| 最適な用途 | カスタムエージェントループときめ細かな制御 | 長時間実行されるタスクと非同期作業 |
このガイドでは、基本的なリクエスト、マルチターンの会話、プリフィル手法、ビジョン機能など、Messages APIを扱う際の一般的なパターンについて説明します。完全なAPI仕様については、Messages APIリファレンスを参照してください。マネージドエージェントハーネスについては、代わりにClaude Managed Agentsの概要を参照してください。
基本的なリクエストとレスポンス
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(message){
"id": "msg_01XFDUDYJgAACzvnptvVoYEL",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello!"
}
],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 12,
"output_tokens": 6
}
}拒否レスポンス(stop_reason: "refusal")には、すべてのモデルにおいて、拒否をトリガーしたポリシーカテゴリを識別するstop_detailsオブジェクトも含まれます。フィールドのリファレンスと処理コードの例については、停止理由の処理を参照してください。
複数の会話ターン
Messages APIはステートレスです。つまり、常に会話履歴全体をAPIに送信します。このパターンを使用して、時間をかけて会話を構築できます。以前の会話ターンは、必ずしも実際にClaudeから発信されたものである必要はありません。合成されたassistantメッセージを使用できます。
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude"},
{"role": "assistant", "content": "Hello!"},
{"role": "user", "content": "Can you describe LLMs to me?"},
],
)
print(message){
"id": "msg_018gCsTGsXkYJVqYPxTgDHBU",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Sure, I'd be happy to provide..."
}
],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 30,
"output_tokens": 309
}
}メッセージ内のsystemロール
Claude Fable 5.1、Claude Mythos 5.1、Claude Fable 5、Claude Mythos 5、Claude Opus 5.5、Claude Opus 4.8、およびClaude Opus 5では、ユーザーターンの後に"role": "system"を持つメッセージを含めることで(配置ルールに従います)、会話の途中で新しいシステム指示を追加できます。systemメッセージをmessagesの最初のエントリにすることはできません。最初から適用される指示には、トップレベルのsystemフィールドを使用してください。
会話途中のシステムメッセージは、トップレベルのsystemフィールドと同じ権限を持ちますが、メッセージ履歴の末尾に追加されるため、それ以前にキャッシュされたプレフィックスを無効化しません。最初のターンから適用すべき指示にはトップレベルのsystemフィールドを使用し、後になって初めて関連性が生じる指示には会話途中のシステムメッセージを使用してください。
プロンプトキャッシングとの組み合わせ方法を含む完全なガイドについては、会話途中のシステムメッセージを参照してください。
Claudeのレスポンスのプリフィル
入力メッセージリストの最後の位置で、Claudeのレスポンスの一部を事前に入力(プリフィル)できます。この手法を使用してClaudeのレスポンスを形作ることができます。次の例では、"max_tokens": 1を使用して、Claudeから単一の多肢選択式の回答を取得しています。
message = anthropic.Anthropic().messages.create(
model="claude-sonnet-4-5",
max_tokens=1,
messages=[
{
"role": "user",
"content": "What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae",
},
{"role": "assistant", "content": "The answer is ("},
],
)
print(message){
"id": "msg_01Q8Faay6S7QPTvEUUQARt7h",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "C"
}
],
"model": "claude-sonnet-4-5",
"stop_reason": "max_tokens",
"stop_sequence": null,
"usage": {
"input_tokens": 42,
"output_tokens": 1
}
}ビジョン
Claudeはリクエスト内のテキストと画像の両方を読み取ることができます。画像はbase64、url、またはfileのソースタイプを使用して提供できます。fileソースタイプは、Files APIを通じてアップロードされた画像を参照します。サポートされているメディアタイプはimage/jpeg、image/png、image/gif、およびimage/webpです。詳細については、ビジョンガイドを参照してください。
import base64
import httpx2
# オプション 1: Base64 エンコードされた画像
image_url = "https://platform.claude.com/docs/images/vision-example.jpg"
image_media_type = "image/jpeg"
image_data = base64.standard_b64encode(httpx2.get(image_url).content).decode("utf-8")
message = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": image_media_type,
"data": image_data,
},
},
{"type": "text", "text": "What is in the above image?"},
],
}
],
)
print(message)
# オプション 2: URL で参照する画像
message_from_url = anthropic.Anthropic().messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "url",
"url": "https://platform.claude.com/docs/images/vision-example.jpg",
},
},
{"type": "text", "text": "What is in the above image?"},
],
}
],
)
print(message_from_url){
"id": "msg_011CdKmWtV3oFx1C5yUbf5CY",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "This image is a beautiful minimalist/flat-design illustration of a sunset landscape. Here's what it contains:\n\n**Sky & Sun:**\n- A warm gradient sky transitioning from golden-yellow at the top to deep orange toward the horizon\n- A large pale yellow sun positioned in the upper-right area\n\n**Birds:**\n- Three small silhouetted birds flying in the upper-left portion of the sky, depicted as simple \"M\" or \"v\" shapes\n\n**Mountains:**\n- Multiple layered mountain peaks in purple and maroon tones\n- The mountains overlap to create depth, with varying shades of dusty purple and deep burgundy\n\n**Water:**\n- A dark purple body of water at the bottom of the image\n- A reflection of the sun shown as horizontal cream/peach colored lines in the center-bottom area\n\nThe overall style is clean, geometric, and uses a warm sunset color palette (oranges, yellows, purples, and maroons), giving it a peaceful, serene aesthetic typical of modern vector/flat design artwork."
}
],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 1030,
"output_tokens": 350
}
}次のステップ
各stop_reasonの値を処理し、レスポンスが終了したときに何をすべきかを決定します。
Messages API内から外部サービスやAPIを呼び出すためのツールをClaudeに与えます。
Messages APIでデスクトップコンピュータ環境を制御します。
お使いのブラウザ上で、Claudeにウェブページのナビゲーション、読み取り、操作を行わせます。
Claudeから、スキーマ検証済みの保証されたJSON出力を取得します。
output_config.task_budgetを使用して、エージェントループ全体にわたる目安となるトークンバジェットを設定します。
Was this page helpful?