すべてのMessages APIレスポンスには、Claudeが生成を停止した理由を示すstop_reasonフィールドが含まれています。このフィールドを確認して、レスポンスをそのまま使用するか、会話を続行するか、再試行するか、別のモデルにフォールバックするかを判断してください。
完全なレスポンススキーマについては、Messages APIリファレンスを参照してください。
| 値 | 発生するタイミング | 対応方法 |
|---|---|---|
end_turn | Claudeが自然にレスポンスを完了した。 | レスポンスを使用します。 |
max_tokens | レスポンスがmax_tokensの制限に達した。 | max_tokensを増やすか、レスポンスを続行します。 |
stop_sequence | Claudeが指定したstop_sequencesのいずれかを出力した。 | stop_sequenceを読み取り、どれがトリガーされたかを確認します。 |
tool_use | Claudeがツールを呼び出している。 | ツールを実行して結果を返します。結果ブロックがまだないサーバーツール呼び出しは、後続のレスポンスで完了します。 |
pause_turn | サーバーツールのループが反復制限に達した。 | アシスタントのコンテンツをそのまま送り返して続行します。 |
refusal | Claudeが応答を拒否した。 | stop_detailsを読み取り、フォールバックモデルで再試行します。 |
model_context_window_exceeded | レスポンスがモデルのコンテキストウィンドウを埋め尽くした。 | レスポンスを切り捨てられたものとして扱います。 |
stop_reasonフィールドは、すべての成功したMessages APIレスポンスの一部です。リクエスト処理の失敗を示すエラーとは異なり、stop_reasonはClaudeがレスポンス生成を完了した理由を示します。
{
"id": "msg_01234",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Here's the answer to your question..."
}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"stop_details": null,
"usage": {
"input_tokens": 100,
"output_tokens": 50
}
}最も一般的な停止理由です。Claudeが自然にレスポンスを完了したことを示します。
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello!"}],
)
if response.stop_reason == "end_turn":
# 完全なレスポンスを処理する
for block in response.content:
if block.type == "text":
print(block.text)Claudeがリクエストで指定されたmax_tokensの制限に達したため停止しました。
client = anthropic.Anthropic()
# トークン数を制限したリクエスト
response = client.messages.create(
model="claude-opus-5",
max_tokens=10,
messages=[{"role": "user", "content": "Explain quantum physics"}],
)
if response.stop_reason == "max_tokens":
# レスポンスが切り詰められました
print("Response was cut off at token limit")
# 続きを取得するには追加のリクエストを検討してくださいClaudeがカスタム停止シーケンスのいずれかに遭遇しました。
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
stop_sequences=["END", "STOP"],
messages=[{"role": "user", "content": "Generate text until you say END"}],
)
if response.stop_reason == "stop_sequence":
print(f"Stopped at sequence: {response.stop_sequence}")Claudeがツールを呼び出しており、実行を期待しています。
client = anthropic.Anthropic()
weather_tool = {
"name": "get_weather",
"description": "Get the current weather in a given location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City and state"},
},
"required": ["location"],
},
}
def execute_tool(name, tool_input):
"""Execute a tool and return the result."""
return f"Weather in {tool_input.get('location', 'unknown')}: 72°F"
response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
tools=[weather_tool],
messages=[{"role": "user", "content": "What is the weather in San Francisco?"}],
)
if response.stop_reason == "tool_use":
# ツールを抽出して実行
for block in response.content:
if block.type == "tool_use":
result = execute_tool(block.name, block.input)
# 最終レスポンスのために結果をClaudeに返すtool_useレスポンスには、idに対応する結果ブロックがないserver_tool_useブロックが含まれることもあります。そのサーバーツール呼び出しは完了しておらず、このレスポンスにはその結果が含まれていません。一般的なケースでは、Claudeがサーバーツールとクライアントツールのいずれかを同じ並列ツール呼び出しグループ内で呼び出します。この場合、APIはクライアントツールを先に実行できるように、サーバーツールを実行せずに返します。この状態を示す他のマーカーはありません。各server_tool_useまたはmcp_tool_useブロックのidに対応する結果ブロックがあるかどうかを確認することで検出してください。
{
"stop_reason": "tool_use",
"content": [
{
"type": "server_tool_use",
"id": "srvtoolu_01HxbWnMRmbWyMfUtJKC45rA",
"name": "web_search",
"input": { "query": "example article" }
},
{
"type": "tool_use",
"id": "toolu_01PjgRJLbXrXEMZwDNYLnBqk",
"name": "run_command",
"input": { "command": "uname -a" }
}
]
}継続は、レスポンス内のすべてのtool_useブロックに対して1つずつtool_resultブロックを含むユーザーメッセージです(ツール呼び出しの処理を参照)。ただし、2つの追加ルールがあります。そのメッセージにはtool_resultブロック以外を含めてはならず、リクエストは同じtools配列を維持する必要があります。待機中のサーバーツールを定義しなくなった再開リクエストは、but no `web_search` tool was providedで終わるメッセージを持つ400エラーで失敗します。APIは結果をまだ開いているアシスタントターンに添付し、遅延されたサーバーツールを実行し(一時停止されたコード実行の場合は再開し)、ターンを続行します。Claudeが直接呼び出したサーバーツールの場合、次のレスポンスのcontentは、前のレスポンスのserver_tool_useのidに対応する結果ブロックから始まります。
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01PjgRJLbXrXEMZwDNYLnBqk",
"content": "Linux demo-host 6.8.0-52-generic x86_64 GNU/Linux"
}
]
}そのユーザーメッセージのtool_resultブロックの後にテキストなどを追加すると、アシスタントターンが終了します。Claudeが直接呼び出したサーバーツールの場合、リクエストは未解決のサーバーツールを指定する400 invalid_request_errorで失敗します:
`web_search` tool use with id `srvtoolu_01HxbWnMRmbWyMfUtJKC45rA` was found without a corresponding `web_search_tool_result` blocktool_resultを省略したり、他のコンテンツの後に配置したりすると、代わりに標準のtool_use ids were found without tool_result blocks immediately afterエラーでより早く失敗します。Claudeに追加の入力を与えるには、ターンが完了した後に別のユーザーメッセージとして送信してください。
ウェブ検索などのサーバーツールを実行中に、サーバー側のサンプリングループが反復制限に達した場合に返されます。デフォルトの制限はリクエストあたり10回の反復です。
これが発生した場合、レスポンスには対応する結果ブロックのないserver_tool_useブロックが含まれることがあります。Claudeに処理を完了させるには、レスポンスをそのまま送り返して会話を続行してください。クライアントのtool_useブロックがあなたの対応を待っている状態のレスポンスでは、stop_reasonがpause_turnになることはありません。Claudeがツールを呼び出すために停止した場合、stop_reasonはtool_useであり、レスポンス自体ではなくクライアントのtool_resultブロックを送信することで続行します。
response = client.messages.create(
model="claude-opus-5",
max_tokens=4096,
tools=[{"type": "web_search_20250305", "name": "web_search"}],
messages=[{"role": "user", "content": "Search for latest AI news"}],
)
if response.stop_reason == "pause_turn":
# レスポンスを送り返して会話を続けます
messages = [
{"role": "user", "content": "Search for latest AI news"},
{"role": "assistant", "content": response.content},
]
continuation = client.messages.create(
model="claude-opus-5",
max_tokens=4096,
messages=messages,
tools=[{"type": "web_search_20250305", "name": "web_search"}],
)Claudeがレスポンスの生成を拒否しました。安全性分類器は、この停止理由をエラーではなく通常のHTTP 200レスポンスとして返します。
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
messages=[{"role": "user", "content": "[Unsafe request]"}],
)
if response.stop_reason == "refusal":
# Claudeが応答を拒否しました
print("Claude was unable to process this request")
# リクエストの言い換えや修正を検討してください拒否の場合、stop_detailsオブジェクトはそれをトリガーしたポリシーカテゴリを識別します。カテゴリと完全な拒否レスポンスの形式については、拒否とフォールバックで説明しています。stop_detailsは、refusal以外のすべての停止理由ではnullです。
Claude Fable 5またはClaude Opus 5で拒否されたリクエストは、通常、別のClaudeモデルで再試行することで処理できます。拒否とフォールバックでは、サーバー側またはクライアントでその再試行を設定する方法を示しています。フォールバッククレジットでは、自分で再試行を構築する際にプロンプトキャッシュのコストを二重に支払わないようにする方法を説明しています。
Claudeがモデルのコンテキストウィンドウの制限に達したため停止しました。これにより、正確な入力サイズを知らなくても、可能な限り最大のトークンをリクエストできます。
# できるだけ多く取得するために最大トークン数でリクエスト
response = client.beta.messages.create(
model="claude-opus-5",
max_tokens=20000, # Python SDK requires streaming for max_tokens above ~21k
messages=[
{"role": "user", "content": "Large input that uses most of context window..."}
],
)
if response.stop_reason == "model_context_window_exceeded":
# レスポンスがmax_tokensより先にコンテキストウィンドウの上限に達した
print("Response reached model's context window limit")
# レスポンスは有効ですが、コンテキストウィンドウによって制限されましたレスポンス処理ロジックでstop_reasonを確認することを習慣にしてください:
def handle_response(response):
if response.stop_reason == "tool_use":
return handle_tool_use(response)
elif response.stop_reason == "max_tokens":
return handle_truncation(response)
elif response.stop_reason == "model_context_window_exceeded":
return handle_context_limit(response)
elif response.stop_reason == "pause_turn":
return handle_pause(response)
elif response.stop_reason == "refusal":
return handle_refusal(response)
else:
# end_turnやその他のケースを処理
return next(
(block.text for block in response.content if block.type == "text"), ""
)トークン制限またはコンテキストウィンドウによってレスポンスが切り捨てられた場合は、出力が不完全であることを読者に知らせる通知を追加してください。代わりにレスポンスが中断した箇所から生成を続行するには、完全なレスポンスの確保を参照してください。
def handle_truncated_response(response):
text = next((block.text for block in response.content if block.type == "text"), "")
if response.stop_reason in ["max_tokens", "model_context_window_exceeded"]:
if response.stop_reason == "max_tokens":
note = "[Response truncated due to max_tokens limit]"
else:
note = "[Response truncated due to context window limit]"
return f"{text}\n\n{note}"
return textサーバーツールを使用する場合、サーバー側のサンプリングループが反復制限(デフォルト10)に達すると、APIはpause_turnを返すことがあります。会話を続行することでこれを処理してください:
def handle_server_tool_conversation(client, user_query, tools, max_continuations=5):
"""
Handle server tool conversations that may require multiple continuations.
The server runs a sampling loop when executing server tools. If the loop
reaches its iteration limit, the API returns pause_turn. Continue the
conversation by sending the response back to let Claude finish.
"""
messages = [{"role": "user", "content": user_query}]
for _ in range(max_continuations):
response = client.messages.create(
model="claude-opus-5", max_tokens=4096, messages=messages, tools=tools
)
if response.stop_reason != "pause_turn":
# Claudeが処理を完了しました - 最終レスポンスを返します
return response
# pause_turn: ロールの交互性を維持するためメッセージリスト全体を置き換えます
messages = [
{"role": "user", "content": user_query},
{"role": "assistant", "content": response.content},
]
# 最大継続回数に達しました - 最後のレスポンスを返します
return responsestop_reason値と実際のエラーを区別することが重要です:
client = anthropic.Anthropic()
try:
response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello!"}],
)
# stop_reasonを含む成功レスポンスを処理
if response.stop_reason == "max_tokens":
print("Response was truncated")
except anthropic.APIStatusError as e:
# 実際のエラーを処理
if e.status_code == 429:
print("Rate limit exceeded")
elif e.status_code == 500:
print("Server error")ストリーミングを使用する場合、stop_reasonは:
message_startイベントではnullmessage_deltaイベントで提供されるclient = anthropic.Anthropic()
with client.messages.stream(
model="claude-opus-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello!"}],
) as stream:
for event in stream:
if event.type == "message_delta":
stop_reason = event.delta.stop_reason
if stop_reason:
print(f"Stream ended with: {stop_reason}")def complete_tool_workflow(client, user_query, tools):
messages = [{"role": "user", "content": user_query}]
while True:
response = client.messages.create(
model="claude-opus-5", max_tokens=1024, messages=messages, tools=tools
)
if response.stop_reason == "tool_use":
# ツールを実行して続行
tool_results = execute_tools(response.content)
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
else:
# 最終レスポンス
return responsedef get_complete_response(client, prompt, max_attempts=3):
messages = [{"role": "user", "content": prompt}]
full_response = ""
for _ in range(max_attempts):
response = client.messages.create(
model="claude-opus-5", messages=messages, max_tokens=4096
)
full_response += next(
(block.text for block in response.content if block.type == "text"), ""
)
if response.stop_reason != "max_tokens":
break
# 中断した箇所から続行
messages = [
{"role": "user", "content": prompt},
{"role": "assistant", "content": full_response},
{"role": "user", "content": "Please continue from where you left off."},
]
return full_responsemodel_context_window_exceeded停止理由により、入力サイズを計算せずに可能な限り最大のトークンをリクエストできます:
def get_max_possible_tokens(client, prompt):
"""
Get as many tokens as possible within the model's context window
without needing to calculate input token count
"""
response = client.beta.messages.create(
model="claude-opus-5",
messages=[{"role": "user", "content": prompt}],
max_tokens=20000, # Python SDK requires streaming for max_tokens above ~21k
)
if response.stop_reason == "model_context_window_exceeded":
# 入力サイズに対して可能な最大トークン数を取得しました
print(
f"Generated {response.usage.output_tokens} tokens (context limit reached)"
)
elif response.stop_reason == "max_tokens":
# リクエストしたトークン数を正確に取得しました
print(f"Generated {response.usage.output_tokens} tokens (max_tokens reached)")
else:
# 自然な完了
print(f"Generated {response.usage.output_tokens} tokens (natural completion)")
return next((block.text for block in response.content if block.type == "text"), "")拒否されたリクエストをサーバー側またはクライアントでフォールバックモデルに再試行します。
SDKにtool_useループ、結果のフォーマット、再試行を管理させます。
ストリーミング時にmessage_deltaイベントからstop_reasonを読み取ります。
停止理由とは異なる4xxおよび5xx HTTPエラーを処理します。
Was this page helpful?