Update knowledge_base.py
Browse files- knowledge_base.py +21 -1
knowledge_base.py
CHANGED
@@ -11,4 +11,24 @@ def create_faiss_index(texts):
|
|
11 |
index = faiss.IndexFlatL2(dimension)
|
12 |
index.add(embeddings)
|
13 |
|
14 |
-
return index, texts
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
index = faiss.IndexFlatL2(dimension)
|
12 |
index.add(embeddings)
|
13 |
|
14 |
+
return index, texts
|
15 |
+
|
16 |
+
def search_faiss(faiss_index, stored_texts, query, top_k=3):
|
17 |
+
"""
|
18 |
+
Search the FAISS index for the most relevant texts based on the query.
|
19 |
+
"""
|
20 |
+
from sentence_transformers import SentenceTransformer
|
21 |
+
|
22 |
+
# Load the same model used for indexing
|
23 |
+
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
24 |
+
|
25 |
+
# Encode the query into an embedding
|
26 |
+
query_embedding = model.encode([query])
|
27 |
+
|
28 |
+
# Search the FAISS index
|
29 |
+
distances, indices = faiss_index.search(query_embedding, top_k)
|
30 |
+
|
31 |
+
# Retrieve the corresponding texts
|
32 |
+
results = [stored_texts[i] for i in indices[0] if i < len(stored_texts)]
|
33 |
+
|
34 |
+
return results
|