File size: 1,662 Bytes
1c642ea 19cc25a 1c642ea 19cc25a 1c642ea 19cc25a 1c642ea 19cc25a 1c642ea | 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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | """
Singleton FAISS vector store shared by all agents.
"""
from __future__ import annotations
import os
from typing import Optional
from langchain_community.vectorstores import FAISS
from langchain_core.documents import Document
from langchain_community.embeddings import HuggingFaceEmbeddings
_vector_store: Optional[FAISS] = None
_embeddings = None
PERSIST_DIR = os.path.join(os.path.dirname(__file__), ".faiss_store")
def _get_embeddings():
global _embeddings
if _embeddings is None:
_embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
return _embeddings
def get_vector_store() -> FAISS:
"""Return the singleton FAISS store, loading from disk if available."""
global _vector_store
if _vector_store is not None:
return _vector_store
emb = _get_embeddings()
if os.path.exists(PERSIST_DIR):
_vector_store = FAISS.load_local(
PERSIST_DIR, emb, allow_dangerous_deserialization=True
)
else:
# Bootstrap with a placeholder so FAISS is initialised
_vector_store = FAISS.from_documents(
[Document(page_content="__init__", metadata={"source": "init"})],
emb,
)
return _vector_store
def add_documents(docs: list[Document]) -> None:
"""Add documents to the store and persist to disk."""
vs = get_vector_store()
vs.add_documents(docs)
vs.save_local(PERSIST_DIR)
def reset_store() -> None:
"""Clear the in-memory store (useful between sessions)."""
global _vector_store
_vector_store = None
if os.path.exists(PERSIST_DIR):
import shutil
shutil.rmtree(PERSIST_DIR)
|