I am building an application in Next.js, TailwindCSS, Appwrite, and Zustand. So now the problem is this api response is extermly show please optmize it and make it faster 

import { NextResponse } from "next/server";
import Together from "together-ai";

const together = new Together({ apiKey: process.env.TOGETHER_API_KEY });

export async function POST(request) {
  try {
    const { action, ...data } = await request.json();

    switch (action) {
      case "regenerate":
        return await handleRegenerate(data);
      case "chat":
        return await handleChat(data);
      default:
        return NextResponse.json({ error: "Invalid action" }, { status: 400 });
    }
  } catch (error) {
    console.error("Error in API:", error);
    return NextResponse.json(
      { error: error.message || "Internal server error" },
      { status: 500 }
    );
  }
}

async function handleRegenerate({
  selectedSections,
  profile,
  jobDescription,
  currentResume,
  message,
  originalSections,
}) {
  if (
    !selectedSections ||
    !profile ||
    !jobDescription ||
    !currentResume ||
    !originalSections ||
    !message
  ) {
    return NextResponse.json(
      { error: "Missing required fields" },
      { status: 400 }
    );
  }

  const prompt = generateRegenerationPrompt(
    selectedSections,
    profile,
    jobDescription,
    currentResume,
    message,
    originalSections
  );

  const response = await together.chat.completions.create({
    messages: [{ role: "user", content: prompt }],
    model: "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
    max_tokens: 2048,
    temperature: 0.7,
    top_p: 0.9,
    n: 1,
    stop: ["
", "
"],
  });

  const generatedContent = response.choices[0].message.content.trim();
  const jsonString = extractJson(generatedContent);

  try {
    const jsonContent = JSON.parse(jsonString);
    const validatedContent = validateResumeContent(jsonContent);

    const replyPrompt = generateReplyPrompt(
      selectedSections,
      originalSections,
      validatedContent,
      message
    );

    const replyResponse = await together.chat.completions.create({
      messages: [{ role: "user", content: replyPrompt }],
      model: "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
      max_tokens: 1024,
      temperature: 0.7,
      top_p: 0.9,
      n: 1,
      stop: ["
", "
"],
    });

    const reply = replyResponse.choices[0].message.content.trim();

    return NextResponse.json({ result: validatedContent, reply });
  } catch (parseError) {
    console.error("Error parsing generated content:", parseError);
    return NextResponse.json(
      { error: "Generated content is not valid JSON", generatedContent },
      { status: 500 }
    );
  }
}

async function handleChat({ message, chatHistory, resume, jobDescription }) {
  if (!message || !chatHistory || !resume || !jobDescription) {
    return NextResponse.json(
      { error: "Missing required fields" },
      { status: 400 }
    );
  }

  const formattedHistory = chatHistory.map((msg) => ({
    role: msg.type === "user" ? "user" : "assistant",
    content: msg.content,
  }));

  const systemMessage = `
    You are a helpful assistant for resume and job application related queries.
    You have access to the following information:
    Resume: ${JSON.stringify(resume, null, 2)}
    Job Description: ${jobDescription}
    Please use this information to provide accurate and tailored responses to the user's questions about their resume and job application.
  `;

  const response = await together.chat.completions.create({
    messages: [
      { role: "system", content: systemMessage },
      ...formattedHistory,
      { role: "user", content: message },
    ],
    model: "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
    max_tokens: 1024,
    temperature: 0.7,
    top_p: 0.9,
    n: 1,
    stop: ["
", "
"],
  });

  const reply = response.choices[0].message.content.trim();

  return NextResponse.json({ reply });
}

const sectionPrompts = {
  summary:
    "Update the summary to highlight key achievements and skills relevant to the job description.",
  experience:
    "Enhance the experience section to emphasize relevant responsibilities and accomplishments.",
  skills:
    "Modify the skills section to showcase skills that align closely with the job requirements.",
  education:
    "Adjust the education section to highlight relevant courses or honors.",
};

function generateRegenerationPrompt(
  selectedSections,
  profile,
  jobDescription,
  currentResume,
  message,
  originalSections
) {
  const sectionInstructions = selectedSections
    .map((section) => {
      const instruction = sectionPrompts[section] || "";
      return `Section: ${section}\nInstruction: ${instruction}\nOriginal Content: ${JSON.stringify(originalSections[section], null, 2)}`;
    })
    .join("\n\n");

  return `
    You are a resume writing assistant. Please regenerate the following sections of the resume based on the profile, job description, and current resume. Only modify the selected sections:

    Selected Sections: ${selectedSections.join(", ")}
    Profile: ${JSON.stringify(profile, null, 2)}
    Job Description: ${jobDescription}
    Current Resume: ${JSON.stringify(currentResume, null, 2)}
    User Message: ${message}
    Instructions:
    For each of the selected sections, follow these specific instructions:
    ${sectionInstructions}

    General Instructions:
    - Only modify the sections specified in the Selected Sections.
    - Maintain the same structure and format as the current resume.
    - Tailor the content to better match the job description and highlight relevant skills and experiences.
    - Ensure that the regenerated sections seamlessly integrate with the rest of the resume.
    - Consider the user's message when making changes: "${message}"
    - Improve the content more than the original, addressing the user's request.
    - Return the entire resume JSON object, including both modified and unmodified sections.
    
    Return only the JSON object with the following structure, no additional text:

    {
      "title": "Full Name",
      "summary": "A concise, impactful professional summary tailored to the job description",
      "email": "email@example.com",
      "phone": "+1234567890",
      "location": "City, Province",
      "sections": {
        "socialLinks": [
          {
            "platform": "Platform Name",
            "url": "https://example.com/profile",
            "id": "unique-id"
          }
        ],
        "education": [
          {
            "school": "School Name",
            "degree": "Degree Name",
            "fieldOfStudy": "Field of Study",
            "startDate": "YYYY-MM-DD",
            "endDate": "YYYY-MM-DD",
            "description": "Key achievements or relevant coursework",
            "id": "unique-id"
          }
        ],
        "experience": [
          {
            "jobTitle": "Job Title",
            "companyName": "Company Name",
            "location": "City, Province",
            "startDate": "YYYY-MM-DD",
            "endDate": "YYYY-MM-DD",
            "description": "Three key responsibilities or achievements",
            "id": "unique-id"
          }
        ],
        "skills": [
          {
            "name": "Skill Name",
            "proficiencyLevel": "Proficiency Level",
            "id": "unique-id"
          }
        ],
        "certifications": [
          {
            "name": "Certification Name",
            "issuingOrganization": "Issuing Organization",
            "issueDate": "YYYY-MM-DD",
            "expirationDate": "YYYY-MM-DD",
            "description": "Relevance to the job",
            "id": "unique-id"
          }
        ],
        "projects": [
          {
            "name": "Project Name",
            "description": "Project description and outcomes",
            "technologiesUsed": "Technologies used",
            "link": "https://project-link.com",
            "startDate": "YYYY-MM-DD",
            "endDate": "YYYY-MM-DD",
            "id": "unique-id"
          }
        ],
        "languages": [
          {
            "name": "Language Name",
            "proficiencyLevel": "Proficiency Level",
            "id": "unique-id"
          }
        ],
        "awards": [
          {
            "name": "Award Name",
            "issuingOrganization": "Issuing Organization",
            "dateReceived": "YYYY-MM-DD",
            "description": "Relevance to the job",
            "id": "unique-id"
          }
        ]
      }
    }
  `;
}

function generateReplyPrompt(
  selectedSections,
  originalSections,
  validatedContent,
  userMessage
) {
  const regeneratedSections = selectedSections.reduce((acc, section) => {
    acc[section] = validatedContent.sections[section];
    return acc;
  }, {});

  return `
    You have just regenerated the following sections of a resume: ${selectedSections.join(", ")}.
    Here are the original sections: ${JSON.stringify(originalSections, null, 2)}
    And here are the regenerated sections: ${JSON.stringify(regeneratedSections, null, 2)}
    Provide a brief summary of the changes made and any suggestions for further improvements.
    Address the user's request to "${userMessage}".
  `;
}

function extractJson(text) {
  const jsonStart = text.indexOf("{");
  const jsonEnd = text.lastIndexOf("}");
  if (jsonStart !== -1 && jsonEnd !== -1) {
    return text.substring(jsonStart, jsonEnd + 1);
  }
  throw new Error("JSON data not found in the generated content");
}

function validateResumeContent(content) {
  const requiredFields = [
    "title",
    "summary",
    "email",
    "phone",
    "location",
    "sections",
  ];
  const requiredSections = [
    "socialLinks",
    "education",
    "experience",
    "skills",
    "certifications",
    "projects",
    "languages",
    "awards",
  ];

  requiredFields.forEach((field) => {
    if (!content[field]) {
      content[field] = "";
    }
  });

  if (!content.sections || typeof content.sections !== "object") {
    content.sections = {};
  }

  requiredSections.forEach((section) => {
    if (!content.sections[section] || !Array.isArray(content.sections[section])) {
      content.sections[section] = [];
    }
  });

  requiredSections.forEach((section) => {
    content.sections[section] = content.sections[section].map((item) => {
      const validatedItem = { ...item, id: item.id || generateUniqueId() };
      ["startDate", "endDate", "issueDate", "expirationDate", "dateReceived"].forEach((dateField) => {
        if (validatedItem[dateField]) {
          validatedItem[dateField] = validateDate(validatedItem[dateField]);
        }
      });
      return validatedItem;
    });
  });

  return content;
}

function validateDate(dateString) {
  if (!dateString || dateString.trim() === "") return "";

  const date = new Date(dateString);
  if (isNaN(date.getTime())) return "";

  return date.toISOString().split("T")[0];
}


function generateUniqueId() {
    return Date.now().toString() + Math.random().toString(36).substr(2, 9);
}