V2 インターフェースは不安定なプレビューです。安定版になる前に、フィードバックに基づいて API が変更される可能性があります。セッションフォークなどの一部の機能は V1 SDK でのみ利用可能です。
V2 Claude Agent TypeScript SDK は、非同期ジェネレーターと yield の調整を不要にします。これによりマルチターン会話がシンプルになり、ターンをまたいでジェネレーターの状態を管理する代わりに、各ターンが個別の send()/stream() サイクルになります。API サーフェスは3つのコンセプトに集約されます:
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?