Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion DashAI/back/api/api_v1/endpoints/generative_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
)
from DashAI.back.dependencies.downloads.nested import missing_downloads
from DashAI.back.models.base_generative_model import BaseGenerativeModel
from DashAI.back.services.RAG.config_equality import configs_equal
from DashAI.back.services.workflows import (
WorkflowConflictError,
WorkflowSessionError,
Expand Down Expand Up @@ -1306,7 +1307,7 @@ async def get_parameter_history_entry(
for key in curr_params:
old_val = prev_params.get(key)
new_val = curr_params[key]
if old_val != new_val:
if not configs_equal(old_val, new_val):
changes.append(
{
"parameter": key,
Expand Down
11 changes: 9 additions & 2 deletions DashAI/back/api/api_v1/endpoints/rag.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from DashAI.back.core.utils import localize
from DashAI.back.dependencies.database.models import GenerativeSession
from DashAI.back.job.RAG_index_job import RAGIndexJob
from DashAI.back.models.RAG.exceptions import RAGPipelineConfigError
from DashAI.back.models.RAG.RAG_constants import RAG_PARAM_KEYS
from DashAI.back.services.RAG.chunking_presets import (
get_chunking_presets as resolve_chunking_presets,
Expand All @@ -31,6 +32,7 @@
get_retriever_presets as resolve_retriever_presets,
)
from DashAI.back.services.RAG.session_configuration_service import (
RAGSessionNotFoundError,
SessionConfigurationService,
)
from DashAI.back.services.RAG.session_defaults_service import build_default_parameters
Expand Down Expand Up @@ -165,17 +167,22 @@ def session_configuration(
Raises
------
HTTPException
404 if the session does not exist.
404 if the session does not exist, 422 if its stored configuration is
malformed.
"""
with session_factory() as db:
try:
configuration = SessionConfigurationService(
db, component_registry
).get_configuration(session_id)
except ValueError as e:
except RAGSessionNotFoundError as e:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=str(e)
) from e
except (ValueError, RAGPipelineConfigError) as e:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e)
) from e
return localize(configuration, accept_language)


Expand Down
8 changes: 8 additions & 0 deletions DashAI/back/converters/hugging_face/text_embedding/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@

TRUNCATE = "truncate"
AGGREGATE = "aggregate"
#: Schema param name of the number of texts encoded together.
BATCH_SIZE_FIELD = "batch_size"
#: Schema param name of the device the checkpoint runs on.
DEVICE_FIELD = "device"
SPECIAL_TOKENS = 2
#: Keeps a vector of zeros from dividing by zero while normalizing.
NORMALIZATION_EPSILON = 1e-12
Expand Down Expand Up @@ -245,6 +249,10 @@ class TextEmbeddingConverter(AdvancedPreprocessingConverter, PretrainedTool):
HF_IGNORE_PATTERNS = [*HFDownloadableMixin.HF_IGNORE_PATTERNS, "pytorch_model.bin"]
QUERY_PROMPT: Optional[str] = None
PASSAGE_PROMPT: Optional[str] = None
#: The batch size and the device only trade memory and speed for hardware
#: and never change the vectors, so they stay out of the persistence
#: signature of any retriever that embeds with this converter.
NON_PERSISTENT_PARAMS = (BATCH_SIZE_FIELD, DEVICE_FIELD)

def pretrained(self) -> Any:
"""Return the loaded checkpoint, using the model cache inside a job.
Expand Down
81 changes: 68 additions & 13 deletions DashAI/back/job/RAG_index_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,78 @@
from typing import Dict

from kink import di, inject
from sqlalchemy.orm import Session

from DashAI.back.dependencies.database.models import GenerativeSession
from DashAI.back.dependencies.registry.component_registry import ComponentRegistry
from DashAI.back.job.base_job import BaseJob, JobError
from DashAI.back.models.RAG.RAG_constants import RAG_PARAM_KEYS as _RAG_PARAM_KEYS
from DashAI.back.models.RAG.RAG_pipeline import RAGPipelineConfig
from DashAI.back.services.RAG.cleanup_service import run_post_index_cleanup
from DashAI.back.services.RAG.prompt_service import PromptService
from DashAI.back.services.RAG.session_params import filter_pipeline_params
from DashAI.back.services.RAG.session_validation_service import (
SessionValidationService,
)
from DashAI.back.services.RAG.setup_service import SetupService
from DashAI.back.services.RAG.setup_service import IndexResult, SetupService

log = logging.getLogger(__name__)


def _cleanup_and_summarize(
db: Session,
component_registry: ComponentRegistry,
session_id: int,
result: IndexResult,
rag_path: str,
) -> Dict[str, int]:
"""Run the post-index cleanup of a built index, then summarise it.

The ids are read before the cleanup, which may roll the session back. A
cleanup failure is logged by :func:`run_post_index_cleanup` and never fails
the job, since the index is complete by now.

Parameters
----------
db : Session
Session the cleanup runs in.
component_registry : ComponentRegistry
Component registry, passed through to the cleanup.
session_id : int
The session that was just indexed.
result : IndexResult
The index the build returned, before it is released.
rag_path : str
The RAG storage root (``RAG_PATH``).

Returns
-------
Dict[str, int]
``{"chunk_set_id": int, "total_chunks": int}`` of the index.
"""
chunk_set_id = result.chunk_set_id
total_chunks = result.total_chunks
root_bridge_id = result.retriever.db_record_id
reranker_bridge_id: int | None = None
if result.reranker is not None:
reranker_bridge_id = result.reranker.db_record_id
run_post_index_cleanup(
db,
component_registry,
session_id,
root_bridge_id,
rag_path,
reranker_bridge_id,
)
log.debug(
"Indexed session %d: chunk set %d, %d chunks",
session_id,
chunk_set_id,
total_chunks,
)
return {"chunk_set_id": chunk_set_id, "total_chunks": total_chunks}


class RAGIndexJob(BaseJob):
"""Chunks, embeds and fits the retriever for one RAG session.

Expand Down Expand Up @@ -96,6 +154,8 @@ def run(self) -> Dict[str, int]:
session = db.get(GenerativeSession, session_id)
if not session:
raise JobError(f"Session {session_id} not found in DB.")
if session.parameters is None:
raise JobError(f"Session {session_id} has no stored parameters.")

# Whitelist-only, same as RAGJob: session parameters may carry
# keys the pipeline config would reject. Prompts are stored in
Expand All @@ -104,11 +164,9 @@ def run(self) -> Dict[str, int]:
db, component_registry
).materialize_session_parameters(
session_id,
dict(session.parameters or {}),
dict(session.parameters),
)
clean_params = {
k: v for k, v in raw_params.items() if k in _RAG_PARAM_KEYS
}
clean_params = filter_pipeline_params(raw_params, _RAG_PARAM_KEYS)
if not (clean_params.get("documents") or []):
raise JobError(f"Session {session_id} has no documents to index.")

Expand Down Expand Up @@ -136,16 +194,13 @@ def run(self) -> Dict[str, int]:
progress=self.report_progress,
)
try:
log.debug(
"Indexed session %d: chunk set %d, %d chunks",
return _cleanup_and_summarize(
db,
component_registry,
session_id,
result.chunk_set_id,
result.total_chunks,
result,
config["RAG_PATH"],
)
return {
"chunk_set_id": result.chunk_set_id,
"total_chunks": result.total_chunks,
}
finally:
SetupService.release_index(result)
except JobError:
Expand Down
Loading
Loading