- Organize architecture, specifications, plans, and guides into dedicated subdirectories under docs/ - Remove legacy and duplicate documents from data/documents/ - Update AGENTS.md, README.md, and agent skills to target canonical docs paths
24 KiB
RAG Assistant — Phase 1 Implementation Guide
Version 1.3 · 2026-10-07 · Current Live document MVP implementation baseline; planned mechanisms are not completion evidence.
1. Purpose and authority
Implement the conditional four-day Live document MVP in
RAG-AI-Phase1-Delivery-Plan.md. API/database specifications govern their
contracts. The English RAG-Phase1-MVP-Scenarios.md supplies acceptance
walkthroughs; the older Persian report is historical context.
One organization, pre-created users, one API instance and one separate worker. Reuse ingestion Phases 1-4, including the current hosted embedding/staging implementation and reviewed repairs. Phase 5 worker/publication/retry and retained review/resume backend services, plus Phase 6 ingestion validation/handoff, are implemented. Authenticated D06/D07 transport and HTTP/search/Live/UI integrations remain pending. The four supplied files are required examples, not the accepted corpus or a filename allowlist. New documents within declared format/structure/resource limits must run without developer changes.
2. Decisions for this implementation
| Topic | Current MVP decision |
|---|---|
| Backend | Modular FastAPI API and separate worker from the same codebase |
| Framework | LangChain for retriever/tool integration; keep provider-neutral application services |
| Existing embeddings | Preserve EmbeddingProvider.embed, OpenAICompatibleEmbeddings and stage_document; a thin Embeddings wrapper is optional |
| UI | Same-origin HTTPS login plus one voice workspace with an admin Documents area |
| Identity | Opaque cookie sessions, admin/user roles, owned voice conversations; no signup |
| Jobs | PostgreSQL polling, current-claim lease fencing and complete atomic publication |
| Upload | New bounded PDF/DOCX/JPEG/PNG/Markdown documents; unknown future total count |
| QC | Retain exact review candidates, evidence-bound admin decisions and same-job retry; no new document state |
| Retrieval | Scoped pgvector semantic search plus exact normalized identifiers; reranker/ANN conditional on measured need |
| Voice | Direct Gemini Live audio over backend WSS; shared LangChain knowledge tool |
| Evidence | Current-session provider transcripts/sources; durable owned session/tool diagnostics |
| Deferred | Full text chat/history, settings editor, rich management/delete UI, recording, seamless reconnect, CTI |
| Settings | Fixed server profiles and seeded instruction/name; retain revisions and expose read-only capabilities |
3. Modules and ports
| Module / path | Responsibility |
|---|---|
app/api/v1/ |
DTOs, cookie/Origin/CSRF validation and safe HTTP errors |
modules/identity/ |
Login, sessions and trusted actor context |
modules/documents/ |
Existing intake/extraction/chunking/embedding; review, status, retry and selection |
modules/knowledge/ |
One scoped search/evidence service and bounded query embedding |
modules/conversations/ |
Minimal owned voice conversation identity/epoch; text execution deferred |
modules/live/ |
Session reservation, audio relay, trusted tool dispatch, cancellation and lifecycle |
infrastructure/ |
Existing SQL/file/provider adapters plus a small LangChain integration boundary |
app/worker.py |
Fenced claim, heartbeat, processing, review interruption, publication and recovery |
Application services retain provider-neutral values. LangChain Documents carry faithful chunk text plus document_id/chunk_id/title/location metadata, but neither a Document nor model metadata grants scope. A custom retriever invokes the shared search service with authenticated backend context. The registered search_knowledge tool exposes only query and optional resolved context.
If a LangChain component requires Embeddings, map embed_query and bounded embed_documents to the existing provider. Respect per-input/token/batch limits, frozen model/dimension/preprocessing identity and float32 validation. Handle empty document lists at the wrapper boundary; do not call an adapter that requires a nonempty batch. Bound aggregate requests and preserve input order. Do not add internal retries, truncation, fresh normalization or provider defaults. Async calls must run existing blocking I/O off the audio/event loop with bounded concurrency/deadlines; cancellation cannot recall a blocking network request.
Ingestion continues to use stage_document and its publication contract. Do not replace it with a framework vector-store insertion helper that bypasses staging, authorization, IDs, profile checks or atomic publication. A custom retriever is sufficient; using LangChain does not require a new vector database, LangGraph rewrite or a separate text-model inference on each audio turn.
4. Implementation order and deliverables
| Work package | Work and completion proof |
|---|---|
| WP1 - Early provider proof | Real Persian audio/transcripts plus one backend-executed tool call on target network; configure fixed funded profiles |
| WP2 - Identity and upload | Secure sessions and bounded multipart transport reuse intake; new upload persists and duplicate key replays |
| WP3 - Worker and review | Continue ingestion Phase 5; fence claims, candidates/decisions, artifact reuse, retries and complete publication |
| WP4 - Shared search | Compatible query vectors, exact identifier matching and eligibility joins; independently marked evidence evaluation |
| WP5 - LangChain and Live | Expose the same search tool, reserve owned sessions, relay PCM, correlate tools/transcripts/sources and suppress cancellation |
| WP6 - UI/deployment/acceptance | Minimal workspace, all four examples plus unseen uploads, provider/restart/revocation checks and actual HTTPS rehearsal |
Map these packages to Days 1-4 in the delivery plan. WP1 is an early risk gate, not work postponed until the other packages finish. A developer can progress independent worker/API work while provider validation is unresolved; no agent delegation, parallel staffing or completed proof is assumed.
Recommended first implementation task: complete WP3 using existing Phases 1-4 and forward schema changes for retained review state, while running WP1 early. Keep the original migration byte-for-byte and report actual check outcomes.
5. Identity and request context
Login verifies a stored password hash using a maintained password-hashing implementation. Generate an unpredictable session token; store only its hash. Cookie rag_session is HttpOnly, Secure and SameSite=Lax. Restrict Origin on login and mutations. Return a session CSRF token after login and through /me; require X-CSRF-Token on authenticated mutations. Configure session expiry at deployment; no business retention period is assumed here.
Resolve (user_id, organization_id, role) exclusively from the session. Check owner for conversation/turn/live endpoints, including administrator requests: admin status does not automatically grant access to other users' chats. Return 404 for hidden resource IDs, 403 for an authenticated non-admin calling an admin-only collection operation. Rate-limit login/provider operations with conservative single-instance limits.
6. Document upload and ingestion
- Authenticate admin and validate upload idempotency key, bounded bytes, actual type/signature/package structure and safe display title/filename. Never read an unbounded multipart body or use a filename as a storage path.
- Reuse the intake service/ports with bounded temporary input where needed. Preserve the replay digest of bytes and normalized title; no new model/profile or client organization fields enter the request. Repeated same key/input returns the original document/job. A new key creates an independent document.
- Save the immutable original and create document/job/audit in a short transaction. Hash/reconcile files outside long transactions. New document is inactive.
- Claim eligible work with token/lease, attempts and documented lock order. Provider work runs outside long transactions. Heartbeat throughout slow calls.
- Dispatch existing frozen-profile extraction/normalization/chunking and embedding components. Validate original checksum and actual provider identity. A legacy profile is dispatched explicitly, never silently reinterpreted.
- Retain exact extraction output for review/reuse, then stage every embedding. The current PageBlockExtractor requires review for PDF pages and vision output; this is an actual implementation gate, not an optional UI decoration.
- Publish all chunks and ready/succeeded state in one fenced transaction. Verify token, unexpired lease, original/profile, non-deletion, complete vectors, ordinals and eligibility; keep is_active=false. Never republish a ready document.
6.1 Exact-output review and resume
A ReviewRequired outcome is mapped by the new worker to a bounded, non-automatically-retried failed attempt with EXTRACTION_REVIEW_REQUIRED. It is distinct from a malformed/permanently unreadable source. Persist trusted references to the exact bounded image/block candidate, source/extraction identity, locator, digest and progress under the current claim before releasing the lease. Unreviewed candidates are not complete validated artifacts and cannot be indexed. Crash recovery must not attach uncommitted or stale candidates.
D06 shows retained candidates to the admin. D07 records approval/rejection of the exact evidence digest and required checks. New OCR output has a different review identity and requires a new decision. Server validates/recomputes digests; client supplied text, paths, profile identity and reviewer identity are forbidden. Use job/document locks and current failed-candidate identity for decisions. Decisions neither activate nor mark a document ready.
After approval, D04 requeues the same eligible job once per key. Resume using the retained inspected page/block output; do not rerun vision and assume the new response was approved. Additional pages may need further review. Rejecting a candidate keeps it failed/unsearchable with zero publication. Never hold a lease waiting for a person. No waiting_review lifecycle status is introduced.
The implementation must persist complete extraction independently of vectors. On validated complete-artifact reuse, check original digest, extraction identity, coverage, warnings and trusted attachment. Chunk/embedding changes alone are not a reason to repeat OCR. Partial review candidates can resume QC but cannot bypass complete-artifact validation or create partial publication.
6.2 Factual FAQ gate
Existing chunking requires approved_factual for Q&A. New uploaded FAQs need an explicit admin approval route, not a hardcoded filename exemption or CLI-only flag. D06 exposes factual-corpus review bound to the extraction digest and groups. D07 can record whole Q&A groups excluded because they are behavioral scenarios, placeholders or unapproved facts. Never split a question from its answer.
Preserve the complete faithful extraction/original. Store an inclusion decision separately with reviewer, digest and excluded group IDs. Only approved factual groups form chunk drafts, with original locators; placeholders cannot become answers by virtue of approval. If no reliable groups remain, fail visibly. Existing validation stays enabled; any new manifest-aware preparation boundary requires regression tests. Numeric/source fidelity and authority are distinct.
Factual preparation validates the whole retained source structure before selecting groups. Explicit heading ancestry associates governing headings and introductory conditions with each descendant Q&A pair; existing whole-group context stays exclusive to that pair. Preserve conditions, negation, exceptions and their real locators in every affected draft. Ambiguous unheaded preambles, detached prose or unresolved relationships fail visibly instead of becoming unrestricted answers. Factual review exposes that context from the same immutable complete artifact. Reviewer identity/checks/note are bounded review metadata, not machine quality warnings; administrator prose never changes extraction readability decisions.
6.3 Retry, recovery and capacity
Transient network/rate-limit errors use bounded backoff/jitter and the existing retry budget. Permanent malformed input fails immediately. Review-required work waits as failed for a valid decision, without automatic provider loops. Manual retry resets attempts and increments retry_generation on the same job once per key. Source modifications require a new upload.
Maintain file reconciliation and safe redacted diagnostics. Unknown document count requires durable backlog, pagination, disk/quota observation and bounded processing/admission. Configured defaults are deployment choices, not capacity proof. Physical purging and retention periods remain unresolved.
7. Selection, revisions and revocation
organization_settings has three counters: revision for assistant configuration, knowledge_revision for selected-set changes, and access_epoch for knowledge removals. All begin at 1.
Selection update locks the settings row, checks expected_revision against knowledge_revision, validates every selected document is ready/not deleted, and updates the selected flags atomically. If the set changes, increment knowledge_revision. If any document is removed, increment access_epoch too. A no-op preserves counters. Activation alone does not invalidate old conversations; new turns use the current selected set.
Each conversation records access_epoch on creation. For simple safe Phase 1 revocation, any active-document removal invalidates ALL older organization conversations for new turns. Close running live sessions and fail/stop running text turns; preserve old history for authorized viewing. UI asks the user to start a new conversation. No full history is copied into it.
Use settings-row serialization when creating/finalizing turns and initiating live sessions. Text finalization rechecks epoch while holding that row lock; commits before a removal are historical answers, and commits after it must fail as stale. Live tool results are rechecked before sending. Direct audio already sent cannot be recalled; provider close is best effort and must be tested. Logout and session expiry also close owned active live sessions.
8. Deferred text turn execution
This section preserves the follow-up text contract; it is not required by the current Live MVP. No new public text chat or durable message history is required. The internal query harness invokes the SAME scoped search service without implementing this turn lifecycle.
In that follow-up milestone, the UI creates a mode=text conversation, then sends POST /chat with a UUID client_request_id.
In a short transaction: authenticate, lock settings/conversation consistently, verify active conversation/current epoch, resolve the request key, reject another running turn, insert running turn and user message. Set a processing deadline. Then release database locks before provider calls.
Build model context from completed authorized turns within the token budget. Add assistant instruction, tool schema and current question. Treat document text as untrusted evidence, not instructions. A search query argument contains only query text; the server determines organization and selection.
Loop within configured tool-call and time limits. Store normalized tool results and correlate call IDs. Assign source references uniquely across the entire text turn (not separately as S1 for every search); remap tool evidence before returning it to the model. Persist the actual organization instruction in the execution snapshot so a later settings change does not destroy traceability. For substantive document claims, require current search evidence. Validate each cited source against evidence returned during this turn. Structural validation does not prove semantic accuracy; the reference evaluation set checks factual support.
At completion recheck epoch, write assistant message/citations and terminal turn status in one transaction. Terminal statuses: answered, needs_clarification, insufficient_information, failed. Search/provider errors produce failed, not insufficient_information.
If the browser times out, it queries the turn by client request ID. Retrying the same payload returns the existing result or 202 running state. Same key plus different payload returns 409. No automatic regeneration after an ambiguous provider timeout. An interrupted run is marked failed; a new user retry uses a new key. On API restart mark its interrupted running turns failed; periodic deadline cleanup handles stalled tasks. This is intentionally simpler than a durable text job queue.
9. Live lifecycle
Create a fresh owned mode=voice conversation. Persist a session reservation before remote setup, then connect the backend to direct Gemini Live WSS, install Persian instructions and search_knowledge, and enable provider transcription. The browser receives an application stream path, never SDP or a persistent provider credential. Authenticate/validate trusted Origin, owner/auth session and access epoch at the stream handshake.
Use the SAME search service and fixed compatible embedding profile as the internal text-query harness and any later text chat. Dispatch search_knowledge through the LangChain integration boundary; do not route native audio through the old text agent. Provider call IDs/hash deduplicate tool events; running duplicates wait, completed duplicates revalidate scope before replay, changed payloads conflict. Store recent evidence for polling. Live answers may use evidence directly; no mandatory extra text-model call. Current-session transcript/source events are specified in API Section 7; durable full voice transcripts are deferred. Persist voice tool records without a dependency on deferred text turns/messages/citations.
States: creating → connecting → connected → closed; any nonterminal state may fail/close. Adapter-confirmed setup defines connected, not client assertions. Use deadlines, bounded audio buffers and TTL; provider calls occur outside database transactions. Restart marks previous nonterminal sessions failed and attempts cleanup.
Follow-up questions resolve the last unambiguous document/article, but retrieve fresh evidence. New topics clear old anchors; ambiguous references prompt clarification. Missing/conflicting support is disclosed; tool/provider failure is a technical error. On interruption flush playback, mark output partial/interrupted, cancel outstanding work where possible and discard late results. Logout/expiry/removal close sessions. Reconnect requires reconciliation and a new session; provider context recovery is not promised.
Capture/resample client audio and convert returned PCM for playback as specified in architecture Section 8.5. Test real Persian names, dates, percentages and amounts. CTI/Asterisk is outside this web MVP and would need an explicitly commissioned audio bridge.
10. Internal search contract
Use the canonical proposed search_knowledge schema/outcomes in API catalog Section 7.2. Required query plus optional resolved context; no model-supplied scope. Proposed backend defaults remain top 5 chunks and maximum 12000 evidence characters, to calibrate against the corpus.
Return actual document/chunk identities and nullable source locators. Distinguish ok, no_evidence, error; similarity alone does not prove sufficient evidence. Use semantic pgvector search plus normalized exact identifier/date/article matching as the initial baseline. Full hybrid fusion, reranking and ANN are conditional on measured failures; adding them must preserve all eligibility checks and the deadline must be re-estimated if required. No new vector store.
Queries and all text-derived chunks share a compatible fixed profile. A changed embedding model requires a controlled isolated reindex/cutover; no ready-document republishing through retry or content versioning. Preserve extracted text so OCR need not repeat.
Separate approved factual FAQs from behavioral evaluation/configuration and live-data placeholders. Retrieved instructions are untrusted source data. Without approved live-data tools, explicitly state that current tariffs, land availability, balances and case status cannot be verified; offer an authorized organizational contact/process without claiming an automated transfer.
11. Deployment and configuration
Deploy UI/reverse proxy, one API process, one worker process and PostgreSQL. Mount persistent originals, extraction artifacts and database volumes. Configure HTTPS, cookie domain/origin, provider secrets, approved file formats, size cap, model profile IDs, embedding dimension, tool limits, request deadlines, job lease/retry budget and session TTL. Do not commit secrets. File-size/retention/session durations are deployment choices, not silently approved organization policy.
Readiness checks DB/schema/vector availability and writable/available required storage; report worker heartbeat age as a degraded ingestion indicator. For the single-host release, the worker can update a small heartbeat file on the shared durable volume; a separate heartbeat table is unnecessary. Liveness does not call AI providers. Provider failure must not make login/history unavailable by design. Log request/turn/job/session IDs and redacted error categories; avoid document bodies, audio payloads, prompts, cookies and keys.
12. Tests and handoff
| Test group | Required evidence |
|---|---|
| Access/replay | Admin/user permissions, voice ownership, Origin/CSRF, forged scope, upload/review/retry/create replay and changed-payload conflict |
| Worker/database | Real PostgreSQL claims, expired/stale leases, heartbeat, failed final batch, rollback, ambiguous commit and restart without duplicate publication |
| Review/FAQ | Trusted retained candidate/digest, stale approval rejection, whole-group inclusion, resume same inspected output and zero chunks before complete approval |
| Selection | Revision conflict, inactive/deleted exclusion and removal closing old context |
| LangChain | Query/document adapter limits/order/compatible preprocessing if wrapper used; tool schema cannot inject identity; same retrieval implementation |
| Files | Both PDFs, infographic, DOCX pair associations plus previously unseen supported files through browser upload |
| Grounding | Independently marked evidence, unsupported/conflicting questions, placeholders and prompt-like source content |
| Real voice | Persian audio/transcripts, actual knowledge tool, follow-up/topic switch/interrupt, provider loss/logout/expiry and fresh-session recovery |
| Deployment | Target HTTPS/microphone/speaker/network and durable file/DB mapping |
Map results to MVP-01 through MVP-14 in the delivery plan. Ordinary provider-free tests do not prove hosted model quality; configured PostgreSQL acceptance must not skip missing infrastructure. Existing recorded results are historical, not checks executed by this documentation revision. Run necessary affected checks during implementation; do not extend unrelated component repairs.
Hand off startup/migration/seed/worker/retry commands, configuration, format/ structural bounds, reference questions/unseen-file results, actual latency/ provider evidence, known failures and release revision. Public text/history acceptance stays deferred.
13. Decisions still requiring confirmation
Actual file/page/storage/corpus admission and session limits; factual authority and reviewer availability; fixed funded extraction/embedding/Live identities and vector dimension; account/quotas/Persian capability proof; hosting/connectivity; session TTL, retention/purge, quantitative quality/latency targets and actual presentation date. General browser upload, all four example structures, LangChain, existing embedding reuse and direct Gemini Live are confirmed direction.
Exact-output retention/review, FAQ inclusion decisions and their forward schema/ HTTP mechanisms in this revision are implementation proposals made concrete for review, not already implemented behavior or approval of every fact in a file.