Claude Platform Docs
MessagesClaude로 구축하기

중지 이유와 폴백

각 stop_reason 값의 의미와 애플리케이션에서 잘림, 도구 사용, 일시 중지된 턴, 거부를 처리하는 방법을 알아보세요.

모든 Messages API 응답에는 Claude가 생성을 중지한 이유를 알려주는 stop_reasonAPI 참조 링크가 포함된 미리보기 사용 가능 — 카드에 포커스가 들어올 때까지 Tab을 누르고, 돌아가려면 Escape를 누르세요. 필드가 포함되어 있습니다. 이 필드를 확인하여 응답을 그대로 사용할지, 대화를 계속할지, 재시도할지, 아니면 다른 모델로 폴백할지 결정하세요.

전체 응답 스키마는 Messages API 레퍼런스API 참조 링크가 포함된 미리보기 사용 가능 — 카드에 포커스가 들어올 때까지 Tab을 누르고, 돌아가려면 Escape를 누르세요.를 참조하세요.

빠른 참조

값발생 시점해야 할 일
end_turnClaude가 자연스럽게 응답을 완료했습니다.응답을 사용하세요.
max_tokens응답이 max_tokens 한도에 도달했습니다.max_tokens를 늘리거나 응답을 이어서 생성하세요.
stop_sequenceClaude가 stop_sequences 중 하나를 출력했습니다.stop_sequence를 읽어 어느 것이 발동했는지 확인하세요.
tool_useClaude가 도구를 호출하고 있습니다.도구를 실행하고 결과를 반환하세요. 결과 블록이 아직 없는 서버 도구 호출은 이후 응답에서 완료됩니다.
pause_turn서버 도구 루프가 반복 한도에 도달했습니다.어시스턴트 콘텐츠를 다시 보내 계속하세요.
refusalClaude가 응답을 거부했습니다.stop_details를 읽고 폴백 모델에서 재시도하세요.
model_context_window_exceeded응답이 모델의 컨텍스트 윈도우를 가득 채웠습니다.응답을 잘린 것으로 처리하세요.

stop_reason 필드

stop_reason 필드는 모든 성공적인 Messages API 응답의 일부입니다. 요청 처리 실패를 나타내는 오류와 달리, stop_reason은 Claude가 응답 생성을 완료한 이유를 알려줍니다.

Example response
{
  "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
  }
}

중지 이유 값

end_turn

가장 일반적인 중지 이유입니다. Claude가 자연스럽게 응답을 완료했음을 나타냅니다.

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-opus-5-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)

max_tokens

Claude가 요청에 지정된 max_tokensAPI 참조 링크가 포함된 미리보기 사용 가능 — 카드에 포커스가 들어올 때까지 Tab을 누르고, 돌아가려면 Escape를 누르세요. 한도에 도달하여 중지했습니다.

client = anthropic.Anthropic()
# 제한된 토큰으로 요청합니다
response = client.messages.create(
    model="claude-opus-5-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")
    # 이어서 받으려면 추가 요청을 보내는 것을 고려하세요

stop_sequence

Claude가 사용자 지정 중지 시퀀스API 참조 링크가 포함된 미리보기 사용 가능 — 카드에 포커스가 들어올 때까지 Tab을 누르고, 돌아가려면 Escape를 누르세요. 중 하나를 만났습니다.

client = anthropic.Anthropic()
response = client.messages.create(
    model="claude-opus-5-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}")

