Files
zhimingge/lib/ai/client-stream.ts
T
dekun dba0245cb1 Replace RSC streaming with /api/ai Route Handler for Docker reliability.
Server Actions + createStreamableValue kept failing in production; fetch-based text stream avoids RSC serialization issues and shows readable error messages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-10 22:39:09 +08:00

35 lines
799 B
TypeScript

import type { AiRequestBody } from "@/lib/ai/types";
export async function streamAiCompletion(
body: AiRequestBody,
onUpdate: (text: string) => void,
): Promise<void> {
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);
}
}