Skip to content

Commit e356136

Browse files
add chat features with documents
1 parent b949a0c commit e356136

File tree

6 files changed

+83
-0
lines changed

6 files changed

+83
-0
lines changed

dump.rdb

88 Bytes
Binary file not shown.

src/controllers/pdf/pdf-upload.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ export const pdfUploadFilesController = async (
3131
message: `Successfully cleared old data and queued ${files.length} new files for processing!`,
3232
});
3333
} catch (error) {
34+
console.error("🔴 FULL ERROR OBJECT IN CONTROLLER:", error);
35+
3436
for (const file of files) {
3537
fs.unlink(file.path);
3638
}

src/controllers/pdf/pdg-chat.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// src/controllers/pdf/pdf-chat.ts
2+
import { Request, Response } from "express";
3+
import { queryKnowledgeBase } from "../../service/vector-store-service";
4+
import { generateChatResponse } from "../../service/ai-response-service";
5+
6+
export const pdfChatController = async (
7+
req: Request,
8+
res: Response
9+
): Promise<any> => {
10+
try {
11+
const { question } = req.body;
12+
13+
if (!question) {
14+
return res.status(400).json({ message: "Question is required." });
15+
}
16+
17+
// 1. Retrieve relevant context from your knowledge base
18+
const context = await queryKnowledgeBase(question);
19+
20+
// 2. Generate a response from the AI using the context
21+
const answer = await generateChatResponse(question, context);
22+
23+
res.status(200).json({ answer });
24+
} catch (error: any) {
25+
console.error("🔴 Error in chat controller:", error);
26+
res.status(500).json({
27+
message: "An error occurred while generating a response.",
28+
error: error.message,
29+
});
30+
}
31+
};

src/routes/PDF-routes.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import express from "express";
22
import { pdfUploadFilesController } from "../controllers/pdf/pdf-upload";
33
import { upload } from "../middleware./uploadfiles";
4+
import { pdfChatController } from "../controllers/pdf/pdg-chat";
45
const router = express.Router();
56

67
router.post("/uploads", upload.array("files", 10), pdfUploadFilesController);
8+
router.post("/chat", pdfChatController);
79

810
export default router;

src/service/ai-response-service.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import "dotenv/config";
2+
import { GoogleGenerativeAI } from "@google/generative-ai";
3+
4+
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);
5+
6+
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
7+
8+
export async function generateChatResponse(
9+
question: string,
10+
context: string[]
11+
): Promise<string> {
12+
// Construct a detailed prompt for the AI
13+
const prompt = `You are an expert assistant.
14+
Using ONLY the following context from documents,
15+
please answer the user's question.
16+
The context is provided in a JSON array.
17+
If the answer is not in the context, say 'I cannot find that information in the provided documents.'
18+
19+
Context:
20+
${JSON.stringify(context)}
21+
22+
User's Question:
23+
${question}`;
24+
25+
try {
26+
const result = await model.generateContent(prompt);
27+
const response = await result.response;
28+
return response.text();
29+
} catch (error) {
30+
console.error("Error generating chat response:", error);
31+
throw new Error("Failed to generate response from AI model.");
32+
}
33+
}

src/service/vector-store-service.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,29 @@ export async function getKnowledgeCollection() {
2424
return collection;
2525
}
2626

27+
export async function queryKnowledgeBase(question: string): Promise<string[]> {
28+
const collection = getKnowledgeCollection();
29+
30+
const results = (await collection).query({
31+
queryTexts: [question],
32+
nResults: 5,
33+
});
34+
35+
return (await results).documents[0];
36+
}
37+
2738
export async function cleanUpPreviousData() {
2839
try {
2940
await client.deleteCollection({ name: "insight_engine_knowledge" });
3041
console.log("✅ Previous collection deleted successfully.");
3142
} catch (error: any) {
43+
if (error.name === "ChromaNotFoundError") {
44+
console.log("No previous collection to delete. Starting fresh.");
45+
}
3246
if (error.message.includes("does not exist")) {
3347
console.log("No previous collection to delete. Starting fresh.");
3448
} else {
49+
console.log(error);
3550
throw error;
3651
}
3752
}

0 commit comments

Comments
 (0)