Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
Refactor AI functions
Khuram Niazf5ccfc81c71a
diff --git a/__tests__/ai.actions.spec.ts b/__tests__/ai.actions.spec.tsindex c46c7f6..fb9d62d 100644--- a/__tests__/ai.actions.spec.ts+++ b/__tests__/ai.actions.spec.ts@@ -19,12 +19,7 @@ jest.mock("@/lib/ai.prompts", () => ({},}));-import {- getResumeReviewByOllama,- getResumeReviewByOpenAi,- getJobMatchByOllama,- getJobMatchByOpenAi,-} from "@/actions/ai.actions";+import { getResumeReview, getJobMatch } from "@/actions/ai.actions";import { Resume, SectionType } from "@/models/profile.model";import { JobResponse } from "@/models/job.model";import { ChatOpenAI } from "@langchain/openai";@@ -138,276 +133,290 @@ describe("AI Actions", () => {delete process.env.OLLAMA_BASE_URL;});- describe("getResumeReviewByOllama", () => {- it("should create ChatOllama model with correct configuration", async () => {- const mockStream = createMockAsyncIterator([- '{"summary": "Good resume"',- ', "score": 85}',- ]);-- MockedChatOllama.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));-- await getResumeReviewByOllama(mockResume, "llama3.1");-- expect(ChatOllama).toHaveBeenCalledWith({- baseUrl: "http://localhost:11434",- model: "llama3.1",- temperature: 0,- format: "json",- maxConcurrency: 1,- numCtx: undefined,+ describe("getResumeReview", () => {+ describe("with ollama model", () => {+ it("should create ChatOllama model with correct configuration", async () => {+ const mockStream = createMockAsyncIterator([+ '{"summary": "Good resume"',+ ', "score": 85}',+ ]);++ MockedChatOllama.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));++ await getResumeReview(mockResume, "ollama", "llama3.1");++ expect(ChatOllama).toHaveBeenCalledWith({+ baseUrl: "http://localhost:11434",+ model: "llama3.1",+ temperature: 0,+ format: "json",+ maxConcurrency: 1,+ numCtx: undefined,+ });});- });- it("should use default baseUrl when OLLAMA_BASE_URL is not set", async () => {- delete process.env.OLLAMA_BASE_URL;+ it("should use default baseUrl when OLLAMA_BASE_URL is not set", async () => {+ delete process.env.OLLAMA_BASE_URL;- const mockStream = createMockAsyncIterator(['{"summary": "test"}']);+ const mockStream = createMockAsyncIterator(['{"summary": "test"}']);- MockedChatOllama.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));+ MockedChatOllama.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));- await getResumeReviewByOllama(mockResume, "llama3.1");+ await getResumeReview(mockResume, "ollama", "llama3.1");- expect(ChatOllama).toHaveBeenCalledWith(- expect.objectContaining({- baseUrl: "http://127.0.0.1:11434",- })- );- });+ expect(ChatOllama).toHaveBeenCalledWith(+ expect.objectContaining({+ baseUrl: "http://127.0.0.1:11434",+ })+ );+ });- it("should return a ReadableStream with encoded chunks", async () => {- const mockChunkStrings = [- '{"summary":',- ' "Good resume",',- ' "score": 85}',- ];- const mockChunks = mockChunkStrings.map((content) => ({ content }));- const mockStream = createMockAsyncIterator(mockChunks);+ it("should return a ReadableStream with encoded chunks", async () => {+ const mockChunkStrings = [+ '{"summary":',+ ' "Good resume",',+ ' "score": 85}',+ ];+ const mockChunks = mockChunkStrings.map((content) => ({ content }));+ const mockStream = createMockAsyncIterator(mockChunks);- MockedChatOllama.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));+ MockedChatOllama.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));- const result = await getResumeReviewByOllama(mockResume, "llama3.1");+ const result = await getResumeReview(mockResume, "ollama", "llama3.1");- expect(result).toBeInstanceOf(ReadableStream);+ expect(result).toBeInstanceOf(ReadableStream);- // Verify streaming functionality- const reader = result!.getReader();- const decoder = new TextDecoder();- let fullText = "";+ // Verify streaming functionality+ const reader = result!.getReader();+ const decoder = new TextDecoder();+ let fullText = "";- while (true) {- const { done, value } = await reader.read();- if (done) break;- fullText += decoder.decode(value);- }+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ fullText += decoder.decode(value);+ }- expect(fullText).toBe(mockChunkStrings.join(""));- });+ expect(fullText).toBe(mockChunkStrings.join(""));+ });- it("should convert resume to text before processing", async () => {- const mockStream = createMockAsyncIterator(['{"summary": "test"}']);+ it("should convert resume to text before processing", async () => {+ const mockStream = createMockAsyncIterator(['{"summary": "test"}']);- MockedChatOllama.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));+ MockedChatOllama.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));- await getResumeReviewByOllama(mockResume, "llama3.1");+ await getResumeReview(mockResume, "ollama", "llama3.1");- expect(convertResumeToText).toHaveBeenCalledWith(mockResume);+ expect(convertResumeToText).toHaveBeenCalledWith(mockResume);+ });});- });- describe("getResumeReviewByOpenAi", () => {- it("should create ChatOpenAI model with correct configuration", async () => {- const mockStream = createMockAsyncIterator(['{"summary": "test"}']);+ describe("with openai model", () => {+ it("should create ChatOpenAI model with correct configuration", async () => {+ const mockStream = createMockAsyncIterator(['{"summary": "test"}']);- MockedChatOpenAI.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));+ MockedChatOpenAI.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));- await getResumeReviewByOpenAi(mockResume, "gpt-4");+ await getResumeReview(mockResume, "openai", "gpt-4");- expect(ChatOpenAI).toHaveBeenCalledWith({- model: "gpt-4",- openAIApiKey: "test-openai-key",- temperature: 0,- maxConcurrency: 1,- maxTokens: 3000,+ expect(ChatOpenAI).toHaveBeenCalledWith({+ model: "gpt-4",+ openAIApiKey: "test-openai-key",+ temperature: 0,+ maxConcurrency: 1,+ maxTokens: 3000,+ });});- });- it("should return a ReadableStream with encoded chunks", async () => {- const mockChunkStrings = ['{"summary":', ' "Excellent resume"}'];- const mockChunks = mockChunkStrings.map((content) => ({ content }));- const mockStream = createMockAsyncIterator(mockChunks);+ it("should return a ReadableStream with encoded chunks", async () => {+ const mockChunkStrings = ['{"summary":', ' "Excellent resume"}'];+ const mockChunks = mockChunkStrings.map((content) => ({ content }));+ const mockStream = createMockAsyncIterator(mockChunks);- MockedChatOpenAI.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));+ MockedChatOpenAI.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));- const result = await getResumeReviewByOpenAi(mockResume, "gpt-4");+ const result = await getResumeReview(mockResume, "openai", "gpt-4");- expect(result).toBeInstanceOf(ReadableStream);+ expect(result).toBeInstanceOf(ReadableStream);- const reader = result!.getReader();- const decoder = new TextDecoder();- let fullText = "";+ const reader = result!.getReader();+ const decoder = new TextDecoder();+ let fullText = "";- while (true) {- const { done, value } = await reader.read();- if (done) break;- fullText += decoder.decode(value);- }+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ fullText += decoder.decode(value);+ }- expect(fullText).toBe(mockChunkStrings.join(""));+ expect(fullText).toBe(mockChunkStrings.join(""));+ });});});- describe("getJobMatchByOllama", () => {- it("should create ChatOllama model with correct configuration", async () => {- const mockStream = createMockAsyncIterator(['{"matching_score": 75}']);-- MockedChatOllama.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));-- await getJobMatchByOllama(mockResume, mockJob, "llama3.1");-- expect(ChatOllama).toHaveBeenCalledWith({- baseUrl: "http://localhost:11434",- model: "llama3.1",- temperature: 0,- format: "json",- maxConcurrency: 1,- numCtx: 3000,+ describe("getJobMatch", () => {+ describe("with ollama model", () => {+ it("should create ChatOllama model with correct configuration", async () => {+ const mockStream = createMockAsyncIterator(['{"matching_score": 75}']);++ MockedChatOllama.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));++ await getJobMatch(mockResume, mockJob, "ollama", "llama3.1");++ expect(ChatOllama).toHaveBeenCalledWith({+ baseUrl: "http://localhost:11434",+ model: "llama3.1",+ temperature: 0,+ format: "json",+ maxConcurrency: 1,+ numCtx: 3000,+ });});- });-- it("should convert both resume and job to text", async () => {- const mockStream = createMockAsyncIterator(['{"matching_score": 80}']);- MockedChatOllama.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));-- await getJobMatchByOllama(mockResume, mockJob, "llama3.1");-- expect(convertResumeToText).toHaveBeenCalledWith(mockResume);- expect(convertJobToText).toHaveBeenCalledWith(mockJob);- });-- it("should return a ReadableStream with job match results", async () => {- const mockChunkStrings = [- '{"matching_score":',- " 85,",- ' "suggestions": []}',- ];- const mockChunks = mockChunkStrings.map((content) => ({ content }));- const mockStream = createMockAsyncIterator(mockChunks);-- MockedChatOllama.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));-- const result = await getJobMatchByOllama(mockResume, mockJob, "llama3.1");-- expect(result).toBeInstanceOf(ReadableStream);-- const reader = result!.getReader();- const decoder = new TextDecoder();- let fullText = "";-- while (true) {- const { done, value } = await reader.read();- if (done) break;- fullText += decoder.decode(value);- }+ it("should convert both resume and job to text", async () => {+ const mockStream = createMockAsyncIterator(['{"matching_score": 80}']);- expect(fullText).toBe(mockChunkStrings.join(""));- });- });+ MockedChatOllama.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));- describe("getJobMatchByOpenAi", () => {- it("should create ChatOpenAI model with correct configuration", async () => {- const mockStream = createMockAsyncIterator(['{"matching_score": 90}']);-- MockedChatOpenAI.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));+ await getJobMatch(mockResume, mockJob, "ollama", "llama3.1");- await getJobMatchByOpenAi(mockResume, mockJob, "gpt-4");+ expect(convertResumeToText).toHaveBeenCalledWith(mockResume);+ expect(convertJobToText).toHaveBeenCalledWith(mockJob);+ });- expect(ChatOpenAI).toHaveBeenCalledWith({- model: "gpt-4",- openAIApiKey: "test-openai-key",- temperature: 0,- maxConcurrency: 1,- maxTokens: 3000,+ it("should return a ReadableStream with job match results", async () => {+ const mockChunkStrings = [+ '{"matching_score":',+ " 85,",+ ' "suggestions": []}',+ ];+ const mockChunks = mockChunkStrings.map((content) => ({ content }));+ const mockStream = createMockAsyncIterator(mockChunks);++ MockedChatOllama.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));++ const result = await getJobMatch(+ mockResume,+ mockJob,+ "ollama",+ "llama3.1"+ );++ expect(result).toBeInstanceOf(ReadableStream);++ const reader = result!.getReader();+ const decoder = new TextDecoder();+ let fullText = "";++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ fullText += decoder.decode(value);+ }++ expect(fullText).toBe(mockChunkStrings.join(""));});});- it("should convert both resume and job to text", async () => {- const mockStream = createMockAsyncIterator(['{"matching_score": 88}']);+ describe("with openai model", () => {+ it("should create ChatOpenAI model with correct configuration", async () => {+ const mockStream = createMockAsyncIterator(['{"matching_score": 90}']);- MockedChatOpenAI.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));+ MockedChatOpenAI.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));- await getJobMatchByOpenAi(mockResume, mockJob, "gpt-4");+ await getJobMatch(mockResume, mockJob, "openai", "gpt-4");- expect(convertResumeToText).toHaveBeenCalledWith(mockResume);- expect(convertJobToText).toHaveBeenCalledWith(mockJob);- });+ expect(ChatOpenAI).toHaveBeenCalledWith({+ model: "gpt-4",+ openAIApiKey: "test-openai-key",+ temperature: 0,+ maxConcurrency: 1,+ maxTokens: 3000,+ });+ });- it("should format prompt with resume and job description", async () => {- const mockStream = createMockAsyncIterator(['{"matching_score": 92}']);+ it("should convert both resume and job to text", async () => {+ const mockStream = createMockAsyncIterator(['{"matching_score": 88}']);- MockedChatOpenAI.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));+ MockedChatOpenAI.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));- await getJobMatchByOpenAi(mockResume, mockJob, "gpt-4");+ await getJobMatch(mockResume, mockJob, "openai", "gpt-4");- expect(MockedJobMatchPrompt.format).toHaveBeenCalledWith({- resume: mockResumeText,- job_description: mockJobText,+ expect(convertResumeToText).toHaveBeenCalledWith(mockResume);+ expect(convertJobToText).toHaveBeenCalledWith(mockJob);});- });-- it("should return a ReadableStream with job match results", async () => {- const mockChunkStrings = [- '{"matching_score": 95,',- ' "detailed_analysis": [],',- ' "suggestions": []}',- ];- const mockChunks = mockChunkStrings.map((content) => ({ content }));- const mockStream = createMockAsyncIterator(mockChunks);-- MockedChatOpenAI.mockImplementation(() => ({- stream: jest.fn().mockResolvedValue(mockStream),- }));- const result = await getJobMatchByOpenAi(mockResume, mockJob, "gpt-4");+ it("should format prompt with resume and job description", async () => {+ const mockStream = createMockAsyncIterator(['{"matching_score": 92}']);- expect(result).toBeInstanceOf(ReadableStream);+ MockedChatOpenAI.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));- const reader = result!.getReader();- const decoder = new TextDecoder();- let fullText = "";+ await getJobMatch(mockResume, mockJob, "openai", "gpt-4");- while (true) {- const { done, value } = await reader.read();- if (done) break;- fullText += decoder.decode(value);- }+ expect(MockedJobMatchPrompt.format).toHaveBeenCalledWith({+ resume: mockResumeText,+ job_description: mockJobText,+ });+ });- expect(fullText).toBe(mockChunkStrings.join(""));+ it("should return a ReadableStream with job match results", async () => {+ const mockChunkStrings = [+ '{"matching_score": 95,',+ ' "detailed_analysis": [],',+ ' "suggestions": []}',+ ];+ const mockChunks = mockChunkStrings.map((content) => ({ content }));+ const mockStream = createMockAsyncIterator(mockChunks);++ MockedChatOpenAI.mockImplementation(() => ({+ stream: jest.fn().mockResolvedValue(mockStream),+ }));++ const result = await getJobMatch(+ mockResume,+ mockJob,+ "openai",+ "gpt-4"+ );++ expect(result).toBeInstanceOf(ReadableStream);++ const reader = result!.getReader();+ const decoder = new TextDecoder();+ let fullText = "";++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ fullText += decoder.decode(value);+ }++ expect(fullText).toBe(mockChunkStrings.join(""));+ });});});@@ -422,11 +431,11 @@ describe("AI Actions", () => {stream: jest.fn().mockResolvedValue(mockStream),}));- // Test all four functions- await getResumeReviewByOllama(mockResume, "llama3.1");- await getResumeReviewByOpenAi(mockResume, "gpt-4");- await getJobMatchByOllama(mockResume, mockJob, "llama3.1");- await getJobMatchByOpenAi(mockResume, mockJob, "gpt-4");+ // Test all functions+ await getResumeReview(mockResume, "ollama", "llama3.1");+ await getResumeReview(mockResume, "openai", "gpt-4");+ await getJobMatch(mockResume, mockJob, "ollama", "llama3.1");+ await getJobMatch(mockResume, mockJob, "openai", "gpt-4");// Resume review should be called 2 times (Ollama and OpenAI)expect(MockedResumeReviewPrompt.format).toHaveBeenCalledTimes(2);diff --git a/src/actions/ai.actions.ts b/src/actions/ai.actions.tsindex 4e638d9..da30dcc 100644--- a/src/actions/ai.actions.ts+++ b/src/actions/ai.actions.ts@@ -77,57 +77,25 @@ async function streamResponse(// --- Main Functions ----export const getResumeReviewByOllama = async (+export const getResumeReview = async (resume: Resume,+ modelType: ModelType,aiModel?: string): Promise<ReadableStream | undefined> => {const resumeText = await convertResumeToText(resume);const inputMessage = await resumeReviewPrompt.format({ resume: resumeText });const model = createModel({- modelType: "ollama",- modelName: aiModel,- format: "json",- });- return streamResponse(model, inputMessage);-};--export const getResumeReviewByOpenAi = async (- resume: Resume,- aiModel?: string-): Promise<ReadableStream | undefined> => {- const resumeText = await convertResumeToText(resume);- const inputMessage = await resumeReviewPrompt.format({ resume: resumeText });- const model = createModel({- modelType: "openai",- modelName: aiModel,- maxTokens: 3000,- });- return streamResponse(model, inputMessage);-};--export const getJobMatchByOllama = async (- resume: Resume,- job: JobResponse,- aiModel?: string-): Promise<ReadableStream | undefined> => {- const resumeText = await convertResumeToText(resume);- const jobText = await convertJobToText(job);- const inputMessage = await jobMatchPrompt.format({- resume: resumeText || "No resume provided",- job_description: jobText,- });- const model = createModel({- modelType: "ollama",+ modelType,modelName: aiModel,- format: "json",- numCtx: 3000,+ ...(modelType === "ollama" ? { format: "json" } : { maxTokens: 3000 }),});return streamResponse(model, inputMessage);};-export const getJobMatchByOpenAi = async (+export const getJobMatch = async (resume: Resume,job: JobResponse,+ modelType: ModelType,aiModel?: string): Promise<ReadableStream | undefined> => {const resumeText = await convertResumeToText(resume);@@ -137,9 +105,11 @@ export const getJobMatchByOpenAi = async (job_description: jobText,});const model = createModel({- modelType: "openai",+ modelType,modelName: aiModel,- maxTokens: 3000,+ ...(modelType === "ollama"+ ? { format: "json", numCtx: 3000 }+ : { maxTokens: 3000 }),});return streamResponse(model, inputMessage);};diff --git a/src/app/api/ai/resume/match/route.ts b/src/app/api/ai/resume/match/route.tsindex 529c3d1..642bdc5 100644--- a/src/app/api/ai/resume/match/route.ts+++ b/src/app/api/ai/resume/match/route.ts@@ -3,7 +3,7 @@ import "server-only";import { auth } from "@/auth";import { NextRequest, NextResponse } from "next/server";import { Resume } from "@/models/profile.model";-import { getJobMatchByOllama, getJobMatchByOpenAi } from "@/actions/ai.actions";+import { getJobMatch } from "@/actions/ai.actions";import { getResumeById } from "@/actions/profile.actions";import { getJobDetails } from "@/actions/job.actions";import { AiModel, AiProvider } from "@/models/ai.model";@@ -30,15 +30,14 @@ export const POST = async (req: NextRequest) => {[getResumeById(resumeId), getJobDetails(jobId)]);- let response;- switch (selectedModel.provider) {- case AiProvider.OPENAI:- response = await getJobMatchByOpenAi(resume, job, selectedModel.model);- break;- default:- response = await getJobMatchByOllama(resume, job, selectedModel.model);- break;- }+ const modelType =+ selectedModel.provider === AiProvider.OPENAI ? "openai" : "ollama";+ const response = await getJobMatch(+ resume,+ job,+ modelType,+ selectedModel.model+ );return new NextResponse(response, {headers: {diff --git a/src/app/api/ai/resume/review/route.ts b/src/app/api/ai/resume/review/route.tsindex fe34d1a..903688b 100644--- a/src/app/api/ai/resume/review/route.ts+++ b/src/app/api/ai/resume/review/route.ts@@ -1,10 +1,7 @@import "server-only";import { auth } from "@/auth";-import {- getResumeReviewByOllama,- getResumeReviewByOpenAi,-} from "@/actions/ai.actions";+import { getResumeReview } from "@/actions/ai.actions";import { NextRequest, NextResponse } from "next/server";import { Resume } from "@/models/profile.model";import { AiModel, AiProvider } from "@/models/ai.model";@@ -25,15 +22,13 @@ export const POST = async (req: NextRequest) => {throw new Error("Resume or selected model is required");}- let response;- switch (selectedModel.provider) {- case AiProvider.OPENAI:- response = await getResumeReviewByOpenAi(resume, selectedModel.model);- break;- default:- response = await getResumeReviewByOllama(resume, selectedModel.model);- break;- }+ const modelType =+ selectedModel.provider === AiProvider.OPENAI ? "openai" : "ollama";+ const response = await getResumeReview(+ resume,+ modelType,+ selectedModel.model+ );return new NextResponse(response, {headers: {