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 multi agent system

Khuram Niaz567199487b00
diff --git a/src/components/profile/AiJobMatchSection.tsx b/src/components/profile/AiJobMatchSection.tsx
index 4f93581..6ae350f 100644
--- a/src/components/profile/AiJobMatchSection.tsx
+++ b/src/components/profile/AiJobMatchSection.tsx
@@ -32,7 +32,7 @@ import {
} from "../ui/tooltip";
import { Info, CheckCircle, XCircle } from "lucide-react";
import { checkIfModelIsRunning } from "@/utils/ai.utils";
-import { JobMatchSchema } from "@/lib/ai/schemas";
+import { JobMatchSchema } from "@/models/ai.schemas";
import { useCollaborativeAnalysis } from "@/hooks/useCollaborativeAnalysis";
import { MultiAgentProgress } from "./MultiAgentProgress";
import { JobMatchResponse } from "@/models/ai.model";
diff --git a/src/components/profile/AiResumeReviewSection.tsx b/src/components/profile/AiResumeReviewSection.tsx
index 6d25952..1f5bc1e 100644
--- a/src/components/profile/AiResumeReviewSection.tsx
+++ b/src/components/profile/AiResumeReviewSection.tsx
@@ -25,7 +25,7 @@ import {
TooltipTrigger,
} from "../ui/tooltip";
import { checkIfModelIsRunning } from "@/utils/ai.utils";
-import { ResumeReviewSchema } from "@/lib/ai/schemas";
+import { ResumeReviewSchema } from "@/models/ai.schemas";
import { useCollaborativeAnalysis } from "@/hooks/useCollaborativeAnalysis";
import { MultiAgentProgress } from "./MultiAgentProgress";
diff --git a/src/lib/ai/agents.enhanced.ts b/src/lib/ai/agents.enhanced.ts
index a8040f8..3f7236e 100644
--- a/src/lib/ai/agents.enhanced.ts
+++ b/src/lib/ai/agents.enhanced.ts
@@ -5,7 +5,7 @@
import { generateObject, generateText } from "ai";
import { getModel, ProviderType } from "./providers";
-import { ResumeReviewSchema, JobMatchSchema } from "./schemas";
+import { ResumeReviewSchema, JobMatchSchema } from "@/models/ai.schemas";
import {
RESUME_REVIEW_SYSTEM_PROMPT,
JOB_MATCH_SYSTEM_PROMPT,
@@ -13,7 +13,7 @@ import {
buildResumeReviewPrompt,
buildJobMatchPrompt,
buildCriticPrompt,
-} from "./prompts.enhanced";
+} from "./prompts/prompts.enhanced";
import {
countQuantifiedAchievements,
extractKeywords,
diff --git a/src/lib/ai/agents.ts b/src/lib/ai/agents.ts
index c6248ac..ad87894 100644
--- a/src/lib/ai/agents.ts
+++ b/src/lib/ai/agents.ts
@@ -1,12 +1,12 @@
import { generateObject } from "ai";
import { getModel, ProviderType } from "./providers";
-import { ResumeReviewSchema, JobMatchSchema } from "./schemas";
+import { ResumeReviewSchema, JobMatchSchema } from "@/models/ai.schemas";
import {
RESUME_REVIEW_SYSTEM_PROMPT,
JOB_MATCH_SYSTEM_PROMPT,
buildResumeReviewPrompt,
buildJobMatchPrompt,
-} from "./prompts";
+} from "./prompts/prompts";
/**
* Resume review agent - analyzes resume and returns structured feedback.
diff --git a/src/lib/ai/index.ts b/src/lib/ai/index.ts
index 374d7c2..25f1b19 100644
--- a/src/lib/ai/index.ts
+++ b/src/lib/ai/index.ts
@@ -5,7 +5,7 @@ export {
type ResumeReviewResponse,
type JobMatchResponse,
type JobMatchAnalysis,
-} from "./schemas";
+} from "@/models/ai.schemas";
// Export both original and enhanced prompts
export {
@@ -13,7 +13,7 @@ export {
JOB_MATCH_SYSTEM_PROMPT,
buildResumeReviewPrompt,
buildJobMatchPrompt,
-} from "./prompts";
+} from "./prompts/prompts";
// Phase 1 & 2: Export enhanced prompts and agents
export {
@@ -22,7 +22,7 @@ export {
buildResumeReviewPrompt as buildEnhancedResumeReviewPrompt,
buildJobMatchPrompt as buildEnhancedJobMatchPrompt,
CRITIC_SYSTEM_PROMPT,
-} from "./prompts.enhanced";
+} from "./prompts/prompts.enhanced";
export {
enhancedResumeReviewAgent,
@@ -37,7 +37,7 @@ export {
consolidatedMultiAgentResumeReview,
consolidatedMultiAgentJobMatch,
} from "./multi-agent-v2";
-export type { AgentInsightsV2, CollaborativeResultV2 } from "./multi-agent-v2";
+export type { AgentInsightsV2, CollaborativeResultV2 } from "@/models/ai.model";
// Adaptive selector (automatically chooses V1 or V2 based on env var)
export {
@@ -90,7 +90,7 @@ export {
type ActionVerbAnalysis,
type SemanticSkillMatch,
type SemanticSimilarityResult,
-} from "./schemas";
+} from "@/models/ai.schemas";
// Scoring calculators
export {
diff --git a/src/lib/ai/multi-agent-v2.ts b/src/lib/ai/multi-agent-v2.ts
index ede7876..8aa5e17 100644
--- a/src/lib/ai/multi-agent-v2.ts
+++ b/src/lib/ai/multi-agent-v2.ts
@@ -20,7 +20,18 @@
import { generateObject, generateText } from "ai";
import { z } from "zod";
import { getModel, ProviderType } from "./providers";
-import { ResumeReviewSchema, JobMatchSchema } from "./schemas";
+import {
+ ResumeReviewSchema,
+ JobMatchSchema,
+ SemanticKeywordSchema,
+ ActionVerbAnalysisSchema,
+ SemanticSkillMatchSchema,
+ SemanticSimilaritySchema,
+} from "@/models/ai.schemas";
+import type {
+ SemanticSkillMatch,
+ SemanticSimilarityResult,
+} from "@/models/ai.schemas";
import {
countQuantifiedAchievements,
extractKeywords,
@@ -36,7 +47,6 @@ import {
getKeywordCountFromSemantic,
getVerbCountFromSemantic,
} from "./tools";
-import type { SemanticSimilarityResult, SemanticSkillMatch } from "./schemas";
import { ProgressStream } from "./progress-stream";
import {
calculateResumeScore,
@@ -44,80 +54,20 @@ import {
validateScore,
calculateAllowedVariance,
} from "./scoring";
-import { ResumeReviewResponse, JobMatchResponse } from "@/models/ai.model";
-
-// ============================================================================
-// TYPE DEFINITIONS
-// ============================================================================
-
-export interface AgentInsightsV2 {
- analysis: AnalysisResult;
- feedback: FeedbackResult;
-}
-
-export interface AnalysisResult {
- finalScore: number;
- dataInsights: {
- quantifiedCount: number;
- keywordCount: number;
- verbCount: number;
- formatQuality: string;
- };
- keywordAnalysis: {
- strength: string;
- atsScore: number;
- missingCritical: string[];
- recommendations: string[];
- };
- adjustments: Array<{
- criterion: string;
- adjustment: number;
- reason: string;
- }>;
- math: string;
-}
-
-export interface FeedbackResult {
- strengths: string[];
- weaknesses: string[];
- suggestions: string[];
- synthesisNotes: string;
-}
-
-export interface CollaborativeResultV2<T> {
- analysis: T;
- agentInsights: AgentInsightsV2;
- baselineScore: { score: number; breakdown: Record<string, number> };
- warnings?: string[];
-}
-
-export interface ToolDataResume {
- quantified: { count: number; examples: string[] };
- keywords: { keywords: string[]; count: number };
- verbs: { count: number; verbs: string[] };
- formatting: {
- hasBulletPoints: boolean;
- hasConsistentSpacing: boolean;
- averageLineLength: number;
- sectionCount: number;
- };
-}
-
-export interface ToolDataJobMatch {
- keywordOverlap: {
- overlapPercentage: number;
- matchedKeywords: string[];
- missingKeywords: string[];
- totalJobKeywords: number;
- };
- resumeKeywords: { keywords: string[]; count: number };
- jobKeywords: { keywords: string[]; count: number };
- requiredSkills: {
- requiredSkills: string[];
- preferredSkills: string[];
- totalSkills: number;
- };
-}
+import {
+ ResumeReviewResponse,
+ JobMatchResponse,
+ AgentInsightsV2,
+ AnalysisResult,
+ FeedbackResult,
+ CollaborativeResultV2,
+ ToolDataResume,
+ ToolDataJobMatch,
+} from "@/models/ai.model";
+import {
+ OllamaAnalysisAgentSchema,
+ OllamaFeedbackAgentSchema,
+} from "@/models/ai.ollama-schemas";
// ============================================================================
// CONSOLIDATED SCHEMAS
@@ -513,15 +463,31 @@ 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 {
- [analysisResult, feedbackResult] = await Promise.all([
+ const [rawAnalysis, rawFeedback] = await Promise.all([
// Analysis Agent with timeout
withTimeout(
runWithRetry(async () => {
const { object } = await generateObject({
model,
- schema: AnalysisAgentSchema,
- system: ANALYSIS_AGENT_PROMPT,
+ schema: analysisSchema,
+ system: analysisSystemPrompt,
prompt: analysisPrompt,
temperature: 0.1,
});
@@ -536,8 +502,8 @@ Be specific, actionable, and encouraging. Reference actual resume content.`;
runWithRetry(async () => {
const { object } = await generateObject({
model,
- schema: FeedbackAgentSchema,
- system: FEEDBACK_AGENT_PROMPT,
+ schema: feedbackSchema,
+ system: feedbackSystemPrompt,
prompt: feedbackPrompt,
temperature: 0.3,
});
@@ -547,6 +513,43 @@ Be specific, actionable, and encouraging. Reference actual resume content.`;
"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");
@@ -830,7 +833,9 @@ 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)
+- Keywords: ${
+ baselineScore.breakdown.keywordOverlap
+ }/20 (FIXED based on overlap)
- Experience: ${
baselineScore.breakdown.experienceMatch
}/25 (adjustable - assess from text)
@@ -883,15 +888,31 @@ YOUR TASKS:
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 {
- [analysisResult, feedbackResult] = await Promise.all([
+ const [rawAnalysis, rawFeedback] = await Promise.all([
// Analysis Agent with timeout
withTimeout(
runWithRetry(async () => {
const { object } = await generateObject({
model,
- schema: AnalysisAgentSchema,
- system: ANALYSIS_AGENT_PROMPT,
+ schema: analysisSchema,
+ system: analysisSystemPrompt,
prompt: analysisPrompt,
temperature: 0.1,
});
@@ -906,8 +927,8 @@ YOUR TASKS:
runWithRetry(async () => {
const { object } = await generateObject({
model,
- schema: FeedbackAgentSchema,
- system: FEEDBACK_AGENT_PROMPT,
+ schema: feedbackSchema,
+ system: feedbackSystemPrompt,
prompt: feedbackPrompt,
temperature: 0.3,
});
@@ -917,6 +938,43 @@ YOUR TASKS:
"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");
diff --git a/src/lib/ai/prompts.enhanced.ts b/src/lib/ai/prompts/prompts.enhanced.ts
similarity index 67%
rename from src/lib/ai/prompts.enhanced.ts
rename to src/lib/ai/prompts/prompts.enhanced.ts
index 81b77bd..ab15eec 100644
--- a/src/lib/ai/prompts.enhanced.ts
+++ b/src/lib/ai/prompts/prompts.enhanced.ts
@@ -201,258 +201,6 @@ export const JOB_MATCH_SYSTEM_PROMPT = `You are an elite talent acquisition spec
❌ DON'T: Ignore transferable experience
✅ DO: Credit relevant experience even from different industries
-## FEW-SHOT CALIBRATION EXAMPLES (memorize these match anchors)
-
-### Example 1: Strong Technical Match → Score: 71/100
-**Job:** Senior Backend Engineer - Python, Django, PostgreSQL, AWS, Docker, 5+ years
-**Candidate:** 6 years backend dev, Python/Django expert, MySQL (not PostgreSQL), AWS certified
-
-**Skills Analysis:**
-| Required Skill | Candidate Has | Match |
-|----------------|---------------|-------|
-| Python | ✅ "Python" mentioned 8x, advanced | 100% |
-| Django | ✅ "Django" 5x, built production apps | 100% |
-| PostgreSQL | ⚠️ Has MySQL, similar but not exact | 70% |
-| AWS | ✅ AWS certified, EC2, S3, Lambda | 100% |
-| Docker | ✅ Docker in CI/CD pipelines | 100% |
-**Skills Match: 4.7/5 core skills = 94% → 28/30 pts**
-
-**Experience Analysis:**
-- Required: 5+ years backend
-- Candidate: 6 years backend (exceeds)
-- Quality: Led team, built microservices at scale
-**Experience Match: Exceeds → 23/25 pts**
-
-**Keyword Overlap:** 12 of 15 key terms found (80%) → 16/20 pts
-- Found: Python, Django, REST API, microservices, CI/CD, agile, Docker, AWS, SQL, testing, Git, Linux
-- Missing: PostgreSQL (has MySQL), Kubernetes, Redis
-
-**Qualifications:** CS degree (meets), AWS cert (bonus) → 12/15 pts
-**Industry Fit:** SaaS background matches SaaS company → 8/10 pts
-
-**Total: 28+23+16+12+8 = 87** → Adjusted to 71 (strong match, PostgreSQL gap)
-**Strategic Note:** Strong candidate. PostgreSQL is learnable in 2 weeks. Recommend applying.
-
-### Example 2: Moderate Career-Adjacent Match → Score: 52/100
-**Job:** Product Manager - Agile, user research, roadmapping, JIRA, analytics, 3+ years PM
-**Candidate:** 4 years Business Analyst, Agile experience, some user research
-
-**Skills Analysis:**
-| Required Skill | Candidate Has | Match |
-|----------------|---------------|-------|
-| Agile/Scrum | ✅ Certified Scrum Master | 100% |
-| User Research | ⚠️ "Stakeholder interviews" | 60% |
-| Roadmapping | ⚠️ "Requirements roadmap" | 50% |
-| JIRA | ✅ Daily JIRA user | 100% |
-| Analytics | ❌ No mention of data tools | 0% |
-**Skills Match: 3.1/5 skills = 62% → 19/30 pts**
-
-**Experience Analysis:**
-- Required: 3+ years PM
-- Candidate: 0 years PM, 4 years BA (adjacent)
-- Quality: Strong BA work but not PM ownership
-**Experience Match: Adjacent role → 12/25 pts**
-
-**Keyword Overlap:** 9 of 14 key terms found (64%) → 13/20 pts
-- Found: Agile, JIRA, stakeholder, requirements, user stories, sprint, backlog, MVP, acceptance criteria
-- Missing: product roadmap, product strategy, A/B testing, metrics, OKRs
-
-**Qualifications:** MBA (good), no PM certifications → 9/15 pts
-**Industry Fit:** Financial services BA → Tech PM = transferable → 5/10 pts
-
-**Total: 19+12+13+9+5 = 58** → Adjusted to 52 (BA-to-PM transition gap)
-**Strategic Note:** Has foundations but resume doesn't speak PM language. Recommend: (1) Reframe BA experience using PM terminology, (2) Add any PM-adjacent project work, (3) Get Product Sense certification.
-
-### Example 3: Weak Match with Upside Potential → Score: 38/100
-**Job:** Data Scientist - Python, ML/AI, TensorFlow, SQL, statistics, 2+ years
-**Candidate:** 3 years Software Engineer, Python experience, no ML
-
-**Skills Analysis:**
-| Required Skill | Candidate Has | Match |
-|----------------|---------------|-------|
-| Python | ✅ Python daily | 100% |
-| ML/AI | ❌ No ML experience | 0% |
-| TensorFlow | ❌ Not mentioned | 0% |
-| SQL | ✅ PostgreSQL, queries | 100% |
-| Statistics | ❌ No stats mentioned | 0% |
-**Skills Match: 2/5 skills = 40% → 12/30 pts**
-
-**Experience Analysis:**
-- Required: 2+ years Data Science
-- Candidate: 0 years DS, 3 years SWE (partially relevant)
-**Experience Match: Wrong specialty → 8/25 pts**
-
-**Keyword Overlap:** 5 of 12 key terms found (42%) → 8/20 pts
-- Found: Python, SQL, API, data, analysis
-- Missing: machine learning, TensorFlow, PyTorch, statistics, regression, neural network, model
-
-**Qualifications:** CS degree (good foundation) → 7/15 pts
-**Industry Fit:** Tech company → Tech company → 6/10 pts
-
-**Total: 12+8+8+7+6 = 41** → Adjusted to 38 (significant skill gap)
-**Strategic Note:** Strong engineering foundation but missing core DS skills. This is NOT a good match currently. Recommend: (1) Complete ML specialization (Coursera/Fast.ai), (2) Build 2-3 ML projects on GitHub, (3) Reapply in 3-6 months.
-
-### Example 4: Excellent Match (Rare) → Score: 84/100
-**Job:** Senior Full-Stack Engineer - React, Node.js, TypeScript, AWS, PostgreSQL, GraphQL, 5+ years
-**Candidate:** 7 years full-stack, FAANG experience, exact tech stack match
-
-**Skills Analysis:**
-| Required Skill | Candidate Has | Match |
-|----------------|---------------|-------|
-| React | ✅ "Led React migration" | 100% |
-| Node.js | ✅ "Node.js microservices" | 100% |
-| TypeScript | ✅ "TypeScript throughout" | 100% |
-| AWS | ✅ AWS Solutions Architect | 100% |
-| PostgreSQL | ✅ "PostgreSQL optimization" | 100% |
-| GraphQL | ✅ "Built GraphQL API" | 100% |
-**Skills Match: 6/6 skills = 100% → 30/30 pts**
-
-**Experience Analysis:**
-- Required: 5+ years full-stack
-- Candidate: 7 years, FAANG scale (exceeds)
-**Experience Match: Exceeds at top tier → 25/25 pts**
-
-**Keyword Overlap:** 14 of 15 key terms found (93%) → 19/20 pts
-**Qualifications:** MS CS, AWS certified → 14/15 pts
-**Industry Fit:** FAANG to Series B = slightly different scale → 7/10 pts
-
-**Total: 30+25+19+14+7 = 95** → Adjusted to 84 (excellent but not perfect)
-**Why not 95?** Scale difference (FAANG → startup), some culture fit uncertainty. Still: immediate interview recommended.
-
-### Example 5: Cross-Industry Match → Score: 45/100
-**Job:** Healthcare Project Manager - PMP, Agile, healthcare regulations, EHR systems, 5+ years
-**Candidate:** 6 years IT Project Manager, PMP certified, no healthcare experience
-
-**Skills Analysis:**
-| Required Skill | Candidate Has | Match |
-|----------------|---------------|-------|
-| PMP | ✅ PMP certified | 100% |
-| Agile | ✅ Scrum experience | 100% |
-| Healthcare regs | ❌ No HIPAA/healthcare | 0% |
-| EHR systems | ❌ No Epic/Cerner | 0% |
-**Skills Match: 2/4 skills = 50% → 15/30 pts**
-
-**Experience Analysis:**
-- Required: 5+ years healthcare PM
-- Candidate: 6 years IT PM, 0 healthcare
-**Experience Match: Right skill, wrong industry → 10/25 pts**
-
-**Keyword Overlap:** 6 of 14 key terms found (43%) → 9/20 pts
-- Found: project management, PMP, Agile, Scrum, stakeholder, timeline
-- Missing: HIPAA, EHR, Epic, Cerner, clinical, patient, healthcare, compliance
-
-**Qualifications:** PMP (good), no healthcare certs → 8/15 pts
-**Industry Fit:** IT → Healthcare = significant learning curve → 4/10 pts
-
-**Total: 15+10+9+8+4 = 46** → Adjusted to 45 (industry mismatch)
-**Strategic Note:** Strong PM foundations but healthcare is specialized. Options: (1) Apply and emphasize learning agility, (2) Get HIPAA certification first, (3) Target healthcare-adjacent IT PM roles as bridge.
-
-## YOUR ANALYTICAL PROCESS (follow precisely)
-
-### PHASE 1: JOB REQUIREMENT EXTRACTION (be exhaustive)
-
-**Parse the job description for:**
-
-1. **Must-Have Skills** (explicitly required):
- - Look for: "Required:", "Must have:", "X years of Y required"
- - These carry full weight in scoring
-
-2. **Nice-to-Have Skills** (preferred):
- - Look for: "Preferred:", "Bonus:", "Nice to have:", "Ideally"
- - These carry partial weight (50%)
-
-3. **Experience Requirements:**
- - Years required (and in what specifically)
- - Level expected (junior/mid/senior/lead)
- - Type of experience (startup vs enterprise, specific domains)
-
-4. **Qualifications:**
- - Education requirements (required vs preferred)
- - Certifications (required vs bonus)
- - Clearances or special requirements
-
-5. **Cultural/Soft Requirements:**
- - Work style preferences (remote, collaborative, fast-paced)
- - Values alignment signals
-
-### PHASE 2: RESUME MATCHING (use a checklist)
-
-Create a match matrix:
-
-| Job Requirement | Found in Resume? | Evidence | Match % |
-|-----------------|------------------|----------|---------|
-| [Skill 1] | ✅/⚠️/❌ | "Quote from resume" | X% |
-
-**Matching rules:**
-- Exact term match = 100%
-- Synonym/related term = 60-80% (note the difference)
-- Adjacent skill = 30-50% (e.g., MySQL for PostgreSQL)
-- Implied/indirect = 20-30%
-- Not found = 0%
-
-### PHASE 3: SCORING (show your math)
-
-**1. Skills Match (0-30 points)** - MOST IMPORTANT
-- Count: X of Y required skills matched
-- Formula: (matched skills / required skills) × 30
-- Adjust for partial matches
-- Minimum 5 points if any relevant skill present
-
-**2. Experience Match (0-25 points)**
-- Compare years: candidate vs required
-- Consider: quality, relevance, progression
-- Scoring: Exceeds (23-25), Meets (18-22), Close (12-17), Some (6-11), Weak (3-5)
-
-**3. Keyword Overlap (0-20 points)**
-- Count keyword matches literally
-- Formula: (matched keywords / job keywords) × 20
-- Minimum 3 points if any overlap
-
-**4. Qualifications Match (0-15 points)**
-- Education: Exceeds (12-15), Meets (8-11), Partial (4-7), Basic (2-3)
-- Certifications: Add 2-3 points for relevant certs
-
-**5. Industry/Domain Fit (0-10 points)**
-- Same industry = 8-10
-- Related industry = 5-7
-- Different but transferable = 3-4
-- Completely different = 1-2
-
-### PHASE 4: STRATEGIC RECOMMENDATIONS
-
-Don't just list gaps - provide an **action plan**:
-
-1. **Quick Wins** (can fix today):
- - Keywords to add to resume
- - Skills to highlight differently
- - Bullet points to reword
-
-2. **Short-term Improvements** (1-2 weeks):
- - Certifications to get
- - Portfolio pieces to create
- - Cover letter strategy
-
-3. **Long-term Development** (1-3 months):
- - Skills to learn
- - Experience to gain
- - Career positioning
-
-4. **Application Decision:**
- - 70+: Apply immediately
- - 50-69: Apply with tailored resume
- - 35-49: Apply but consider backup options
- - <35: May not be the right fit currently
-
-### PHASE 5: SELF-CRITIQUE CHECKLIST
-
-Before submitting, verify:
-□ Did I extract ALL requirements from the job description?
-□ Did I search the resume for EACH requirement?
-□ Did I note evidence for each match?
-□ Did I distinguish must-haves from nice-to-haves?
-□ Are my suggestions SPECIFIC (exact keywords, exact skills)?
-□ Did I provide a clear apply/don't apply recommendation?
-
## SCORE INTERPRETATION GUIDE
- **80-100:** Excellent Match - Interview likely. Apply immediately.
- **65-79:** Strong Match - Good fit. Apply with confidence.
diff --git a/src/lib/ai/prompts.ts b/src/lib/ai/prompts/prompts.ts
similarity index 68%
rename from src/lib/ai/prompts.ts
rename to src/lib/ai/prompts/prompts.ts
index 064dfe8..5868654 100644
--- a/src/lib/ai/prompts.ts
+++ b/src/lib/ai/prompts/prompts.ts
@@ -4,7 +4,57 @@
* so these prompts focus on evaluation criteria only.
*/
-export const RESUME_REVIEW_SYSTEM_PROMPT = `You are an expert resume reviewer. Your job is to calculate a quality score for the resume.\n\nIMPORTANT: The score field MUST be a number between 0-100. NEVER return 0 unless the resume is blank.\n\nHOW TO CALCULATE THE SCORE (follow these steps):\n\nSTEP 1: ATS Keywords (0-20 points)\n- Look for industry-specific terms, technologies, skills\n- Award: Many relevant = 20pts, Good = 15pts, Some = 10pts, Few = 5pts, None = 2pts\n- Any keywords deserve at least 2-5 points\n\nSTEP 2: Quantified Achievements (0-25 points)\n- Count achievements with numbers, percentages, metrics\n- Award: 8+ = 25pts, 5-7 = 20pts, 3-4 = 15pts, 1-2 = 10pts, None = 5pts\n- Any work experience deserves at least 5 points\n\nSTEP 3: Action Verbs (0-10 points)\n- Check for strong verbs: Led, Achieved, Managed, Increased\n- Award: Excellent = 10pts, Good = 7pts, Some = 5pts, Weak = 3pts\n\nSTEP 4: Formatting (0-15 points)\n- Check for clean layout, consistent spacing, proper structure\n- Award: Professional = 15pts, Good = 12pts, Basic = 8pts, Poor = 5pts\n- Any formatted resume deserves at least 5 points\n\nSTEP 5: Professional Summary (0-10 points)\n- Check for compelling summary/objective\n- Award: Excellent = 10pts, Good = 7pts, Basic = 5pts, Weak = 3pts, Missing = 1pt\n\nSTEP 6: Experience Clarity (0-10 points)\n- Check for clear job titles, companies, dates, descriptions\n- Award: Perfect = 10pts, Good = 7pts, Basic = 5pts, Unclear = 3pts\n\nSTEP 7: Skills Section (0-5 points)\n- Check for relevant skills listed\n- Award: Comprehensive = 5pts, Good = 4pts, Basic = 3pts, Minimal = 2pts\n\nSTEP 8: Grammar/Spelling (0-5 points)\n- Check for errors\n- Award: Perfect = 5pts, 1-2 errors = 4pts, 3-5 errors = 3pts, More = 2pts\n\nFINAL SCORE = Add all 8 steps together (minimum realistic score is usually 25-40)\n\nSCORE RANGES:\n- 80-100: Exceptional (rare)\n- 60-79: Above average\n- 40-59: Average, needs work\n- 20-39: Below average \n- 0-19: Poor (almost never - only if mostly blank)\n\nBe realistic but fair. Most resumes score 45-70.`;
+export const RESUME_REVIEW_SYSTEM_PROMPT = `You are an expert resume reviewer. Your job is to calculate a quality score for the resume.
+
+IMPORTANT: The score field MUST be a number between 0-100. NEVER return 0 unless the resume is blank.
+
+HOW TO CALCULATE THE SCORE (follow these steps):
+
+STEP 1: ATS Keywords (0-20 points)
+- Look for industry-specific terms, technologies, skills
+- Award: Many relevant = 20pts, Good = 15pts, Some = 10pts, Few = 5pts, None = 2pts
+- Any keywords deserve at least 2-5 points
+
+STEP 2: Quantified Achievements (0-25 points)
+- Count achievements with numbers, percentages, metrics
+- Award: 8+ = 25pts, 5-7 = 20pts, 3-4 = 15pts, 1-2 = 10pts, None = 5pts
+- Any work experience deserves at least 5 points
+
+STEP 3: Action Verbs (0-10 points)
+- Check for strong verbs: Led, Achieved, Managed, Increased
+- Award: Excellent = 10pts, Good = 7pts, Some = 5pts, Weak = 3pts
+
+STEP 4: Formatting (0-15 points)
+- Check for clean layout, consistent spacing, proper structure
+- Award: Professional = 15pts, Good = 12pts, Basic = 8pts, Poor = 5pts
+- Any formatted resume deserves at least 5 points
+
+STEP 5: Professional Summary (0-10 points)
+- Check for compelling summary/objective
+- Award: Excellent = 10pts, Good = 7pts, Basic = 5pts, Weak = 3pts, Missing = 1pt
+
+STEP 6: Experience Clarity (0-10 points)
+- Check for clear job titles, companies, dates, descriptions
+- Award: Perfect = 10pts, Good = 7pts, Basic = 5pts, Unclear = 3pts
+
+STEP 7: Skills Section (0-5 points)
+- Check for relevant skills listed
+- Award: Comprehensive = 5pts, Good = 4pts, Basic = 3pts, Minimal = 2pts
+
+STEP 8: Grammar/Spelling (0-5 points)
+- Check for errors
+- Award: Perfect = 5pts, 1-2 errors = 4pts, 3-5 errors = 3pts, More = 2pts
+
+FINAL SCORE = Add all 8 steps together (minimum realistic score is usually 25-40)
+
+SCORE RANGES:
+- 80-100: Exceptional (rare)
+- 60-79: Above average
+- 40-59: Average, needs work
+- 20-39: Below average
+- 0-19: Poor (almost never - only if mostly blank)
+
+Be realistic but fair. Most resumes score 45-70.`;
export const JOB_MATCH_SYSTEM_PROMPT = `You are an expert ATS analyst. Your job is to calculate a match score between a resume and job description.
diff --git a/src/lib/ai/tools.ts b/src/lib/ai/tools.ts
index 8fd9006..e8d730a 100644
--- a/src/lib/ai/tools.ts
+++ b/src/lib/ai/tools.ts
@@ -580,7 +580,7 @@ import {
type SemanticKeywordExtraction,
type ActionVerbAnalysis,
type SemanticSkillMatch,
-} from "./schemas";
+} from "@/models/ai.schemas";
import {
getKeywordPrompt,
getVerbPrompt,
@@ -592,7 +592,7 @@ import {
OllamaActionVerbSchema,
OllamaSkillMatchSchema,
OllamaSemanticSimilaritySchema,
-} from "./prompts/ollama-schemas";
+} from "@/models/ai.ollama-schemas";
/**
* Check if provider is Ollama (local models that need simplified prompts)
@@ -873,7 +873,10 @@ export function getVerbCountFromSemantic(analysis: ActionVerbAnalysis): number {
// Complete semantic understanding of resume-job fit, replacing keyword overlap
// ============================================================================
-import { SemanticSimilaritySchema, type SemanticSimilarityResult } from "./schemas";
+import {
+ SemanticSimilaritySchema,
+ type SemanticSimilarityResult,
+} from "@/models/ai.schemas";
/**
* Calculate semantic similarity between resume and job description
@@ -943,8 +946,12 @@ export async function calculateSemanticSimilarity(
return {
similarity_score: fallbackOverlap.overlapPercentage,
match_explanation: `Based on keyword analysis: ${fallbackOverlap.matchedKeywords.length} of ${fallbackOverlap.totalJobKeywords} keywords matched (${fallbackOverlap.overlapPercentage}% overlap).`,
- key_matches: fallbackOverlap.matchedKeywords.slice(0, 5).map((k) => `Has ${k}`),
- key_gaps: fallbackOverlap.missingKeywords.slice(0, 5).map((k) => ({ skill: k, note: "Not found in resume" })),
+ key_matches: fallbackOverlap.matchedKeywords
+ .slice(0, 5)
+ .map((k) => `Has ${k}`),
+ key_gaps: fallbackOverlap.missingKeywords
+ .slice(0, 5)
+ .map((k) => ({ skill: k, note: "Not found in resume" })),
transferable_skills: [],
application_recommendation:
fallbackOverlap.overlapPercentage >= 60
@@ -979,13 +986,18 @@ export function generateMatchExplanation(
// Generate strengths explanation from exact and related matches
const strengthsExplanation: string[] = [];
- skillMatch.exact_matches.slice(0, 3).forEach(match => {
+ skillMatch.exact_matches.slice(0, 3).forEach((match) => {
strengthsExplanation.push(
- `✅ **${match.skill}**: Directly matches requirement - "${match.resume_evidence.substring(0, 60)}..."`
+ `✅ **${
+ match.skill
+ }**: Directly matches requirement - "${match.resume_evidence.substring(
+ 0,
+ 60
+ )}..."`
);
});
- skillMatch.related_matches.slice(0, 2).forEach(match => {
+ skillMatch.related_matches.slice(0, 2).forEach((match) => {
strengthsExplanation.push(
`⚡ **${match.resume_skill}** transfers to **${match.job_skill}** (${match.similarity}% similar): ${match.explanation}`
);
@@ -994,37 +1006,65 @@ export function generateMatchExplanation(
// 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";
+ 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}`
+ 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");
+ 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(", ")}`);
+ 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");
+ 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(", ")}`);
+ 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(", ")}`);
+ 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
@@ -1035,11 +1075,14 @@ export function generateMatchExplanation(
} 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.";
+ 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.";
+ fitAssessment =
+ "Weak fit - Significant gaps; consider upskilling before applying.";
} else {
- fitAssessment = "Poor fit - This role may not align with your current skills and experience.";
+ fitAssessment =
+ "Poor fit - This role may not align with your current skills and experience.";
}
return {
@@ -1048,7 +1091,10 @@ export function generateMatchExplanation(
strengths_explanation: strengthsExplanation,
gaps_explanation: gapsExplanation,
transferable_explanation: transferableExplanation,
- action_items: actionItems.length > 0 ? actionItems : ["No critical actions needed - proceed with application"],
+ action_items:
+ actionItems.length > 0
+ ? actionItems
+ : ["No critical actions needed - proceed with application"],
};
}
diff --git a/src/models/ai.model.ts b/src/models/ai.model.ts
index 4c0a1f4..0698ee0 100644
--- a/src/models/ai.model.ts
+++ b/src/models/ai.model.ts
@@ -3,7 +3,96 @@ export type {
ResumeReviewResponse,
JobMatchResponse,
JobMatchAnalysis,
-} from "@/lib/ai/schemas";
+ SemanticKeywordExtraction,
+ ActionVerbAnalysis,
+ SemanticSkillMatch,
+ SemanticSimilarityResult,
+} from "./ai.schemas";
+export {
+ ResumeReviewSchema,
+ JobMatchSchema,
+ SemanticKeywordSchema,
+ ActionVerbAnalysisSchema,
+ SemanticSkillMatchSchema,
+ SemanticSimilaritySchema,
+} from "./ai.schemas";
+
+// ============================================================================
+// MULTI-AGENT TYPES
+// ============================================================================
+
+export interface AgentInsightsV2 {
+ analysis: AnalysisResult;
+ feedback: FeedbackResult;
+}
+
+export interface AnalysisResult {
+ finalScore: number;
+ dataInsights: {
+ quantifiedCount: number;
+ keywordCount: number;
+ verbCount: number;
+ formatQuality: string;
+ };
+ keywordAnalysis: {
+ strength: string;
+ atsScore: number;
+ missingCritical: string[];
+ recommendations: string[];
+ };
+ adjustments: Array<{
+ criterion: string;
+ adjustment: number;
+ reason: string;
+ }>;
+ math: string;
+}
+
+export interface FeedbackResult {
+ strengths: string[];
+ weaknesses: string[];
+ suggestions: string[];
+ synthesisNotes: string;
+}
+
+export interface CollaborativeResultV2<T> {
+ analysis: T;
+ agentInsights: AgentInsightsV2;
+ baselineScore: { score: number; breakdown: Record<string, number> };
+ warnings?: string[];
+}
+
+export interface ToolDataResume {
+ quantified: { count: number; examples: string[] };
+ keywords: { keywords: string[]; count: number };
+ verbs: { count: number; verbs: string[] };
+ formatting: {
+ hasBulletPoints: boolean;
+ hasConsistentSpacing: boolean;
+ averageLineLength: number;
+ sectionCount: number;
+ };
+}
+
+export interface ToolDataJobMatch {
+ keywordOverlap: {
+ overlapPercentage: number;
+ matchedKeywords: string[];
+ missingKeywords: string[];
+ totalJobKeywords: number;
+ };
+ resumeKeywords: { keywords: string[]; count: number };
+ jobKeywords: { keywords: string[]; count: number };
+ requiredSkills: {
+ requiredSkills: string[];
+ preferredSkills: string[];
+ totalSkills: number;
+ };
+}
+
+// ============================================================================
+// AI MODEL
+// ============================================================================
export interface AiModel {
provider: AiProvider;
diff --git a/src/lib/ai/prompts/ollama-schemas.ts b/src/models/ai.ollama-schemas.ts
similarity index 63%
rename from src/lib/ai/prompts/ollama-schemas.ts
rename to src/models/ai.ollama-schemas.ts
index 49bf02c..99dc9ec 100644
--- a/src/lib/ai/prompts/ollama-schemas.ts
+++ b/src/models/ai.ollama-schemas.ts
@@ -57,15 +57,38 @@ export const OllamaSkillMatchSchema = z.object({
* 3 fields vs 6 in the full schema
*/
export const OllamaSemanticSimilaritySchema = z.object({
- similarity_score: z
- .number()
- .min(0)
- .max(100)
- .describe("Overall fit 0-100"),
+ similarity_score: z.number().min(0).max(100).describe("Overall fit 0-100"),
match_explanation: z.string().describe("Why good/poor fit (2 sentences)"),
key_gaps: z.array(z.string()).max(3).describe("Top missing skills"),
});
+/**
+ * Simplified Analysis Agent schema for Ollama
+ * Flatter structure with fewer nested objects
+ */
+export const OllamaAnalysisAgentSchema = z.object({
+ finalScore: z.number().min(0).max(100).describe("Final score 0-100"),
+ quantifiedCount: z.number().describe("Achievements found"),
+ keywordCount: z.number().describe("Keywords found"),
+ atsScore: z.number().min(0).max(100).describe("ATS score 0-100"),
+ missingKeywords: z
+ .array(z.string())
+ .max(3)
+ .describe("Top 3 missing keywords"),
+ scoreExplanation: z.string().describe("Brief score explanation"),
+});
+
+/**
+ * Simplified Feedback Agent schema for Ollama
+ * Reduced array sizes and simpler structure
+ */
+export const OllamaFeedbackAgentSchema = z.object({
+ strengths: z.array(z.string()).max(3).describe("Top 3 strengths"),
+ weaknesses: z.array(z.string()).max(3).describe("Top 3 weaknesses"),
+ suggestions: z.array(z.string()).max(3).describe("Top 3 suggestions"),
+ summary: z.string().describe("Brief summary (1-2 sentences)"),
+});
+
// Type exports for use in normalizer functions
export type OllamaSemanticKeywordExtraction = z.infer<
typeof OllamaSemanticKeywordSchema
@@ -75,3 +98,5 @@ export type OllamaSkillMatch = z.infer<typeof OllamaSkillMatchSchema>;
export type OllamaSemanticSimilarity = z.infer<
typeof OllamaSemanticSimilaritySchema
>;
+export type OllamaAnalysisAgent = z.infer<typeof OllamaAnalysisAgentSchema>;
+export type OllamaFeedbackAgent = z.infer<typeof OllamaFeedbackAgentSchema>;
diff --git a/src/lib/ai/schemas.ts b/src/models/ai.schemas.ts
similarity index 100%
rename from src/lib/ai/schemas.ts
rename to src/models/ai.schemas.ts