Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K
    入門
    Claude 簡介快速開始
    模型與定價
    模型概覽選擇模型Claude 4.6 新功能遷移指南模型棄用定價
    使用 Claude 構建
    功能概覽使用 Messages API處理停止原因提示詞最佳實踐
    上下文管理
    上下文視窗壓縮上下文編輯
    功能
    提示詞快取延伸思考自適應思考思考力度串流訊息批次處理引用多語言支援Token 計數嵌入視覺PDF 支援Files API搜尋結果結構化輸出
    工具
    概覽如何實作工具使用細粒度工具串流Bash 工具程式碼執行工具程式化工具呼叫電腦使用工具文字編輯器工具網頁擷取工具網頁搜尋工具記憶工具工具搜尋工具
    Agent Skills
    概覽快速開始最佳實踐企業級 Skills透過 API 使用 Skills
    Agent SDK
    概覽快速開始TypeScript SDKTypeScript V2(預覽版)Python SDK遷移指南
    串流輸入即時串流回應處理停止原因處理權限使用者核准與輸入使用 hooks 控制執行工作階段管理檔案檢查點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 中直接從結果訊息偵測拒絕和其他停止原因

    結果訊息上的 stop_reason 欄位告訴您模型為何停止生成。這是偵測拒絕、最大 token 限制和其他終止條件的建議方式(無需解析串流)。

    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回應達到了最大輸出 token 限制。
    stop_sequence模型生成了已配置的停止序列。
    refusal模型拒絕執行該請求。
    tool_use模型的最終輸出是工具呼叫。這在 SDK 結果中不常見,因為工具呼叫通常在返回結果之前就已執行。
    null未收到 API 回應;例如,在第一個請求之前發生了錯誤,或結果是從快取的工作階段重播的。

    錯誤結果上的停止原因

    錯誤結果(例如 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。
    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())

    偵測拒絕

    stop_reason === "refusal" 是偵測模型拒絕請求的最簡單方式。以前,偵測拒絕需要啟用部分訊息串流並手動掃描 StreamEvent 訊息中的 message_delta 事件。有了結果訊息上的 stop_reason,您可以直接檢查:

    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"))

    後續步驟

    • 即時串流回應:存取原始 API 事件,包括即時到達的 message_delta
    • 結構化輸出:從代理取得型別化的 JSON 回應
    • 追蹤成本和用量:從結果訊息了解 token 使用量和計費資訊

    Was this page helpful?

    • 讀取 stop_reason