okay I have some issues with my LLM code, this is to generate Cv based on the input cv pdf here's my code and its corresponding response: code: router.post('/createCvAndCoverLetter1', authMiddleware, rateLimiterMiddleware, upload.single('cv'), async (req, res) => { let filePath; try { const { job_title, job_description } = req.body; if (!req.file || !job_title || !job_description) { return res.status(400).json({ error: 'Missing required fields or file.' }); } // Parse document filePath = req.file.path; let resumeText = ''; if (req.file.mimetype === 'application/pdf') { const fileBuffer = fs.readFileSync(filePath); const loadingTask = pdfjsLib.getDocument({ data: new Uint8Array(fileBuffer), standardFontDataUrl: STANDARD_FONT_DATA_URL, }); const pdf = await loadingTask.promise; for (let i = 1; i <= pdf.numPages; i++) { const page = await pdf.getPage(i); const textContent = await page.getTextContent(); resumeText += textContent.items.map(item => item.str).join(' '); } } else if (req.file.mimetype === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') { const result = await mammoth.extractRawText({ path: filePath }); resumeText = result.value; } else { return res.status(400).json({ error: 'Unsupported file type' }); } // Extract name and email const name = extractName(resumeText); const email = extractEmail(resumeText); // Process with Ollama API const generateDocumentPrompt = (type) => `[INST] <> You are an expert ${type} writer with 15 years experience in ${job_title}. Generate ATS-optimized HTML documents compatible with Summernote. <> RESUME INPUT: ${resumeText} JOB DESCRIPTION: ${job_description} [REQUIREMENTS] 1. Maintain name: ${extractName(resumeText)} and email: ${extractEmail(resumeText)} 2. Use inline CSS (no Tailwind) 3. Structure: ${type === 'CV' ? 'Contact, Summary, Experience, Education, Skills' : 'Introduction, Body, Conclusion'} 4. Modern styling 5. Replace \\n with
[OUTPUT_FORMAT] - HTML5 with inline styles - Valid HTML between
tags only - No explanations - No markdown, only html5 contents - Professionally written contents [/OUTPUT_FORMAT] [/INST]`; // Generate initial documents const [cvResponse, coverLetterResponse] = await Promise.all([ callOllamaAPI(generateDocumentPrompt('CV')), callOllamaAPI(generateDocumentPrompt('Cover Letter')) ]); // Validate HTML structure if (!isValidHTML(cvResponse) || !isValidHTML(coverLetterResponse)) { throw new Error('Invalid HTML generated'); } // Refinement prompt template const refinePrompt = (content, type) => `[INST] <> You are a professional ${type} editor with over 15 years of Experience specializing in ${job_title}. Optimize document for ATS and improve formatting. <> REFINE THIS ${type.toUpperCase()}: ${content} [REQUIREMENTS] 1. Enhance ATS keywords: ${extractKeywords(job_description, 15)} 2. Improve content hierarchy 3. Optimize inline CSS 4. Maintain HTML structure 5. Ensure the HTML is compatible with Summernote, a WYSIWYG editor. [SAFETY] - Redact personal info except name/email - Professional tone only - No external links - Don't mention what you have done with ${type} document in your output [/SAFETY] [OUTPUT_FORMAT] - HTML5 with inline styles - Valid HTML between
tags only - No explanations - No markdown, only html5 tags - Professionally written contents [/OUTPUT_FORMAT] [/INST]`; // Parallel refinement const [refinedCV, refinedCoverLetter] = await Promise.all([ callOllamaAPI(refinePrompt(cvResponse, 'CV')), callOllamaAPI(refinePrompt(coverLetterResponse, 'Cover Letter')) ]); // Supabase update const supabase = getSupabase(req.session.authToken); const { data: { user }, error: authError } = await supabase.auth.getUser(); if (authError || !user) throw new Error('User authentication failed'); const { error: updateError } = await supabase .from('user_profiles') .update({ free_cv: false, updated_at: new Date().toISOString() }) .eq('user_id', user.id); if (updateError) throw updateError; // Final response res.json({ cv: sanitizeHTML(refinedCV), coverLetter: sanitizeHTML(refinedCoverLetter) }); } catch (error) { console.error('CV Processing Error:', error); res.status(500).json({ error: 'Processing failed', details: error?.message || 'Unknown error', }); } finally { if (filePath && fs.existsSync(filePath)) { fs.unlinkSync(filePath); } } }); function isValidHTML(content) { return //i.test(content); } function extractKeywords(text, limit=15) { return [...new Set(text.match(/\b(\w+)\b/g))].slice(0, limit).join(', '); } function sanitizeHTML(content) { const allowedTags = [ 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'br', 'span', 'strong', 'em', 'ul', 'ol', 'li', 'a', 'img', 'table', 'thead', 'tbody', 'tr', 'th', 'td' ]; const allowedAttributes = { '*': ['style', 'class', 'id'], 'a': ['href', 'target', 'rel'], 'img': ['src', 'alt', 'title'] }; const allowedSchemes = ['http', 'https', 'mailto', 'tel']; return sanitizeHtml(content, { allowedTags: allowedTags, allowedAttributes: allowedAttributes, allowedSchemes: allowedSchemes, allowedSchemesByTag: { 'a': ['http', 'https', 'mailto', 'tel'] }, transformTags: { 'a': sanitizeHtml.simpleTransform('a', { target: '_blank', rel: 'noopener noreferrer' }) } }); } const extractName = (text) => { // Common patterns for names in resumes const namePatterns = [ /^[A-Z][a-z]+(?:\s[A-Z][a-z]*)*/, // "John Doe" or "John A. Doe" /^[A-Z][a-z]+\s[A-Z][a-z]+/, // "John Doe" /^[A-Z][a-z]+,\s[A-Z][a-z]+/, // "Doe, John" /^[A-Z][a-z]+\s[A-Z]\.\s[A-Z][a-z]+/, // "John A. Doe" ]; // Try each pattern until a match is found for (const pattern of namePatterns) { const match = text.match(pattern); if (match) { return match[0].trim(); // Return the first match } } // Fallback if no name is found return "Applicant Name"; }; const extractEmail = (text) => { // Regex to match email addresses const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/; const match = text.match(emailRegex); // Return the first match or a default value return match ? match[0].trim() : "email@example.com"; }; cv output:

Raissa Sama Mbogueu

Montreal H3L 1L3

438-787-7170

email@example.com

Summary

Experienced Digital Marketing Manager seeking to lead clients and drive successful marketing campaigns.

Experience

  • Bilingual Customer Service Associate Guinnes Brewery Cameroon (2017-2024)
  • Education University of Buea, BSc Management

Proven track record of providing excellent customer service in a fast-paced environment. Developed strong product knowledge and communication skills to effectively address customer inquiries and concerns.

Skills

  • Microsoft Word
  • Microsoft Excel
  • Bilingual (French and English)
  • Customer Service
  • Troubleshooting
  • Communication
cover letter output:

Raissa Sama Mbogueu

Email: **email@example.com**

Phone: 438-787-7170

Digital Marketing Candidate

Overview

We are seeking an experienced Head of Digital Marketing to lead our clients and drive business growth. With a strong background in the fashion industry, I possess a solid understanding of e-commerce dynamics and the UAE market.

Summary

I am a seasoned digital marketing professional with 15 years of experience in managing successful campaigns. I hold a BSc Management degree from the University of Buea and am fluent in French and English.

Work Experience

  • Bilingual Customer Service Associate, Guinness Cameroon (2017-2024)
  • BSc Management, University of Buea (2016)

Education & Training

University of Buea, BSc Management (2016)

Skills

  • Digital Marketing and E-commerce
  • Team Leadership and Management
  • Customer Service and Communication
  • Microsoft Word, Excel
  • Bilingual (French and English)

About Me:

I am a seasoned digital marketing professional with a strong understanding of the fashion industry and the UAE market. I possess excellent communication skills and experience in leading teams to achieve business growth.

Contact Information

Email: **email@example.com**

Phone: 438-787-7170

here's the job description sent: Job Overview: We are seeking an experienced Head of Digital Marketing to lead our clients digital marketing strategy and execution for their thriving e-commerce fashion brand. The ideal candidate will have a proven track record in digital marketing, specifically within the fashion industry, and substantial experience in the UAE market. This role requires a strategic thinker who can drive brand growth, enhance customer engagement, and increase online sales. Key Responsibilities: * Develop and Implement Digital Marketing Strategy: Lead the creation and execution of comprehensive digital marketing strategies that align with business goals and drive growth. * Team Leadership: Manage and mentor a team of digital marketing professionals, fostering a culture of innovation and excellence. * Performance Marketing: Oversee performance marketing campaigns across channels such as Google Ads, Facebook Ads, and affiliate marketing to drive traffic and conversions. * SEO & Content Marketing: Develop and implement SEO and content marketing strategies to improve organic search visibility and engagement. * Social Media Management: Oversee social media strategies, content creation, and community management to enhance brand presence and customer interaction. * Email Marketing: Lead the planning and execution of email marketing campaigns, ensuring effective segmentation and personalization to maximize ROI. * Data Analysis & Reporting: Utilize analytics tools to measure and report on campaign performance, using insights to optimize future strategies. * Market Research: Stay abreast of industry trends, competitor activities, and market developments, particularly within the UAE. * Budget Management: Manage the digital marketing budget, ensuring efficient allocation and maximizing ROI. Qualifications: * Experience: Minimum of 8 years of experience in digital marketing, with at least 3 years in a leadership role. * Industry Knowledge: Strong background in the fashion industry, with a solid understanding of e-commerce dynamics. * UAE Market Expertise: Proven experience in the UAE market, with a deep understanding of local consumer behavior and digital trends. * Technical Skills: Proficient in digital marketing tools and platforms, including Google Analytics, SEO tools, PPC platforms, and CRM systems. * Analytical Skills: Strong analytical mindset with the ability to interpret data and translate it into actionable strategies. * Leadership: Exceptional leadership and team management skills. * Communication: Excellent verbal and written communication skills, with the ability to present strategies and results to stakeholders. Preferred Qualifications: * Experience in luxury or high-end fashion brands.