Loading...
    • 开发者指南
    • API 参考
    • MCP
    • 资源
    • 发布说明
    Search...
    ⌘K
    快速开始
    Claude 简介快速入门
    模型与定价
    模型概览选择模型Claude 4.5 新功能迁移到 Claude 4.5模型弃用定价
    使用 Claude 构建
    功能概览使用 Messages API上下文窗口提示词最佳实践
    能力
    提示词缓存上下文编辑扩展思考工作量流式消息批量处理引用多语言支持Token 计数嵌入视觉PDF 支持Files API搜索结果结构化输出
    工具
    概览如何实现工具使用细粒度工具流式传输Bash 工具代码执行工具程序化工具调用计算机使用工具文本编辑器工具Web 获取工具Web 搜索工具内存工具工具搜索工具
    Agent Skills
    概览快速入门最佳实践在 API 中使用 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 的响应链接复杂提示词长上下文提示扩展思考提示
    测试与评估
    定义成功标准开发测试用例使用评估工具降低延迟
    加强防护栏
    减少幻觉提高输出一致性缓解越狱流式拒绝减少提示词泄露保持 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
    指南

    会话管理

    了解 Claude Agent SDK 如何处理会话和会话恢复

    会话管理

    Claude Agent SDK 提供会话管理功能,用于处理对话状态和恢复。会话允许您在多次交互中继续对话,同时保持完整的上下文。

    会话如何工作

    当您启动新查询时,SDK 会自动创建一个会话,并在初始系统消息中返回会话 ID。您可以捕获此 ID 以便稍后恢复会话。

    获取会话 ID

    import { query } from "@anthropic-ai/claude-agent-sdk"
    
    let sessionId: string | undefined
    
    const response = query({
      prompt: "Help me build a web application",
      options: {
        model: "claude-sonnet-4-5"
      }
    })
    
    for await (const message of response) {
      // The first message is a system init message with the session ID
      if (message.type === 'system' && message.subtype === 'init') {
        sessionId = message.session_id
        console.log(`Session started with ID: ${sessionId}`)
        // You can save this ID for later resumption
      }
    
      // Process other messages...
      console.log(message)
    }
    
    // Later, you can use the saved sessionId to resume
    if (sessionId) {
      const resumedResponse = query({
        prompt: "Continue where we left off",
        options: {
          resume: sessionId
        }
      })
    }

    恢复会话

    SDK 支持从之前的对话状态恢复会话,从而实现连续的开发工作流。使用 resume 选项和会话 ID 来继续之前的对话。

    import { query } from "@anthropic-ai/claude-agent-sdk"
    
    // Resume a previous session using its ID
    const response = query({
      prompt: "Continue implementing the authentication system from where we left off",
      options: {
        resume: "session-xyz", // Session ID from previous conversation
        model: "claude-sonnet-4-5",
        allowedTools: ["Read", "Edit", "Write", "Glob", "Grep", "Bash"]
      }
    })
    
    // The conversation continues with full context from the previous session
    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"
    
    // First, capture the session ID
    let sessionId: string | undefined
    
    const response = query({
      prompt: "Help me design a 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(`Original session: ${sessionId}`)
      }
    }
    
    // Fork the session to try a different approach
    const forkedResponse = query({
      prompt: "Now let's redesign this as a GraphQL API instead",
      options: {
        resume: sessionId,
        forkSession: true,  // Creates a new session ID
        model: "claude-sonnet-4-5"
      }
    })
    
    for await (const message of forkedResponse) {
      if (message.type === 'system' && message.subtype === 'init') {
        console.log(`Forked session: ${message.session_id}`)
        // This will be a different session ID
      }
    }
    
    // The original session remains unchanged and can still be resumed
    const originalContinued = query({
      prompt: "Add authentication to the REST API",
      options: {
        resume: sessionId,
        forkSession: false,  // Continue original session (default)
        model: "claude-sonnet-4-5"
      }
    })
    • 获取会话 ID