Murali Chandran commited on
Commit
bf4478b
·
1 Parent(s): 9dfc96d

rag files

Browse files
Files changed (2) hide show
  1. rag.py +60 -0
  2. schemas.py +5 -0
rag.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import faiss
3
+ import json
4
+ from sentence_transformers import SentenceTransformer
5
+
6
+ KNOWLEDGE_BASE_DIR = "./knowledge_base"
7
+ FAISS_INDEX_PATH = "./faiss_index.bin"
8
+ METADATA_PATH = "./faiss_metadata.json"
9
+ EMBEDDING_MODEL = "BAAI/bge-small-en-v1.5"
10
+
11
+ print(f"--- Loading Embedding Model: {EMBEDDING_MODEL} ---")
12
+ embedder = SentenceTransformer(EMBEDDING_MODEL)
13
+ text_chunks = []
14
+
15
+ def chunk_document(text):
16
+ paragraphs = text.split("\n\n")
17
+ return [p.strip() for p in paragraphs if len(p.strip()) > 20]
18
+
19
+ def initialize_vector_store():
20
+ global text_chunks
21
+ embedding_dim = embedder.get_sentence_embedding_dimension()
22
+
23
+ if os.path.exists(FAISS_INDEX_PATH) and os.path.exists(METADATA_PATH):
24
+ print("--- Loading existing FAISS index ---")
25
+ index = faiss.read_index(FAISS_INDEX_PATH)
26
+ with open(METADATA_PATH, "r") as f:
27
+ text_chunks = json.load(f)
28
+ return index
29
+
30
+ print("--- Building FAISS index from scratch ---")
31
+ os.makedirs(KNOWLEDGE_BASE_DIR, exist_ok=True)
32
+
33
+ all_text = ""
34
+ for filename in os.listdir(KNOWLEDGE_BASE_DIR):
35
+ if filename.endswith(".txt") or filename.endswith(".md"):
36
+ with open(os.path.join(KNOWLEDGE_BASE_DIR, filename), "r", encoding="utf-8") as f:
37
+ all_text += f.read() + "\n\n"
38
+
39
+ if not all_text.strip():
40
+ all_text = "Flow matching is a generative modeling framework."
41
+
42
+ text_chunks = chunk_document(all_text)
43
+
44
+ print(f"--- Embedding {len(text_chunks)} chunks ---")
45
+ embeddings = embedder.encode(text_chunks, convert_to_numpy=True)
46
+
47
+ index = faiss.IndexFlatL2(embedding_dim)
48
+ index.add(embeddings)
49
+
50
+ faiss.write_index(index, FAISS_INDEX_PATH)
51
+ with open(METADATA_PATH, "w") as f:
52
+ json.dump(text_chunks, f)
53
+
54
+ return index
55
+
56
+ def retrieve_context(index, query, top_k=3):
57
+ query_vector = embedder.encode([query], convert_to_numpy=True)
58
+ distances, indices = index.search(query_vector, k=top_k)
59
+ retrieved_chunks = [text_chunks[i] for i in indices[0] if i != -1]
60
+ return "\n\n---\n\n".join(retrieved_chunks)
schemas.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+
3
+ class BotRequest(BaseModel):
4
+ page_text: str
5
+ user_query: str