dba0245cb1
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>
35 lines
799 B
TypeScript
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);
|
|
}
|
|
}
|