tool_use

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):
    """Run 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-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에 반환합니다

서버 도구가 아직 대기 중인 경우

Claude는 같은 병렬 도구 호출 그룹에서 서버 도구와 클라이언트 도구(사용자의 코드가 실행하는 도구)를 함께 호출할 수 있습니다. 그러면 API는 사용자가 클라이언트 도구를 먼저 실행할 수 있도록 서버 도구를 실행하지 않고 tool_use 응답을 반환합니다.

대기 중인 호출은 결과 블록이 없는 server_tool_use 또는 mcp_tool_use 블록입니다. 응답에서 이를 나타내는 다른 표시는 없습니다. 서버 도구가 실행된 후에는 web_search_tool_result와 같은 해당 결과 블록이 tool_use_id 필드에 호출의 id를 담습니다.

다음 혼합 응답에는 대기 중인 서버 도구와 클라이언트 도구 호출이 있습니다:

A mixed tool_use response
{
  "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" }
    }
  ]
}

이와 같은 혼합 응답에서 계속하려면 후속 요청을 구성하세요:

  1. 이전 메시지를 유지하고 응답의 content를 변경하지 않은 채 assistant 메시지로 추가합니다.
  2. 각 클라이언트 tool_use 블록마다 하나씩 tool_result 블록만 포함하는 사용자 메시지를 추가합니다. 대기 중인 호출에는 아무것도 추가하지 않습니다.
  3. 대기 중인 서버 도구가 계속 정의되어 있도록 이전과 동일한 tools 배열로 요청을 보냅니다.

tool_result 블록의 필드는 도구 호출 처리를 참조하세요. 후속 요청의 사용자 메시지는 다음과 같습니다:

The follow-up user message
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01PjgRJLbXrXEMZwDNYLnBqk",
      "content": "Linux demo-host 6.8.0-52-generic x86_64 GNU/Linux"
    }
  ]
}

API는 사용자의 결과를 Claude의 완료되지 않은 턴에 추가하고, 대기 중인 서버 도구를 실행한 다음 계속 진행합니다. Claude가 직접 호출한 서버 도구의 경우, 다음 응답의 content는 해당 도구의 결과 블록으로 시작합니다.

모든 tool_use 응답에 대해 앞의 단계를 따르는 루프는 대기 중인 서버 도구를 감지할 필요가 없습니다. 이후 요청에서는 messages에 세 개의 개별 메시지를 다음 순서로 유지하세요: 첫 번째 응답, 사용자의 tool_result 메시지, 그다음 응답.

다음 두 경우에는 후속 요청에 필드가 하나 더 필요합니다:

  • 응답에 container가 포함된 경우: 해당 ID를 다시 보내세요(코드 실행 도구의 컨테이너 재사용 섹션 참조).
  • 대기 중인 블록이 mcp_tool_use 블록인 경우: 이전과 동일한 mcp_servers를 보내세요.

후속 요청에서 다음과 같은 실수는 각각 400 invalid_request_error로 실패합니다. 표시된 메시지는 웹 검색의 경우입니다. 다른 서버 도구의 경우 메시지에 포함된 이름이 다릅니다.

실수오류 메시지에 포함되는 내용
tools가 더 이상 대기 중인 서버 도구를 정의하지 않음but no `web_search` tool was provided
tool_result 블록 뒤에 텍스트 또는 기타 콘텐츠가 옴was found without a corresponding `web_search_tool_result` block
프로그래매틱 도구 호출에서 tool_result 블록 뒤에 텍스트 또는 기타 콘텐츠가 옴only tool_result blocks are allowed
tool_result 블록 앞에 텍스트 또는 기타 콘텐츠가 옴`tool_use` ids were found without `tool_result` blocks immediately after
tool_result 블록이 누락됨`tool_use` ids were found without `tool_result` blocks immediately after

tool_result 블록 뒤의 콘텐츠는 서버 도구가 아직 대기 중인 상태에서 Claude의 턴을 종료하므로 실패합니다. Claude에게 추가 입력을 제공하려면 응답의 stop_reason이 tool_use도 pause_turn도 아닐 때까지 계속 진행하세요. 그런 다음 같은 messages 목록에 새 사용자 메시지로 입력을 보내세요.

pause_turn

웹 검색과 같은 서버 도구를 실행하는 동안 서버 측 샘플링 루프가 반복 한도에 도달하면 반환됩니다. 기본 한도는 요청당 10회 반복입니다.

Claude가 사용자가 실행하는 도구를 호출하기 위해 중지하면 중지 이유는 tool_use이며, 절대 pause_turn이 아닙니다.

Claude가 일시 중지된 턴을 완료할 수 있도록 새 요청을 구성하세요:

  1. 이전 메시지를 유지하고, 결과 블록이 없는 server_tool_use 블록을 포함하여 응답의 content를 변경하지 않은 채 assistant 메시지로 추가합니다.
  2. 이전과 동일한 tools로, assistant 메시지 뒤에 사용자 메시지 없이 요청을 보냅니다.

응답에 container가 포함되어 있으면 턴이 파일을 유지할 수 있도록 해당 ID도 함께 다시 보내세요. 자세한 내용은 코드 실행 도구의 컨테이너 재사용 섹션을 참조하세요. 다음 예제는 웹 검색을 사용하며 컨테이너 ID를 보내지 않습니다:

response = client.messages.create(
    model="claude-opus-5-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-5",
        max_tokens=4096,
        messages=messages,
        tools=[{"type": "web_search_20250305", "name": "web_search"}],
    )

애플리케이션은 서버 도구를 사용하는 모든 에이전트 루프에서 pause_turn을 처리해야 합니다. 반복되는 일시 중지를 처리하고 컨테이너 ID를 다시 보내는 루프는 pause_turn에 대한 재시도 로직을 구현하세요를 참조하세요.

refusal

Claude가 응답 생성을 거부했습니다. 안전 분류기는 이 중지 이유를 오류가 아닌 정상적인 HTTP 200 응답으로 반환합니다.

client = anthropic.Anthropic()
response = client.messages.create(
    model="claude-opus-5-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_detailsAPI 참조 링크가 포함된 미리보기 사용 가능 — 카드에 포커스가 들어올 때까지 Tab을 누르고, 돌아가려면 Escape를 누르세요. 객체는 거부를 유발한 정책 카테고리를 식별합니다. 카테고리와 전체 거부 응답 형태는 거부의 모습에서 다룹니다. stop_details는 refusal 이외의 모든 중지 이유에서 null입니다.

거부된 요청은 일반적으로 다른 Claude 모델로 재시도하여 응답을 받을 수 있습니다. 이는 Claude Fable 5.2, Claude Fable 5.1, Claude Fable 5, Claude Opus 5.5, Claude Opus 5, Claude Sonnet 5.5 및 Claude Haiku 5.5에 적용됩니다. 거부와 폴백에서는 서버 측 또는 클라이언트에서 해당 재시도를 설정하는 방법을 보여줍니다. Claude Haiku 5.5에는 서버 측 폴백이 없으므로 재시도를 클라이언트 측 폴백으로 설정하세요. Claude Haiku 5.5를 제외한 이 모델들 중 하나에서 재시도를 직접 구축하는 경우, 폴백 크레딧에서 프롬프트 캐시 비용을 두 번 지불하지 않는 방법을 다룹니다.

reasoning_extraction 거부는 예외에 해당합니다. 추론을 사고 블록에 유지하기에서 설명하는 것처럼 다른 모델에서 재시도하는 대신 프롬프트를 변경하세요.

model_context_window_exceeded

Claude가 모델의 컨텍스트 윈도우 한도에 도달하여 중지했습니다. 이를 통해 정확한 입력 크기를 알지 못해도 가능한 최대 토큰을 요청할 수 있습니다.

client = anthropic.Anthropic()

# 가능한 한 많은 출력을 얻기 위해 최대 토큰으로 요청합니다
response = client.beta.messages.create(
    model="claude-opus-5-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에 도달하기 전에 "context window"(컨텍스트 윈도우) 한도에 도달했습니다
    print("Response reached model's context window limit")
    # 응답은 여전히 유효하지만 컨텍스트 윈도우에 의해 제한되었습니다

중지 이유 처리를 위한 모범 사례

항상 stop_reason을 확인하세요

응답 처리 로직에서 stop_reason을 확인하는 것을 습관화하세요:

def handle_response(response):
    match response.stop_reason:
        case "tool_use":
            return handle_tool_use(response)
        case "max_tokens":
            return handle_truncation(response)
        case "model_context_window_exceeded":
            return handle_context_limit(response)
        case "pause_turn":
            return handle_pause(response)
        case "refusal":
            return handle_refusal(response)
        case _:
            # 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

pause_turn에 대한 재시도 로직을 구현하세요

서버 도구를 사용할 때, 서버 측 샘플링 루프가 반복 한도(기본값 10)에 도달하면 API가 pause_turn을 반환할 수 있습니다. 이를 처리하려면 일시 중지된 응답을 변경하지 않은 채 메시지에 추가하고 요청을 다시 보내세요. 응답에 container가 포함되어 있으면 해당 ID도 함께 다시 보내세요. 그렇지 않으면 다음 요청에서 새 컨테이너가 시작되며, 해당 턴의 앞부분에서 생성된 파일이 손실됩니다.

client = anthropic.Anthropic()


def handle_server_tool_conversation(client, user_query, tools, max_requests=5):
    messages = [{"role": "user", "content": user_query}]
    container_id = None

    for _ in range(max_requests):
        response = client.messages.create(
            model="claude-opus-5-5",
            max_tokens=4096,
            messages=messages,
            tools=tools,
            container=container_id,
        )

        if response.stop_reason != "pause_turn":
            # 일시 중지되지 않음: 응답을 반환합니다
            return response

        # pause_turn: 일시 중지된 응답을 assistant 메시지로 추가한 후 계속합니다
        messages.append({"role": "assistant", "content": response.content})

        # 도구가 컨테이너에서 실행된 경우, 파일이 유지되도록 컨테이너 ID를 다시 전송합니다
        if response.container:
            container_id = response.container.id

    # max_requests번 요청 후에도 여전히 일시 중지됨: 마지막 응답을 반환합니다
    return response


response = handle_server_tool_conversation(
    client,
    "Use the code execution tool to find the 1,000th prime number.",
    [{"type": "code_execution_20250825", "name": "code_execution"}],
)
print(response.stop_reason)

이 함수는 마지막 응답을 반환하며, 이 응답에는 턴의 마지막 부분만 포함됩니다. 전체 턴을 표시하거나 대화를 계속하려면 일시 중지된 응답도 함께 보관하세요.

중지 이유와 오류의 비교

stop_reason 값과 실제 오류를 구분하는 것이 중요합니다:

중지 이유 (성공적인 응답)

  • 응답 본문의 일부
  • 생성이 정상적으로 중지된 이유를 나타냄
  • 응답에 유효한 콘텐츠가 포함됨

오류 (실패한 요청)

  • HTTP 상태 코드 4xx 또는 5xx
  • 요청 처리 실패를 나타냄
  • 응답에 오류 세부 정보가 포함됨
client = anthropic.Anthropic()

try:
    response = client.messages.create(
        model="claude-opus-5-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:
    # 실제 오류를 처리합니다
    match e.status_code:
        case 429:
            print("Rate limit exceeded")
        case 500:
            print("Server error")

스트리밍 고려 사항

스트리밍을 사용할 때 stop_reason은:

  • 초기 message_start 이벤트에서는 null
  • message_delta 이벤트에서 제공됨
  • 다른 어떤 이벤트에서도 제공되지 않음
client = anthropic.Anthropic()

with client.messages.stream(
    model="claude-opus-5-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-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 response

완전한 응답 보장하기

def 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-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_response

입력 크기를 모르는 상태에서 최대 토큰 얻기

model_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-5",
        messages=[{"role": "user", "content": prompt}],
        max_tokens=20000,  # Python SDK requires streaming for max_tokens above ~21k
    )

    match response.stop_reason:
        case "model_context_window_exceeded":
            # 입력 크기를 고려해 가능한 최대 토큰 수를 받았습니다
            print(
                f"Generated {response.usage.output_tokens} tokens (context limit reached)"
            )
        case "max_tokens":
            # 요청한 토큰 수를 정확히 받았습니다
            print(
                f"Generated {response.usage.output_tokens} tokens (max_tokens reached)"
            )
        case _:
            # 자연스러운 완료
            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 오류를 처리하세요.

이 페이지가 도움이 되었나요?