File size: 2,046 Bytes
11e46c7 b3c4d3d 11e46c7 92dea51 11e46c7 92dea51 11e46c7 92dea51 11e46c7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | import { NextRequest, NextResponse } from "next/server";
import { promises as fs } from "fs";
import path from "path";
import { v4 as uuidv4 } from "uuid";
export const runtime = "nodejs";
const url =
"https://web-zero-web-zero.hf.space/api/v1/run/iterate?stream=false";
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const { previousDescription, newUpdate, currentCode } = body;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
input_value: `
## Previous Description
${previousDescription}
## New Update
${newUpdate}
## Earlier Component Code
${currentCode}
`,
output_type: "chat",
input_type: "chat",
tweaks: {},
}),
});
if (!response.ok) {
const errorText = await response.text();
console.error("API Response Error:", errorText);
throw new Error(`API request failed with status ${response.status}`);
}
const data = await response.json();
const code =
data?.outputs?.[0]?.outputs?.[0]?.outputs?.message?.message?.text || "";
if (!code) {
throw new Error("No code generated from the API response");
}
const formattedCode = code.replace(/^```tsx\n|\n```$/g, "");
const id = uuidv4();
const generatedDir = path.resolve(
process.cwd(),
"src",
"components",
"generated"
);
const filename = path.join(generatedDir, `${id}.tsx`);
await fs.mkdir(generatedDir, { recursive: true });
await fs.writeFile(filename, formattedCode, "utf8");
return NextResponse.json({
id,
from: "ai",
content: formattedCode,
});
} catch (error) {
console.error("Error in iterate API:", error);
return NextResponse.json(
{
error:
error instanceof Error
? error.message
: "Failed to process the iteration request",
},
{ status: 500 }
);
}
}
|