import { unstable_v2_createSession, unstable_v2_resumeSession, type SDKMessage} from "@anthropic-ai/claude-agent-sdk";// Helper to extract text from assistant messagesfunction 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 conversationconst session = unstable_v2_createSession({ model: "claude-opus-4-7"});await session.send("Remember this number: 42");// Get the session ID from any received messagelet 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 IDawait 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);}
查看 V1 中的相同操作
Copy
import { query } from "@anthropic-ai/claude-agent-sdk";// Create initial sessionconst initialQuery = query({ prompt: "Remember this number: 42", options: { model: "claude-opus-4-7" }});// Get session ID from any messagelet 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 sessionconst 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); }}
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
手动清理:
Copy
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()
为多轮对话创建新会话。
Copy
function unstable_v2_createSession(options: { model: string; // Additional options supported}): SDKSession;