Loading...
    • 開発者ガイド
    • API リファレンス
    • MCP
    • リソース
    • リリースノート
    Search...
    ⌘K
    はじめに
    Claude の紹介クイックスタート
    モデルと料金
    モデル概要モデルの選び方Claude 4.6 の新機能移行ガイドモデルの廃止料金
    Claude で構築する
    機能概要Messages API の使用停止理由の処理プロンプトのベストプラクティス
    コンテキスト管理
    コンテキストウィンドウコンパクションコンテキスト編集
    機能
    プロンプトキャッシング拡張思考適応型思考エフォートメッセージのストリーミングバッチ処理引用多言語サポートトークンカウントエンベディングビジョンPDF サポートFiles API検索結果構造化出力
    ツール
    概要ツール使用の実装方法きめ細かいツールストリーミングBash ツールコード実行ツールプログラムによるツール呼び出しコンピュータ使用ツールテキストエディタツールWeb フェッチツールWeb 検索ツールメモリツールツール検索ツール
    Agent Skills
    概要クイックスタートベストプラクティスエンタープライズ向け SkillsAPI での Skills の使用
    Agent SDK
    概要クイックスタートTypeScript SDKTypeScript V2(プレビュー)Python SDK移行ガイド
    API での MCP
    MCP コネクタリモート MCP サーバー
    サードパーティプラットフォームの Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    プロンプトエンジニアリング
    概要プロンプトジェネレータープロンプトテンプレートの使用プロンプト改善ツール明確かつ直接的に例を使う(マルチショットプロンプティング)Claude に考えさせる(CoT)XML タグを使うClaude に役割を与える(システムプロンプト)複雑なプロンプトを連鎖させる長文コンテキストのヒント拡張思考のヒント
    テストと評価
    成功基準の定義テストケースの開発評価ツールの使用レイテンシの削減
    ガードレールの強化
    ハルシネーションの削減出力の一貫性を高めるジェイルブレイクの軽減ストリーミング拒否プロンプト漏洩の防止Claude をキャラクターに保つ
    管理とモニタリング
    Admin API 概要データレジデンシーワークスペースUsage and Cost APIClaude Code Analytics APIゼロデータリテンション
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    Agent SDK

    TypeScript SDK V2 インターフェース(プレビュー)

    セッションベースの send/stream パターンによるマルチターン会話を実現する、簡素化された V2 TypeScript Agent SDK のプレビュー。

    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)
    V1 での同じ操作を見る
    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 での同じ操作を見る

    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)
      }
    }
    V1 での同じ操作を見る
    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)
    }
    V1 での同じ操作を見る
    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()

    API リファレンス

    unstable_v2_createSession()

    マルチターン会話用の新しいセッションを作成します。

    function unstable_v2_createSession(options: {
      model: string;
      // 追加オプションをサポート
    }): Session

    unstable_v2_resumeSession()

    ID を指定して既存のセッションを再開します。

    function unstable_v2_resumeSession(
      sessionId: string,
      options: {
        model: string;
        // 追加オプションをサポート
      }
    ): Session

    unstable_v2_prompt()

    シングルターンクエリ用のワンショット便利関数です。

    function unstable_v2_prompt(
      prompt: string,
      options: {
        model: string;
        // 追加オプションをサポート
      }
    ): Promise<Result>

    Session インターフェース

    interface Session {
      send(message: string): Promise<void>;
      stream(): AsyncGenerator<SDKMessage>;
      close(): void;
    }

    機能の利用可能性

    V1 のすべての機能が V2 で利用できるわけではありません。以下の機能は V1 SDK を使用する必要があります:

    • セッションフォーク(forkSession オプション)
    • 一部の高度なストリーミング入力パターン

    フィードバック

    V2 インターフェースが安定版になる前に、フィードバックを共有してください。問題や提案は GitHub Issues を通じて報告してください。

    関連情報

    • TypeScript SDK リファレンス(V1) - V1 SDK の完全なドキュメント
    • SDK 概要 - SDK の一般的なコンセプト
    • GitHub 上の V2 サンプル - 動作するコード例

    Was this page helpful?

    • API リファレンス
    • unstable_v2_createSession()
    • unstable_v2_resumeSession()
    • unstable_v2_prompt()
    • Session インターフェース