Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat: Add semantic chunking and advanced RAG configuration options

LearningCircuit4438d23c9233
diff --git a/pdm.lock b/pdm.lock
index 65254bfc69..346c0b2d0f 100644
--- a/pdm.lock
+++ b/pdm.lock
@@ -5,7 +5,7 @@
groups = ["default", "dev"]
strategy = ["inherit_metadata"]
lock_version = "4.5.0"
-content_hash = "sha256:56fb8ecfee2017cb31512c40fa165c5877ec159c4fe1c98b2e43d79c2a7ebb8d"
+content_hash = "sha256:bc8d87bd48d231a232075a9eac95e565a93fa2e4b9225590acdeabfb4fa29596"
[[metadata.targets]]
requires_python = ">=3.11,<3.15"
@@ -2871,6 +2871,21 @@ files = [
{file = "langchain_core-1.0.4.tar.gz", hash = "sha256:086d408bcbeedecb0b152201e0163b85e7a6d9b26e11a75cc577b7371291df4e"},
]
+[[package]]
+name = "langchain-experimental"
+version = "0.4.0"
+requires_python = "<4.0,>=3.10"
+summary = "Building applications with LLMs through composability"
+groups = ["default"]
+dependencies = [
+ "langchain-community<1.0.0,>=0.4.0",
+ "langchain-core<2.0.0,>=1.0.0",
+]
+files = [
+ {file = "langchain_experimental-0.4.0-py3-none-any.whl", hash = "sha256:50306e75218e3a3f002de3dd879d719addd6481284b1a282292fac46a130f4a1"},
+ {file = "langchain_experimental-0.4.0.tar.gz", hash = "sha256:16bb5c9810e1908c0e2d82cd000bb434bb437b8977507e4dbfe5f25800f431fd"},
+]
+
[[package]]
name = "langchain-ollama"
version = "1.0.0"
diff --git a/pyproject.toml b/pyproject.toml
index 2033817449..fa53244fd5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -83,6 +83,7 @@ dependencies = [
"markdown~=3.10",
"datasets~=4.4",
"pyarrow~=22.0",
+ "langchain-experimental>=0.4.0",
]
[project.optional-dependencies]
diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.py
index 5886e35dd4..94cb4b62e9 100644
--- a/src/local_deep_research/database/models/library.py
+++ b/src/local_deep_research/database/models/library.py
@@ -274,6 +274,23 @@ class Collection(Base):
chunk_size = Column(Integer, nullable=True) # Chunk size used
chunk_overlap = Column(Integer, nullable=True) # Chunk overlap used
+ # Advanced embedding configuration options (Issue #1054)
+ splitter_type = Column(
+ String(50), nullable=True
+ ) # Splitter type: 'recursive', 'semantic', 'token', 'sentence'
+ text_separators = Column(
+ JSON, nullable=True
+ ) # Text separators for chunking, e.g., ["\n\n", "\n", ". ", " ", ""]
+ distance_metric = Column(
+ String(50), nullable=True
+ ) # Distance metric: 'cosine', 'l2', 'dot_product'
+ normalize_vectors = Column(
+ Boolean, nullable=True
+ ) # Whether to normalize embeddings with L2
+ index_type = Column(
+ String(50), nullable=True
+ ) # FAISS index type: 'flat', 'hnsw', 'ivf'
+
# Timestamps
created_at = Column(UtcDateTime, default=utcnow(), nullable=False)
updated_at = Column(
@@ -558,6 +575,23 @@ class RAGIndex(Base):
chunk_size = Column(Integer, nullable=False)
chunk_overlap = Column(Integer, nullable=False)
+ # Advanced embedding configuration options (Issue #1054)
+ splitter_type = Column(
+ String(50), nullable=True
+ ) # Splitter type: 'recursive', 'semantic', 'token', 'sentence'
+ text_separators = Column(
+ JSON, nullable=True
+ ) # Text separators for chunking, e.g., ["\n\n", "\n", ". ", " ", ""]
+ distance_metric = Column(
+ String(50), nullable=True
+ ) # Distance metric: 'cosine', 'l2', 'dot_product'
+ normalize_vectors = Column(
+ Boolean, nullable=True
+ ) # Whether to normalize embeddings with L2
+ index_type = Column(
+ String(50), nullable=True
+ ) # FAISS index type: 'flat', 'hnsw', 'ivf'
+
# Index statistics
chunk_count = Column(Integer, default=0) # Number of chunks in this index
total_documents = Column(Integer, default=0) # Number of source documents
diff --git a/src/local_deep_research/embeddings/splitters/__init__.py b/src/local_deep_research/embeddings/splitters/__init__.py
new file mode 100644
index 0000000000..add7435b7a
--- /dev/null
+++ b/src/local_deep_research/embeddings/splitters/__init__.py
@@ -0,0 +1,9 @@
+"""
+Text splitters for document chunking.
+
+This module provides various text splitting strategies for RAG indexing.
+"""
+
+from .text_splitter_registry import get_text_splitter, VALID_SPLITTER_TYPES
+
+__all__ = ["get_text_splitter", "VALID_SPLITTER_TYPES"]
diff --git a/src/local_deep_research/embeddings/splitters/text_splitter_registry.py b/src/local_deep_research/embeddings/splitters/text_splitter_registry.py
new file mode 100644
index 0000000000..3965bd909c
--- /dev/null
+++ b/src/local_deep_research/embeddings/splitters/text_splitter_registry.py
@@ -0,0 +1,145 @@
+"""
+Central registry for text splitters.
+
+This module provides a factory function to create different types of text splitters
+based on configuration, similar to how embeddings_config.py works for embeddings.
+"""
+
+from typing import Optional, List, Any
+from langchain_text_splitters import (
+ RecursiveCharacterTextSplitter,
+ TokenTextSplitter,
+ SentenceTransformersTokenTextSplitter,
+)
+from langchain_core.embeddings import Embeddings
+from loguru import logger
+
+# Valid splitter type options
+VALID_SPLITTER_TYPES = [
+ "recursive",
+ "token",
+ "sentence",
+ "semantic",
+]
+
+
+def get_text_splitter(
+ splitter_type: str = "recursive",
+ chunk_size: int = 1000,
+ chunk_overlap: int = 200,
+ text_separators: Optional[List[str]] = None,
+ embeddings: Optional[Embeddings] = None,
+ **kwargs,
+) -> Any:
+ """
+ Get text splitter based on type.
+
+ Args:
+ splitter_type: Type of splitter ('recursive', 'token', 'sentence', 'semantic')
+ chunk_size: Maximum size of chunks
+ chunk_overlap: Overlap between chunks
+ text_separators: Custom separators (only used for 'recursive' type)
+ embeddings: Embeddings instance (required for 'semantic' type)
+ **kwargs: Additional splitter-specific parameters
+
+ Returns:
+ A text splitter instance
+
+ Raises:
+ ValueError: If splitter_type is invalid or required parameters are missing
+ ImportError: If required dependencies are not installed
+ """
+ # Normalize splitter type
+ splitter_type = splitter_type.strip().lower()
+
+ # Validate splitter type
+ if splitter_type not in VALID_SPLITTER_TYPES:
+ logger.error(f"Invalid splitter type: {splitter_type}")
+ raise ValueError(
+ f"Invalid splitter type: {splitter_type}. "
+ f"Must be one of: {VALID_SPLITTER_TYPES}"
+ )
+
+ logger.info(
+ f"Creating text splitter: type={splitter_type}, "
+ f"chunk_size={chunk_size}, chunk_overlap={chunk_overlap}"
+ )
+
+ # Create the appropriate splitter
+ if splitter_type == "token":
+ return TokenTextSplitter(
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ )
+
+ elif splitter_type == "sentence":
+ return SentenceTransformersTokenTextSplitter(
+ chunk_overlap=chunk_overlap,
+ tokens_per_chunk=chunk_size,
+ )
+
+ elif splitter_type == "semantic":
+ # Semantic chunking requires embeddings
+ if embeddings is None:
+ raise ValueError(
+ "Semantic splitter requires 'embeddings' parameter. "
+ "Please provide an embeddings instance."
+ )
+
+ try:
+ # Try to import experimental semantic chunker
+ from langchain_experimental.text_splitter import SemanticChunker
+
+ # Get breakpoint threshold from kwargs or use default
+ breakpoint_threshold_type = kwargs.get(
+ "breakpoint_threshold_type", "percentile"
+ )
+ breakpoint_threshold_amount = kwargs.get(
+ "breakpoint_threshold_amount", None
+ )
+
+ # Create semantic chunker
+ chunker_kwargs = {"embeddings": embeddings}
+
+ if breakpoint_threshold_type:
+ chunker_kwargs["breakpoint_threshold_type"] = (
+ breakpoint_threshold_type
+ )
+
+ if breakpoint_threshold_amount is not None:
+ chunker_kwargs["breakpoint_threshold_amount"] = (
+ breakpoint_threshold_amount
+ )
+
+ logger.info(
+ f"Creating SemanticChunker with threshold_type={breakpoint_threshold_type}, "
+ f"threshold_amount={breakpoint_threshold_amount}"
+ )
+
+ return SemanticChunker(**chunker_kwargs)
+
+ except ImportError as e:
+ logger.exception("Failed to import SemanticChunker")
+ raise ImportError(
+ "Semantic chunking requires langchain-experimental. "
+ "Install it with: pip install langchain-experimental"
+ ) from e
+
+ else: # "recursive" or default
+ # Use custom separators if provided, otherwise use defaults
+ if text_separators is None:
+ text_separators = ["\n\n", "\n", ". ", " ", ""]
+
+ return RecursiveCharacterTextSplitter(
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ length_function=len,
+ separators=text_separators,
+ )
+
+
+def is_semantic_chunker_available() -> bool:
+ """Check if semantic chunking is available."""
+ import importlib.util
+
+ return importlib.util.find_spec("langchain_experimental") is not None
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index 8de4b34b7c..511d05b1a8 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -66,6 +66,32 @@ def get_rag_service(collection_id: Optional[str] = None) -> LibraryRAGService:
settings.get_setting("local_search_chunk_overlap", 200)
)
+ # Get new advanced configuration settings (Issue #1054)
+ import json
+
+ default_splitter_type = settings.get_setting(
+ "local_search_splitter_type", "recursive"
+ )
+ default_text_separators = settings.get_setting(
+ "local_search_text_separators", '["\n\n", "\n", ". ", " ", ""]'
+ )
+ # Parse JSON string to list
+ if isinstance(default_text_separators, str):
+ try:
+ default_text_separators = json.loads(default_text_separators)
+ except json.JSONDecodeError:
+ default_text_separators = ["\n\n", "\n", ". ", " ", ""]
+ default_distance_metric = settings.get_setting(
+ "local_search_distance_metric", "cosine"
+ )
+ default_normalize_vectors = settings.get_setting(
+ "local_search_normalize_vectors", "true"
+ )
+ # Convert string "true"/"false" to boolean
+ if isinstance(default_normalize_vectors, str):
+ default_normalize_vectors = default_normalize_vectors.lower() == "true"
+ default_index_type = settings.get_setting("local_search_index_type", "flat")
+
# If collection_id provided, check for stored settings
if collection_id:
with get_user_db_session(username) as db_session:
@@ -86,6 +112,16 @@ def get_rag_service(collection_id: Optional[str] = None) -> LibraryRAGService:
chunk_size=collection.chunk_size or default_chunk_size,
chunk_overlap=collection.chunk_overlap
or default_chunk_overlap,
+ splitter_type=collection.splitter_type
+ or default_splitter_type,
+ text_separators=collection.text_separators
+ or default_text_separators,
+ distance_metric=collection.distance_metric
+ or default_distance_metric,
+ normalize_vectors=collection.normalize_vectors
+ if collection.normalize_vectors is not None
+ else default_normalize_vectors,
+ index_type=collection.index_type or default_index_type,
)
elif collection:
# New collection - use defaults and store them
@@ -100,6 +136,11 @@ def get_rag_service(collection_id: Optional[str] = None) -> LibraryRAGService:
embedding_provider=default_embedding_provider,
chunk_size=default_chunk_size,
chunk_overlap=default_chunk_overlap,
+ splitter_type=default_splitter_type,
+ text_separators=default_text_separators,
+ distance_metric=default_distance_metric,
+ normalize_vectors=default_normalize_vectors,
+ index_type=default_index_type,
)
# Store settings on collection (will be done during indexing)
@@ -115,6 +156,11 @@ def get_rag_service(collection_id: Optional[str] = None) -> LibraryRAGService:
embedding_provider=default_embedding_provider,
chunk_size=default_chunk_size,
chunk_overlap=default_chunk_overlap,
+ splitter_type=default_splitter_type,
+ text_separators=default_text_separators,
+ distance_metric=default_distance_metric,
+ normalize_vectors=default_normalize_vectors,
+ index_type=default_index_type,
)
@@ -250,9 +296,28 @@ def collection_create_page():
@login_required
def get_current_settings():
"""Get current RAG configuration from settings."""
+ import json as json_lib
+
try:
settings = get_settings_manager()
+ # Get text separators and parse if needed
+ text_separators = settings.get_setting(
+ "local_search_text_separators", '["\n\n", "\n", ". ", " ", ""]'
+ )
+ if isinstance(text_separators, str):
+ try:
+ text_separators = json_lib.loads(text_separators)
+ except json_lib.JSONDecodeError:
+ text_separators = ["\n\n", "\n", ". ", " ", ""]
+
+ # Get normalize_vectors and convert to boolean if needed
+ normalize_vectors = settings.get_setting(
+ "local_search_normalize_vectors", "true"
+ )
+ if isinstance(normalize_vectors, str):
+ normalize_vectors = normalize_vectors.lower() == "true"
+
return jsonify(
{
"success": True,
@@ -270,6 +335,17 @@ def get_current_settings():
"chunk_overlap": settings.get_setting(
"local_search_chunk_overlap", 200
),
+ "splitter_type": settings.get_setting(
+ "local_search_splitter_type", "recursive"
+ ),
+ "text_separators": text_separators,
+ "distance_metric": settings.get_setting(
+ "local_search_distance_metric", "cosine"
+ ),
+ "normalize_vectors": normalize_vectors,
+ "index_type": settings.get_setting(
+ "local_search_index_type", "flat"
+ ),
},
}
)
@@ -652,6 +728,8 @@ def configure_rag():
Change RAG configuration (embedding model, chunk size, etc.).
This will create a new index with the new configuration.
"""
+ import json as json_lib
+
try:
data = request.get_json()
embedding_model = data.get("embedding_model")
@@ -660,19 +738,27 @@ def configure_rag():
chunk_overlap = data.get("chunk_overlap")
collection_id = data.get("collection_id")
+ # Get new advanced settings (with defaults)
+ splitter_type = data.get("splitter_type", "recursive")
+ text_separators = data.get(
+ "text_separators", ["\n\n", "\n", ". ", " ", ""]
+ )
+ distance_metric = data.get("distance_metric", "cosine")
+ normalize_vectors = data.get("normalize_vectors", True)
+ index_type = data.get("index_type", "flat")
+
if not all(
[
embedding_model,
embedding_provider,
chunk_size,
chunk_overlap,
- collection_id,
]
):
return jsonify(
{
"success": False,
- "error": "All configuration parameters are required including collection_id",
+ "error": "All configuration parameters are required (embedding_model, embedding_provider, chunk_size, chunk_overlap)",
}
), 400
@@ -685,25 +771,59 @@ def configure_rag():
settings.set_setting("local_search_chunk_size", int(chunk_size))
settings.set_setting("local_search_chunk_overlap", int(chunk_overlap))
- # Create new RAG service with new configuration
- new_rag_service = LibraryRAGService(
- username=session["username"],
- embedding_model=embedding_model,
- embedding_provider=embedding_provider,
- chunk_size=int(chunk_size),
- chunk_overlap=int(chunk_overlap),
+ # Save new advanced settings
+ settings.set_setting("local_search_splitter_type", splitter_type)
+ # Convert list to JSON string for storage
+ if isinstance(text_separators, list):
+ text_separators_str = json_lib.dumps(text_separators)
+ else:
+ text_separators_str = text_separators
+ settings.set_setting(
+ "local_search_text_separators", text_separators_str
+ )
+ settings.set_setting("local_search_distance_metric", distance_metric)
+ # Convert boolean to string for storage
+ settings.set_setting(
+ "local_search_normalize_vectors", str(normalize_vectors).lower()
)
+ settings.set_setting("local_search_index_type", index_type)
+
+ # If collection_id is provided, update that collection's configuration
+ if collection_id:
+ # Create new RAG service with new configuration
+ new_rag_service = LibraryRAGService(
+ username=session["username"],
+ embedding_model=embedding_model,
+ embedding_provider=embedding_provider,
+ chunk_size=int(chunk_size),
+ chunk_overlap=int(chunk_overlap),
+ splitter_type=splitter_type,
+ text_separators=text_separators
+ if isinstance(text_separators, list)
+ else json_lib.loads(text_separators),
+ distance_metric=distance_metric,
+ normalize_vectors=normalize_vectors,
+ index_type=index_type,
+ )
- # Get or create new index with this configuration
- rag_index = new_rag_service._get_or_create_rag_index(collection_id)
+ # Get or create new index with this configuration
+ rag_index = new_rag_service._get_or_create_rag_index(collection_id)
- return jsonify(
- {
- "success": True,
- "message": "Configuration updated. You can now index documents with the new settings.",
- "index_hash": rag_index.index_hash,
- }
- )
+ return jsonify(
+ {
+ "success": True,
+ "message": "Configuration updated for collection. You can now index documents with the new settings.",
+ "index_hash": rag_index.index_hash,
+ }
+ )
+ else:
+ # Just saving default settings without updating a specific collection
+ return jsonify(
+ {
+ "success": True,
+ "message": "Default embedding settings saved successfully. New collections will use these settings.",
+ }
+ )
except Exception as e:
logger.exception("Error configuring RAG")
diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.py
index f9d3ae1e04..60cf545b26 100644
--- a/src/local_deep_research/research_library/services/library_rag_service.py
+++ b/src/local_deep_research/research_library/services/library_rag_service.py
@@ -13,7 +13,6 @@ from pathlib import Path
from typing import Any, Dict, List, Optional
from langchain_core.documents import Document as LangchainDocument
-from langchain_text_splitters import RecursiveCharacterTextSplitter
from loguru import logger
from sqlalchemy import func
@@ -26,12 +25,13 @@ from ...database.models.library import (
EmbeddingProvider,
)
from ...database.session_context import get_user_db_session
+from ...embeddings.splitters import get_text_splitter
from ...web_search_engines.engines.search_engine_local import (
LocalEmbeddingManager,
)
from ...security.file_integrity import FileIntegrityManager, FAISSIndexVerifier
import hashlib
-from faiss import IndexFlatL2
+from faiss import IndexFlatL2, IndexFlatIP, IndexHNSWFlat
from langchain_community.vectorstores import FAISS
from langchain_community.docstore.in_memory import InMemoryDocstore
@@ -46,6 +46,11 @@ class LibraryRAGService:
embedding_provider: str = "sentence_transformers",
chunk_size: int = 1000,
chunk_overlap: int = 200,
+ splitter_type: str = "recursive",
+ text_separators: Optional[list] = None,
+ distance_metric: str = "cosine",
+ normalize_vectors: bool = True,
+ index_type: str = "flat",
embedding_manager: Optional["LocalEmbeddingManager"] = None,
):
"""
@@ -57,6 +62,11 @@ class LibraryRAGService:
embedding_provider: Provider type ('sentence_transformers' or 'ollama')
chunk_size: Size of text chunks for splitting
chunk_overlap: Overlap between consecutive chunks
+ splitter_type: Type of splitter ('recursive', 'token', 'sentence', 'semantic')
+ text_separators: List of text separators for chunking (default: ["\n\n", "\n", ". ", " ", ""])
+ distance_metric: Distance metric ('cosine', 'l2', or 'dot_product')
+ normalize_vectors: Whether to normalize vectors with L2
+ index_type: FAISS index type ('flat', 'hnsw', or 'ivf')
embedding_manager: Optional pre-constructed LocalEmbeddingManager for testing/flexibility
"""
self.username = username
@@ -64,16 +74,18 @@ class LibraryRAGService:
self.embedding_provider = embedding_provider
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
-
- # Initialize text splitter
- self.text_splitter = RecursiveCharacterTextSplitter(
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- length_function=len,
- separators=["\n\n", "\n", ". ", " ", ""],
+ self.splitter_type = splitter_type
+ self.text_separators = (
+ text_separators
+ if text_separators is not None
+ else ["\n\n", "\n", ". ", " ", ""]
)
+ self.distance_metric = distance_metric
+ self.normalize_vectors = normalize_vectors
+ self.index_type = index_type
# Use provided embedding manager or create a new one
+ # (Must be created before text splitter for semantic chunking)
if embedding_manager is not None:
self.embedding_manager = embedding_manager
else:
@@ -105,6 +117,18 @@ class LibraryRAGService:
settings_snapshot=settings_snapshot,
)
+ # Initialize text splitter based on type
+ # (Must be created AFTER embedding_manager for semantic chunking)
+ self.text_splitter = get_text_splitter(
+ splitter_type=self.splitter_type,
+ chunk_size=self.chunk_size,
+ chunk_overlap=self.chunk_overlap,
+ text_separators=self.text_separators,
+ embeddings=self.embedding_manager.embeddings
+ if self.splitter_type == "semantic"
+ else None,
+ )
+
# Initialize or load FAISS index for library collection
self.faiss_index = None
self.rag_index_record = None
@@ -169,6 +193,11 @@ class LibraryRAGService:
index_hash=index_hash,
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
+ splitter_type=self.splitter_type,
+ text_separators=self.text_separators,
+ distance_metric=self.distance_metric,
+ normalize_vectors=self.normalize_vectors,
+ index_type=self.index_type,
chunk_count=0,
total_documents=0,
status="active",
@@ -229,17 +258,48 @@ class LibraryRAGService:
f"Failed to load FAISS index: {e}, creating new one"
)
- # Create new FAISS index
+ # Create new FAISS index with configurable type and distance metric
logger.info(
- f"Creating new FAISS index with dimension {rag_index.embedding_dimension}"
+ f"Creating new FAISS index: type={self.index_type}, metric={self.distance_metric}, dimension={rag_index.embedding_dimension}"
)
- index = IndexFlatL2(rag_index.embedding_dimension)
+
+ # Create index based on type and distance metric
+ if self.index_type == "hnsw":
+ # HNSW: Fast approximate search, best for large collections
+ # M=32 is a good default for connections per layer
+ index = IndexHNSWFlat(rag_index.embedding_dimension, 32)
+ logger.info("Created HNSW index with M=32 connections")
+ elif self.index_type == "ivf":
+ # IVF requires training, for now fall back to flat
+ # TODO: Implement IVF with proper training
+ logger.warning(
+ "IVF index type not yet fully implemented, using Flat index"
+ )
+ if self.distance_metric in ("cosine", "dot_product"):
+ index = IndexFlatIP(rag_index.embedding_dimension)
+ else:
+ index = IndexFlatL2(rag_index.embedding_dimension)
+ else: # "flat" or default
+ # Flat index: Exact search
+ if self.distance_metric in ("cosine", "dot_product"):
+ # For cosine similarity, use inner product (IP) with normalized vectors
+ index = IndexFlatIP(rag_index.embedding_dimension)
+ logger.info(
+ "Created Flat index with Inner Product (for cosine similarity)"
+ )
+ else: # l2
+ index = IndexFlatL2(rag_index.embedding_dimension)
+ logger.info("Created Flat index with L2 distance")
+
faiss_index = FAISS(
self.embedding_manager.embeddings,
index=index,
docstore=InMemoryDocstore(), # Minimal - chunks in DB
index_to_docstore_id={},
- normalize_L2=True,
+ normalize_L2=self.normalize_vectors, # Use configurable normalization
+ )
+ logger.info(
+ f"FAISS index created with normalization={self.normalize_vectors}"
)
return faiss_index
diff --git a/src/local_deep_research/web/static/js/embedding_settings.js b/src/local_deep_research/web/static/js/embedding_settings.js
index cdc168b8e3..a2a29477d8 100644
--- a/src/local_deep_research/web/static/js/embedding_settings.js
+++ b/src/local_deep_research/web/static/js/embedding_settings.js
@@ -117,6 +117,24 @@ async function loadCurrentSettings() {
document.getElementById('chunk-overlap').value = settings.chunk_overlap;
}
+ // Set new advanced settings
+ if (settings.splitter_type) {
+ document.getElementById('splitter-type').value = settings.splitter_type;
+ }
+ if (settings.distance_metric) {
+ document.getElementById('distance-metric').value = settings.distance_metric;
+ }
+ if (settings.index_type) {
+ document.getElementById('index-type').value = settings.index_type;
+ }
+ if (settings.normalize_vectors !== undefined) {
+ document.getElementById('normalize-vectors').checked = settings.normalize_vectors;
+ }
+ if (settings.text_separators) {
+ // Convert array to JSON string for display
+ document.getElementById('text-separators').value = JSON.stringify(settings.text_separators);
+ }
+
// Load Ollama URL from global settings
loadOllamaUrl();
@@ -298,6 +316,22 @@ function renderIndexInfo(info) {
<span class="ldr-info-label">Chunk Overlap:</span>
<span class="ldr-info-value">${info.chunk_overlap} characters</span>
</div>
+ <div class="ldr-info-item">
+ <span class="ldr-info-label">Splitter Type:</span>
+ <span class="ldr-info-value">${info.splitter_type || 'recursive'}</span>
+ </div>
+ <div class="ldr-info-item">
+ <span class="ldr-info-label">Distance Metric:</span>
+ <span class="ldr-info-value">${info.distance_metric || 'cosine'}</span>
+ </div>
+ <div class="ldr-info-item">
+ <span class="ldr-info-label">Index Type:</span>
+ <span class="ldr-info-value">${info.index_type || 'flat'}</span>
+ </div>
+ <div class="ldr-info-item">
+ <span class="ldr-info-label">Normalize Vectors:</span>
+ <span class="ldr-info-value">${info.normalize_vectors !== undefined ? (info.normalize_vectors ? 'Yes' : 'No') : 'Yes'}</span>
+ </div>
<div class="ldr-info-item">
<span class="ldr-info-label">Total Chunks:</span>
<span class="ldr-info-value">${info.chunk_count}</span>
@@ -333,11 +367,35 @@ async function handleConfigSubmit(event) {
}
}
+ // Get text separators and parse JSON
+ let textSeparators;
+ const textSeparatorsValue = document.getElementById('text-separators').value.trim();
+ if (textSeparatorsValue) {
+ try {
+ textSeparators = JSON.parse(textSeparatorsValue);
+ if (!Array.isArray(textSeparators)) {
+ showError('Text separators must be a JSON array');
+ return;
+ }
+ } catch (e) {
+ showError('Invalid JSON format for text separators');
+ return;
+ }
+ } else {
+ // Use default if empty
+ textSeparators = ["\n\n", "\n", ". ", " ", ""];
+ }
+
const formData = {
embedding_provider: provider,
embedding_model: document.getElementById('embedding-model').value,
chunk_size: parseInt(document.getElementById('chunk-size').value),
- chunk_overlap: parseInt(document.getElementById('chunk-overlap').value)
+ chunk_overlap: parseInt(document.getElementById('chunk-overlap').value),
+ splitter_type: document.getElementById('splitter-type').value,
+ distance_metric: document.getElementById('distance-metric').value,
+ index_type: document.getElementById('index-type').value,
+ normalize_vectors: document.getElementById('normalize-vectors').checked,
+ text_separators: textSeparators
};
console.log('📋 Form data:', formData);
diff --git a/src/local_deep_research/web/templates/pages/embedding_settings.html b/src/local_deep_research/web/templates/pages/embedding_settings.html
index 06f659d9f8..1059a23712 100644
--- a/src/local_deep_research/web/templates/pages/embedding_settings.html
+++ b/src/local_deep_research/web/templates/pages/embedding_settings.html
@@ -87,6 +87,63 @@
</div>
</div>
+ <div class="ldr-form-row">
+ <div class="ldr-form-group ldr-col-md-6">
+ <label for="splitter-type">Text Splitter Type</label>
+ <select id="splitter-type" class="ldr-form-control">
+ <option value="recursive">Recursive (Default - uses separators)</option>
+ <option value="token">Token-based (Good for LLM context)</option>
+ <option value="sentence">Sentence-based (Clean boundaries)</option>
+ <option value="semantic">Semantic (Smart grouping - slower)</option>
+ </select>
+ <small class="ldr-form-text ldr-text-muted">
+ How documents are split into chunks. Semantic uses AI to find natural breakpoints (slower but smarter)
+ </small>
+ </div>
+ <div class="ldr-form-group ldr-col-md-6">
+ <label for="distance-metric">Distance Metric</label>
+ <select id="distance-metric" class="ldr-form-control">
+ <option value="cosine">Cosine Similarity (Recommended)</option>
+ <option value="l2">Euclidean Distance (L2)</option>
+ <option value="dot_product">Dot Product</option>
+ </select>
+ <small class="ldr-form-text ldr-text-muted">
+ Cosine similarity recommended for text embeddings
+ </small>
+ </div>
+ <div class="ldr-form-group ldr-col-md-6">
+ <label for="index-type">Index Type</label>
+ <select id="index-type" class="ldr-form-control">
+ <option value="flat">Flat (Exact search, &lt;10K docs)</option>
+ <option value="hnsw">HNSW (Fast, large collections)</option>
+ <option value="ivf">IVF (Balanced, updates)</option>
+ </select>
+ <small class="ldr-form-text ldr-text-muted">
+ HNSW recommended for &gt;10K documents (50-60× faster)
+ </small>
+ </div>
+ </div>
+
+ <div class="ldr-form-group">
+ <label>
+ <input type="checkbox" id="normalize-vectors" checked>
+ Normalize vectors (L2)
+ </label>
+ <small class="ldr-form-text ldr-text-muted" style="display: block; margin-left: 25px;">
+ <i class="fas fa-info-circle"></i> Recommended: Ensures fair comparison regardless of document length
+ </small>
+ </div>
+
+ <div class="ldr-form-group">
+ <label for="text-separators">Text Separators (Advanced)</label>
+ <textarea id="text-separators" class="ldr-form-control" rows="3"
+ placeholder='["\n\n", "\n", ". ", " ", ""]'></textarea>
+ <small class="ldr-form-text ldr-text-muted">
+ JSON array of separators. Default works for 80% of use cases.
+ For code: add language-specific separators like "\nclass", "\ndef"
+ </small>
+ </div>
+
<button type="submit" class="ldr-btn ldr-btn-primary">
<i class="fas fa-save"></i> Save Default Settings
</button>