Loading...
    • 개발자 가이드
    • API 레퍼런스
    • MCP
    • 리소스
    • 릴리스 노트
    Search...
    ⌘K
    시작하기
    Claude 소개빠른 시작
    모델 및 가격
    모델 개요모델 선택Claude 4.6의 새로운 기능마이그레이션 가이드모델 지원 중단가격
    Claude로 구축하기
    기능 개요Messages API 사용중지 사유 처리프롬프트 모범 사례
    컨텍스트 관리
    컨텍스트 윈도우압축컨텍스트 편집
    기능
    프롬프트 캐싱확장 사고적응형 사고노력 수준메시지 스트리밍배치 처리인용다국어 지원토큰 카운팅임베딩비전PDF 지원Files API검색 결과구조화된 출력
    도구
    개요도구 사용 구현 방법세분화된 도구 스트리밍Bash 도구코드 실행 도구프로그래밍 방식 도구 호출컴퓨터 사용 도구텍스트 편집기 도구웹 페치 도구웹 검색 도구메모리 도구도구 검색 도구
    Agent Skills
    개요빠른 시작모범 사례엔터프라이즈용 SkillsAPI로 Skills 사용
    Agent SDK
    개요빠른 시작TypeScript SDKTypeScript V2 (미리보기)Python SDK마이그레이션 가이드
    스트리밍 입력실시간 응답 스트리밍중지 사유 처리권한 처리사용자 승인 및 입력훅으로 실행 제어세션 관리파일 체크포인팅SDK에서 구조화된 출력Agent SDK 호스팅AI 에이전트 안전한 배포시스템 프롬프트 수정SDK에서 MCP커스텀 도구SDK에서 서브에이전트SDK에서 슬래시 명령어SDK에서 Agent Skills비용 및 사용량 추적할 일 목록SDK에서 플러그인
    API에서 MCP
    MCP 커넥터원격 MCP 서버
    서드파티 플랫폼의 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    프롬프트 엔지니어링
    개요프롬프트 생성기프롬프트 템플릿 사용프롬프트 개선기명확하고 직접적으로 작성예시 사용 (멀티샷 프롬프팅)Claude에게 생각하게 하기 (CoT)XML 태그 사용Claude에게 역할 부여 (시스템 프롬프트)복잡한 프롬프트 연결긴 컨텍스트 팁확장 사고 팁
    테스트 및 평가
    성공 기준 정의테스트 케이스 개발평가 도구 사용지연 시간 줄이기
    가드레일 강화
    환각 줄이기출력 일관성 높이기탈옥 방지스트리밍 거부프롬프트 유출 줄이기Claude 캐릭터 유지
    관리 및 모니터링
    Admin API 개요데이터 상주워크스페이스사용량 및 비용 APIClaude Code Analytics API제로 데이터 보존
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    가이드

    중지 이유 처리

    Agent SDK에서 결과 메시지로부터 거부 및 기타 중지 이유를 직접 감지하기

    Was this page helpful?

    • stop_reason 읽기

    결과 메시지의 stop_reason 필드는 모델이 생성을 중지한 이유를 알려줍니다. 이는 거부, 최대 토큰 제한 및 기타 종료 조건을 감지하는 권장 방법입니다(스트림 파싱이 필요하지 않습니다).

    stop_reason은 스트리밍 활성화 여부와 관계없이 모든 ResultMessage에서 사용할 수 있습니다. include_partial_messages(Python) 또는 includePartialMessages(TypeScript)를 설정할 필요가 없습니다.

    stop_reason 읽기

    stop_reason 필드는 성공 및 오류 결과 메시지 모두에 존재합니다. 메시지 스트림을 반복한 후 확인하세요:

    from claude_agent_sdk import query, ResultMessage
    import asyncio
    
    async def check_stop_reason():
        async for message in query(prompt="Write a poem about the ocean"):
            if isinstance(message, ResultMessage):
                print(f"Stop reason: {message.stop_reason}")
                if message.stop_reason == "refusal":
                    print("The model declined this request.")
    
    asyncio.run(check_stop_reason())

    사용 가능한 중지 이유

    중지 이유의미
    end_turn모델이 정상적으로 응답 생성을 완료했습니다.
    max_tokens응답이 최대 출력 토큰 제한에 도달했습니다.
    stop_sequence모델이 구성된 중지 시퀀스를 생성했습니다.
    refusal모델이 요청 수행을 거부했습니다.
    tool_use모델의 최종 출력이 도구 호출이었습니다. SDK 결과에서는 도구 호출이 결과 반환 전에 일반적으로 실행되므로 이는 드문 경우입니다.
    nullAPI 응답을 받지 못했습니다. 예를 들어, 첫 번째 요청 전에 오류가 발생했거나 캐시된 세션에서 결과가 재생된 경우입니다.

    오류 결과의 중지 이유

    오류 결과(error_max_turns 또는 error_during_execution 등)에도 stop_reason이 포함됩니다. 이 값은 오류가 발생하기 전에 수신된 마지막 어시스턴트 메시지를 반영합니다:

    결과 변형stop_reason 값
    success최종 어시스턴트 메시지의 중지 이유.
    error_max_turns턴 제한에 도달하기 전 마지막 어시스턴트 메시지의 중지 이유.
    error_max_budget_usd예산이 초과되기 전 마지막 어시스턴트 메시지의 중지 이유.
    error_max_structured_output_retries재시도 제한에 도달하기 전 마지막 어시스턴트 메시지의 중지 이유.
    error_during_execution마지막으로 확인된 중지 이유, 또는 API 응답 전에 오류가 발생한 경우 null.

    거부 감지

    stop_reason === "refusal"은 모델이 요청을 거부할 때 이를 감지하는 가장 간단한 방법입니다. 이전에는 거부를 감지하려면 부분 메시지 스트리밍을 활성화하고 StreamEvent 메시지에서 message_delta 이벤트를 수동으로 스캔해야 했습니다. 결과 메시지의 stop_reason을 사용하면 직접 확인할 수 있습니다:

    다음 단계

    • 실시간 응답 스트리밍: message_delta를 포함한 원시 API 이벤트를 도착하는 대로 접근
    • 구조화된 출력: 에이전트로부터 타입이 지정된 JSON 응답 받기
    • 비용 및 사용량 추적: 결과 메시지에서 토큰 사용량 및 청구 정보 이해
    from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
    import asyncio
    
    async def handle_max_turns():
        options = ClaudeAgentOptions(max_turns=3)
    
        async for message in query(prompt="Refactor this module", options=options):
            if isinstance(message, ResultMessage):
                if message.subtype == "error_max_turns":
                    print(f"Hit turn limit. Last stop reason: {message.stop_reason}")
                    # stop_reason might be "end_turn" or "tool_use"
                    # depending on what the model was doing when the limit hit
    
    asyncio.run(handle_max_turns())
    from claude_agent_sdk import query, ResultMessage
    import asyncio
    
    async def safe_query(prompt: str):
        async for message in query(prompt=prompt):
            if isinstance(message, ResultMessage):
                if message.stop_reason == "refusal":
                    print("Request was declined. Please revise your prompt.")
                    return None
                return message.result
        return None
    
    asyncio.run(safe_query("Summarize this article"))