Knowledge Base¶
src.domains.knowledge_base.endpoints
¶
REST API endpoints for Knowledge Base creation and RAG attachment to LLMs.
Atomic endpoints following REST principles. Each endpoint delegates business logic to services.
Architecture
Endpoints -> Services -> Repository -> Database
Endpoints
GET /knowledge_base/{llm_id}/status - Poll KB job status POST /knowledge_base/create - Create new KB assistant or update existing
create_knowledge_base(payload, background_tasks, db=Depends(get_db))
¶
Create new Knowledge Base assistant or update existing one.
Decision tree: - If base LLM has NO KB attached: Create new specialized LLM + KB - If base LLM HAS KB attached: Update existing KB with new documents
A background task then ingests the documents asynchronously (extraction → chunking → embeddings → vector store); the polled status endpoint reports progress and errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
KnowledgeBaseCreate
|
Request body with selectedModel, modelName, description, paths. |
required |
background_tasks
|
BackgroundTasks
|
FastAPI background task queue. |
required |
db
|
Session
|
Database session. |
Depends(get_db)
|
Returns:
| Name | Type | Description |
|---|---|---|
KnowledgeBaseResponse |
msg and model_id |
Raises:
| Type | Description |
|---|---|
InvalidInputException
|
If validation fails. |
KnowledgeBaseNotFoundException
|
If base LLM not found. |
DatabaseException
|
If KB creation fails. |
Source code in backend/src/domains/knowledge_base/endpoints.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | |
get_embedding_model_status()
¶
On-disk presence of the KB embedding model + any in-flight download.
get_kb_job_status(llm_id, db=Depends(get_db))
¶
Poll Knowledge Base job status with automatic cleanup for failed jobs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm_id
|
int
|
Specialized LLM ID created during KB creation. |
required |
db
|
Session
|
Database session. |
Depends(get_db)
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
status, status_updated_at, error_message |
Raises:
| Type | Description |
|---|---|
KnowledgeBaseNotFoundException
|
If KB job not found. |
DatabaseException
|
If error fetching status. |
Source code in backend/src/domains/knowledge_base/endpoints.py
post_embedding_model_download()
¶
Kick off the embedding-model download in the background (idempotent).
src.domains.knowledge_base.schemas
¶
Pydantic validation schemas for Knowledge Base creation and status responses.
Defines data transfer objects for Knowledge Base assistant creation workflow. Schemas validate document paths, base model selection, and assistant metadata.
Example
from src.domains.knowledge_base.schemas import KnowledgeBaseCreate import requests
payload = KnowledgeBaseCreate( paths=["/uploads/report1.pdf", "/uploads/report2.txt"], selectedModel=42, modelName="Financial Assistant", description="Q1-Q4 2024 earnings reports" ) response = requests.post("/knowledge_base/create", json=payload.model_dump())
KnowledgeBaseCreate
¶
Bases: BaseModel
Request schema for creating or updating a Knowledge Base assistant.
Attributes:
| Name | Type | Description |
|---|---|---|
paths |
List[str]
|
List of absolute file paths to PDF/TXT documents to ingest. |
selectedModel |
int
|
Database ID of base LLM to specialize with KB attachment. |
modelName |
str
|
Name for the new specialized assistant (e.g., "Financial Reports Bot"). |
description |
str
|
Optional user annotation describing the KB's purpose or domain. |
Example
kb_req = KnowledgeBaseCreate( ... paths=["/uploads/q1.pdf", "/uploads/q2.pdf"], ... selectedModel=42, ... modelName="Earnings Reports Assistant", ... description="2024 Q1-Q4 financial data" ... )
KnowledgeBaseResponse
¶
Bases: BaseModel
Response schema for KB creation endpoint with async processing confirmation.
Attributes:
| Name | Type | Description |
|---|---|---|
msg |
str
|
Human-readable status message (e.g., "Knowledge Base Assistant is being created."). |
model_id |
int
|
Database ID of the newly created specialized LLM (poll /kb/{model_id}/status). |
Example
response = KnowledgeBaseResponse( ... msg="Knowledge Base Assistant is being created.", ... model_id=108 ... )
Client polls GET /knowledge_base/108/status until status="completed"¶
src.domains.knowledge_base.services
¶
Business logic layer for Knowledge Base domain.
Implements service pattern for Knowledge Base operations: KB/assistant lifecycle, job state machine, and background ingestion orchestration.
Ingestion pipeline (per file, background task):
SHA-256 → dedup against the KB's KnowledgeDocument rows → register the
document → extract (DocumentReader, services stay format-agnostic) →
pending_vision stops here (image/scanned PDF, indexed by the OCR/VLM
tiers of a later release) → 3-pass chunking → hybrid vector store
(rag.kb_chunks). Per-file failures mark THAT document failed and
the run continues; the job only fails when nothing could be ingested.
Classes:
| Name | Description |
|---|---|
KB_Service |
Business logic for KB creation, updates, and job tracking. |
Architecture
Endpoints → Services → Repository → Database ↓ src.ingestion (DocumentReader → chunking → vector store)
KB_Service()
¶
Business logic for Knowledge Base operations.
Coordinates KB creation, updates, document processing, and background tasks.
Source code in backend/src/domains/knowledge_base/services.py
create_kb_assistant(db, base_llm_id, model_name, description, file_paths)
¶
Create new Knowledge Base assistant (database setup only).
Creates specialized LLM, KnowledgeBase, and KBJob entities. Does NOT process documents — that's done in the background task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Session
|
Database session. |
required |
base_llm_id
|
int
|
Base LLM ID to specialize from. |
required |
model_name
|
str
|
Name for specialized assistant. |
required |
description
|
str
|
Description for specialized assistant. |
required |
file_paths
|
List[str]
|
List of file paths to process. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[int, int]
|
Tuple of (specialized_llm_id, kb_job_id) for background task. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If base LLM not found or not local. |
Source code in backend/src/domains/knowledge_base/services.py
get_kb_job_status(db, llm_id)
¶
Get KB job status with automatic cleanup for failed jobs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Session
|
Database session. |
required |
llm_id
|
int
|
Specialized LLM ID (new_model_id in KBJob). |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with status, updated_at, and error_message. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If KB job not found. |
Source code in backend/src/domains/knowledge_base/services.py
process_and_index_documents(db, kb_job_id, file_paths, is_update=False)
¶
Ingest documents into the KB's vector store (background task).
Per-file pipeline — see module docstring. Each file commits on its own: the document row must be VISIBLE to the vector store's separate connection (FK), and progress survives an interruption.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Session
|
Database session (a fresh SessionLocal in background tasks). |
required |
kb_job_id
|
int
|
KBJob ID to track progress. |
required |
file_paths
|
List[str]
|
List of file paths to process. |
required |
is_update
|
bool
|
True if updating existing KB, False if creating new. |
False
|
Source code in backend/src/domains/knowledge_base/services.py
update_existing_kb(db, base_llm_id, file_paths)
¶
Queue update for existing KB with new documents (database setup only).
Creates KBJob for update operation. Does NOT process documents - that's done in background task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Session
|
Database session. |
required |
base_llm_id
|
int
|
Base LLM ID with existing KB attachment. |
required |
file_paths
|
List[str]
|
List of new file paths to add. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[int, int]
|
Tuple of (base_llm_id, kb_job_id) for background task. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If LLM not found or KB not attached. |