V2 是实验性的会话 API,已标记为废弃,将在未来版本中移除。新项目应直接使用 V1 的 query() API。

核心机制

V2 的设计目标:简化多轮对话,避免 V1 中 async generator 的 yield 协调复杂性。V2 将发送和接收分离为独立步骤:

  • createSession() / resumeSession():创建或恢复会话
  • session.send():发送消息
  • session.stream():获取响应

V2 vs V1 对比:

场景V2V1
单次查询unstable_v2_prompt()query() + 迭代
多轮对话send() + stream() 循环需要 async generator 输入
会话恢复resumeSession(sessionId)query({ options: { resume: sessionId } })

关键细节

V2 基础用法:

import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";
 
await using session = unstable_v2_createSession({ model: "claude-opus-4-7" });
 
await session.send("Hello!");
for await (const msg of session.stream()) {
    if (msg.type === "assistant") {
        console.log(msg.message.content);
    }
}

V2 不支持的 V1 功能:

  • Session forking(forkSession 选项)
  • 部分高级流式输入模式

迁移到 V1:

// V2
await session.send("What is 5 + 3?");
for await (const msg of session.stream()) { ... }
 
// V1 等价
for await (const msg of query({ prompt: "What is 5 + 3?", options: { model: "..." } })) { ... }

与其他概念的关联

  • typescript - V1 TypeScript SDK 完整参考
  • sessions - V1 的会话管理(resume、fork 等)

实践要点

  • 所有 V2 函数名以 unstable_v2_ 开头,是废弃的明确信号
  • 现有 V2 代码应迁移到 V1 query() API
  • V2 的 send()/stream() 模式在 V1 中通过 async generator 输入实现
  • 参考 V2 examples on GitHub 了解迁移示例