| import { GoogleGenerativeAI } from '@google/generative-ai';
|
| import dotenv from 'dotenv';
|
|
|
| dotenv.config();
|
|
|
| class RAGEngine {
|
| constructor() {
|
| this.genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
|
|
|
| this.model = this.genAI.getGenerativeModel({ model: 'models/gemini-pro' });
|
| }
|
|
|
| |
| |
|
|
| chunkText(text, chunkSize = 2000, overlap = 200) {
|
| const chunks = [];
|
| let start = 0;
|
|
|
| while (start < text.length) {
|
| const end = Math.min(start + chunkSize, text.length);
|
| chunks.push(text.slice(start, end));
|
| start = end - overlap;
|
| }
|
|
|
| return chunks;
|
| }
|
|
|
| |
| |
| |
|
|
| async generateEmbedding(text) {
|
|
|
|
|
| return text;
|
| }
|
|
|
| |
| |
|
|
| async semanticSearch(query, chunks) {
|
|
|
|
|
| return chunks.filter(chunk =>
|
| chunk.toLowerCase().includes(query.toLowerCase())
|
| );
|
| }
|
|
|
| |
| |
|
|
| async generateResponse(query, context) {
|
| try {
|
| const prompt = `
|
| You are an AI assistant analyzing disaster management training data for the Government of India (NDMA).
|
|
|
| Context from uploaded documents:
|
| ${context}
|
|
|
| Query: ${query}
|
|
|
| Please provide a detailed, data-driven response based on the context provided. Include specific numbers, statistics, and insights where available.
|
| `;
|
|
|
| const result = await this.model.generateContent(prompt);
|
| const response = await result.response;
|
| return response.text();
|
| } catch (error) {
|
| throw new Error(`RAG generation failed: ${error.message}`);
|
| }
|
| }
|
|
|
| |
| |
|
|
| async query(question, documentText) {
|
| try {
|
|
|
| const chunks = this.chunkText(documentText);
|
|
|
|
|
| const relevantChunks = await this.semanticSearch(question, chunks);
|
|
|
|
|
| const context = relevantChunks.slice(0, 3).join('\n\n');
|
|
|
|
|
| const response = await this.generateResponse(question, context);
|
|
|
| return response;
|
| } catch (error) {
|
| throw new Error(`RAG query failed: ${error.message}`);
|
| }
|
| }
|
| }
|
|
|
| export default new RAGEngine();
|
|
|