import { query, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";import { readFile } from "fs/promises";async function* generateMessages(): AsyncGenerator<SDKUserMessage> { // First message yield { type: "user", message: { role: "user", content: "Analyze this codebase for security issues" }, parent_tool_use_id: null }; // Wait for conditions or user input await new Promise((resolve) => setTimeout(resolve, 2000)); // Follow-up with image yield { type: "user", message: { role: "user", content: [ { type: "text", text: "Review this architecture diagram" }, { type: "image", source: { type: "base64", media_type: "image/png", data: await readFile("diagram.png", "base64") } } ] }, parent_tool_use_id: null };}// Process streaming responsesfor await (const message of query({ prompt: generateMessages(), options: { maxTurns: 10, allowedTools: ["Read", "Grep"] }})) { if (message.type === "result" && message.subtype === "success") { console.log(message.result); }}
在 TypeScript SDK 中,如果您的訊息產生器拋出例外,例如當它讀取的檔案遺失時,串流會以錯誤結束,該錯誤顯示為 Claude Code process aborted by user,而不是原始錯誤,因此當您看到該訊息時,請先檢查產生器內的程式碼。該錯誤前面也可能會有一長行的最小化捆綁 SDK 原始碼,因此請閱讀輸出末尾以取得錯誤文字。在 Python SDK 中,產生器例外會在偵錯層級記錄,工作階段會停滯而不會引發,因此如果串流工作階段掛起且沒有輸出,請啟用偵錯記錄並檢查您的產生器。