Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(rag): add opt-in HNSW vector indexes

XZH9ca18f66bdd6
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index 5275d5566..c11537d51 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -1297,6 +1297,10 @@ class LlamaIndexConfigUpdate(BaseModel):
top_k: int | None = None
vector_top_k_multiplier: int | None = None
bm25_top_k_multiplier: int | None = None
+ vector_index_type: str | None = None
+ hnsw_m: int | None = None
+ hnsw_ef_construction: int | None = None
+ hnsw_ef_search: int | None = None
chunk_size: int | None = None
chunk_overlap: int | None = None
image_description_concurrency: int | None = None
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py
index f6815c48a..17a4daf60 100644
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@ -251,6 +251,8 @@ DEFAULT_IMA_SETTINGS: dict[str, Any] = {
# * ``top_k`` — default number of chunks a query returns.
# * ``vector_top_k_multiplier`` / ``bm25_top_k_multiplier`` — how many extra
# candidates each child retriever fetches before fusion re-ranks to ``top_k``.
+# * ``vector_index_type`` — FAISS index type for the next full index build.
+# HNSW is opt-in and trades exact recall for sub-linear search at scale.
# * ``chunk_size`` / ``chunk_overlap`` — indexing chunk geometry; changes apply
# on the next (re-)index, not retroactively.
# * ``image_description_concurrency`` / ``image_description_timeout_seconds`` —
@@ -262,6 +264,11 @@ DEFAULT_IMA_SETTINGS: dict[str, Any] = {
LLAMAINDEX_VECTOR_PROFILE = "vector"
LLAMAINDEX_HYBRID_PROFILE = "hybrid"
_LLAMAINDEX_PROFILES = frozenset({LLAMAINDEX_VECTOR_PROFILE, LLAMAINDEX_HYBRID_PROFILE})
+LLAMAINDEX_FLAT_VECTOR_INDEX = "flat"
+LLAMAINDEX_HNSW_VECTOR_INDEX = "hnsw"
+_LLAMAINDEX_VECTOR_INDEX_TYPES = frozenset(
+ {LLAMAINDEX_FLAT_VECTOR_INDEX, LLAMAINDEX_HNSW_VECTOR_INDEX}
+)
DEFAULT_LLAMAINDEX_SETTINGS: dict[str, Any] = {
"version": 1,
@@ -269,6 +276,10 @@ DEFAULT_LLAMAINDEX_SETTINGS: dict[str, Any] = {
"top_k": 5,
"vector_top_k_multiplier": 2,
"bm25_top_k_multiplier": 2,
+ "vector_index_type": LLAMAINDEX_FLAT_VECTOR_INDEX,
+ "hnsw_m": 32,
+ "hnsw_ef_construction": 200,
+ "hnsw_ef_search": 64,
"chunk_size": 512,
"chunk_overlap": 50,
"image_description_concurrency": 4,
@@ -814,6 +825,9 @@ class RuntimeSettingsService:
profile = _string(settings.get("retrieval_profile")).lower()
if profile not in _LLAMAINDEX_PROFILES:
profile = LLAMAINDEX_HYBRID_PROFILE
+ vector_index_type = _string(settings.get("vector_index_type")).lower()
+ if vector_index_type not in _LLAMAINDEX_VECTOR_INDEX_TYPES:
+ vector_index_type = LLAMAINDEX_FLAT_VECTOR_INDEX
chunk_size = _coerce_clamped_int(settings.get("chunk_size"), 512, 64, 8192)
# Overlap must stay below the chunk size or chunking degenerates.
chunk_overlap = _coerce_clamped_int(
@@ -829,6 +843,12 @@ class RuntimeSettingsService:
"bm25_top_k_multiplier": _coerce_clamped_int(
settings.get("bm25_top_k_multiplier"), 2, 1, 10
),
+ "vector_index_type": vector_index_type,
+ "hnsw_m": _coerce_clamped_int(settings.get("hnsw_m"), 32, 4, 64),
+ "hnsw_ef_construction": _coerce_clamped_int(
+ settings.get("hnsw_ef_construction"), 200, 16, 512
+ ),
+ "hnsw_ef_search": _coerce_clamped_int(settings.get("hnsw_ef_search"), 64, 1, 512),
"chunk_size": chunk_size,
"chunk_overlap": chunk_overlap,
"image_description_concurrency": _coerce_clamped_int(
diff --git a/deeptutor/services/rag/pipelines/llamaindex/config.py b/deeptutor/services/rag/pipelines/llamaindex/config.py
index 47e7849a5..5034f7e0e 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/config.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/config.py
@@ -9,6 +9,9 @@ import sys
VECTOR_PROFILE = "vector"
HYBRID_PROFILE = "hybrid"
SUPPORTED_RETRIEVAL_PROFILES = {VECTOR_PROFILE, HYBRID_PROFILE}
+FLAT_VECTOR_INDEX = "flat"
+HNSW_VECTOR_INDEX = "hnsw"
+SUPPORTED_VECTOR_INDEX_TYPES = {FLAT_VECTOR_INDEX, HNSW_VECTOR_INDEX}
def should_show_progress() -> bool:
@@ -39,6 +42,16 @@ class RetrievalConfig:
return max(requested, requested * max(1, int(multiplier)))
+@dataclass(frozen=True)
+class VectorIndexConfig:
+ """FAISS construction knobs for the next full index build."""
+
+ type: str = FLAT_VECTOR_INDEX
+ hnsw_m: int = 32
+ hnsw_ef_construction: int = 200
+ hnsw_ef_search: int = 64
+
+
def normalize_retrieval_profile(value: str | None) -> str:
"""Return a supported retrieval profile, defaulting to hybrid."""
profile = (value or "").strip().lower()
@@ -47,6 +60,14 @@ def normalize_retrieval_profile(value: str | None) -> str:
return HYBRID_PROFILE
+def normalize_vector_index_type(value: str | None) -> str:
+ """Return a supported vector index type, defaulting to exact flat search."""
+ index_type = (value or "").strip().lower()
+ if index_type in SUPPORTED_VECTOR_INDEX_TYPES:
+ return index_type
+ return FLAT_VECTOR_INDEX
+
+
def retrieval_config_from_env() -> RetrievalConfig:
"""Build retrieval config from environment variables.
@@ -88,6 +109,20 @@ def retrieval_config_from_settings() -> RetrievalConfig:
)
+def vector_index_config_from_settings() -> VectorIndexConfig:
+ """Build FAISS construction settings, retaining the exact flat default."""
+ try:
+ settings = _load_runtime_settings()
+ except Exception:
+ return VectorIndexConfig()
+ return VectorIndexConfig(
+ type=normalize_vector_index_type(settings.get("vector_index_type")),
+ hnsw_m=int(settings.get("hnsw_m", 32) or 32),
+ hnsw_ef_construction=int(settings.get("hnsw_ef_construction", 200) or 200),
+ hnsw_ef_search=int(settings.get("hnsw_ef_search", 64) or 64),
+ )
+
+
def default_top_k() -> int:
"""The configured default number of chunks a retrieval returns."""
try:
@@ -124,11 +159,15 @@ __all__ = [
"HYBRID_PROFILE",
"RetrievalConfig",
"SUPPORTED_RETRIEVAL_PROFILES",
+ "SUPPORTED_VECTOR_INDEX_TYPES",
"VECTOR_PROFILE",
+ "FLAT_VECTOR_INDEX",
+ "HNSW_VECTOR_INDEX",
"chunk_geometry",
"default_top_k",
"image_description_limits",
"normalize_retrieval_profile",
"retrieval_config_from_env",
"retrieval_config_from_settings",
+ "vector_index_config_from_settings",
]
diff --git a/deeptutor/services/rag/pipelines/llamaindex/ingestion.py b/deeptutor/services/rag/pipelines/llamaindex/ingestion.py
index dc68da1d7..352a63ff6 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/ingestion.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/ingestion.py
@@ -15,7 +15,7 @@ from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.schema import BaseNode
from . import vector_store
-from .config import should_show_progress
+from .config import should_show_progress, vector_index_config_from_settings
def build_ingestion_pipeline() -> IngestionPipeline:
@@ -98,7 +98,9 @@ def create_index_from_documents(
if show_progress is None:
show_progress = should_show_progress()
nodes = documents_to_nodes(documents, show_progress=show_progress)
- storage_context = vector_store.storage_context_for_nodes(nodes)
+ storage_context = vector_store.storage_context_for_nodes(
+ nodes, vector_index_config_from_settings()
+ )
index = VectorStoreIndex(
nodes=nodes, storage_context=storage_context, show_progress=show_progress
)
diff --git a/deeptutor/services/rag/pipelines/llamaindex/vector_store.py b/deeptutor/services/rag/pipelines/llamaindex/vector_store.py
index 00f2b1bcb..9bfcff969 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/vector_store.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/vector_store.py
@@ -14,7 +14,8 @@ CPU core and makes retrieval take minutes (issue #552).
This seam swaps in a FAISS index instead:
* New (and re-indexed) knowledge bases are persisted as a binary FAISS index
- (``IndexFlatIP``), loaded once and searched with vectorized BLAS.
+ (exact ``IndexFlatIP`` by default, or opt-in HNSW for large corpora), loaded
+ once and searched without a Python-side scan.
* Legacy ``SimpleVectorStore`` knowledge bases stay fully readable, so upgrading
never breaks an existing index. Re-indexing one rebuilds it as FAISS for the
full speed-up.
@@ -36,6 +37,8 @@ from llama_index.core import StorageContext, load_index_from_storage
from llama_index.core.vector_stores.simple import DEFAULT_VECTOR_STORE, NAMESPACE_SEP
import numpy as np
+from .config import HNSW_VECTOR_INDEX, VectorIndexConfig
+
logger = logging.getLogger(__name__)
BACKEND_FAISS = "faiss"
@@ -182,7 +185,23 @@ def _uniform_dimension(embeddings: Iterable[Any]) -> Optional[int]:
return dimension if dimension and dimension > 0 else None
-def new_faiss_storage_context(dimension: int) -> Optional[StorageContext]:
+def _new_faiss_index(faiss: Any, dimension: int, config: VectorIndexConfig) -> Any:
+ """Construct a cosine-compatible FAISS index for ``config``."""
+ if config.type == HNSW_VECTOR_INDEX:
+ index = faiss.IndexHNSWFlat(
+ dimension,
+ max(1, int(config.hnsw_m)),
+ faiss.METRIC_INNER_PRODUCT,
+ )
+ index.hnsw.efConstruction = max(1, int(config.hnsw_ef_construction))
+ index.hnsw.efSearch = max(1, int(config.hnsw_ef_search))
+ return index
+ return faiss.IndexFlatIP(dimension)
+
+
+def new_faiss_storage_context(
+ dimension: int, index_config: VectorIndexConfig | None = None
+) -> Optional[StorageContext]:
"""Return a StorageContext whose default store is a fresh cosine FAISS index.
Returns None when FAISS is unavailable or the dimension is invalid, so
@@ -192,11 +211,15 @@ def new_faiss_storage_context(dimension: int) -> Optional[StorageContext]:
cosine_cls = _cosine_faiss_cls()
if faiss is None or cosine_cls is None or dimension <= 0:
return None
- store = cosine_cls(faiss_index=faiss.IndexFlatIP(dimension))
+ store = cosine_cls(
+ faiss_index=_new_faiss_index(faiss, dimension, index_config or VectorIndexConfig())
+ )
return StorageContext.from_defaults(vector_store=store)
-def storage_context_for_nodes(nodes: list[Any]) -> Optional[StorageContext]:
+def storage_context_for_nodes(
+ nodes: list[Any], index_config: VectorIndexConfig | None = None
+) -> Optional[StorageContext]:
"""Choose the write-time StorageContext for a set of embedded nodes.
Returns a FAISS-backed context when every node shares one embedding
@@ -209,7 +232,7 @@ def storage_context_for_nodes(nodes: list[Any]) -> Optional[StorageContext]:
dimension = _uniform_dimension(getattr(node, "embedding", None) for node in nodes)
if dimension is None:
return None
- return new_faiss_storage_context(dimension)
+ return new_faiss_storage_context(dimension, index_config)
def detect_backend(storage_dir: Path) -> str:
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index 1f73ea932..40033604b 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -1927,3 +1927,40 @@ def test_lightrag_config_endpoint_round_trips_the_indexing_knobs(
assert again["max_concurrent_files"] == 4
assert again["entity_extract_max_gleaning"] == 2
assert again["top_k"] == 42
+
+
+def test_llamaindex_config_endpoint_round_trips_vector_index_knobs(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """The vector-index form depends on every field surviving a save/reload."""
+ from deeptutor.services.config.runtime_settings import RuntimeSettingsService
+
+ service = RuntimeSettingsService(tmp_path, process_env={})
+ monkeypatch.setattr(
+ "deeptutor.services.config.get_runtime_settings_service",
+ lambda: service,
+ )
+
+ client = TestClient(_build_app())
+ initial = client.get("/api/v1/knowledge/rag-pipelines/llamaindex/config")
+ assert initial.status_code == 200
+ assert initial.json()["vector_index_type"] == "flat"
+
+ saved = client.put(
+ "/api/v1/knowledge/rag-pipelines/llamaindex/config",
+ json={
+ "vector_index_type": "hnsw",
+ "hnsw_m": 24,
+ "hnsw_ef_construction": 128,
+ "hnsw_ef_search": 48,
+ },
+ )
+ assert saved.status_code == 200
+ assert saved.json()["vector_index_type"] == "hnsw"
+ assert saved.json()["hnsw_m"] == 24
+ assert saved.json()["hnsw_ef_construction"] == 128
+ assert saved.json()["hnsw_ef_search"] == 48
+
+ again = client.get("/api/v1/knowledge/rag-pipelines/llamaindex/config").json()
+ assert again["vector_index_type"] == "hnsw"
+ assert again["hnsw_ef_search"] == 48
diff --git a/tests/services/config/test_llamaindex_settings.py b/tests/services/config/test_llamaindex_settings.py
index 93342128b..40e78f809 100644
--- a/tests/services/config/test_llamaindex_settings.py
+++ b/tests/services/config/test_llamaindex_settings.py
@@ -14,6 +14,10 @@ def test_llamaindex_defaults_when_absent(tmp_path: Path) -> None:
assert loaded["top_k"] == 5
assert loaded["vector_top_k_multiplier"] == 2
assert loaded["bm25_top_k_multiplier"] == 2
+ assert loaded["vector_index_type"] == "flat"
+ assert loaded["hnsw_m"] == 32
+ assert loaded["hnsw_ef_construction"] == 200
+ assert loaded["hnsw_ef_search"] == 64
assert loaded["chunk_size"] == 512
assert loaded["chunk_overlap"] == 50
assert loaded["image_description_concurrency"] == 4
@@ -51,6 +55,10 @@ def test_llamaindex_clamps_out_of_range(tmp_path: Path) -> None:
"retrieval_profile": "nonsense",
"top_k": 999,
"bm25_top_k_multiplier": 0,
+ "vector_index_type": "hnsw",
+ "hnsw_m": 999,
+ "hnsw_ef_construction": 1,
+ "hnsw_ef_search": 0,
"chunk_size": 8,
"chunk_overlap": 99999,
"image_description_concurrency": 999,
@@ -62,6 +70,10 @@ def test_llamaindex_clamps_out_of_range(tmp_path: Path) -> None:
assert loaded["retrieval_profile"] == "hybrid"
assert loaded["top_k"] == 50
assert loaded["bm25_top_k_multiplier"] == 1
+ assert loaded["vector_index_type"] == "hnsw"
+ assert loaded["hnsw_m"] == 64
+ assert loaded["hnsw_ef_construction"] == 16
+ assert loaded["hnsw_ef_search"] == 1
assert loaded["chunk_size"] == 64
# Overlap is clamped below the chunk size so chunking never degenerates.
assert loaded["chunk_overlap"] == 63
@@ -78,6 +90,13 @@ def test_llamaindex_profile_env_override(tmp_path: Path) -> None:
assert loaded["retrieval_profile"] == "hybrid"
+def test_llamaindex_unknown_vector_index_falls_back_to_flat(tmp_path: Path) -> None:
+ svc = RuntimeSettingsService(tmp_path, process_env={})
+ saved = svc.save_llamaindex({"vector_index_type": "ivf"})
+
+ assert saved["vector_index_type"] == "flat"
+
+
def test_chunk_geometry_preserves_zero_overlap(monkeypatch) -> None:
from deeptutor.services.rag.pipelines.llamaindex import config
@@ -90,6 +109,27 @@ def test_chunk_geometry_preserves_zero_overlap(monkeypatch) -> None:
assert config.chunk_geometry() == (512, 0)
+def test_vector_index_config_uses_runtime_settings(monkeypatch) -> None:
+ from deeptutor.services.rag.pipelines.llamaindex import config
+
+ monkeypatch.setattr(
+ config,
+ "_load_runtime_settings",
+ lambda: {
+ "vector_index_type": "HNSW",
+ "hnsw_m": 24,
+ "hnsw_ef_construction": 128,
+ "hnsw_ef_search": 48,
+ },
+ )
+
+ selected = config.vector_index_config_from_settings()
+ assert selected.type == "hnsw"
+ assert selected.hnsw_m == 24
+ assert selected.hnsw_ef_construction == 128
+ assert selected.hnsw_ef_search == 48
+
+
def test_image_description_limits_use_runtime_settings(monkeypatch) -> None:
from deeptutor.services.rag.pipelines.llamaindex import config
diff --git a/tests/services/rag/test_llamaindex_faiss_vector_store.py b/tests/services/rag/test_llamaindex_faiss_vector_store.py
index 8369208a4..7ea9be02f 100644
--- a/tests/services/rag/test_llamaindex_faiss_vector_store.py
+++ b/tests/services/rag/test_llamaindex_faiss_vector_store.py
@@ -19,6 +19,7 @@ import pytest
from deeptutor.services.rag.pipelines.llamaindex import storage as storage_module
from deeptutor.services.rag.pipelines.llamaindex import vector_store
+from deeptutor.services.rag.pipelines.llamaindex.config import VectorIndexConfig
faiss = pytest.importorskip("faiss")
pytest.importorskip("llama_index.vector_stores.faiss")
@@ -74,8 +75,8 @@ def _nodes() -> list[TextNode]:
return nodes
-def _persist_faiss_index(storage_dir: Path) -> None:
- context = vector_store.new_faiss_storage_context(_DIM)
+def _persist_faiss_index(storage_dir: Path, index_config: VectorIndexConfig | None = None) -> None:
+ context = vector_store.new_faiss_storage_context(_DIM, index_config)
assert context is not None
index = VectorStoreIndex(nodes=_nodes(), storage_context=context)
context.persist(persist_dir=str(storage_dir))
@@ -101,6 +102,26 @@ def test_new_index_persists_faiss_and_ranks_by_cosine(tmp_path: Path) -> None:
assert ids == ["gamma", "alpha"]
+def test_opt_in_hnsw_index_persists_and_ranks_by_cosine(tmp_path: Path) -> None:
+ """HNSW is an opt-in scalable backend with the same cosine semantics."""
+ index_config = VectorIndexConfig(
+ type="hnsw", hnsw_m=8, hnsw_ef_construction=32, hnsw_ef_search=16
+ )
+ _persist_faiss_index(tmp_path, index_config)
+
+ persisted = vector_store.faiss_read_index(
+ str(tmp_path / vector_store.DEFAULT_VECTOR_STORE_FILENAME)
+ )
+ assert type(persisted).__name__ == "IndexHNSWFlat"
+ assert persisted.metric_type == faiss.METRIC_INNER_PRODUCT
+ assert persisted.hnsw.efConstruction == 32
+ assert persisted.hnsw.efSearch == 16
+
+ index = vector_store.load_index(tmp_path)
+ results = index.as_retriever(similarity_top_k=2).retrieve("probe")
+ assert [r.node.node_id for r in results] == ["gamma", "alpha"]
+
+
def test_legacy_simple_index_stays_readable_without_mutation(tmp_path: Path) -> None:
"""An existing SimpleVectorStore KB keeps working after the FAISS upgrade."""
_persist_simple_index(tmp_path)
@@ -266,6 +287,35 @@ def test_storage_create_index_persists_faiss_end_to_end(tmp_path: Path) -> None:
assert storage_module.retrieve_nodes(storage_dir, "probe", top_k=1)
+def test_storage_create_index_honors_hnsw_settings(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The production ingestion path uses the persisted index-type settings."""
+ from llama_index.core import Document
+
+ from deeptutor.services.rag.pipelines.llamaindex import ingestion
+
+ monkeypatch.setattr(
+ ingestion,
+ "vector_index_config_from_settings",
+ lambda: VectorIndexConfig(
+ type="hnsw", hnsw_m=8, hnsw_ef_construction=32, hnsw_ef_search=16
+ ),
+ )
+ storage_dir = tmp_path / "version-1"
+ storage_dir.mkdir()
+
+ count = storage_module.create_index([Document(text="node gamma", id_="g")], storage_dir)
+
+ assert count == 1
+ assert vector_store.detect_backend(storage_dir) == vector_store.BACKEND_FAISS
+ persisted = vector_store.faiss_read_index(
+ str(storage_dir / vector_store.DEFAULT_VECTOR_STORE_FILENAME)
+ )
+ assert type(persisted).__name__ == "IndexHNSWFlat"
+ assert storage_module.retrieve_nodes(storage_dir, "probe", top_k=1)
+
+
def test_faiss_persist_and_load_survive_non_ascii_path(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
diff --git a/web/components/knowledge/EngineDetail.tsx b/web/components/knowledge/EngineDetail.tsx
index 0f223e313..b8ede706b 100644
--- a/web/components/knowledge/EngineDetail.tsx
+++ b/web/components/knowledge/EngineDetail.tsx
@@ -389,6 +389,10 @@ function LlamaIndexForm({
top_k: form.top_k,
vector_top_k_multiplier: form.vector_top_k_multiplier,
bm25_top_k_multiplier: form.bm25_top_k_multiplier,
+ vector_index_type: form.vector_index_type,
+ hnsw_m: form.hnsw_m,
+ hnsw_ef_construction: form.hnsw_ef_construction,
+ hnsw_ef_search: form.hnsw_ef_search,
chunk_size: form.chunk_size,
chunk_overlap: form.chunk_overlap,
image_description_concurrency: form.image_description_concurrency,
@@ -406,6 +410,7 @@ function LlamaIndexForm({
};
const isHybrid = form.retrieval_profile === "hybrid";
+ const isHnsw = form.vector_index_type === "hnsw";
const profiles: {
id: LlamaIndexConfig["retrieval_profile"];
desc: string;
@@ -420,6 +425,20 @@ function LlamaIndexForm({
},
];
+ const vectorIndexes: {
+ id: LlamaIndexConfig["vector_index_type"];
+ desc: string;
+ }[] = [
+ {
+ id: "flat",
+ desc: "Exact nearest-neighbor search. Best for small and medium knowledge bases.",
+ },
+ {
+ id: "hnsw",
+ desc: "Approximate graph search for large knowledge bases. Faster at scale with a small recall trade-off.",
+ },
+ ];
+
return (
<div className="space-y-6 rounded-2xl border border-[var(--border)] p-4">
{/* Retrieval profile */}
@@ -487,6 +506,72 @@ function LlamaIndexForm({
/>
</div>
+ {/* Vector index */}
+ <div>
+ <div className="mb-2 flex items-baseline justify-between gap-2">
+ <span className="text-[12px] font-medium text-[var(--foreground)]">
+ {t("Vector index")}
+ </span>
+ <span className="text-[11px] text-[var(--muted-foreground)]">
+ {t("Applies on the next full re-index")}
+ </span>
+ </div>
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
+ {vectorIndexes.map((indexType) => {
+ const active = form.vector_index_type === indexType.id;
+ return (
+ <button
+ key={indexType.id}
+ type="button"
+ onClick={() => set({ vector_index_type: indexType.id })}
+ className={`flex flex-col gap-1 rounded-xl border p-3 text-left transition-colors ${
+ active
+ ? "border-[var(--primary)] bg-[var(--primary)]/5"
+ : "border-[var(--border)] hover:border-[var(--ring)]"
+ }`}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <span className="font-mono text-[12.5px] font-medium text-[var(--foreground)]">
+ {indexType.id}
+ </span>
+ {active && (
+ <Check className="h-3.5 w-3.5 text-[var(--primary)]" />
+ )}
+ </div>
+ <span className="text-[11.5px] leading-snug text-[var(--muted-foreground)]">
+ {t(indexType.desc)}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ {isHnsw && (
+ <div className="mt-3 grid grid-cols-1 gap-4 sm:grid-cols-3">
+ <NumberField
+ label={t("HNSW graph degree")}
+ value={form.hnsw_m}
+ min={4}
+ max={64}
+ onChange={(v) => set({ hnsw_m: v })}
+ />
+ <NumberField
+ label={t("HNSW construction candidates")}
+ value={form.hnsw_ef_construction}
+ min={16}
+ max={512}
+ onChange={(v) => set({ hnsw_ef_construction: v })}
+ />
+ <NumberField
+ label={t("HNSW search candidates")}
+ value={form.hnsw_ef_search}
+ min={1}
+ max={512}
+ onChange={(v) => set({ hnsw_ef_search: v })}
+ />
+ </div>
+ )}
+ </div>
+
{/* Chunking */}
<div>
<div className="mb-2 flex items-baseline justify-between gap-2">
diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.ts
index 3b073590b..f51705d31 100644
--- a/web/lib/knowledge-api.ts
+++ b/web/lib/knowledge-api.ts
@@ -58,6 +58,11 @@ export interface LlamaIndexConfig {
top_k: number;
vector_top_k_multiplier: number;
bm25_top_k_multiplier: number;
+ /** Vector index type used by the next full index build. */
+ vector_index_type: "flat" | "hnsw";
+ hnsw_m: number;
+ hnsw_ef_construction: number;
+ hnsw_ef_search: number;
/** Chunk geometry — applies to documents indexed after the change. */
chunk_size: number;
chunk_overlap: number;
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 846e8a812..74770c722 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -3402,5 +3402,12 @@
"Tutor threads": "Tutor threads",
"Filter by archive status": "Filter by archive status",
"Active and archived": "Active and archived",
- "Loading conversations": "Loading conversations"
+ "Loading conversations": "Loading conversations",
+ "Vector index": "Vector index",
+ "Applies on the next full re-index": "Applies on the next full re-index",
+ "Exact nearest-neighbor search. Best for small and medium knowledge bases.": "Exact nearest-neighbor search. Best for small and medium knowledge bases.",
+ "Approximate graph search for large knowledge bases. Faster at scale with a small recall trade-off.": "Approximate graph search for large knowledge bases. Faster at scale with a small recall trade-off.",
+ "HNSW graph degree": "HNSW graph degree",
+ "HNSW construction candidates": "HNSW construction candidates",
+ "HNSW search candidates": "HNSW search candidates"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 1279f3d24..fd38297d0 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -3402,5 +3402,12 @@
"Tutor threads": "小老师追问",
"Filter by archive status": "按归档状态筛选",
"Active and archived": "进行中与已归档",
- "Loading conversations": "正在加载聊天"
+ "Loading conversations": "正在加载聊天",
+ "Vector index": "向量索引",
+ "Applies on the next full re-index": "在下次完整重建索引时生效",
+ "Exact nearest-neighbor search. Best for small and medium knowledge bases.": "精确最近邻搜索,适合中小型知识库。",
+ "Approximate graph search for large knowledge bases. Faster at scale with a small recall trade-off.": "面向大型知识库的近似图搜索,规模更大时更快,但会有少量召回损失。",
+ "HNSW graph degree": "HNSW 图连接度",
+ "HNSW construction candidates": "HNSW 构建候选数",
+ "HNSW search candidates": "HNSW 搜索候选数"
}