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

תיעוד 194

ממשק API של סשן V2 ב-TypeScript SDK (הוסר)

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

[!WARNING]

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

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

V2 היה ממשק API ניסיוני לסשן שהסיר את הצורך במחוללי async ובתיאום yield. במקום לנהל את מצב ה-generator לאורך התורות, כל תור היה מחזור נפרד של send()/stream(). היקף ה-API הצטמצם ליצירת סשן, שליחת הודעה, והזרמת התשובה:

  • createSession() / resumeSession(): התחלה או המשך של שיחה
  • session.send(): שליחת הודעה
  • session.stream(): קבלת התשובה

#התקנה

Agent SDK 0.2.x היא הגרסה האחרונה שכוללת את ממשק V2. גרסת החבילה קפצה מ-0.2.x ישירות ל-0.3.142, כך שגרסת ההסרה שלמעלה ונעילת ההתקנה שלמטה מתארות את אותו גבול. כדי להתקין את המהדורה האחרונה התואמת ל-V2, נעלו את גרסאות ה-major וה-minor:

npm install @anthropic-ai/[email protected]

[!NOTE]

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

#התחלה מהירה

#הנחיה חד-פעמית

לשאילתות פשוטות של תור יחיד שבהן אין צורך לתחזק סשן, השתמשו ב-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-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);
  }
}

#סשן בסיסי

לאינטראקציות מעבר להנחיה יחידה, צרו סשן. 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, גם הקלט וגם הפלט זורמים דרך async generator יחיד. להנחיה בסיסית זה נראה דומה, אבל הוספת לוגיקה מרובת תורות דורשת ארגון מחדש כדי להשתמש ב-generator של קלט.

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);
  }
}

#שיחה מרובת תורות

סשנים שומרים הקשר לאורך כמה חילופים. כדי להמשיך שיחה, קראו שוב ל-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);
  }
}

#חידוש סשן

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

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

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);
  }
}

#ניקוי

אפשר לסגור סשנים ידנית או אוטומטית באמצעות 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

#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)
  • חלק מדפוסי קלט הזרמה מתקדמים

#ראו גם