本页目录15
- V2 会话 API 已被移除:TypeScript Agent SDK 0.3.142 起不再提供 unstable_v2_createSession、unstable_v2_resumeSession、unstable_v2_prompt 以及 SDKSession/SDKSessionOptions 类型
- 如需维护旧代码,可通过 npm install @anthropic-ai/claude-agent-sdk@0.2 锁定到最后一个支持 V2 的版本
- 迁移路径:改用 query() API,配合 options.resume 续接会话,或传入 AsyncIterable<SDKUserMessage> 实现多轮对话
- V2 的设计是把发送与接收拆分为 session.send() 与 session.stream() 两步,避免像 V1 那样用单一 async generator 协调输入输出
- V2 不支持会话分叉(forkSession 选项)等部分高级功能,这些仍需使用 V1 SDK
本文是对 Claude Agent SDK 官方文档某页的中文整理,完整与最新内容以原文为准:https://code.claude.com/docs/en/agent-sdk/typescript-v2-preview
警告:V2 会话 API 已不再受支持。TypeScript Agent SDK 0.3.142 版本移除了
unstable_v2_createSession、unstable_v2_resumeSession、unstable_v2_prompt,以及SDKSession和SDKSessionOptions类型。若要迁移,请使用
query()API 及其接受的 session 选项。多轮对话请传入AsyncIterable<SDKUserMessage>,续接已保存的会话请使用options.resume。本页仅供仍维护 Agent SDK 0.2.x 及更早版本代码的开发者参考。
概述
V2 是一个实验性的会话 API,目的是去掉 async generator 与 yield 协调的复杂度。与在多轮之间管理 generator 状态不同,V2 中每一轮对话都是独立的 send() / stream() 循环。API 表面被简化为三个概念:
createSession()/resumeSession():开始或继续一段对话session.send():发送一条消息session.stream():获取响应
安装
Agent SDK 0.2.x 是最后一个包含 V2 接口的版本。包版本号从 0.2.x 直接跳到 0.3.142,因此上面提到的移除版本号与下面的安装锁定版本描述的是同一个分界点。要安装最后一个兼容 V2 的版本,需锁定主版本号和次版本号:
npm install @anthropic-ai/claude-agent-sdk@0.2
提示:SDK 会为你的平台捆绑一个原生的 Claude Code 二进制文件作为可选依赖,因此大多数安装不需要单独安装 Claude Code。具体哪些安装场景仍需要,参见 快速上手中的安装说明。
快速上手
单次提问(One-shot prompt)
对于不需要维护会话的简单单轮查询,使用 unstable_v2_prompt()。以下示例发送一个数学问题并打印答案:
import { unstable_v2_prompt } from "@anthropic-ai/claude-agent-sdk";
const result = await unstable_v2_prompt("What is 2 + 2?", {
model: "claude-opus-4-7"
});
if (result.subtype === "success") {
console.log(result.result);
}
import { query } from "@anthropic-ai/claude-agent-sdk";
const q = query({
prompt: "What is 2 + 2?",
options: { model: "claude-opus-4-7" }
});
for await (const msg of q) {
if (msg.type === "result" && msg.subtype === "success") {
console.log(msg.result);
}
}
基础会话(Basic session)
对于超出单次提问的交互,需要创建一个会话。V2 把发送和接收拆分为两个独立步骤:
send()发送你的消息stream()流式接收响应
这种显式拆分让你更容易在两轮之间插入逻辑(例如在发送后续消息前先处理上一轮响应)。
以下示例创建一个会话,向 Claude 发送“Hello!”,并打印文本响应。示例使用了 await using(TypeScript 5.2+)在代码块结束时自动关闭会话。你也可以手动调用 session.close()。
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()) {
// Filter for assistant messages to get human-readable output
if (msg.type === "assistant") {
const text = msg.message.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
console.log(text);
}
}
在 V1 中,输入和输出都通过单个 async generator 流动。对于基础提问,写法看起来相似,但一旦要加入多轮逻辑,就需要重构为使用输入 generator。
import { query } from "@anthropic-ai/claude-agent-sdk";
const q = query({
prompt: "Hello!",
options: { model: "claude-opus-4-7" }
});
for await (const msg of q) {
if (msg.type === "assistant") {
const text = msg.message.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
console.log(text);
}
}
多轮对话(Multi-turn conversation)
会话会跨多次交互保留上下文。要继续对话,只需在同一个会话上再次调用 send(),Claude 会记住之前的对话轮次。
以下示例先问一个数学问题,再追问一个引用上一个答案的问题:
import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";
await using session = unstable_v2_createSession({
model: "claude-opus-4-7"
});
// Turn 1
await session.send("What is 5 + 3?");
for await (const msg of session.stream()) {
// Filter for assistant messages to get human-readable output
if (msg.type === "assistant") {
const text = msg.message.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
console.log(text);
}
}
// Turn 2
await session.send("Multiply that by 2");
for await (const msg of session.stream()) {
if (msg.type === "assistant") {
const text = msg.message.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
console.log(text);
}
}
import { query } from "@anthropic-ai/claude-agent-sdk";
// Must create an async iterable to feed messages
async function* createInputStream() {
yield {
type: "user",
session_id: "",
message: { role: "user", content: [{ type: "text", text: "What is 5 + 3?" }] },
parent_tool_use_id: null
};
// Must coordinate when to yield next message
yield {
type: "user",
session_id: "",
message: { role: "user", content: [{ type: "text", text: "Multiply by 2" }] },
parent_tool_use_id: null
};
}
const q = query({
prompt: createInputStream(),
options: { model: "claude-opus-4-7" }
});
for await (const msg of q) {
if (msg.type === "assistant") {
const text = msg.message.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
console.log(text);
}
}
续接会话(Session resume)
如果你从之前的交互中保存了会话 ID,可以在之后续接该会话。这对长时间运行的工作流,或需要在应用重启后仍保留对话的场景很有用。
以下示例创建一个会话、保存其 ID、关闭会话,然后再续接该对话:
import {
unstable_v2_createSession,
unstable_v2_resumeSession,
type SDKMessage
} from "@anthropic-ai/claude-agent-sdk";
// Helper to extract text from assistant messages
function getAssistantText(msg: SDKMessage): string | null {
if (msg.type !== "assistant") return null;
return msg.message.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
}
// Create initial session and have a conversation
const session = unstable_v2_createSession({
model: "claude-opus-4-7"
});
await session.send("Remember this number: 42");
// Get the session ID from any received message
let sessionId: string | undefined;
for await (const msg of session.stream()) {
sessionId = msg.session_id;
const text = getAssistantText(msg);
if (text) console.log("Initial response:", text);
}
console.log("Session ID:", sessionId);
session.close();
// Later: resume the session using the stored ID
await using resumedSession = unstable_v2_resumeSession(sessionId!, {
model: "claude-opus-4-7"
});
await resumedSession.send("What number did I ask you to remember?");
for await (const msg of resumedSession.stream()) {
const text = getAssistantText(msg);
if (text) console.log("Resumed response:", text);
}
import { query } from "@anthropic-ai/claude-agent-sdk";
// Create initial session
const initialQuery = query({
prompt: "Remember this number: 42",
options: { model: "claude-opus-4-7" }
});
// Get session ID from any message
let sessionId: string | undefined;
for await (const msg of initialQuery) {
sessionId = msg.session_id;
if (msg.type === "assistant") {
const text = msg.message.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
console.log("Initial response:", text);
}
}
console.log("Session ID:", sessionId);
// Later: resume the session
const resumedQuery = query({
prompt: "What number did I ask you to remember?",
options: {
model: "claude-opus-4-7",
resume: sessionId
}
});
for await (const msg of resumedQuery) {
if (msg.type === "assistant") {
const text = msg.message.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
console.log("Resumed response:", text);
}
}
资源清理(Cleanup)
会话可以手动关闭,也可以借助 await using(TypeScript 5.2+ 的自动资源管理特性)自动关闭。如果你使用较旧的 TypeScript 版本,或遇到兼容性问题,请改用手动清理。
以下示例仅展示清理模式,不发送任何消息,因此运行不会产生输出。
自动清理(TypeScript 5.2+):
import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";
await using session = unstable_v2_createSession({
model: "claude-opus-4-7"
});
// Session closes automatically when the block exits
手动清理:
import { unstable_v2_createSession } from "@anthropic-ai/claude-agent-sdk";
const session = unstable_v2_createSession({
model: "claude-opus-4-7"
});
// ... use the session ...
session.close();
API 参考
unstable_v2_createSession()
创建一个用于多轮对话的新会话。
function unstable_v2_createSession(options: {
model: string;
// Additional options supported
}): SDKSession;
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
options.model | string | 使用的模型;原文注明 options 中还支持其他选项(未在本页列出具体项) |
返回值:SDKSession
unstable_v2_resumeSession()
通过 ID 续接一个已存在的会话。
function unstable_v2_resumeSession(
sessionId: string,
options: {
model: string;
// Additional options supported
}
): SDKSession;
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
sessionId | string | 要续接的会话 ID | |
options.model | string | 使用的模型;原文注明 options 中还支持其他选项(未在本页列出具体项) |
返回值:SDKSession
unstable_v2_prompt()
用于单轮查询的一次性便捷函数。
function unstable_v2_prompt(
prompt: string,
options: {
model: string;
// Additional options supported
}
): Promise<SDKResultMessage>;
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
prompt | string | 提示词内容 | |
options.model | string | 使用的模型;原文注明 options 中还支持其他选项(未在本页列出具体项) |
返回值:Promise<SDKResultMessage>
SDKSession 接口
interface SDKSession {
readonly sessionId: string;
send(message: string | SDKUserMessage): Promise<void>;
stream(): AsyncGenerator<SDKMessage, void>;
close(): void;
}
| 成员 | 类型/签名 | 说明 |
|---|---|---|
sessionId | readonly string | 会话的只读 ID |
send(message) | (message: string | SDKUserMessage) => Promise<void> | 发送一条消息(字符串或 SDKUserMessage) |
stream() | () => AsyncGenerator<SDKMessage, void> | 以异步生成器形式获取响应消息流 |
close() | () => void | 关闭会话 |
功能可用性
V2 会话 API 并未覆盖 V1 的所有功能。以下功能仍需要 V1 SDK:
- 会话分叉(
forkSession选项) - 部分高级流式输入模式
另请参阅
- TypeScript SDK reference (V1) —— 完整的 V1 SDK 文档
- SDK overview —— 通用 SDK 概念
- V2 examples on GitHub —— 可运行的示例代码