Spaces:
Sleeping
Sleeping
github-actions[bot] commited on
Commit ·
cec9c04
1
Parent(s): 0102881
deploy: backend from e6f5637
Browse files- Dockerfile +2 -1
- rag/curriculum_rag.py +28 -6
- rag/vectorstore_loader.py +34 -0
- startup.sh +5 -0
- startup_validation.py +6 -0
- tests/test_rag_pipeline.py +6 -1
Dockerfile
CHANGED
|
@@ -7,7 +7,8 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
|
|
| 7 |
HF_HOME=/data/.huggingface \
|
| 8 |
HUGGINGFACE_HUB_CACHE=/data/.huggingface/hub \
|
| 9 |
TRANSFORMERS_CACHE=/data/.huggingface/transformers \
|
| 10 |
-
MPLCONFIGDIR=/tmp/matplotlib
|
|
|
|
| 11 |
|
| 12 |
WORKDIR /app
|
| 13 |
|
|
|
|
| 7 |
HF_HOME=/data/.huggingface \
|
| 8 |
HUGGINGFACE_HUB_CACHE=/data/.huggingface/hub \
|
| 9 |
TRANSFORMERS_CACHE=/data/.huggingface/transformers \
|
| 10 |
+
MPLCONFIGDIR=/tmp/matplotlib \
|
| 11 |
+
EMBEDDING_MODEL=BAAI/bge-small-en-v1.5
|
| 12 |
|
| 13 |
WORKDIR /app
|
| 14 |
|
rag/curriculum_rag.py
CHANGED
|
@@ -145,12 +145,34 @@ def retrieve_curriculum_context(
|
|
| 145 |
normalize_embeddings=True,
|
| 146 |
).tolist()
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
documents = (result.get("documents") or [[]])[0]
|
| 156 |
metadatas = (result.get("metadatas") or [[]])[0]
|
|
|
|
| 145 |
normalize_embeddings=True,
|
| 146 |
).tolist()
|
| 147 |
|
| 148 |
+
try:
|
| 149 |
+
result = collection.query(
|
| 150 |
+
query_embeddings=[query_embedding],
|
| 151 |
+
n_results=max(1, top_k),
|
| 152 |
+
where=where,
|
| 153 |
+
include=["documents", "metadatas", "distances"],
|
| 154 |
+
)
|
| 155 |
+
except Exception as exc:
|
| 156 |
+
err_msg = str(exc)
|
| 157 |
+
if "dimension of" in err_msg:
|
| 158 |
+
match = re.search(r"dimension of (\d+)", err_msg)
|
| 159 |
+
expected_dim = int(match.group(1)) if match else 384
|
| 160 |
+
fallback_model = "BAAI/bge-small-en-v1.5" if expected_dim == 384 else "BAAI/bge-base-en-v1.5"
|
| 161 |
+
from rag.vectorstore_loader import get_vectorstore_components, reset_vectorstore_singleton
|
| 162 |
+
reset_vectorstore_singleton()
|
| 163 |
+
_, collection, embedder = get_vectorstore_components(model_name=fallback_model)
|
| 164 |
+
query_embedding = embedder.encode(
|
| 165 |
+
prefixed_query,
|
| 166 |
+
normalize_embeddings=True,
|
| 167 |
+
).tolist()
|
| 168 |
+
result = collection.query(
|
| 169 |
+
query_embeddings=[query_embedding],
|
| 170 |
+
n_results=max(1, top_k),
|
| 171 |
+
where=where,
|
| 172 |
+
include=["documents", "metadatas", "distances"],
|
| 173 |
+
)
|
| 174 |
+
else:
|
| 175 |
+
raise
|
| 176 |
|
| 177 |
documents = (result.get("documents") or [[]])[0]
|
| 178 |
metadatas = (result.get("metadatas") or [[]])[0]
|
rag/vectorstore_loader.py
CHANGED
|
@@ -37,6 +37,25 @@ def _resolve_vectorstore_dir() -> Path:
|
|
| 37 |
# cold start triggers a ~130 MB download that can exceed the 60s startup timeout.
|
| 38 |
_DEFAULT_EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL", "BAAI/bge-small-en-v1.5")
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
def get_vectorstore_components(
|
| 41 |
collection_name: str = "curriculum_chunks",
|
| 42 |
model_name: str = _DEFAULT_EMBEDDING_MODEL,
|
|
@@ -52,7 +71,22 @@ def get_vectorstore_components(
|
|
| 52 |
name=collection_name,
|
| 53 |
metadata={"hnsw:space": "cosine"},
|
| 54 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
embedder = SentenceTransformer(model_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
_VECTORSTORE_SINGLETON = (client, collection, embedder)
|
| 57 |
return _VECTORSTORE_SINGLETON
|
| 58 |
|
|
|
|
| 37 |
# cold start triggers a ~130 MB download that can exceed the 60s startup timeout.
|
| 38 |
_DEFAULT_EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL", "BAAI/bge-small-en-v1.5")
|
| 39 |
|
| 40 |
+
|
| 41 |
+
def _get_collection_dimension(vectorstore_dir: Path, collection_name: str = "curriculum_chunks") -> int | None:
|
| 42 |
+
db_path = vectorstore_dir / "chroma.sqlite3"
|
| 43 |
+
if not db_path.exists():
|
| 44 |
+
return None
|
| 45 |
+
try:
|
| 46 |
+
import sqlite3
|
| 47 |
+
conn = sqlite3.connect(str(db_path))
|
| 48 |
+
cur = conn.cursor()
|
| 49 |
+
cur.execute("SELECT dimension FROM collections WHERE name = ?", (collection_name,))
|
| 50 |
+
row = cur.fetchone()
|
| 51 |
+
conn.close()
|
| 52 |
+
if row and row[0]:
|
| 53 |
+
return int(row[0])
|
| 54 |
+
except Exception:
|
| 55 |
+
pass
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
|
| 59 |
def get_vectorstore_components(
|
| 60 |
collection_name: str = "curriculum_chunks",
|
| 61 |
model_name: str = _DEFAULT_EMBEDDING_MODEL,
|
|
|
|
| 71 |
name=collection_name,
|
| 72 |
metadata={"hnsw:space": "cosine"},
|
| 73 |
)
|
| 74 |
+
|
| 75 |
+
expected_dim = _get_collection_dimension(vectorstore_dir, collection_name)
|
| 76 |
+
# Auto-align model_name with the collection dimension to prevent 384 vs 768 mismatch
|
| 77 |
+
if expected_dim == 384 and ("bge-base" in model_name or "768" in model_name):
|
| 78 |
+
model_name = "BAAI/bge-small-en-v1.5"
|
| 79 |
+
elif expected_dim == 768 and ("bge-small" in model_name or "384" in model_name):
|
| 80 |
+
model_name = "BAAI/bge-base-en-v1.5"
|
| 81 |
+
|
| 82 |
embedder = SentenceTransformer(model_name)
|
| 83 |
+
actual_dim = getattr(embedder, "get_sentence_embedding_dimension", lambda: None)()
|
| 84 |
+
if expected_dim is not None and actual_dim is not None and actual_dim != expected_dim:
|
| 85 |
+
if expected_dim == 384:
|
| 86 |
+
embedder = SentenceTransformer("BAAI/bge-small-en-v1.5")
|
| 87 |
+
elif expected_dim == 768:
|
| 88 |
+
embedder = SentenceTransformer("BAAI/bge-base-en-v1.5")
|
| 89 |
+
|
| 90 |
_VECTORSTORE_SINGLETON = (client, collection, embedder)
|
| 91 |
return _VECTORSTORE_SINGLETON
|
| 92 |
|
startup.sh
CHANGED
|
@@ -13,6 +13,11 @@ export CURRICULUM_DIR
|
|
| 13 |
export VECTORSTORE_DIR
|
| 14 |
export CURRICULUM_VECTORSTORE_DIR="${VECTORSTORE_DIR}"
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
echo "=========================================="
|
| 17 |
echo "MathPulse AI Startup"
|
| 18 |
echo "=========================================="
|
|
|
|
| 13 |
export VECTORSTORE_DIR
|
| 14 |
export CURRICULUM_VECTORSTORE_DIR="${VECTORSTORE_DIR}"
|
| 15 |
|
| 16 |
+
# Force canonical 384-dim embedding model to prevent dimension mismatch on HF Spaces
|
| 17 |
+
if [ "${EMBEDDING_MODEL:-}" = "BAAI/bge-base-en-v1.5" ] || [ -z "${EMBEDDING_MODEL:-}" ]; then
|
| 18 |
+
export EMBEDDING_MODEL="BAAI/bge-small-en-v1.5"
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
echo "=========================================="
|
| 22 |
echo "MathPulse AI Startup"
|
| 23 |
echo "=========================================="
|
startup_validation.py
CHANGED
|
@@ -144,6 +144,12 @@ def _validate_embedding_model() -> None:
|
|
| 144 |
f"Expected: {EXPECTED_EMBEDDING_MODEL}. "
|
| 145 |
"RAG retrieval will fail without an embedding model."
|
| 146 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
elif embedding_model != EXPECTED_EMBEDDING_MODEL:
|
| 148 |
logger.warning(
|
| 149 |
f"WARNING: EMBEDDING_MODEL is set to '{embedding_model}' — "
|
|
|
|
| 144 |
f"Expected: {EXPECTED_EMBEDDING_MODEL}. "
|
| 145 |
"RAG retrieval will fail without an embedding model."
|
| 146 |
)
|
| 147 |
+
elif embedding_model == "BAAI/bge-base-en-v1.5":
|
| 148 |
+
logger.warning(
|
| 149 |
+
f"Overriding legacy EMBEDDING_MODEL '{embedding_model}' to canonical '{EXPECTED_EMBEDDING_MODEL}'."
|
| 150 |
+
)
|
| 151 |
+
os.environ["EMBEDDING_MODEL"] = EXPECTED_EMBEDDING_MODEL
|
| 152 |
+
embedding_model = EXPECTED_EMBEDDING_MODEL
|
| 153 |
elif embedding_model != EXPECTED_EMBEDDING_MODEL:
|
| 154 |
logger.warning(
|
| 155 |
f"WARNING: EMBEDDING_MODEL is set to '{embedding_model}' — "
|
tests/test_rag_pipeline.py
CHANGED
|
@@ -193,4 +193,9 @@ class TestSubjectNormalizationAndWhere:
|
|
| 193 |
quarter=1,
|
| 194 |
competency="computes simple interest",
|
| 195 |
)
|
| 196 |
-
assert mock_ret.call_args[1]["query"] == "computes simple interest"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
quarter=1,
|
| 194 |
competency="computes simple interest",
|
| 195 |
)
|
| 196 |
+
assert mock_ret.call_args[1]["query"] == "computes simple interest"
|
| 197 |
+
|
| 198 |
+
def test_vectorstore_dimension_alignment(self):
|
| 199 |
+
from rag.vectorstore_loader import _get_collection_dimension, _resolve_vectorstore_dir
|
| 200 |
+
dim = _get_collection_dimension(_resolve_vectorstore_dir())
|
| 201 |
+
assert dim in (384, None)
|