File size: 2,412 Bytes
ef904b0
 
 
 
 
 
 
 
 
 
 
60264d1
 
ef904b0
 
 
 
 
60264d1
 
 
 
 
 
 
 
 
 
ef904b0
 
 
60264d1
 
 
 
ef904b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
64
65
66
67
"""
Vector store layer: persist and query embeddings.

Two interchangeable backends implement the same interface (see base.py):
    - "chroma"   : local, server-less ChromaDB (default, great for testing)
    - "pgvector" : PostgreSQL + pgvector (production, needs a running server)

Select the backend with the VECTOR_BACKEND environment variable, or override
per call via get_vector_store(backend=...).

    from src.vectorstore import get_vector_store
    store = get_vector_store()              # uses VECTOR_BACKEND (default "pgvector")
    store = get_vector_store("chroma")      # explicit override
"""

import os
from typing import Any

# Load .env before reading VECTOR_BACKEND below — otherwise the documented
# backend switch in .env is ignored (it's read at import time, and the backend
# modules that call load_dotenv() are imported lazily, too late to matter).
try:
    from dotenv import load_dotenv

    load_dotenv()
except ImportError:  # python-dotenv is optional at runtime
    pass

from .base import BaseVectorStore

# Global backend selector. Change the env var (or DEFAULT_BACKEND) to switch.
# Default is pgvector (PostgreSQL); start it locally with `docker compose up -d`.
# The Hugging Face Space overrides this to "chroma" (see Dockerfile), since it
# ships a prebuilt Chroma store and has no Postgres server.
DEFAULT_BACKEND = "pgvector"
VECTOR_BACKEND = os.getenv("VECTOR_BACKEND", DEFAULT_BACKEND).strip().lower()


def get_vector_store(backend: str | None = None, **kwargs: Any) -> BaseVectorStore:
    """
    Factory that returns the configured vector-store backend.

    Args:
        backend: "chroma" or "pgvector". If None, uses the VECTOR_BACKEND global.
        **kwargs: forwarded to the backend constructor (e.g. collection_name,
                  embedding_dim, persist_dir, connection_string).
    """
    chosen = (backend or VECTOR_BACKEND).strip().lower()

    if chosen in ("chroma", "chromadb"):
        from .chroma_store import ChromaVectorStore

        return ChromaVectorStore(**kwargs)

    if chosen in ("pgvector", "postgres", "postgresql"):
        from .pgvector_store import PgVectorStore

        return PgVectorStore(**kwargs)

    raise ValueError(
        f"Unknown vector store backend: {chosen!r}. "
        f"Expected one of: 'chroma', 'pgvector'."
    )


__all__ = ["BaseVectorStore", "get_vector_store", "VECTOR_BACKEND", "DEFAULT_BACKEND"]