import type { AiRequestBody } from "@/lib/ai/types"; export async function streamAiCompletion( body: AiRequestBody, onUpdate: (text: string) => void, ): Promise { const res = await fetch("/api/ai", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); if (!res.ok) { const message = (await res.text()).trim(); throw new Error(message || `AI 请求失败 (${res.status})`); } if (!res.body) { throw new Error("AI 响应为空"); } const reader = res.body.getReader(); const decoder = new TextDecoder(); let text = ""; while (true) { const { done, value } = await reader.read(); if (done) { break; } text += decoder.decode(value, { stream: true }); onUpdate(text); } }