from sentence_transformers import SentenceTransformer import faiss import numpy as np from config import EMBEDDING_MODEL model = SentenceTransformer(EMBEDDING_MODEL) index = faiss.IndexFlatL2(384) docs = [] def chunk_text(text, max_length=500): sentences = text.split('. ') chunks = [] current_chunk = '' for sentence in sentences: if len(current_chunk) + len(sentence) <= max_length: current_chunk += sentence + '. ' else: chunks.append(current_chunk.strip()) current_chunk = sentence + '. ' if current_chunk: chunks.append(current_chunk.strip()) return chunks def build_index(doc_texts): global docs docs = [] all_chunks = [] for doc in doc_texts: chunks = chunk_text(doc) docs.extend(chunks) all_chunks.extend(chunks) embeddings = model.encode(all_chunks) index.add(np.array(embeddings)) def get_relevant_chunks(query, top_k=1): query_vec = model.encode([query]) D, I = index.search(np.array(query_vec), top_k) return "\n\n".join([docs[i] for i in I[0]])