Spaces:
Running
Running
File size: 23,882 Bytes
c10f8f8 5c71dae c10f8f8 35ef307 c10f8f8 35ef307 5131535 c10f8f8 f9c67bc c10f8f8 5131535 c10f8f8 b709981 5131535 f9c67bc 35ef307 c10f8f8 0b02673 c10f8f8 5131535 c10f8f8 e710a1b c10f8f8 d071fc0 c10f8f8 6769a8e c10f8f8 0b02673 c10f8f8 f9c67bc 3baaafe f9c67bc d071fc0 f9c67bc c10f8f8 5c71dae c10f8f8 f9c67bc c10f8f8 6769a8e c10f8f8 f9c67bc c10f8f8 0b02673 c10f8f8 0b02673 c10f8f8 0b02673 c10f8f8 35ef307 c10f8f8 5131535 c10f8f8 17234c8 0698bd6 17234c8 c10f8f8 f9c67bc 63b29b5 56178b1 63b29b5 f9c67bc 56178b1 f9c67bc 530fd3f c10f8f8 dd89112 c10f8f8 f9c67bc c10f8f8 f9c67bc c10f8f8 f9c67bc c10f8f8 f9c67bc c10f8f8 0b02673 530fd3f 0b02673 530fd3f 0b02673 06bf527 0b02673 530fd3f 0b02673 530fd3f c10f8f8 35ef307 c10f8f8 35ef307 c10f8f8 35ef307 c10f8f8 35ef307 c10f8f8 17234c8 c10f8f8 17234c8 c10f8f8 35ef307 c10f8f8 35ef307 c10f8f8 35ef307 c10f8f8 35ef307 c10f8f8 35ef307 c10f8f8 35ef307 c10f8f8 35ef307 c10f8f8 35ef307 c10f8f8 17234c8 c10f8f8 17234c8 c10f8f8 35ef307 066d2e7 35ef307 c10f8f8 5131535 35ef307 5131535 6cca3b1 5131535 d157265 c10f8f8 5131535 d157265 c10f8f8 06bf527 0b02673 c10f8f8 |
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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 |
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { headers } from "next/headers";
import { InferenceClient } from "@huggingface/inference";
import { MODELS } from "@/lib/providers";
import {
DIVIDER,
FOLLOW_UP_SYSTEM_PROMPT,
INITIAL_SYSTEM_PROMPT,
MAX_REQUESTS_PER_IP,
NEW_FILE_END,
NEW_FILE_START,
REPLACE_END,
SEARCH_START,
UPDATE_FILE_START,
UPDATE_FILE_END,
PROMPT_FOR_PROJECT_NAME,
} from "@/lib/prompts";
import { calculateMaxTokens, estimateInputTokens, getProviderSpecificConfig } from "@/lib/max-tokens";
import MY_TOKEN_KEY from "@/lib/get-cookie-name";
import { Page } from "@/types";
import { createRepo, RepoDesignation, uploadFiles } from "@huggingface/hub";
import { isAuthenticated } from "@/lib/auth";
import { getBestProvider } from "@/lib/best-provider";
// import { rewritePrompt } from "@/lib/rewrite-prompt";
import { COLORS } from "@/lib/utils";
import { templates } from "@/lib/templates";
import { injectDeepSiteBadge, isIndexPage } from "@/lib/inject-badge";
const ipAddresses = new Map();
const STREAMING_TIMEOUT = 180000;
const REQUEST_TIMEOUT = 240000;
export const maxDuration = 300;
export async function POST(request: NextRequest) {
const authHeaders = await headers();
const userToken = request.cookies.get(MY_TOKEN_KEY())?.value;
const body = await request.json();
const { prompt, provider, model, redesignMarkdown, enhancedSettings, pages } = body;
if (!model || (!prompt && !redesignMarkdown)) {
return NextResponse.json(
{ ok: false, error: "Missing required fields" },
{ status: 400 }
);
}
const selectedModel = MODELS.find(
(m) => m.value === model || m.label === model
);
if (!selectedModel) {
return NextResponse.json(
{ ok: false, error: "Invalid model selected" },
{ status: 400 }
);
}
let token: string | null = null;
if (userToken) token = userToken;
let billTo: string | null = null;
/**
* Handle local usage token, this bypass the need for a user token
* and allows local testing without authentication.
* This is useful for development and testing purposes.
*/
if (process.env.HF_TOKEN && process.env.HF_TOKEN.length > 0) {
token = process.env.HF_TOKEN;
}
const ip = authHeaders.get("x-forwarded-for")?.includes(",")
? authHeaders.get("x-forwarded-for")?.split(",")[1].trim()
: authHeaders.get("x-forwarded-for");
if (!token) {
ipAddresses.set(ip, (ipAddresses.get(ip) || 0) + 1);
if (ipAddresses.get(ip) > MAX_REQUESTS_PER_IP) {
return NextResponse.json(
{
ok: false,
openLogin: true,
message: "Log In to continue using the service",
},
{ status: 429 }
);
}
token = process.env.DEFAULT_HF_TOKEN as string;
billTo = "huggingface";
}
const selectedProvider = await getBestProvider(selectedModel.value, provider)
let rewrittenPrompt = redesignMarkdown ? `Here is my current design as a markdown:\n\n${redesignMarkdown}\n\nNow, please create a new design based on this markdown. Use the images in the markdown.` : prompt;
if (enhancedSettings.isActive) {
// rewrittenPrompt = await rewritePrompt(rewrittenPrompt, enhancedSettings, { token, billTo }, selectedModel.value, selectedProvider.provider);
}
try {
const encoder = new TextEncoder();
const stream = new TransformStream();
const writer = stream.writable.getWriter();
const response = new NextResponse(stream.readable, {
headers: {
"Content-Type": "text/plain; charset=utf-8",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
});
(async () => {
// let completeResponse = "";
let timeoutId: NodeJS.Timeout | null = null;
let isTimedOut = false;
try {
const client = new InferenceClient(token);
const systemPrompt = INITIAL_SYSTEM_PROMPT;
const userPrompt = rewrittenPrompt;
const estimatedInputTokens = estimateInputTokens(systemPrompt, userPrompt);
const dynamicMaxTokens = calculateMaxTokens(selectedProvider, estimatedInputTokens, true);
const providerConfig = getProviderSpecificConfig(selectedProvider, dynamicMaxTokens);
const chatCompletion = client.chatCompletionStream(
{
model: selectedModel.value,
provider: selectedProvider.provider,
messages: [
{
role: "system",
content: systemPrompt,
},
{
role: "user",
content: userPrompt + (enhancedSettings.isActive ? `1. I want to use the following primary color: ${enhancedSettings.primaryColor} (eg: bg-${enhancedSettings.primaryColor}-500).
2. I want to use the following secondary color: ${enhancedSettings.secondaryColor} (eg: bg-${enhancedSettings.secondaryColor}-500).
3. I want to use the following theme: ${enhancedSettings.theme} mode.` : "")
},
],
...providerConfig,
},
billTo ? { billTo } : {}
);
// Set up timeout
const timeoutPromise = new Promise((_, reject) => {
timeoutId = setTimeout(() => {
isTimedOut = true;
reject(new Error('Request timeout: The AI model took too long to respond. Please try again with a simpler prompt or try a different model.'));
}, STREAMING_TIMEOUT);
});
// Race between streaming and timeout
await Promise.race([
(async () => {
while (true) {
const { done, value } = await chatCompletion.next()
if (done) {
break;
}
const chunk = value.choices[0]?.delta?.content;
if (chunk) {
await writer.write(encoder.encode(chunk));
}
}
})(),
timeoutPromise
]);
// Clear timeout if successful
if (timeoutId) clearTimeout(timeoutId);
// Explicitly close the writer after successful completion
await writer.close();
} catch (error: any) {
// Clear timeout on error
if (timeoutId) clearTimeout(timeoutId);
if (isTimedOut || error.message?.includes('timeout') || error.message?.includes('Request timeout')) {
await writer.write(
encoder.encode(
JSON.stringify({
ok: false,
message: "Request timeout: The AI model took too long to respond. Please try again with a simpler prompt or try a different model.",
})
)
);
} else if (error.message?.includes("exceeded your monthly included credits")) {
await writer.write(
encoder.encode(
JSON.stringify({
ok: false,
openProModal: true,
message: error.message,
})
)
);
} else if (error?.message?.includes("inference provider information")) {
await writer.write(
encoder.encode(
JSON.stringify({
ok: false,
openSelectProvider: true,
message: error.message,
})
)
);
}
else {
await writer.write(
encoder.encode(
JSON.stringify({
ok: false,
message:
error.message ||
"An error occurred while processing your request.",
})
)
);
}
} finally {
try {
await writer?.close();
} catch {
}
}
})();
return response;
} catch (error: any) {
return NextResponse.json(
{
ok: false,
openSelectProvider: true,
message:
error?.message || "An error occurred while processing your request.",
},
{ status: 500 }
);
}
}
export async function PUT(request: NextRequest) {
const user = await isAuthenticated();
if (user instanceof NextResponse || !user) {
return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
}
const authHeaders = await headers();
const body = await request.json();
const { prompt, provider, selectedElementHtml, model, pages, files, repoId: repoIdFromBody, isNew } =
body;
let repoId = repoIdFromBody;
if (!prompt || pages.length === 0) {
return NextResponse.json(
{ ok: false, error: "Missing required fields" },
{ status: 400 }
);
}
const selectedModel = MODELS.find(
(m) => m.value === model || m.label === model
);
if (!selectedModel) {
return NextResponse.json(
{ ok: false, error: "Invalid model selected" },
{ status: 400 }
);
}
let token = user.token as string;
let billTo: string | null = null;
/**
* Handle local usage token, this bypass the need for a user token
* and allows local testing without authentication.
* This is useful for development and testing purposes.
*/
if (process.env.HF_TOKEN && process.env.HF_TOKEN.length > 0) {
token = process.env.HF_TOKEN;
}
const ip = authHeaders.get("x-forwarded-for")?.includes(",")
? authHeaders.get("x-forwarded-for")?.split(",")[1].trim()
: authHeaders.get("x-forwarded-for");
if (!token) {
ipAddresses.set(ip, (ipAddresses.get(ip) || 0) + 1);
if (ipAddresses.get(ip) > MAX_REQUESTS_PER_IP) {
return NextResponse.json(
{
ok: false,
openLogin: true,
message: "Log In to continue using the service",
},
{ status: 429 }
);
}
token = process.env.DEFAULT_HF_TOKEN as string;
billTo = "huggingface";
}
const client = new InferenceClient(token);
const escapeRegExp = (string: string) => {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};
const createFlexibleHtmlRegex = (searchBlock: string) => {
let searchRegex = escapeRegExp(searchBlock)
.replace(/\s+/g, '\\s*')
.replace(/>\s*</g, '>\\s*<')
.replace(/\s*>/g, '\\s*>');
return new RegExp(searchRegex, 'g');
};
const selectedProvider = await getBestProvider(selectedModel.value, provider)
try {
const systemPrompt = FOLLOW_UP_SYSTEM_PROMPT + (isNew ? PROMPT_FOR_PROJECT_NAME : "");
const userContext = "You are modifying the HTML file based on the user's request.";
const allPages = pages || [];
const pagesContext = allPages
.map((p: Page) => `- ${p.path}\n${p.html}`)
.join("\n\n");
const assistantContext = `${
selectedElementHtml
? `\n\nYou have to update ONLY the following element, NOTHING ELSE: \n\n\`\`\`html\n${selectedElementHtml}\n\`\`\` Could be in multiple pages, if so, update all the pages.`
: ""
}. Current pages (${allPages.length} total): ${pagesContext}. ${files?.length > 0 ? `Available images: ${files?.map((f: string) => f).join(', ')}.` : ""}`;
const estimatedInputTokens = estimateInputTokens(systemPrompt, prompt, userContext + assistantContext);
const dynamicMaxTokens = calculateMaxTokens(selectedProvider, estimatedInputTokens, false);
const providerConfig = getProviderSpecificConfig(selectedProvider, dynamicMaxTokens);
const chatCompletion = client.chatCompletionStream(
{
model: selectedModel.value,
provider: selectedProvider.provider,
messages: [
{
role: "system",
content: systemPrompt,
},
{
role: "user",
content: userContext,
},
{
role: "assistant",
content: assistantContext,
},
{
role: "user",
content: prompt,
},
],
...providerConfig,
},
billTo ? { billTo } : {}
);
// Set up timeout for AI streaming
let chunk = "";
let timeoutId: NodeJS.Timeout | null = null;
let isTimedOut = false;
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => {
isTimedOut = true;
reject(new Error('Request timeout: The AI model took too long to respond. Please try again with a simpler prompt or try a different model.'));
}, REQUEST_TIMEOUT);
});
try {
await Promise.race([
(async () => {
while (true) {
const { done, value } = await chatCompletion.next();
if (done) {
break;
}
const deltaContent = value.choices[0]?.delta?.content;
if (deltaContent) {
chunk += deltaContent;
}
}
})(),
timeoutPromise
]);
// Clear timeout if successful
if (timeoutId) clearTimeout(timeoutId);
} catch (timeoutError: any) {
console.log("++TIMEOUT ERROR++", timeoutError)
console.log("++TIMEOUT ERROR MESSAGE++", timeoutError.message)
// Clear timeout on error
if (timeoutId) clearTimeout(timeoutId);
if (isTimedOut || timeoutError.message?.includes('timeout') || timeoutError.message?.includes('Request timeout')) {
return NextResponse.json(
{
ok: false,
message: "Request timeout: The AI model took too long to respond. Please try again with a simpler prompt or try a different model.",
},
{ status: 504 }
);
}
throw timeoutError;
}
if (!chunk) {
return NextResponse.json(
{ ok: false, message: "No content returned from the model" },
{ status: 400 }
);
}
if (chunk) {
const updatedLines: number[][] = [];
let newHtml = "";
const updatedPages = [...(pages || [])];
const updateFileRegex = new RegExp(`${UPDATE_FILE_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^\\s]+)\\s*${UPDATE_FILE_END.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([\\s\\S]*?)(?=${UPDATE_FILE_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}|${NEW_FILE_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}|$)`, 'g');
let updateFileMatch;
while ((updateFileMatch = updateFileRegex.exec(chunk)) !== null) {
const [, filePath, fileContent] = updateFileMatch;
const pageIndex = updatedPages.findIndex(p => p.path === filePath);
if (pageIndex !== -1) {
let pageHtml = updatedPages[pageIndex].html;
let processedContent = fileContent;
const htmlMatch = fileContent.match(/```html\s*([\s\S]*?)\s*```/);
if (htmlMatch) {
processedContent = htmlMatch[1];
}
let position = 0;
let moreBlocks = true;
while (moreBlocks) {
const searchStartIndex = processedContent.indexOf(SEARCH_START, position);
if (searchStartIndex === -1) {
moreBlocks = false;
continue;
}
const dividerIndex = processedContent.indexOf(DIVIDER, searchStartIndex);
if (dividerIndex === -1) {
moreBlocks = false;
continue;
}
const replaceEndIndex = processedContent.indexOf(REPLACE_END, dividerIndex);
if (replaceEndIndex === -1) {
moreBlocks = false;
continue;
}
const searchBlock = processedContent.substring(
searchStartIndex + SEARCH_START.length,
dividerIndex
);
const replaceBlock = processedContent.substring(
dividerIndex + DIVIDER.length,
replaceEndIndex
);
if (searchBlock.trim() === "") {
pageHtml = `${replaceBlock}\n${pageHtml}`;
updatedLines.push([1, replaceBlock.split("\n").length]);
} else {
const regex = createFlexibleHtmlRegex(searchBlock);
const match = regex.exec(pageHtml);
if (match) {
const matchedText = match[0];
const beforeText = pageHtml.substring(0, match.index);
const startLineNumber = beforeText.split("\n").length;
const replaceLines = replaceBlock.split("\n").length;
const endLineNumber = startLineNumber + replaceLines - 1;
updatedLines.push([startLineNumber, endLineNumber]);
pageHtml = pageHtml.replace(matchedText, replaceBlock);
}
}
position = replaceEndIndex + REPLACE_END.length;
}
updatedPages[pageIndex].html = pageHtml;
if (filePath === '/' || filePath === '/index' || filePath === 'index' || filePath === 'index.html') {
newHtml = pageHtml;
}
}
}
const newFileRegex = new RegExp(`${NEW_FILE_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^\\s]+)\\s*${NEW_FILE_END.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([\\s\\S]*?)(?=${UPDATE_FILE_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}|${NEW_FILE_START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}|$)`, 'g');
let newFileMatch;
while ((newFileMatch = newFileRegex.exec(chunk)) !== null) {
const [, filePath, fileContent] = newFileMatch;
let fileData = fileContent;
// Try to extract content from code blocks
const htmlMatch = fileContent.match(/```html\s*([\s\S]*?)\s*```/);
const cssMatch = fileContent.match(/```css\s*([\s\S]*?)\s*```/);
const jsMatch = fileContent.match(/```javascript\s*([\s\S]*?)\s*```/);
if (htmlMatch) {
fileData = htmlMatch[1];
} else if (cssMatch) {
fileData = cssMatch[1];
} else if (jsMatch) {
fileData = jsMatch[1];
}
const existingFileIndex = updatedPages.findIndex(p => p.path === filePath);
if (existingFileIndex !== -1) {
updatedPages[existingFileIndex] = {
path: filePath,
html: fileData.trim()
};
} else {
updatedPages.push({
path: filePath,
html: fileData.trim()
});
}
}
if (updatedPages.length === pages?.length && !chunk.includes(UPDATE_FILE_START)) {
let position = 0;
let moreBlocks = true;
while (moreBlocks) {
const searchStartIndex = chunk.indexOf(SEARCH_START, position);
if (searchStartIndex === -1) {
moreBlocks = false;
continue;
}
const dividerIndex = chunk.indexOf(DIVIDER, searchStartIndex);
if (dividerIndex === -1) {
moreBlocks = false;
continue;
}
const replaceEndIndex = chunk.indexOf(REPLACE_END, dividerIndex);
if (replaceEndIndex === -1) {
moreBlocks = false;
continue;
}
const searchBlock = chunk.substring(
searchStartIndex + SEARCH_START.length,
dividerIndex
);
const replaceBlock = chunk.substring(
dividerIndex + DIVIDER.length,
replaceEndIndex
);
if (searchBlock.trim() === "") {
newHtml = `${replaceBlock}\n${newHtml}`;
updatedLines.push([1, replaceBlock.split("\n").length]);
} else {
const regex = createFlexibleHtmlRegex(searchBlock);
const match = regex.exec(newHtml);
if (match) {
const matchedText = match[0];
const beforeText = newHtml.substring(0, match.index);
const startLineNumber = beforeText.split("\n").length;
const replaceLines = replaceBlock.split("\n").length;
const endLineNumber = startLineNumber + replaceLines - 1;
updatedLines.push([startLineNumber, endLineNumber]);
newHtml = newHtml.replace(matchedText, replaceBlock);
}
}
position = replaceEndIndex + REPLACE_END.length;
}
const mainPageIndex = updatedPages.findIndex(p => p.path === '/' || p.path === '/index' || p.path === 'index');
if (mainPageIndex !== -1) {
updatedPages[mainPageIndex].html = newHtml;
}
}
const files: File[] = [];
updatedPages.forEach((page: Page) => {
let mimeType = "text/html";
if (page.path.endsWith(".css")) {
mimeType = "text/css";
} else if (page.path.endsWith(".js")) {
mimeType = "text/javascript";
} else if (page.path.endsWith(".json")) {
mimeType = "application/json";
}
const content = (mimeType === "text/html" && isIndexPage(page.path)) && isNew
? injectDeepSiteBadge(page.html)
: page.html;
const file = new File([content], page.path, { type: mimeType });
files.push(file);
});
if (isNew) {
const projectName = chunk.match(/<<<<<<< PROJECT_NAME_START\s*([\s\S]*?)\s*>>>>>>> PROJECT_NAME_END/)?.[1]?.trim();
const formattedTitle = projectName?.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.split("-")
.filter(Boolean)
.join("-")
.slice(0, 96);
const repo: RepoDesignation = {
type: "space",
name: `${user.name}/${formattedTitle}`,
};
const { repoUrl} = await createRepo({
repo,
accessToken: user.token as string,
});
repoId = repoUrl.split("/").slice(-2).join("/");
const colorFrom = COLORS[Math.floor(Math.random() * COLORS.length)];
const colorTo = COLORS[Math.floor(Math.random() * COLORS.length)];
const README = `---
title: ${projectName}
colorFrom: ${colorFrom}
colorTo: ${colorTo}
emoji: 🐳
sdk: static
pinned: false
tags:
- deepsite-v3
---
# Welcome to your new DeepSite project!
This project was created with [DeepSite](https://huggingface.co/deepsite).
`;
files.push(new File([README], "README.md", { type: "text/markdown" }));
}
const response = await uploadFiles({
repo: {
type: "space",
name: repoId,
},
files,
commitTitle: prompt,
accessToken: user.token as string,
});
return NextResponse.json({
ok: true,
updatedLines,
pages: updatedPages,
repoId,
commit: {
...response.commit,
title: prompt,
}
});
} else {
return NextResponse.json(
{ ok: false, message: "No content returned from the model" },
{ status: 400 }
);
}
} catch (error: any) {
console.log("++ERROR++", error)
console.log("++ERROR MESSAGE++", error.message)
if (error.message?.includes('timeout') || error.message?.includes('Request timeout')) {
return NextResponse.json(
{
ok: false,
message: "Request timeout: The operation took too long to complete. Please try again with a simpler request or try a different model.",
},
{ status: 504 }
);
}
if (error.message?.includes("exceeded your monthly included credits")) {
return NextResponse.json(
{
ok: false,
openProModal: true,
message: error.message,
},
{ status: 402 }
);
}
return NextResponse.json(
{
ok: false,
openSelectProvider: true,
message:
error.message || "An error occurred while processing your request.",
},
{ status: 500 }
);
}
}
|