Spaces:
Sleeping
Sleeping
Download src/rag_engine.py from low-key-007/CHatbotRL: direct link, hf CLI and curl.
- Browser
- Download file 2.88 kB
-
https://huggingface.co/spaces/low-key-007/CHatbotRL/resolve/main/src/rag_engine.py
- Command line
-
hf download hf://spaces/low-key-007/CHatbotRL/src/rag_engine.py
-
curl -L -o rag_engine.py https://huggingface.co/spaces/low-key-007/CHatbotRL/resolve/main/src/rag_engine.py
2.88 kB
| import os | |
| import json | |
| import faiss | |
| import numpy as np | |
| from pathlib import Path | |
| from langchain_openai import OpenAIEmbeddings | |
| from langchain_google_genai import GoogleGenerativeAIEmbeddings | |
| from langchain_text_splitters import RecursiveCharacterTextSplitter | |
| from src.config import Config | |
| class RAGEngine: | |
| def __init__(self): | |
| self.dimension = 1536 | |
| self.index = None | |
| self.knowledge_chunks = [] | |
| self.chunks_meta = [] # Weights handling | |
| self.faiss_path = Path(Config.STORE_DIR) / "knowledge.faiss" | |
| self.meta_path = Path(Config.STORE_DIR) / "chunks_meta.json" | |
| # Initialize Embeddings | |
| if Config.USE_MODEL == "gemini": | |
| self.embed_model = GoogleGenerativeAIEmbeddings( | |
| model="models/embedding-001", | |
| google_api_key=Config.GEMINI_KEYS[0] | |
| ) | |
| self.dimension = 768 | |
| else: | |
| self.embed_model = OpenAIEmbeddings( | |
| model="text-embedding-3-small", | |
| openai_api_key=Config.OPENAI_KEYS[0] | |
| ) | |
| self._load_or_create_index() | |
| def _load_or_create_index(self): | |
| if self.faiss_path.exists(): | |
| self.index = faiss.read_index(str(self.faiss_path)) | |
| self.chunks_meta = json.load(open(self.meta_path, "r")) | |
| # Logic to load chunks text skipped for brevity (assume loaded) | |
| else: | |
| self.index = faiss.IndexFlatL2(self.dimension) | |
| def retrieve(self, query: str, k=3): | |
| if self.index.ntotal == 0: return [] | |
| q_vec = self.embed_model.embed_query(query) | |
| D, I = self.index.search(np.array([q_vec], dtype="float32"), k*2) | |
| results = [] | |
| for dist, idx in zip(D[0], I[0]): | |
| if idx < 0: continue | |
| # Weighting Logic (RLHF) | |
| weight = self.chunks_meta[idx].get("weight", 1.0) | |
| score = -float(dist) + (0.5 * weight) # Boost score by weight | |
| results.append((score, idx)) | |
| results.sort(key=lambda x: x[0], reverse=True) | |
| return [self.knowledge_chunks[idx] for _, idx in results[:k]] | |
| def adjust_weights(self, message: str, rating: int): | |
| """Reinforcement Learning: Adjust weights based on user feedback""" | |
| if self.index.ntotal == 0: return | |
| q_vec = self.embed_model.embed_query(message) | |
| _, I = self.index.search(np.array([q_vec], dtype="float32"), 5) | |
| delta = 0.35 * (rating / 2.5) if rating > 0 else -0.7 | |
| for idx in I[0]: | |
| if 0 <= idx < len(self.chunks_meta): | |
| old = self.chunks_meta[idx].get("weight", 1.0) | |
| self.chunks_meta[idx]["weight"] = max(0.1, min(10.0, old + delta)) | |
| # Save state | |
| json.dump(self.chunks_meta, open(self.meta_path, "w")) | |
| # Singleton | |
| engine = RAGEngine() |