File size: 1,106 Bytes
eb09214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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]])