Skip to content

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.

Refactor to reduce duplication

Khuram Niaz3520dbb5dead
diff --git a/src/lib/ai/multi-agent/job-match.ts b/src/lib/ai/multi-agent/job-match.ts
index d2b5d6d..7cef800 100644
--- a/src/lib/ai/multi-agent/job-match.ts
+++ b/src/lib/ai/multi-agent/job-match.ts
@@ -4,22 +4,17 @@
* 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 {
@@ -30,31 +25,28 @@ import {
import {
JobMatchResponse,
AgentInsights,
- AnalysisResult,
- FeedbackResult,
CollaborativeResult,
ToolDataJobMatch,
+ SemanticData,
} 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";
+import { withTimeout } from "./utils";
+import {
+ executeAgents,
+ handleExtractionError,
+ handleAgentError,
+} from "./shared";
-// ============================================================================
// JOB MATCH
-// ============================================================================
export async function multiAgentJobMatch(
resumeText: string,
@@ -65,22 +57,18 @@ export async function multiAgentJobMatch(
): Promise<CollaborativeResult<JobMatchResponse>> {
const model = getModel(provider, modelName);
- // =========================================================================
- // STEP 1: Tool Extraction - Full Semantic Analysis (Phase 3)
- // =========================================================================
+ // STEP 1: Tool Extraction - Full Semantic Analysis
+
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 };
+ let semanticData: SemanticData = {
+ 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(
@@ -104,7 +92,6 @@ export async function multiAgentJobMatch(
),
]);
- // Generate comprehensive match explanation
const matchExplanation = generateMatchExplanation(
semanticMatch,
semanticSimilarity
@@ -116,17 +103,15 @@ export async function multiAgentJobMatch(
];
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!
+ overlapPercentage: semanticSimilarity.similarity_score,
matchedKeywords,
missingKeywords,
totalJobKeywords: matchedKeywords.length + missingKeywords.length,
@@ -155,27 +140,13 @@ export async function multiAgentJobMatch(
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");
+ handleExtractionError(error, progressStream, "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,
@@ -186,8 +157,8 @@ export async function multiAgentJobMatch(
keywordOverlapPercent: toolData.keywordOverlap.overlapPercentage,
matchedSkillsCount,
requiredSkillsCount,
- experienceYears: 0, // Will be assessed by AI
- requiredYears: 0, // Will be assessed by AI
+ experienceYears: 0,
+ requiredYears: 0,
});
const allowedVariance = calculateAllowedVariance(
@@ -201,15 +172,13 @@ export async function multiAgentJobMatch(
`[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,
@@ -219,7 +188,121 @@ export async function multiAgentJobMatch(
minScore,
maxScore
)
- : `Analyze how well this resume matches the job description:
+ : buildFullJobMatchAnalysisPrompt(
+ resumeText,
+ jobDescription,
+ toolData,
+ baselineScore,
+ matchedSkillsCount,
+ requiredSkillsCount,
+ minScore,
+ maxScore
+ );
+
+ const feedbackPrompt = isOllama
+ ? buildOllamaJobMatchFeedbackPrompt(
+ resumeText,
+ jobDescription,
+ toolData,
+ baselineScore
+ )
+ : buildFullJobMatchFeedbackPrompt(
+ resumeText,
+ jobDescription,
+ toolData,
+ baselineScore,
+ minScore,
+ maxScore
+ );
+
+ let analysisResult;
+ let feedbackResult;
+
+ try {
+ const result = await executeAgents({
+ model,
+ provider,
+ analysis: {
+ schema: isOllama ? OllamaAnalysisAgentSchema : AnalysisAgentSchema,
+ systemPrompt: isOllama
+ ? OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT
+ : ANALYSIS_AGENT_PROMPT,
+ prompt: analysisPrompt,
+ temperature: 0.1,
+ },
+ feedback: {
+ schema: isOllama ? OllamaFeedbackAgentSchema : FeedbackAgentSchema,
+ systemPrompt: isOllama
+ ? OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT
+ : FEEDBACK_AGENT_PROMPT,
+ prompt: feedbackPrompt,
+ temperature: 0.3,
+ },
+ });
+
+ analysisResult = result.analysisResult;
+ feedbackResult = result.feedbackResult;
+ } catch (error) {
+ handleAgentError(error, progressStream, "job matching");
+ }
+
+ 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
+
+ const finalResponse = buildJobMatchResponse(
+ validatedScore,
+ baselineScore,
+ toolData,
+ semanticData,
+ analysisResult,
+ feedbackResult,
+ matchedSkillsCount,
+ requiredSkillsCount
+ );
+
+ const agentInsights: AgentInsights = {
+ analysis: analysisResult,
+ feedback: feedbackResult,
+ };
+
+ return {
+ analysis: finalResponse,
+ agentInsights,
+ baselineScore,
+ warnings: warnings.length > 0 ? warnings : undefined,
+ };
+}
+
+// PROMPT BUILDERS
+
+function buildFullJobMatchAnalysisPrompt(
+ resumeText: string,
+ jobDescription: string,
+ toolData: ToolDataJobMatch,
+ baselineScore: { score: number; breakdown: Record<string, number> },
+ matchedSkillsCount: number,
+ requiredSkillsCount: number,
+ minScore: number,
+ maxScore: number
+): string {
+ return `Analyze how well this resume matches the job description:
RESUME:
${resumeText}
@@ -229,8 +312,8 @@ ${jobDescription}
OBJECTIVE METRICS (from tools):
- Skills matched: ${matchedSkillsCount} of ${requiredSkillsCount} (${Math.round(
- (matchedSkillsCount / Math.max(requiredSkillsCount, 1)) * 100
- )}%)
+ (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)}%
@@ -240,11 +323,11 @@ 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)
+ baselineScore.breakdown.keywordOverlap
+ }/20 (FIXED based on overlap)
- Experience: ${
- baselineScore.breakdown.experienceMatch
- }/25 (adjustable - assess from text)
+ baselineScore.breakdown.experienceMatch
+ }/25 (adjustable - assess from text)
- Qualifications: ${baselineScore.breakdown.qualifications}/15 (adjustable)
- Industry Fit: ${baselineScore.breakdown.industryFit}/10 (adjustable)
@@ -255,15 +338,17 @@ YOUR TASKS:
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:
+function buildFullJobMatchFeedbackPrompt(
+ resumeText: string,
+ jobDescription: string,
+ toolData: ToolDataJobMatch,
+ baselineScore: { score: number; breakdown: Record<string, number> },
+ minScore: number,
+ maxScore: number
+): string {
+ return `Generate match feedback comparing resume to job description:
RESUME:
${resumeText}
@@ -275,130 +360,33 @@ CONTEXT:
- Baseline score: ${baselineScore.score}/100
- Expected range: ${minScore}-${maxScore}
- Matched skills: ${toolData.keywordOverlap.matchedKeywords
- .slice(0, 5)
- .join(", ")}
+ .slice(0, 5)
+ .join(", ")}
- Missing skills: ${toolData.keywordOverlap.missingKeywords
- .slice(0, 5)
- .join(", ")}
+ .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
+// RESPONSE BUILDER
+
+function buildJobMatchResponse(
+ validatedScore: number,
+ baselineScore: { score: number; breakdown: Record<string, number> },
+ toolData: ToolDataJobMatch,
+ semanticData: SemanticData,
+ analysisResult: {
+ keywordAnalysis: { strength: string; missingCritical: string[] };
+ },
+ feedbackResult: { suggestions: string[]; synthesisNotes: string },
+ matchedSkillsCount: number,
+ requiredSkillsCount: number
+): JobMatchResponse {
const detailedAnalysis = [];
// Skills Match - use semantic skill match data if available
@@ -414,18 +402,25 @@ YOUR TASKS:
...semanticData.skillMatch.exact_matches
.slice(0, 3)
.map(
- (m) => `✅ ${m.skill}: "${m.resume_evidence.substring(0, 40)}..."`
+ (m: { skill: string; resume_evidence: string }) =>
+ `✅ ${m.skill}: "${m.resume_evidence.substring(0, 40)}..."`
),
...semanticData.skillMatch.related_matches
.slice(0, 2)
.map(
- (m) =>
+ (m: {
+ resume_skill: string;
+ job_skill: string;
+ similarity: number;
+ }) =>
`⚡ ${m.resume_skill} → ${m.job_skill} (${m.similarity}% similar)`
),
...semanticData.skillMatch.missing_skills
- .filter((s) => s.importance === "critical")
+ .filter((s: any) => s.importance === "critical")
.slice(0, 2)
- .map((s) => `❌ ${s.skill} (critical, ${s.learnability} to learn)`),
+ .map(
+ (s: any) => `❌ ${s.skill} (critical, ${s.learnability} to learn)`
+ ),
],
});
} else {
@@ -443,7 +438,8 @@ YOUR TASKS:
});
}
- // Semantic Similarity - Phase 3 replacement for keyword overlap
+ // Semantic Similarity
+
if (semanticData.similarity) {
detailedAnalysis.push({
category: `Semantic Fit (${baselineScore.breakdown.keywordOverlap}/20 pts)`,
@@ -467,7 +463,7 @@ YOUR TASKS:
});
}
- // Transferable Skills (Phase 3 - new section)
+ // Transferable Skills
if (
semanticData.similarity &&
semanticData.similarity.transferable_skills.length > 0
@@ -477,7 +473,8 @@ YOUR TASKS:
value: semanticData.similarity.transferable_skills
.slice(0, 3)
.map(
- (s) => `💡 ${s.resume_skill} → ${s.job_skill}: ${s.how_it_transfers}`
+ (s: any) =>
+ `💡 ${s.resume_skill} → ${s.job_skill}: ${s.how_it_transfers}`
),
});
}
@@ -526,7 +523,7 @@ YOUR TASKS:
? "Apply after addressing key gaps"
: "Consider upskilling before applying");
- const finalResponse: JobMatchResponse = {
+ return {
matching_score: validatedScore,
detailed_analysis: detailedAnalysis,
suggestions,
@@ -543,16 +540,4 @@ YOUR TASKS:
`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.ts
index 0eefecb..4dfd2ee 100644
--- a/src/lib/ai/multi-agent/resume-review.ts
+++ b/src/lib/ai/multi-agent/resume-review.ts
@@ -4,7 +4,6 @@
* 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 {
@@ -18,7 +17,6 @@ import {
analyzeActionVerbs,
getKeywordCountFromSemantic,
getVerbCountFromSemantic,
- AIUnavailableError,
} from "../tools";
import { ProgressStream } from "../progress-stream";
import {
@@ -29,27 +27,25 @@ import {
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";
+import { withTimeout } from "./utils";
+import {
+ executeAgents,
+ handleExtractionError,
+ handleAgentError,
+} from "./shared";
// ============================================================================
// RESUME REVIEW
@@ -68,12 +64,9 @@ export async function multiAgentResumeReview(
// =========================================================================
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),
@@ -109,20 +102,7 @@ export async function multiAgentResumeReview(
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");
+ handleExtractionError(error, progressStream, "resume analysis");
}
progressStream?.sendCompleted("tool-extraction", 0);
@@ -151,14 +131,12 @@ export async function multiAgentResumeReview(
// =========================================================================
// 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,
@@ -167,155 +145,44 @@ export async function multiAgentResumeReview(
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.`;
+ : buildFullResumeAnalysisPrompt(
+ resumeText,
+ toolData,
+ baselineScore,
+ minScore,
+ maxScore
+ );
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}
+ : buildFullResumeFeedbackPrompt(resumeText, baselineScore, 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;
+ let analysisResult;
+ let feedbackResult;
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"
- ),
- ]);
+ const result = await executeAgents({
+ model,
+ provider,
+ analysis: {
+ schema: isOllama ? OllamaAnalysisAgentSchema : AnalysisAgentSchema,
+ systemPrompt: isOllama ? OLLAMA_ANALYSIS_SYSTEM_PROMPT : ANALYSIS_AGENT_PROMPT,
+ prompt: analysisPrompt,
+ temperature: 0.1,
+ },
+ feedback: {
+ schema: isOllama ? OllamaFeedbackAgentSchema : FeedbackAgentSchema,
+ systemPrompt: isOllama ? OLLAMA_FEEDBACK_SYSTEM_PROMPT : FEEDBACK_AGENT_PROMPT,
+ prompt: feedbackPrompt,
+ temperature: 0.3,
+ },
+ verbCount: toolData.verbs.count,
+ });
- // 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;
- }
+ analysisResult = result.analysisResult;
+ feedbackResult = result.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}`
- );
+ handleAgentError(error, progressStream, "resume analysis");
}
progressStream?.sendCompleted("analysis-agent", 1);
@@ -366,3 +233,76 @@ Be specific, actionable, and encouraging. Reference actual resume content.`;
warnings: warnings.length > 0 ? warnings : undefined,
};
}
+
+// ============================================================================
+// PROMPT BUILDERS
+// ============================================================================
+
+function buildFullResumeAnalysisPrompt(
+ resumeText: string,
+ toolData: ToolDataResume,
+ baselineScore: { score: number; breakdown: Record<string, number> },
+ minScore: number,
+ maxScore: number
+): string {
+ return `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.`;
+}
+
+function buildFullResumeFeedbackPrompt(
+ resumeText: string,
+ baselineScore: { score: number; breakdown: Record<string, number> },
+ minScore: number,
+ maxScore: number
+): string {
+ return `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.`;
+}
diff --git a/src/lib/ai/multi-agent/shared/agent-executor.ts b/src/lib/ai/multi-agent/shared/agent-executor.ts
new file mode 100644
index 0000000..0513698
--- /dev/null
+++ b/src/lib/ai/multi-agent/shared/agent-executor.ts
@@ -0,0 +1,81 @@
+/**
+ * Generic Agent Executor
+ *
+ * Handles parallel execution of Analysis and Feedback agents with:
+ * - Provider-aware schema selection
+ * - Timeout and retry logic
+ * - Ollama result normalization
+ */
+
+import { generateObject } from "ai";
+import {
+ AnalysisResult,
+ FeedbackResult,
+ AgentExecutorParams,
+ AgentExecutorResult,
+} from "@/models/ai.model";
+import {
+ isOllamaProvider,
+ AGENT_TIMEOUT_MS,
+ normalizeAnalysisResult,
+ normalizeFeedbackResult,
+ type OllamaAnalysisAgent,
+ type OllamaFeedbackAgent,
+} from "../../ollama";
+import { runWithRetry, withTimeout } from "../utils";
+
+export async function executeAgents(
+ params: AgentExecutorParams
+): Promise<AgentExecutorResult> {
+ const { model, provider, analysis, feedback, verbCount } = params;
+ const isOllama = isOllamaProvider(provider);
+
+ const [rawAnalysis, rawFeedback] = await Promise.all([
+ withTimeout(
+ runWithRetry(async () => {
+ const { object } = await generateObject({
+ model,
+ schema: analysis.schema,
+ system: analysis.systemPrompt,
+ prompt: analysis.prompt,
+ temperature: analysis.temperature,
+ });
+ return object;
+ }, "Analysis Agent"),
+ AGENT_TIMEOUT_MS,
+ "Analysis Agent"
+ ),
+
+ withTimeout(
+ runWithRetry(async () => {
+ const { object } = await generateObject({
+ model,
+ schema: feedback.schema,
+ system: feedback.systemPrompt,
+ prompt: feedback.prompt,
+ temperature: feedback.temperature,
+ });
+ return object;
+ }, "Feedback Agent"),
+ AGENT_TIMEOUT_MS,
+ "Feedback Agent"
+ ),
+ ]);
+
+ if (isOllama) {
+ return {
+ analysisResult: normalizeAnalysisResult(
+ rawAnalysis as OllamaAnalysisAgent,
+ verbCount
+ ),
+ feedbackResult: normalizeFeedbackResult(
+ rawFeedback as OllamaFeedbackAgent
+ ),
+ };
+ }
+
+ return {
+ analysisResult: rawAnalysis as AnalysisResult,
+ feedbackResult: rawFeedback as FeedbackResult,
+ };
+}
diff --git a/src/lib/ai/multi-agent/shared/error-handler.ts b/src/lib/ai/multi-agent/shared/error-handler.ts
new file mode 100644
index 0000000..21b5404
--- /dev/null
+++ b/src/lib/ai/multi-agent/shared/error-handler.ts
@@ -0,0 +1,63 @@
+/**
+ * Standardized Error Handling
+ *
+ * Provides consistent error handling patterns for the multi-agent system.
+ */
+
+import { ProgressStream } from "../../progress-stream";
+import { AIUnavailableError } from "../../tools";
+
+export type OperationType = "resume analysis" | "job matching";
+export type StepType = "tool-extraction" | "analysis-agent";
+
+function isTimeoutError(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : String(error);
+ return message.includes("timed out");
+}
+
+export function handleExtractionError(
+ error: unknown,
+ progressStream: ProgressStream | undefined,
+ operationType: OperationType
+): never {
+ const isTimeout = isTimeoutError(error);
+
+ console.error(`[${operationType}] Semantic extraction failed:`, error);
+
+ if (progressStream) {
+ const warningMsg = isTimeout
+ ? "AI model is taking too long. Please try again or use a different model."
+ : `AI unavailable for ${operationType}. Please try again later.`;
+ progressStream.sendWarning("tool-extraction", warningMsg, 0);
+ }
+
+ throw new AIUnavailableError(operationType);
+}
+
+export function handleAgentError(
+ error: unknown,
+ progressStream: ProgressStream | undefined,
+ operationType: OperationType
+): never {
+ const errorMessage = error instanceof Error ? error.message : String(error);
+ const isTimeout = isTimeoutError(error);
+
+ console.error(`[${operationType}] Agent execution failed:`, error);
+
+ 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);
+ }
+
+ const actionName = operationType === "resume analysis"
+ ? "Resume review"
+ : "Job match analysis";
+
+ throw new Error(
+ isTimeout
+ ? `${actionName} timed out. The AI model may be overloaded. Please try again.`
+ : `${actionName} failed: ${errorMessage}`
+ );
+}
diff --git a/src/lib/ai/multi-agent/shared/index.ts b/src/lib/ai/multi-agent/shared/index.ts
new file mode 100644
index 0000000..f20298b
--- /dev/null
+++ b/src/lib/ai/multi-agent/shared/index.ts
@@ -0,0 +1,19 @@
+/**
+ * Shared Multi-Agent Utilities
+ *
+ * Common functionality used by both resume review and job match agents.
+ */
+
+export {
+ executeAgents,
+ type AgentConfig,
+ type AgentExecutorParams,
+ type AgentExecutorResult,
+} from "./agent-executor";
+
+export {
+ handleExtractionError,
+ handleAgentError,
+ type OperationType,
+ type StepType,
+} from "./error-handler";
diff --git a/src/models/ai.model.ts b/src/models/ai.model.ts
index f26328b..7c45eed 100644
--- a/src/models/ai.model.ts
+++ b/src/models/ai.model.ts
@@ -1,3 +1,9 @@
+// Import types needed in this file
+import type {
+ SemanticSkillMatch,
+ SemanticSimilarityResult,
+} from "./ai.schemas";
+
// Re-export types from new schemas
export type {
ResumeReviewResponse,
@@ -17,9 +23,7 @@ export {
SemanticSimilaritySchema,
} from "./ai.schemas";
-// ============================================================================
// MULTI-AGENT TYPES
-// ============================================================================
export interface AgentInsights {
analysis: AnalysisResult;
@@ -62,6 +66,43 @@ export interface CollaborativeResult<T> {
warnings?: string[];
}
+// AGENT EXECUTOR TYPES
+
+export interface AgentConfig {
+ schema: import("zod").ZodSchema;
+ systemPrompt: string;
+ prompt: string;
+ temperature: number;
+}
+
+export interface AgentExecutorParams {
+ model: import("ai").LanguageModel;
+ provider: import("../lib/ai/providers").ProviderType;
+ analysis: AgentConfig;
+ feedback: AgentConfig;
+ verbCount?: number; // For Ollama normalization in resume review
+}
+
+export interface AgentExecutorResult {
+ analysisResult: AnalysisResult;
+ feedbackResult: FeedbackResult;
+}
+
+// JOB MATCH TYPES
+
+export interface SemanticData {
+ skillMatch: SemanticSkillMatch | null;
+ similarity: SemanticSimilarityResult | null;
+ matchExplanation: {
+ summary: string;
+ fit_assessment: string;
+ strengths_explanation: string[];
+ gaps_explanation: string[];
+ transferable_explanation: string[];
+ action_items: string[];
+ } | null;
+}
+
export interface ToolDataResume {
quantified: { count: number; examples: string[] };
keywords: { keywords: string[]; count: number };
@@ -90,9 +131,7 @@ export interface ToolDataJobMatch {
};
}
-// ============================================================================
// AI MODEL
-// ============================================================================
export interface AiModel {
provider: AiProvider;