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迁移指南
    流式输入实时流式响应处理停止原因处理权限用户审批与输入使用钩子控制执行会话管理文件检查点SDK 中的结构化输出托管 Agent SDK安全部署 AI 智能体修改系统提示词SDK 中的 MCP自定义工具SDK 中的子智能体SDK 中的斜杠命令SDK 中的 Agent Skills跟踪成本与用量待办事项列表SDK 中的插件
    API 中的 MCP
    MCP 连接器远程 MCP 服务器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示工程
    概览提示词生成器使用提示词模板提示词优化器清晰直接使用示例(多样本提示)让 Claude 思考(思维链)使用 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
    指南

    会话管理

    了解 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-opus-4-6"
      }
    })
    
    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-opus-4-6",
        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-opus-4-6" }
    })
    
    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-opus-4-6"
      }
    })
    
    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-opus-4-6"
      }
    })

    Was this page helpful?

    • 获取会话 ID