V2 介面是一個不穩定的預覽版。API 可能會根據回饋在穩定之前進行更改。某些功能(如會話分叉)僅在 V1 SDK 中可用。
V2 Claude Agent TypeScript SDK 消除了對非同步生成器和 yield 協調的需求。這使得多輪對話更加簡單,不再需要跨輪次管理生成器狀態,每一輪都是一個獨立的 send()/stream() 循環。API 介面簡化為三個概念:
createSession() / resumeSession():開始或繼續對話session.send():發送訊息session.stream():取得回應V2 介面包含在現有的 SDK 套件中:
npm install @anthropic-ai/claude-agent-sdk對於不需要維護會話的簡單單輪查詢,使用 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-6'
})
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-6' }
})
for await (const msg of q) {
if (msg.type === 'result') {
console.log(msg.result)
}
}對於超出單一提示的互動,請建立一個會話。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-6'
})
await session.send('Hello!')
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)
}
}在 V1 中,輸入和輸出都通過單一非同步生成器流動。對於基本提示,這看起來類似,但添加多輪邏輯需要重構以使用輸入生成器。
import { query } from '@anthropic-ai/claude-agent-sdk'
const q = query({
prompt: 'Hello!',
options: { model: 'claude-opus-4-6' }
})
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)
}
}會話在多次交換中保持上下文。要繼續對話,在同一個會話上再次呼叫 send()。Claude 會記住之前的輪次。
此範例提出一個數學問題,然後提出一個引用先前答案的後續問題:
import { unstable_v2_createSession } from '@anthropic-ai/claude-agent-sdk'
await using session = unstable_v2_createSession({
model: 'claude-opus-4-6'
})
// 第 1 輪
await session.send('What is 5 + 3?')
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)
}
}
// 第 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'
// 必須建立一個非同步可迭代物件來提供訊息
async function* createInputStream() {
yield {
type: 'user',
session_id: '',
message: { role: 'user', content: [{ type: 'text', text: 'What is 5 + 3?' }] },
parent_tool_use_id: null
}
// 必須協調何時 yield 下一條訊息
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-6' }
})
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)
}
}如果您有來自先前互動的會話 ID,可以稍後恢復它。這對於長時間運行的工作流程或需要在應用程式重新啟動之間持久化對話時非常有用。
此範例建立一個會話,儲存其 ID,關閉它,然後恢復對話:
import {
unstable_v2_createSession,
unstable_v2_resumeSession,
type SDKMessage
} from '@anthropic-ai/claude-agent-sdk'
// 從助理訊息中提取文字的輔助函式
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('')
}
// 建立初始會話並進行對話
const session = unstable_v2_createSession({
model: 'claude-opus-4-6'
})
await session.send('Remember this number: 42')
// 從任何接收到的訊息中取得會話 ID
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()
// 稍後:使用儲存的 ID 恢復會話
await using resumedSession = unstable_v2_resumeSession(sessionId!, {
model: 'claude-opus-4-6'
})
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'
// 建立初始會話
const initialQuery = query({
prompt: 'Remember this number: 42',
options: { model: 'claude-opus-4-6' }
})
// 從任何訊息中取得會話 ID
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)
// 稍後:恢復會話
const resumedQuery = query({
prompt: 'What number did I ask you to remember?',
options: {
model: 'claude-opus-4-6',
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)
}
}會話可以手動關閉,也可以使用 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-6'
})
// 當區塊退出時,會話會自動關閉手動清理:
import { unstable_v2_createSession } from '@anthropic-ai/claude-agent-sdk'
const session = unstable_v2_createSession({
model: 'claude-opus-4-6'
})
// ... 使用會話 ...
session.close()unstable_v2_createSession()建立一個用於多輪對話的新會話。
function unstable_v2_createSession(options: {
model: string;
// 支援其他選項
}): Sessionunstable_v2_resumeSession()透過 ID 恢復現有會話。
function unstable_v2_resumeSession(
sessionId: string,
options: {
model: string;
// 支援其他選項
}
): Sessionunstable_v2_prompt()用於單輪查詢的一次性便捷函式。
function unstable_v2_prompt(
prompt: string,
options: {
model: string;
// 支援其他選項
}
): Promise<Result>interface Session {
send(message: string): Promise<void>;
stream(): AsyncGenerator<SDKMessage>;
close(): void;
}並非所有 V1 功能都已在 V2 中可用。以下功能需要使用 V1 SDK:
forkSession 選項)在 V2 介面穩定之前,請分享您的回饋。透過 GitHub Issues 報告問題和建議。
Was this page helpful?