Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K

    第一步

    Claude 介紹快速入門

    模型與定價

    模型概覽選擇模型Claude 4.5 的新功能遷移到 Claude 4.5模型棄用定價

    使用 Claude 建構

    功能概覽使用 Messages API上下文視窗提示詞最佳實踐

    功能

    提示詞快取上下文編輯延伸思考串流訊息批次處理引用多語言支援Token 計數嵌入向量視覺PDF 支援Files API搜尋結果Google Sheets 附加元件

    工具

    概述如何實現工具使用代幣高效工具使用細粒度工具串流Bash 工具代碼執行工具電腦使用工具文字編輯工具網頁擷取工具網路搜尋工具記憶工具

    代理技能

    概述在 API 中開始使用 Agent Skills技能編寫最佳實踐使用 Agent Skills 與 API

    Agent SDK

    概述Agent SDK 參考 - TypeScriptPython SDK

    指南

    串流輸入處理權限會話管理託管 Agent SDK修改系統提示SDK 中的 MCP自訂工具SDK 中的子代理SDK 中的斜線命令SDK 中的代理技能追蹤成本和使用量待辦事項清單SDK 中的外掛程式

    API 中的 MCP

    MCP 連接器遠端 MCP 伺服器

    Claude 在第三方平台上

    Amazon BedrockVertex AI

    提示工程

    概述提示詞生成器使用提示模板提示詞改進器保持清晰和直接使用範例(多樣提示)讓 Claude 思考(思維鏈)使用 XML 標籤給 Claude 分配角色(系統提示詞)預填 Claude 的回應串接複雜提示長文本技巧延伸思考技巧

    測試與評估

    定義成功標準開發測試案例使用評估工具降低延遲

    加強防護措施

    減少幻覺提高輸出一致性防範越獄handle-streaming-refusals減少提示詞洩漏保持 Claude 的角色特性

    管理和監控

    Admin API 概述使用量和成本 APIClaude Code 分析 API
    Console
    指南

    會話管理

    了解 Claude Agent SDK 如何處理會話和會話恢復

    會話管理

    Claude Agent SDK 提供會話管理功能,用於處理對話狀態和恢復。會話允許您在多次互動中繼續對話,同時保持完整的上下文。

    會話如何運作

    當您開始新的查詢時,SDK 會自動創建一個會話,並在初始系統消息中返回會話 ID。您可以捕獲此 ID 以便稍後恢復會話。

    獲取會話 ID

    TypeScript
    import { query } from "@anthropic-ai/claude-agent-sdk"
    
    let sessionId: string | undefined
    
    const response = query({
      prompt: "幫我建立一個網頁應用程式",
      options: {
        model: "claude-sonnet-4-5"
      }
    })
    
    for await (const message of response) {
      // 第一條消息是包含會話 ID 的系統初始化消息
      if (message.type === 'system' && message.subtype === 'init') {
        sessionId = message.session_id
        console.log(`會話已開始,ID:${sessionId}`)
        // 您可以保存此 ID 以供稍後恢復
      }
    
      // 處理其他消息...
      console.log(message)
    }
    
    // 稍後,您可以使用保存的 sessionId 來恢復
    if (sessionId) {
      const resumedResponse = query({
        prompt: "從我們停下的地方繼續",
        options: {
          resume: sessionId
        }
      })
    }
    Python
    from claude_agent_sdk import query, ClaudeAgentOptions
    
    session_id = None
    
    async for message in query(
        prompt="幫我建立一個網頁應用程式",
        options=ClaudeAgentOptions(
            model="claude-sonnet-4-5"
        )
    ):
        # 第一條消息是包含會話 ID 的系統初始化消息
        if hasattr(message, 'subtype') and message.subtype == 'init':
            session_id = message.data.get('session_id')
            print(f"會話已開始,ID:{session_id}")
            # 您可以保存此 ID 以供稍後恢復
    
        # 處理其他消息...
        print(message)
    
    # 稍後,您可以使用保存的 session_id 來恢復
    if session_id:
        async for message in query(
            prompt="從我們停下的地方繼續",
            options=ClaudeAgentOptions(
                resume=session_id
            )
        ):
            print(message)

    恢復會話

    SDK 支援從先前的對話狀態恢復會話,實現連續的開發工作流程。使用 resume 選項配合會話 ID 來繼續先前的對話。

    import { query } from "@anthropic-ai/claude-agent-sdk"
    
    // 使用會話 ID 恢復先前的會話
    const response = query({
      prompt: "從我們停下的地方繼續實作身份驗證系統",
      options: {
        resume: "session-xyz", // 來自先前對話的會話 ID
        model: "claude-sonnet-4-5",
        allowedTools: ["Read", "Edit", "Write", "Glob", "Grep", "Bash"]
      }
    })
    
    // 對話會繼續,並保持先前會話的完整上下文
    for await (const message of response) {
      console.log(message)
    }

    當您恢復會話時,SDK 會自動處理載入對話歷史和上下文,讓 Claude 能夠從停下的地方完全繼續。

    分叉會話

    當恢復會話時,您可以選擇繼續原始會話或將其分叉為新的分支。預設情況下,恢復會繼續原始會話。使用 forkSession 選項(TypeScript)或 fork_session 選項(Python)來創建一個從恢復狀態開始的新會話 ID。

    何時分叉會話

    分叉在以下情況下很有用:

    • 從同一起點探索不同的方法
    • 創建多個對話分支而不修改原始對話
    • 測試更改而不影響原始會話歷史
    • 為不同實驗維護獨立的對話路徑

    分叉與繼續

    行為forkSession: false(預設)forkSession: true
    會話 ID與原始相同生成新的會話 ID
    歷史附加到原始會話從恢復點創建新分支
    原始會話被修改保持不變
    使用情況繼續線性對話分支探索替代方案

    範例:分叉會話

    import { query } from "@anthropic-ai/claude-agent-sdk"
    
    // 首先,捕獲會話 ID
    let sessionId: string | undefined
    
    const response = query({
      prompt: "幫我設計一個 REST API",
      options: { model: "claude-sonnet-4-5" }
    })
    
    for await (const message of response) {
      if (message.type === 'system' && message.subtype === 'init') {
        sessionId = message.session_id
        console.log(`原始會話:${sessionId}`)
      }
    }
    
    // 分叉會話以嘗試不同的方法
    const forkedResponse = query({
      prompt: "現在讓我們將其重新設計為 GraphQL API",
      options: {
        resume: sessionId,
        forkSession: true,  // 創建新的會話 ID
        model: "claude-sonnet-4-5"
      }
    })
    
    for await (const message of forkedResponse) {
      if (message.type === 'system' && message.subtype === 'init') {
        console.log(`分叉會話:${message.session_id}`)
        // 這將是不同的會話 ID
      }
    }
    
    // 原始會話保持不變,仍可恢復
    const originalContinued = query({
      prompt: "為 REST API 添加身份驗證",
      options: {
        resume: sessionId,
        forkSession: false,  // 繼續原始會話(預設)
        model: "claude-sonnet-4-5"
      }
    })
    • 獲取會話 ID
    © 2025 ANTHROPIC PBC

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

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

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    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

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

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

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

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

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    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

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    © 2025 ANTHROPIC PBC