I am building an application in Next.js, TailwindCSS, Appwrite, and Zustand. Please fix this error 
Error parsing generated content: SyntaxError: Unexpected token '`', "```
{
  "t"... is not valid JSON
    at JSON.parse (<anonymous>)
    at POST (webpack-internal:///(rsc)/./src/app/api/generate/route.js:61:38)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async E:\ResumeFlex\resumeflex\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:55038
    at async ek.execute (E:\ResumeFlex\resumeflex\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:45808)
    at async ek.handle (E:\ResumeFlex\resumeflex\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:56292)
    at async doRender (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:1357:42)
    at async cacheEntry.responseCache.get.routeKind (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:1579:28)
    at async DevServer.renderToResponseWithComponentsImpl (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:1487:28)
    at async DevServer.renderPageComponent (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:1911:24)
    at async DevServer.renderToResponseImpl (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:1949:32)
    at async DevServer.pipeImpl (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:916:25)
    at async NextNodeServer.handleCatchallRenderRequest (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\next-server.js:272:17)
    at async DevServer.handleRequestImpl (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:812:17)
    at async E:\ResumeFlex\resumeflex\node_modules\next\dist\server\dev\next-dev-server.js:339:20
    at async Span.traceAsyncFn (E:\ResumeFlex\resumeflex\node_modules\next\dist\trace\trace.js:154:20)
    at async DevServer.handleRequest (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\dev\next-dev-server.js:336:24)
    at async invokeRender (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\lib\router-server.js:173:21)
    at async handleRequest (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\lib\router-server.js:350:24)
    at async requestHandlerImpl (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\lib\router-server.js:374:13)
    at async Server.requestListener (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\lib\start-server.js:141:13)
Error parsing extracted JSON: SyntaxError: Bad control character in string literal in JSON at position 1963
    at JSON.parse (<anonymous>)
    at extractJsonFromString (webpack-internal:///(rsc)/./src/app/api/generate/route.js:156:25)
    at POST (webpack-internal:///(rsc)/./src/app/api/generate/route.js:70:35)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async E:\ResumeFlex\resumeflex\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:55038
    at async ek.execute (E:\ResumeFlex\resumeflex\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:45808)
    at async ek.handle (E:\ResumeFlex\resumeflex\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:56292)
    at async doRender (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:1357:42)
    at async cacheEntry.responseCache.get.routeKind (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:1579:28)
    at async DevServer.renderToResponseWithComponentsImpl (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:1487:28)
    at async DevServer.renderPageComponent (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:1911:24)
    at async DevServer.renderToResponseImpl (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:1949:32)
    at async DevServer.pipeImpl (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:916:25)
    at async NextNodeServer.handleCatchallRenderRequest (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\next-server.js:272:17)
    at async DevServer.handleRequestImpl (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\base-server.js:812:17)
    at async E:\ResumeFlex\resumeflex\node_modules\next\dist\server\dev\next-dev-server.js:339:20
    at async Span.traceAsyncFn (E:\ResumeFlex\resumeflex\node_modules\next\dist\trace\trace.js:154:20)
    at async DevServer.handleRequest (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\dev\next-dev-server.js:336:24)
    at async invokeRender (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\lib\router-server.js:173:21)
    at async handleRequest (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\lib\router-server.js:350:24)
    at async requestHandlerImpl (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\lib\router-server.js:374:13)
    at async Server.requestListener (E:\ResumeFlex\resumeflex\node_modules\next\dist\server\lib\start-server.js:141:13)
 POST /api/generate 500 in 21515ms

CODE
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 { type, profile, jobDescription, currentResume } =
      await request.json();

    if (!type || !profile || !jobDescription) {
      return NextResponse.json(
        { error: "Missing required fields" },
        { status: 400 }
      );
    }

    let prompt = "";
    switch (type) {
      case "resume":
        prompt = generateResumePrompt(profile, jobDescription, currentResume);
        break;
      case "cover":
        prompt = generateCoverLetterPrompt(profile, jobDescription);
        break;
      case "email":
        prompt = generateEmailPrompt(profile, jobDescription);
        break;
      default:
        return NextResponse.json({ error: "Invalid type" }, { status: 400 });
    }

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

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

    try {
      // Attempt to parse the JSON content
      const jsonContent = JSON.parse(generatedContent);

      // Validate and clean the content
      const validatedContent = validateContent(jsonContent, type);

      return NextResponse.json({ result: validatedContent });
    } catch (parseError) {
      console.error("Error parsing generated content:", parseError);

      // Attempt to extract JSON from the generated content
      const extractedJson = extractJsonFromString(generatedContent);

      if (extractedJson) {
        const validatedContent = validateContent(extractedJson, type);
        return NextResponse.json({ result: validatedContent });
      }

      return NextResponse.json(
        { error: "Generated content is not valid JSON" },
        { status: 500 }
      );
    }
  } catch (error) {
    console.error("Error in generate API:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}


function validateCoverLetterContent(content) {
    const requiredFields = ['salutation', 'opening', 'body', 'closing', 'signature'];
  
    for (const field of requiredFields) {
      if (!content[field]) {
        content[field] = field === 'body' ? [] : ''; // Set empty array for body, empty string for others
      }
    }
  
    // Ensure body is an array with at least one paragraph
    if (!Array.isArray(content.body) || content.body.length === 0) {
      content.body = [''];
    }
  
    // Ensure all paragraphs in body are strings
    content.body = content.body.map(paragraph => paragraph.toString());
  
    return content;
  }
  
  function validateEmailContent(content) {
    const requiredFields = ['subject', 'greeting', 'body', 'closing', 'signature'];
  
    for (const field of requiredFields) {
      if (!content[field]) {
        content[field] = field === 'body' ? [] : ''; // Set empty array for body, empty string for others
      }
    }
  
    // Ensure body is an array with at least one paragraph
    if (!Array.isArray(content.body) || content.body.length === 0) {
      content.body = [''];
    }
  
    // Ensure all paragraphs in body are strings
    content.body = content.body.map(paragraph => paragraph.toString());
  
    return content;
  }
  

function validateContent(content, type) {
  // Implement validation logic based on the content type
  switch (type) {
    case "resume":
      return validateResumeContent(content);
    case "cover":
      return validateCoverLetterContent(content);
    case "email":
      return validateEmailContent(content);
    default:
      return content;
  }
}

function extractJsonFromString(str) {
  const jsonRegex = /{[\s\S]*}/;
  const match = str.match(jsonRegex);
  if (match) {
    try {
      return JSON.parse(match[0]);
    } catch (error) {
      console.error("Error parsing extracted JSON:", error);
      return null;
    }
  }
  return null;
}

function generateResumePrompt(profile, jobDescription) {
    return `Create a professional, tailored resume for the following person based on their profile, the provided job description, and their current resume. Return the result as a JSON object with the following structure:
  
  {
    "title": "Full Name",
    "summary": "A concise, impactful professional summary tailored to the job description",
    "email": "email@example.com",
    "phone": "+1234567890",
    "location": "City, State",
    "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, State",
          "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"
        }
      ]
    }
  }
  
  Profile:
  ${JSON.stringify(profile, null, 2)}
  
  Job Description:
  ${jobDescription}
  
  Instructions:
  1. If a current resume is provided, enhance its content to better align with the job description. If no current resume exists, create a new one based on the profile and job description.
  2. Tailor the resume content to highlight skills and experiences that closely match the job description.
  3. For the 'experience' section, DO NOT change job titles, company names, or dates. Only enhance the description.
  4. For each job in the 'experience' section, provide EXACTLY 3 detailed points in the description. Each point should be at least 2 sentences long, providing specific achievements, responsibilities, or projects. Separate each point with '\n'. Do not use markers.
  5. Ensure the summary is concise (2-3 sentences) and highlights key qualifications relevant to the job.
  6. Prioritize skills mentioned in the job description.
  7. Include relevant projects, certifications, or awards that demonstrate qualifications for the job.
  8. All date fields must be in the format "YYYY-MM-DD". If a date is unknown or not applicable, use an empty string "".
  9. Ensure all required fields have valid values. Use placeholder data if necessary.
  10. Do not include any fields that are not in the specified structure.
  11. Use quantifiable achievements and specific examples where possible in the experience descriptions.
  12. Ensure that the experience points are tailored to the job description, highlighting transferable skills and relevant accomplishments.
  
  Return only the JSON object, no additional text.`;
}
function validateResumeContent(content) {
  const requiredFields = [
    "title",
    "summary",
    "email",
    "phone",
    "location",
    "sections",
  ];
  const requiredSections = [
    "socialLinks",
    "education",
    "experience",
    "skills",
    "certifications",
    "projects",
    "languages",
    "awards",
  ];

  for (const field of requiredFields) {
    if (!content[field]) {
      content[field] = ""; // Set empty string for missing required fields
    }
  }

  for (const section of requiredSections) {
    if (
      !content.sections[section] ||
      !Array.isArray(content.sections[section])
    ) {
      content.sections[section] = [];
    }
  }

  // Ensure each item in each section has an id and valid dates
  for (const section of requiredSections) {
    content.sections[section] = content.sections[section].map((item) => {
      const validatedItem = { ...item, id: item.id || generateUniqueId() };

      // Validate date fields
      [
        "startDate",
        "endDate",
        "issueDate",
        "expirationDate",
        "dateReceived",
      ].forEach((dateField) => {
        if (dateField in validatedItem) {
          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 ""; // Invalid date

  return date.toISOString().split("T")[0]; // Return YYYY-MM-DD format
}

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

function generateCoverLetterPrompt(profile, jobDescription) {
  return `Write a compelling cover letter for the following person based on their profile and the job description provided. Return the result as a JSON object with the following structure:

{
  "salutation": "Dear Hiring Manager,",
  "opening": "Opening paragraph",
  "body": ["Body paragraph 1", "Body paragraph 2"],
  "closing": "Closing paragraph",
  "signature": "Sincerely,\\n[Full Name]"
}

Profile:
${JSON.stringify(profile, null, 2)}

Job Description:
${jobDescription}

The cover letter should be professional, engaging, and tailored to the specific job opportunity. Return only the JSON object, no additional text.`;
}

function generateEmailPrompt(profile, jobDescription) {
  return `Compose a professional email for job application for the following person based on their profile and the job description provided. Return the result as a JSON object with the following structure:

{
  "subject": "Application for [Job Title] - [Your Name]",
  "greeting": "Dear Hiring Manager,",
  "body": ["Paragraph 1", "Paragraph 2"],
  "closing": "Closing line",
  "signature": "Best regards,\\n[Your Name]\\n[Your Phone Number]\\n[Your Email]"
}

Profile:
${JSON.stringify(profile, null, 2)}

Job Description:
${jobDescription}

The email should be concise, professional, and express interest in the position while highlighting key qualifications. Return only the JSON object, no additional text.`;
}