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.

Remove multi agent approach

Khuram Niaz9dc762873bef
diff --git a/__tests__/ai.actions.spec.ts b/__tests__/ai.actions.spec.ts
index 972ea9d..6dfe773 100644
--- a/__tests__/ai.actions.spec.ts
+++ b/__tests__/ai.actions.spec.ts
@@ -1,6 +1,6 @@
/**
- * AI Library Tests - Multi-Agent System
- * Tests for the new mathematical scoring and multi-agent collaboration system
+ * AI Library Tests
+ * Tests for the mathematical scoring and analysis system
*/
import {
diff --git a/__tests__/ai.library.spec.ts b/__tests__/ai.library.spec.ts
index c69513d..6145d1a 100644
--- a/__tests__/ai.library.spec.ts
+++ b/__tests__/ai.library.spec.ts
@@ -1,13 +1,11 @@
/**
- * AI Library Tests - Multi-Agent System
+ * AI Library Tests
* Tests for analysis tools, mathematical scoring, and validation functions
*
- * Note: This tests the AI library functions used by the API routes, not server actions.
+ * Note: This tests the AI library functions used by the API routes.
* The AI functionality is implemented in API routes:
- * - /api/ai/resume/review (single-agent)
- * - /api/ai/resume/review-collaborative (multi-agent)
- * - /api/ai/resume/match (single-agent job matching)
- * - /api/ai/resume/match-collaborative (multi-agent job matching)
+ * - /api/ai/resume/review (resume analysis)
+ * - /api/ai/resume/match (job matching)
*/
import {
diff --git a/__tests__/performance-comparison.spec.ts b/__tests__/performance-comparison.spec.ts
deleted file mode 100644
index 23c8036..0000000
--- a/__tests__/performance-comparison.spec.ts
+++ /dev/null
@@ -1,267 +0,0 @@
-/**
- * Multi-Agent System Performance Tests
- * Measures latency, score consistency, and quality
- */
-
-import {
- multiAgentResumeReview,
- multiAgentJobMatch,
- type ProviderType,
-} from "@/lib/ai";
-
-const SAMPLE_RESUME = `
-John Doe
-Senior Software Engineer
-
-PROFESSIONAL SUMMARY
-Experienced software engineer with 8+ years building scalable web applications.
-Led teams of 5-10 engineers to deliver mission-critical systems.
-
-EXPERIENCE
-Senior Software Engineer - Tech Corp (2020-Present)
-- Led migration to microservices architecture, reducing latency by 40%
-- Managed $2M cloud infrastructure budget, achieving 25% cost savings
-- Mentored 5 junior engineers, improving team velocity by 30%
-- Built REST APIs handling 10M+ requests/day
-
-Software Engineer - StartupCo (2016-2020)
-- Developed React-based dashboard used by 50K+ users
-- Implemented CI/CD pipeline reducing deployment time by 60%
-- Optimized database queries improving response time by 45%
-
-SKILLS
-Languages: JavaScript, TypeScript, Python, SQL
-Frontend: React, Next.js, Vue.js, HTML/CSS
-Backend: Node.js, Express, Django, PostgreSQL
-Cloud: AWS (EC2, S3, Lambda), Docker, Kubernetes
-Tools: Git, Jest, Webpack, CI/CD
-
-EDUCATION
-BS Computer Science - State University (2016)
-`;
-
-const SAMPLE_JOB = `
-Senior Full Stack Engineer
-
-We are seeking an experienced full stack engineer to join our growing team.
-
-REQUIREMENTS:
-- 5+ years of professional software development experience
-- Strong proficiency in JavaScript/TypeScript and React
-- Experience with Node.js and RESTful API design
-- Familiarity with cloud platforms (AWS, Azure, or GCP)
-- Experience with Docker and containerization
-- Strong problem-solving and communication skills
-
-PREFERRED:
-- Experience with Kubernetes and microservices
-- PostgreSQL or other SQL database experience
-- CI/CD pipeline setup and maintenance
-- Team leadership or mentoring experience
-
-RESPONSIBILITIES:
-- Design and build scalable web applications
-- Collaborate with product and design teams
-- Mentor junior developers
-- Participate in code reviews and technical planning
-`;
-
-interface PerformanceMetrics {
- latency: number;
- score: number;
- timestamp: Date;
- type: "resume" | "job-match";
- warnings?: string[];
-}
-
-/**
- * Run a single test and collect metrics
- */
-async function runTest(
- type: "resume" | "job-match"
-): Promise<PerformanceMetrics> {
- const startTime = Date.now();
-
- try {
- if (type === "resume") {
- const result = await multiAgentResumeReview(
- SAMPLE_RESUME,
- "openai" as ProviderType,
- "gpt-4o"
- );
-
- const latency = Date.now() - startTime;
-
- return {
- latency,
- score: result.analysis.score,
- timestamp: new Date(),
- type,
- warnings: result.warnings,
- };
- } else {
- const result = await multiAgentJobMatch(
- SAMPLE_RESUME,
- SAMPLE_JOB,
- "openai" as ProviderType,
- "gpt-4o"
- );
-
- const latency = Date.now() - startTime;
-
- return {
- latency,
- score: result.analysis.matching_score,
- timestamp: new Date(),
- type,
- warnings: result.warnings,
- };
- }
- } catch (error) {
- const latency = Date.now() - startTime;
- console.error(`Test failed for ${type}:`, error);
- return {
- latency,
- score: -1,
- timestamp: new Date(),
- type,
- warnings: [error instanceof Error ? error.message : String(error)],
- };
- }
-}
-
-/**
- * Run multiple iterations and calculate statistics
- */
-async function runBenchmark(
- type: "resume" | "job-match",
- iterations: number = 3
-): Promise<{
- avgLatency: number;
- minLatency: number;
- maxLatency: number;
- avgScore: number;
- scoreVariance: number;
- successRate: number;
- metrics: PerformanceMetrics[];
-}> {
- console.log(`\nRunning ${iterations} iterations for ${type}...`);
-
- const metrics: PerformanceMetrics[] = [];
-
- for (let i = 0; i < iterations; i++) {
- console.log(` Iteration ${i + 1}/${iterations}...`);
- const result = await runTest(type);
- metrics.push(result);
-
- // Wait 2 seconds between iterations to avoid rate limiting
- if (i < iterations - 1) {
- await new Promise((resolve) => setTimeout(resolve, 2000));
- }
- }
-
- const successfulMetrics = metrics.filter((m) => m.score >= 0);
- const latencies = successfulMetrics.map((m) => m.latency);
- const scores = successfulMetrics.map((m) => m.score);
-
- const avgLatency = latencies.reduce((a, b) => a + b, 0) / latencies.length;
- const avgScore = scores.reduce((a, b) => a + b, 0) / scores.length;
- const scoreVariance =
- scores.reduce((sum, score) => sum + Math.pow(score - avgScore, 2), 0) /
- scores.length;
-
- return {
- avgLatency,
- minLatency: Math.min(...latencies),
- maxLatency: Math.max(...latencies),
- avgScore,
- scoreVariance: Math.sqrt(scoreVariance),
- successRate: (successfulMetrics.length / metrics.length) * 100,
- metrics,
- };
-}
-
-/**
- * Run performance benchmarks
- */
-async function runPerformanceTests() {
- console.log("=".repeat(80));
- console.log("MULTI-AGENT SYSTEM PERFORMANCE TEST");
- console.log("=".repeat(80));
-
- // Resume Review Test
- console.log("\nRESUME REVIEW TEST");
- const resumeResults = await runBenchmark("resume", 3);
-
- console.log("\nRESUME REVIEW RESULTS:");
- console.log(` Avg Latency: ${(resumeResults.avgLatency / 1000).toFixed(2)}s`);
- console.log(
- ` Range: ${(resumeResults.minLatency / 1000).toFixed(2)}s - ${(
- resumeResults.maxLatency / 1000
- ).toFixed(2)}s`
- );
- console.log(
- ` Avg Score: ${resumeResults.avgScore.toFixed(
- 1
- )} +/- ${resumeResults.scoreVariance.toFixed(1)}`
- );
- console.log(` Success Rate: ${resumeResults.successRate.toFixed(0)}%`);
-
- // Job Match Test
- console.log("\n\nJOB MATCH TEST");
- const jobResults = await runBenchmark("job-match", 3);
-
- console.log("\nJOB MATCH RESULTS:");
- console.log(` Avg Latency: ${(jobResults.avgLatency / 1000).toFixed(2)}s`);
- console.log(
- ` Range: ${(jobResults.minLatency / 1000).toFixed(2)}s - ${(
- jobResults.maxLatency / 1000
- ).toFixed(2)}s`
- );
- console.log(
- ` Avg Score: ${jobResults.avgScore.toFixed(
- 1
- )} +/- ${jobResults.scoreVariance.toFixed(1)}`
- );
- console.log(` Success Rate: ${jobResults.successRate.toFixed(0)}%`);
-
- // Summary
- console.log("\n" + "=".repeat(80));
- console.log("SUMMARY");
- console.log("=".repeat(80));
- console.log(
- `Average Latency: ${(
- (resumeResults.avgLatency + jobResults.avgLatency) /
- 2000
- ).toFixed(2)}s`
- );
- console.log(
- `Score Consistency: +/-${Math.max(
- resumeResults.scoreVariance,
- jobResults.scoreVariance
- ).toFixed(1)} points`
- );
- console.log("=".repeat(80));
-}
-
-// Wrap in describe block for Jest
-describe("Multi-Agent System Performance", () => {
- it("should complete resume review and job match successfully", async () => {
- await runPerformanceTests();
- }, 300000); // 5 minute timeout for comprehensive testing
-});
-
-// Run the benchmark
-if (require.main === module) {
- runPerformanceTests()
- .then(() => {
- console.log("\nBenchmark complete!");
- process.exit(0);
- })
- .catch((error) => {
- console.error("\nBenchmark failed:", error);
- process.exit(1);
- });
-}
-
-export { runTest, runBenchmark, runPerformanceTests };
diff --git a/scripts/test-semantic-extraction.ts b/scripts/test-semantic-extraction.ts
deleted file mode 100644
index 2eef122..0000000
--- a/scripts/test-semantic-extraction.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-/**
- * Test Script: Semantic Extraction Validation
- *
- * Purpose: Verify that semantic extraction produces consistent results
- * compared to legacy hard-coded matching
- *
- * Usage:
- * 1. Ensure Ollama is running: `ollama serve`
- * 2. Have llama3.2 model available: `ollama pull llama3.2`
- * 3. Run: `npx tsx scripts/test-semantic-extraction.ts`
- */
-
-import {
- extractKeywords,
- countActionVerbs,
- extractSemanticKeywords,
- analyzeActionVerbs,
- performSemanticSkillMatch,
-} from "../src/lib/ai/tools";
-
-const SAMPLE_RESUME = `
-JOHN DOE
-Senior Software Engineer
-
-PROFESSIONAL SUMMARY
-Full-stack developer with 7+ years building scalable web applications using React, Node.js, and AWS.
-
-EXPERIENCE
-Senior Software Engineer | TechCorp | 2020-Present
-• Led team of 8 engineers in migrating legacy monolith to microservices architecture
-• Architected CI/CD pipeline using Docker, Kubernetes, and GitHub Actions
-• Reduced deployment time by 60% and infrastructure costs by $200K annually
-• Implemented comprehensive test coverage (Jest, Cypress) achieving 85% coverage
-
-Software Engineer | StartupXYZ | 2017-2020
-• Developed React-based dashboard handling 1M+ daily active users
-• Built RESTful APIs using Node.js and PostgreSQL
-• Improved API response time by 40% through caching and optimization
-
-TECHNICAL SKILLS
-Languages: JavaScript, TypeScript, Python, SQL
-Frameworks: React, Node.js, Express, Next.js
-Tools: Docker, Kubernetes, AWS (EC2, S3, Lambda), Git, JIRA
-Methodologies: Agile, Scrum, TDD, CI/CD
-`;
-
-const SAMPLE_JOB = `
-Senior Full Stack Engineer
-
-Requirements:
-• 5+ years of professional software development experience
-• Expert knowledge of React and TypeScript
-• Strong experience with Node.js and Express
-• Experience with cloud platforms (AWS, GCP, or Azure)
-• Proficiency in Docker and Kubernetes
-• Experience with CI/CD pipelines
-• Strong understanding of microservices architecture
-• Experience with PostgreSQL or MySQL
-• Familiarity with Agile/Scrum methodologies
-
-Nice to Have:
-• GraphQL experience
-• Terraform or infrastructure as code
-• Redis or similar caching solutions
-• Experience with monitoring tools (Datadog, New Relic)
-`;
-
-async function testKeywordExtraction() {
- console.log("\\n" + "=".repeat(80));
- console.log("TEST 1: Keyword Extraction Comparison");
- console.log("=".repeat(80));
-
- // Legacy extraction
- console.log("\\n[Legacy] Hard-coded keyword matching:");
- const legacyKeywords = extractKeywords(SAMPLE_RESUME);
- console.log(` Total keywords found: ${legacyKeywords.count}`);
- console.log(
- ` Keywords: ${legacyKeywords.keywords.slice(0, 15).join(", ")}...`
- );
-
- // Semantic extraction
- console.log("\\n[Semantic] LLM-based extraction:");
- try {
- const semanticKeywords = await extractSemanticKeywords(
- SAMPLE_RESUME,
- "ollama",
- "llama3.2"
- );
- console.log(` Total keywords found: ${semanticKeywords.total_count}`);
- console.log(
- ` Technical skills: ${semanticKeywords.technical_skills
- .slice(0, 10)
- .join(", ")}`
- );
- console.log(
- ` Tools/Platforms: ${semanticKeywords.tools_platforms
- .slice(0, 10)
- .join(", ")}`
- );
- console.log(
- ` Methodologies: ${semanticKeywords.methodologies.join(", ")}`
- );
-
- // Compare counts
- const difference = Math.abs(
- semanticKeywords.total_count - legacyKeywords.count
- );
- const percentDiff = (difference / legacyKeywords.count) * 100;
- console.log(
- `\\n ✓ Difference: ${difference} keywords (${percentDiff.toFixed(1)}%)`
- );
-
- if (semanticKeywords.total_count > legacyKeywords.count) {
- console.log(
- ` ✓ Semantic found ${
- semanticKeywords.total_count - legacyKeywords.count
- } additional keywords`
- );
- }
- } catch (error) {
- console.error(` ✗ Semantic extraction failed:`, error);
- }
-}
-
-async function testActionVerbAnalysis() {
- console.log("\\n" + "=".repeat(80));
- console.log("TEST 2: Action Verb Analysis Comparison");
- console.log("=".repeat(80));
-
- // Legacy counting
- console.log("\\n[Legacy] Hard-coded verb matching:");
- const legacyVerbs = countActionVerbs(SAMPLE_RESUME);
- console.log(` Strong verbs found: ${legacyVerbs.count}`);
- console.log(` Verbs: ${legacyVerbs.verbs.join(", ")}`);
-
- // Semantic analysis
- console.log("\\n[Semantic] LLM-based analysis:");
- try {
- const semanticVerbs = await analyzeActionVerbs(
- SAMPLE_RESUME,
- "ollama",
- "llama3.2"
- );
- console.log(` Strong verbs found: ${semanticVerbs.strong_verbs.length}`);
- console.log(
- ` High impact verbs: ${semanticVerbs.strong_verbs
- .filter((v) => v.impact_level === "high")
- .map((v) => v.verb)
- .join(", ")}`
- );
- console.log(
- ` Medium impact verbs: ${semanticVerbs.strong_verbs
- .filter((v) => v.impact_level === "medium")
- .map((v) => v.verb)
- .join(", ")}`
- );
- console.log(
- ` Verb strength score: ${semanticVerbs.verb_strength_score}/10`
- );
-
- if (semanticVerbs.weak_verbs.length > 0) {
- console.log(
- `\\n Weak verbs detected: ${semanticVerbs.weak_verbs.length}`
- );
- semanticVerbs.weak_verbs.forEach((w) => {
- console.log(` - "${w.verb}" → suggest: "${w.suggestion}"`);
- });
- }
-
- console.log(
- `\\n ✓ Verb strength score: ${semanticVerbs.verb_strength_score}/10`
- );
- } catch (error) {
- console.error(` ✗ Semantic analysis failed:`, error);
- }
-}
-
-async function testSemanticSkillMatch() {
- console.log("\\n" + "=".repeat(80));
- console.log("TEST 3: Semantic Skill Matching");
- console.log("=".repeat(80));
-
- console.log("\\n[Semantic] Performing skill match analysis...");
- try {
- const skillMatch = await performSemanticSkillMatch(
- SAMPLE_RESUME,
- SAMPLE_JOB,
- "ollama",
- "llama3.2"
- );
-
- console.log(`\\n Overall match: ${skillMatch.overall_match_percentage}%`);
-
- console.log(`\\n Exact matches (${skillMatch.exact_matches.length}):`);
- skillMatch.exact_matches.slice(0, 5).forEach((match) => {
- console.log(` ✓ ${match.skill}`);
- });
-
- console.log(`\\n Related matches (${skillMatch.related_matches.length}):`);
- skillMatch.related_matches.forEach((match) => {
- console.log(
- ` ≈ ${match.job_skill} ↔ ${match.resume_skill} (${match.similarity}% similar)`
- );
- console.log(` Reason: ${match.explanation}`);
- });
-
- console.log(`\\n Missing skills (${skillMatch.missing_skills.length}):`);
- skillMatch.missing_skills.forEach((missing) => {
- const priority =
- missing.importance === "critical"
- ? "🔴"
- : missing.importance === "important"
- ? "🟡"
- : "🟢";
- console.log(
- ` ${priority} ${missing.skill} - ${missing.importance} (${missing.learnability} to learn)`
- );
- });
-
- console.log(
- `\\n ✓ Semantic matching provides ${skillMatch.related_matches.length} transferable skill insights`
- );
- } catch (error) {
- console.error(` ✗ Semantic matching failed:`, error);
- }
-}
-
-async function runAllTests() {
- console.log("\\n🚀 Starting Semantic Extraction Validation Tests");
- console.log("Prerequisites: Ollama must be running with llama3.2 model\\n");
-
- const startTime = Date.now();
-
- await testKeywordExtraction();
- await testActionVerbAnalysis();
- await testSemanticSkillMatch();
-
- const duration = ((Date.now() - startTime) / 1000).toFixed(1);
-
- console.log("\\n" + "=".repeat(80));
- console.log(`✅ All tests completed in ${duration}s`);
- console.log("=".repeat(80) + "\\n");
-
- console.log("Summary:");
- console.log(
- " • Semantic extraction provides more comprehensive keyword coverage"
- );
- console.log(
- " • Action verb analysis includes strength scoring and suggestions"
- );
- console.log(
- " • Skill matching understands transferable skills and similarity"
- );
- console.log(
- " • Results demonstrate improved accuracy over hard-coded matching"
- );
- console.log("\\nNext steps:");
- console.log(
- " 1. Enable feature flag: NEXT_PUBLIC_USE_SEMANTIC_EXTRACTION=true"
- );
- console.log(" 2. Test in UI with real resumes");
- console.log(" 3. Monitor performance and accuracy");
- console.log(" 4. Gradually roll out to users\\n");
-}
-
-// Run tests
-runAllTests().catch((error) => {
- console.error("\\n❌ Test suite failed:", error);
- process.exit(1);
-});
diff --git a/src/app/api/ai/resume/match-collaborative/route.ts b/src/app/api/ai/resume/match-collaborative/route.ts
deleted file mode 100644
index 52d0819..0000000
--- a/src/app/api/ai/resume/match-collaborative/route.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-import "server-only";
-
-import { auth } from "@/auth";
-import { NextRequest } from "next/server";
-import { checkRateLimit } from "@/lib/ai/rate-limiter";
-import { adaptiveJobMatch } from "@/lib/ai/adaptive-selector";
-import {
- ProgressStream,
- encodeProgressMessage,
- createProgressUpdate,
-} from "@/lib/ai/progress-stream";
-import { convertResumeToText, convertJobToText } from "@/utils/ai.utils";
-import { getResumeById } from "@/actions/profile.actions";
-import { getJobDetails } from "@/actions/job.actions";
-import { AiModel } from "@/models/ai.model";
-
-// Extend timeout for multi-agent collaboration (2 minutes)
-// Typical: ~18s, allowing 2min for safety
-export const maxDuration = 120;
-
-export const POST = async (req: NextRequest) => {
- const session = await auth();
- const userId = session?.accessToken?.sub;
-
- if (!session || !session.user || !userId) {
- return new Response(JSON.stringify({ message: "Not Authenticated" }), {
- status: 401,
- headers: { "Content-Type": "application/json" },
- });
- }
-
- // Rate limiting
- const rateLimit = checkRateLimit(userId);
- if (!rateLimit.allowed) {
- return new Response(
- JSON.stringify({
- error: `Rate limit exceeded. Try again in ${Math.ceil(
- rateLimit.resetIn / 1000
- )} seconds.`,
- }),
- { status: 429, headers: { "Content-Type": "application/json" } }
- );
- }
-
- const { selectedModel, resumeId, jobId } = (await req.json()) as {
- selectedModel: AiModel;
- resumeId: string;
- jobId: string;
- };
-
- if (!resumeId || !jobId || !selectedModel) {
- return new Response(
- JSON.stringify({ error: "Resume, job, and model selection required" }),
- { status: 400, headers: { "Content-Type": "application/json" } }
- );
- }
-
- try {
- const [resume, job] = await Promise.all([
- getResumeById(resumeId),
- getJobDetails(jobId),
- ]);
-
- if (!resume.success || !job.success) {
- throw new Error("Failed to fetch resume or job details");
- }
-
- const resumeText = await convertResumeToText(resume.data!);
- const jobText = await convertJobToText(job.job!);
-
- // Create a ReadableStream for SSE
- const stream = new ReadableStream({
- async start(controller) {
- const progressStream = new ProgressStream(controller);
-
- try {
- // Run collaborative analysis with progress updates
- const { analysis } = await adaptiveJobMatch(
- resumeText,
- jobText,
- selectedModel.provider,
- selectedModel.model || "llama3.2",
- progressStream
- );
-
- // Send completion and final result
- const completeUpdate = createProgressUpdate("complete", "completed");
- try {
- controller.enqueue(
- new TextEncoder().encode(encodeProgressMessage(completeUpdate))
- );
-
- // Send the final analysis as the last message
- const finalMessage = `data: ${JSON.stringify({
- type: "result",
- data: analysis,
- })}\n\n`;
- controller.enqueue(new TextEncoder().encode(finalMessage));
- } catch {
- // Controller may already be closed (client disconnected)
- }
-
- try {
- controller.close();
- } catch {
- // Already closed
- }
- } catch (error) {
- console.error("Collaborative job match error:", error);
- try {
- const errorMessage = `data: ${JSON.stringify({
- type: "error",
- message:
- error instanceof Error ? error.message : "Analysis failed",
- })}\n\n`;
- controller.enqueue(new TextEncoder().encode(errorMessage));
- controller.close();
- } catch {
- // Controller may already be closed
- }
- }
- },
- });
-
- return new Response(stream, {
- headers: {
- "Content-Type": "text/event-stream",
- "Cache-Control": "no-cache",
- Connection: "keep-alive",
- },
- });
- } catch (error) {
- console.error("Job match error:", error);
- const message =
- error instanceof Error ? error.message : "AI request failed";
-
- return new Response(JSON.stringify({ error: message }), {
- status: 500,
- headers: { "Content-Type": "application/json" },
- });
- }
-};
diff --git a/src/app/api/ai/resume/match/route.ts b/src/app/api/ai/resume/match/route.ts
index b0836b8..9fd3d2c 100644
--- a/src/app/api/ai/resume/match/route.ts
+++ b/src/app/api/ai/resume/match/route.ts
@@ -19,8 +19,7 @@ import { getJobDetails } from "@/actions/job.actions";
import { AiModel } from "@/models/ai.model";
/**
- * Single-Agent Job Match Endpoint
- * For multi-agent collaborative analysis, use /api/ai/resume/match-collaborative
+ * Job Match Endpoint
*/
export const POST = async (req: NextRequest) => {
const session = await auth();
diff --git a/src/app/api/ai/resume/review-collaborative/route.ts b/src/app/api/ai/resume/review-collaborative/route.ts
deleted file mode 100644
index e8ba754..0000000
--- a/src/app/api/ai/resume/review-collaborative/route.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import "server-only";
-
-import { auth } from "@/auth";
-import { NextRequest } from "next/server";
-import { checkRateLimit } from "@/lib/ai/rate-limiter";
-import { adaptiveResumeReview } from "@/lib/ai/adaptive-selector";
-import {
- ProgressStream,
- encodeProgressMessage,
- createProgressUpdate,
-} from "@/lib/ai/progress-stream";
-import { convertResumeToText } from "@/utils/ai.utils";
-import { Resume } from "@/models/profile.model";
-import { AiModel } from "@/models/ai.model";
-
-// Extend timeout for multi-agent collaboration (2 minutes)
-// Typical: ~18s, allowing 2min for safety
-export const maxDuration = 120;
-
-export const POST = async (req: NextRequest) => {
- const session = await auth();
- const userId = session?.accessToken?.sub;
-
- if (!session || !session.user || !userId) {
- return new Response(JSON.stringify({ message: "Not Authenticated" }), {
- status: 401,
- headers: { "Content-Type": "application/json" },
- });
- }
-
- // Rate limiting
- const rateLimit = checkRateLimit(userId);
- if (!rateLimit.allowed) {
- return new Response(
- JSON.stringify({
- error: `Rate limit exceeded. Try again in ${Math.ceil(
- rateLimit.resetIn / 1000
- )} seconds.`,
- }),
- { status: 429, headers: { "Content-Type": "application/json" } }
- );
- }
-
- const { selectedModel, resume } = (await req.json()) as {
- selectedModel: AiModel;
- resume: Resume;
- };
-
- if (!resume || !selectedModel) {
- return new Response(
- JSON.stringify({ error: "Resume and model selection required" }),
- { status: 400, headers: { "Content-Type": "application/json" } }
- );
- }
-
- try {
- const resumeText = await convertResumeToText(resume);
-
- // Create a ReadableStream for SSE
- const stream = new ReadableStream({
- async start(controller) {
- const progressStream = new ProgressStream(controller);
-
- try {
- // Run collaborative analysis with progress updates
- const { analysis } = await adaptiveResumeReview(
- resumeText,
- selectedModel.provider,
- selectedModel.model || "llama3.2",
- progressStream
- );
-
- // Send completion and final result
- const completeUpdate = createProgressUpdate("complete", "completed");
- try {
- controller.enqueue(
- new TextEncoder().encode(encodeProgressMessage(completeUpdate))
- );
-
- // Send the final analysis as the last message
- const finalMessage = `data: ${JSON.stringify({
- type: "result",
- data: analysis,
- })}\n\n`;
- controller.enqueue(new TextEncoder().encode(finalMessage));
- } catch {
- // Controller may already be closed (client disconnected)
- }
-
- try {
- controller.close();
- } catch {
- // Already closed
- }
- } catch (error) {
- console.error("Collaborative review error:", error);
- try {
- const errorMessage = `data: ${JSON.stringify({
- type: "error",
- message:
- error instanceof Error ? error.message : "Analysis failed",
- })}\n\n`;
- controller.enqueue(new TextEncoder().encode(errorMessage));
- controller.close();
- } catch {
- // Controller may already be closed
- }
- }
- },
- });
-
- return new Response(stream, {
- headers: {
- "Content-Type": "text/event-stream",
- "Cache-Control": "no-cache",
- Connection: "keep-alive",
- },
- });
- } catch (error) {
- console.error("Resume review error:", error);
- const message =
- error instanceof Error ? error.message : "AI request failed";
-
- return new Response(JSON.stringify({ error: message }), {
- status: 500,
- headers: { "Content-Type": "application/json" },
- });
- }
-};
diff --git a/src/app/api/ai/resume/review/route.ts b/src/app/api/ai/resume/review/route.ts
index d124e5c..b3960a3 100644
--- a/src/app/api/ai/resume/review/route.ts
+++ b/src/app/api/ai/resume/review/route.ts
@@ -22,8 +22,7 @@ import { Resume } from "@/models/profile.model";
import { AiModel } from "@/models/ai.model";
/**
- * Single-Agent Resume Review Endpoint
- * For multi-agent collaborative analysis, use /api/ai/resume/review-collaborative
+ * Resume Review Endpoint
*/
export const POST = async (req: NextRequest) => {
const session = await auth();
diff --git a/src/components/profile/AiJobMatchSection.tsx b/src/components/profile/AiJobMatchSection.tsx
index 8e8cca7..594687c 100644
--- a/src/components/profile/AiJobMatchSection.tsx
+++ b/src/components/profile/AiJobMatchSection.tsx
@@ -33,9 +33,6 @@ import {
import { Info, CheckCircle, XCircle } from "lucide-react";
import { checkIfModelIsRunning } from "@/utils/ai.utils";
import { JobMatchSchema } from "@/models/ai.schemas";
-import { useCollaborativeAnalysis } from "@/hooks/useCollaborativeAnalysis";
-import { MultiAgentProgress } from "./MultiAgentProgress";
-import { JobMatchResponse } from "@/models/ai.model";
interface AiSectionProps {
aISectionOpen: boolean;
@@ -51,7 +48,6 @@ export const AiJobMatchSection = ({
const [selectedResumeId, setSelectedResumeId] = useState<string>();
const [runningModelName, setRunningModelName] = useState<string>("");
const [runningModelError, setRunningModelError] = useState<string>("");
- const [useCollaboration, setUseCollaboration] = useState<boolean>(false);
const selectedModel: AiModel = getFromLocalStorage(
"aiSettings",
@@ -60,12 +56,7 @@ export const AiJobMatchSection = ({
const resumesRef = useRef<Resume[]>([]);
// Standard single-agent mode
- const {
- object,
- submit,
- isLoading: singleAgentLoading,
- stop,
- } = useObject({
+ const { object, submit, isLoading, stop } = useObject({
api: "/api/ai/resume/match",
schema: JobMatchSchema,
onError: (err) => {
@@ -77,18 +68,6 @@ export const AiJobMatchSection = ({
},
});
- // Multi-agent collaborative mode
- const {
- isLoading: multiAgentLoading,
- result: collaborativeResult,
- error: collaborativeError,
- start: startCollaborative,
- stop: stopCollaborative,
- } = useCollaborativeAnalysis<JobMatchResponse>("job-match");
-
- const isLoading = useCollaboration ? multiAgentLoading : singleAgentLoading;
- const displayObject = useCollaboration ? collaborativeResult : object;
-
const getResumes = async () => {
try {
const { data, success, message } = await getResumeList();
@@ -111,11 +90,7 @@ export const AiJobMatchSection = ({
};
const getJobMatch = (resumeId: string, jobId: string) => {
- if (useCollaboration) {
- startCollaborative({ resumeId, jobId, selectedModel });
- } else {
- submit({ resumeId, jobId, selectedModel });
- }
+ submit({ resumeId, jobId, selectedModel });
};
const checkModelStatus = useCallback(async () => {
@@ -135,11 +110,7 @@ export const AiJobMatchSection = ({
const onOpenChange = async (openState: boolean) => {
triggerChange(openState);
if (!openState && isLoading) {
- if (useCollaboration) {
- stopCollaborative();
- } else {
- stop();
- }
+ stop();
}
if (openState && selectedModel.provider === "ollama") {
await checkModelStatus();
@@ -167,9 +138,7 @@ export const AiJobMatchSection = ({
// Check if we have any content to show
const hasContent =
- displayObject &&
- (displayObject.matching_score !== undefined ||
- displayObject.detailed_analysis);
+ object && (object.matching_score !== undefined || object.detailed_analysis);
return (
<Sheet open={aISectionOpen} onOpenChange={onOpenChange}>
@@ -209,57 +178,6 @@ export const AiJobMatchSection = ({
</>
)}
- {/* Multi-Agent Mode Toggle */}
- <div className="mt-4 p-3 border rounded-lg bg-muted/50">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <label
- htmlFor="collaboration-mode"
- className="text-sm font-medium"
- >
- Multi-Agent Collaboration
- </label>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Info className="h-4 w-4 text-muted-foreground" />
- </TooltipTrigger>
- <TooltipContent className="max-w-xs">
- <p className="font-semibold mb-1">Multi-Agent System</p>
- <p className="text-xs mb-2">
- Uses 3 specialized AI agents working together:
- </p>
- <ul className="text-xs space-y-1">
- <li>• Tool Extraction (extracts metrics)</li>
- <li>• Data Analyzer (combines insights)</li>
- <li>• Feedback Expert (actionable advice)</li>
- </ul>
- <p className="text-xs mt-2 text-yellow-500">
- ⚠️ Slower but significantly more accurate
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- <input
- id="collaboration-mode"
- type="checkbox"
- checked={useCollaboration}
- onChange={(e) => setUseCollaboration(e.target.checked)}
- disabled={isLoading}
- className="h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary"
- />
- </div>
- {useCollaboration && (
- <p className="text-xs text-muted-foreground mt-2">
- 🤖 Multiple AI agents will analyze this job match together
- </p>
- )}
- </div>
-
- {/* Multi-Agent Progress Indicator */}
- <MultiAgentProgress isActive={useCollaboration && isLoading} />
-
{!selectedResumeId && (
<div className="mt-4">
<Select
@@ -294,20 +212,14 @@ export const AiJobMatchSection = ({
{isLoading && !hasContent ? (
<div className="flex items-center flex-col mt-4">
<Loading />
- <div className="mt-2">
- {useCollaboration
- ? "Agents collaborating..."
- : "Analyzing job match..."}
- </div>
+ <div className="mt-2">Analyzing job match...</div>
<div className="text-xs text-muted-foreground mt-1">
- {useCollaboration
- ? "Multiple agents are analyzing qualifications"
- : "Agent is comparing qualifications"}
+ Agent is comparing qualifications
</div>
</div>
) : (
<AiJobMatchResponseContent
- content={displayObject}
+ content={object}
isStreaming={isLoading}
/>
)}
diff --git a/src/components/profile/AiResumeReviewSection.tsx b/src/components/profile/AiResumeReviewSection.tsx
index 38b3d49..6b30d30 100644
--- a/src/components/profile/AiResumeReviewSection.tsx
+++ b/src/components/profile/AiResumeReviewSection.tsx
@@ -26,8 +26,6 @@ import {
} from "../ui/tooltip";
import { checkIfModelIsRunning } from "@/utils/ai.utils";
import { ResumeReviewSchema } from "@/models/ai.schemas";
-import { useCollaborativeAnalysis } from "@/hooks/useCollaborativeAnalysis";
-import { MultiAgentProgress } from "./MultiAgentProgress";
interface AiSectionProps {
resume: Resume;
@@ -37,7 +35,6 @@ const AiResumeReviewSection = ({ resume }: AiSectionProps) => {
const [aISectionOpen, setAiSectionOpen] = useState(false);
const [runningModelName, setRunningModelName] = useState<string>("");
const [runningModelError, setRunningModelError] = useState<string>("");
- const [useCollaboration, setUseCollaboration] = useState<boolean>(false);
const selectedModel: AiModel = getFromLocalStorage(
"aiSettings",
@@ -45,12 +42,7 @@ const AiResumeReviewSection = ({ resume }: AiSectionProps) => {
);
// Standard single-agent mode
- const {
- object,
- submit,
- isLoading: singleAgentLoading,
- stop,
- } = useObject({
+ const { object, submit, isLoading, stop } = useObject({
api: "/api/ai/resume/review",
schema: ResumeReviewSchema,
onError: (err) => {
@@ -62,18 +54,6 @@ const AiResumeReviewSection = ({ resume }: AiSectionProps) => {
},
});
- // Multi-agent collaborative mode
- const {
- isLoading: multiAgentLoading,
- result: collaborativeResult,
- error: collaborativeError,
- start: startCollaborative,
- stop: stopCollaborative,
- } = useCollaborativeAnalysis<ResumeReviewResponse>("resume-review");
-
- const isLoading = useCollaboration ? multiAgentLoading : singleAgentLoading;
- const displayObject = useCollaboration ? collaborativeResult : object;
-
const getResumeReview = () => {
if (!resume || resume.ResumeSections?.length === 0) {
toast({
@@ -84,21 +64,13 @@ const AiResumeReviewSection = ({ resume }: AiSectionProps) => {
return;
}
- if (useCollaboration) {
- startCollaborative({ selectedModel, resume });
- } else {
- submit({ selectedModel, resume });
- }
+ submit({ selectedModel, resume });
};
const triggerSheetChange = async (openState: boolean) => {
setAiSectionOpen(openState);
if (!openState && isLoading) {
- if (useCollaboration) {
- stopCollaborative();
- } else {
- stop();
- }
+ stop();
} else if (openState && selectedModel.provider === "ollama") {
await checkModelStatus();
}
@@ -119,9 +91,7 @@ const AiResumeReviewSection = ({ resume }: AiSectionProps) => {
};
// Check if we have any content to show
- const hasContent =
- displayObject &&
- (displayObject.score !== undefined || displayObject.summary);
+ const hasContent = object && (object.score !== undefined || object.summary);
return (
<Sheet open={aISectionOpen} onOpenChange={triggerSheetChange}>
@@ -177,58 +147,6 @@ const AiResumeReviewSection = ({ resume }: AiSectionProps) => {
</>
)}
- {/* Multi-Agent Mode Toggle */}
- <div className="mt-4 p-3 border rounded-lg bg-muted/50">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <label
- htmlFor="collaboration-mode-review"
- className="text-sm font-medium"
- >
- Multi-Agent Collaboration
- </label>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Info className="h-4 w-4 text-muted-foreground" />
- </TooltipTrigger>
- <TooltipContent className="max-w-xs">
- <p className="font-semibold mb-1">
- Consolidated Multi-Agent System
- </p>
- <p className="text-xs mb-2">
- Uses 2 specialized AI agents working together:
- </p>
- <ul className="text-xs space-y-1">
- <li>• Analysis Agent (data, keywords, scoring)</li>
- <li>• Feedback Agent (actionable recommendations)</li>
- </ul>
- <p className="text-xs mt-2 text-green-500">
- ✨ Slower but refined response
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- <input
- id="collaboration-mode-review"
- type="checkbox"
- checked={useCollaboration}
- onChange={(e) => setUseCollaboration(e.target.checked)}
- disabled={isLoading}
- className="h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary"
- />
- </div>
- {useCollaboration && (
- <p className="text-xs text-muted-foreground mt-2">
- 🤖 2 AI agents will analyze your resume together
- </p>
- )}
- </div>
-
- {/* Multi-Agent Progress Indicator */}
- <MultiAgentProgress isActive={useCollaboration && isLoading} />
-
<div className="mt-4">
<Button
size="sm"
@@ -250,15 +168,11 @@ const AiResumeReviewSection = ({ resume }: AiSectionProps) => {
{isLoading && !hasContent ? (
<div className="flex items-center flex-col mt-4">
<Loading />
- <div className="mt-2">
- {useCollaboration
- ? "2 agents analyzing..."
- : "Analyzing resume..."}
- </div>
+ <div className="mt-2">Analyzing resume...</div>
</div>
) : (
<AiResumeReviewResponseContent
- content={displayObject}
+ content={object}
isStreaming={isLoading}
/>
)}
diff --git a/src/components/profile/MultiAgentProgress.tsx b/src/components/profile/MultiAgentProgress.tsx
deleted file mode 100644
index 042978c..0000000
--- a/src/components/profile/MultiAgentProgress.tsx
+++ /dev/null
@@ -1,176 +0,0 @@
-"use client";
-
-import { useEffect, useState } from "react";
-import {
- AGENT_STEPS,
- type AgentStep,
- type ProgressUpdate,
-} from "@/lib/ai/progress-stream";
-import { AlertTriangle, CheckCircle2, Circle, Loader2 } from "lucide-react";
-import { cn } from "@/lib/utils";
-
-interface MultiAgentProgressProps {
- isActive: boolean;
-}
-
-// 2-agent system (3 steps total)
-const AGENT_ORDER: AgentStep[] = [
- "tool-extraction",
- "analysis-agent",
- "feedback-agent",
-];
-
-export function MultiAgentProgress({ isActive }: MultiAgentProgressProps) {
- const [currentSteps, setCurrentSteps] = useState<Set<AgentStep>>(new Set());
- const [completedSteps, setCompletedSteps] = useState<Set<AgentStep>>(
- new Set()
- );
- const [warningMessage, setWarningMessage] = useState<string | null>(null);
-
- useEffect(() => {
- if (!isActive) {
- setCurrentSteps(new Set());
- setCompletedSteps(new Set());
- setWarningMessage(null);
- }
- }, [isActive]);
-
- // Expose a method to update progress (will be called from parent)
- useEffect(() => {
- const handleProgress = (update: ProgressUpdate) => {
- if (update.status === "started") {
- setCurrentSteps((prev) => new Set([...prev, update.step]));
- } else if (update.status === "completed") {
- setCurrentSteps((prev) => {
- const next = new Set(prev);
- next.delete(update.step);
- return next;
- });
- setCompletedSteps((prev) => new Set([...prev, update.step]));
- if (update.step === "complete") {
- setCurrentSteps(new Set());
- }
- } else if (update.status === "warning" && update.warningMessage) {
- setWarningMessage(update.warningMessage);
- }
- };
-
- // Listen for custom progress events
- window.addEventListener(
- "multiagent-progress" as any,
- ((e: CustomEvent<ProgressUpdate>) => {
- handleProgress(e.detail);
- }) as EventListener
- );
-
- return () => {
- window.removeEventListener(
- "multiagent-progress" as any,
- (() => {}) as EventListener
- );
- };
- }, []);
-
- if (!isActive) {
- return null;
- }
-
- return (
- <div className="mt-4 p-4 border rounded-lg bg-muted/30">
- <div className="flex items-center gap-2 mb-3">
- <Loader2 className="h-4 w-4 animate-spin text-primary" />
- <h4 className="text-sm font-semibold">
- Multi-Agent Analysis in Progress
- </h4>
- </div>
-
- <div className="space-y-2">
- {AGENT_ORDER.map((step, index) => {
- const stepInfo = AGENT_STEPS[step];
- const isCompleted = completedSteps.has(step);
- const isCurrent = currentSteps.has(step);
- const isPending = !isCompleted && !isCurrent;
-
- return (
- <div
- key={step}
- className={cn(
- "flex items-start gap-3 p-2 rounded-md transition-colors",
- isCurrent && "bg-primary/10",
- isCompleted && "opacity-60"
- )}
- >
- <div className="flex-shrink-0 mt-0.5">
- {isCompleted && (
- <CheckCircle2 className="h-4 w-4 text-green-600" />
- )}
- {isCurrent && (
- <Loader2 className="h-4 w-4 animate-spin text-primary" />
- )}
- {isPending && (
- <Circle className="h-4 w-4 text-muted-foreground" />
- )}
- </div>
-
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="text-lg">{stepInfo.emoji}</span>
- <span
- className={cn(
- "text-sm font-medium",
- isCurrent && "text-primary",
- isCompleted && "text-muted-foreground"
- )}
- >
- {stepInfo.name}
- </span>
- <span className="text-xs text-muted-foreground">
- ({index + 1}/{AGENT_ORDER.length})
- </span>
- </div>
- <p
- className={cn(
- "text-xs mt-0.5",
- isCurrent ? "text-foreground" : "text-muted-foreground"
- )}
- >
- {stepInfo.description}
- </p>
- </div>
- </div>
- );
- })}
- </div>
-
- {warningMessage && (
- <div className="mt-3 p-2 rounded-md bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800">
- <div className="flex items-center gap-2">
- <AlertTriangle className="h-4 w-4 text-amber-600 dark:text-amber-500 flex-shrink-0" />
- <p className="text-xs text-amber-700 dark:text-amber-400">
- {warningMessage}
- </p>
- </div>
- </div>
- )}
-
- {completedSteps.size > 0 && currentSteps.size > 0 && (
- <div className="mt-3 pt-3 border-t">
- <div className="flex items-center justify-between text-xs text-muted-foreground">
- <span>Progress:</span>
- <span className="font-medium">
- {completedSteps.size} of {AGENT_ORDER.length} agents completed
- </span>
- </div>
- <div className="mt-1 h-1.5 bg-muted rounded-full overflow-hidden">
- <div
- className="h-full bg-primary transition-all duration-300"
- style={{
- width: `${(completedSteps.size / AGENT_ORDER.length) * 100}%`,
- }}
- />
- </div>
- </div>
- )}
- </div>
- );
-}
diff --git a/src/hooks/useCollaborativeAnalysis.ts b/src/hooks/useCollaborativeAnalysis.ts
deleted file mode 100644
index 6e13f72..0000000
--- a/src/hooks/useCollaborativeAnalysis.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-"use client";
-
-import { useState, useCallback, useRef } from "react";
-import { ProgressUpdate } from "@/lib/ai/progress-stream";
-import { ResumeReviewResponse, JobMatchResponse } from "@/models/ai.model";
-
-type AnalysisType = "resume-review" | "job-match";
-
-// Default timeout for collaborative analysis (2 minutes)
-const DEFAULT_TIMEOUT_MS = 120000;
-
-export function useCollaborativeAnalysis<
- T extends ResumeReviewResponse | JobMatchResponse
->(type: AnalysisType, options?: { timeoutMs?: number }) {
- const [isLoading, setIsLoading] = useState(false);
- const [result, setResult] = useState<T | null>(null);
- const [error, setError] = useState<string | null>(null);
- const [timedOut, setTimedOut] = useState(false);
-
- const abortControllerRef = useRef<AbortController | null>(null);
- const timeoutIdRef = useRef<NodeJS.Timeout | null>(null);
-
- const emitProgress = useCallback((update: ProgressUpdate) => {
- const event = new CustomEvent("multiagent-progress", { detail: update });
- window.dispatchEvent(event);
- }, []);
-
- const cleanup = useCallback(() => {
- if (timeoutIdRef.current) {
- clearTimeout(timeoutIdRef.current);
- timeoutIdRef.current = null;
- }
- if (abortControllerRef.current) {
- abortControllerRef.current = null;
- }
- }, []);
-
- const start = useCallback(
- async (payload: unknown) => {
- // Clean up any previous request
- cleanup();
-
- setIsLoading(true);
- setError(null);
- setResult(null);
- setTimedOut(false);
-
- // Create new AbortController for this request
- abortControllerRef.current = new AbortController();
- const { signal } = abortControllerRef.current;
-
- // Set up timeout
- const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
- timeoutIdRef.current = setTimeout(() => {
- if (abortControllerRef.current) {
- abortControllerRef.current.abort();
- setTimedOut(true);
- setError(
- `Analysis timed out after ${Math.round(timeoutMs / 1000)} seconds`
- );
- setIsLoading(false);
- }
- }, timeoutMs);
-
- const endpoint =
- type === "resume-review"
- ? "/api/ai/resume/review-collaborative"
- : "/api/ai/resume/match-collaborative";
-
- try {
- const response = await fetch(endpoint, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(payload),
- signal,
- });
-
- if (!response.ok) {
- const errorData = await response.json();
- throw new Error(errorData.error || "Request failed");
- }
-
- if (!response.body) {
- throw new Error("No response body");
- }
-
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
-
- while (true) {
- const { done, value } = await reader.read();
-
- if (done) {
- break;
- }
-
- const chunk = decoder.decode(value);
- const lines = chunk.split("\n\n").filter((line) => line.trim());
-
- for (const line of lines) {
- if (line.startsWith("data: ")) {
- try {
- const data = JSON.parse(line.substring(6));
-
- if (data.type === "error") {
- setError(data.message);
- setIsLoading(false);
- cleanup();
- return;
- }
-
- if (data.type === "result") {
- setResult(data.data as T);
- setIsLoading(false);
- cleanup();
- return;
- }
-
- // It's a progress update
- if (data.step) {
- emitProgress(data as ProgressUpdate);
- }
- } catch {
- // Skip malformed JSON lines
- console.warn("Malformed SSE data:", line);
- }
- }
- }
- }
-
- // Stream ended without explicit result
- setIsLoading(false);
- cleanup();
- } catch (err) {
- // Ignore abort errors (user cancellation or timeout)
- if (err instanceof Error && err.name === "AbortError") {
- if (!timedOut) {
- setError("Analysis was cancelled");
- }
- setIsLoading(false);
- cleanup();
- return;
- }
-
- const message = err instanceof Error ? err.message : "Analysis failed";
- setError(message);
- setIsLoading(false);
- cleanup();
- }
- },
- [type, emitProgress, cleanup, options?.timeoutMs, timedOut]
- );
-
- const stop = useCallback(() => {
- if (abortControllerRef.current) {
- abortControllerRef.current.abort();
- }
- cleanup();
- setIsLoading(false);
- }, [cleanup]);
-
- return {
- isLoading,
- result,
- error,
- timedOut,
- start,
- stop,
- };
-}
diff --git a/src/lib/ai/adaptive-selector.ts b/src/lib/ai/adaptive-selector.ts
deleted file mode 100644
index 1ded52a..0000000
--- a/src/lib/ai/adaptive-selector.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-/**
- * Multi-Agent Analysis Functions
- *
- * Architecture:
- * - Analysis Agent: Data analysis, keyword optimization, and scoring
- * - Feedback Agent: Actionable recommendations with synthesis
- */
-
-import { ProviderType } from "./providers";
-import { ProgressStream } from "./progress-stream";
-import {
- multiAgentResumeReview,
- multiAgentJobMatch,
-} from "./multi-agent";
-import {
- ResumeReviewResponse,
- JobMatchResponse,
- CollaborativeResult,
-} from "@/models/ai.model";
-
-/**
- * Resume review using multi-agent system
- *
- * @param resumeText - The resume content to review
- * @param provider - AI provider to use
- * @param modelName - Model name for the provider
- * @param progressStream - Optional progress stream for real-time updates
- * @returns Resume review analysis
- */
-export async function adaptiveResumeReview(
- resumeText: string,
- provider: ProviderType,
- modelName: string,
- progressStream?: ProgressStream
-): Promise<CollaborativeResult<ResumeReviewResponse>> {
- console.log("[Multi-Agent] Running resume review");
- return multiAgentResumeReview(
- resumeText,
- provider,
- modelName,
- progressStream
- );
-}
-
-/**
- * Job match analysis using multi-agent system
- *
- * @param resumeText - The resume content
- * @param jobDescription - The job description
- * @param provider - AI provider to use
- * @param modelName - Model name for the provider
- * @param progressStream - Optional progress stream for real-time updates
- * @returns Job match analysis
- */
-export async function adaptiveJobMatch(
- resumeText: string,
- jobDescription: string,
- provider: ProviderType,
- modelName: string,
- progressStream?: ProgressStream
-): Promise<CollaborativeResult<JobMatchResponse>> {
- console.log("[Multi-Agent] Running job match");
- return multiAgentJobMatch(
- resumeText,
- jobDescription,
- provider,
- modelName,
- progressStream
- );
-}
-
-/**
- * Get information about the multi-agent system
- */
-export function getSystemInfo(): {
- agentCount: number;
- description: string;
- estimatedLatency: string;
-} {
- return {
- agentCount: 2,
- description: "Multi-Agent System (Analysis + Feedback)",
- estimatedLatency: "15-20s",
- };
-}
diff --git a/src/lib/ai/index.ts b/src/lib/ai/index.ts
index e65da88..4c8fb48 100644
--- a/src/lib/ai/index.ts
+++ b/src/lib/ai/index.ts
@@ -15,29 +15,6 @@ export {
buildJobMatchPrompt,
} from "./prompts";
-// Multi-agent system
-export {
- multiAgentResumeReview,
- multiAgentJobMatch,
-} from "./multi-agent";
-export type { AgentInsights, CollaborativeResult } from "@/models/ai.model";
-
-// Multi-agent wrapper functions
-export {
- adaptiveResumeReview,
- adaptiveJobMatch,
- getSystemInfo,
-} from "./adaptive-selector";
-
-// Progress streaming
-export type { ProgressUpdate, AgentStep } from "./progress-stream";
-export {
- AGENT_STEPS,
- createProgressUpdate,
- encodeProgressMessage,
- ProgressStream,
-} from "./progress-stream";
-
// Analysis tools
export {
countQuantifiedAchievements,
diff --git a/src/lib/ai/multi-agent/index.ts b/src/lib/ai/multi-agent/index.ts
deleted file mode 100644
index b118e2f..0000000
--- a/src/lib/ai/multi-agent/index.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * 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/index.ts b/src/lib/ai/multi-agent/job-match/index.ts
deleted file mode 100644
index c4af0b8..0000000
--- a/src/lib/ai/multi-agent/job-match/index.ts
+++ /dev/null
@@ -1,376 +0,0 @@
-/**
- * Multi-Agent Job Match
- *
- * Handles job matching analysis using the multi-agent collaboration system.
- */
-
-import { getModel, ProviderType } from "../../providers";
-import { AnalysisAgentSchema, FeedbackAgentSchema } from "@/models/ai.schemas";
-import {
- ANALYSIS_AGENT_PROMPT,
- FEEDBACK_AGENT_PROMPT,
-} from "../../prompts/resume-review";
-
-import {
- performSemanticSkillMatch,
- calculateSemanticSimilarity,
- generateMatchExplanation,
-} from "../../tools";
-import { ProgressStream } from "../../progress-stream";
-import {
- calculateJobMatchScore,
- validateScore,
- calculateAllowedVariance,
-} from "../../scoring";
-import {
- JobMatchResponse,
- AgentInsights,
- CollaborativeResult,
- ToolDataJobMatch,
- SemanticData,
-} from "@/models/ai.model";
-import { TEMPERATURES } from "../../config";
-import {
- isOllamaProvider,
- SEMANTIC_TIMEOUT_MS,
- OllamaAnalysisAgentSchema,
- OllamaFeedbackAgentSchema,
- OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT,
- OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT,
- buildOllamaJobMatchAnalysisPrompt,
- buildOllamaJobMatchFeedbackPrompt,
-} from "../../ollama";
-import { withTimeout } from "../utils";
-import {
- executeAgents,
- handleExtractionError,
- handleAgentError,
-} from "../shared";
-import { buildJobMatchResponse } from "./response-builder";
-
-// 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
-
- progressStream?.sendStarted("tool-extraction", 0);
-
- let toolData: ToolDataJobMatch;
- let semanticData: SemanticData = {
- skillMatch: null,
- similarity: null,
- matchExplanation: null,
- };
-
- try {
- 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"
- ),
- ]);
-
- 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);
-
- semanticData = {
- skillMatch: semanticMatch,
- similarity: semanticSimilarity,
- matchExplanation,
- };
-
- toolData = {
- keywordOverlap: {
- overlapPercentage: semanticSimilarity.similarity_score,
- 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) {
- 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,
- toolData.keywordOverlap.totalJobKeywords
- );
-
- const baselineScore = calculateJobMatchScore({
- keywordOverlapPercent: toolData.keywordOverlap.overlapPercentage,
- matchedSkillsCount,
- requiredSkillsCount,
- experienceYears: 0,
- requiredYears: 0,
- });
-
- 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);
-
- const analysisPrompt = isOllama
- ? buildOllamaJobMatchAnalysisPrompt(
- resumeText,
- jobDescription,
- toolData,
- baselineScore,
- minScore,
- maxScore
- )
- : 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: TEMPERATURES.ANALYSIS,
- },
- feedback: {
- schema: isOllama ? OllamaFeedbackAgentSchema : FeedbackAgentSchema,
- systemPrompt: isOllama
- ? OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT
- : FEEDBACK_AGENT_PROMPT,
- prompt: feedbackPrompt,
- temperature: TEMPERATURES.FEEDBACK,
- },
- });
-
- 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}
-
-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.`;
-}
-
-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}
-
-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`;
-}
diff --git a/src/lib/ai/multi-agent/job-match/response-builder.ts b/src/lib/ai/multi-agent/job-match/response-builder.ts
deleted file mode 100644
index 02c5563..0000000
--- a/src/lib/ai/multi-agent/job-match/response-builder.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-/**
- * Job Match Response Builder
- *
- * Handles building the final JobMatchResponse from agent results and semantic data.
- */
-
-import {
- JobMatchResponse,
- ToolDataJobMatch,
- SemanticData,
-} from "@/models/ai.model";
-
-interface AnalysisResultInput {
- keywordAnalysis: { strength: string; missingCritical: string[] };
-}
-
-interface FeedbackResultInput {
- suggestions: string[];
- synthesisNotes: string;
-}
-
-interface BaselineScore {
- score: number;
- breakdown: Record<string, number>;
-}
-
-export function buildJobMatchResponse(
- validatedScore: number,
- baselineScore: BaselineScore,
- toolData: ToolDataJobMatch,
- semanticData: SemanticData,
- analysisResult: AnalysisResultInput,
- feedbackResult: FeedbackResultInput,
- matchedSkillsCount: number,
- requiredSkillsCount: number
-): JobMatchResponse {
- 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: { skill: string; resume_evidence: string }) =>
- `✅ ${m.skill}: "${m.resume_evidence.substring(0, 40)}..."`
- ),
- ...semanticData.skillMatch.related_matches
- .slice(0, 2)
- .map(
- (m: {
- resume_skill: string;
- job_skill: string;
- similarity: number;
- }) =>
- `⚡ ${m.resume_skill} → ${m.job_skill} (${m.similarity}% similar)`
- ),
- ...semanticData.skillMatch.missing_skills
- .filter((s: any) => s.importance === "critical")
- .slice(0, 2)
- .map(
- (s: any) => `❌ ${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
-
- 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
- if (
- semanticData.similarity &&
- semanticData.similarity.transferable_skills.length > 0
- ) {
- detailedAnalysis.push({
- category: "Transferable Skills",
- value: semanticData.similarity.transferable_skills
- .slice(0, 3)
- .map(
- (s: any) =>
- `💡 ${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");
-
- return {
- 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}`,
- ],
- };
-}
diff --git a/src/lib/ai/multi-agent/resume-review/index.ts b/src/lib/ai/multi-agent/resume-review/index.ts
deleted file mode 100644
index 3a8b321..0000000
--- a/src/lib/ai/multi-agent/resume-review/index.ts
+++ /dev/null
@@ -1,307 +0,0 @@
-/**
- * Multi-Agent Resume Review
- *
- * Handles resume analysis using the multi-agent collaboration system.
- */
-
-import { getModel, ProviderType } from "../../providers";
-import { AnalysisAgentSchema, FeedbackAgentSchema } from "@/models/ai.schemas";
-import {
- ANALYSIS_AGENT_PROMPT,
- FEEDBACK_AGENT_PROMPT,
-} from "../../prompts/resume-review";
-import {
- countQuantifiedAchievements,
- analyzeFormatting,
- extractSemanticKeywords,
- analyzeActionVerbs,
- getKeywordCountFromSemantic,
- getVerbCountFromSemantic,
-} from "../../tools";
-import { ProgressStream } from "../../progress-stream";
-import {
- calculateResumeScore,
- validateScore,
- calculateAllowedVariance,
-} from "../../scoring";
-import {
- ResumeReviewResponse,
- AgentInsights,
- CollaborativeResult,
- ToolDataResume,
-} from "@/models/ai.model";
-import { TEMPERATURES } from "../../config";
-import {
- isOllamaProvider,
- SEMANTIC_TIMEOUT_MS,
- OllamaAnalysisAgentSchema,
- OllamaFeedbackAgentSchema,
- OLLAMA_ANALYSIS_SYSTEM_PROMPT,
- OLLAMA_FEEDBACK_SYSTEM_PROMPT,
- buildOllamaResumeAnalysisPrompt,
- buildOllamaResumeFeedbackPrompt,
-} from "../../ollama";
-import { withTimeout } from "../utils";
-import {
- executeAgents,
- handleExtractionError,
- handleAgentError,
-} from "../shared";
-import { buildResumeReviewResponse } from "./response-builder";
-
-// 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 -
-
- progressStream?.sendStarted("tool-extraction", 0);
-
- let toolData: ToolDataResume;
-
- try {
- 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) {
- handleExtractionError(error, progressStream, "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
-
- progressStream?.sendStarted("analysis-agent", 1);
- progressStream?.sendStarted("feedback-agent", 2);
-
- const isOllama = isOllamaProvider(provider);
-
- const analysisPrompt = isOllama
- ? buildOllamaResumeAnalysisPrompt(
- resumeText,
- toolData,
- baselineScore,
- minScore,
- maxScore
- )
- : buildFullResumeAnalysisPrompt(
- resumeText,
- toolData,
- baselineScore,
- minScore,
- maxScore
- );
-
- const feedbackPrompt = isOllama
- ? buildOllamaResumeFeedbackPrompt(resumeText, baselineScore)
- : buildFullResumeFeedbackPrompt(
- resumeText,
- baselineScore,
- minScore,
- maxScore
- );
-
- let analysisResult;
- let feedbackResult;
-
- try {
- const result = await executeAgents({
- model,
- provider,
- analysis: {
- schema: isOllama ? OllamaAnalysisAgentSchema : AnalysisAgentSchema,
- systemPrompt: isOllama
- ? OLLAMA_ANALYSIS_SYSTEM_PROMPT
- : ANALYSIS_AGENT_PROMPT,
- prompt: analysisPrompt,
- temperature: TEMPERATURES.ANALYSIS,
- },
- feedback: {
- schema: isOllama ? OllamaFeedbackAgentSchema : FeedbackAgentSchema,
- systemPrompt: isOllama
- ? OLLAMA_FEEDBACK_SYSTEM_PROMPT
- : FEEDBACK_AGENT_PROMPT,
- prompt: feedbackPrompt,
- temperature: TEMPERATURES.FEEDBACK,
- },
- verbCount: toolData.verbs.count,
- });
-
- analysisResult = result.analysisResult;
- feedbackResult = result.feedbackResult;
- } catch (error) {
- handleAgentError(error, progressStream, "resume analysis");
- }
-
- 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 = buildResumeReviewResponse(
- validatedScore,
- feedbackResult
- );
-
- const agentInsights: AgentInsights = {
- analysis: analysisResult,
- feedback: feedbackResult,
- };
-
- return {
- analysis: finalResponse,
- agentInsights,
- baselineScore,
- 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/resume-review/response-builder.ts b/src/lib/ai/multi-agent/resume-review/response-builder.ts
deleted file mode 100644
index 9c235e9..0000000
--- a/src/lib/ai/multi-agent/resume-review/response-builder.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Resume Review Response Builder
- *
- * Handles building the final ResumeReviewResponse from agent results.
- */
-
-import { ResumeReviewResponse } from "@/models/ai.model";
-
-interface FeedbackResultInput {
- strengths: string[];
- weaknesses: string[];
- suggestions: string[];
-}
-
-export function buildResumeReviewResponse(
- validatedScore: number,
- feedbackResult: FeedbackResultInput
-): ResumeReviewResponse {
- const scoreCategory =
- validatedScore >= 70
- ? "above average"
- : validatedScore >= 50
- ? "average"
- : "below average";
-
- const summary = `This resume scores ${validatedScore}/100, which is ${scoreCategory}. ${
- feedbackResult.strengths[0] || "Multiple strengths identified."
- }`;
-
- return {
- score: validatedScore,
- summary,
- strengths: feedbackResult.strengths,
- weaknesses: feedbackResult.weaknesses,
- suggestions: feedbackResult.suggestions,
- };
-}
diff --git a/src/lib/ai/multi-agent/shared/agent-executor.ts b/src/lib/ai/multi-agent/shared/agent-executor.ts
deleted file mode 100644
index 5e84ef3..0000000
--- a/src/lib/ai/multi-agent/shared/agent-executor.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-/**
- * Generic Agent Executor
- *
- * Handles parallel execution of Analysis and Feedback agents with:
- * - Provider-aware schema selection
- * - Timeout and retry logic
- * - Ollama result normalization
- */
-
-import { generateText, Output } 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 { output } = await generateText({
- model,
- output: Output.object({ schema: analysis.schema }),
- system: analysis.systemPrompt,
- prompt: analysis.prompt,
- temperature: analysis.temperature,
- });
- return output;
- }, "Analysis Agent"),
- AGENT_TIMEOUT_MS,
- "Analysis Agent"
- ),
-
- withTimeout(
- runWithRetry(async () => {
- const { output } = await generateText({
- model,
- output: Output.object({ schema: feedback.schema }),
- system: feedback.systemPrompt,
- prompt: feedback.prompt,
- temperature: feedback.temperature,
- });
- return output;
- }, "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
deleted file mode 100644
index 21b5404..0000000
--- a/src/lib/ai/multi-agent/shared/error-handler.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * 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
deleted file mode 100644
index f20298b..0000000
--- a/src/lib/ai/multi-agent/shared/index.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-/**
- * 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/lib/ai/multi-agent/utils.ts b/src/lib/ai/multi-agent/utils.ts
deleted file mode 100644
index 993c4c2..0000000
--- a/src/lib/ai/multi-agent/utils.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * Multi-Agent Shared Utilities
- *
- * Common utilities used by both resume review and job match agents.
- */
-
-import { RETRY } from "../config";
-
-// RETRY MECHANISM
-
-export async function runWithRetry<T>(
- operation: () => Promise<T>,
- operationName: string,
- maxRetries: number = RETRY.MAX_ATTEMPTS
-): 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 =
- RETRY.BASE_DELAY_MS * Math.pow(RETRY.BACKOFF_MULTIPLIER, attempt);
- await new Promise((resolve) => setTimeout(resolve, delay));
- }
- }
- }
-
- throw new Error(
- `${operationName} failed after ${maxRetries + 1} attempts: ${
- lastError.message
- }`
- );
-}
-
-// TIMEOUT WRAPPER
-
-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.ts
index cccdb99..6b3535e 100644
--- a/src/lib/ai/ollama/index.ts
+++ b/src/lib/ai/ollama/index.ts
@@ -2,16 +2,12 @@
* 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
*/
import type { ProviderType } from "../providers";
-import {
- SEMANTIC_TIMEOUT_MS,
- AGENT_TIMEOUT_MS,
-} from "../config";
+import { SEMANTIC_TIMEOUT_MS, AGENT_TIMEOUT_MS } from "../config";
// Re-export timeouts for backward compatibility
export { SEMANTIC_TIMEOUT_MS, AGENT_TIMEOUT_MS };
@@ -29,34 +25,16 @@ export {
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.ts
index 4481b01..49bb28f 100644
--- a/src/lib/ai/ollama/normalizers.ts
+++ b/src/lib/ai/ollama/normalizers.ts
@@ -10,8 +10,6 @@ import type {
OllamaActionVerbAnalysis,
OllamaSkillMatch,
OllamaSemanticSimilarity,
- OllamaAnalysisAgent,
- OllamaFeedbackAgent,
} from "@/models/ai.ollama-schemas";
import type {
SemanticKeywordExtraction,
@@ -19,7 +17,6 @@ import type {
SemanticSkillMatch,
SemanticSimilarityResult,
} from "@/models/ai.schemas";
-import type { AnalysisResult, FeedbackResult } from "@/models/ai.model";
/**
* Normalize Ollama keyword extraction to full schema format
@@ -105,43 +102,3 @@ export function normalizeSemanticSimilarity(
: "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/progress-stream.ts b/src/lib/ai/progress-stream.ts
deleted file mode 100644
index 5195717..0000000
--- a/src/lib/ai/progress-stream.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-/**
- * Progress Streaming for Multi-Agent Collaboration
- * Sends real-time updates to the client about which agent is working
- */
-
-export type AgentStep =
- | "tool-extraction"
- | "analysis-agent"
- | "feedback-agent"
- | "complete";
-
-export interface ProgressUpdate {
- step: AgentStep;
- status: "started" | "completed" | "warning";
- message: string;
- timestamp: number;
- agentNumber?: number;
- totalAgents?: number;
- /** Start time of this step (for timeout tracking on client) */
- startTime?: number;
- /** Estimated duration in milliseconds for this step */
- estimatedDurationMs?: number;
- /** User-friendly warning message when something goes wrong */
- warningMessage?: string;
-}
-
-// Estimated durations for each agent step (in milliseconds)
-const ESTIMATED_DURATIONS: Record<AgentStep, number> = {
- "tool-extraction": 3000,
- "analysis-agent": 12000,
- "feedback-agent": 10000,
- complete: 0,
-};
-
-export const AGENT_STEPS: Record<
- AgentStep,
- {
- name: string;
- description: string;
- emoji: string;
- estimatedDurationMs: number;
- }
-> = {
- "tool-extraction": {
- name: "Tool Extraction",
- description: "Extracting objective metrics and keywords",
- emoji: "🔧",
- estimatedDurationMs: ESTIMATED_DURATIONS["tool-extraction"],
- },
- "analysis-agent": {
- name: "Analysis Agent",
- description: "Comprehensive analysis with scoring",
- emoji: "🧠",
- estimatedDurationMs: ESTIMATED_DURATIONS["analysis-agent"],
- },
- "feedback-agent": {
- name: "Feedback Agent",
- description: "Generating actionable recommendations",
- emoji: "💬",
- estimatedDurationMs: ESTIMATED_DURATIONS["feedback-agent"],
- },
- complete: {
- name: "Complete",
- description: "Analysis ready",
- emoji: "🎉",
- estimatedDurationMs: ESTIMATED_DURATIONS["complete"],
- },
-};
-
-/**
- * Creates a progress update message with timing information
- */
-export function createProgressUpdate(
- step: AgentStep,
- status: "started" | "completed",
- agentNumber?: number,
- totalAgents: number = 3
-): ProgressUpdate {
- const stepInfo = AGENT_STEPS[step];
- const now = Date.now();
- const message =
- status === "started"
- ? `${stepInfo.emoji} ${stepInfo.name}: ${stepInfo.description}...`
- : `${stepInfo.emoji} ${stepInfo.name} completed`;
-
- return {
- step,
- status,
- message,
- timestamp: now,
- agentNumber,
- totalAgents,
- // Include start time for timeout tracking on the client
- startTime: status === "started" ? now : undefined,
- // Include estimated duration so client can show progress/warning
- estimatedDurationMs:
- status === "started" ? stepInfo.estimatedDurationMs : undefined,
- };
-}
-
-/**
- * Encodes progress update as SSE message
- */
-export function encodeProgressMessage(update: ProgressUpdate): string {
- return `data: ${JSON.stringify(update)}\n\n`;
-}
-
-/**
- * Helper to send progress through a stream controller
- */
-export class ProgressStream {
- private controller:
- | ReadableStreamDefaultController
- | TransformStreamDefaultController
- | null = null;
-
- constructor(
- controller?:
- | ReadableStreamDefaultController
- | TransformStreamDefaultController
- ) {
- this.controller = controller || null;
- }
-
- setController(
- controller:
- | ReadableStreamDefaultController
- | TransformStreamDefaultController
- ) {
- this.controller = controller;
- }
-
- sendProgress(
- step: AgentStep,
- status: "started" | "completed",
- agentNumber?: number
- ) {
- if (!this.controller) return;
-
- try {
- const update = createProgressUpdate(step, status, agentNumber);
- const message = encodeProgressMessage(update);
- this.controller.enqueue(new TextEncoder().encode(message));
- } catch {
- // Controller may be closed (client disconnected, timeout, etc.)
- // Silently ignore as this is expected when the stream ends
- }
- }
-
- sendStarted(step: AgentStep, agentNumber?: number) {
- this.sendProgress(step, "started", agentNumber);
- }
-
- sendCompleted(step: AgentStep, agentNumber?: number) {
- this.sendProgress(step, "completed", agentNumber);
- }
-
- sendWarning(step: AgentStep, warningMessage: string, agentNumber?: number) {
- if (!this.controller) return;
-
- try {
- const update: ProgressUpdate = {
- step,
- status: "warning",
- message: `⚠️ ${warningMessage}`,
- timestamp: Date.now(),
- agentNumber,
- warningMessage,
- };
- const message = encodeProgressMessage(update);
- this.controller.enqueue(new TextEncoder().encode(message));
- } catch {
- // Controller may be closed
- }
- }
-}
diff --git a/src/lib/ai/prompts/index.ts b/src/lib/ai/prompts/index.ts
index 629af87..d8f5e4d 100644
--- a/src/lib/ai/prompts/index.ts
+++ b/src/lib/ai/prompts/index.ts
@@ -15,12 +15,6 @@ export {
RESUME_CALIBRATION_EXAMPLES,
SCORING_PHASES,
SCORE_INTERPRETATION_GUIDE,
- ANALYSIS_AGENT_PROMPT,
- FEEDBACK_AGENT_PROMPT,
- OLLAMA_ANALYSIS_SYSTEM_PROMPT,
- OLLAMA_FEEDBACK_SYSTEM_PROMPT,
- buildOllamaResumeAnalysisPrompt,
- buildOllamaResumeFeedbackPrompt,
getKeywordPrompt,
getVerbPrompt,
} from "./resume-review";
@@ -30,10 +24,6 @@ export {
JOB_MATCH_SYSTEM_PROMPT,
buildJobMatchPrompt,
JOB_MATCH_SCORE_GUIDE,
- OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT,
- OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT,
- buildOllamaJobMatchAnalysisPrompt,
- buildOllamaJobMatchFeedbackPrompt,
getSkillMatchPrompt,
getSimilarityPrompt,
} from "./job-match";
diff --git a/src/lib/ai/prompts/job-match/index.ts b/src/lib/ai/prompts/job-match/index.ts
index 0661cf8..1061382 100644
--- a/src/lib/ai/prompts/job-match/index.ts
+++ b/src/lib/ai/prompts/job-match/index.ts
@@ -11,13 +11,5 @@ export { buildJobMatchPrompt } from "./user";
// Calibration examples
export { JOB_MATCH_SCORE_GUIDE } from "./calibration";
-// Ollama-specific prompts
-export {
- OLLAMA_JOB_MATCH_ANALYSIS_SYSTEM_PROMPT,
- OLLAMA_JOB_MATCH_FEEDBACK_SYSTEM_PROMPT,
- buildOllamaJobMatchAnalysisPrompt,
- buildOllamaJobMatchFeedbackPrompt,
-} from "./ollama";
-
// Semantic extraction prompts
export { getSkillMatchPrompt, getSimilarityPrompt } from "./semantic";
diff --git a/src/lib/ai/prompts/job-match/ollama.ts b/src/lib/ai/prompts/job-match/ollama.ts
deleted file mode 100644
index ed4083c..0000000
--- a/src/lib/ai/prompts/job-match/ollama.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * Job Match Ollama Prompts
- *
- * Simplified prompts optimized for small local models like llama3.2.
- */
-
-import type { ToolDataJobMatch } from "@/models/ai.model";
-import type { BaselineScore } from "../../scoring";
-
-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 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/prompts/resume-review/agents.ts b/src/lib/ai/prompts/resume-review/agents.ts
deleted file mode 100644
index 19928ec..0000000
--- a/src/lib/ai/prompts/resume-review/agents.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * Resume Review Agent Prompts
- *
- * System prompts for the Multi-Agent Resume Review System.
- */
-
-/**
- * Analysis Agent System Prompt
- *
- * Combines data analysis, keyword optimization, and fair scoring expertise.
- * Responsible for analyzing objective data and calculating a fair final score.
- */
-export const ANALYSIS_AGENT_PROMPT = `You are an expert resume analyzer combining data analysis, keyword optimization, and fair scoring expertise.
-
-Your role is to:
-1. ANALYZE objective data (quantified achievements, keywords, verbs, formatting)
-2. ASSESS keyword strength and ATS optimization
-3. CALCULATE a fair final score within the allowed variance of the mathematical baseline
-
-Key principles:
-- Use the baseline score as your anchor - it's calculated from objective metrics
-- Only adjust for subjective quality factors (summary clarity, experience detail, grammar)
-- Your final score MUST be within the allowed variance
-- Be realistic: most resumes score 45-65, exceptional ones 70-80, perfect 80+ is rare
-- Provide specific evidence for all assessments`;
-
-/**
- * Feedback Agent System Prompt
- *
- * Transforms analysis into actionable guidance with specific evidence and priorities.
- * Responsible for generating strengths, weaknesses, and improvement suggestions.
- */
-export const FEEDBACK_AGENT_PROMPT = `You are an expert feedback specialist who transforms analysis into actionable guidance.
-
-Your role is to:
-1. IDENTIFY the top strengths with specific evidence
-2. HIGHLIGHT weaknesses that matter most for job success
-3. PROVIDE concrete, implementable suggestions with examples
-4. SYNTHESIZE insights to ensure consistency
-
-Key principles:
-- Be specific: reference actual content, not generic observations
-- Be actionable: give exact steps to improve, not vague advice
-- Be encouraging: frame weaknesses as opportunities
-- Be prioritized: highest-impact improvements first
-- Be consistent: strengths/weaknesses should align with the score`;
diff --git a/src/lib/ai/prompts/resume-review/index.ts b/src/lib/ai/prompts/resume-review/index.ts
index 9f0c9d1..4f9a448 100644
--- a/src/lib/ai/prompts/resume-review/index.ts
+++ b/src/lib/ai/prompts/resume-review/index.ts
@@ -15,16 +15,5 @@ export {
SCORE_INTERPRETATION_GUIDE,
} from "./calibration";
-// Agent prompts
-export { ANALYSIS_AGENT_PROMPT, FEEDBACK_AGENT_PROMPT } from "./agents";
-
-// Ollama-specific prompts
-export {
- OLLAMA_ANALYSIS_SYSTEM_PROMPT,
- OLLAMA_FEEDBACK_SYSTEM_PROMPT,
- buildOllamaResumeAnalysisPrompt,
- buildOllamaResumeFeedbackPrompt,
-} from "./ollama";
-
// Semantic extraction prompts
export { getKeywordPrompt, getVerbPrompt } from "./semantic";
diff --git a/src/lib/ai/prompts/resume-review/ollama.ts b/src/lib/ai/prompts/resume-review/ollama.ts
deleted file mode 100644
index ba4170a..0000000
--- a/src/lib/ai/prompts/resume-review/ollama.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * Resume Review Ollama Prompts
- *
- * Simplified prompts optimized for small local models like llama3.2.
- */
-
-import type { ToolDataResume } from "@/models/ai.model";
-import type { BaselineScore } from "../../scoring";
-
-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.";
-
-/**
- * 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.`;
-}
diff --git a/src/models/ai.model.ts b/src/models/ai.model.ts
index 7c45eed..d057075 100644
--- a/src/models/ai.model.ts
+++ b/src/models/ai.model.ts
@@ -23,71 +23,6 @@ export {
SemanticSimilaritySchema,
} from "./ai.schemas";
-// MULTI-AGENT TYPES
-
-export interface AgentInsights {
- 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 CollaborativeResult<T> {
- analysis: T;
- agentInsights: AgentInsights;
- baselineScore: { score: number; breakdown: Record<string, number> };
- 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 {
diff --git a/src/models/ai.ollama-schemas.ts b/src/models/ai.ollama-schemas.ts
index 99dc9ec..79f6fb0 100644
--- a/src/models/ai.ollama-schemas.ts
+++ b/src/models/ai.ollama-schemas.ts
@@ -62,33 +62,6 @@ export const OllamaSemanticSimilaritySchema = z.object({
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
@@ -98,5 +71,3 @@ 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/models/ai.schemas.ts b/src/models/ai.schemas.ts
index 6926301..a0c022a 100644
--- a/src/models/ai.schemas.ts
+++ b/src/models/ai.schemas.ts
@@ -484,104 +484,3 @@ export const SemanticSimilaritySchema = z.object({
});
export type SemanticSimilarityResult = z.infer<typeof SemanticSimilaritySchema>;
-// ============================================================================
-// MULTI-AGENT SCHEMAS
-// ============================================================================
-
-/**
- * Analysis Agent Schema (combines Data + Keyword + Scoring)
- * Used in the multi-agent system for resume review and job matching
- */
-export const AnalysisAgentSchema = z.object({
- finalScore: z
- .number()
- .min(0)
- .max(100)
- .describe(
- "Final score after all adjustments, must be within allowed variance"
- ),
-
- dataInsights: z
- .object({
- quantifiedCount: z
- .number()
- .describe("Count of quantified achievements found"),
- keywordCount: z.number().describe("Count of relevant keywords found"),
- verbCount: z.number().describe("Count of strong action verbs found"),
- formatQuality: z
- .string()
- .describe("Brief assessment of formatting quality (1 sentence)"),
- })
- .describe("Objective data analysis findings"),
-
- keywordAnalysis: z
- .object({
- strength: z
- .string()
- .describe("Overall keyword strength assessment (1 sentence)"),
- atsScore: z
- .number()
- .min(0)
- .max(100)
- .describe("ATS-friendliness score (0-100)"),
- missingCritical: z
- .array(z.string())
- .max(5)
- .describe("Top missing critical keywords/skills"),
- recommendations: z
- .array(z.string())
- .max(3)
- .describe("Top 3 keyword optimization recommendations"),
- })
- .describe("Keyword and ATS optimization analysis"),
-
- adjustments: z
- .array(
- z.object({
- criterion: z.string().describe("The criterion being adjusted"),
- adjustment: z
- .number()
- .describe("Points added (+) or subtracted (-) from baseline"),
- reason: z.string().describe("Brief explanation for this adjustment"),
- })
- )
- .describe("List of all adjustments made to the baseline score"),
-
- math: z
- .string()
- .describe("Show your math: 'Baseline X + adj1 + adj2 - adj3 = Final Y'"),
-});
-
-export type AnalysisAgentResult = z.infer<typeof AnalysisAgentSchema>;
-
-/**
- * Feedback Agent Schema (combines Feedback + Synthesis)
- * Used in the multi-agent system for actionable recommendations
- */
-export const FeedbackAgentSchema = z.object({
- strengths: z
- .array(z.string())
- .min(2)
- .max(5)
- .describe("2-5 specific strengths with evidence from the content"),
-
- weaknesses: z
- .array(z.string())
- .min(2)
- .max(5)
- .describe("2-5 specific weaknesses with why they matter"),
-
- suggestions: z
- .array(z.string())
- .min(2)
- .max(5)
- .describe("2-5 actionable improvements with specific instructions"),
-
- synthesisNotes: z
- .string()
- .describe(
- "Brief notes on consistency between score and feedback (2-3 sentences)"
- ),
-});
-
-export type FeedbackAgentResult = z.infer<typeof FeedbackAgentSchema>;