מדריך קלוד קוד בעברית

תיעוד 152

API של הפעלות ב-TypeScript SDK V2 (הוסר)

תיעוד עיון עבור ה-API של הפעלות (session) שהוסר ב-TypeScript Agent SDK V2, עם דפוסי send/stream מבוססי הפעלה לשיחות מרובות תורות.

אזהרה: ה-API של הפעלות V2 אינו נתמך עוד. TypeScript Agent SDK 0.3.142 מסיר את unstable_v2_createSession, את unstable_v2_resumeSession, את unstable_v2_prompt, ואת הטיפוסים SDKSession ו-SDKSessionOptions.

כדי להגר, השתמש ב-API של query() ובאפשרויות ההפעלה שהוא מקבל. העבר AsyncIterable<SDKUserMessage> עבור שיחות מרובות תורות, או את options.resume כדי להמשיך הפעלה שמורה. דף זה נשמר לעיון אם אתה מתחזק קוד ב-Agent SDK 0.2.x או בגרסאות מוקדמות יותר.

V2 היה API נסיוני של הפעלות שהסיר את הצורך במחוללים אסינכרוניים (async generators) ובתיאום של yield. במקום לנהל את מצב המחולל לאורך תורות, כל תור היה מחזור נפרד של 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/[email protected]

הערה: ה-SDK מצרף קובץ בינארי מקורי של Claude Code עבור הפלטפורמה שלך כתלות אופציונלית, כך שרוב ההתקנות אינן דורשות התקנה נפרדת של Claude Code. ראה את הערת ההתקנה במדריך ההתחלה המהירה עבור התקנות שכן זקוקות לכך.

#התחלה מהירה

#פרומפט חד פעמי (One-shot prompt)

עבור שאילתות פשוטות של תור יחיד שבהן אינך צריך לתחזק הפעלה, השתמש ב-unstable_v2_prompt(). דוגמה זו שולחת שאלת מתמטיקה ורושמת ביומן (log) את התשובה:

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);
}
הצג את אותה הפעולה ב-V1
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() מזרים בחזרה את התגובה

הפרדה מפורשת זו מקלה על הוספת לוגיקה בין תורות (כמו עיבוד תגובות לפני שליחת שאלות המשך).

הדוגמה שלהלן יוצרת הפעלה, שולחת "Hello!" אל Claude, ומדפיסה את תגובת הטקסט. היא משתמשת ב-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

ב-V1, גם הקלט וגם הפלט זורמים דרך מחולל אסינכרוני יחיד. עבור פרומפט בסיסי זה נראה דומה, אך הוספת לוגיקה מרובת תורות דורשת ארגון מחדש כדי להשתמש במחולל קלט.

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);
  }
}
הצג את אותה הפעולה ב-V1
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)

אם יש לך מזהה הפעלה מאינטראקציה קודמת, תוכל לחדש אותה מאוחר יותר. הדבר שימושי עבור תהליכי עבודה ארוכי טווח או כאשר עליך לשמר שיחות מעבר להפעלות מחדש של האפליקציה.

דוגמה זו יוצרת הפעלה, שומרת את המזהה שלה, סוגרת אותה, ולאחר מכן מחדשת את השיחה:

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);
}
הצג את אותה הפעולה ב-V1
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 (API reference)

#unstable_v2_createSession()

יוצר הפעלה חדשה עבור שיחות מרובות תורות.

function unstable_v2_createSession(options: {
  model: string;
  // Additional options supported
}): SDKSession;

#unstable_v2_resumeSession()

מחדש הפעלה קיימת לפי מזהה.

function unstable_v2_resumeSession(
  sessionId: string,
  options: {
    model: string;
    // Additional options supported
  }
): SDKSession;

#unstable_v2_prompt()

פונקציית נוחות חד פעמית לשאילתות של תור יחיד.

function unstable_v2_prompt(
  prompt: string,
  options: {
    model: string;
    // Additional options supported
  }
): Promise<SDKResultMessage>;

#ממשק SDKSession

interface SDKSession {
  readonly sessionId: string;
  send(message: string | SDKUserMessage): Promise<void>;
  stream(): AsyncGenerator<SDKMessage, void>;
  close(): void;
}

#זמינות תכונות

ה-API של הפעלות V2 אינו תומך בכל תכונה של V1. התכונות הבאות דורשות את V1 SDK:

  • פיצול הפעלה (האפשרות forkSession)
  • מספר דפוסי קלט מתקדמים בהזרמה

#ראה גם