Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
Refactor and modularize multi agenti system
Khuram Niaz90f3e878a8d1
diff --git a/src/lib/ai/multi-agent.ts b/src/lib/ai/multi-agent.tsindex e6a69e2..58db987 100644--- a/src/lib/ai/multi-agent.ts+++ b/src/lib/ai/multi-agent.ts@@ -8,1007 +8,16 @@* - Analysis Agent: Data analysis, keyword optimization, and scoring* - Feedback Agent: Actionable recommendations and synthesis* - Both agents run in parallel (independent of each other)+ *+ * Implementation split into:+ * - multi-agent/utils.ts - Shared utilities (retry, timeout)+ * - multi-agent/resume-review.ts - Resume review logic+ * - multi-agent/job-match.ts - Job match logic*/-import { generateObject } from "ai";-import { z } from "zod";-import { getModel, ProviderType } from "./providers";-import { AnalysisAgentSchema, FeedbackAgentSchema } from "@/models/ai.schemas";-import {- ANALYSIS_AGENT_PROMPT,- FEEDBACK_AGENT_PROMPT,-} from "./prompts/prompts.agents";-import type {- SemanticSkillMatch,- SemanticSimilarityResult,-} from "@/models/ai.schemas";-import {- countQuantifiedAchievements,- analyzeFormatting,- extractSemanticKeywords,- analyzeActionVerbs,- performSemanticSkillMatch,- calculateSemanticSimilarity,- generateMatchExplanation,- getKeywordCountFromSemantic,- getVerbCountFromSemantic,- AIUnavailableError,-} from "./tools";-import { ProgressStream } from "./progress-stream";-import {- calculateResumeScore,- calculateJobMatchScore,- validateScore,- calculateAllowedVariance,-} from "./scoring";-import {- ResumeReviewResponse,- JobMatchResponse,- AgentInsights,- AnalysisResult,- FeedbackResult,- CollaborativeResult,- ToolDataResume,- ToolDataJobMatch,-} from "@/models/ai.model";-import {- OllamaAnalysisAgentSchema,- OllamaFeedbackAgentSchema,-} from "@/models/ai.ollama-schemas";--// ============================================================================-// RETRY MECHANISM-// ============================================================================--async function runWithRetry<T>(- operation: () => Promise<T>,- operationName: string,- maxRetries: number = 1-): Promise<T> {- let lastError: Error = new Error("Unknown error");-- for (let attempt = 0; attempt <= maxRetries; attempt++) {- try {- return await operation();- } catch (error) {- lastError = error instanceof Error ? error : new Error(String(error));- console.warn(- `${operationName} attempt ${attempt + 1} failed:`,- lastError.message- );-- if (attempt < maxRetries) {- const delay = 1000 * Math.pow(2, attempt);- await new Promise((resolve) => setTimeout(resolve, delay));- }- }- }-- throw new Error(- `${operationName} failed after ${maxRetries + 1} attempts: ${- lastError.message- }`- );-}--// ============================================================================-// TIMEOUT WRAPPER (Phase 4: Prevent small model hangs)-// ============================================================================--const SEMANTIC_TIMEOUT_MS = 60000; // 60 seconds for semantic extraction (Ollama needs more time)-const AGENT_TIMEOUT_MS = 120000; // 120 seconds for agent calls--function isOllamaProvider(provider: ProviderType): boolean {- return provider === "ollama";-}--async function withTimeout<T>(- promise: Promise<T>,- timeoutMs: number,- operationName: string-): Promise<T> {- let timeoutId: NodeJS.Timeout;- const timeoutPromise = new Promise<never>((_, reject) => {- timeoutId = setTimeout(() => {- reject(new Error(`${operationName} timed out after ${timeoutMs}ms`));- }, timeoutMs);- });-- try {- const result = await Promise.race([promise, timeoutPromise]);- clearTimeout(timeoutId!);- return result;- } catch (error) {- clearTimeout(timeoutId!);- throw error;- }-}--// ============================================================================-// RESUME REVIEW-// ============================================================================--export async function multiAgentResumeReview(- resumeText: string,- provider: ProviderType,- modelName: string,- progressStream?: ProgressStream-): Promise<CollaborativeResult<ResumeReviewResponse>> {- const model = getModel(provider, modelName);-- // =========================================================================- // STEP 1: Tool Extraction - Semantic Extraction is now the default (Phase 3)- // =========================================================================- progressStream?.sendStarted("tool-extraction", 0);-- // Phase 3: Semantic extraction is now the default- // Legacy extraction only used as fallback if semantic extraction fails- let toolData: ToolDataResume;-- try {- // Phase 4: Wrap with timeout to prevent small model hangs- const [semanticKeywords, semanticVerbs] = await Promise.all([- withTimeout(- extractSemanticKeywords(resumeText, provider, modelName),- SEMANTIC_TIMEOUT_MS,- "extractSemanticKeywords"- ),- withTimeout(- analyzeActionVerbs(resumeText, provider, modelName),- SEMANTIC_TIMEOUT_MS,- "analyzeActionVerbs"- ),- ]);-- const quantified = countQuantifiedAchievements(resumeText);- const formatting = analyzeFormatting(resumeText);-- toolData = {- quantified,- keywords: {- keywords: [- ...semanticKeywords.technical_skills,- ...semanticKeywords.tools_platforms,- ...semanticKeywords.methodologies,- ],- count: getKeywordCountFromSemantic(semanticKeywords),- },- verbs: {- verbs: semanticVerbs.strong_verbs.map((v) => v.verb),- count: getVerbCountFromSemantic(semanticVerbs),- },- formatting,- };-- console.log("[Resume Review] Using semantic extraction (Phase 3)");- } catch (error) {- const errorMessage = error instanceof Error ? error.message : String(error);- const isTimeout = errorMessage.includes("timed out");-- console.error("[Resume Review] Semantic extraction failed:", error);-- // Send user-friendly error message- if (progressStream) {- const warningMsg = isTimeout- ? "AI model is taking too long. Please try again or use a different model."- : "AI unavailable for resume analysis. Please try again later.";- progressStream.sendWarning("tool-extraction", warningMsg, 0);- }-- throw new AIUnavailableError("resume analysis");- }-- progressStream?.sendCompleted("tool-extraction", 0);-- // =========================================================================- // STEP 2: Calculate Baseline Score- // =========================================================================- const baselineScore = calculateResumeScore({- quantifiedCount: toolData.quantified.count,- keywordCount: toolData.keywords.count,- verbCount: toolData.verbs.count,- hasBulletPoints: toolData.formatting.hasBulletPoints,- sectionCount: toolData.formatting.sectionCount,- });-- const allowedVariance = calculateAllowedVariance(- baselineScore.score,- "resume"- );- const minScore = Math.max(0, baselineScore.score - allowedVariance);- const maxScore = Math.min(100, baselineScore.score + allowedVariance);-- console.log(- `[Resume Review] Baseline: ${baselineScore.score}, Allowed variance: ±${allowedVariance} (${minScore}-${maxScore})`- );-- // =========================================================================- // STEP 3: PARALLEL - Analysis Agent & Feedback Agent- // These agents can run simultaneously as they're independent- // =========================================================================- progressStream?.sendStarted("analysis-agent", 1);- progressStream?.sendStarted("feedback-agent", 2);-- const isOllama = isOllamaProvider(provider);-- // Build prompts - simpler for Ollama- const analysisPrompt = isOllama- ? `Score this resume. Baseline: ${- baselineScore.score- }, range: ${minScore}-${maxScore}.--Resume:-${resumeText}--Metrics: ${toolData.quantified.count} achievements, ${- toolData.keywords.count- } keywords, ${toolData.verbs.count} action verbs.-Keywords found: ${toolData.keywords.keywords.slice(0, 15).join(", ")}`- : `Analyze this resume comprehensively:--RESUME:-${resumeText}--OBJECTIVE METRICS (from tools):-- Quantified achievements: ${toolData.quantified.count} found- Examples: ${toolData.quantified.examples.slice(0, 3).join(", ")}-- Keywords: ${toolData.keywords.count} found- List: ${toolData.keywords.keywords.slice(0, 20).join(", ")}-- Action verbs: ${toolData.verbs.count} found- List: ${toolData.verbs.verbs.slice(0, 15).join(", ")}-- Formatting: ${- toolData.formatting.hasBulletPoints ? "Has bullets" : "No bullets"- }, ${toolData.formatting.sectionCount} sections--CALCULATED BASELINE SCORE: ${baselineScore.score}/100--BASELINE BREAKDOWN (mathematically calculated):-- Keywords: ${baselineScore.breakdown.keywords}/20 (FIXED based on count)-- Achievements: ${- baselineScore.breakdown.achievements- }/25 (FIXED based on count)-- Action Verbs: ${baselineScore.breakdown.verbs}/10 (FIXED based on count)-- Formatting: ${baselineScore.breakdown.formatting}/15 (FIXED based on analysis)-- Summary: ${baselineScore.breakdown.summary}/10 (adjustable based on quality)-- Experience: ${- baselineScore.breakdown.experienceClarity- }/10 (adjustable based on clarity)-- Skills: ${- baselineScore.breakdown.skillsSection- }/5 (adjustable based on organization)-- Grammar: ${baselineScore.breakdown.grammar}/5 (adjustable based on errors)--YOUR TASKS:-1. Verify/comment on the objective data analysis-2. Assess keyword strength and ATS optimization (0-100 score)-3. Identify missing critical keywords for resume improvement-4. Calculate final score by adjusting ONLY the subjective criteria (last 4)-5. Your final score MUST be between ${minScore} and ${maxScore}--IMPORTANT: The first 4 criteria are FIXED (objective counts). You can only adjust the last 4 based on resume quality.`;-- const feedbackPrompt = isOllama- ? `Give feedback on this resume. Score: ${baselineScore.score}.--Resume:-${resumeText}--Provide strengths, weaknesses, and suggestions.`- : `Generate actionable feedback for this resume:--RESUME:-${resumeText}--CONTEXT:-- Baseline score: ${baselineScore.score}/100 (calculated from objective metrics)-- Expected final score range: ${minScore}-${maxScore}--YOUR TASKS:-1. Identify 2-5 specific strengths with evidence from the resume-2. Identify 2-5 weaknesses that matter for job search success-3. Provide 2-5 actionable suggestions with exact implementation steps-4. Add synthesis notes on consistency between likely score and feedback--Be specific, actionable, and encouraging. Reference actual resume content.`;-- let analysisResult: AnalysisResult;- let feedbackResult: FeedbackResult;-- // Select schema based on provider- const analysisSchema = isOllama- ? OllamaAnalysisAgentSchema- : AnalysisAgentSchema;- const feedbackSchema = isOllama- ? OllamaFeedbackAgentSchema- : FeedbackAgentSchema;-- // Simplified system prompts for Ollama- const analysisSystemPrompt = isOllama- ? "You are a resume analyzer. Analyze the resume and provide a score with explanation."- : ANALYSIS_AGENT_PROMPT;- const feedbackSystemPrompt = isOllama- ? "You are a resume feedback expert. Provide strengths, weaknesses, and suggestions."- : FEEDBACK_AGENT_PROMPT;-- try {- const [rawAnalysis, rawFeedback] = await Promise.all([- // Analysis Agent with timeout- withTimeout(- runWithRetry(async () => {- const { object } = await generateObject({- model,- schema: analysisSchema,- system: analysisSystemPrompt,- prompt: analysisPrompt,- temperature: 0.1,- });- return object;- }, "Analysis Agent"),- AGENT_TIMEOUT_MS,- "Analysis Agent"- ),-- // Feedback Agent with timeout- withTimeout(- runWithRetry(async () => {- const { object } = await generateObject({- model,- schema: feedbackSchema,- system: feedbackSystemPrompt,- prompt: feedbackPrompt,- temperature: 0.3,- });- return object;- }, "Feedback Agent"),- AGENT_TIMEOUT_MS,- "Feedback Agent"- ),- ]);-- // Normalize Ollama results to full format- if (isOllama) {- const ollamaAnalysis = rawAnalysis as z.infer<- typeof OllamaAnalysisAgentSchema- >;- analysisResult = {- finalScore: ollamaAnalysis.finalScore,- dataInsights: {- quantifiedCount: ollamaAnalysis.quantifiedCount,- keywordCount: ollamaAnalysis.keywordCount,- verbCount: toolData.verbs.count,- formatQuality: "Analyzed by Ollama",- },- keywordAnalysis: {- strength: "Analyzed",- atsScore: ollamaAnalysis.atsScore,- missingCritical: ollamaAnalysis.missingKeywords,- recommendations: [],- },- adjustments: [],- math: ollamaAnalysis.scoreExplanation,- };-- const ollamaFeedback = rawFeedback as z.infer<- typeof OllamaFeedbackAgentSchema- >;- feedbackResult = {- strengths: ollamaFeedback.strengths,- weaknesses: ollamaFeedback.weaknesses,- suggestions: ollamaFeedback.suggestions,- synthesisNotes: ollamaFeedback.summary,- };- } else {- analysisResult = rawAnalysis as AnalysisResult;- feedbackResult = rawFeedback as FeedbackResult;- }- } catch (error) {- const errorMessage = error instanceof Error ? error.message : String(error);- const isTimeout = errorMessage.includes("timed out");-- console.error("[Resume Review] Agent execution failed:", error);-- // Send user-friendly error message- if (progressStream) {- const warningMsg = isTimeout- ? "Analysis is taking too long. Please try again or use a faster model."- : "Analysis failed. Please try again.";- progressStream.sendWarning("analysis-agent", warningMsg, 1);- }-- // Throw to let caller handle the error- throw new Error(- isTimeout- ? "Resume review timed out. The AI model may be overloaded. Please try again."- : `Resume review failed: ${errorMessage}`- );- }-- progressStream?.sendCompleted("analysis-agent", 1);- progressStream?.sendCompleted("feedback-agent", 2);-- // =========================================================================- // STEP 4: Validation- // =========================================================================- const validatedScore = validateScore(- analysisResult.finalScore,- baselineScore.score,- allowedVariance- );-- const warnings: string[] = [];- if (validatedScore !== analysisResult.finalScore) {- warnings.push(- `Score adjusted from ${analysisResult.finalScore} to ${validatedScore} (outside allowed variance)`- );- }-- // =========================================================================- // STEP 5: Build Final Response- // =========================================================================- const finalResponse: ResumeReviewResponse = {- score: validatedScore,- summary: `This resume scores ${validatedScore}/100, which is ${- validatedScore >= 70- ? "above average"- : validatedScore >= 50- ? "average"- : "below average"- }. ${feedbackResult.strengths[0] || "Multiple strengths identified."}`,- strengths: feedbackResult.strengths,- weaknesses: feedbackResult.weaknesses,- suggestions: feedbackResult.suggestions,- };-- const agentInsights: AgentInsights = {- analysis: analysisResult,- feedback: feedbackResult,- };-- return {- analysis: finalResponse,- agentInsights,- baselineScore,- warnings: warnings.length > 0 ? warnings : undefined,- };-}--// ============================================================================-// JOB MATCH-// ============================================================================--export async function multiAgentJobMatch(- resumeText: string,- jobDescription: string,- provider: ProviderType,- modelName: string,- progressStream?: ProgressStream-): Promise<CollaborativeResult<JobMatchResponse>> {- const model = getModel(provider, modelName);-- // =========================================================================- // STEP 1: Tool Extraction - Full Semantic Analysis (Phase 3)- // =========================================================================- progressStream?.sendStarted("tool-extraction", 0);-- // Phase 3: Full semantic matching is now the default- // Includes semantic skill matching AND semantic similarity calculation- let toolData: ToolDataJobMatch;- let semanticData: {- skillMatch: SemanticSkillMatch | null;- similarity: SemanticSimilarityResult | null;- matchExplanation: ReturnType<typeof generateMatchExplanation> | null;- } = { skillMatch: null, similarity: null, matchExplanation: null };-- try {- // Phase 4: Wrap semantic extraction with timeout to prevent small model hangs- const [semanticMatch, semanticSimilarity] = await Promise.all([- withTimeout(- performSemanticSkillMatch(- resumeText,- jobDescription,- provider,- modelName- ),- SEMANTIC_TIMEOUT_MS,- "performSemanticSkillMatch"- ),- withTimeout(- calculateSemanticSimilarity(- resumeText,- jobDescription,- provider,- modelName- ),- SEMANTIC_TIMEOUT_MS,- "calculateSemanticSimilarity"- ),- ]);-- // Generate comprehensive match explanation- const matchExplanation = generateMatchExplanation(- semanticMatch,- semanticSimilarity- );-- const matchedKeywords = [- ...semanticMatch.exact_matches.map((m) => m.skill),- ...semanticMatch.related_matches.map((m) => m.job_skill),- ];- const missingKeywords = semanticMatch.missing_skills.map((s) => s.skill);-- // Store semantic data for enhanced output- semanticData = {- skillMatch: semanticMatch,- similarity: semanticSimilarity,- matchExplanation,- };-- // Use semantic similarity score instead of simple keyword overlap percentage- toolData = {- keywordOverlap: {- overlapPercentage: semanticSimilarity.similarity_score, // Use semantic similarity!- matchedKeywords,- missingKeywords,- totalJobKeywords: matchedKeywords.length + missingKeywords.length,- },- resumeKeywords: {- keywords: matchedKeywords,- count: matchedKeywords.length,- },- jobKeywords: {- keywords: [...matchedKeywords, ...missingKeywords],- count: matchedKeywords.length + missingKeywords.length,- },- requiredSkills: {- requiredSkills: semanticMatch.missing_skills- .filter((s) => s.importance === "critical")- .map((s) => s.skill),- preferredSkills: semanticMatch.missing_skills- .filter((s) => s.importance === "important")- .map((s) => s.skill),- totalSkills: matchedKeywords.length + missingKeywords.length,- },- };-- console.log(- "[Job Match] Using semantic similarity (Phase 3):",- semanticSimilarity.similarity_score- );- } catch (error) {- const errorMessage = error instanceof Error ? error.message : String(error);- const isTimeout = errorMessage.includes("timed out");-- console.error("[Job Match] Semantic extraction failed:", error);-- // Send user-friendly error message- if (progressStream) {- const warningMsg = isTimeout- ? "AI model is taking too long. Please try again or use a different model."- : "AI unavailable for job matching. Please try again later.";- progressStream.sendWarning("tool-extraction", warningMsg, 0);- }-- throw new AIUnavailableError("job matching");- }-- progressStream?.sendCompleted("tool-extraction", 0);-- // =========================================================================- // STEP 2: Calculate Baseline Score- // =========================================================================- const matchedSkillsCount = toolData.keywordOverlap.matchedKeywords.length;- const requiredSkillsCount = Math.max(- toolData.requiredSkills.totalSkills,- toolData.keywordOverlap.totalJobKeywords- );-- const baselineScore = calculateJobMatchScore({- keywordOverlapPercent: toolData.keywordOverlap.overlapPercentage,- matchedSkillsCount,- requiredSkillsCount,- experienceYears: 0, // Will be assessed by AI- requiredYears: 0, // Will be assessed by AI- });-- const allowedVariance = calculateAllowedVariance(- baselineScore.score,- "job-match"- );- const minScore = Math.max(0, baselineScore.score - allowedVariance);- const maxScore = Math.min(100, baselineScore.score + allowedVariance);-- console.log(- `[Job Match] Baseline: ${baselineScore.score}, Allowed variance: ±${allowedVariance} (${minScore}-${maxScore})`- );-- // =========================================================================- // STEP 3: PARALLEL - Analysis Agent & Feedback Agent- // =========================================================================- progressStream?.sendStarted("analysis-agent", 1);- progressStream?.sendStarted("feedback-agent", 2);-- const isOllama = isOllamaProvider(provider);-- // Build prompts - simpler for Ollama- const analysisPrompt = isOllama- ? `Score this resume-job match. Baseline: ${- baselineScore.score- }, range: ${minScore}-${maxScore}.--Resume:-${resumeText}--Job:-${jobDescription}--Matched skills: ${toolData.keywordOverlap.matchedKeywords- .slice(0, 8)- .join(", ")}-Missing skills: ${toolData.keywordOverlap.missingKeywords- .slice(0, 8)- .join(", ")}`- : `Analyze how well this resume matches the job description:--RESUME:-${resumeText}--JOB DESCRIPTION:-${jobDescription}--OBJECTIVE METRICS (from tools):-- Skills matched: ${matchedSkillsCount} of ${requiredSkillsCount} (${Math.round(- (matchedSkillsCount / Math.max(requiredSkillsCount, 1)) * 100- )}%)-- Matched: ${toolData.keywordOverlap.matchedKeywords.slice(0, 10).join(", ")}-- Missing: ${toolData.keywordOverlap.missingKeywords.slice(0, 10).join(", ")}-- Keyword overlap: ${Math.round(toolData.keywordOverlap.overlapPercentage)}%--CALCULATED BASELINE SCORE: ${baselineScore.score}/100--BASELINE BREAKDOWN:-- Skills: ${baselineScore.breakdown.skillsMatch}/30 (FIXED based on match ratio)-- Keywords: ${- baselineScore.breakdown.keywordOverlap- }/20 (FIXED based on overlap)-- Experience: ${- baselineScore.breakdown.experienceMatch- }/25 (adjustable - assess from text)-- Qualifications: ${baselineScore.breakdown.qualifications}/15 (adjustable)-- Industry Fit: ${baselineScore.breakdown.industryFit}/10 (adjustable)--YOUR TASKS:-1. Verify the skills and keyword matching-2. Assess experience match and quality from the texts-3. Evaluate qualifications and industry fit-4. Calculate final score (must be ${minScore}-${maxScore})--Adjust only the last 3 criteria based on your assessment.`;-- const feedbackPrompt = isOllama- ? `Give feedback on this resume-job match. Score: ${baselineScore.score}.--Resume:-${resumeText}--Job:-${jobDescription}--Matched: ${toolData.keywordOverlap.matchedKeywords.slice(0, 5).join(", ")}-Missing: ${toolData.keywordOverlap.missingKeywords.slice(0, 5).join(", ")}`- : `Generate match feedback comparing resume to job description:--RESUME:-${resumeText}--JOB DESCRIPTION:-${jobDescription}--CONTEXT:-- Baseline score: ${baselineScore.score}/100-- Expected range: ${minScore}-${maxScore}-- Matched skills: ${toolData.keywordOverlap.matchedKeywords- .slice(0, 5)- .join(", ")}-- Missing skills: ${toolData.keywordOverlap.missingKeywords- .slice(0, 5)- .join(", ")}--YOUR TASKS:-1. Identify strengths that make this candidate a good fit-2. Identify gaps or weaknesses in the match-3. Provide specific suggestions to improve the match (keywords, skills, experience to highlight)-4. Add synthesis notes on overall fit assessment`;-- let analysisResult: AnalysisResult;- let feedbackResult: FeedbackResult;-- // Select schema based on provider- const analysisSchema = isOllama- ? OllamaAnalysisAgentSchema- : AnalysisAgentSchema;- const feedbackSchema = isOllama- ? OllamaFeedbackAgentSchema- : FeedbackAgentSchema;-- // Simplified system prompts for Ollama- const analysisSystemPrompt = isOllama- ? "You are a job match analyzer. Score how well the resume matches the job."- : ANALYSIS_AGENT_PROMPT;- const feedbackSystemPrompt = isOllama- ? "You are a job match expert. Provide strengths, gaps, and suggestions."- : FEEDBACK_AGENT_PROMPT;-- try {- const [rawAnalysis, rawFeedback] = await Promise.all([- // Analysis Agent with timeout- withTimeout(- runWithRetry(async () => {- const { object } = await generateObject({- model,- schema: analysisSchema,- system: analysisSystemPrompt,- prompt: analysisPrompt,- temperature: 0.1,- });- return object;- }, "Analysis Agent"),- AGENT_TIMEOUT_MS,- "Analysis Agent"- ),-- // Feedback Agent with timeout- withTimeout(- runWithRetry(async () => {- const { object } = await generateObject({- model,- schema: feedbackSchema,- system: feedbackSystemPrompt,- prompt: feedbackPrompt,- temperature: 0.3,- });- return object;- }, "Feedback Agent"),- AGENT_TIMEOUT_MS,- "Feedback Agent"- ),- ]);-- // Normalize Ollama results to full format- if (isOllama) {- const ollamaAnalysis = rawAnalysis as z.infer<- typeof OllamaAnalysisAgentSchema- >;- analysisResult = {- finalScore: ollamaAnalysis.finalScore,- dataInsights: {- quantifiedCount: ollamaAnalysis.quantifiedCount,- keywordCount: ollamaAnalysis.keywordCount,- verbCount: 0,- formatQuality: "Analyzed by Ollama",- },- keywordAnalysis: {- strength: "Analyzed",- atsScore: ollamaAnalysis.atsScore,- missingCritical: ollamaAnalysis.missingKeywords,- recommendations: [],- },- adjustments: [],- math: ollamaAnalysis.scoreExplanation,- };-- const ollamaFeedback = rawFeedback as z.infer<- typeof OllamaFeedbackAgentSchema- >;- feedbackResult = {- strengths: ollamaFeedback.strengths,- weaknesses: ollamaFeedback.weaknesses,- suggestions: ollamaFeedback.suggestions,- synthesisNotes: ollamaFeedback.summary,- };- } else {- analysisResult = rawAnalysis as AnalysisResult;- feedbackResult = rawFeedback as FeedbackResult;- }- } catch (error) {- const errorMessage = error instanceof Error ? error.message : String(error);- const isTimeout = errorMessage.includes("timed out");-- console.error("[Job Match] Agent execution failed:", error);-- // Send user-friendly error message- if (progressStream) {- const warningMsg = isTimeout- ? "Analysis is taking too long. Please try again or use a faster model."- : "Analysis failed. Please try again.";- progressStream.sendWarning("analysis-agent", warningMsg, 1);- }-- // Throw to let caller handle the error- throw new Error(- isTimeout- ? "Job match analysis timed out. The AI model may be overloaded. Please try again."- : `Job match analysis failed: ${errorMessage}`- );- }-- progressStream?.sendCompleted("analysis-agent", 1);- progressStream?.sendCompleted("feedback-agent", 2);-- // =========================================================================- // STEP 4: Validation- // =========================================================================- const validatedScore = validateScore(- analysisResult.finalScore,- baselineScore.score,- allowedVariance- );-- const warnings: string[] = [];- if (validatedScore !== analysisResult.finalScore) {- warnings.push(- `Score adjusted from ${analysisResult.finalScore} to ${validatedScore}`- );- }-- // =========================================================================- // STEP 5: Build Final Response (Enhanced with Phase 3 Semantic Data)- // =========================================================================-- // Build enhanced detailed analysis using semantic data when available- const detailedAnalysis = [];-- // Skills Match - use semantic skill match data if available- if (semanticData.skillMatch) {- const exactCount = semanticData.skillMatch.exact_matches.length;- const relatedCount = semanticData.skillMatch.related_matches.length;- const missingCount = semanticData.skillMatch.missing_skills.length;-- detailedAnalysis.push({- category: `Skills Match (${baselineScore.breakdown.skillsMatch}/30 pts)`,- value: [- `${exactCount} exact matches, ${relatedCount} transferable skills, ${missingCount} gaps`,- ...semanticData.skillMatch.exact_matches- .slice(0, 3)- .map(- (m) => `✅ ${m.skill}: "${m.resume_evidence.substring(0, 40)}..."`- ),- ...semanticData.skillMatch.related_matches- .slice(0, 2)- .map(- (m) =>- `⚡ ${m.resume_skill} → ${m.job_skill} (${m.similarity}% similar)`- ),- ...semanticData.skillMatch.missing_skills- .filter((s) => s.importance === "critical")- .slice(0, 2)- .map((s) => `❌ ${s.skill} (critical, ${s.learnability} to learn)`),- ],- });- } else {- detailedAnalysis.push({- category: `Skills Match (${baselineScore.breakdown.skillsMatch}/30 pts)`,- value: [- `Matched ${matchedSkillsCount} of ${requiredSkillsCount} required skills`,- ...toolData.keywordOverlap.matchedKeywords- .slice(0, 5)- .map((k) => `✅ ${k}`),- ...toolData.keywordOverlap.missingKeywords- .slice(0, 3)- .map((k) => `❌ ${k}`),- ],- });- }-- // Semantic Similarity - Phase 3 replacement for keyword overlap- if (semanticData.similarity) {- detailedAnalysis.push({- category: `Semantic Fit (${baselineScore.breakdown.keywordOverlap}/20 pts)`,- value: [- `${Math.round(- semanticData.similarity.similarity_score- )}% semantic match`,- semanticData.similarity.match_explanation,- ...semanticData.similarity.key_matches.slice(0, 2),- ],- });- } else {- detailedAnalysis.push({- category: `Keyword Overlap (${baselineScore.breakdown.keywordOverlap}/20 pts)`,- value: [- `${Math.round(- toolData.keywordOverlap.overlapPercentage- )}% keyword match`,- analysisResult.keywordAnalysis.strength,- ],- });- }-- // Transferable Skills (Phase 3 - new section)- if (- semanticData.similarity &&- semanticData.similarity.transferable_skills.length > 0- ) {- detailedAnalysis.push({- category: "Transferable Skills",- value: semanticData.similarity.transferable_skills- .slice(0, 3)- .map(- (s) => `💡 ${s.resume_skill} → ${s.job_skill}: ${s.how_it_transfers}`- ),- });- }-- // Overall Assessment- detailedAnalysis.push({- category: "Overall Assessment",- value: [- semanticData.matchExplanation?.fit_assessment ||- feedbackResult.synthesisNotes,- ],- });-- // Build suggestions using semantic data- const suggestions = [];-- // Action items from semantic analysis- if (- semanticData.matchExplanation &&- semanticData.matchExplanation.action_items.length > 0- ) {- suggestions.push({- category: "Priority Actions",- value: semanticData.matchExplanation.action_items.slice(0, 4),- });- }-- // Keywords to add- suggestions.push({- category: "Skills to Add",- value: analysisResult.keywordAnalysis.missingCritical.slice(0, 4),- });-- // Top improvements- suggestions.push({- category: "Top Improvements",- value: feedbackResult.suggestions.slice(0, 4),- });-- // Build additional comments with semantic recommendation- const recommendation =- semanticData.similarity?.application_recommendation ||- (validatedScore >= 70- ? "Apply now - strong match"- : validatedScore >= 50- ? "Apply after addressing key gaps"- : "Consider upskilling before applying");-- const finalResponse: JobMatchResponse = {- matching_score: validatedScore,- detailed_analysis: detailedAnalysis,- suggestions,- additional_comments: [- `Score: ${validatedScore}/100 - ${- validatedScore >= 70- ? "Strong"- : validatedScore >= 50- ? "Moderate"- : "Weak"- } match`,- semanticData.similarity?.match_explanation ||- feedbackResult.synthesisNotes,- `Recommendation: ${recommendation}`,- ],- };-- const agentInsights: AgentInsights = {- analysis: analysisResult,- feedback: feedbackResult,- };-- return {- analysis: finalResponse,- agentInsights,- baselineScore,- warnings: warnings.length > 0 ? warnings : undefined,- };-}+export {+ multiAgentResumeReview,+ multiAgentJobMatch,+ runWithRetry,+ withTimeout,+} from "./multi-agent/index";diff --git a/src/lib/ai/multi-agent/index.ts b/src/lib/ai/multi-agent/index.tsnew file mode 100644index 0000000..b118e2f--- /dev/null+++ b/src/lib/ai/multi-agent/index.ts@@ -0,0 +1,15 @@+/**+ * Multi-Agent Collaboration System+ *+ * Architecture:+ * User Request → Tools → Baseline → [Analysis Agent, Feedback Agent] → Validation → Output+ *+ * Agents:+ * - Analysis Agent: Data analysis, keyword optimization, and scoring+ * - Feedback Agent: Actionable recommendations and synthesis+ * - Both agents run in parallel (independent of each other)+ */++export { multiAgentResumeReview } from "./resume-review";+export { multiAgentJobMatch } from "./job-match";+export { runWithRetry, withTimeout } from "./utils";diff --git a/src/lib/ai/multi-agent/job-match.ts b/src/lib/ai/multi-agent/job-match.tsnew file mode 100644index 0000000..d2b5d6d--- /dev/null+++ b/src/lib/ai/multi-agent/job-match.ts@@ -0,0 +1,558 @@+/**+ * Multi-Agent Job Match+ *+ * Handles job matching analysis using the multi-agent collaboration system.+ */++import { generateObject } from "ai";+import { getModel, ProviderType } from "../providers";+import { AnalysisAgentSchema, FeedbackAgentSchema } from "@/models/ai.schemas";+import {+ ANALYSIS_AGENT_PROMPT,+ FEEDBACK_AGENT_PROMPT,+} from "../prompts/prompts.agents";+import type {+ SemanticSkillMatch,+ SemanticSimilarityResult,+} from "@/models/ai.schemas";+import {+ performSemanticSkillMatch,+ calculateSemanticSimilarity,+ generateMatchExplanation,+ AIUnavailableError,+} from "../tools";+import { ProgressStream } from "../progress-stream";+import {+ calculateJobMatchScore,+ validateScore,+ calculateAllowedVariance,+} from "../scoring";+import {+ JobMatchResponse,+ AgentInsights,+ AnalysisResult,+ FeedbackResult,+ CollaborativeResult,+ ToolDataJobMatch,+} from "@/models/ai.model";+import {+ isOllamaProvider,+ SEMANTIC_TIMEOUT_MS,+ AGENT_TIMEOUT_MS,+ OllamaAnalysisAgentSchema,+ OllamaFeedbackAgentSchema,+ normalizeAnalysisResult,+ normalizeFeedbackResult,+ OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT,+ OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT,+ buildOllamaJobMatchAnalysisPrompt,+ buildOllamaJobMatchFeedbackPrompt,+ type OllamaAnalysisAgent,+ type OllamaFeedbackAgent,+} from "../ollama";+import { runWithRetry, withTimeout } from "./utils";++// ============================================================================+// JOB MATCH+// ============================================================================++export async function multiAgentJobMatch(+ resumeText: string,+ jobDescription: string,+ provider: ProviderType,+ modelName: string,+ progressStream?: ProgressStream+): Promise<CollaborativeResult<JobMatchResponse>> {+ const model = getModel(provider, modelName);++ // =========================================================================+ // STEP 1: Tool Extraction - Full Semantic Analysis (Phase 3)+ // =========================================================================+ progressStream?.sendStarted("tool-extraction", 0);++ // Phase 3: Full semantic matching is now the default+ // Includes semantic skill matching AND semantic similarity calculation+ let toolData: ToolDataJobMatch;+ let semanticData: {+ skillMatch: SemanticSkillMatch | null;+ similarity: SemanticSimilarityResult | null;+ matchExplanation: ReturnType<typeof generateMatchExplanation> | null;+ } = { skillMatch: null, similarity: null, matchExplanation: null };++ try {+ // Phase 4: Wrap semantic extraction with timeout to prevent small model hangs+ const [semanticMatch, semanticSimilarity] = await Promise.all([+ withTimeout(+ performSemanticSkillMatch(+ resumeText,+ jobDescription,+ provider,+ modelName+ ),+ SEMANTIC_TIMEOUT_MS,+ "performSemanticSkillMatch"+ ),+ withTimeout(+ calculateSemanticSimilarity(+ resumeText,+ jobDescription,+ provider,+ modelName+ ),+ SEMANTIC_TIMEOUT_MS,+ "calculateSemanticSimilarity"+ ),+ ]);++ // Generate comprehensive match explanation+ const matchExplanation = generateMatchExplanation(+ semanticMatch,+ semanticSimilarity+ );++ const matchedKeywords = [+ ...semanticMatch.exact_matches.map((m) => m.skill),+ ...semanticMatch.related_matches.map((m) => m.job_skill),+ ];+ const missingKeywords = semanticMatch.missing_skills.map((s) => s.skill);++ // Store semantic data for enhanced output+ semanticData = {+ skillMatch: semanticMatch,+ similarity: semanticSimilarity,+ matchExplanation,+ };++ // Use semantic similarity score instead of simple keyword overlap percentage+ toolData = {+ keywordOverlap: {+ overlapPercentage: semanticSimilarity.similarity_score, // Use semantic similarity!+ matchedKeywords,+ missingKeywords,+ totalJobKeywords: matchedKeywords.length + missingKeywords.length,+ },+ resumeKeywords: {+ keywords: matchedKeywords,+ count: matchedKeywords.length,+ },+ jobKeywords: {+ keywords: [...matchedKeywords, ...missingKeywords],+ count: matchedKeywords.length + missingKeywords.length,+ },+ requiredSkills: {+ requiredSkills: semanticMatch.missing_skills+ .filter((s) => s.importance === "critical")+ .map((s) => s.skill),+ preferredSkills: semanticMatch.missing_skills+ .filter((s) => s.importance === "important")+ .map((s) => s.skill),+ totalSkills: matchedKeywords.length + missingKeywords.length,+ },+ };++ console.log(+ "[Job Match] Using semantic similarity (Phase 3):",+ semanticSimilarity.similarity_score+ );+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ const isTimeout = errorMessage.includes("timed out");++ console.error("[Job Match] Semantic extraction failed:", error);++ // Send user-friendly error message+ if (progressStream) {+ const warningMsg = isTimeout+ ? "AI model is taking too long. Please try again or use a different model."+ : "AI unavailable for job matching. Please try again later.";+ progressStream.sendWarning("tool-extraction", warningMsg, 0);+ }++ throw new AIUnavailableError("job matching");+ }++ progressStream?.sendCompleted("tool-extraction", 0);++ // =========================================================================+ // STEP 2: Calculate Baseline Score+ // =========================================================================+ const matchedSkillsCount = toolData.keywordOverlap.matchedKeywords.length;+ const requiredSkillsCount = Math.max(+ toolData.requiredSkills.totalSkills,+ toolData.keywordOverlap.totalJobKeywords+ );++ const baselineScore = calculateJobMatchScore({+ keywordOverlapPercent: toolData.keywordOverlap.overlapPercentage,+ matchedSkillsCount,+ requiredSkillsCount,+ experienceYears: 0, // Will be assessed by AI+ requiredYears: 0, // Will be assessed by AI+ });++ const allowedVariance = calculateAllowedVariance(+ baselineScore.score,+ "job-match"+ );+ const minScore = Math.max(0, baselineScore.score - allowedVariance);+ const maxScore = Math.min(100, baselineScore.score + allowedVariance);++ console.log(+ `[Job Match] Baseline: ${baselineScore.score}, Allowed variance: ±${allowedVariance} (${minScore}-${maxScore})`+ );++ // =========================================================================+ // STEP 3: PARALLEL - Analysis Agent & Feedback Agent+ // =========================================================================+ progressStream?.sendStarted("analysis-agent", 1);+ progressStream?.sendStarted("feedback-agent", 2);++ const isOllama = isOllamaProvider(provider);++ // Build prompts - simpler for Ollama+ const analysisPrompt = isOllama+ ? buildOllamaJobMatchAnalysisPrompt(+ resumeText,+ jobDescription,+ toolData,+ baselineScore,+ minScore,+ maxScore+ )+ : `Analyze how well this resume matches the job description:++RESUME:+${resumeText}++JOB DESCRIPTION:+${jobDescription}++OBJECTIVE METRICS (from tools):+- Skills matched: ${matchedSkillsCount} of ${requiredSkillsCount} (${Math.round(+ (matchedSkillsCount / Math.max(requiredSkillsCount, 1)) * 100+ )}%)+- Matched: ${toolData.keywordOverlap.matchedKeywords.slice(0, 10).join(", ")}+- Missing: ${toolData.keywordOverlap.missingKeywords.slice(0, 10).join(", ")}+- Keyword overlap: ${Math.round(toolData.keywordOverlap.overlapPercentage)}%++CALCULATED BASELINE SCORE: ${baselineScore.score}/100++BASELINE BREAKDOWN:+- Skills: ${baselineScore.breakdown.skillsMatch}/30 (FIXED based on match ratio)+- Keywords: ${+ baselineScore.breakdown.keywordOverlap+ }/20 (FIXED based on overlap)+- Experience: ${+ baselineScore.breakdown.experienceMatch+ }/25 (adjustable - assess from text)+- Qualifications: ${baselineScore.breakdown.qualifications}/15 (adjustable)+- Industry Fit: ${baselineScore.breakdown.industryFit}/10 (adjustable)++YOUR TASKS:+1. Verify the skills and keyword matching+2. Assess experience match and quality from the texts+3. Evaluate qualifications and industry fit+4. Calculate final score (must be ${minScore}-${maxScore})++Adjust only the last 3 criteria based on your assessment.`;++ const feedbackPrompt = isOllama+ ? buildOllamaJobMatchFeedbackPrompt(+ resumeText,+ jobDescription,+ toolData,+ baselineScore+ )+ : `Generate match feedback comparing resume to job description:++RESUME:+${resumeText}++JOB DESCRIPTION:+${jobDescription}++CONTEXT:+- Baseline score: ${baselineScore.score}/100+- Expected range: ${minScore}-${maxScore}+- Matched skills: ${toolData.keywordOverlap.matchedKeywords+ .slice(0, 5)+ .join(", ")}+- Missing skills: ${toolData.keywordOverlap.missingKeywords+ .slice(0, 5)+ .join(", ")}++YOUR TASKS:+1. Identify strengths that make this candidate a good fit+2. Identify gaps or weaknesses in the match+3. Provide specific suggestions to improve the match (keywords, skills, experience to highlight)+4. Add synthesis notes on overall fit assessment`;++ let analysisResult: AnalysisResult;+ let feedbackResult: FeedbackResult;++ // Select schema based on provider+ const analysisSchema = isOllama+ ? OllamaAnalysisAgentSchema+ : AnalysisAgentSchema;+ const feedbackSchema = isOllama+ ? OllamaFeedbackAgentSchema+ : FeedbackAgentSchema;++ // System prompts - simplified for Ollama+ const analysisSystemPrompt = isOllama+ ? OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT+ : ANALYSIS_AGENT_PROMPT;+ const feedbackSystemPrompt = isOllama+ ? OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT+ : FEEDBACK_AGENT_PROMPT;++ try {+ const [rawAnalysis, rawFeedback] = await Promise.all([+ // Analysis Agent with timeout+ withTimeout(+ runWithRetry(async () => {+ const { object } = await generateObject({+ model,+ schema: analysisSchema,+ system: analysisSystemPrompt,+ prompt: analysisPrompt,+ temperature: 0.1,+ });+ return object;+ }, "Analysis Agent"),+ AGENT_TIMEOUT_MS,+ "Analysis Agent"+ ),++ // Feedback Agent with timeout+ withTimeout(+ runWithRetry(async () => {+ const { object } = await generateObject({+ model,+ schema: feedbackSchema,+ system: feedbackSystemPrompt,+ prompt: feedbackPrompt,+ temperature: 0.3,+ });+ return object;+ }, "Feedback Agent"),+ AGENT_TIMEOUT_MS,+ "Feedback Agent"+ ),+ ]);++ // Normalize Ollama results to full format+ if (isOllama) {+ analysisResult = normalizeAnalysisResult(+ rawAnalysis as OllamaAnalysisAgent+ );+ feedbackResult = normalizeFeedbackResult(+ rawFeedback as OllamaFeedbackAgent+ );+ } else {+ analysisResult = rawAnalysis as AnalysisResult;+ feedbackResult = rawFeedback as FeedbackResult;+ }+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ const isTimeout = errorMessage.includes("timed out");++ console.error("[Job Match] Agent execution failed:", error);++ // Send user-friendly error message+ if (progressStream) {+ const warningMsg = isTimeout+ ? "Analysis is taking too long. Please try again or use a faster model."+ : "Analysis failed. Please try again.";+ progressStream.sendWarning("analysis-agent", warningMsg, 1);+ }++ // Throw to let caller handle the error+ throw new Error(+ isTimeout+ ? "Job match analysis timed out. The AI model may be overloaded. Please try again."+ : `Job match analysis failed: ${errorMessage}`+ );+ }++ progressStream?.sendCompleted("analysis-agent", 1);+ progressStream?.sendCompleted("feedback-agent", 2);++ // =========================================================================+ // STEP 4: Validation+ // =========================================================================+ const validatedScore = validateScore(+ analysisResult.finalScore,+ baselineScore.score,+ allowedVariance+ );++ const warnings: string[] = [];+ if (validatedScore !== analysisResult.finalScore) {+ warnings.push(+ `Score adjusted from ${analysisResult.finalScore} to ${validatedScore}`+ );+ }++ // =========================================================================+ // STEP 5: Build Final Response (Enhanced with Phase 3 Semantic Data)+ // =========================================================================++ // Build enhanced detailed analysis using semantic data when available+ const detailedAnalysis = [];++ // Skills Match - use semantic skill match data if available+ if (semanticData.skillMatch) {+ const exactCount = semanticData.skillMatch.exact_matches.length;+ const relatedCount = semanticData.skillMatch.related_matches.length;+ const missingCount = semanticData.skillMatch.missing_skills.length;++ detailedAnalysis.push({+ category: `Skills Match (${baselineScore.breakdown.skillsMatch}/30 pts)`,+ value: [+ `${exactCount} exact matches, ${relatedCount} transferable skills, ${missingCount} gaps`,+ ...semanticData.skillMatch.exact_matches+ .slice(0, 3)+ .map(+ (m) => `✅ ${m.skill}: "${m.resume_evidence.substring(0, 40)}..."`+ ),+ ...semanticData.skillMatch.related_matches+ .slice(0, 2)+ .map(+ (m) =>+ `⚡ ${m.resume_skill} → ${m.job_skill} (${m.similarity}% similar)`+ ),+ ...semanticData.skillMatch.missing_skills+ .filter((s) => s.importance === "critical")+ .slice(0, 2)+ .map((s) => `❌ ${s.skill} (critical, ${s.learnability} to learn)`),+ ],+ });+ } else {+ detailedAnalysis.push({+ category: `Skills Match (${baselineScore.breakdown.skillsMatch}/30 pts)`,+ value: [+ `Matched ${matchedSkillsCount} of ${requiredSkillsCount} required skills`,+ ...toolData.keywordOverlap.matchedKeywords+ .slice(0, 5)+ .map((k) => `✅ ${k}`),+ ...toolData.keywordOverlap.missingKeywords+ .slice(0, 3)+ .map((k) => `❌ ${k}`),+ ],+ });+ }++ // Semantic Similarity - Phase 3 replacement for keyword overlap+ if (semanticData.similarity) {+ detailedAnalysis.push({+ category: `Semantic Fit (${baselineScore.breakdown.keywordOverlap}/20 pts)`,+ value: [+ `${Math.round(+ semanticData.similarity.similarity_score+ )}% semantic match`,+ semanticData.similarity.match_explanation,+ ...semanticData.similarity.key_matches.slice(0, 2),+ ],+ });+ } else {+ detailedAnalysis.push({+ category: `Keyword Overlap (${baselineScore.breakdown.keywordOverlap}/20 pts)`,+ value: [+ `${Math.round(+ toolData.keywordOverlap.overlapPercentage+ )}% keyword match`,+ analysisResult.keywordAnalysis.strength,+ ],+ });+ }++ // Transferable Skills (Phase 3 - new section)+ if (+ semanticData.similarity &&+ semanticData.similarity.transferable_skills.length > 0+ ) {+ detailedAnalysis.push({+ category: "Transferable Skills",+ value: semanticData.similarity.transferable_skills+ .slice(0, 3)+ .map(+ (s) => `💡 ${s.resume_skill} → ${s.job_skill}: ${s.how_it_transfers}`+ ),+ });+ }++ // Overall Assessment+ detailedAnalysis.push({+ category: "Overall Assessment",+ value: [+ semanticData.matchExplanation?.fit_assessment ||+ feedbackResult.synthesisNotes,+ ],+ });++ // Build suggestions using semantic data+ const suggestions = [];++ // Action items from semantic analysis+ if (+ semanticData.matchExplanation &&+ semanticData.matchExplanation.action_items.length > 0+ ) {+ suggestions.push({+ category: "Priority Actions",+ value: semanticData.matchExplanation.action_items.slice(0, 4),+ });+ }++ // Keywords to add+ suggestions.push({+ category: "Skills to Add",+ value: analysisResult.keywordAnalysis.missingCritical.slice(0, 4),+ });++ // Top improvements+ suggestions.push({+ category: "Top Improvements",+ value: feedbackResult.suggestions.slice(0, 4),+ });++ // Build additional comments with semantic recommendation+ const recommendation =+ semanticData.similarity?.application_recommendation ||+ (validatedScore >= 70+ ? "Apply now - strong match"+ : validatedScore >= 50+ ? "Apply after addressing key gaps"+ : "Consider upskilling before applying");++ const finalResponse: JobMatchResponse = {+ matching_score: validatedScore,+ detailed_analysis: detailedAnalysis,+ suggestions,+ additional_comments: [+ `Score: ${validatedScore}/100 - ${+ validatedScore >= 70+ ? "Strong"+ : validatedScore >= 50+ ? "Moderate"+ : "Weak"+ } match`,+ semanticData.similarity?.match_explanation ||+ feedbackResult.synthesisNotes,+ `Recommendation: ${recommendation}`,+ ],+ };++ const agentInsights: AgentInsights = {+ analysis: analysisResult,+ feedback: feedbackResult,+ };++ return {+ analysis: finalResponse,+ agentInsights,+ baselineScore,+ warnings: warnings.length > 0 ? warnings : undefined,+ };+}diff --git a/src/lib/ai/multi-agent/resume-review.ts b/src/lib/ai/multi-agent/resume-review.tsnew file mode 100644index 0000000..0eefecb--- /dev/null+++ b/src/lib/ai/multi-agent/resume-review.ts@@ -0,0 +1,368 @@+/**+ * Multi-Agent Resume Review+ *+ * Handles resume analysis using the multi-agent collaboration system.+ */++import { generateObject } from "ai";+import { getModel, ProviderType } from "../providers";+import { AnalysisAgentSchema, FeedbackAgentSchema } from "@/models/ai.schemas";+import {+ ANALYSIS_AGENT_PROMPT,+ FEEDBACK_AGENT_PROMPT,+} from "../prompts/prompts.agents";+import {+ countQuantifiedAchievements,+ analyzeFormatting,+ extractSemanticKeywords,+ analyzeActionVerbs,+ getKeywordCountFromSemantic,+ getVerbCountFromSemantic,+ AIUnavailableError,+} from "../tools";+import { ProgressStream } from "../progress-stream";+import {+ calculateResumeScore,+ validateScore,+ calculateAllowedVariance,+} from "../scoring";+import {+ ResumeReviewResponse,+ AgentInsights,+ AnalysisResult,+ FeedbackResult,+ CollaborativeResult,+ ToolDataResume,+} from "@/models/ai.model";+import {+ isOllamaProvider,+ SEMANTIC_TIMEOUT_MS,+ AGENT_TIMEOUT_MS,+ OllamaAnalysisAgentSchema,+ OllamaFeedbackAgentSchema,+ normalizeAnalysisResult,+ normalizeFeedbackResult,+ OLLAMA_ANALYSIS_SYSTEM_PROMPT,+ OLLAMA_FEEDBACK_SYSTEM_PROMPT,+ buildOllamaResumeAnalysisPrompt,+ buildOllamaResumeFeedbackPrompt,+ type OllamaAnalysisAgent,+ type OllamaFeedbackAgent,+} from "../ollama";+import { runWithRetry, withTimeout } from "./utils";++// ============================================================================+// RESUME REVIEW+// ============================================================================++export async function multiAgentResumeReview(+ resumeText: string,+ provider: ProviderType,+ modelName: string,+ progressStream?: ProgressStream+): Promise<CollaborativeResult<ResumeReviewResponse>> {+ const model = getModel(provider, modelName);++ // =========================================================================+ // STEP 1: Tool Extraction - Semantic Extraction is now the default (Phase 3)+ // =========================================================================+ progressStream?.sendStarted("tool-extraction", 0);++ // Phase 3: Semantic extraction is now the default+ // Legacy extraction only used as fallback if semantic extraction fails+ let toolData: ToolDataResume;++ try {+ // Phase 4: Wrap with timeout to prevent small model hangs+ const [semanticKeywords, semanticVerbs] = await Promise.all([+ withTimeout(+ extractSemanticKeywords(resumeText, provider, modelName),+ SEMANTIC_TIMEOUT_MS,+ "extractSemanticKeywords"+ ),+ withTimeout(+ analyzeActionVerbs(resumeText, provider, modelName),+ SEMANTIC_TIMEOUT_MS,+ "analyzeActionVerbs"+ ),+ ]);++ const quantified = countQuantifiedAchievements(resumeText);+ const formatting = analyzeFormatting(resumeText);++ toolData = {+ quantified,+ keywords: {+ keywords: [+ ...semanticKeywords.technical_skills,+ ...semanticKeywords.tools_platforms,+ ...semanticKeywords.methodologies,+ ],+ count: getKeywordCountFromSemantic(semanticKeywords),+ },+ verbs: {+ verbs: semanticVerbs.strong_verbs.map((v) => v.verb),+ count: getVerbCountFromSemantic(semanticVerbs),+ },+ formatting,+ };++ console.log("[Resume Review] Using semantic extraction (Phase 3)");+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ const isTimeout = errorMessage.includes("timed out");++ console.error("[Resume Review] Semantic extraction failed:", error);++ // Send user-friendly error message+ if (progressStream) {+ const warningMsg = isTimeout+ ? "AI model is taking too long. Please try again or use a different model."+ : "AI unavailable for resume analysis. Please try again later.";+ progressStream.sendWarning("tool-extraction", warningMsg, 0);+ }++ throw new AIUnavailableError("resume analysis");+ }++ progressStream?.sendCompleted("tool-extraction", 0);++ // =========================================================================+ // STEP 2: Calculate Baseline Score+ // =========================================================================+ const baselineScore = calculateResumeScore({+ quantifiedCount: toolData.quantified.count,+ keywordCount: toolData.keywords.count,+ verbCount: toolData.verbs.count,+ hasBulletPoints: toolData.formatting.hasBulletPoints,+ sectionCount: toolData.formatting.sectionCount,+ });++ const allowedVariance = calculateAllowedVariance(+ baselineScore.score,+ "resume"+ );+ const minScore = Math.max(0, baselineScore.score - allowedVariance);+ const maxScore = Math.min(100, baselineScore.score + allowedVariance);++ console.log(+ `[Resume Review] Baseline: ${baselineScore.score}, Allowed variance: ±${allowedVariance} (${minScore}-${maxScore})`+ );++ // =========================================================================+ // STEP 3: PARALLEL - Analysis Agent & Feedback Agent+ // These agents can run simultaneously as they're independent+ // =========================================================================+ progressStream?.sendStarted("analysis-agent", 1);+ progressStream?.sendStarted("feedback-agent", 2);++ const isOllama = isOllamaProvider(provider);++ // Build prompts - simpler for Ollama+ const analysisPrompt = isOllama+ ? buildOllamaResumeAnalysisPrompt(+ resumeText,+ toolData,+ baselineScore,+ minScore,+ maxScore+ )+ : `Analyze this resume comprehensively:++RESUME:+${resumeText}++OBJECTIVE METRICS (from tools):+- Quantified achievements: ${toolData.quantified.count} found+ Examples: ${toolData.quantified.examples.slice(0, 3).join(", ")}+- Keywords: ${toolData.keywords.count} found+ List: ${toolData.keywords.keywords.slice(0, 20).join(", ")}+- Action verbs: ${toolData.verbs.count} found+ List: ${toolData.verbs.verbs.slice(0, 15).join(", ")}+- Formatting: ${+ toolData.formatting.hasBulletPoints ? "Has bullets" : "No bullets"+ }, ${toolData.formatting.sectionCount} sections++CALCULATED BASELINE SCORE: ${baselineScore.score}/100++BASELINE BREAKDOWN (mathematically calculated):+- Keywords: ${baselineScore.breakdown.keywords}/20 (FIXED based on count)+- Achievements: ${+ baselineScore.breakdown.achievements+ }/25 (FIXED based on count)+- Action Verbs: ${baselineScore.breakdown.verbs}/10 (FIXED based on count)+- Formatting: ${baselineScore.breakdown.formatting}/15 (FIXED based on analysis)+- Summary: ${baselineScore.breakdown.summary}/10 (adjustable based on quality)+- Experience: ${+ baselineScore.breakdown.experienceClarity+ }/10 (adjustable based on clarity)+- Skills: ${+ baselineScore.breakdown.skillsSection+ }/5 (adjustable based on organization)+- Grammar: ${baselineScore.breakdown.grammar}/5 (adjustable based on errors)++YOUR TASKS:+1. Verify/comment on the objective data analysis+2. Assess keyword strength and ATS optimization (0-100 score)+3. Identify missing critical keywords for resume improvement+4. Calculate final score by adjusting ONLY the subjective criteria (last 4)+5. Your final score MUST be between ${minScore} and ${maxScore}++IMPORTANT: The first 4 criteria are FIXED (objective counts). You can only adjust the last 4 based on resume quality.`;++ const feedbackPrompt = isOllama+ ? buildOllamaResumeFeedbackPrompt(resumeText, baselineScore)+ : `Generate actionable feedback for this resume:++RESUME:+${resumeText}++CONTEXT:+- Baseline score: ${baselineScore.score}/100 (calculated from objective metrics)+- Expected final score range: ${minScore}-${maxScore}++YOUR TASKS:+1. Identify 2-5 specific strengths with evidence from the resume+2. Identify 2-5 weaknesses that matter for job search success+3. Provide 2-5 actionable suggestions with exact implementation steps+4. Add synthesis notes on consistency between likely score and feedback++Be specific, actionable, and encouraging. Reference actual resume content.`;++ let analysisResult: AnalysisResult;+ let feedbackResult: FeedbackResult;++ // Select schema based on provider+ const analysisSchema = isOllama+ ? OllamaAnalysisAgentSchema+ : AnalysisAgentSchema;+ const feedbackSchema = isOllama+ ? OllamaFeedbackAgentSchema+ : FeedbackAgentSchema;++ // System prompts - simplified for Ollama+ const analysisSystemPrompt = isOllama+ ? OLLAMA_ANALYSIS_SYSTEM_PROMPT+ : ANALYSIS_AGENT_PROMPT;+ const feedbackSystemPrompt = isOllama+ ? OLLAMA_FEEDBACK_SYSTEM_PROMPT+ : FEEDBACK_AGENT_PROMPT;++ try {+ const [rawAnalysis, rawFeedback] = await Promise.all([+ // Analysis Agent with timeout+ withTimeout(+ runWithRetry(async () => {+ const { object } = await generateObject({+ model,+ schema: analysisSchema,+ system: analysisSystemPrompt,+ prompt: analysisPrompt,+ temperature: 0.1,+ });+ return object;+ }, "Analysis Agent"),+ AGENT_TIMEOUT_MS,+ "Analysis Agent"+ ),++ // Feedback Agent with timeout+ withTimeout(+ runWithRetry(async () => {+ const { object } = await generateObject({+ model,+ schema: feedbackSchema,+ system: feedbackSystemPrompt,+ prompt: feedbackPrompt,+ temperature: 0.3,+ });+ return object;+ }, "Feedback Agent"),+ AGENT_TIMEOUT_MS,+ "Feedback Agent"+ ),+ ]);++ // Normalize Ollama results to full format+ if (isOllama) {+ analysisResult = normalizeAnalysisResult(+ rawAnalysis as OllamaAnalysisAgent,+ toolData.verbs.count+ );+ feedbackResult = normalizeFeedbackResult(+ rawFeedback as OllamaFeedbackAgent+ );+ } else {+ analysisResult = rawAnalysis as AnalysisResult;+ feedbackResult = rawFeedback as FeedbackResult;+ }+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);+ const isTimeout = errorMessage.includes("timed out");++ console.error("[Resume Review] Agent execution failed:", error);++ // Send user-friendly error message+ if (progressStream) {+ const warningMsg = isTimeout+ ? "Analysis is taking too long. Please try again or use a faster model."+ : "Analysis failed. Please try again.";+ progressStream.sendWarning("analysis-agent", warningMsg, 1);+ }++ // Throw to let caller handle the error+ throw new Error(+ isTimeout+ ? "Resume review timed out. The AI model may be overloaded. Please try again."+ : `Resume review failed: ${errorMessage}`+ );+ }++ progressStream?.sendCompleted("analysis-agent", 1);+ progressStream?.sendCompleted("feedback-agent", 2);++ // =========================================================================+ // STEP 4: Validation+ // =========================================================================+ const validatedScore = validateScore(+ analysisResult.finalScore,+ baselineScore.score,+ allowedVariance+ );++ const warnings: string[] = [];+ if (validatedScore !== analysisResult.finalScore) {+ warnings.push(+ `Score adjusted from ${analysisResult.finalScore} to ${validatedScore} (outside allowed variance)`+ );+ }++ // =========================================================================+ // STEP 5: Build Final Response+ // =========================================================================+ const finalResponse: ResumeReviewResponse = {+ score: validatedScore,+ summary: `This resume scores ${validatedScore}/100, which is ${+ validatedScore >= 70+ ? "above average"+ : validatedScore >= 50+ ? "average"+ : "below average"+ }. ${feedbackResult.strengths[0] || "Multiple strengths identified."}`,+ strengths: feedbackResult.strengths,+ weaknesses: feedbackResult.weaknesses,+ suggestions: feedbackResult.suggestions,+ };++ const agentInsights: AgentInsights = {+ analysis: analysisResult,+ feedback: feedbackResult,+ };++ return {+ analysis: finalResponse,+ agentInsights,+ baselineScore,+ warnings: warnings.length > 0 ? warnings : undefined,+ };+}diff --git a/src/lib/ai/multi-agent/utils.ts b/src/lib/ai/multi-agent/utils.tsnew file mode 100644index 0000000..2613237--- /dev/null+++ b/src/lib/ai/multi-agent/utils.ts@@ -0,0 +1,66 @@+/**+ * Multi-Agent Shared Utilities+ *+ * Common utilities used by both resume review and job match agents.+ */++// ============================================================================+// RETRY MECHANISM+// ============================================================================++export async function runWithRetry<T>(+ operation: () => Promise<T>,+ operationName: string,+ maxRetries: number = 1+): Promise<T> {+ let lastError: Error = new Error("Unknown error");++ for (let attempt = 0; attempt <= maxRetries; attempt++) {+ try {+ return await operation();+ } catch (error) {+ lastError = error instanceof Error ? error : new Error(String(error));+ console.warn(+ `${operationName} attempt ${attempt + 1} failed:`,+ lastError.message+ );++ if (attempt < maxRetries) {+ const delay = 1000 * Math.pow(2, attempt);+ await new Promise((resolve) => setTimeout(resolve, delay));+ }+ }+ }++ throw new Error(+ `${operationName} failed after ${maxRetries + 1} attempts: ${+ lastError.message+ }`+ );+}++// ============================================================================+// TIMEOUT WRAPPER (Phase 4: Prevent small model hangs)+// ============================================================================++export async function withTimeout<T>(+ promise: Promise<T>,+ timeoutMs: number,+ operationName: string+): Promise<T> {+ let timeoutId: NodeJS.Timeout;+ const timeoutPromise = new Promise<never>((_, reject) => {+ timeoutId = setTimeout(() => {+ reject(new Error(`${operationName} timed out after ${timeoutMs}ms`));+ }, timeoutMs);+ });++ try {+ const result = await Promise.race([promise, timeoutPromise]);+ clearTimeout(timeoutId!);+ return result;+ } catch (error) {+ clearTimeout(timeoutId!);+ throw error;+ }+}diff --git a/src/lib/ai/ollama/index.ts b/src/lib/ai/ollama/index.tsnew file mode 100644index 0000000..3f7e4b3--- /dev/null+++ b/src/lib/ai/ollama/index.ts@@ -0,0 +1,53 @@+/**+ * Ollama-specific AI logic+ *+ * This module centralizes all Ollama-specific functionality:+ * - Simplified prompts for local models+ * - Result normalizers (Ollama → full schema)+ * - Utility functions and constants+ */++// Utils+export {+ isOllamaProvider,+ SEMANTIC_TIMEOUT_MS,+ AGENT_TIMEOUT_MS,+} from "./utils";++// Normalizers+export {+ normalizeKeywordExtraction,+ normalizeActionVerbAnalysis,+ normalizeSkillMatch,+ normalizeSemanticSimilarity,+ normalizeAnalysisResult,+ normalizeFeedbackResult,+} from "./normalizers";++// Prompts+export {+ OLLAMA_ANALYSIS_SYSTEM_PROMPT,+ OLLAMA_FEEDBACK_SYSTEM_PROMPT,+ OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT,+ OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT,+ buildOllamaResumeAnalysisPrompt,+ buildOllamaResumeFeedbackPrompt,+ buildOllamaJobMatchAnalysisPrompt,+ buildOllamaJobMatchFeedbackPrompt,+} from "./prompts";++// Re-export schemas from models for convenience+export {+ OllamaSemanticKeywordSchema,+ OllamaActionVerbSchema,+ OllamaSkillMatchSchema,+ OllamaSemanticSimilaritySchema,+ OllamaAnalysisAgentSchema,+ OllamaFeedbackAgentSchema,+ type OllamaSemanticKeywordExtraction,+ type OllamaActionVerbAnalysis,+ type OllamaSkillMatch,+ type OllamaSemanticSimilarity,+ type OllamaAnalysisAgent,+ type OllamaFeedbackAgent,+} from "@/models/ai.ollama-schemas";diff --git a/src/lib/ai/ollama/normalizers.ts b/src/lib/ai/ollama/normalizers.tsnew file mode 100644index 0000000..4481b01--- /dev/null+++ b/src/lib/ai/ollama/normalizers.ts@@ -0,0 +1,147 @@+/**+ * Ollama result normalizers+ *+ * These functions convert Ollama's simplified schema output+ * to the full schema format expected by the rest of the application.+ */++import type {+ OllamaSemanticKeywordExtraction,+ OllamaActionVerbAnalysis,+ OllamaSkillMatch,+ OllamaSemanticSimilarity,+ OllamaAnalysisAgent,+ OllamaFeedbackAgent,+} from "@/models/ai.ollama-schemas";+import type {+ SemanticKeywordExtraction,+ ActionVerbAnalysis,+ SemanticSkillMatch,+ SemanticSimilarityResult,+} from "@/models/ai.schemas";+import type { AnalysisResult, FeedbackResult } from "@/models/ai.model";++/**+ * Normalize Ollama keyword extraction to full schema format+ */+export function normalizeKeywordExtraction(+ ollamaResult: OllamaSemanticKeywordExtraction+): SemanticKeywordExtraction {+ return {+ technical_skills: ollamaResult.technical_skills,+ tools_platforms: ollamaResult.tools || [],+ methodologies: [],+ domain_knowledge: [],+ soft_skills: [],+ total_count: ollamaResult.total_count,+ };+}++/**+ * Normalize Ollama action verb analysis to full schema format+ */+export function normalizeActionVerbAnalysis(+ ollamaResult: OllamaActionVerbAnalysis+): ActionVerbAnalysis {+ return {+ strong_verbs: ollamaResult.strong_verbs.map((verb) => ({+ verb,+ context: "Found in resume",+ impact_level: "medium" as const,+ })),+ weak_verbs: ollamaResult.weak_verbs.map((verb) => ({+ verb,+ context: "Found in resume",+ suggestion: "",+ })),+ verb_strength_score: ollamaResult.verb_strength_score,+ };+}++/**+ * Normalize Ollama skill match to full schema format+ */+export function normalizeSkillMatch(+ ollamaResult: OllamaSkillMatch+): SemanticSkillMatch {+ return {+ exact_matches: ollamaResult.matched_skills+ .filter((m) => m.skill.trim())+ .map((m) => ({+ skill: m.skill,+ resume_evidence: m.evidence,+ job_requirement: "Required by job",+ })),+ related_matches: [],+ missing_skills: ollamaResult.missing_skills+ .filter((s) => s.trim())+ .map((skill) => ({+ skill,+ importance: "important" as const,+ learnability: "moderate" as const,+ })),+ overall_match_percentage: ollamaResult.match_percentage,+ };+}++/**+ * Normalize Ollama semantic similarity to full schema format+ */+export function normalizeSemanticSimilarity(+ ollamaResult: OllamaSemanticSimilarity+): SemanticSimilarityResult {+ return {+ similarity_score: ollamaResult.similarity_score,+ match_explanation: ollamaResult.match_explanation,+ key_matches: [],+ key_gaps: ollamaResult.key_gaps.map((gap) => ({+ skill: gap,+ note: "Missing from resume",+ })),+ transferable_skills: [],+ application_recommendation:+ ollamaResult.similarity_score >= 60+ ? "Consider applying - good fit"+ : "Consider upskilling before applying",+ };+}++/**+ * Normalize Ollama analysis agent result to full format+ */+export function normalizeAnalysisResult(+ ollamaResult: OllamaAnalysisAgent,+ verbCount: number = 0+): AnalysisResult {+ return {+ finalScore: ollamaResult.finalScore,+ dataInsights: {+ quantifiedCount: ollamaResult.quantifiedCount,+ keywordCount: ollamaResult.keywordCount,+ verbCount,+ formatQuality: "Analyzed by Ollama",+ },+ keywordAnalysis: {+ strength: "Analyzed",+ atsScore: ollamaResult.atsScore,+ missingCritical: ollamaResult.missingKeywords,+ recommendations: [],+ },+ adjustments: [],+ math: ollamaResult.scoreExplanation,+ };+}++/**+ * Normalize Ollama feedback agent result to full format+ */+export function normalizeFeedbackResult(+ ollamaResult: OllamaFeedbackAgent+): FeedbackResult {+ return {+ strengths: ollamaResult.strengths,+ weaknesses: ollamaResult.weaknesses,+ suggestions: ollamaResult.suggestions,+ synthesisNotes: ollamaResult.summary,+ };+}diff --git a/src/lib/ai/ollama/prompts.ts b/src/lib/ai/ollama/prompts.tsnew file mode 100644index 0000000..bb4b237--- /dev/null+++ b/src/lib/ai/ollama/prompts.ts@@ -0,0 +1,100 @@+/**+ * Ollama-specific prompts+ *+ * Simplified prompts optimized for small local models like llama3.2.+ * These prompts are more concise and direct compared to cloud model prompts.+ */++import type { ToolDataResume, ToolDataJobMatch } from "@/models/ai.model";+import type { BaselineScore } from "../scoring";++// System prompts for Ollama agents+export const OLLAMA_ANALYSIS_SYSTEM_PROMPT =+ "You are a resume analyzer. Analyze the resume and provide a score with explanation.";++export const OLLAMA_FEEDBACK_SYSTEM_PROMPT =+ "You are a resume feedback expert. Provide strengths, weaknesses, and suggestions.";++export const OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT =+ "You are a job match analyzer. Score how well the resume matches the job.";++export const OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT =+ "You are a job match expert. Provide strengths, gaps, and suggestions.";++/**+ * Build resume review analysis prompt for Ollama+ */+export function buildOllamaResumeAnalysisPrompt(+ resumeText: string,+ toolData: ToolDataResume,+ baselineScore: BaselineScore,+ minScore: number,+ maxScore: number+): string {+ return `Score this resume. Baseline: ${baselineScore.score}, range: ${minScore}-${maxScore}.++Resume:+${resumeText}++Metrics: ${toolData.quantified.count} achievements, ${toolData.keywords.count} keywords, ${toolData.verbs.count} action verbs.+Keywords found: ${toolData.keywords.keywords.slice(0, 15).join(", ")}`;+}++/**+ * Build resume review feedback prompt for Ollama+ */+export function buildOllamaResumeFeedbackPrompt(+ resumeText: string,+ baselineScore: BaselineScore+): string {+ return `Give feedback on this resume. Score: ${baselineScore.score}.++Resume:+${resumeText}++Provide strengths, weaknesses, and suggestions.`;+}++/**+ * Build job match analysis prompt for Ollama+ */+export function buildOllamaJobMatchAnalysisPrompt(+ resumeText: string,+ jobDescription: string,+ toolData: ToolDataJobMatch,+ baselineScore: BaselineScore,+ minScore: number,+ maxScore: number+): string {+ return `Score this resume-job match. Baseline: ${baselineScore.score}, range: ${minScore}-${maxScore}.++Resume:+${resumeText}++Job:+${jobDescription}++Matched skills: ${toolData.keywordOverlap.matchedKeywords.slice(0, 8).join(", ")}+Missing skills: ${toolData.keywordOverlap.missingKeywords.slice(0, 8).join(", ")}`;+}++/**+ * Build job match feedback prompt for Ollama+ */+export function buildOllamaJobMatchFeedbackPrompt(+ resumeText: string,+ jobDescription: string,+ toolData: ToolDataJobMatch,+ baselineScore: BaselineScore+): string {+ return `Give feedback on this resume-job match. Score: ${baselineScore.score}.++Resume:+${resumeText}++Job:+${jobDescription}++Matched: ${toolData.keywordOverlap.matchedKeywords.slice(0, 5).join(", ")}+Missing: ${toolData.keywordOverlap.missingKeywords.slice(0, 5).join(", ")}`;+}diff --git a/src/lib/ai/ollama/utils.ts b/src/lib/ai/ollama/utils.tsnew file mode 100644index 0000000..f659a6b--- /dev/null+++ b/src/lib/ai/ollama/utils.ts@@ -0,0 +1,16 @@+/**+ * Ollama-specific utilities+ */++import type { ProviderType } from "../providers";++// Timeouts for Ollama (local models need more time)+export const SEMANTIC_TIMEOUT_MS = 60000; // 60 seconds for semantic extraction+export const AGENT_TIMEOUT_MS = 120000; // 120 seconds for agent calls++/**+ * Check if provider is Ollama (local models that need simplified prompts/schemas)+ */+export function isOllamaProvider(provider: ProviderType): boolean {+ return provider === "ollama";+}diff --git a/src/lib/ai/scoring.ts b/src/lib/ai/scoring.tsindex ac751c9..de4ca2d 100644--- a/src/lib/ai/scoring.ts+++ b/src/lib/ai/scoring.ts@@ -3,6 +3,14 @@* Ensures accurate, consistent scoring across all analyses*/+/**+ * Baseline score result type+ */+export type BaselineScore = {+ score: number;+ breakdown: Record<string, number>;+};+/*** Resume Review Scoring Calculator* Returns exact scores based on objective metricsdiff --git a/src/lib/ai/tools.ts b/src/lib/ai/tools.tsindex dc0e2d6..76ca9b6 100644--- a/src/lib/ai/tools.ts+++ b/src/lib/ai/tools.ts@@ -1,572 +1,24 @@/**- * AI Analysis Tools - Provide accurate counting and extraction functions- * These tools give agents the ability to perform precise analysis programmatically- */--/**- * Extract and count quantified achievements (numbers, percentages, metrics)- */-export function countQuantifiedAchievements(text: string): {- count: number;- examples: string[];-} {- // Match patterns like: "40%", "$2M", "5+ years", "Increased by 50%"- const patterns = [- /\d+%/g, // Percentages: 40%- /\$[\d,]+[KMB]?/g, // Money: $2M, $500K- /\d+\+?\s*(years?|months?|weeks?)/gi, // Time: 5+ years- /(increased|decreased|improved|reduced|grew|boosted)\s+by\s+\d+/gi, // Actions with numbers- /\d+x\s+(faster|better|more)/gi, // Multipliers: 2x faster- /team\s+of\s+\d+/gi, // Team size: team of 12- /\d+\s+(clients?|customers?|users?|projects?)/gi, // Quantities- ];-- const matches = new Set<string>();- patterns.forEach((pattern) => {- const found = text.match(pattern);- if (found) {- found.forEach((m) => matches.add(m));- }- });-- const examples = Array.from(matches).slice(0, 5); // Top 5 examples- return { count: matches.size, examples };-}--// ============================================================================-// AI UNAVAILABLE ERROR - Used when semantic extraction fails-// ============================================================================--export class AIUnavailableError extends Error {- constructor(operation: string) {- super(`AI unavailable for ${operation}. Please try again later.`);- this.name = "AIUnavailableError";- }-}--// ============================================================================-// TEXT ANALYSIS UTILITIES (no hardcoded keyword lists)-// ============================================================================--/**- * Analyze text structure and formatting quality- */-export function analyzeFormatting(text: string): {- hasBulletPoints: boolean;- hasConsistentSpacing: boolean;- averageLineLength: number;- sectionCount: number;-} {- const lines = text.split("\n");- const bulletLines = lines.filter(- (line) =>- line.trim().startsWith("•") ||- line.trim().startsWith("-") ||- line.trim().startsWith("*")- );-- const hasBulletPoints = bulletLines.length > 3;-- // Count potential sections (all caps lines or lines ending with :)- const sectionHeaders = lines.filter(- (line) =>- (line.trim().length > 0 && line === line.toUpperCase()) ||- line.trim().endsWith(":")- );-- const nonEmptyLines = lines.filter((line) => line.trim().length > 0);- const averageLineLength =- nonEmptyLines.reduce((sum, line) => sum + line.length, 0) /- Math.max(nonEmptyLines.length, 1);-- return {- hasBulletPoints,- hasConsistentSpacing: averageLineLength > 20 && averageLineLength < 100,- averageLineLength: Math.round(averageLineLength),- sectionCount: sectionHeaders.length,- };-}--// ============================================================================-// SEMANTIC EXTRACTION FUNCTIONS (Phase 1 Improvements + Phase 4 Optimization)-// Uses LLM for dynamic, context-aware extraction instead of hard-coded lists-// Phase 4: Provider-aware prompts for Ollama vs Cloud optimization-// ============================================================================--import { generateObject } from "ai";-import { getModel, ProviderType } from "./providers";-import {- SemanticKeywordSchema,- ActionVerbAnalysisSchema,- SemanticSkillMatchSchema,- type SemanticKeywordExtraction,- type ActionVerbAnalysis,- type SemanticSkillMatch,-} from "@/models/ai.schemas";-import {- getKeywordPrompt,- getVerbPrompt,- getSkillMatchPrompt,- getSimilarityPrompt,-} from "./prompts/semantic-prompts";-import {- OllamaSemanticKeywordSchema,- OllamaActionVerbSchema,- OllamaSkillMatchSchema,- OllamaSemanticSimilaritySchema,-} from "@/models/ai.ollama-schemas";--/**- * Check if provider is Ollama (local models that need simplified prompts)- */-function isOllamaProvider(provider: ProviderType): boolean {- return provider === "ollama";-}--/**- * Extract keywords using LLM for dynamic, semantic understanding- * Replaces hard-coded keyword lists with intelligent extraction- *- * Benefits:- * - Automatically adapts to new technologies- * - Understands context (e.g., "python" in programming vs biology)- * - Recognizes synonyms and variations (k8s = kubernetes)- * - No maintenance required for keyword lists- *- * @param text - Resume or job description text- * @param provider - AI provider (ollama/openai)- * @param modelName - Model to use for extraction- * @param contextHint - Optional hint about domain (e.g., "software engineering", "healthcare")- */-export async function extractSemanticKeywords(- text: string,- provider: ProviderType = "ollama",- modelName: string = "llama3.2",- contextHint?: string-): Promise<SemanticKeywordExtraction> {- const model = getModel(provider, modelName);- // Phase 4: Provider-aware schema and prompt selection- const schema = isOllamaProvider(provider)- ? OllamaSemanticKeywordSchema- : SemanticKeywordSchema;- const prompt = getKeywordPrompt(provider, text, contextHint);-- try {- const { object } = await generateObject({- model,- schema,- prompt,- temperature: 0.1,- });-- // Normalize Ollama result to full schema format- if (isOllamaProvider(provider)) {- return {- technical_skills: object.technical_skills,- tools_platforms: (object as { tools: string[] }).tools || [],- methodologies: [],- domain_knowledge: [],- soft_skills: [],- total_count: object.total_count,- };- }-- return object as SemanticKeywordExtraction;- } catch (error) {- console.error("Semantic keyword extraction failed:", error);- throw new AIUnavailableError("keyword extraction");- }-}--/**- * Analyze action verbs using LLM for semantic strength assessment- * Replaces hard-coded verb lists with intelligent analysis- *- * Benefits:- * - Understands verb strength in context- * - Identifies passive constructions- * - Provides specific improvement suggestions- * - Recognizes weak phrases like "responsible for"- *- * @param text - Resume text to analyze- * @param provider - AI provider (ollama/openai)- * @param modelName - Model to use for analysis- */-export async function analyzeActionVerbs(- text: string,- provider: ProviderType = "ollama",- modelName: string = "llama3.2"-): Promise<ActionVerbAnalysis> {- const model = getModel(provider, modelName);- // Phase 4: Provider-aware schema and prompt selection- const schema = isOllamaProvider(provider)- ? OllamaActionVerbSchema- : ActionVerbAnalysisSchema;- const prompt = getVerbPrompt(provider, text);-- try {- const { object } = await generateObject({- model,- schema,- prompt,- temperature: 0.2,- });-- // Normalize Ollama result to full schema format- if (isOllamaProvider(provider)) {- const ollamaResult = object as {- strong_verbs: string[];- weak_verbs: string[];- verb_strength_score: number;- };- return {- strong_verbs: ollamaResult.strong_verbs.map((verb) => ({- verb,- context: "Found in resume",- impact_level: "medium" as const,- })),- weak_verbs: ollamaResult.weak_verbs.map((verb) => ({- verb,- context: "Found in resume",- suggestion: "",- })),- verb_strength_score: ollamaResult.verb_strength_score,- };- }-- return object as ActionVerbAnalysis;- } catch (error) {- console.error("Action verb analysis failed:", error);- throw new AIUnavailableError("action verb analysis");- }-}--/**- * Perform semantic skill matching between resume and job- * Uses LLM to understand skill relationships and transferability- *- * Benefits:- * - Recognizes related skills (PostgreSQL vs MySQL)- * - Assesses skill transferability- * - Provides learnability estimates- * - Gives strategic application advice- *- * @param resumeText - Candidate's resume text- * @param jobText - Job description text- * @param provider - AI provider (ollama/openai)- * @param modelName - Model to use for matching- */-export async function performSemanticSkillMatch(- resumeText: string,- jobText: string,- provider: ProviderType = "ollama",- modelName: string = "llama3.2"-): Promise<SemanticSkillMatch> {- const model = getModel(provider, modelName);- // Phase 4: Provider-aware schema and prompt selection- const schema = isOllamaProvider(provider)- ? OllamaSkillMatchSchema- : SemanticSkillMatchSchema;- const prompt = getSkillMatchPrompt(provider, resumeText, jobText);-- try {- const { object } = await generateObject({- model,- schema,- prompt,- temperature: 0.2,- });-- // Normalize Ollama result to full schema format- if (isOllamaProvider(provider)) {- const ollamaResult = object as {- matched_skills: Array<{ skill: string; evidence: string }>;- missing_skills: string[];- match_percentage: number;- };- return {- exact_matches: ollamaResult.matched_skills- .filter((m) => m.skill.trim())- .map((m) => ({- skill: m.skill,- resume_evidence: m.evidence,- job_requirement: "Required by job",- })),- related_matches: [],- missing_skills: ollamaResult.missing_skills- .filter((s) => s.trim())- .map((skill) => ({- skill,- importance: "important" as const,- learnability: "moderate" as const,- })),- overall_match_percentage: ollamaResult.match_percentage,- };- }-- // Post-process cloud result to remove empty strings and duplicates- const cloudResult = object as SemanticSkillMatch;- const cleanedResult = {- exact_matches: cloudResult.exact_matches.filter(- (match) =>- match.skill.trim() &&- match.resume_evidence.trim() &&- match.job_requirement.trim()- ),- related_matches: cloudResult.related_matches.filter(- (match) =>- match.job_skill.trim() &&- match.resume_skill.trim() &&- match.explanation.trim()- ),- missing_skills: cloudResult.missing_skills.filter((skill) =>- skill.skill.trim()- ),- overall_match_percentage: cloudResult.overall_match_percentage,- };-- // Remove duplicate skills from missing_skills if they're in exact_matches- const exactSkills = new Set(- cleanedResult.exact_matches.map((m) => m.skill.toLowerCase())- );- cleanedResult.missing_skills = cleanedResult.missing_skills.filter(- (m) => !exactSkills.has(m.skill.toLowerCase())- );-- return cleanedResult;- } catch (error) {- console.error("Semantic skill matching failed:", error);- throw new AIUnavailableError("skill matching");- }-}--/**- * Get keyword count from semantic extraction (for backward compatibility)- */-export function getKeywordCountFromSemantic(- extraction: SemanticKeywordExtraction-): number {- return extraction.total_count;-}--/**- * Get verb count from semantic analysis (for backward compatibility)- */-export function getVerbCountFromSemantic(analysis: ActionVerbAnalysis): number {- return analysis.strong_verbs.length;-}--// ============================================================================-// PHASE 3: SEMANTIC SIMILARITY WITH EXPLANATIONS-// Complete semantic understanding of resume-job fit, replacing keyword overlap-// ============================================================================--import {- SemanticSimilaritySchema,- type SemanticSimilarityResult,-} from "@/models/ai.schemas";--/**- * Calculate semantic similarity between resume and job description- * This is the core Phase 3 function that replaces keyword overlap entirely- *- * Uses LLM to:- * 1. Calculate overall semantic similarity (0-100)- * 2. Generate human-readable explanation of fit- * 3. Identify key matching areas and gaps- * 4. Provide strategic application advice- *- * @param resumeText - Candidate's resume text- * @param jobDescription - Job description text- * @param provider - AI provider (ollama/openai/deepseek)- * @param modelName - Model to use- * @returns SemanticSimilarityResult with score, explanations, and recommendations- */-export async function calculateSemanticSimilarity(- resumeText: string,- jobDescription: string,- provider: ProviderType = "ollama",- modelName: string = "llama3.2"-): Promise<SemanticSimilarityResult> {- const model = getModel(provider, modelName);- // Phase 4: Provider-aware schema and prompt selection- const schema = isOllamaProvider(provider)- ? OllamaSemanticSimilaritySchema- : SemanticSimilaritySchema;- const prompt = getSimilarityPrompt(provider, resumeText, jobDescription);-- try {- const { object } = await generateObject({- model,- schema,- prompt,- temperature: 0.2,- });-- // Normalize Ollama result to full schema format- if (isOllamaProvider(provider)) {- const ollamaResult = object as {- similarity_score: number;- match_explanation: string;- key_gaps: string[];- };- return {- similarity_score: ollamaResult.similarity_score,- match_explanation: ollamaResult.match_explanation,- key_matches: [],- key_gaps: ollamaResult.key_gaps.map((gap) => ({- skill: gap,- note: "Missing from resume",- })),- transferable_skills: [],- application_recommendation:- ollamaResult.similarity_score >= 60- ? "Consider applying - good fit"- : "Consider upskilling before applying",- };- }-- return object as SemanticSimilarityResult;- } catch (error) {- console.error("Semantic similarity calculation failed:", error);- throw new AIUnavailableError("similarity calculation");- }-}--/**- * Generate a comprehensive match explanation combining semantic skill matching- * and overall similarity assessment- *- * This function synthesizes data from performSemanticSkillMatch and calculateSemanticSimilarity- * to create detailed, actionable explanations for the user- *- * @param skillMatch - Result from performSemanticSkillMatch- * @param similarity - Result from calculateSemanticSimilarity- * @returns Structured explanation with fit summary and detailed insights- */-export function generateMatchExplanation(- skillMatch: SemanticSkillMatch,- similarity: SemanticSimilarityResult-): {- summary: string;- fit_assessment: string;- strengths_explanation: string[];- gaps_explanation: string[];- transferable_explanation: string[];- action_items: string[];-} {- // Generate strengths explanation from exact and related matches- const strengthsExplanation: string[] = [];-- skillMatch.exact_matches.slice(0, 3).forEach((match) => {- strengthsExplanation.push(- `✅ **${- match.skill- }**: Directly matches requirement - "${match.resume_evidence.substring(- 0,- 60- )}..."`- );- });-- skillMatch.related_matches.slice(0, 2).forEach((match) => {- strengthsExplanation.push(- `⚡ **${match.resume_skill}** transfers to **${match.job_skill}** (${match.similarity}% similar): ${match.explanation}`- );- });-- // Generate gaps explanation with learnability context- const gapsExplanation: string[] = [];-- skillMatch.missing_skills.slice(0, 4).forEach((skill) => {- const urgencyIcon =- skill.importance === "critical"- ? "🔴"- : skill.importance === "important"- ? "🟡"- : "🟢";- const learnTime =- skill.learnability === "quick"- ? "<1 month"- : skill.learnability === "moderate"- ? "1-3 months"- : "3+ months";- gapsExplanation.push(- `${urgencyIcon} **${skill.skill}** (${skill.importance}): Learning time ~${learnTime}`- );- });-- // Generate transferable skills explanation- const transferableExplanation: string[] = similarity.transferable_skills.map(- (skill) =>- `💡 ${skill.resume_skill} → ${skill.job_skill}: ${skill.how_it_transfers}`- );-- // Generate prioritized action items- const actionItems: string[] = [];-- // Critical missing skills first- const criticalMissing = skillMatch.missing_skills.filter(- (s) => s.importance === "critical"- );- if (criticalMissing.length > 0) {- actionItems.push(- `🔴 Address critical gaps first: ${criticalMissing- .map((s) => s.skill)- .join(", ")}`- );- }-- // Quick wins- const quickLearns = skillMatch.missing_skills.filter(- (s) => s.learnability === "quick" && s.importance !== "nice-to-have"- );- if (quickLearns.length > 0) {- actionItems.push(- `⚡ Quick wins (learn in <1 month): ${quickLearns- .map((s) => s.skill)- .join(", ")}`- );- }-- // Highlight existing transferable skills in application- if (skillMatch.related_matches.length > 0) {- actionItems.push(- `📝 Highlight transferable skills in cover letter: ${skillMatch.related_matches- .slice(0, 3)- .map((m) => m.resume_skill)- .join(", ")}`- );- }-- // Fit assessment based on scores- let fitAssessment: string;- const score = similarity.similarity_score;- if (score >= 75) {- fitAssessment = "Excellent fit - You're a strong candidate for this role.";- } else if (score >= 60) {- fitAssessment = "Good fit - You match most requirements with minor gaps.";- } else if (score >= 45) {- fitAssessment =- "Moderate fit - Some gaps exist but may be worth applying with a tailored resume.";- } else if (score >= 30) {- fitAssessment =- "Weak fit - Significant gaps; consider upskilling before applying.";- } else {- fitAssessment =- "Poor fit - This role may not align with your current skills and experience.";- }-- return {- summary: similarity.match_explanation,- fit_assessment: fitAssessment,- strengths_explanation: strengthsExplanation,- gaps_explanation: gapsExplanation,- transferable_explanation: transferableExplanation,- action_items:- actionItems.length > 0- ? actionItems- : ["No critical actions needed - proceed with application"],- };-}-+ * AI Analysis Tools+ * Re-exports from modular tools directory for backward compatibility+ *+ * @see ./tools/index.ts for the modular implementation+ */++export {+ // Error classes+ AIUnavailableError,+ // Achievement analysis+ countQuantifiedAchievements,+ // Formatting analysis+ analyzeFormatting,+ // Semantic extraction (LLM-powered)+ extractSemanticKeywords,+ analyzeActionVerbs,+ performSemanticSkillMatch,+ getKeywordCountFromSemantic,+ getVerbCountFromSemantic,+ // Semantic similarity (LLM-powered)+ calculateSemanticSimilarity,+ generateMatchExplanation,+} from "./tools/index";diff --git a/src/lib/ai/tools/achievement.ts b/src/lib/ai/tools/achievement.tsnew file mode 100644index 0000000..3b4a690--- /dev/null+++ b/src/lib/ai/tools/achievement.ts@@ -0,0 +1,34 @@+/**+ * Achievement Analysis Tools+ * Extract and analyze quantified achievements from text+ */++/**+ * Extract and count quantified achievements (numbers, percentages, metrics)+ */+export function countQuantifiedAchievements(text: string): {+ count: number;+ examples: string[];+} {+ // Match patterns like: "40%", "$2M", "5+ years", "Increased by 50%"+ const patterns = [+ /\d+%/g, // Percentages: 40%+ /\$[\d,]+[KMB]?/g, // Money: $2M, $500K+ /\d+\+?\s*(years?|months?|weeks?)/gi, // Time: 5+ years+ /(increased|decreased|improved|reduced|grew|boosted)\s+by\s+\d+/gi, // Actions with numbers+ /\d+x\s+(faster|better|more)/gi, // Multipliers: 2x faster+ /team\s+of\s+\d+/gi, // Team size: team of 12+ /\d+\s+(clients?|customers?|users?|projects?)/gi, // Quantities+ ];++ const matches = new Set<string>();+ patterns.forEach((pattern) => {+ const found = text.match(pattern);+ if (found) {+ found.forEach((m) => matches.add(m));+ }+ });++ const examples = Array.from(matches).slice(0, 5); // Top 5 examples+ return { count: matches.size, examples };+}diff --git a/src/lib/ai/tools/errors.ts b/src/lib/ai/tools/errors.tsnew file mode 100644index 0000000..acbea5b--- /dev/null+++ b/src/lib/ai/tools/errors.ts@@ -0,0 +1,13 @@+/**+ * AI Tools Error Classes+ */++/**+ * Error thrown when AI is unavailable for a specific operation+ */+export class AIUnavailableError extends Error {+ constructor(operation: string) {+ super(`AI unavailable for ${operation}. Please try again later.`);+ this.name = "AIUnavailableError";+ }+}diff --git a/src/lib/ai/tools/formatting.ts b/src/lib/ai/tools/formatting.tsnew file mode 100644index 0000000..fcf27be--- /dev/null+++ b/src/lib/ai/tools/formatting.ts@@ -0,0 +1,43 @@+/**+ * Text Formatting Analysis Tools+ * Analyze text structure and formatting quality+ */++/**+ * Analyze text structure and formatting quality+ */+export function analyzeFormatting(text: string): {+ hasBulletPoints: boolean;+ hasConsistentSpacing: boolean;+ averageLineLength: number;+ sectionCount: number;+} {+ const lines = text.split("\n");+ const bulletLines = lines.filter(+ (line) =>+ line.trim().startsWith("•") ||+ line.trim().startsWith("-") ||+ line.trim().startsWith("*")+ );++ const hasBulletPoints = bulletLines.length > 3;++ // Count potential sections (all caps lines or lines ending with :)+ const sectionHeaders = lines.filter(+ (line) =>+ (line.trim().length > 0 && line === line.toUpperCase()) ||+ line.trim().endsWith(":")+ );++ const nonEmptyLines = lines.filter((line) => line.trim().length > 0);+ const averageLineLength =+ nonEmptyLines.reduce((sum, line) => sum + line.length, 0) /+ Math.max(nonEmptyLines.length, 1);++ return {+ hasBulletPoints,+ hasConsistentSpacing: averageLineLength > 20 && averageLineLength < 100,+ averageLineLength: Math.round(averageLineLength),+ sectionCount: sectionHeaders.length,+ };+}diff --git a/src/lib/ai/tools/index.ts b/src/lib/ai/tools/index.tsnew file mode 100644index 0000000..3d3bc3b--- /dev/null+++ b/src/lib/ai/tools/index.ts@@ -0,0 +1,35 @@+/**+ * AI Analysis Tools+ * Provide accurate counting and extraction functions for resume analysis+ *+ * Modules:+ * - errors: Custom error classes for AI operations+ * - achievement: Extract and analyze quantified achievements+ * - formatting: Analyze text structure and formatting+ * - semantic-extraction: LLM-powered keyword and skill extraction+ * - semantic-similarity: LLM-powered similarity analysis+ */++// Error classes+export { AIUnavailableError } from "./errors";++// Achievement analysis+export { countQuantifiedAchievements } from "./achievement";++// Formatting analysis+export { analyzeFormatting } from "./formatting";++// Semantic extraction (LLM-powered)+export {+ extractSemanticKeywords,+ analyzeActionVerbs,+ performSemanticSkillMatch,+ getKeywordCountFromSemantic,+ getVerbCountFromSemantic,+} from "./semantic-extraction";++// Semantic similarity (LLM-powered)+export {+ calculateSemanticSimilarity,+ generateMatchExplanation,+} from "./semantic-similarity";diff --git a/src/lib/ai/tools/semantic-extraction.ts b/src/lib/ai/tools/semantic-extraction.tsnew file mode 100644index 0000000..5ffdea9--- /dev/null+++ b/src/lib/ai/tools/semantic-extraction.ts@@ -0,0 +1,220 @@+/**+ * Semantic Extraction Tools+ * Uses LLM for dynamic, context-aware extraction instead of hard-coded lists+ * Provider-aware prompts for Ollama vs Cloud optimization+ */++import { generateObject } from "ai";+import { getModel, ProviderType } from "../providers";+import {+ SemanticKeywordSchema,+ ActionVerbAnalysisSchema,+ SemanticSkillMatchSchema,+ type SemanticKeywordExtraction,+ type ActionVerbAnalysis,+ type SemanticSkillMatch,+} from "@/models/ai.schemas";+import {+ getKeywordPrompt,+ getVerbPrompt,+ getSkillMatchPrompt,+} from "../prompts/semantic-prompts";+import {+ isOllamaProvider,+ OllamaSemanticKeywordSchema,+ OllamaActionVerbSchema,+ OllamaSkillMatchSchema,+ normalizeKeywordExtraction,+ normalizeActionVerbAnalysis,+ normalizeSkillMatch,+ type OllamaSemanticKeywordExtraction,+ type OllamaActionVerbAnalysis,+ type OllamaSkillMatch,+} from "../ollama";+import { AIUnavailableError } from "./errors";++/**+ * Extract keywords using LLM for dynamic, semantic understanding+ * Replaces hard-coded keyword lists with intelligent extraction+ *+ * Benefits:+ * - Automatically adapts to new technologies+ * - Understands context (e.g., "python" in programming vs biology)+ * - Recognizes synonyms and variations (k8s = kubernetes)+ * - No maintenance required for keyword lists+ *+ * @param text - Resume or job description text+ * @param provider - AI provider (ollama/openai)+ * @param modelName - Model to use for extraction+ * @param contextHint - Optional hint about domain (e.g., "software engineering", "healthcare")+ */+export async function extractSemanticKeywords(+ text: string,+ provider: ProviderType = "ollama",+ modelName: string = "llama3.2",+ contextHint?: string+): Promise<SemanticKeywordExtraction> {+ const model = getModel(provider, modelName);+ const schema = isOllamaProvider(provider)+ ? OllamaSemanticKeywordSchema+ : SemanticKeywordSchema;+ const prompt = getKeywordPrompt(provider, text, contextHint);++ try {+ const { object } = await generateObject({+ model,+ schema,+ prompt,+ temperature: 0.1,+ });++ // Normalize Ollama result to full schema format+ if (isOllamaProvider(provider)) {+ return normalizeKeywordExtraction(+ object as OllamaSemanticKeywordExtraction+ );+ }++ return object as SemanticKeywordExtraction;+ } catch (error) {+ console.error("Semantic keyword extraction failed:", error);+ throw new AIUnavailableError("keyword extraction");+ }+}++/**+ * Analyze action verbs using LLM for semantic strength assessment+ * Replaces hard-coded verb lists with intelligent analysis+ *+ * Benefits:+ * - Understands verb strength in context+ * - Identifies passive constructions+ * - Provides specific improvement suggestions+ * - Recognizes weak phrases like "responsible for"+ *+ * @param text - Resume text to analyze+ * @param provider - AI provider (ollama/openai)+ * @param modelName - Model to use for analysis+ */+export async function analyzeActionVerbs(+ text: string,+ provider: ProviderType = "ollama",+ modelName: string = "llama3.2"+): Promise<ActionVerbAnalysis> {+ const model = getModel(provider, modelName);+ const schema = isOllamaProvider(provider)+ ? OllamaActionVerbSchema+ : ActionVerbAnalysisSchema;+ const prompt = getVerbPrompt(provider, text);++ try {+ const { object } = await generateObject({+ model,+ schema,+ prompt,+ temperature: 0.2,+ });++ // Normalize Ollama result to full schema format+ if (isOllamaProvider(provider)) {+ return normalizeActionVerbAnalysis(object as OllamaActionVerbAnalysis);+ }++ return object as ActionVerbAnalysis;+ } catch (error) {+ console.error("Action verb analysis failed:", error);+ throw new AIUnavailableError("action verb analysis");+ }+}++/**+ * Perform semantic skill matching between resume and job+ * Uses LLM to understand skill relationships and transferability+ *+ * Benefits:+ * - Recognizes related skills (PostgreSQL vs MySQL)+ * - Assesses skill transferability+ * - Provides learnability estimates+ * - Gives strategic application advice+ *+ * @param resumeText - Candidate's resume text+ * @param jobText - Job description text+ * @param provider - AI provider (ollama/openai)+ * @param modelName - Model to use for matching+ */+export async function performSemanticSkillMatch(+ resumeText: string,+ jobText: string,+ provider: ProviderType = "ollama",+ modelName: string = "llama3.2"+): Promise<SemanticSkillMatch> {+ const model = getModel(provider, modelName);+ const schema = isOllamaProvider(provider)+ ? OllamaSkillMatchSchema+ : SemanticSkillMatchSchema;+ const prompt = getSkillMatchPrompt(provider, resumeText, jobText);++ try {+ const { object } = await generateObject({+ model,+ schema,+ prompt,+ temperature: 0.2,+ });++ // Normalize Ollama result to full schema format+ if (isOllamaProvider(provider)) {+ return normalizeSkillMatch(object as OllamaSkillMatch);+ }++ // Post-process cloud result to remove empty strings and duplicates+ const cloudResult = object as SemanticSkillMatch;+ const cleanedResult = {+ exact_matches: cloudResult.exact_matches.filter(+ (match) =>+ match.skill.trim() &&+ match.resume_evidence.trim() &&+ match.job_requirement.trim()+ ),+ related_matches: cloudResult.related_matches.filter(+ (match) =>+ match.job_skill.trim() &&+ match.resume_skill.trim() &&+ match.explanation.trim()+ ),+ missing_skills: cloudResult.missing_skills.filter((skill) =>+ skill.skill.trim()+ ),+ overall_match_percentage: cloudResult.overall_match_percentage,+ };++ // Remove duplicate skills from missing_skills if they're in exact_matches+ const exactSkills = new Set(+ cleanedResult.exact_matches.map((m) => m.skill.toLowerCase())+ );+ cleanedResult.missing_skills = cleanedResult.missing_skills.filter(+ (m) => !exactSkills.has(m.skill.toLowerCase())+ );++ return cleanedResult;+ } catch (error) {+ console.error("Semantic skill matching failed:", error);+ throw new AIUnavailableError("skill matching");+ }+}++/**+ * Get keyword count from semantic extraction (for backward compatibility)+ */+export function getKeywordCountFromSemantic(+ extraction: SemanticKeywordExtraction+): number {+ return extraction.total_count;+}++/**+ * Get verb count from semantic analysis (for backward compatibility)+ */+export function getVerbCountFromSemantic(analysis: ActionVerbAnalysis): number {+ return analysis.strong_verbs.length;+}diff --git a/src/lib/ai/tools/semantic-similarity.ts b/src/lib/ai/tools/semantic-similarity.tsnew file mode 100644index 0000000..498df97--- /dev/null+++ b/src/lib/ai/tools/semantic-similarity.ts@@ -0,0 +1,205 @@+/**+ * Semantic Similarity Tools+ * Complete semantic understanding of resume-job fit, replacing keyword overlap+ */++import { generateObject } from "ai";+import { getModel, ProviderType } from "../providers";+import {+ SemanticSimilaritySchema,+ type SemanticSimilarityResult,+ type SemanticSkillMatch,+} from "@/models/ai.schemas";+import { getSimilarityPrompt } from "../prompts/semantic-prompts";+import {+ isOllamaProvider,+ OllamaSemanticSimilaritySchema,+ normalizeSemanticSimilarity,+ type OllamaSemanticSimilarity,+} from "../ollama";+import { AIUnavailableError } from "./errors";++/**+ * Calculate semantic similarity between resume and job description+ * This is the core function that replaces keyword overlap entirely+ *+ * Uses LLM to:+ * 1. Calculate overall semantic similarity (0-100)+ * 2. Generate human-readable explanation of fit+ * 3. Identify key matching areas and gaps+ * 4. Provide strategic application advice+ *+ * @param resumeText - Candidate's resume text+ * @param jobDescription - Job description text+ * @param provider - AI provider (ollama/openai/deepseek)+ * @param modelName - Model to use+ * @returns SemanticSimilarityResult with score, explanations, and recommendations+ */+export async function calculateSemanticSimilarity(+ resumeText: string,+ jobDescription: string,+ provider: ProviderType = "ollama",+ modelName: string = "llama3.2"+): Promise<SemanticSimilarityResult> {+ const model = getModel(provider, modelName);+ const schema = isOllamaProvider(provider)+ ? OllamaSemanticSimilaritySchema+ : SemanticSimilaritySchema;+ const prompt = getSimilarityPrompt(provider, resumeText, jobDescription);++ try {+ const { object } = await generateObject({+ model,+ schema,+ prompt,+ temperature: 0.2,+ });++ // Normalize Ollama result to full schema format+ if (isOllamaProvider(provider)) {+ return normalizeSemanticSimilarity(object as OllamaSemanticSimilarity);+ }++ return object as SemanticSimilarityResult;+ } catch (error) {+ console.error("Semantic similarity calculation failed:", error);+ throw new AIUnavailableError("similarity calculation");+ }+}++/**+ * Generate a comprehensive match explanation combining semantic skill matching+ * and overall similarity assessment+ *+ * This function synthesizes data from performSemanticSkillMatch and calculateSemanticSimilarity+ * to create detailed, actionable explanations for the user+ *+ * @param skillMatch - Result from performSemanticSkillMatch+ * @param similarity - Result from calculateSemanticSimilarity+ * @returns Structured explanation with fit summary and detailed insights+ */+export function generateMatchExplanation(+ skillMatch: SemanticSkillMatch,+ similarity: SemanticSimilarityResult+): {+ summary: string;+ fit_assessment: string;+ strengths_explanation: string[];+ gaps_explanation: string[];+ transferable_explanation: string[];+ action_items: string[];+} {+ // Generate strengths explanation from exact and related matches+ const strengthsExplanation: string[] = [];++ skillMatch.exact_matches.slice(0, 3).forEach((match) => {+ strengthsExplanation.push(+ `✅ **${+ match.skill+ }**: Directly matches requirement - "${match.resume_evidence.substring(+ 0,+ 60+ )}..."`+ );+ });++ skillMatch.related_matches.slice(0, 2).forEach((match) => {+ strengthsExplanation.push(+ `⚡ **${match.resume_skill}** transfers to **${match.job_skill}** (${match.similarity}% similar): ${match.explanation}`+ );+ });++ // Generate gaps explanation with learnability context+ const gapsExplanation: string[] = [];++ skillMatch.missing_skills.slice(0, 4).forEach((skill) => {+ const urgencyIcon =+ skill.importance === "critical"+ ? "🔴"+ : skill.importance === "important"+ ? "🟡"+ : "🟢";+ const learnTime =+ skill.learnability === "quick"+ ? "<1 month"+ : skill.learnability === "moderate"+ ? "1-3 months"+ : "3+ months";+ gapsExplanation.push(+ `${urgencyIcon} **${skill.skill}** (${skill.importance}): Learning time ~${learnTime}`+ );+ });++ // Generate transferable skills explanation+ const transferableExplanation: string[] = similarity.transferable_skills.map(+ (skill) =>+ `💡 ${skill.resume_skill} → ${skill.job_skill}: ${skill.how_it_transfers}`+ );++ // Generate prioritized action items+ const actionItems: string[] = [];++ // Critical missing skills first+ const criticalMissing = skillMatch.missing_skills.filter(+ (s) => s.importance === "critical"+ );+ if (criticalMissing.length > 0) {+ actionItems.push(+ `🔴 Address critical gaps first: ${criticalMissing+ .map((s) => s.skill)+ .join(", ")}`+ );+ }++ // Quick wins+ const quickLearns = skillMatch.missing_skills.filter(+ (s) => s.learnability === "quick" && s.importance !== "nice-to-have"+ );+ if (quickLearns.length > 0) {+ actionItems.push(+ `⚡ Quick wins (learn in <1 month): ${quickLearns+ .map((s) => s.skill)+ .join(", ")}`+ );+ }++ // Highlight existing transferable skills in application+ if (skillMatch.related_matches.length > 0) {+ actionItems.push(+ `📝 Highlight transferable skills in cover letter: ${skillMatch.related_matches+ .slice(0, 3)+ .map((m) => m.resume_skill)+ .join(", ")}`+ );+ }++ // Fit assessment based on scores+ let fitAssessment: string;+ const score = similarity.similarity_score;+ if (score >= 75) {+ fitAssessment = "Excellent fit - You're a strong candidate for this role.";+ } else if (score >= 60) {+ fitAssessment = "Good fit - You match most requirements with minor gaps.";+ } else if (score >= 45) {+ fitAssessment =+ "Moderate fit - Some gaps exist but may be worth applying with a tailored resume.";+ } else if (score >= 30) {+ fitAssessment =+ "Weak fit - Significant gaps; consider upskilling before applying.";+ } else {+ fitAssessment =+ "Poor fit - This role may not align with your current skills and experience.";+ }++ return {+ summary: similarity.match_explanation,+ fit_assessment: fitAssessment,+ strengths_explanation: strengthsExplanation,+ gaps_explanation: gapsExplanation,+ transferable_explanation: transferableExplanation,+ action_items:+ actionItems.length > 0+ ? actionItems+ : ["No critical actions needed - proceed with application"],+ };+}