I am building an application in Next.js, TailwindCSS, Appwrite, and Zustand.  Now update my api so this genrates extact same json everytime according to the doc code and remeber I am coding in js and example is tpyescript 

EXAMPLE CODE
JSON Mode
Learn how to use JSON mode to get structured outputs from LLMs including Llama 3.1.

Suggest Edits
JSON mode corrals the LLM into outputting JSON conforming to a provided schema. To activate JSON mode, provide the response_format parameter to the Chat Completions API with {"type": "json_object"}. The JSON Schema can be specified with the schema property of response_format.

Supported models
meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo
meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo
mistralai/Mixtral-8x7B-Instruct-v0.1
mistralai/Mistral-7B-Instruct-v0.1
JSON mode example
When using JSON mode, always instruct the model to produce JSON, either in a system or user message. This is very important so that it only responds in JSON, along with providing the response_format parameter.

With JSON mode, you can specify a schema for the output of the LLM. In Python, we'll do this with Pydantic and in TypeScript, we'll do this with Zod. Here's an example of JSON mode with Python using Llama 3.1.

Python
TypeScript
curl

import Together from 'together-ai';
import { z } from 'zod';
import { zodToJsonSchema } from 'zod-to-json-schema';

const together = new Together();

// Defining the schema we want our data in
const voiceNoteSchema = z.object({
  title: z.string().describe('A title for the voice note'),
  summary: z
    .string()
    .describe('A short one sentence summary of the voice note.'),
  actionItems: z
    .array(z.string())
    .describe('A list of action items from the voice note'),
});
const jsonSchema = zodToJsonSchema(voiceNoteSchema, 'voiceNoteSchema');

async function main() {
  const transcript =
    "Good morning! It's 7:00 AM, and I'm just waking up. Today is going to be a busy day, so let's get started. First, I need to make a quick breakfast. I think I'll have some scrambled eggs and toast with a cup of coffee. While I'm cooking, I'll also check my emails to see if there's anything urgent.";
  const extract = await together.chat.completions.create({
    messages: [
      {
        role: 'system',
        content:
          'The following is a voice message transcript. Only answer in JSON.',
      },
      {
        role: 'user',
        content: transcript,
      },
    ],
    model: 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo',
    // @ts-ignore
    response_format: { type: 'json_object', schema: jsonSchema },
  });

  if (extract?.choices?.[0]?.message?.content) {
    const output = JSON.parse(extract?.choices?.[0]?.message?.content);
    console.log(output);
    return output;
  }
  return 'No output.';
}

main();

{
  title: 'Morning Routine',
  actionItems: [ 'Make breakfast', 'Check emails' ],
  summary: 'The speaker is starting their day by making breakfast and checking their emails.'
}

API 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.`;
}