docs: restructure documentation hierarchy and update agent reference map
- 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
This commit is contained in:
@@ -0,0 +1,737 @@
|
||||
# Organization Knowledge Assistant — Software Architecture
|
||||
|
||||
| Document field | Value |
|
||||
| --- | --- |
|
||||
| Version | 1.3 - LangChain Live document MVP; existing embedding pipeline retained |
|
||||
| Date | 2026-10-07 |
|
||||
| Status | Proposed implementation design; open decisions are listed in Section 19 |
|
||||
| Audience | Project management, technical mentor, backend, frontend and AI developers |
|
||||
| Application | New-document uploads and direct Persian Live voice; broader text/history design is deferred |
|
||||
| Source baseline | Project requirements and architecture decisions recorded during design |
|
||||
|
||||
Document lifecycle decision (revision 1.1): every upload is an independent immutable document. Chunks and ingestion jobs reference it directly; answer sources use document/chunk IDs. Content versioning is not a current requirement. Settings revisions and embedding profile metadata remain technical controls, not document versions.
|
||||
|
||||
## 1. Purpose and Scope
|
||||
|
||||
The current milestone is the conditional four-day Live document MVP governed by delivery plan revision 1.3. Known users in one organization upload new supported documents through the browser, activate ready knowledge and ask Persian spoken questions. LangChain exposes the shared scoped retrieval/tool boundary; Gemini Live owns native audio conversation. Full text chat, durable messages and settings editing are deferred. Historical/broader sections below do not expand this active scope.
|
||||
|
||||
The four supplied PDFs/DOCX/image examples are mandatory initial tests, not an upload allowlist or a known final corpus. New files within declared structure/resource limits require no developer code changes.
|
||||
|
||||
The initial business use case is a reliable demonstration and subsequent organizational service. Business success depends on understandable answers, verifiable sources, document coverage and dependable operation. This architecture does not guarantee commercial outcomes or zero hallucinations.
|
||||
|
||||
### 1.1 Confirmed design constraints
|
||||
|
||||
- PostgreSQL with pgvector stores application data and document embeddings.
|
||||
- Preserve the implemented hosted embedding adapter, validation and staging from ingestion Phases 1-4, including compatible profiles/vectors; funded deployment identity and Persian quality still need proof. Provider comparison is optional, not required delivery work.
|
||||
- Initial voice uses direct Gemini Live API access managed by the backend over WSS. There is no mandatory separate ASR, TTS or answer-generation call for each voice turn.
|
||||
- The agent decides whether to call the knowledge search tool and can repeat a search when necessary.
|
||||
- Documents are dynamically uploaded, updated and selected by the organization.
|
||||
- The only initial knowledge tool is `search_knowledge`. A separate read-document tool is excluded.
|
||||
- The internal text-query harness, current Live path and later text chat share one retrieval implementation, access rules and embedding identity. Durable text history is deferred.
|
||||
- The MVP UI has login and one workspace with voice and admin upload/status/review/selection. Name/instruction/profiles stay seeded/server-configured; settings editing and full text UI are deferred.
|
||||
- LangChain is the selected RAG/tool framework. Provider-neutral ingestion does not need a wholesale framework refactor.
|
||||
|
||||
### 1.2 Proposed implementation choices
|
||||
|
||||
A modular monolith built with Python and FastAPI, plus a separate ingestion worker from the same codebase, is the proposed deployment baseline. PostgreSQL-backed jobs avoid requiring a separate broker. A custom LangChain retriever/tool invokes the existing application search service. Use a thin Embeddings wrapper only where needed, preserving profile/preprocessing, bounds and validation. The provider-native Live session performs the audio conversation loop; optional future LangGraph text orchestration is not an MVP prerequisite.
|
||||
|
||||
These choices separate confirmed product/framework direction from proposed implementation mechanisms, not claims of operational completion. The 2026-10-07 user direction confirms new-document upload, all four initial examples, existing embedding reuse, LangChain and limited-demo scope. Current integration mechanisms remain proposed. Broader model catalogues, SSE/mixed history and extra logical tables below remain future context, not Phase 1 requirements. Representative PDF, DOCX and image extraction are now in MVP scope. Exact model IDs, format/size caps, account eligibility, retention, capacity and delivery dates still require validation. Local-cookie authentication is the proposed Phase 1 implementation.
|
||||
|
||||
### 1.3 Scope boundaries
|
||||
|
||||
The current MVP includes document ingestion/review, organization-scoped retrieval, owned Live voice sessions, retrieved evidence and basic administration/logging. Full text conversations/citations/history and configuration mutation belong to a later milestone. Fine-tuning, autonomous database writes by the model, internet search, arbitrary tools, CTI integration and a separate audio transcription service are outside the current scope. Raw audio recording is not a baseline requirement.
|
||||
|
||||
## 2. Architecture Principles
|
||||
|
||||
1. **Agentic interaction:** the model chooses a registered tool; the backend validates and executes the call. Models never receive database credentials or generate executable SQL for direct execution.
|
||||
2. **Organization-controlled knowledge:** retrieval is restricted to authorized, selected and ready documents.
|
||||
3. **Shared retrieval:** both conversation modes use one search implementation and evidence contract.
|
||||
4. **Backend-managed live audio:** the backend relays client audio to direct Gemini Live and executes authorized tools on the same controlled session.
|
||||
5. **Persistent application state:** provider session state and local process memory are not authoritative conversation history.
|
||||
6. **Explicit lifecycle:** uploading a file does not immediately make it searchable. Ingestion must complete before publication.
|
||||
7. **Traceable answers:** evidence links identify actual documents and chunks. Presence of a citation alone does not prove semantic correctness.
|
||||
8. **Incremental implementation:** add extraction strategies and retrieval refinements based on actual documents and evaluation results.
|
||||
|
||||
## 3. System Context and Deployment Boundaries
|
||||
|
||||
| Component | Responsibilities | Deployment |
|
||||
| --- | --- | --- |
|
||||
| Web dashboard | Login, voice/microphone/speaker, available transcripts/sources, admin upload/status/review/selection | Same-origin HTTPS |
|
||||
| FastAPI application | Authorization, owned voice/session/tool control, document/review/selection APIs and read-only capabilities | Backend process |
|
||||
| Ingestion worker | Extraction, chunking, embedding, retries and publication | Separate process from the same codebase |
|
||||
| PostgreSQL + pgvector | Existing foundation/jobs/chunks/vectors; retained review metadata and new auth/voice/tool records | Persistent database |
|
||||
| File storage | Immutable originals and retained extraction artifacts | Existing durable volume; object storage only if already selected |
|
||||
| Embedding/extraction providers | Existing compatible vector generation and direct/vision extraction | Fixed funded profiles; preserve embedding identity |
|
||||
| Live provider | Direct audio understanding and speech generation | External live model service |
|
||||
|
||||
A provider adapter is backend code. It is not the provider service. The browser uses an authenticated application WSS stream to the backend. The backend owns the Gemini Live connection, credentials, policy and tool execution; the provider service remains external.
|
||||
|
||||
The two presentation diagrams are retained in Appendix A. They show logical responsibilities; they do not imply that the live model runs inside the backend deployment.
|
||||
|
||||
## 4. Backend Modules and Dependency Rules
|
||||
|
||||
| Module | Owns | Public application operations |
|
||||
| --- | --- | --- |
|
||||
| Identity | Users, organization memberships and session authorization | Authenticate user; resolve organization and role |
|
||||
| Documents | File metadata, ingestion state and selection | Upload independent document; list; activate; deactivate |
|
||||
| Knowledge | Chunk retrieval and evidence construction | Search authorized knowledge |
|
||||
| Conversations | Owned voice identity/epoch now; text turns/messages/citations later | Create owned voice context; invalidate/close |
|
||||
| Live Sessions | Provider session mapping, connection state and live event handling | Create; connect control channel; process event; close |
|
||||
| Configuration | Seeded instruction/name, fixed profiles and technical revisions | Read capabilities now; editor later |
|
||||
| Audit/Operations | Administrative events, traces and health | Record audit event; expose operational status |
|
||||
|
||||
API handlers validate transport data, authenticate and call application services. Application services coordinate domain rules through interfaces. Provider clients, SQLAlchemy repositories and file-storage implementations belong to infrastructure. Tools call application services rather than API endpoints inside the same process.
|
||||
|
||||
Shared organization context is created from authenticated identity. Client input and model arguments cannot override it. Cross-module access uses explicit operations rather than arbitrary writes to another module's tables.
|
||||
|
||||
### 4.1 Suggested code organization
|
||||
|
||||
| Path | Purpose |
|
||||
| --- | --- |
|
||||
| `app/main.py` | API bootstrap and dependency wiring |
|
||||
| `app/worker.py` | Ingestion worker entry point |
|
||||
| `app/api/v1/` | HTTP and application event endpoints |
|
||||
| `app/modules/identity/` | Authentication and authorization |
|
||||
| `app/modules/documents/` | Document lifecycle |
|
||||
| `app/modules/knowledge/` | Retrieval and search tool contracts |
|
||||
| `app/modules/conversations/` | Minimal owned voice context; text/history later |
|
||||
| `app/modules/live/` | Live session controller |
|
||||
| `app/modules/configuration/` | Model profiles and organization settings |
|
||||
| `app/integrations/ai/` | Text, embedding and live provider adapters |
|
||||
| `app/infrastructure/db/` | Repositories, migrations and database sessions |
|
||||
| `app/infrastructure/storage/` | Original-file access |
|
||||
| `app/infrastructure/jobs/` | Durable job claiming and retry implementation |
|
||||
| `tests/` | Unit, integration, contract and scenario evaluations |
|
||||
|
||||
Use application/domain/infrastructure subdivisions where module complexity warrants them. Do not introduce empty abstractions solely to match the proposed directory structure.
|
||||
|
||||
## 5. Agentic Conversation Design
|
||||
|
||||
### 5.1 Agent responsibilities
|
||||
|
||||
The agent interprets the user's wording and conversation context, asks clarification when meaning is ambiguous, and calls `search_knowledge` for organization-specific facts. It can answer greetings and conversational coordination without retrieval. For factual questions about the documents, it is instructed to obtain supporting evidence before answering.
|
||||
|
||||
The agent may reformulate queries while preserving dates, negation, location, units and other constraints. It must distinguish, for example, general opening hours from Thursday-specific hours. It can issue another search when initial results are incomplete, subject to configured call and time limits.
|
||||
|
||||
Document content is evidence, not executable instructions. Retrieved text cannot grant permissions, change tools or override the agent policy. Answers should identify uncertainty and conflicting sources rather than silently resolve a policy dispute.
|
||||
|
||||
### 5.2 Agentic behavior and enforcement
|
||||
|
||||
The model's choice to search is probabilistic. A system prompt alone cannot guarantee that every factual response is grounded. The application enforces tool authorization, budgets and source validity; evaluation checks whether the model calls the tool appropriately and supports its claims.
|
||||
|
||||
For text responses, validate structured source references before finalizing a turn. If the model returns invalid references, use a bounded repair attempt or return a controlled error. A stricter pre-release factuality gate can be added if evaluation requires it.
|
||||
|
||||
For live speech, generated audio may be relayed to the user before a server-side semantic validation step finishes. This architecture therefore does not claim a prevalidated guarantee for every spoken sentence. If that guarantee becomes mandatory, the audio release/control design must be revisited and its latency impact accepted explicitly.
|
||||
|
||||
### 5.3 Text turn sequence (deferred)
|
||||
|
||||
This sequence is preserved for the follow-up text milestone. Current retrieval is tested through an internal query harness; voice is not dependent on a shipped text model/turn loop.
|
||||
|
||||
1. Authenticate the request and verify conversation ownership.
|
||||
2. Persist the user message using a client request ID to detect retries.
|
||||
3. Load bounded conversation context and a configuration/document-selection snapshot.
|
||||
4. Run the text agent with the registered search tool.
|
||||
5. Validate and execute tool calls through the shared knowledge service.
|
||||
6. Return tool evidence to the same agent loop.
|
||||
7. Produce a response, validate reference IDs and persist the assistant message and citations.
|
||||
8. Return the final answer or stream supported application events.
|
||||
|
||||
A failed turn is recorded explicitly and does not appear as a completed assistant answer. Retrying a completed request returns the existing result instead of creating duplicate messages.
|
||||
|
||||
## 6. Search Tool Contract
|
||||
|
||||
### 6.1 Model-visible interface
|
||||
|
||||
The Phase 1 model tool is `search_knowledge`, replacing the earlier proposed `search_documents` name. It maps to one shared backend knowledge service used by text and Live. The prototype's `retriever_tool` is a different, implemented interface.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "search_knowledge",
|
||||
"description": "Retrieve authorized evidence for a document-dependent question.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": "string"},
|
||||
"context": {"type": "string", "description": "Optional resolved conversational reference; never authorization."}
|
||||
},
|
||||
"required": ["query"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This is a proposed tool schema, not a REST endpoint. Query is required; optional `context` carries a resolved reference such as the circular just discussed. Document filters are deferred until a supported, backend-validated filter contract exists. Reject organization/user IDs, SQL, arbitrary paths and model-selected access scope. Backend execution context supplies identity, allowed documents, embedding profile, limits and correlation IDs.
|
||||
|
||||
### 6.2 Result contract
|
||||
|
||||
The canonical proposed `ok | no_evidence | error` payload and JSON examples are in [API catalog Section 7.2](RAG-Phase1-API-Catalog.md). Evidence contains `source_ref`, `document_id`, `chunk_id`, `title`, `text` and `location.page/section`; unavailable locations are null. References identify actual retained chunks and are unique within their turn. Never fabricate an excerpt or page number.
|
||||
|
||||
`no_evidence` means retrieval completed but sufficient supporting evidence was not found. A timeout, embedding/provider failure or revoked context produces `error`, not a fabricated empty-success result.
|
||||
|
||||
### 6.3 Execution pipeline
|
||||
|
||||
1. Validate non-empty query and enforce configured length/call budgets.
|
||||
2. Resolve organization access and selected documents from trusted state.
|
||||
3. Recheck current document permissions and deactivation before retrieval.
|
||||
4. Normalize Persian query text without changing semantic constraints.
|
||||
5. Embed the query using the compatible embedding profile of the active index.
|
||||
6. Run filtered vector retrieval and optionally combine lexical results.
|
||||
7. Deduplicate, select relevant chunks and cap the evidence token budget.
|
||||
8. Build references from stored metadata and persist retrieval provenance.
|
||||
9. Return evidence to the requesting text or live agent.
|
||||
|
||||
Recommend semantic plus lexical retrieval for document/article numbers, dates and organization names using the existing PostgreSQL stack. If hybrid fusion exceeds the schedule, semantic retrieval plus exact normalized identifier matching is the minimum proposed option. Apply the same eligibility checks and evidence budget to both paths. Reranking remains optional. Persian lexical behavior must be tested with actual data; a generic full-text configuration is not assumed to provide Persian stemming automatically.
|
||||
|
||||
Similarity values are ranking signals, not probabilities that an answer is correct. Any relevance threshold is calibrated against the evaluation set. For small datasets, exact vector search is an acceptable baseline. Approximate index choice, filtered recall and performance are measured before deployment.
|
||||
|
||||
## 7. Dynamic Document Lifecycle
|
||||
|
||||
### 7.1 Upload and extraction
|
||||
|
||||
Authenticated upload preserves an immutable original under a generated storage key and creates an independent document plus durable job. Filename is display metadata, never a path. Use one downstream text pipeline for readable text and image-derived text; choose extraction by actual page content and quality.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
U["Upload: independent document and immutable original"] --> J["Queued job; worker claims lease"]
|
||||
J --> F{"Actual content"}
|
||||
F -->|DOCX or readable text| D["Paragraphs and tables; keep Q and A together"]
|
||||
F -->|PDF page| P["Attempt direct extraction on this page"]
|
||||
F -->|Image or scanned page| O["OCR or vision: faithful transcription"]
|
||||
P --> Q{"Readable, complete, ordered; numbers checked?"}
|
||||
Q -->|Yes| B["Common extracted blocks and page method"]
|
||||
Q -->|No or uncertain| R["Render affected page"]
|
||||
R --> O
|
||||
D --> B
|
||||
O --> B
|
||||
B --> C{"Simple checks and manual review where uncertain"}
|
||||
C -->|Reliable| A["Retain source text and normalized search text"]
|
||||
C -->|Visibly unreliable| X["Fail visibly; no indexing"]
|
||||
A --> K["Semantic chunks and compatible embeddings"]
|
||||
K --> T["Fenced atomic publication; ready and inactive"]
|
||||
T --> S["Admin inspects and activates"]
|
||||
```
|
||||
|
||||
For DOCX, extract paragraphs and tables in meaningful order, preserving headings, cells and question/answer relationships. This sample bank stores many questions and answers in adjacent rows: pair by the actual labels/order, not by assuming one FAQ per row. Use `page=null` and a `section` locator containing table/row range or Q&A identifier; DOCX pagination is not reliable.
|
||||
|
||||
For each PDF page, attempt direct extraction if text is usable. Check reading order, completeness and important numeric fields against the page. A non-empty text layer does not prove readability. Render only affected pages for OCR/vision fallback; mixed extraction methods within one PDF are supported and recorded per page. This is simple checks plus manual inspection for uncertain pages, not a required automatic quality classifier.
|
||||
|
||||
Preferred initial extraction API candidate: a configurable Gemini Flash vision model; `gemini-2.5-flash` appears in the official pricing catalog checked on 2026-10-06. Availability and account access must be verified before use. PDF vision can retain layout information; raw non-PDF input should not be assumed to retain DOCX table structure. See [Gemini document processing](https://ai.google.dev/gemini-api/docs/document-processing) and [pricing](https://ai.google.dev/gemini-api/docs/pricing). Mistral OCR is an optional benchmark alternative; PaddleOCR is a future local candidate only after verifying Persian support. Neither is mandatory.
|
||||
|
||||
Proposed extraction instruction:
|
||||
|
||||
> Transcribe all visible source content; do not summarize. Preserve headings, subheadings, lists, conditions, exclusions and reading order. Associate each infographic heading with its own description and parent group. Mark unreadable regions explicitly. Do not guess or silently correct numbers, dates, names or identifiers. Keep any warning or interpretation separate from the transcribed text.
|
||||
|
||||
The common logical representation extends the existing `ExtractedBlock` concept with document ID/title supplied by its envelope, `page` or `section`, block type/heading, faithful `text`, extraction method/model and warnings. These are logical fields, not one table per concept. Proposed artifact example; the text placeholder is deliberately not a source quotation:
|
||||
|
||||
```json
|
||||
{
|
||||
"document_id": "10000000-0000-4000-8000-000000000003",
|
||||
"title": "Administrative reform infographic",
|
||||
"blocks": [{
|
||||
"page": null,
|
||||
"section": "image/group-right/item-1",
|
||||
"block_type": "heading_with_description",
|
||||
"heading": "<verified parent and child headings>",
|
||||
"text": "<complete manually checked transcription>",
|
||||
"extraction_method": "vision",
|
||||
"model": "<configured-extraction-model>",
|
||||
"warnings": []
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
Keep original bytes, faithful extracted text and derived normalized search text separately where practical. Normalize Persian/Arabic character variants and whitespace for search while preserving source display, ZWNJ where meaningful, digit order, decimal separators, units and numeric meaning. Record the preprocessing profile. Extraction artifacts allow chunking or embedding changes without paying for OCR again; see [database Section 4.4](RAG-Phase1-Database-Design.md).
|
||||
|
||||
Quality checks explicitly cover reversed dates/digits, dropped negation or exclusions, missing/duplicated blocks, wrong reading order and unreadable regions. Compare critical fields to the original; do not fix them by guesswork. No invented model confidence percentage. Proposed simple gate: uncertain pages are manually checked before publication; visibly unreliable extraction fails with a redacted quality reason and no chunks. The existing queued/processing/ready/failed lifecycle remains. Review does not require a new document state or approval subsystem.
|
||||
|
||||
### 7.1.1 Retained review for arbitrary new uploads
|
||||
|
||||
Current PDF page/vision extraction requires evidence-bound review. Retain exact
|
||||
bounded page images/blocks under the worker claim, fail visibly with a review
|
||||
reason and release the lease. Admin inspection/decision and same-job retry use
|
||||
API D06/D07/D04. New OCR output cannot inherit an old approval. Incomplete
|
||||
candidates remain non-queryable; complete artifacts are attached only after
|
||||
coverage/quality validation under a current claim.
|
||||
|
||||
Preserve the implemented embedding/staging path. Unknown upload count requires
|
||||
durable backlog, pagination, configured file/page/resource bounds and capacity
|
||||
measurement. No hardcoded examples, four-document cap or per-file coding.
|
||||
Factual FAQ approval and whole-group exclusions preserve faithful original
|
||||
content while keeping behavioral scenarios/placeholders out of answer evidence.
|
||||
|
||||
### 7.2 Document processing states
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> queued
|
||||
queued --> processing
|
||||
processing --> ready
|
||||
processing --> failed
|
||||
failed --> queued: Retry
|
||||
ready --> deleted: Delete
|
||||
```
|
||||
|
||||
Activation/selection is separate from processing state: a ready document can remain unselected. Only selected ready documents can be searched.
|
||||
|
||||
### 7.3 Chunking and embedding
|
||||
|
||||
Each chunk preserves its document identity, order, text and available source location. Chunk size and overlap are configurable and recorded as processing metadata. Prefer regulation article/clause plus its note, circular decision plus conditions/exclusions, FAQ question plus answer, and infographic parent heading plus child description. Size limits and overlap apply when necessary, without losing the exception that qualifies a rule. Image-derived text uses the same embedding model as other text. Local BGE-M3 or Qwen embedding models are optional future alternatives, not required hosted services.
|
||||
|
||||
Embedding profiles record provider, model, dimensions and preprocessing version. Documents and queries must use the same compatible profile. Changing the embedding model requires a controlled corpus reindex from retained extracted text, with incompatible vectors isolated and a verified cutover. Ready document/chunk identities and originals remain immutable; do not use failed-document retry to republish a ready document. The maintenance/cutover mechanism requires a separate implementation design before any deployed profile change. Equal vector dimensions do not make two embedding models interchangeable.
|
||||
|
||||
### 7.4 Publication, updates and selection
|
||||
|
||||
Each upload creates a new independent document; there is no document-version entity or in-place content replacement. Upload the changed file, wait until it is ready, then deactivate the old document and activate the new one. The old document remains inactive for historical reference. Failure of the new upload leaves the old active document usable. Retry processes only the same failed document and creates no new identity.
|
||||
|
||||
An administrator selects ready document IDs for the organization. Every turn records the effective selection revision and the source document/chunk IDs. A selection change applies to subsequent turns. Current access revocation/deactivation overrides cached or snapshotted access immediately for new tool operations; sensitive in-flight results must be rechecked before delivery.
|
||||
|
||||
Previously sent evidence cannot be recalled from a provider context. On document revocation during a live conversation, invalidate affected context and reset or close the provider session when necessary. Previously delivered speech cannot be withdrawn. The UI must not imply that changing selection rewrites old answers.
|
||||
|
||||
Deletion first excludes the document from retrieval. Physical deletion follows the retention policy, including chunks, vectors, originals and derived copies. Historical citations retain minimal tombstone metadata when permitted; access to retained content still requires authorization.
|
||||
|
||||
### 7.5 Durable worker behavior
|
||||
|
||||
The worker claims jobs with a lease and claim token, updates progress and publishes only if it still owns the claim. Expired leases allow recovery after a crash. External embedding calls occur outside long database transactions. Idempotent chunk writes and publication prevent duplicate indexed chunks after retries.
|
||||
|
||||
Store job attempts, next retry time, stage, error category and processing profile. Retry temporary network/rate-limit failures with bounded backoff; unsupported formats and invalid input require correction. File storage and PostgreSQL do not share a transaction: use staged storage and reconciliation to clean abandoned uploads or recover incomplete metadata transitions.
|
||||
|
||||
## 8. Live Voice with direct Gemini API access
|
||||
|
||||
### 8.1 Connection responsibilities
|
||||
|
||||
Use direct Gemini Live for the initial voice MVP. The provider connection is stateful WSS; the backend relays client audio and controls private tools. Browser-to-provider SDP/WebRTC from revision 1.1 is superseded for this MVP, not assumed compatible with Gemini. See [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api).
|
||||
|
||||
OpenRouter is for bounded comparisons of two or three text/vision candidates. Its [audio interface](https://openrouter.ai/docs/guides/overview/multimodal/audio) supports request audio and streamed response audio; that does not establish a compatible bidirectional Gemini Live session.
|
||||
|
||||
### 8.2 Session establishment
|
||||
|
||||
Authenticate the HTTP creation request; persist the owned reservation and idempotency hash before provider setup. Validate session/auth/access epoch again at the application WSS handshake using cookie and trusted Origin. The backend connects to Gemini with its server credential, installs Persian instructions and `search_knowledge`, and enables available input/output transcription. Mark connected only after trusted adapter confirmation. The application WSS transport/event fields are proposed in [API catalog Section 7](RAG-Phase1-API-Catalog.md).
|
||||
|
||||
### 8.3 Voice tool cycle
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as Browser or approved audio bridge
|
||||
participant B as Backend Live controller
|
||||
participant L as Gemini Live
|
||||
participant K as Shared knowledge service
|
||||
participant D as PostgreSQL and pgvector
|
||||
U->>B: Authenticated audio stream
|
||||
B->>L: Audio on direct Live WSS session
|
||||
L->>B: search_knowledge(query, optional context)
|
||||
B->>B: Validate owner, scope, epoch and call ID
|
||||
B->>K: Retrieve authorized evidence
|
||||
K->>D: Query embedding plus eligible semantic/identifier search
|
||||
D-->>K: Relevant chunks and locators
|
||||
K-->>B: ok, no_evidence or error
|
||||
B-->>L: Correlated tool result
|
||||
L-->>B: Persian speech and available transcription
|
||||
B-->>U: Audio, transcript and source references
|
||||
```
|
||||
|
||||
The Live model may answer directly from returned evidence. A separate text-generation call on every voice turn is not mandatory. The existing prototype text agent is not a prerequisite for this milestone. The trusted dispatcher invokes the shared LangChain knowledge tool; adding a separate answer model would require a measured purpose and re-estimated latency/cost.
|
||||
|
||||
Backend dispatch correlates session/call IDs, validates complete arguments, deduplicates same-ID calls and rejects changed arguments. Recheck current document eligibility and epoch before releasing evidence, including cached duplicates. [Live tools](https://ai.google.dev/gemini-api/docs/live-api/tools) require application handling of function responses; validate the chosen model's blocking/asynchronous capabilities rather than combining incompatible examples.
|
||||
|
||||
### 8.4 Conversation, interruption and failure behavior
|
||||
|
||||
| Situation | Required behavior |
|
||||
| --- | --- |
|
||||
| Follow-up | Resolve “its exceptions” to the last clearly identified circular/article; send a focused query with optional resolved context and retrieve current evidence again |
|
||||
| Topic changes | Replace the topic anchor; do not carry article/document assumptions into the new question |
|
||||
| Ambiguous reference | Ask which document/article; do not choose solely from similarity |
|
||||
| Insufficient evidence | State the missing support and ask a useful clarification; no invented policy or number |
|
||||
| Conflicting evidence | Identify the disagreement and sources; ask which applies or refer to an authorized reviewer |
|
||||
| Retrieval timeout/provider failure | Technical failure with bounded retry/visible status; never claim the document does not exist |
|
||||
| Interruption/cancel | Stop and clear queued playback, mark partial transcription interrupted, cancel outstanding tool work when possible and discard late results |
|
||||
| Disconnect/restart | Show disconnection, reconcile/close old session, start a new session; do not replay old audio or silently restore context |
|
||||
| Duplicate call | Same session/call ID and hash reuses an eligible saved result; running duplicates do not execute twice |
|
||||
|
||||
Seamless reconnect and provider context restoration are deferred. A new session must ask the user to repeat unresolved references. Account logout, session expiry and knowledge removal close sessions under the existing epoch rules. Provider cleanup is best effort, bounded by TTL.
|
||||
|
||||
### 8.5 Audio, transcripts and telephony boundaries
|
||||
|
||||
The proposed application stream uses mono raw PCM matching Gemini: 16-bit little-endian input at 16 kHz and output at 24 kHz. Capture/resample browser audio and convert output for playback; do not forward compressed browser blobs as PCM. The provider accepts explicitly declared input rates, but standardizing the bridge simplifies the MVP. Interruption clears playback buffers. Verify these behaviors against the configured model using [Live capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities).
|
||||
|
||||
Keep available answer transcription and source references visible for the current session. Missing transcription is labeled unavailable, never reconstructed as if spoken; partial generated text does not prove what was heard. Durable full voice history and raw recording remain deferred. The chosen demo model must prove output-transcription delivery; API/storage details must not imply voice messages already exist in the current text-only schema.
|
||||
|
||||
Answers should be concise Persian, with fuller references in the UI; do not recite long chunk IDs or technical citations. Test real Persian utterances and comprehension, local names, dates, percentages and amounts. Multilingual support alone does not prove acceptable quality.
|
||||
|
||||
CTI/Asterisk remains outside the web MVP; no operator behavior analysis requirements are imported. If later explicitly commissioned, an audio bridge must connect the call media/control to the backend, negotiate actual codecs, decode/resample telephony input to PCM and convert 24 kHz output to the negotiated call format. Telephone credentials, routing, hangup/interruption and network rehearsal are separate integration work; API credit does not create a phone connection.
|
||||
|
||||
## 9. Logical Data Model
|
||||
|
||||
The database specification is authoritative. The active MVP preserves seven foundation tables and adds auth_sessions, voice conversations, live_sessions and voice-only tool_calls, plus retained-review metadata in a forward migration. No text-table dependency is required for voice.
|
||||
|
||||
The broader logical entities below are future context, independent of the earlier CTI module's database. They are not a requirement for new embedding profile/generation tables, text history or another vector-store layout in the current milestone.
|
||||
|
||||
| Entity | Important fields and purpose |
|
||||
| --- | --- |
|
||||
| organizations | ID, name, status |
|
||||
| users / memberships | Identity, organization, role and active state |
|
||||
| organization_settings | Revision, allowed model profiles, retrieval limits, active selection revision |
|
||||
| documents | Organization, display name, checksum, storage key, MIME, processing status/profile, selected flag, deletion state |
|
||||
| ingestion_jobs | Document, stage, state, attempts, lease owner/token, lease expiry, next attempt, error |
|
||||
| embedding_profiles | Provider/model, dimensions, preprocessing version, index generation and active state |
|
||||
| chunks | Document, ordinal, original and normalized text, page/section, processing profile |
|
||||
| chunk_embeddings | Chunk, embedding profile/generation and vector |
|
||||
| conversations | Organization, owner, title, mode, state and timestamps |
|
||||
| turns | Conversation, sequence, client request ID, configuration/selection snapshot, state |
|
||||
| messages | Turn, role, content, modality, provider item ID, completion/interruption state |
|
||||
| tool_calls | Turn/session, provider call ID, validated query, execution state, result references and latency |
|
||||
| message_sources | Message, document/chunk, source reference and supporting excerpt if allowed |
|
||||
| live_sessions | Conversation, provider session ID, controller owner, model, connection state and timestamps |
|
||||
| audit_events | Actor, organization, action, target, timestamp and redacted metadata |
|
||||
|
||||
All organization-owned access must enforce organization scope. Use foreign keys and constraints to prevent cross-organization relationships, not only API checks. Add unique constraints for chunk ordinals per document, client request IDs per conversation and provider event/call IDs in their proper scope.
|
||||
|
||||
Use relational columns for identifiers, statuses and queryable fields; JSONB holds variable provider metadata and processing details. Do not store secrets in metadata. Use timezone-aware timestamps in UTC and display localized time in the UI. Page numbering semantics must be recorded by the extractor.
|
||||
|
||||
Vector dimension and storage type must match the chosen embedding profile. Separate incompatible vector generations by table/partition or another explicitly tested strategy. Index foreign keys and frequent organization/status filters. Select approximate vector indexes only after measuring filtered recall and query latency [R4].
|
||||
|
||||
## 10. Application API Contracts
|
||||
|
||||
The API catalog revision 1.3 is authoritative for active/deferred delivery status. Core MVP capabilities are new-document upload/review/selection and Live voice. Public text chat/history, settings mutation, mixed mode and SSE are deferred. The broader route table below is retained future context and cannot override the catalog.
|
||||
|
||||
| Method and route | Purpose | Result |
|
||||
| --- | --- | --- |
|
||||
| `POST /api/v1/auth/login` | Local login if local authentication is selected | Secure session; final identity contract TBD |
|
||||
| `POST /api/v1/auth/logout` | End authenticated session | 204 |
|
||||
| `GET /api/v1/me` | Current identity and organization roles | 200 |
|
||||
| `POST /api/v1/documents` | Multipart file upload | 202 with document/job IDs |
|
||||
| `GET /api/v1/documents` | Paginated organization documents | 200 |
|
||||
| `GET /api/v1/documents/{id}` | Metadata and processing state | 200 |
|
||||
| `PATCH /api/v1/knowledge-selection` | Replace selected document IDs using expected revision | 200 or 409 |
|
||||
| `DELETE /api/v1/documents/{id}` | Exclude and schedule permitted cleanup | 202 |
|
||||
| `GET /api/v1/configuration` | Read organization settings and capabilities | 200 |
|
||||
| `PATCH /api/v1/configuration` | Admin settings update using expected revision | 200 or 409 |
|
||||
| `POST /api/v1/conversations` | Start text, voice or mixed conversation | 201 |
|
||||
| `GET /api/v1/conversations/{id}/messages` | Authorized, paginated history | 200 |
|
||||
| `POST /api/v1/chat` | Submit a text turn | JSON result, or explicit SSE mode |
|
||||
| `POST /api/v1/voice/sessions` | Initialize live session and signaling | 201 |
|
||||
| `POST /api/v1/voice/sessions/{id}/close` | Idempotent close | 200 |
|
||||
| `GET /api/v1/conversations/{id}/events` | Authorized application event stream | SSE |
|
||||
| `GET /health/live` | Process liveness | 200 |
|
||||
| `GET /health/ready` | Ability to serve required dependencies | 200 or 503 |
|
||||
|
||||
All IDs from clients are checked for ownership. Pagination and upload limits are bounded. The internal search tool is not an unauthenticated public endpoint. Final endpoint names can evolve before frontend contract freeze.
|
||||
|
||||
### 10.1 Text turn example (deferred)
|
||||
|
||||
```json
|
||||
{
|
||||
"conversation_id": "conv_example",
|
||||
"client_request_id": "request_example",
|
||||
"message": "What are the organization's Thursday working hours?"
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"conversation_id": "conv_example",
|
||||
"turn_id": "turn_example",
|
||||
"message_id": "msg_example",
|
||||
"status": "answered",
|
||||
"answer": "An answer grounded in the selected reference documents.",
|
||||
"sources": [
|
||||
{"source_ref": "S1", "document_id": "doc_example", "chunk_id": "chunk_example", "page": 3}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Final application statuses include `answered`, `needs_clarification`, `insufficient_information` and `failed`. Streaming text is provisional until the completion event validates the final source mapping. The UI must preserve errors or interruption instead of implying successful completion.
|
||||
|
||||
### 10.2 Upload response example
|
||||
|
||||
```json
|
||||
{
|
||||
"document_id": "doc_example",
|
||||
"job_id": "job_example",
|
||||
"status": "queued",
|
||||
"searchable": false
|
||||
}
|
||||
```
|
||||
|
||||
### 10.3 Live session application contract
|
||||
|
||||
For Phase 1, the request carries `conversation_id` and `client_request_id`; the response contains session ID, state and an owned application WSS path. The backend connects to direct Gemini Live. No SDP or provider credential is returned. See the canonical API catalog for proposed events and ownership/replay behavior.
|
||||
|
||||
### 10.4 Error envelope
|
||||
|
||||
```json
|
||||
{
|
||||
"error": {
|
||||
"code": "KNOWLEDGE_NOT_READY",
|
||||
"message": "Selected documents are not ready for search.",
|
||||
"request_id": "req_example",
|
||||
"retryable": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Use 401 for unauthenticated access, 403/404 according to the resource-disclosure policy, 409 for revision/idempotency conflict, 413 for size limit, 415 for unsupported type, 422 for invalid input, 429 for quotas and 503 for unavailable dependencies. Never return internal exception strings or credentials.
|
||||
|
||||
## 11. Configuration and Model Boundaries
|
||||
|
||||
Separate text, live and embedding model profiles. Changing the response model does not rebuild embeddings; changing the embedding profile does. A live profile must support the chosen media and trusted tool-control features. The UI exposes only administrator-approved, capability-compatible models.
|
||||
|
||||
Configuration is revisioned. Record model, prompt, tool schema, retrieval profile and selection revision per turn/session. Apply ordinary model changes to new turns or sessions; do not silently mutate an active live session. Document access revocation is handled immediately as described in Section 7.
|
||||
|
||||
Provider adapters normalize completion events, tool calls, timeouts, rate limits, usage and error categories. They must not assume every model implements identical event schemas. Business services depend on interfaces such as TextModel, EmbeddingProvider, LiveSessionProvider, KnowledgeRepository and FileStore.
|
||||
|
||||
## 12. Security and Organization Isolation
|
||||
|
||||
Authenticate every application entry point and authorize every tool operation. Proposed roles are organization administrator and conversation user; additional roles require a product need. Ordinary users cannot change model credentials or organization selections.
|
||||
|
||||
Use HTTPS, server-managed secrets, controlled CORS origins and an explicit session expiration policy. If cookies are selected, apply secure/HttpOnly attributes and CSRF protection to mutations. If external SSO is selected, replace local credential handling while preserving application membership checks.
|
||||
|
||||
Treat uploads, model arguments and extracted content as untrusted input. Validate upload paths, avoid executing embedded content, limit parser resources and refuse unregistered tools. Restrict client ability to update provider session instructions or inject trusted tool outputs using available provider permissions. Validate remaining access assumptions during the live integration spike.
|
||||
|
||||
Document bodies and full prompts are not ordinary operational logs. Log IDs, stage, latency and redacted errors by default. Access to stored message content and citations follows organization membership and resource permissions. Administrative changes generate audit records.
|
||||
|
||||
## 13. Reliability and Concurrency
|
||||
|
||||
| Failure | Required behavior |
|
||||
| --- | --- |
|
||||
| Embedding rate limit | Bounded retry; preserve job state |
|
||||
| Unsupported/unreadable file | Failed document with actionable reason |
|
||||
| Replacement ingestion failure | Keep prior active document available |
|
||||
| Database outage | Reject dependent operations explicitly; do not invent answers |
|
||||
| Search timeout | Return tool error; distinguish it from no evidence |
|
||||
| Duplicate tool event | Reuse correlated result; avoid duplicate execution/history |
|
||||
| Lost live control channel | Pause or close knowledge interaction and notify UI |
|
||||
| Browser disconnect | Cleanup after grace period and record uncertain completion |
|
||||
| Worker crash | Recover expired lease and continue idempotently |
|
||||
| Invalid citation | Repair within budget or fail the response |
|
||||
|
||||
Serialize mutating turns per conversation in the initial implementation. A text turn must not race with an active voice turn against the same context. Keep live session control owned by one backend process; multi-instance deployment requires routing/ownership and a defined restart policy.
|
||||
|
||||
Retries of text generation and live session creation can incur duplicate provider work after an ambiguous timeout. Correlate application requests, reconcile known provider state where supported and avoid blind automatic recreation. Idempotency keys include a payload hash; reusing a key with a different request returns a conflict.
|
||||
|
||||
## 14. Observability and Performance
|
||||
|
||||
Correlate request, organization, conversation, turn, live session, tool call, document and job IDs. Measure text time to first output, total turn latency, query embedding latency, retrieval latency, live tool turnaround, available audio latency measurements, ingestion duration, error rates and provider usage.
|
||||
|
||||
Do not treat server tool latency as end-to-end voice latency. Browser measurements are required to include microphone, network and playback behavior. Usage may be incomplete if a session terminates before final provider events; represent it as partial rather than zero.
|
||||
|
||||
Capacity targets remain to be agreed: concurrent text users, active voice sessions, corpus size, ingestion throughput, maximum upload size and acceptable percentile latency. Test on the intended deployment network and representative Persian documents. Connection pools, evidence budgets and concurrency limits should be tuned from measurements.
|
||||
|
||||
## 15. Deployment and Operations
|
||||
|
||||
The first deployment consists of the dashboard/HTTPS entry point, one FastAPI service, one ingestion worker, PostgreSQL with pgvector and durable file storage. API and worker share code and configuration but run as separate processes. Redis and an external broker are optional future components, not baseline dependencies.
|
||||
|
||||
Apply reviewed database migrations as an explicit deployment step. Keep separate development, test and production credentials. Readiness checks should validate required local dependencies without making expensive model calls on every health probe. Perform provider connectivity checks as controlled diagnostics.
|
||||
|
||||
Backups must cover both the database and original files with a restorable mapping. Test restoration and reindexing. Recovery objectives, retention schedules and backup frequency are operational decisions requiring approval; no numeric guarantee is implied by this document.
|
||||
|
||||
Graceful shutdown stops new sessions/jobs, drains active work within a configured deadline and records interrupted work. Live sessions cannot be assumed migratable between processes. Monitor disk space, job backlog, database connections and external provider quotas.
|
||||
|
||||
## 16. Validation and Acceptance
|
||||
|
||||
Build a reference evaluation set from approved organization documents and expected answers before tuning prompts. Include natural Persian variants, follow-up pronouns, dates, numbers, conflicting documents, absent information and questions about unselected documents.
|
||||
|
||||
| Area | Acceptance evidence |
|
||||
| --- | --- |
|
||||
| Retrieval | Expected evidence appears for representative questions; numeric recall target agreed with stakeholders |
|
||||
| Grounding | Answer claims supported by cited passages; unsupported questions handled explicitly |
|
||||
| Agent behavior | Appropriate search calls, bounded retries and clarification for ambiguity |
|
||||
| Isolation | Cross-organization IDs and model-supplied scope cannot expose documents |
|
||||
| Dynamic documents | Upload, select, replace, deactivate and delete reflected in new retrieval |
|
||||
| Voice/session persistence | Upload/review/retry/live create replay correctly; restart preserves jobs/documents and makes old media sessions terminal |
|
||||
| Voice | Persian speech and document retrieval, available transcript/sources, interruption, explicit disconnection/new-session recovery and close tested |
|
||||
| Control security | Client cannot escalate tool access or change protected session policy |
|
||||
| Ingestion recovery | Crashes and provider failures recover without duplicate publication |
|
||||
| Deployment | HTTPS/microphone behavior, backups and demonstration network verified |
|
||||
|
||||
Use unit tests for permissions and state transitions, integration tests with PostgreSQL/pgvector, provider contract tests, and a small controlled live evaluation. Stub-only tests do not validate actual provider signaling or Persian audio quality. Evaluate internal text-query retrieval and real spoken answers independently even though search is shared. Include the four supplied examples and unseen new uploads. Full text-history acceptance is deferred.
|
||||
|
||||
## 17. Migration from the Existing Repository
|
||||
|
||||
The earlier review inspected commit `cb54a35`; the mapping below describes that historical prototype and the broader future text design. It is not an instruction to rebuild ingestion Phases 1-4, convert all services to LangChain, migrate text history now or alter applied embedding profiles. Current component progress and next work are in delivery plan Section 2 and the reference map.
|
||||
|
||||
| Existing area | Required evolution |
|
||||
| --- | --- |
|
||||
| `app/services/retriever.py` | Replace Chroma/FastEmbed with repository and embedding interfaces backed by pgvector and the compatible configured embedding provider |
|
||||
| `app/services/doc_processor.py` | Replace folder-only Markdown ingestion with registered extraction strategies and document-linked jobs |
|
||||
| `app/services/tools/retriever_tool.py` | Enforce trusted organization scope and structured evidence output |
|
||||
| `app/services/agent/exec.py` | Retain the agentic tool loop; add bounded execution, injected services and durable context |
|
||||
| `app/services/agent/prompt.py` | Replace technical-documentation persona with organization-knowledge policy |
|
||||
| `app/schemas/chat.py` | Add conversation/turn identity, structured sources and explicit outcomes |
|
||||
| `app/api/v1/chat.py` | Add authorization, idempotency, safe errors and optional streaming |
|
||||
| `app/core/config.py` | Separate secrets from versioned organization/model settings |
|
||||
| `app/main.py` | Explicit lifecycle initialization, bounded CORS and readiness |
|
||||
|
||||
Remove indexing side effects from module imports. Re-embed the source documents into the new compatible index; do not copy incompatible existing vectors. Treat in-memory conversation state as temporary unless explicitly migrated. Add dependency manifests, migrations, operational packaging and meaningful tests before claiming a reproducible release.
|
||||
|
||||
## 18. Implementation Sequence
|
||||
|
||||
1. Prove actual funded Gemini Persian audio/transcripts/tools and target-network access early.
|
||||
2. Reuse ingestion Phases 1-4; implement Phase 5 worker, exact-output review/resume and complete publication.
|
||||
3. Add minimal cookie identity and new-document HTTP upload/status/review/selection.
|
||||
4. Implement one scoped pgvector search service using compatible existing embeddings.
|
||||
5. Expose the service through LangChain retriever/tool boundaries; evaluate evidence with an internal query harness.
|
||||
6. Reserve owned voice contexts/sessions; connect native Live function calls to the same tool, audio relay, sources, cancellation and epoch checks.
|
||||
7. Finish the basic workspace, limits/failure feedback, unseen-file evaluation and actual HTTPS rehearsal.
|
||||
|
||||
Map this sequence to the conditional Days 1-4 in the delivery plan; execute
|
||||
independent provider proof early. Durable text chat/history, rich settings,
|
||||
optional ranking and broader operational expansion are later work. Actual dates
|
||||
and capacity/quality targets require confirmation. Documentation is not runtime evidence.
|
||||
|
||||
## 19. Open Decisions and Owners
|
||||
|
||||
| Decision | Suggested owner | Architectural impact |
|
||||
| --- | --- | --- |
|
||||
| File formats, scans, tables, document languages and size | Product owner / organization | Extractors, OCR, chunking and acceptance set |
|
||||
| Organization-wide selection | Confirmed MVP direction | Preserve selected-set revision and backend eligibility |
|
||||
| Exact Gemini Live model and account/tool/transcript capabilities | AI/backend team | Backend WSS adapter, audio and tool proof |
|
||||
| Funded embedding/extraction/Live profiles | AI team | Preserve current embedding compatibility; prove real quality/access |
|
||||
| Cookie session TTL/account operation | IT / backend | Pre-created local accounts now; SSO deferred |
|
||||
| Raw audio recording and content retention | Organization / IT | Storage, lifecycle and consent requirements |
|
||||
| Concurrent sessions and latency targets | Product / IT | Capacity, scaling and quotas |
|
||||
| Whether spoken answers require pre-release validation | Product / AI | Compatibility with direct live audio |
|
||||
| Hosting, outbound connectivity and data transfer approval | IT / organization | Provider reachability and deployment |
|
||||
| Backup policy and recovery objectives | IT | Operations and restoration testing |
|
||||
| Review usability and quantitative quality | Product owner / AI | Exact-output decisions and factual FAQ approval without per-file coding |
|
||||
| Meeting year and IT handover date | Project manager | Delivery plan |
|
||||
|
||||
These items must be resolved by their owners rather than silently converted into product policy.
|
||||
|
||||
## 20. Reference Documentation
|
||||
|
||||
External references establish platform capabilities. Module boundaries, contracts and lifecycle rules in this document are project design proposals. Model/API availability must be checked when implementing the selected adapter.
|
||||
|
||||
- **[R1]** [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api): initial direct provider/session access.
|
||||
- **[R2]** [Gemini Live capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities): audio, transcription and interruption.
|
||||
- **[R3]** [Gemini Live tools](https://ai.google.dev/gemini-api/docs/live-api/tools): correlated function calls/results.
|
||||
- **[R4]** [pgvector — Official repository](https://github.com/pgvector/pgvector): vector search, index types and filtering considerations.
|
||||
|
||||
## Appendix A. Presentation Diagrams
|
||||
|
||||
The following diagrams retain the previously agreed overview. Detailed security, lifecycle and failure requirements are defined in the main sections.
|
||||
|
||||
### A.1 Agentic AI and Dynamic Documents
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
USER["User — Text or Live Voice"] --> AGENT["AI Agent"]
|
||||
|
||||
subgraph AI["Agentic Conversation"]
|
||||
AGENT --> DECISION{"Need Document Knowledge?"}
|
||||
DECISION -->|"Yes"| CALL["Call Search Tool with Search Query"]
|
||||
DECISION -->|"Ready to Answer"| ANSWER["Generate Response with Sources"]
|
||||
end
|
||||
|
||||
subgraph TOOL["Tool: search_knowledge"]
|
||||
CALL --> SCOPE["Apply Organization and Selected Document Filters"]
|
||||
SCOPE --> QUERY["Embed Search Query"]
|
||||
QUERY --> SEARCH["Semantic Search"]
|
||||
SEARCH --> SELECT["Select Relevant Chunks"]
|
||||
SELECT --> RESULT["Return Content, Document IDs and Sources"]
|
||||
end
|
||||
|
||||
RESULT -->|"Tool Result"| AGENT
|
||||
ANSWER --> USER
|
||||
|
||||
subgraph DOCS["Dynamic Organization Documents"]
|
||||
ADMIN["Organization Admin"] --> MANAGE["Upload, Update and Select Documents"]
|
||||
MANAGE --> PROCESS["Extract, Chunk and Embed"]
|
||||
PROCESS --> DB[("PostgreSQL + pgvector")]
|
||||
MANAGE --> ACTIVE["Active Document Selection"]
|
||||
end
|
||||
|
||||
ACTIVE --> SCOPE
|
||||
SEARCH <-->|"Retrieve Matching Chunks"| DB
|
||||
```
|
||||
|
||||
### A.2 Layered Backend Overview
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph L1["1. Presentation"]
|
||||
UI["Web Dashboard"]
|
||||
end
|
||||
|
||||
subgraph L2["2. Backend API — FastAPI"]
|
||||
CHAT["Text Chat"]
|
||||
SESSION["Live Session"]
|
||||
DOCS["Documents and Configuration"]
|
||||
end
|
||||
|
||||
subgraph L3["3. Agentic AI — logical; Live model is external"]
|
||||
TEXT["Text AI Agent"]
|
||||
LIVE["Live AI Model"]
|
||||
TOOL["Search Documents Tool"]
|
||||
|
||||
TEXT <-->|"Tool Calls and Evidence"| TOOL
|
||||
LIVE <-->|"Tool Calls and Evidence via Backend"| TOOL
|
||||
end
|
||||
|
||||
subgraph L4["4. Knowledge Management"]
|
||||
INGEST["Extract, Chunk and Embed"]
|
||||
SEARCH["Search Organization-selected Documents"]
|
||||
end
|
||||
|
||||
subgraph L5["5. Storage"]
|
||||
FILES[("Document Files")]
|
||||
DB[("PostgreSQL + pgvector — Documents and Chat History")]
|
||||
end
|
||||
|
||||
UI --> CHAT
|
||||
UI --> SESSION
|
||||
UI --> DOCS
|
||||
|
||||
CHAT <--> TEXT
|
||||
SESSION -->|"Initialize and Control"| LIVE
|
||||
UI <-->|"Authenticated audio WSS"| SESSION
|
||||
SESSION <-->|"Direct Gemini Live WSS"| LIVE
|
||||
|
||||
TOOL <--> SEARCH
|
||||
SEARCH <--> DB
|
||||
|
||||
DOCS -->|"Upload and Update"| INGEST
|
||||
DOCS -->|"Active Document Selection"| SEARCH
|
||||
DOCS -->|"Store Original Files"| FILES
|
||||
FILES --> INGEST
|
||||
INGEST --> DB
|
||||
```
|
||||
|
||||
## 21. Historical MVP decision log and implementation evidence - 2026-10-06
|
||||
|
||||
No standalone ADR directory or separate requirements specification was found. This focused decision log records the current user-authorized MVP changes; the delivery plan retains requirement IDs P1-01–P1-12 and adds sample/voice acceptance.
|
||||
|
||||
| Classification | Decision or evidence |
|
||||
| --- | --- |
|
||||
| Confirmed product direction | Complete upload → extraction/QC → chunk/index → Persian voice → retrieval → grounded spoken answer; text-only or voice without retrieval is insufficient |
|
||||
| Confirmed existing lifecycle | Independent immutable uploads; direct document/chunk references; manual replacement; same eligible failed document/job retry; existing scope/revision/epoch/fencing rules |
|
||||
| Confirmed provider direction | Direct Gemini Live; Flash vision extraction candidate; OpenRouter comparisons; USD 20 initial allocation and USD 30 planned budget |
|
||||
| Proposed details | Application WSS event schema, optional tool context, derived extraction artifact, manual quality gate, identifier matching alongside semantic retrieval |
|
||||
| Verified by static inspection | Markdown folder loader and character splitter; Chroma/FastEmbed `BAAI/bge-small-en-v1.5`; LangGraph `MemorySaver`; configurable OpenAI-compatible text client; prototype chat route without the planned auth/turn contracts |
|
||||
| Verified by static inspection | Seven-table ingestion foundation and trusted intake CLI/local immutable originals; settings allow only PDF/Markdown; `ExtractedBlock` has text/page/section; no extraction worker, hosted embedding adapter, pgvector chat search, Live adapter or frontend |
|
||||
| Not verified here | Provider calls, Persian audio, comparative OCR, full PDF text/layout, deployed account/model access or operational voice MVP |
|
||||
|
||||
The pre-existing setup guide records earlier database acceptance; those results were not rerun for this documentation task. The current foundation's explicit embedding profile is authoritative when deployed; the English-only prototype model is not evidence of Persian retrieval quality. Preserve an approved existing profile until a separately reviewed controlled reindex. Planned OpenAI-compatible embedding access needs funded credentials; the Gemini/OpenRouter allocation does not itself fund a separate OpenAI account.
|
||||
|
||||
See the [Persian sample scenarios](RAG-Phase1-Scenario-Report-FA.md) for local inspection limits and worked examples, and [delivery plan Section 14](RAG-AI-Phase1-Delivery-Plan.md) for pricing, account/quota checks and budget.
|
||||
|
||||
## 22. Current Live document MVP decisions - 2026-10-07
|
||||
|
||||
| Category | Current baseline |
|
||||
| --- | --- |
|
||||
| Confirmed product | Limited demo for known users; new browser uploads; all four examples; unknown future document count |
|
||||
| Confirmed framework | LangChain RAG/tools; direct Gemini Live audio loop |
|
||||
| Confirmed reuse | Implemented ingestion/embedding Phases 1-4 and repaired validation/staging; no wholesale embedding refactor |
|
||||
| Required next implementation | Fenced worker/review/resume/publication, scoped pgvector search, HTTP identity/upload, owned Live and minimal workspace |
|
||||
| Deferred milestone | Full text/history/citations, rich settings/delete UI, raw recording, seamless reconnect and CTI |
|
||||
| Proposed concrete contracts | D06/D07 evidence-bound review and preview, FAQ inclusion manifest, retained extraction_state and voice-only tool_calls |
|
||||
| Conditional delivery | Four implementation days; three optimistic; provider/QC/sample/network failure requires re-estimation |
|
||||
|
||||
Use delivery plan revision 1.3 for scope, API/database revision 1.3 for contracts
|
||||
and the implementation guide for workflows. Section 21 is a historical snapshot;
|
||||
older text/settings assumptions do not govern this milestone. No runtime,
|
||||
provider, database acceptance or quality result was executed by this document edit.
|
||||
|
||||
References for the integration boundary:
|
||||
[LangChain Embeddings](https://reference.langchain.com/python/langchain-core/embeddings/embeddings/Embeddings),
|
||||
[LangChain tools](https://docs.langchain.com/oss/python/langchain/tools),
|
||||
[retrieve and rerank](https://sbert.net/examples/sentence_transformer/applications/retrieve_rerank/README.html).
|
||||
@@ -0,0 +1,287 @@
|
||||
# Organization Knowledge Assistant - Live Document MVP Delivery Plan
|
||||
|
||||
| Field | Value |
|
||||
| --- | --- |
|
||||
| Version | 1.3 |
|
||||
| Date | 2026-10-07 |
|
||||
| Status | Current implementation baseline; mechanisms and unresolved deployment choices are proposed, not completion evidence |
|
||||
| Capacity assumption | One primary developer, existing ingestion Phases 1-4, basic same-origin UI |
|
||||
| Milestone | Four implementation days as a conditional demo target; three days is optimistic |
|
||||
| Scope authority | This plan governs the current MVP; it supersedes the previous 7-10 day text-and-voice milestone |
|
||||
|
||||
## 1. Release Objective
|
||||
|
||||
Deliver an authenticated Persian document assistant with this actual workflow:
|
||||
upload a new document in the browser -> extract and review where required ->
|
||||
chunk and embed -> publish completely -> activate -> ask a spoken question ->
|
||||
retrieve authorized evidence -> hear a grounded Persian answer and see sources.
|
||||
|
||||
Users upload new documents without developer intervention or per-file code.
|
||||
The total number of future uploads is unknown. The four supplied files are
|
||||
mandatory initial acceptance examples, not a filename/hash allowlist or the
|
||||
entire corpus. A session that speaks without searching uploaded knowledge does
|
||||
not fulfill the MVP.
|
||||
|
||||
The release is a limited demonstration for known users in one organization,
|
||||
with general upload within declared format, structural and resource bounds.
|
||||
It is not universal document parsing or a production capacity/SLA claim.
|
||||
Full text chat and durable message history move to the follow-up milestone.
|
||||
|
||||
## 2. Confirmed Direction, Current State and Day 1 Dependencies
|
||||
|
||||
Confirmed user direction: browser upload, all four supplied examples, new
|
||||
documents beyond those examples, LangChain, reuse of the implemented embedding
|
||||
pipeline, and backend-managed direct Gemini Live speech-to-speech.
|
||||
|
||||
| Existing component | Evidence and reuse boundary |
|
||||
| --- | --- |
|
||||
| Ingestion Phase 1 | Foundation settings, ports, bootstrap and seven-table migration exist |
|
||||
| Phase 2 | Immutable originals and trusted CLI intake/status/reconciliation exist; HTTP upload is not implemented |
|
||||
| Phase 3 | Extraction, normalization, semantic chunk drafts, QC gates and non-queryable candidates exist |
|
||||
| Phase 4 | Hosted embedding adapter, profile/token/vector validation and bounded memory staging exist |
|
||||
| Phase 5/6 | Worker, claim/lease fencing, retained-output review/resume backend services, retry, atomic publication and integration/operator handoff are implemented; authenticated D06/D07 transport remains pending |
|
||||
| Prototype | Markdown/Chroma/FastEmbed/LangGraph text path exists; it does not search the new uploaded-document pipeline |
|
||||
| Missing integration | HTTP identity/upload, review workflow, pgvector retrieval, LangChain integration, Live and UI remain planned |
|
||||
|
||||
Keep implemented validation, frozen processing/embedding profiles and applied
|
||||
migrations. Framework integration does not require changing embedding model,
|
||||
dimension, preprocessing or rebuilding compatible vectors. Recorded tests
|
||||
establish component behavior only; real hosted-provider quality, Persian
|
||||
speech and the complete workflow remain unverified.
|
||||
|
||||
In the first Day 1 work block, prove real Gemini audio, Persian output,
|
||||
transcription and a backend-executed function call on the intended network.
|
||||
Confirm funded embedding/extraction profiles and actual HTTPS hosting in the
|
||||
same day. Failed provider access changes the dependent estimate; it does not
|
||||
justify quietly replacing Live with text.
|
||||
|
||||
## 3. Included and Deferred Scope
|
||||
|
||||
| Area | Current MVP | Follow-up / deferred |
|
||||
| --- | --- | --- |
|
||||
| Identity | Fixed organization, pre-created accounts, simple cookie login, admin/user permissions and owner checks | Signup, invitations, SSO, multi-organization administration |
|
||||
| Documents | New browser uploads, list/status, minimal review and retry, active selection | Rich management, replacement automation, delete UI and retention automation |
|
||||
| Formats | PDF, DOCX, JPEG/PNG and existing UTF-8 Markdown, within configured structural/resource limits | Universal layout support and arbitrary formats |
|
||||
| Processing | Existing extraction/chunking/embedding components, separate durable worker, fenced recovery and complete publication | Distributed fleet, broker, batch checkpoint orchestration |
|
||||
| QC | Evidence-bound review of retained output and explicit factual FAQ approval; clear failures | Elaborate review editor and automatic quality classifier |
|
||||
| Search/framework | LangChain tool/retriever integration over one scoped pgvector search service; compatible query embedding and exact identifiers | Retrieval tuning UI; reranker/ANN only if measured failures justify them |
|
||||
| Voice | Direct Gemini Live through backend WSS, Persian speech, follow-ups, topic changes, interruption and visible failure | Seamless reconnect, raw recording, telephony/CTI |
|
||||
| Visible evidence | Current-session provider transcripts when delivered, retrieved sources with real locators | Guaranteed durable transcript, complete message history and exact spoken-claim attribution |
|
||||
| Persistence | Original files, jobs/chunks, review decisions, identity, owned voice/session/tool metadata | Durable text turns/messages/citations and cross-mode continuation |
|
||||
| Configuration | Fixed server profiles and seeded assistant name/instruction; read-only capabilities | Settings editor, model/voice selector and provider comparisons as required delivery work |
|
||||
| Deployment | One API, one worker, PostgreSQL/pgvector, durable files and same-origin HTTPS | High availability, autoscaling and certified load/SLA |
|
||||
|
||||
Deletion is not a required UI feature. Existing deletion exclusion, worker
|
||||
non-deletion checks and maintenance lifecycle invariants still apply.
|
||||
Simple retry is included where needed to resume approved extraction or an
|
||||
eligible failed job; it is not a new document or ready-document reindex.
|
||||
|
||||
## 4. User Interface
|
||||
|
||||
Use login plus one workspace with a voice area and an admin-only Documents area.
|
||||
Do not build the previous four-screen dashboard for this milestone.
|
||||
|
||||
The Documents area provides upload, title/filename, real processing state,
|
||||
safe error/retry feedback, inspection of retained extraction evidence where
|
||||
required, a minimal approval/rejection action and active selection controls.
|
||||
Expose configured upload limits. Do not promise arbitrary file success.
|
||||
An unreadable/unsupported accepted file fails visibly and remains unsearchable.
|
||||
|
||||
The voice area provides start/end, microphone/playback controls, connection
|
||||
state, partial/completed/interrupted provider transcripts when available,
|
||||
retrieved sources and clear recovery guidance. Do not invent transcript text
|
||||
or page numbers. Label evidence as retrieved sources unless actual answer
|
||||
attribution has been proved. Refreshing the page need not recover a full transcript.
|
||||
|
||||
## 5. Implementation Architecture
|
||||
|
||||
Use one modular FastAPI application, a separate ingestion worker from the
|
||||
same codebase, PostgreSQL/pgvector and durable file storage. LangChain is the
|
||||
RAG/tool framework; Gemini Live owns the native audio conversation loop.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
UI["Same-origin web workspace"] -->|"Upload and authenticated control"| API["FastAPI"]
|
||||
API --> FILES["Immutable originals and retained extraction"]
|
||||
API -->|"Durable jobs"| DB[("PostgreSQL + pgvector")]
|
||||
FILES --> WORKER["Existing pipeline + fenced worker"]
|
||||
WORKER -->|"Atomic publication"| DB
|
||||
API --> SEARCH["Shared search service / LangChain tool"]
|
||||
SEARCH --> DB
|
||||
UI <-->|"Authenticated audio/events WSS"| API
|
||||
API <-->|"Direct audio + correlated function calls/results"| LIVE["Gemini Live"]
|
||||
```
|
||||
|
||||
### 5.1 Existing embedding pipeline and LangChain boundary
|
||||
|
||||
Retain EmbeddingProvider.embed, OpenAICompatibleEmbeddings and stage_document.
|
||||
Use a thin LangChain Embeddings adapter only if an integration requires it;
|
||||
otherwise the custom retriever can call the existing service directly.
|
||||
Query embedding uses compatible identity and normalization. Preserve token,
|
||||
batch, response, float32/vector and memory limits; do not add stacked retries,
|
||||
silent truncation or a framework-driven replacement ingestion/index path.
|
||||
Provider/SQL work must not block audio handling.
|
||||
|
||||
### 5.2 Retrieval and native voice
|
||||
|
||||
The model requests search_knowledge; backend scope, budgets, deduplication and
|
||||
epoch checks govern execution. Search returns actual document/chunk IDs,
|
||||
evidence and nullable locators. Validate retrieval separately using an internal
|
||||
text-query harness; a shipped text chat/model loop is not a prerequisite.
|
||||
|
||||
Native Live can answer directly from returned evidence without a second text
|
||||
model per voice turn. Recheck scope before sending tool results. Flush queued
|
||||
playback on interruption and suppress late/cancelled results. Provider loss is
|
||||
visible; reconcile/close the old session before starting a fresh one.
|
||||
|
||||
### 5.3 Worker and review reliability
|
||||
|
||||
Persist uploads/jobs first. Claim with a token/lease, heartbeat during slow
|
||||
provider work and publish only under current ownership. Publish all chunks
|
||||
with ready/succeeded state in one transaction. Partial/staged output is never
|
||||
searchable. Keep new ready documents inactive until admin selection.
|
||||
|
||||
ReviewRequired currently stops PDF/image extraction. Implement bounded
|
||||
retained review candidates and decisions before claiming those formats work
|
||||
through the UI. Release the lease and use failed state with a review-required
|
||||
reason; do not add a waiting-review document state or hold a lease for a human.
|
||||
Approval applies to exact retained output, not a fresh OCR response.
|
||||
Reuse approved retained page output on same-document retry. Preserve complete
|
||||
extraction separately from vectors so OCR need not repeat solely for chunking.
|
||||
|
||||
## 6. Document Lifecycle and Knowledge Changes
|
||||
|
||||
Each upload is an independent immutable document. Jobs/chunks reference
|
||||
document_id and evidence references document_id/chunk_id. No content versions.
|
||||
An idempotent retry of an upload returns the same IDs; a new upload key creates
|
||||
an independent document even for identical bytes.
|
||||
|
||||
Document states remain queued -> processing -> ready or failed; active selection
|
||||
is separate. Retry reuses the same eligible failed document/job and frozen profile.
|
||||
New content needs a new upload. A replacement can be uploaded inactive, checked,
|
||||
then selected while the prior document is deselected.
|
||||
|
||||
Preserve configuration revision, knowledge_revision and access_epoch. Any active
|
||||
removal invalidates older organization conversation context and closes active
|
||||
Live sessions conservatively. A fresh session retrieves current evidence;
|
||||
it does not copy revoked history. Future deletion and current maintenance
|
||||
tombstones exclude content immediately. Physical purge policy is unresolved.
|
||||
|
||||
## 7. Minimum Persistent Data
|
||||
|
||||
Keep the seven existing foundation tables. Add reviewed forward migrations
|
||||
for auth_sessions, owned conversations, live_sessions, voice tool_calls and
|
||||
bounded retained extraction/review references as specified in the database design.
|
||||
Text turns/messages/citations are deferred; do not create a dependency on them
|
||||
for voice tool persistence. No raw audio or persistent provider credentials.
|
||||
|
||||
Unknown corpus size requires pagination, bounded per-document processing,
|
||||
durable backlog, disk/quota observation and explicit admission failure when
|
||||
capacity is exhausted. File/page/chunk/session limits are configurable
|
||||
deployment choices, not evidence of unlimited capacity or approved business policy.
|
||||
|
||||
## 8. Delivery Schedule and Checkpoints
|
||||
|
||||
| Day | Work | Exit condition |
|
||||
| --- | --- | --- |
|
||||
| 1 | Early Live/account/network/tool proof; confirm profiles; identity and durable browser upload | Persian audio/tool proof recorded and authenticated upload persists |
|
||||
| 2 | Phase 5 worker, retained extraction/review, retry and atomic publication using Phases 1-4 | All four example structures can reach ready through the actual workflow |
|
||||
| 3 | Scoped pgvector search, LangChain integration, Live knowledge tool, sources/follow-up/interruption | A newly uploaded active document supports a real spoken answer |
|
||||
| 4 | Finish basic UI, real HTTPS deployment, unseen-file and failure checks, rehearse | Full acceptance walkthrough succeeds on target device/network |
|
||||
|
||||
This is a conditional four-day target from the inspected current state, not
|
||||
four days to rebuild ingestion. Three days is optimistic. Numbered working days
|
||||
are not calendar commitments. If review/resume, sample fidelity, funded profiles
|
||||
or real audio/tool access fails, re-estimate and report the blocked gate.
|
||||
Do not meet the deadline by dropping sample support, upload, authorization or voice.
|
||||
|
||||
## 9. Acceptance Criteria
|
||||
|
||||
| ID | Check | Required outcome |
|
||||
| --- | --- | --- |
|
||||
| MVP-01 | Identity and ownership | Unauthenticated/normal-user mutations and other users' voice state are denied |
|
||||
| MVP-02 | New upload | A file not hardcoded in the repository is uploaded in the browser and persists |
|
||||
| MVP-03 | Sample coverage | Both supplied PDFs, the infographic and DOCX complete the workflow |
|
||||
| MVP-04 | Extraction fidelity | Dates/numbers/negation/exclusions, visual groups and all DOCX Q&A pair associations are retained |
|
||||
| MVP-05 | Review and FAQ | Exact retained output is approved/rejected; uncertain/unapproved/placeholder or behavioral content cannot become facts |
|
||||
| MVP-06 | Worker publication | Partial vectors remain absent; stale claims fail; crash/retry cannot duplicate publication |
|
||||
| MVP-07 | Scoped retrieval | Only authorized ready active undeleted documents return evidence with real IDs/locators |
|
||||
| MVP-08 | Voice grounding | Real Persian audio invokes backend search and receives supported spoken answers with visible evidence/transcript behavior |
|
||||
| MVP-09 | Conversation behavior | Follow-up, ambiguity, topic switch and interruption work without resurrecting cancelled output |
|
||||
| MVP-10 | Missing evidence and faults | Missing/conflicting evidence gets limitation/clarification; technical failures get explicit errors |
|
||||
| MVP-11 | Revocation and cleanup | Removal/logout/expiry closes sessions; revoked context and late results are not reused |
|
||||
| MVP-12 | Replay and restart | Repeated upload/review/retry/live create does not duplicate work; restart makes old media sessions unusable |
|
||||
| MVP-13 | Unseen documents and limits | Several new files of supported structures run without code changes; limit/unsupported failures are understandable |
|
||||
| MVP-14 | Deployment and handoff | Actual HTTPS/microphone/speaker/provider rehearsal plus reproducible startup and evidence |
|
||||
|
||||
Use an initial reference set of roughly 15-20 questions, then include unseen
|
||||
documents. Independently mark expected source passages; separate retrieval,
|
||||
answer support and spoken quality. A model score or successful fixture suite
|
||||
is not a factual accuracy percentage. Agree any numeric quality/concurrency/
|
||||
latency target; record observed latency and failures without inventing a SLA.
|
||||
All full text-chat/history acceptance belongs to the follow-up milestone.
|
||||
|
||||
## 10. Demonstration Script
|
||||
|
||||
1. Log in as admin and upload documents through the browser, including a new file.
|
||||
2. Show queued/processing and any required exact-output review, then ready.
|
||||
3. Activate the documents and start an owned voice session.
|
||||
4. Ask supported Persian questions from both PDFs, the infographic and factual FAQ.
|
||||
5. Show real evidence locators, number/exception fidelity and available transcript.
|
||||
6. Ask a follow-up, an ambiguous question, an unsupported question and switch topics.
|
||||
7. Interrupt the answer; show stopped playback and a correct new request.
|
||||
8. Deactivate a used source; show old-session invalidation and a fresh scoped session.
|
||||
9. Exercise provider loss, repeated requests and worker restart independently.
|
||||
10. Repeat upload/retrieval with previously unseen supported files.
|
||||
|
||||
Do not satisfy this script with pre-seeded hardcoded answers, a filename
|
||||
allowlist or a voice demo that never searches the uploaded documents.
|
||||
|
||||
## 11. Risks and Scope Control
|
||||
|
||||
Primary risks: exact-output review/resume backend services exist but authenticated
|
||||
D06/D07 transport is pending; mixed-source FAQ still needs real factual review; funded providers and Persian quality are
|
||||
unproven; the target network may fail; new file complexity and unknown backlog
|
||||
may exceed limits. Test these early and expose bounded failures.
|
||||
|
||||
Reduce UI polish, settings/history and optional ranking work first. Reranking
|
||||
is a measured follow-up or an explicitly re-estimated corrective task, not a
|
||||
guarantee that extraction/retrieval defects disappear. Stable framework and
|
||||
data-integrity boundaries are retained throughout.
|
||||
|
||||
## 12. Expansion After This MVP
|
||||
|
||||
Full grounded text chat with durable turns/messages/citations; richer settings
|
||||
and document administration; larger evaluation/capacity work; measured reranking
|
||||
or ANN; retention/cleanup; seamless audio reconnect and durable voice history.
|
||||
Broader architecture is context, not authority to add these to the four-day scope.
|
||||
|
||||
## 13. Release Handoff
|
||||
|
||||
Provide release revision, startup/migration/seed/worker commands, secret-free
|
||||
configuration, supported structure/limit matrix, reference and unseen-file
|
||||
results, actual provider/deployment evidence and known limitations.
|
||||
This documentation revision does not implement or certify the release.
|
||||
|
||||
## 14. Provider Budget and Validation
|
||||
|
||||
Select one funded Live profile, one compatible embedding profile and one
|
||||
extraction profile. Keep their usage separate. Confirm billing, account/region
|
||||
eligibility, current prices, quotas and remaining credit before paid trials.
|
||||
Reserve rehearsal capacity; no fixed dollar allocation or session count is
|
||||
guaranteed by this revision. The prior comparison budget is not a requirement
|
||||
to buy or integrate an extra text provider. Preserve already approved embedding
|
||||
identity; incompatible changes need a separately reviewed reindex/cutover.
|
||||
|
||||
## 15. Implementation Entry Gate and Remaining Decisions
|
||||
|
||||
Start with a real Live spike while completing worker/review integration.
|
||||
Confirm actual format/structure bounds, upload/page/storage limits, factual FAQ
|
||||
approval, funded model identities/dimension, reviewer availability, session
|
||||
TTL/capacity, HTTPS hosting, target-network reachability, quality targets and
|
||||
presentation date. Unknown future document count does not authorize unbounded
|
||||
resources. Storage retention/purge remains an owner decision.
|
||||
|
||||
Read the implementation guide for work packages, API/database contracts for
|
||||
transport/persistence and the English scenario report for concrete walkthroughs.
|
||||
The reference map/setup guide remain the evidence of existing component progress.
|
||||
@@ -0,0 +1,406 @@
|
||||
# RAG Assistant — Phase 1 API Catalog
|
||||
|
||||
Version 1.3 · 2026-10-07 · Current Live document MVP contract; planned endpoints are not claimed operational.
|
||||
|
||||
Companions: `RAG-Phase1-Implementation-Guide.md`, `RAG-Phase1-Database-Design.md`, `RAG-Phase1-MVP-Scenarios.md`. Scope follows `RAG-AI-Phase1-Delivery-Plan.md`. No document versioning is implemented: every upload is a new document; there is no version-upload route, model selector, mixed conversation or SSE in Phase 1.
|
||||
|
||||
## 1. Transport and common conventions
|
||||
|
||||
Base path `/api/v1`; UTF-8 JSON except multipart upload; same-origin HTTPS. UUIDs identify application records. Timestamps are UTC RFC3339. `null` means unavailable, not an invented source location. Unexpected request fields return 422. Example UUIDs are illustrative.
|
||||
|
||||
Secure HttpOnly `rag_session` cookie authenticates requests. Login and all mutations enforce trusted Origin; authenticated mutations also require `X-CSRF-Token`. `/me` returns a CSRF token for refresh. No frontend persistent provider key, organization ID override or model override is accepted.
|
||||
|
||||
Roles: `admin` and `user`. Both can create owned voice conversations and read/control their own Live state. Only admin manages uploads, review, retry and selection. Hidden resource access returns 404. Admin does not implicitly own all conversations. Full text chat/history, delete UI and settings mutation are deferred.
|
||||
|
||||
Lists use `limit` (default 20, maximum 100) and opaque `cursor`. Stable ordering is `(created_at DESC,id DESC)` except messages, ordered by ascending `sequence_no`. Responses use `{items:[],next_cursor:null}`. Unknown/invalid cursor returns 422. No total count is promised.
|
||||
|
||||
`X-Request-ID` response header and `error.request_id` correlate logs. Servers generate one if none is valid. `Idempotency-Key` is required on upload, manual ingestion retry and delete; UUID `client_request_id` is required in create-conversation, chat and create-live bodies. Keys are scoped to actor/organization and operation as specified below. Reuse with different normalized input returns 409.
|
||||
|
||||
Proposed field limits: deferred text message 8000 characters; assistant name 120; instruction 8000; search query 2000; conversation title 120; document title 200; review note 2000. File limits/formats and audio frame caps come from deployment configuration and are exposed as capabilities where useful. These are implementation defaults to confirm, not provider guarantees.
|
||||
|
||||
## 2. Endpoint inventory
|
||||
|
||||
| ID | Method and path | Access | Success | Delivery |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| A01 | POST `/auth/login` | Public, trusted Origin | 200 + cookie | MVP |
|
||||
| A02 | POST `/auth/logout` | Authenticated; expired/missing session accepted | 204 | MVP |
|
||||
| A03 | GET `/me` | Authenticated | 200 | MVP |
|
||||
| D01 | POST `/documents` | Admin | 202 | MVP |
|
||||
| D02 | GET `/documents` | Admin | 200 | MVP |
|
||||
| D03 | GET `/documents/{document_id}` | Admin | 200 | MVP |
|
||||
| D04 | POST `/documents/{document_id}/retry` | Admin | 202 | MVP |
|
||||
| D05 | DELETE `/documents/{document_id}?expected_revision=N` | Admin | 202 | Deferred |
|
||||
| D06 | GET `/documents/{document_id}/extraction-review` | Admin | 200 | MVP |
|
||||
| D07 | POST `/documents/{document_id}/extraction-review/decisions` | Admin | 200 | MVP |
|
||||
| K01 | GET `/knowledge-selection` | Admin | 200 | MVP |
|
||||
| K02 | PATCH `/knowledge-selection` | Admin | 200 | MVP |
|
||||
| F01 | GET `/configuration` | Authenticated | 200 | MVP |
|
||||
| F02 | PATCH `/configuration` | Admin | 200 | Deferred |
|
||||
| C01 | POST `/conversations` | Authenticated | 201 | MVP: voice only |
|
||||
| C02 | GET `/conversations` | Owner | 200 | Deferred |
|
||||
| C03 | GET `/conversations/{conversation_id}/messages` | Owner | 200 | Deferred |
|
||||
| T01 | POST `/chat` | Owner of text conversation | 200 or 202 | Deferred |
|
||||
| T02 | GET `/conversations/{conversation_id}/turns/{client_request_id}` | Owner | 200 | Deferred |
|
||||
| V01 | POST `/voice/sessions` | Owner of voice conversation | 201 or 202 | MVP |
|
||||
| V02 | GET `/voice/sessions/{session_id}` | Owner | 200 | MVP |
|
||||
| V03 | GET `/voice/sessions/by-request/{client_request_id}` | Owner | 200 | MVP |
|
||||
| V04 | POST `/voice/sessions/{session_id}/close` | Owner | 200 | MVP |
|
||||
| H01 | GET `/health/live` | Deployment health access | 200 | MVP |
|
||||
| H02 | GET `/health/ready` | Deployment health access | 200 or 503 | MVP |
|
||||
|
||||
Delivery labels define the current MVP. Deferred sections preserve future contracts, not routes required to ship now. F01 is read-only settings/capabilities; C01 only accepts mode=voice in this milestone. The old prototype POST /chat is not a scoped MVP consumer and must not be exposed as an authenticated replacement.
|
||||
|
||||
The inventory above lists application HTTP endpoints only. Proposed application Live WSS: `/api/v1/voice/sessions/{session_id}/stream` (authenticated upgrade, Section 7); this is distinct from the backend/provider Gemini WSS connection. Internal model tools have no public REST route.
|
||||
|
||||
Health paths are outside `/api/v1`. Register `/voice/sessions/by-request/...` before dynamic routes if the router needs that ordering. `search_knowledge` is internal and has no public HTTP route.
|
||||
|
||||
## 3. Authentication
|
||||
|
||||
### A01 — Login
|
||||
|
||||
```json
|
||||
{"username":"demo.admin","password":"<password>"}
|
||||
```
|
||||
|
||||
```json
|
||||
{"user":{"id":"01000000-0000-4000-8000-000000000001","username":"demo.admin","role":"admin","organization_id":"02000000-0000-4000-8000-000000000001"},"csrf_token":"<session-csrf-token>","expires_at":"2026-10-05T18:00:00Z"}
|
||||
```
|
||||
|
||||
Credentials invalid: 401 `INVALID_CREDENTIALS`; throttled: 429. Do not distinguish missing username from wrong password. Expiry above is illustrative. Set Secure/HttpOnly/SameSite=Lax cookie; rotate tokens after successful login.
|
||||
|
||||
### A02 — Logout
|
||||
|
||||
No body. Revoke current session, clear cookie and close owned live sessions linked to it. Repeated logout returns 204. For a valid session require CSRF; missing/expired session may simply clear cookie after Origin validation.
|
||||
|
||||
### A03 — Current identity
|
||||
|
||||
No body. Same identity/CSRF/expiry shape as login. Missing/expired session returns 401 `AUTH_REQUIRED`.
|
||||
|
||||
## 4. Documents and selected knowledge
|
||||
|
||||
### D01 — Upload
|
||||
|
||||
`multipart/form-data`: required `file`; optional `title`. Required `Idempotency-Key`. The server creates one independent document and ingestion job. New document is inactive.
|
||||
|
||||
Current local intake validates configured PDF, UTF-8 Markdown, DOCX, JPEG and PNG with byte/signature/package/image bounds and correct MIME. D01 accepts new files without a repository filename/hash allowlist. The four examples are acceptance fixtures, not upload eligibility. Stream/spool within configured limits; do not buffer an unbounded request. These engineering defaults do not imply every layout is extractable or total corpus capacity is unlimited. D01 HTTP transport remains planned.
|
||||
|
||||
```json
|
||||
{"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","is_active":false,"searchable":false}
|
||||
```
|
||||
|
||||
202 acknowledges durable metadata/job creation, not completed processing. Replay same upload returns these stable identities with current processing state and header `Idempotency-Replayed: true`. Scope key to organization; hash bytes and normalized title. 413 `FILE_TOO_LARGE`, 415 `UNSUPPORTED_FILE_TYPE`, 422 `INVALID_FILE`, 409 `IDEMPOTENCY_CONFLICT`. A parser failure after acceptance is represented by document status, not a later HTTP response to upload.
|
||||
|
||||
### D02 — List
|
||||
|
||||
Query: common pagination; optional `status=queued|processing|ready|failed`, `is_active=true|false`. Exclude deleted documents. Items use the D03 shape, except potentially omit verbose error detail. Return current `knowledge_revision` alongside the list.
|
||||
|
||||
### D03 — Detail / processing polling
|
||||
|
||||
```json
|
||||
{"id":"10000000-0000-4000-8000-000000000001","title":"Working Hours","filename":"working-hours.pdf","status":"ready","is_active":false,"searchable":false,"created_at":"2026-10-05T09:00:00Z","chunk_count":8,"job":{"id":"40000000-0000-4000-8000-000000000001","status":"succeeded","stage":"publish","attempt_count":1,"retry_generation":0,"can_retry":false,"error":null}}
|
||||
```
|
||||
|
||||
`searchable = ready AND active AND not deleted AND not content-purged`. A review-required failure is failed with a safe reason and `review_required:true`; it is not a new lifecycle state. Detail may include `review_required:false` for other outcomes. D06 supplies retained review evidence only to admins. Poll while queued/processing; proposed interval 2 seconds, slow down when tab is hidden. Failed job exposes `{code,message,retryable}` without internal stack traces. `can_retry` means server allows retry of the unchanged original; corrupt input generally requires new upload. Return 404 for deleted/hidden ID.
|
||||
|
||||
### D04 — Retry failed processing
|
||||
|
||||
No body; required `Idempotency-Key`. Eligible only for failed undeleted document and retained original. Requeue same job, reset attempt count, increment retry generation and audit. Same key replays without incrementing twice.
|
||||
|
||||
```json
|
||||
{"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","retry_generation":1}
|
||||
```
|
||||
|
||||
409 `DOCUMENT_NOT_RETRYABLE` for running/ready/unrecoverable failure; 404 hidden/deleted. Review-required retry becomes eligible only after all currently pending evidence-bound approvals exist; additional pages can require later review. An unapproved candidate returns 409 `EXTRACTION_REVIEW_PENDING`; rejection stays failed. Successful factual-corpus review is a separate precondition where required. No ready document is reindexed through retry. The retry-key record is retained in audit metadata with a database uniqueness constraint.
|
||||
|
||||
### D06 - Read retained extraction/factual review
|
||||
|
||||
Admin-only, paginated bounded review candidates. No provider calls. Return 404
|
||||
for hidden/deleted documents. A document with no pending candidates returns an
|
||||
empty items list. Example application shape:
|
||||
|
||||
```json
|
||||
{"document_id":"10000000-0000-4000-8000-000000000001","status":"failed","review_required":true,"items":[{"evidence_sha256":"<server-computed-digest>","review_kind":"extraction","location":{"page":1,"section":"pdf/page/1"},"blocks":[{"block_id":"pdf/page/1/block/1","text":"<retained exact extraction>","group_id":null}],"required_checks":["readability","order","completeness","numbers","dates","negation","exceptions"],"decision":null,"preview_path":"/api/v1/documents/10000000-0000-4000-8000-000000000001/extraction-review/<digest>/preview"}],"next_cursor":null}
|
||||
```
|
||||
|
||||
Serve the retained image on authenticated GET
|
||||
`/documents/{document_id}/extraction-review/{evidence_sha256}/preview`.
|
||||
This is a D06 subresource with the same admin/organization/candidate checks,
|
||||
configured byte/pixel limits, a validated image MIME and Cache-Control: no-store.
|
||||
It accepts no raw path or redirect and exposes no internal storage key.
|
||||
For factual_corpus candidates, preview_path may be null and blocks are grouped
|
||||
Q&A and their governing context with real source locators from the retained complete
|
||||
extraction. Context association is deterministic; ambiguous scope fails visibly.
|
||||
required_checks then includes factual
|
||||
authority, whole-pair association, behavioral separation and placeholders.
|
||||
Locators/digests are actual server values; illustrative strings are not API values.
|
||||
|
||||
### D07 - Decide on retained evidence
|
||||
|
||||
Required Idempotency-Key; normal admin Origin/CSRF checks. Server derives actor.
|
||||
One candidate decision per request; UI may submit multiple requests.
|
||||
|
||||
```json
|
||||
{"evidence_sha256":"<digest-from-D06>","decision":"approve","checked":["readability","order","completeness","numbers","dates","negation","exceptions"],"note":"Compared retained extraction against the original page.","excluded_group_ids":[]}
|
||||
```
|
||||
|
||||
200 returns document_id, evidence_sha256, decision and review_required indicating
|
||||
whether current pending decisions remain. It does not enqueue, activate or
|
||||
mark ready; D04 resumes the same failed job with its own key.
|
||||
|
||||
Allow approve/reject only. Require a nonblank bounded note; approval checked
|
||||
must match the server-required check set. For extraction, excluded_group_ids
|
||||
must be empty. For factual_corpus, permit only whole existing Q&A group IDs
|
||||
to exclude unapproved facts, behavioral entries or live-data placeholders.
|
||||
Store the inclusion manifest separately; never edit original/faithful extraction.
|
||||
An empty eligible factual set cannot be indexed.
|
||||
|
||||
Scope idempotency to organization/actor/document/extraction_review/key; hash
|
||||
the canonical decision, checks, note, evidence digest and excluded group IDs.
|
||||
Replay is resolved before new state checks but after authorization; it returns
|
||||
the saved decision without mutating current candidate state. Changed payload
|
||||
returns 409 IDEMPOTENCY_CONFLICT. A new conflicting decision for an already
|
||||
decided candidate returns 409 REVIEW_ALREADY_DECIDED. Removed/superseded evidence,
|
||||
wrong failed-job state or profile/source mismatch returns 409 REVIEW_STALE.
|
||||
Invalid digest/check/group shape returns 422 VALIDATION_ERROR.
|
||||
|
||||
A valid digest alone grants no access. Recompute/validate trusted retained
|
||||
candidate identity under the document/job locks; don't trust client blocks,
|
||||
paths, models or reviewer fields. Rejecting keeps zero publication and a safe
|
||||
failure reason. Lost worker ownership cannot attach candidates; an admin cannot
|
||||
approve a fresh OCR response using an old digest.
|
||||
|
||||
### D05 — Delete (deferred HTTP/UI)
|
||||
|
||||
Required `expected_revision` is the current knowledge revision; required idempotency key. Transaction locks selection and document. Mark deleted and inactive; if formerly active, increment knowledge revision and access epoch and invalidate sessions. Physical cleanup is not promised by this response.
|
||||
|
||||
```json
|
||||
{"document_id":"10000000-0000-4000-8000-000000000001","deleted":true,"knowledge_revision":3,"access_epoch":2,"cleanup_status":"pending_policy"}
|
||||
```
|
||||
|
||||
202; 409 `REVISION_CONFLICT` on stale initial request. Replay same delete/key returns recorded result before revision validation. A new delete request for an already-deleted owned document can return its tombstone result without changing revisions. No read or search route restores eligibility.
|
||||
|
||||
### K01 — Get selection
|
||||
|
||||
```json
|
||||
{"revision":1,"access_epoch":1,"document_ids":[]}
|
||||
```
|
||||
|
||||
### K02 — Replace selected set
|
||||
|
||||
This replaces the entire set, not a delta. UI reads current selection before toggling a document.
|
||||
|
||||
```json
|
||||
{"expected_revision":1,"document_ids":["10000000-0000-4000-8000-000000000001"]}
|
||||
```
|
||||
|
||||
```json
|
||||
{"revision":2,"access_epoch":1,"document_ids":["10000000-0000-4000-8000-000000000001"],"conversations_invalidated":false}
|
||||
```
|
||||
|
||||
Duplicate IDs: 422. Any unready item: 409 `DOCUMENT_NOT_READY`, with rejected IDs in details; no partial update. Hidden ID: 404. Stale revision: 409 `REVISION_CONFLICT`. No-op preserves revision. Removing an active ID increments epoch and sets `conversations_invalidated=true`; all older organization conversations become unusable for new turns. After a timeout GET current state instead of blindly repeating with an old revision.
|
||||
|
||||
## 5. Configuration (read-only in MVP)
|
||||
|
||||
### F01 — Read
|
||||
|
||||
```json
|
||||
{"revision":1,"assistant_name":"Organization Assistant","instruction":"Reply concisely in Persian using authorized document evidence.","capabilities":{"text":false,"voice":true,"captions":true,"supported_upload_types":["<confirmed-MIME-type>"],"max_upload_bytes":null}}
|
||||
```
|
||||
|
||||
Runtime must replace illustrative capability placeholders with actual configuration; `max_upload_bytes` is a positive integer in deployed responses. Add configured `max_pdf_pages` and a bounded `supported_structure_notes` description. Voice/captions capabilities reflect validated provider support, not assumed availability; captions=true above is the intended release outcome. The browser must not advertise full text chat. No settings mutation UI is required. No model secrets or selectable model list. Non-admin may read presentation settings/capabilities.
|
||||
|
||||
### F02 — Update (deferred)
|
||||
|
||||
```json
|
||||
{"expected_revision":1,"assistant_name":"HR Assistant","instruction":"Use formal Persian and state when supporting evidence is missing."}
|
||||
```
|
||||
|
||||
200 returns F01 with incremented revision. Both fields are required; no-op preserves revision. Stale value: 409 `REVISION_CONFLICT`. Text applies on subsequent turns; existing live session keeps its snapshot until restarted. Settings cannot relax system authorization or grounding rules.
|
||||
|
||||
## 6. Conversations and deferred text
|
||||
|
||||
### C01 — Create
|
||||
|
||||
```json
|
||||
{"client_request_id":"50000000-0000-4000-8000-000000000001","mode":"voice","title":"Working hours"}
|
||||
```
|
||||
|
||||
```json
|
||||
{"id":"60000000-0000-4000-8000-000000000001","mode":"text","title":"Working hours","status":"active","access_epoch":1,"created_at":"2026-10-05T09:05:00Z"}
|
||||
```
|
||||
|
||||
The current MVP accepts `mode=voice` only; text/mixed requests return 409 `MODE_MISMATCH`. Follow-up text support uses a separate mode and must not silently alter the voice contract. Title optional. Idempotency scope `(owner,client_request_id)`; same payload replays original 201. Different payload 409. New conversation snapshots current epoch. Voice history cannot be continued as text in Phase 1.
|
||||
|
||||
### C02 — List own conversations (deferred history UI)
|
||||
|
||||
Common pagination, optional `mode`. Items use C01 response plus `updated_at`; derive `status=stale` when epoch differs. Status values: active, stale, closed. List excludes other users regardless of role.
|
||||
|
||||
### C03 — Read messages (deferred)
|
||||
|
||||
Common pagination, ascending sequence. Voice can return no durable messages: current-session answer transcripts are delivered through Live events when available; durable full voice history is deferred. Old text history remains viewable even when stale.
|
||||
|
||||
```json
|
||||
{"conversation_id":"60000000-0000-4000-8000-000000000001","conversation_status":"active","items":[{"id":"70000000-0000-4000-8000-000000000001","turn_id":"80000000-0000-4000-8000-000000000001","sequence_no":1,"role":"user","content":"What are the Thursday opening hours?","created_at":"2026-10-05T09:06:00Z","sources":[]}],"next_cursor":null}
|
||||
```
|
||||
|
||||
Assistant items also expose `turn_status` and source objects. Failed turns remain visible as state, not fabricated assistant answers. A user message may exist without an assistant reply; UI follows turn status.
|
||||
|
||||
### T01 — Submit text turn (deferred)
|
||||
|
||||
```json
|
||||
{"conversation_id":"60000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","message":"What are the Thursday opening hours?"}
|
||||
```
|
||||
|
||||
```json
|
||||
{"conversation_id":"60000000-0000-4000-8000-000000000001","turn_id":"80000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","status":"answered","message_id":"70000000-0000-4000-8000-000000000002","answer":"The illustrative working-hours document states Thursday closing is noon.","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Working Hours","excerpt":"Illustrative Thursday hours: 08:00 to 12:00.","location":{"page":2,"section":null},"available":true}],"error":null}
|
||||
```
|
||||
|
||||
200 returns terminal execution: answered, needs_clarification, insufficient_information or failed. `answer`/`message_id` are null on failed, with normalized error. A successfully processed unsupported question uses insufficient_information, human-readable answer and usually empty sources. Failed generation is not reported as a successful answer.
|
||||
|
||||
202 returns a running turn shape with `answer:null`, `message_id:null`, empty sources, `error:null` and `Location` pointing to T02. This occurs on duplicate running request or when the initial response deadline expires while the owned task is still running. Do not start a second task. Client disconnection must not silently create duplicate execution.
|
||||
|
||||
Scope key `(conversation_id,client_request_id)`. Changed message under same key: 409. Another different request while one runs: 409 `CONVERSATION_BUSY`. Wrong mode: 409 `MODE_MISMATCH`. Stale epoch: 409 `CONVERSATION_STALE`. Admission failures use the common HTTP error envelope; failures after a turn is persisted use its failed terminal result. Retry completed failures only with a new request ID.
|
||||
|
||||
### T02 — Recover/poll turn (deferred)
|
||||
|
||||
Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.
|
||||
|
||||
## 7. Voice contract — direct Gemini Live; proposed application WSS
|
||||
|
||||
The initial provider is direct Gemini Live managed by the backend. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. None is verified as implemented. Audio/event field names below are proposed application names, not provider-native event names.
|
||||
|
||||
### V01 — Create session (HTTP)
|
||||
|
||||
```json
|
||||
{"conversation_id":"61000000-0000-4000-8000-000000000001","client_request_id":"91000000-0000-4000-8000-000000000001"}
|
||||
```
|
||||
|
||||
```json
|
||||
{"session_id":"a0000000-0000-4000-8000-000000000001","conversation_id":"61000000-0000-4000-8000-000000000001","status":"connecting","stream_path":"/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001/stream","expires_at":"2026-10-06T09:30:00Z","poll_url":"/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001"}
|
||||
```
|
||||
|
||||
Voice conversation must be owned and current-epoch. Reserve session before provider creation. Scope key `(owner,client_request_id)`; hash normalized conversation/create options, with no SDP. Changed payload is 409. One nonterminal session per conversation. Duplicate creation returns 202 and the existing ID/state; completed replay returns 201 with the same still-eligible session. Replay never creates another provider connection. Closed/failed/expired returns 409 `LIVE_SESSION_UNUSABLE`.
|
||||
|
||||
No persistent provider secret or provider credential is returned. Backend adapter installs tools/Persian policy and enables available transcription before marking usable. Provider timeout leaves failed/uncertain reservation: inspect with V03, never blind recreation. 503 can represent a capability failure before reservation. `connecting` is not proof of working audio.
|
||||
|
||||
### V02 — Poll state, diagnostics and recent retrieved sources (HTTP)
|
||||
|
||||
```json
|
||||
{"session_id":"a0000000-0000-4000-8000-000000000001","status":"connected","close_reason":null,"expires_at":"2026-10-06T09:30:00Z","recent_tool_results":[{"tool_call_id":"b0000000-0000-4000-8000-000000000001","status":"succeeded","created_at":"2026-10-06T09:08:00Z","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Illustrative circular","excerpt":"<verified source passage>","location":{"page":1,"section":"<verified clause>"},"available":true}]}]}
|
||||
```
|
||||
|
||||
Illustrative payload; not an extracted source quotation. At most 20 recent results, chronological, deduplicate by tool_call_id. Sources are retrieved evidence unless exact answer attribution is verified. Redact revoked excerpts and mark unavailable. States: creating, connecting, connected, closed, failed. Poll approximately every 2 seconds while active; stop at terminal state. Polling is not durable transcript recovery. A client cannot claim connected state or inject a trusted tool result.
|
||||
|
||||
### V03 — Recover creation by request ID (HTTP)
|
||||
|
||||
200 returns V01's session/path shape if reservation remains eligible, otherwise terminal state and `stream_path:null`. Owner-only, 404 if no reservation, never creates a session. Before starting a fresh request after media loss, reconcile/close the old session. The old path does not restore provider context.
|
||||
|
||||
### V04 — Close (HTTP)
|
||||
|
||||
No body. 200 `{session_id,status:"closed",close_reason:"user_requested"}`. Already terminal returns its existing state. Close application stream/microphone/playback and attempt provider cleanup. Unresolved cleanup is logged and bounded by expiry; logout, auth expiry, epoch revocation and provider loss also close the session.
|
||||
|
||||
### 7.1 Application Live stream (WebSocket)
|
||||
|
||||
Proposed WSS upgrade on the V01 `stream_path`: authenticate cookie, trusted Origin, owner, auth session, current epoch and unexpired reservation before accepting. HTTP creation requires normal CSRF; the browser WebSocket handshake uses cookie/Origin validation, not an assumed arbitrary CSRF header. Reject extra caller/model scope. One media connection per session; an additional connection is refused and does not open another provider session.
|
||||
|
||||
Proposed binary client frames carry mono PCM16 little-endian at 16 kHz; server audio frames carry PCM16 at 24 kHz. These rates and bounded frame/buffer limits are agreed at stream setup. JSON control/events are distinguished from binary audio. Bridge/transcoding is backend/client work, not a public provider key flow.
|
||||
|
||||
Illustrative proposed control/event shapes:
|
||||
|
||||
```json
|
||||
{"type":"session_ready","session_id":"a0000000-0000-4000-8000-000000000001","input_audio":{"encoding":"pcm_s16le","sample_rate":16000,"channels":1},"output_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}
|
||||
```
|
||||
|
||||
```json
|
||||
{"type":"transcript","turn_ref":"live-turn-1","role":"assistant","text":"<provider-supplied Persian transcript>","status":"completed"}
|
||||
```
|
||||
|
||||
```json
|
||||
{"type":"sources","turn_ref":"live-turn-1","tool_call_id":"call-1","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Illustrative circular","location":{"page":1,"section":null}}]}
|
||||
```
|
||||
|
||||
```json
|
||||
{"type":"turn_interrupted","turn_ref":"live-turn-1","cancelled_tool_call_ids":["call-1"]}
|
||||
```
|
||||
|
||||
```json
|
||||
{"type":"error","turn_ref":"live-turn-2","error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}}
|
||||
```
|
||||
|
||||
Transcript status is partial, completed or interrupted. The adapter must prove turn/event correlation for the selected provider; `turn_ref` is an application correlation field, not a new database identity contract. UI retains available transcript and sources for the current session, marks missing transcript unavailable and labels retrieval-only sources accurately. No raw recording or guaranteed durable full transcript is introduced.
|
||||
|
||||
On interruption, flush audio buffers, mark partial output, cancel outstanding calls when possible and suppress late results. On disconnection/restart, mark old session unusable and start a new one after reconciliation; seamless reconnect/context restoration is deferred. Do not replay audio/tool events as fresh turns. Use bounded buffers, idle/creation/tool deadlines and existing session TTL; values require deployment validation.
|
||||
|
||||
### 7.2 Internal model tool — `search_knowledge`
|
||||
|
||||
Model arguments, identical for the internal text-query harness, later text chat and Live. The LangChain tool uses this schema while trusted dispatcher context supplies authority:
|
||||
|
||||
```json
|
||||
{"query":"What are the conditions and exceptions of the circular?","context":"The circular identified as source S1 in the preceding exchange."}
|
||||
```
|
||||
|
||||
`query` required, 1–2000 characters; optional `context` proposed maximum 2000 characters, a conversation-resolved textual reference. Reject unknown fields. Context does not grant permission or turn previous model prose into evidence. No model-supplied organization/user IDs or paths; supported document filters remain deferred. Backend derives identity, current selected ready/active/undeleted scope, profile, bounded top_k/evidence size and execution IDs.
|
||||
|
||||
Illustrative successful result; text/location must be populated from actual retained chunks, never from these placeholders:
|
||||
|
||||
```json
|
||||
{
|
||||
"status":"ok",
|
||||
"knowledge_revision":2,
|
||||
"sources":[{
|
||||
"source_ref":"S1",
|
||||
"document_id":"10000000-0000-4000-8000-000000000001",
|
||||
"chunk_id":"30000000-0000-4000-8000-000000000001",
|
||||
"title":"Illustrative administrative circular",
|
||||
"text":"<verified decision together with conditions and exclusions>",
|
||||
"location":{"page":1,"section":"<verified clause or heading>"}
|
||||
}],
|
||||
"warnings":[]
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{"status":"no_evidence","knowledge_revision":2,"sources":[],"warnings":["insufficient_support"]}
|
||||
```
|
||||
|
||||
```json
|
||||
{"status":"error","sources":[],"error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}}
|
||||
```
|
||||
|
||||
`no_evidence` is completed retrieval with insufficient support, not a provider failure. Contradictory passages may be returned with `warnings:["conflicting_evidence"]`; ask clarification or disclose conflict instead of silently resolving policy. `error` also covers provider unavailable/profile mismatch/revoked context, with normalized codes and safe retryability. Document claims require current supporting passages; greeting/clarification may omit search.
|
||||
|
||||
Locators use existing `location.page/section`. DOCX and image use page null, with table/row/Q&A or visual-group location in section. Same search backend/profile serves all extracted text. Source refs are unique across a turn and validated against returned evidence.
|
||||
|
||||
Deduplicate by parent session/turn plus provider call ID and normalized argument hash. Same running call waits; same completed call replays only after fresh eligibility/epoch checks; changed payload conflicts. Cancelled/closed/stale-parent results are not sent back to generate a new answer. No tool request becomes a public REST upload/search endpoint. The MVP persists voice tool_calls independently of deferred text turns/messages/citations. Cancelled work is terminal failed with a cancellation reason and cannot be replayed to resume speech.
|
||||
|
||||
## 8. Health
|
||||
|
||||
H01: 200 `{"status":"ok"}` when the process is alive. H02: 200 `{"status":"ready","ingestion":"available"}` or degraded ingestion marker if worker heartbeat is stale; 503 `{"status":"not_ready"}` for required DB/schema/storage failure. Health responses never disclose connection strings or provider keys. Provider outages surface in relevant business operations, not liveness.
|
||||
|
||||
## 9. Error envelope and mapping
|
||||
|
||||
```json
|
||||
{"error":{"code":"REVISION_CONFLICT","message":"Selection changed; reload and try again.","request_id":"req-example","retryable":false,"details":{"current_revision":3}}}
|
||||
```
|
||||
|
||||
| HTTP | Codes / use | Client action |
|
||||
| --- | --- | --- |
|
||||
| 401 | AUTH_REQUIRED, INVALID_CREDENTIALS | Login; do not retry provider work |
|
||||
| 403 | FORBIDDEN, CSRF_INVALID | Show denial or refresh session token |
|
||||
| 404 | NOT_FOUND | Stop; do not expose ownership details |
|
||||
| 409 | REVISION_CONFLICT | Read latest selection/configuration |
|
||||
| 409 | IDEMPOTENCY_CONFLICT | Correct client request/key handling |
|
||||
| 409 | CONVERSATION_BUSY, CONVERSATION_STALE, MODE_MISMATCH | Poll current turn, start fresh conversation, or correct mode |
|
||||
| 409 | DOCUMENT_NOT_READY, DOCUMENT_NOT_RETRYABLE, LIVE_SESSION_UNUSABLE | Follow returned state |
|
||||
| 409 | EXTRACTION_REVIEW_PENDING, REVIEW_STALE, REVIEW_ALREADY_DECIDED | Refresh exact review evidence or follow the recorded decision |
|
||||
| 413/415/422 | FILE_TOO_LARGE, UNSUPPORTED_FILE_TYPE, VALIDATION_ERROR | Correct input |
|
||||
| 429 | RATE_LIMITED | Honor Retry-After; reuse key when retrying same operation |
|
||||
| 503 | DEPENDENCY_UNAVAILABLE | Show service failure; reconcile state before retry |
|
||||
|
||||
Inside persisted jobs/sessions/tool calls, normalized codes include PROVIDER_TIMEOUT, PROVIDER_UNAVAILABLE, SEARCH_FAILED, PROCESS_INTERRUPTED, CONVERSATION_STALE, TOOL_CANCELLED and EXTRACTION_REVIEW_REQUIRED. Review-required is a controlled human-action failure, not an automatic transient-provider retry. INVALID_CITATION and failed text-turn responses belong to the deferred text contract. An HTTP 200 failed-turn result still represents application failure. Technical retryability does not authorize automatic regeneration under a new key.
|
||||
|
||||
## 10. Frontend implementation order and exclusions
|
||||
|
||||
Prove real native audio/tools early. Build A01/A03, bounded upload/polling, D06/D07 review and D04 resume, selection, C01 voice creation, V01-V04/WSS and read-only F01 capabilities. Full T01/T02/messages and settings editing are deferred. Display request progress and state rather than a fake percentage. Disable selection on non-ready documents. On stale conversation explain that sources changed and offer New Conversation. Do not automatically copy revoked context.
|
||||
|
||||
Out of scope: file-version API, raw downloads for ordinary users, document text editing, search HTTP endpoint, model selector, raw audio recording, streamed chat, mixed-mode history, full event replay. Sources needed by normal users are supplied in authorized message/session responses.
|
||||
@@ -0,0 +1,456 @@
|
||||
# RAG Assistant — Phase 1 Database Design
|
||||
|
||||
Version 1.3 · 2026-10-07 · Live document MVP persistence contract; proposed forward changes are not applied migrations.
|
||||
|
||||
Companions: `RAG-Phase1-Implementation-Guide.md` and `RAG-Phase1-API-Catalog.md`. Scope: PostgreSQL + pgvector, one organization, existing ingestion foundation, retained review decisions and owned voice/session/tool metadata. Durable text turns/messages/citations are deferred. No deployed database was queried; the repository foundation migration was inspected statically for this documentation update. Only seven foundation tables are currently implemented; compare this complete proposal with actual migrations before applying it. Live tables/SDP fields are not applied foundation schema.
|
||||
|
||||
Document revision 1.3 is not an Alembic schema revision. Preserve the seven applied foundation tables/migration. The active MVP adds four tables: auth_sessions, conversations, live_sessions and voice-only tool_calls (eleven total), plus forward changes for retained review state/audit action. The fourteen-table broader text design is deferred. Document identities remain direct; technical revisions/profiles are not content versions.
|
||||
|
||||
## 1. Conventions
|
||||
|
||||
All IDs are application-generated UUIDs. `uuid PK` means primary key. Timestamps are `timestamptz` in UTC; `created_at` defaults to database now. Unless marked nullable, fields are NOT NULL. JSON defaults are `{}` or `[]` as appropriate. Status fields use text plus CHECK constraints for simple evolution. Hashes use lowercase SHA-256 hex (`char(64)`), except password hashes which use the selected password library's encoded format. Counters use integer/bigint and CHECK >= 0; revisions/sequence numbers start at 1.
|
||||
|
||||
Tables other than settings have a UUID `id` PK. Settings uses `organization_id` as PK. Every organization-owned table has `organization_id uuid` referencing organizations, even where derivable. For all referenced scoped entities add `UNIQUE(organization_id,id)` and use composite scoped foreign keys. This prevents a valid UUID from another organization being attached accidentally. Do not treat UUID unpredictability as access control.
|
||||
|
||||
Use RESTRICT/NO ACTION for normal deletion; no broad CASCADE from users/documents into historical chats. Soft deletion and explicit cleanup control lifecycle. Owners/roles are checked by application queries. Single-organization deployment does not justify dropping organization filtering. Row-level security is deferred, not claimed to be enabled.
|
||||
|
||||
## 2. Relationship overview
|
||||
|
||||
The active MVP uses owned voice conversations and voice tool records:
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
documents ||--o{ document_chunks : contains
|
||||
documents ||--|| ingestion_jobs : processes
|
||||
users ||--o{ auth_sessions : authenticates
|
||||
users ||--o{ conversations : owns
|
||||
conversations ||--o{ live_sessions : hosts
|
||||
auth_sessions ||--o{ live_sessions : authorizes
|
||||
live_sessions ||--o{ tool_calls : executes
|
||||
```
|
||||
|
||||
The following diagram is the deferred text-and-voice model; it is not a migration requirement for the current milestone:
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
documents ||--o{ document_chunks : contains
|
||||
documents ||--|| ingestion_jobs : processes
|
||||
conversations ||--o{ turns : contains
|
||||
turns ||--o{ messages : records
|
||||
turns ||--o{ citations : supports
|
||||
conversations ||--o{ live_sessions : hosts
|
||||
turns |o--o{ tool_calls : text_calls
|
||||
live_sessions |o--o{ tool_calls : voice_calls
|
||||
```
|
||||
|
||||
The diagram omits identity/configuration/audit for readability. Each tool call belongs to exactly one text turn OR one live session. A citation also references the exact tool call/evidence that produced its chunk. These relationships are defined below.
|
||||
|
||||
## 3. Identity and organization tables
|
||||
|
||||
### 3.1 organizations
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id | uuid PK | Fixed seeded organization |
|
||||
| name | varchar(200) | Display name |
|
||||
| created_at | timestamptz now | Creation |
|
||||
|
||||
### 3.2 users
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id | uuid | Identity and organization |
|
||||
| username | varchar(120) | Canonical lowercase login name |
|
||||
| password_hash | text | Salted adaptive password hash; never plaintext |
|
||||
| role | text | admin or user |
|
||||
| is_enabled | boolean true | Account authorization |
|
||||
| created_at, updated_at | timestamptz | Audit timestamps |
|
||||
|
||||
Unique username globally for simple login without organization selector. CHECK role. Add UNIQUE(organization_id,id). Disabling a user revokes sessions and closes live sessions; account-management UI is deferred (maintenance command only).
|
||||
|
||||
### 3.3 auth_sessions
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, user_id | uuid | Session owner |
|
||||
| token_hash | char(64) UNIQUE | Hash of opaque cookie token |
|
||||
| created_at, expires_at, last_seen_at | timestamptz | Lifetime |
|
||||
| revoked_at | timestamptz nullable | Explicit revocation |
|
||||
|
||||
Composite FK to users. CHECK expires_at > created_at. Index expires_at for cleanup. Never store raw cookie. Derive CSRF token from raw session cookie using a separate server-side HMAC secret (or an equivalent reviewed synchronizer mechanism); compare in constant time. `/me` can reproduce it without persisting a raw CSRF token.
|
||||
|
||||
### 3.4 organization_settings
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| organization_id | uuid PK/FK | One row per organization |
|
||||
| assistant_name | varchar(120) | UI/model name |
|
||||
| instruction | text | Organization instruction, API length limit |
|
||||
| revision | bigint 1 | Settings optimistic revision |
|
||||
| knowledge_revision | bigint 1 | Selected-set revision |
|
||||
| access_epoch | bigint 1 | Invalidation counter for removals |
|
||||
| updated_by | uuid nullable | Actor; scoped FK to users |
|
||||
| updated_at | timestamptz | Last configuration/selection mutation |
|
||||
|
||||
CHECK all counters >= 1. Selection uses documents.is_active; no assignment table in Phase 1. Lock this row first for selection, context creation and finalization to impose a consistent order.
|
||||
|
||||
## 4. Knowledge tables
|
||||
|
||||
### 4.1 documents
|
||||
|
||||
Each upload is one independent immutable document. This table owns file metadata and processing state directly. There is no document-version table or version-number field. Replacement means a new upload/document ID, followed by active-selection change after readiness. The same idempotent upload replay returns the original ID.
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, uploaded_by | uuid | Identity and admin actor |
|
||||
| title | varchar(200) | Display title |
|
||||
| original_filename | text | Display only, never trusted path |
|
||||
| upload_request_id | uuid | Upload Idempotency-Key |
|
||||
| upload_payload_hash | char(64) | File bytes + normalized metadata digest |
|
||||
| storage_key | text UNIQUE | Generated original-file reference |
|
||||
| file_sha256 | char(64) | Original bytes hash |
|
||||
| mime_type | text | Validated MIME |
|
||||
| size_bytes | bigint | Original size > 0 |
|
||||
| status | text queued | queued, processing, ready, failed |
|
||||
| processing_profile | jsonb | Extractor/chunk/embedding settings |
|
||||
| chunk_count | integer 0 | Published chunk count |
|
||||
| ready_at | timestamptz nullable | Successful publication |
|
||||
| is_active | boolean false | Organization selection |
|
||||
| deleted_at | timestamptz nullable | Soft deletion |
|
||||
| content_purged_at | timestamptz nullable | Explicit future cleanup marker |
|
||||
| created_at, updated_at | timestamptz | Timestamps |
|
||||
|
||||
UNIQUE(organization_id,upload_request_id). Scoped FK uploaded_by→users. CHECK size_bytes > 0, chunk_count >= 0. CHECK ready implies ready_at IS NOT NULL and chunk_count > 0. CHECK is_active implies status='ready', deleted_at IS NULL and content_purged_at IS NULL. Storage keys are generated and unique; no automatic same-hash deduplication between documents.
|
||||
|
||||
Do not overwrite the original bytes or republish a ready document. Manual retry accepts only eligible failed documents; first successful publication fixes the source/chunk identities. If content changes, upload a new independent document. Physical purging must first deactivate the document; retained metadata is a tombstone, never eligible search content.
|
||||
|
||||
Freeze the actual snapshot produced by IngestionSettings.processing_profile,
|
||||
including current schema-2 extraction/normalization/chunking and embedding
|
||||
identity/request limits. Do not replace it with the older illustrative flat
|
||||
JSON profile. Current extraction/chunking/embedding components are implemented;
|
||||
their worker integration and atomic publication are implemented for the requested Phase 5 worker scope. Dimension D is explicit;
|
||||
equal dimensions alone do not make models compatible. LangChain integration
|
||||
does not change these snapshots or require re-embedding compatible vectors.
|
||||
|
||||
### 4.2 document_chunks
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, document_id | uuid | Source identity |
|
||||
| ordinal | integer | 0-based order |
|
||||
| text | text | Extracted evidence |
|
||||
| location | jsonb | `{page: integer-or-null, section: string-or-null}`; section may identify table/row/Q&A or image group |
|
||||
| token_count | integer nullable | Actual tokenizer count if available |
|
||||
| embedding | vector(D) | Model-compatible vector |
|
||||
| created_at | timestamptz | Publication |
|
||||
|
||||
UNIQUE(document_id,ordinal); CHECK ordinal >= 0 and length(text)>0; token_count >= 0 when set. FK document scoped. Page is positive when present. Do not invent a page index for a format without pages.
|
||||
|
||||
Index document_id; initial small-corpus search uses exact cosine distance after eligibility joins. Defer ANN/HNSW until measured latency requires it. If later added, validate filtered-search recall. Example query is parameterized and conceptual (D is a migration parameter):
|
||||
|
||||
```sql
|
||||
SELECT c.id, c.text, c.location, d.id AS document_id,
|
||||
c.embedding <=> CAST(:query_vector AS vector) AS distance
|
||||
FROM document_chunks c
|
||||
JOIN documents d ON d.id = c.document_id AND d.organization_id = c.organization_id
|
||||
WHERE d.organization_id = :organization_id
|
||||
AND d.is_active = true AND d.deleted_at IS NULL
|
||||
AND d.status = 'ready' AND d.content_purged_at IS NULL
|
||||
ORDER BY c.embedding <=> CAST(:query_vector AS vector), c.id
|
||||
LIMIT :top_k;
|
||||
```
|
||||
|
||||
Server validates profile, dimension and bounded top_k before query. A nearest neighbor is not automatically sufficient evidence; no universal distance threshold is assumed.
|
||||
|
||||
### 4.3 ingestion_jobs
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, document_id | uuid | One job per document |
|
||||
| status | text queued | queued, processing, succeeded, failed |
|
||||
| stage | text extract | extract, chunk, embed, publish |
|
||||
| attempt_count | integer 0 | Claims within current retry generation |
|
||||
| retry_generation | integer 0 | Manual retries |
|
||||
| next_attempt_at | timestamptz now | Backoff scheduling |
|
||||
| claim_token | uuid nullable | Fencing token |
|
||||
| lease_expires_at | timestamptz nullable | Worker lease |
|
||||
| claimed_by | text nullable | Worker process identifier |
|
||||
| error_code, error_message | text nullable | Redacted failure |
|
||||
| error_retryable | boolean false | Eligibility hint |
|
||||
| created_at, updated_at | timestamptz | Timestamps |
|
||||
|
||||
UNIQUE(document_id). CHECK processing requires claim_token and lease_expires_at; non-processing clears them. Index `(status,next_attempt_at)` and partial lease expiry for processing. Claim eligible rows with row lock/SKIP LOCKED, regenerate token and increment attempt count. Recovery excludes deleted documents and reclaims expired jobs within retry budget. Final publication locks job and checks token plus lease; an expired worker cannot publish even if its provider call completed. Manual retry uses audit idempotency record and updates this same job atomically.
|
||||
|
||||
### 4.4 Retained extraction, review and factual inclusion
|
||||
|
||||
Existing code validates extraction envelopes and stores non-queryable candidates.
|
||||
Phase 5 implements durable current-claim complete_artifact attachment/reuse in
|
||||
forward revision 0002_worker_artifact, with documents.extraction_state jsonb
|
||||
NOT NULL DEFAULT '{}' and CHECK jsonb_typeof(extraction_state)='object'.
|
||||
Partial review candidates, decisions and factual inclusion below are implemented
|
||||
behind trusted backend services in forward revision 0003_extraction_review.
|
||||
Authenticated D06/D07 HTTP transport still requires identity/Origin/CSRF integration. This is derived-processing
|
||||
metadata, not a new document lifecycle or content version.
|
||||
|
||||
Keep large image/block/envelope bodies in the separate durable extraction
|
||||
namespace. extraction_state holds bounded trusted references and decisions:
|
||||
|
||||
| Logical field | Requirement |
|
||||
| --- | --- |
|
||||
| original_sha256, extraction_profile_sha256 | Source/frozen extraction identity |
|
||||
| complete_artifact | Nullable trusted storage key/digest for a complete validated envelope |
|
||||
| candidates | Bounded array of exact retained page/block or factual-corpus references, review kind, locator and evidence digest |
|
||||
| decisions | Evidence-bound approved/rejected status, required checks, note and authenticated reviewer identity |
|
||||
| factual_inclusion | Nullable approved extraction digest and whole excluded Q&A group IDs; never rewrites faithful text |
|
||||
|
||||
Persist candidate image/block hashes and storage keys privately; public API
|
||||
returns authenticated preview paths and faithful blocks, not raw storage keys.
|
||||
Server recomputes review_digest using original, frozen extraction identity,
|
||||
locator, exact image and exact blocks. Bind factual approval/inclusion to the
|
||||
complete extraction digest and existing group IDs. Bound JSON/reference count,
|
||||
preview bytes, notes and groups under the recorded processing/deployment limits.
|
||||
|
||||
Worker attachment/progress/completion writes lock document then job and verify
|
||||
current token, unexpired lease, original/profile and non-deletion. Write immutable
|
||||
file candidates before short transactions; orphan candidates are report-only
|
||||
until a separately approved cleanup policy. An unfenced late result cannot
|
||||
replace retained output or an approved decision.
|
||||
|
||||
Complete-artifact attachment compares the validated candidate pointer under those
|
||||
locks: the identical pointer replays without changing other extraction_state
|
||||
fields; a different pointer cannot replace it. Both paths still require the
|
||||
current claim and valid lease. No replay bypasses fencing.
|
||||
|
||||
When PDF/vision review is required, retain exact candidate output under the
|
||||
current claim, mark job/document failed with EXTRACTION_REVIEW_REQUIRED, clear
|
||||
claim ownership and publish zero chunks. Do not hold a lease for a human or add
|
||||
waiting_review. This outcome is not an automatically retried provider error.
|
||||
|
||||
Admin D07 locks document then job, validates the same failed candidate/source/
|
||||
profile, and commits decision plus unique extraction_review audit replay record
|
||||
atomically. Resolve an authorized replay before rechecking changing state.
|
||||
Concurrent changed decisions fail with REVIEW_ALREADY_DECIDED; stale candidate
|
||||
identity fails with REVIEW_STALE. Decisions do not mark ready or activate.
|
||||
D04 requeues the same eligible failed job after required approvals.
|
||||
|
||||
Reuse exact approved retained page/block candidates to resume QC. An incomplete
|
||||
candidate is never treated as an indexable complete envelope. A fresh vision
|
||||
response requires fresh review. After all coverage and approvals succeed,
|
||||
assemble/validate and attach the complete extraction artifact under a valid
|
||||
claim. Preserve it independently of vector staging; no OCR repeat solely
|
||||
because chunking/embedding changes.
|
||||
|
||||
For FAQ, record explicit factual authority and whole-group exclusions
|
||||
separately. Preserve all original Q&A associations in faithful extraction;
|
||||
only approved factual groups feed chunking. Governing context is resolved from the
|
||||
whole retained structure before selection and stays with each affected answer;
|
||||
context exclusive to excluded pairs is omitted. Review exposes the same context.
|
||||
Reviewer prose is stored as bounded inspection metadata separately from quality
|
||||
warnings and never interpreted as an extraction unreadability flag. Behavioral scenarios and live-data
|
||||
placeholders remain unsearchable factual content. No trustworthy remaining
|
||||
groups means visible failure. Client text/group labels cannot bypass validation.
|
||||
|
||||
Chunk text stays faithful evidence; its embedding input and lexical/identifier
|
||||
matching use recorded normalization. Do not reverse numbers, drop exceptions
|
||||
or change meaning. Reindexing ready documents is separately designed controlled
|
||||
maintenance, not failed-job retry. Purging applies to originals, extraction
|
||||
candidates/artifacts, decisions, chunks and retained tool excerpts under an
|
||||
explicit policy; immediate logical exclusion remains required.
|
||||
|
||||
## 5. Minimal voice conversation and evidence; deferred text tables
|
||||
|
||||
### 5.1 conversations
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, owner_user_id | uuid | Ownership |
|
||||
| client_request_id | uuid | Create idempotency key |
|
||||
| request_hash | char(64) | Normalized create payload |
|
||||
| mode | text | text or voice |
|
||||
| title | varchar(120) nullable | Optional display label |
|
||||
| status | text active | active, stale, closed |
|
||||
| access_epoch | bigint | Knowledge-removal snapshot |
|
||||
| created_at, updated_at | timestamptz | Ordering |
|
||||
|
||||
UNIQUE(owner_user_id,client_request_id). Scoped FK owner. Index owner/created_at/id. Effective status is stale if epoch differs even before explicit row updates. The MVP accepts mode=voice only, records owned identity/epoch and retains no message history. The proposed future mode=text branch is not enabled by merely adding the column. Add chain keys needed for live ownership; stale/closed conversations cannot start new media.
|
||||
|
||||
### 5.2 turns (deferred)
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, conversation_id | uuid | Text turn identity |
|
||||
| client_request_id | uuid | Chat retry correlation |
|
||||
| request_hash | char(64) | Conversation/message digest |
|
||||
| status | text running | running, answered, needs_clarification, insufficient_information, failed |
|
||||
| settings_revision, knowledge_revision, access_epoch | bigint | Actual snapshots |
|
||||
| execution_profile | jsonb | Model, actual organization instruction, prompt version, tool schema version and limits |
|
||||
| started_at, deadline_at | timestamptz | Execution timeout |
|
||||
| finished_at | timestamptz nullable | Terminal completion |
|
||||
| error_code, error_message | text nullable | Normalized failure |
|
||||
| error_retryable | boolean false | Technical retry hint |
|
||||
| created_at | timestamptz | Creation |
|
||||
|
||||
UNIQUE(conversation_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status='running'. CHECK terminal iff finished_at is not null; deadline_at > started_at. Scoped FK conversation. Mode=text is an application invariant checked while locking conversation. Message text resides in messages, not duplicated here. Reconstruct API response from messages/citations; replay does not call provider again. Startup/deadline cleanup marks interrupted turns failed.
|
||||
|
||||
### 5.3 messages (deferred)
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, conversation_id, turn_id | uuid | Ownership and text turn |
|
||||
| sequence_no | bigint | Stable conversation order, >=1 |
|
||||
| role | text | user or assistant |
|
||||
| content | text | Message body |
|
||||
| created_at | timestamptz | Creation |
|
||||
|
||||
UNIQUE(conversation_id,sequence_no), UNIQUE(turn_id,role). Both roles may exist for completed turn; failed turn can have user only. Add UNIQUE(organization_id,conversation_id,id) as needed for matching references. Enforce `(organization_id,conversation_id,turn_id)` FK to a corresponding unique key on turns, not independent FKs that could attach a message to the wrong conversation. Allocate sequence while holding conversation row lock; no model tool/system messages in this table.
|
||||
|
||||
### 5.4 tool_calls (voice-only MVP)
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, live_session_id | uuid | Owned voice parent; live_session_id NOT NULL |
|
||||
| external_call_id | text | Provider call correlation |
|
||||
| tool_name | text | search_knowledge only |
|
||||
| arguments | jsonb | Validated query/context without model scope |
|
||||
| request_hash | char(64) | Canonical argument digest |
|
||||
| status | text running | running, succeeded, failed |
|
||||
| knowledge_revision, access_epoch | bigint | Retrieval snapshots |
|
||||
| result_json | jsonb nullable | Evidence IDs/text/locations, no_evidence or normalized error |
|
||||
| error_code | text nullable | Technical/cancellation reason |
|
||||
| created_at | timestamptz | Creation |
|
||||
| completed_at | timestamptz nullable | Terminal completion |
|
||||
|
||||
UNIQUE(live_session_id,external_call_id); scoped FK to live_sessions.
|
||||
CHECK terminal iff completed_at is non-null; CHECK tool_name='search_knowledge'.
|
||||
No turn_id or FK to deferred turns/messages/citations is required in this
|
||||
migration. A later text extension must explicitly add its parent/constraint
|
||||
design; it is not implicit scope for this MVP.
|
||||
|
||||
Same call ID/hash waits or replays saved output after fresh eligibility/epoch
|
||||
checks. Different hash conflicts. Cancelled, expired, stale or closed-parent work
|
||||
is terminal failed with safe reason, and cannot release late evidence or resume
|
||||
audio. API restart fails interrupted running calls and their old media sessions.
|
||||
Provider work is outside transactions.
|
||||
|
||||
Source references are unique within a live turn; result_json retains actual
|
||||
document_id/chunk_id, title, faithful excerpt and nullable location. UI labels
|
||||
them retrieved evidence unless spoken attribution is verified. Redact revoked
|
||||
excerpts on poll/replay. Retained tool content is covered by purge policy;
|
||||
diagnostic logs must not contain document bodies/audio/secrets.
|
||||
|
||||
### 5.5 citations (deferred)
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, turn_id, tool_call_id | uuid | Answer/evidence correlation |
|
||||
| source_ref | text | S1, S2... unique across all searches within this turn |
|
||||
| document_id, chunk_id | uuid | Stable actual source IDs |
|
||||
| title_snapshot | text | Title at answer time |
|
||||
| location_snapshot | jsonb | Actual source locator |
|
||||
| excerpt | text nullable | Display evidence; cleared if policy requires purge |
|
||||
| created_at | timestamptz | Answer commit |
|
||||
|
||||
UNIQUE(turn_id,source_ref). Scoped FKs for sources plus chain-consistent composite FKs: chunk belongs to the cited document, tool call belongs to the same turn. Add referenced unique keys on these chains. Application verifies source_ref belongs to tool result, not arbitrary model output. No assistant_message_id needed: UNIQUE(turn_id,role) resolves the assistant. Only terminal non-failed answers can have final citations (transaction invariant).
|
||||
|
||||
Keep source identity rows as tombstones if allowed. `available` in API is computed from current access and retention state; revoked source excerpts are not emitted by source endpoints. Old answer prose cannot be retroactively withdrawn and remains owner-visible under history policy. Do not hard-delete referenced chunks through ordinary application DELETE.
|
||||
|
||||
## 6. Live and audit tables
|
||||
|
||||
### 6.1 live_sessions
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, conversation_id, owner_user_id, auth_session_id | uuid | Session ownership and logout correlation |
|
||||
| client_request_id | uuid | Creation correlation |
|
||||
| request_hash | char(64) | Normalized conversation/create-options digest; no SDP |
|
||||
| provider, model | text | Chosen live profile |
|
||||
| provider_session_id | text nullable | External reference |
|
||||
| status | text creating | creating, connecting, connected, closed, failed |
|
||||
| settings_revision, knowledge_revision, access_epoch | bigint | Creation snapshots |
|
||||
| execution_profile | jsonb | Instruction/prompt plus proposed audio/transcription capability snapshot |
|
||||
| expires_at, created_at, updated_at | timestamptz | TTL/lifecycle |
|
||||
| connected_at, closed_at | timestamptz nullable | Transition timestamps |
|
||||
| close_reason, error_code | text nullable | Normalized reason |
|
||||
|
||||
UNIQUE(owner_user_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status IN ('creating','connecting','connected'). Scoped and chain-consistent FKs ensure owner/auth session belong to same organization and user; live conversation is owned by that user. CHECK terminal implies closed_at set. No SDP replay field is required for the proposed Gemini WSS flow. Store no raw audio. Provider credentials are server configuration, never database plaintext. Application stream path derives from session ID; it is not a bearer provider credential.
|
||||
|
||||
API instance owns the direct Gemini Live WSS connection and audio relay in memory; DB stores mapping/state, not recoverable media. After API restart, mark nonterminal sessions failed and attempt cleanup. Reconnection uses a new session. Poll returns recent tool_calls, not a fabricated transcript. Available current-session provider transcripts are relayed to the UI with completion/interruption state; durable full voice message storage is deferred. Existing text messages/turns are not silently reused for voice.
|
||||
|
||||
### 6.2 audit_events
|
||||
|
||||
| Column | Type/default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| id, organization_id, actor_user_id | uuid (actor nullable) | Administrator/system action |
|
||||
| action | text | upload, selection_changed, document_deleted, ingestion_retry, extraction_review, configuration_changed, session_revoked |
|
||||
| target_id | uuid nullable | Referenced object; polymorphic diagnostic field |
|
||||
| request_id | text nullable | HTTP tracing |
|
||||
| idempotency_key | uuid nullable | Delete/retry idempotency |
|
||||
| request_hash | char(64) nullable | Mutation payload hash |
|
||||
| response_json | jsonb nullable | Replay of delete/retry outcome |
|
||||
| metadata | jsonb | Changed IDs/revisions, redacted reason |
|
||||
| created_at | timestamptz | Event time |
|
||||
|
||||
Partial UNIQUE(organization_id,actor_user_id,action,target_id,idempotency_key) WHERE idempotency_key IS NOT NULL. Delete/retry/review require non-null actor and target. A forward migration extends the action CHECK and replay-required CHECK to extraction_review; never edit the initial revision. Insert audit replay record in SAME transaction as the mutation. Concurrent unique conflict reloads committed response. Preserve these records for the supported retry window; no cleanup duration is assumed. Avoid document text/secrets in audit metadata.
|
||||
|
||||
## 7. Transaction boundaries and invariant enforcement
|
||||
|
||||
| Operation | One database transaction | Outside transaction |
|
||||
| --- | --- | --- |
|
||||
| Upload | Document + job + audit | File staging/write; reconcile orphans |
|
||||
| Claim | Row lock, new token/lease, attempt increment | Extraction and provider calls |
|
||||
| Publish | Lock document/job; verify token/lease; insert all chunks once; ready/succeeded | Already complete staged embeddings |
|
||||
| Selection | Settings lock, expected revision, active flags, revision/epoch, stale conversations, audit | Best-effort closing provider sessions after logical invalidation |
|
||||
| Review decision | Document/job lock, exact candidate/source/profile check, decision + audit replay | Reading exact retained preview; no provider call |
|
||||
| Review/artifact attachment | Document/job lock, current token/lease, trusted references/progress | Bounded candidate/artifact file writes |
|
||||
| Deferred chat admission | Settings/conversation locks, request lookup, turn + user message | Provider inference/tool loop |
|
||||
| Deferred chat completion | Settings/conversation locks, epoch validation, assistant + citations + terminal status | Browser delivery after commit |
|
||||
| Live create | Reservation/idempotency/ownership first; state update after provider | Provider creation and trusted control |
|
||||
| Delete/retry | State change + unique audit replay result | Physical cleanup or future worker execution |
|
||||
|
||||
Use consistent lock order where resources overlap: organization settings → conversation or document → job or turn/session. Do not hold settings lock during remote calls. Publication does not acquire settings after a document lock; it leaves selection unchanged. Retry/publish paths lock document then job to avoid inversion. Claims lock only jobs and commit quickly.
|
||||
|
||||
On active-document removal: database epoch invalidation is authoritative immediately for new operations. After transaction, notify/close provider sessions and discard stale pending evidence. Cannot recall previously delivered live audio. Session close failure remains observable and bounded by TTL; it is not represented as guaranteed erasure at the provider.
|
||||
|
||||
## 8. Migration plan
|
||||
|
||||
Treat migrations/versions/0001_ingestion_foundation.py as applied and immutable.
|
||||
The generic 001_identity/002_knowledge/003_conversations sequence from revision
|
||||
1.2 is not an instruction to recreate or combine the current foundation.
|
||||
|
||||
| Forward change | Content and gate |
|
||||
| --- | --- |
|
||||
| Retained extraction/review | documents.extraction_state; extraction_review audit/check support; test fencing, stale decisions and idempotency |
|
||||
| Identity and voice | auth_sessions, owned voice conversations, live_sessions, voice-only tool_calls; scoped/owner-chain FKs and replay/partial uniqueness |
|
||||
| Later text milestone | turns/messages/citations plus explicit text-tool parent extension; not needed for voice shipment |
|
||||
|
||||
Choose actual revision IDs after inspecting Alembic head. Create tables in FK
|
||||
dependency order and update compatibility/schema checks for new revisions
|
||||
without weakening original frozen embedding checks. Inspect bootstrap/consumers
|
||||
of changed contracts. Validate upgrades against isolated real PostgreSQL.
|
||||
|
||||
The seven foundation tables already hold organizations/users/settings,
|
||||
documents/jobs/chunks and audit. Preserve IDs, profile snapshots, vectors and
|
||||
original files. No model/dimension/preprocessing change or content rewrite is
|
||||
authorized by framework integration. No applied migration was changed or new
|
||||
migration executed by this documentation update.
|
||||
|
||||
## 9. Essential database validation
|
||||
|
||||
Require real PostgreSQL evidence for current MVP changes: cross-organization/
|
||||
owner-chain FK rejection; upload/review/retry/live-create replay and changed
|
||||
payload conflicts; concurrent live reservation; claim/lease fencing; exact
|
||||
retained-output decisions and attachment races; retry of the same document/job;
|
||||
complete publication rollback/ambiguous commit/crash; inactive/deleted exclusion;
|
||||
epoch race before tool-result delivery; cancellation/restart terminal states.
|
||||
Tool sources must resolve to the actual document/chunk chain.
|
||||
|
||||
Ordinary-suite skips do not establish database acceptance. Use the documented
|
||||
isolated TEST_DATABASE_URL with --require-postgres. Existing recorded foundation/
|
||||
Phase 3/4 historical results and current Phase 5/6 worker/database acceptance
|
||||
are separate from pending authenticated transport/browser/Live acceptance and
|
||||
real-provider/Persian quality.
|
||||
Text finalization/history/citation tests belong to the later text milestone.
|
||||
|
||||
## 10. Deliberately absent from Phase 1
|
||||
|
||||
No per-organization vector database, message broker tables, raw audio blobs, arbitrary tool schema registry, retention scheduler, multi-version assignment workflow or model catalogue. Full document bodies are in file storage/chunks; original files and recordings are not PostgreSQL byte arrays. Keep no production capacity or retention claim until stakeholders supply those requirements.
|
||||
@@ -0,0 +1,279 @@
|
||||
# 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
|
||||
|
||||
1. 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.
|
||||
2. 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.
|
||||
3. Save the immutable original and create document/job/audit in a short transaction.
|
||||
Hash/reconcile files outside long transactions. New document is inactive.
|
||||
4. Claim eligible work with token/lease, attempts and documented lock order.
|
||||
Provider work runs outside long transactions. Heartbeat throughout slow calls.
|
||||
5. 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.
|
||||
6. 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.
|
||||
7. 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](RAG-Phase1-API-Catalog.md). 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.
|
||||
@@ -0,0 +1,162 @@
|
||||
# Live Document MVP - English Scenarios
|
||||
|
||||
Version 1.3 | 2026-10-07 | Current scenario reference; examples are acceptance
|
||||
requirements, not observed runtime results.
|
||||
|
||||
Companions: [delivery plan](RAG-AI-Phase1-Delivery-Plan.md),
|
||||
[implementation guide](RAG-Phase1-Implementation-Guide.md),
|
||||
[API catalog](RAG-Phase1-API-Catalog.md) and
|
||||
[database design](RAG-Phase1-Database-Design.md).
|
||||
|
||||
## 1. Product and user journey
|
||||
|
||||
Known users in one organization sign in. An admin uploads new supported files
|
||||
from the browser, inspects uncertain extraction, activates ready documents and
|
||||
starts a Persian voice conversation. Users hear supported document answers and
|
||||
see retrieved sources plus available provider transcripts.
|
||||
|
||||
LangChain supplies the RAG/tool integration boundary. Gemini Live manages
|
||||
native audio; the backend owns secrets, identity, tools and scope. Existing
|
||||
ingestion/embedding Phases 1-4 remain the processing foundation.
|
||||
|
||||
## 2. Four mandatory examples and unseen documents
|
||||
|
||||
| Example file | Required quality checks |
|
||||
| --- | --- |
|
||||
| 7364346504113364738_13450847753183.pdf | PDF reading order, word/digit order, real page locators and direct/page-fallback coverage |
|
||||
| 5905170444656189186_13450510740952.pdf | Circular dates, percentages, conditions, negation and exceptions |
|
||||
| photo_1_2026-10-06_09-05-11.jpg | Separate infographic groups and correct parent heading/description associations |
|
||||
| -2348240626507047168_13449360743721.docx | Preserve all 100 Q&A associations; distinguish factual answers, behavioral scenarios and live-data placeholders |
|
||||
|
||||
These examples reveal required structures; they are not an upload filename/hash
|
||||
allowlist or a four-document capacity limit. Upload additional previously unseen
|
||||
files of the supported structures through the same UI without code changes.
|
||||
Record declared limitations and understandable failures for unsupported/
|
||||
unreadable/oversized content. Future total upload count is unknown; resource
|
||||
bounds/backlog/capacity are explicit deployment decisions.
|
||||
|
||||
## 3. New browser upload and duplicate submission
|
||||
|
||||
The admin selects a new file/title. D01 validates actual type and configured
|
||||
limits, stores immutable bytes and creates one inactive document/job.
|
||||
A replay of the same idempotency key and bytes/title returns the same IDs.
|
||||
A changed payload under that key conflicts. The same bytes with a new key
|
||||
create a new independent document; no original overwrite or content version.
|
||||
|
||||
Show real queued/processing/ready/failed state; do not invent percentage progress.
|
||||
A successful upload acknowledgement does not mean the file is searchable.
|
||||
|
||||
## 4. PDF/image review and same-output resume
|
||||
|
||||
Worker extraction identifies required page review and retains the exact bounded
|
||||
image/block candidate under its current claim. It fails with a review-required
|
||||
reason, zero published chunks and released lease.
|
||||
|
||||
The admin opens D06 and compares retained text with the original/rendered page.
|
||||
D07 approves/rejects the digest with the required readability/order/completeness/
|
||||
number/date/negation/exception checks and a note. D04 resumes the same eligible
|
||||
document/job after approval. Retained inspected output is reused, rather than a
|
||||
new OCR response silently inheriting approval. Further pages may need review.
|
||||
|
||||
A stale digest, other-organization candidate, client-supplied replacement text
|
||||
or conflicting decision cannot alter evidence. Rejection keeps it unsearchable.
|
||||
Partial candidates cannot be passed off as a complete validated artifact.
|
||||
All pages/quality checks must finish before complete publication.
|
||||
|
||||
## 5. Word FAQ authority and inclusion
|
||||
|
||||
Extraction retains all original question/answer associations and locators.
|
||||
This preserves source content, not proof that every entry is valid knowledge.
|
||||
|
||||
An explicit factual-corpus decision identifies approved factual FAQ groups
|
||||
and excludes whole pairs that contain unapproved facts, behavioral scenarios
|
||||
or current-value placeholders. Store that manifest separately from faithful
|
||||
extraction; do not edit the original. Preserve valid question/answer grouping
|
||||
through chunking. Empty eligible factual content fails clearly.
|
||||
|
||||
An entry that says a price or tariff is current without an approved value does
|
||||
not authorize invented pricing. A behavioral example does not become a system
|
||||
instruction through retrieval. No live business-data/telephony tool is promised.
|
||||
|
||||
## 6. Complete publication and active selection
|
||||
|
||||
Worker stages every vector using the frozen compatible profile and current
|
||||
limits. A failed final batch leaves zero published chunks. Publish chunks,
|
||||
ready state and succeeded job together under a valid token/unexpired lease.
|
||||
A ready document stays inactive until the admin selects it.
|
||||
|
||||
A stale worker after lease expiry, interrupted claim, repeated publication
|
||||
or uncertain commit cannot create a partial/duplicate searchable document.
|
||||
Activation uses current knowledge_revision; stale selection conflicts.
|
||||
|
||||
## 7. Grounded spoken circular question
|
||||
|
||||
Create an owned voice conversation/session. Ask in Persian the equivalent of:
|
||||
"What conditions and exceptions does this circular contain?"
|
||||
|
||||
The model calls search_knowledge with query and optional resolved context.
|
||||
The backend resolves scope, embeds with the same compatible profile and returns
|
||||
real evidence/document/chunk IDs and locators. The native Live model speaks a
|
||||
concise answer with actual supported numbers/conditions; UI shows retrieved
|
||||
sources and provider transcription when available. No numerical source content
|
||||
is invented in this scenario description.
|
||||
|
||||
## 8. Follow-up, topic switch and ambiguity
|
||||
|
||||
Ask "What were its exceptions?" after a clearly identified circular.
|
||||
Resolve the reference, retrieve fresh evidence and answer from it.
|
||||
|
||||
Then ask about a group in the infographic. Replace the old topic anchor and
|
||||
retrieve that group's verified description. Do not carry unrelated circular
|
||||
article/date assumptions into the new topic.
|
||||
|
||||
Ask "What about the next article?" without an unambiguous article/document.
|
||||
Request clarification rather than choose an arbitrary similarity match.
|
||||
|
||||
## 9. Interruption and failure
|
||||
|
||||
Interrupt with the Persian equivalent of "Wait, only tell me the exceptions."
|
||||
Stop/clear queued playback, mark partial output interrupted and suppress cancelled
|
||||
tool results. A late result cannot restart the prior answer.
|
||||
|
||||
For no supporting evidence, state the limitation. For conflicting evidence,
|
||||
disclose conflict or ask clarification. For query embedding/search/provider
|
||||
timeout, show a technical failure; do not report that no document exists.
|
||||
If Live is disconnected, the UI shows the failure without inventing a spoken
|
||||
response from the unavailable provider. Reconcile/close and start a fresh
|
||||
session; seamless context restoration is deferred.
|
||||
|
||||
## 10. Knowledge removal, logout and ownership
|
||||
|
||||
Deactivate a document used in a session. Increment knowledge revision/access
|
||||
epoch and make older context unusable; conservatively close active organization
|
||||
sessions. A fresh session searches current active evidence. Old excerpts must
|
||||
not reappear through poll, cached tool replay or late result delivery.
|
||||
|
||||
Logout/expiry closes linked sessions. A normal user cannot upload/review/select;
|
||||
another user's conversation/session cannot be read, streamed or closed by
|
||||
guessing its UUID. Admin status does not grant conversation ownership.
|
||||
|
||||
## 11. Persistence, unknown backlog and restart
|
||||
|
||||
New uploads wait durably while the single worker is busy. UI lists are paginated.
|
||||
Admission/resource failures are explicit, and limits are published. This scenario
|
||||
does not certify unlimited corpus size or concurrent voice capacity.
|
||||
|
||||
Restart preserves originals/jobs/ready documents and recorded decisions.
|
||||
Interrupted jobs recover under fresh claims without duplicate publication.
|
||||
Old API-owned media sessions/running tools become terminal and unusable;
|
||||
users start fresh. Current-session transcript may be lost on page refresh;
|
||||
durable full voice history and raw recording are deferred.
|
||||
|
||||
## 12. Evaluation and handoff
|
||||
|
||||
Map checks to MVP-01 through MVP-14. Independently annotate expected source
|
||||
passages; do not use an indexed FAQ as the sole proof of its own retrieval.
|
||||
Evaluate retrieval, answer support and spoken quality separately with roughly
|
||||
15-20 initial questions and unseen-file questions.
|
||||
|
||||
Rehearse browser upload -> review if needed -> ready -> activate -> real Persian
|
||||
voice -> shared retrieval -> spoken answer/sources on target HTTPS/network.
|
||||
Record actual errors/latency/provider usage and limits, not invented accuracy
|
||||
percentages or unexecuted acceptance claims.
|
||||
@@ -0,0 +1,315 @@
|
||||
> Historical Persian report (revision 1.2). For the current English Live document MVP baseline and scenarios, use [Live Document MVP Scenarios](RAG-Phase1-MVP-Scenarios.md) and delivery/API/database revision 1.3. Older text/history/settings delivery requirements below do not govern this milestone. The historical body is preserved unchanged.
|
||||
|
||||
# گزارش فاز یک دستیار اسناد سازمان — پیادهسازی، API و دیتابیس با سناریو
|
||||
|
||||
نسخه ۱.۲ — تاریخ ۲۰۲۶/۱۰/۰۶
|
||||
|
||||
این گزارش طراحی پیشنهادی پیادهسازی است؛ به معنی ساختهشدن برنامه، اجرای مایگریشن یا موفقیت تستها نیست. بازه تحویل همان ۷ تا ۱۰ روز و فرض ظرفیت، یک توسعهدهنده اصلی است.
|
||||
|
||||
## ۱. این مجموعه سند دقیقاً چه چیزی تحویل میدهد؟
|
||||
|
||||
| سند | کاربرد |
|
||||
| --- | --- |
|
||||
| `RAG-Phase1-Implementation-Guide.md` | توسعهدهنده بداند چه ماژولهایی بسازد، ترتیب کار چیست و هر جریان چگونه اجرا شود |
|
||||
| `RAG-Phase1-API-Catalog.md` | فرانت و بکاند روی آدرسها، ورودی، خروجی، دسترسی، وضعیت و خطا توافق کنند |
|
||||
| `RAG-Phase1-Database-Design.md` | جداول، ستونها، ارتباطها، محدودیتها و ترتیب مایگریشن مشخص باشند |
|
||||
| همین گزارش | جریان محصول و ارتباط API، منطق و دیتابیس با مثال قابل فهم باشد |
|
||||
|
||||
مبنای محدوده، `RAG-AI-Phase1-Delivery-Plan.md` است. سند معماری اصلی مسیر محصول کامل را نگه میدارد؛ امکاناتی که آنجا آمدهاند الزاماً در فاز یک پیاده نمیشوند.
|
||||
|
||||
سه سند فنی انگلیسیاند تا برای داکیومنت پروژه و توسعه قابل استفاده باشند. این گزارش فارسی است. قراردادهای تازه مثل روش احراز هویت و جزئیات جدولها، پیشنهاد فنی مشخص برای شروعاند و تأیید قبلی کارفرما فرض نشده است.
|
||||
|
||||
## ۲. محصولی که در پایان فاز یک نشان میدهیم
|
||||
|
||||
مدیر وارد سامانه میشود، سند سازمان را آپلود میکند، آمادهشدن آن را میبیند و فعالش میکند. کاربر از طریق متن یا صوت سؤال میپرسد. مدل تصمیم میگیرد ابزار سرچ را اجرا کند؛ بکاند شواهد را از اسناد فعال پیدا میکند و مدل بر اساس آن پاسخ میدهد.
|
||||
|
||||
چهار صفحه داریم: ورود، گفتگو، اسناد و تنظیمات. در تنظیمات فقط نام و دستورالعمل دستیار تغییر میکند. انتخاب اسناد در صفحه اسناد است. مدلها از تنظیمات سرور تعیین میشوند. مدیریت مدل، نسخهبندی خودکار سند، SSO، ثبتنام و تاریخچه ماندگار کامل صوتی خارج از این تحویلاند. استخراج تصویر، fallback صفحه PDF و جدولهای DOCX نمونه در محدوده MVP هستند؛ OCR عمومی همه فرمتها الزام نیست.
|
||||
|
||||
تصمیم سادهسازی: جدول نسخهها حذف شده است. هر آپلود یک سند مستقل میسازد؛ قطعات و کار پردازش مستقیم به آن متصلاند. برای اصلاح محتوا، فایل جدید آپلود و پس از آمادهشدن جای سند فعال قبلی انتخاب میشود. Retry همان سند را دوباره پردازش میکند و سند تازه نمیسازد. تعداد جدولها اکنون ۱۴ است.
|
||||
|
||||
## ۳. تقسیم کار سیستم با زبان ساده
|
||||
|
||||
| جزء | کار واقعی |
|
||||
| --- | --- |
|
||||
| مرورگر | فرمها، نمایش چت و منابع، میکروفون و پخش صوت |
|
||||
| API | دریافت درخواست، بررسی هویت و دسترسی و برگرداندن نتیجه |
|
||||
| سرویس گفتگو | اجرای نوبت متنی، نگهداری سابقه و مدیریت درخواست تکراری |
|
||||
| مدل | تشخیص نیاز به سرچ و تولید پاسخ با شواهد |
|
||||
| ابزار سرچ | اجرای جستوجو در اسناد آماده و فعال؛ مدل SQL اجرا نمیکند |
|
||||
| Worker | استخراج متن و ساخت قطعات و Embedding در پسزمینه |
|
||||
| PostgreSQL + pgvector | کاربران، اسناد، کارها، بردارها، گفتگوها و وضعیتها |
|
||||
| مخزن فایل | نگهداری فایل اصلی آپلودشده |
|
||||
| کنترلکننده Live | ساخت و بستن جلسه صوتی و اجرای ابزارها در بکاند |
|
||||
|
||||
همه ماژولهای بکاند در یک کدبیساند. Worker یک فرایند جدا از API است تا پردازش فایل، پاسخگویی UI را معطل نکند. صف کارها همان جدول دیتابیس است و در این فاز Redis یا RabbitMQ لازم نشده است.
|
||||
|
||||
## ۴. سناریو اول: مدیر سند ساعات کاری را آپلود میکند
|
||||
|
||||
فرض کنیم فرمت فایل نمونه در روز اول تأیید شده و متن آن قابل استخراج است. سند میگوید: «پنجشنبهها از ساعت ۸ تا ۱۲».
|
||||
|
||||
| قدم | درخواست یا رفتار | اتفاق در دیتابیس | نتیجه UI |
|
||||
| --- | --- | --- | --- |
|
||||
| ۱ | `POST /api/v1/auth/login` | نشست احراز هویت در `auth_sessions` | ورود موفق |
|
||||
| ۲ | `POST /api/v1/documents` با فایل | یک سند مستقل در `documents` و کار متصل به همان سند در `ingestion_jobs` ساخته میشود | «در صف پردازش» |
|
||||
| ۳ | Worker کار را میگیرد | وضعیت job و سند processing میشود | «در حال پردازش» |
|
||||
| ۴ | استخراج، قطعهبندی و Embedding | هنوز قطعات ناقص وارد سرچ نمیشوند | کاربر منتظر وضعیت آماده میماند |
|
||||
| ۵ | انتشار موفق | قطعات در `document_chunks`؛ سند ready؛ job succeeded | «آماده، غیرفعال» |
|
||||
| ۶ | مدیر فعال میکند | مجموعه انتخابشده با `PATCH /knowledge-selection` تغییر میکند | «فعال برای پاسخگویی» |
|
||||
|
||||
آپلود پاسخ ۲۰۲ میدهد؛ یعنی فایل و کار پردازش ثبت شدهاند، نه اینکه مدل همان لحظه آن را میشناسد. فرانت با `GET /documents/{id}` وضعیت را میخواند.
|
||||
|
||||
سند آماده ولی غیرفعال قابل سرچ نیست. این دو وضعیت مستقلاند: یکی میگوید پردازش انجام شده، دیگری میگوید سازمان اجازه استفاده داده است.
|
||||
|
||||
در MVP جدید تصویر و صفحه اسکنشده نمونه با vision/OCR پردازش میشوند. اگر خروجی ناخوانا، ناقص یا از نظر عدد/استثنا غیرقابل اعتماد باشد، failed با دلیل روشن نمایش داده میشود؛ متن خالی یا غیرقابل اعتماد ready نمیشود.
|
||||
|
||||
## ۵. سناریو دوم: کاربر متنی سؤال میپرسد
|
||||
|
||||
کاربر مینویسد: «پنجشنبه تا چه ساعتی باز هستید؟»
|
||||
|
||||
۱. فرانت با `POST /conversations` یک گفتگوی text میسازد.
|
||||
۲. سؤال را همراه `conversation_id` و `client_request_id` به `POST /chat` میدهد.
|
||||
۳. بکاند یک `turn` به معنی «یک نوبت سؤال و پاسخ» ثبت میکند. سؤال کاربر در `messages` ذخیره میشود.
|
||||
۴. مدل میبیند برای پاسخ به اطلاعات سازمان نیاز دارد و ابزار `search_knowledge` را با کوئری «ساعت کاری پنجشنبه» صدا میزند.
|
||||
۵. ابزار هویت سازمان را از نشست معتبر میگیرد؛ خود مدل نمیتواند سازمان یا اسناد مجاز را عوض کند.
|
||||
۶. سؤال به بردار تبدیل میشود و قطعات مرتبط از اسناد آماده و فعال پیدا میشوند.
|
||||
۷. متن قطعه، شناسه سند و قطعه و محل منبع به مدل برمیگردد.
|
||||
۸. مدل پاسخ میدهد: «طبق سند ساعات کاری، پنجشنبهها تا ساعت ۱۲ باز هستیم.»
|
||||
۹. پاسخ در `messages` و ارجاع آن در `citations` ذخیره میشود؛ turn به answered میرسد.
|
||||
۱۰. UI پاسخ و منبع را نمایش میدهد.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as User
|
||||
participant B as Backend
|
||||
participant M as AI Model
|
||||
participant S as Search Tool
|
||||
participant D as Database
|
||||
U->>B: Text question
|
||||
B->>D: Save running turn
|
||||
B->>M: Question and tool schema
|
||||
M->>B: Search tool call
|
||||
B->>S: Execute authorized search
|
||||
S->>D: Retrieve selected ready chunks
|
||||
D-->>S: Evidence
|
||||
S-->>B: Content and sources
|
||||
B->>M: Tool result
|
||||
M-->>B: Grounded answer
|
||||
B->>D: Save answer and citations
|
||||
B-->>U: Answer and sources
|
||||
```
|
||||
|
||||
ایجنتیک بودن همین است: برای «سلام» لازم نیست سرچ انجام شود، اما برای ادعای مربوط به سند سازمان شواهد لازم است. ابزار جواب نهایی را تولید نمیکند؛ اطلاعات لازم را میآورد.
|
||||
|
||||
## ۶. سناریو سوم: اطلاعات پیدا نمیشود یا سؤال مبهم است
|
||||
|
||||
| سؤال/وضعیت | رفتار درست | وضعیت نوبت |
|
||||
| --- | --- | --- |
|
||||
| «پنجشنبه تا چند باز هستید؟» و سند مربوط موجود است | پاسخ مستند | answered |
|
||||
| «اون روز تا چند باز هستید؟» بدون زمینه کافی | «منظورتان کدام روز است؟» | needs_clarification |
|
||||
| «مبلغ پاداش امسال چقدره؟» و سندی درباره آن نیست | اعلام نبود اطلاعات در اسناد | insufficient_information |
|
||||
| سرویس Embedding قطع است | اعلام مشکل سرویس؛ نه ادعای نبود اطلاعات | failed |
|
||||
|
||||
تفاوت دو ردیف آخر مهم است: «جستوجو انجام شد و مدرک نبود» با «جستوجو نتوانست اجرا شود» یکی نیست. API و دیتابیس این تفاوت را حفظ میکنند تا UI پیام اشتباه نشان ندهد.
|
||||
|
||||
## ۷. سناریو چهارم: کاربر دوبار ارسال میزند یا پاسخ HTTP گم میشود
|
||||
|
||||
فرض کنیم سؤال ثبت شده و مدل در حال پاسخ است، ولی اینترنت مرورگر برای لحظهای قطع میشود.
|
||||
|
||||
فرانت نباید فوراً یک سؤال جدید با شناسه جدید بسازد. همان `client_request_id` را نگه میدارد و از این مسیر وضعیت را میپرسد:
|
||||
|
||||
`GET /api/v1/conversations/{conversation_id}/turns/{client_request_id}`
|
||||
|
||||
- اگر running باشد، منتظر میماند.
|
||||
- اگر answered باشد، همان جواب ثبتشده را نمایش میدهد.
|
||||
- اگر failed باشد، خطا را نشان میدهد؛ تلاش جدید آگاهانه با شناسه جدید انجام میشود.
|
||||
- اگر هنوز رکورد ثبت نشده باشد، همان درخواست و همان شناسه را دوباره میفرستد.
|
||||
|
||||
در دیتابیس ترکیب گفتگوی مشخص و شناسه درخواست یکتا است. بنابراین دو بار ارسال یک درخواست، دو نوبت مستقل نمیسازد. این همان کاربرد عملی Idempotency است.
|
||||
|
||||
اگر سؤال با همان شناسه عوض شود، ۴۰۹ میگیریم؛ این خطای برنامه فرانت است. اگر در یک گفتگو یک نوبت در حال اجرا باشد و سؤال جدید با شناسه دیگر برسد، `CONVERSATION_BUSY` برمیگردد. در فاز یک نوبتهای یک گفتگو همزمان اجرا نمیشوند.
|
||||
|
||||
## ۸. سناریو پنجم: کاربر صوتی سؤال میپرسد
|
||||
|
||||
۱. کاربر دسترسی میکروفون میدهد و گفتگوی voice متعلق به خودش ایجاد میکند.
|
||||
۲. `POST /api/v1/voice/sessions` شناسه جلسه و مسیر WSS برنامه را میدهد؛ قرارداد SDP قبلی برای MVP جدید کنار گذاشته شده است.
|
||||
۳. بکاند با کلید سروری به Gemini Live مستقیم وصل میشود و دستور فارسی، ابزار `search_knowledge` و transcription قابل پشتیبانی را تنظیم میکند.
|
||||
۴. صوت کاربر از مرورگر به بکاند و سپس جلسه Gemini میرود.
|
||||
۵. برای سؤال وابسته به سند، مدل ابزار را فراخوانی میکند؛ بکاند با هویت و محدوده خودش همان سرچ مشترک متن را اجرا میکند.
|
||||
۶. قطعات واقعی و محل منبع به مدل میرسند؛ مدل میتواند بدون فراخوانی جداگانه مدل متنی پاسخ فارسی صوتی بسازد.
|
||||
۷. UI صوت، متن پاسخ موجود و منابع را نشان میدهد. منبع بازیابیشده لزوماً استناد دقیق جمله صوتی نیست.
|
||||
۸. وقفه کاربر پخش صفشده را متوقف میکند؛ نتیجه دیررس ابزار نوبت لغوشده پاسخ تازه نمیسازد.
|
||||
|
||||
**بکاند جلسه و انتقال صوت را مدیریت میکند و کلید دائمی در مرورگر نیست.** نام رویدادها و مسیر WSS در کاتالوگ، پیشنهاد فنیاند و هنوز پیادهسازی نشدهاند. OpenRouter برای مقایسه متن/vision است؛ دریافت فایل صوتی یا خروجی صوتی stream به معنی پشتیبانی جلسه دوطرفه Gemini Live نیست.
|
||||
|
||||
در قطعی، UI وضعیت را نشان میدهد؛ جلسه قدیمی تعیین تکلیف و جلسه جدید ساخته میشود. بازیابی بیوقفه زمینه و تاریخچه ماندگار کامل صوتی خارج از فاز یکاند. متن موجود در همان جلسه نگه داشته میشود؛ متن ناموجود یا ناقص صریحاً مشخص است و به جای گفتار واقعی جعل نمیشود. تلفظ و فهم فارسی، اسمهای محلی، تاریخ، درصد و مبلغ باید با صوت واقعی بررسی شود.
|
||||
|
||||
## ۹. سناریو ششم: سازمان سند ساعات کاری را عوض میکند
|
||||
|
||||
سند قدیمی ساعت پایان را ۱۲ نوشته؛ سند جدید ساعت ۱۳ را اعلام میکند.
|
||||
|
||||
۱. مدیر سند جدید را جداگانه آپلود میکند و منتظر آمادهشدن میماند.
|
||||
۲. سند قدیمی را از انتخاب خارج و جدید را فعال میکند. API میتواند مجموعه نهایی انتخابها را در یک تغییر ثبت کند؛ هر دو فایل سند مستقلاند و هیچ شماره نسخه یا جدول نسخهای نداریم.
|
||||
۳. شمارنده تغییر منابع افزایش پیدا میکند.
|
||||
۴. چون سندی حذف شده، شمارنده اعتبار زمینه گفتگو هم تغییر میکند.
|
||||
۵. گفتگوهای قبلی سازمان برای سؤال جدید stale میشوند؛ UI دکمه «گفتگوی جدید» نشان میدهد.
|
||||
۶. جلسههای صوتی قبلی بسته میشوند تا زمینه قدیمی دوباره استفاده نشود.
|
||||
۷. گفتگوی جدید سؤال را از سند جدید جواب میدهد: ساعت ۱۳.
|
||||
|
||||
برای سرعت و سادگی فاز یک، هنگام حذف یک منبع فعال همه گفتگوهای قدیمی سازمان برای ادامه نامعتبر میشوند؛ نه فقط گفتگوهایی که قطعاً از همان سند استفاده کردهاند. این رفتار محافظهکارانه است و در فاز بعد میتوان دقیقترش کرد.
|
||||
|
||||
پاسخ قبلی که «۱۲» گفته، در تاریخچه همان پاسخ قبلی باقی میماند؛ با تغییر سند بازنویسی نمیشود. صوتی که قبلاً پخش شده هم قابل پسگرفتن نیست. کنترل ما روی استفاده بعدی از اطلاعات است.
|
||||
|
||||
## ۱۰. سه عدد revision چه فرقی دارند؟
|
||||
|
||||
| فیلد | چه وقت تغییر میکند؟ | کاربرد |
|
||||
| --- | --- | --- |
|
||||
| revision | تغییر نام یا دستورالعمل دستیار | جلوگیری از ذخیره همزمان روی تنظیمات قدیمی |
|
||||
| knowledge_revision | تغییر مجموعه اسناد فعال | مشخصکردن مجموعه دانش هر نوبت |
|
||||
| access_epoch | خارجکردن سند فعال یا حذف آن | نامعتبرکردن زمینههای قدیمی گفتگو |
|
||||
|
||||
مثال: فقط سندی اضافه کنیم، knowledge_revision تغییر میکند و سؤال بعدی آن را میبیند. سند فعالی را برداریم، access_epoch هم تغییر میکند تا اطلاعات قدیمی از حافظه گفتگو دوباره وارد پاسخ نشوند.
|
||||
|
||||
اگر دو مدیر همزمان تنظیمات را باز کنند، درخواست دوم که revision قدیمی دارد ۴۰۹ میگیرد. UI تنظیمات تازه را میخواند تا تغییر مدیر اول ناخواسته از بین نرود.
|
||||
|
||||
## ۱۱. سناریو هفتم: Worker وسط کار قطع میشود
|
||||
|
||||
Worker فایل را گرفته و مشغول Embedding است. فرایند قطع میشود.
|
||||
|
||||
کار در دیتابیس مانده است. Worker برای مدت محدود اجازه پردازش داشته که Lease نام دارد. بعد از تمامشدن این مدت، کار قابل گرفتن دوباره است. دریافتکننده جدید یک claim token تازه میگیرد.
|
||||
|
||||
اگر Worker قبلی دیر برگردد، توکنش دیگر معتبر نیست و حق انتشار ندارد. Worker جدید میتواند پردازش را از ابتدا انجام دهد. در این فاز ادامهدادن دقیق از هر قطعه را پیاده نمیکنیم؛ انتشار نهایی یکپارچه است و محدودیت یکتایی، ساخت قطعات تکراری را میگیرد.
|
||||
|
||||
برای خطای موقت، تلاش مجدد با فاصله انجام میشود. برای فایل خراب، ادامه دادن بیفایده است و failed نمایش داده میشود. مدیر فقط برای خطای قابل تلاش مجدد میتواند Retry بزند. خود Retry هم کلید یکتا دارد تا دوبار کلیک، دو بار بودجه تلاش را بازنشانی نکند.
|
||||
|
||||
## ۱۲. چرا این جدولها لازماند؟
|
||||
|
||||
| گروه | جدولها | مثال ساده |
|
||||
| --- | --- | --- |
|
||||
| هویت | organizations، users، auth_sessions | چه کسی وارد شده و چه اجازهای دارد؟ |
|
||||
| تنظیمات | organization_settings | اسم دستیار و نسخه تنظیمات و منابع چیست؟ |
|
||||
| اسناد | documents | این فایل چیست، کجا ذخیره شده و آماده پاسخگویی است؟ |
|
||||
| پردازش | ingestion_jobs | چه فایلی منتظر است و چرا پردازشش شکست خورده؟ |
|
||||
| دانش | document_chunks | کدام تکه متن و بردار باید جستوجو شود؟ |
|
||||
| گفتگو | conversations، turns، messages | کدام مکالمه، کدام نوبت، چه سؤال و پاسخی؟ |
|
||||
| شواهد | tool_calls، citations | چه سرچهایی انجام شد و جواب به چه منبعی استناد کرد؟ |
|
||||
| صوت | live_sessions | کدام جلسه وصل است و چرا بسته شده؟ |
|
||||
| تغییرات مدیریتی | audit_events | چه کسی سند را غیرفعال یا Retry کرده؟ |
|
||||
|
||||
تعداد جدولها به معنی تعداد سرویس یا برنامه جدا نیست. برای مثال سه جدول گفتگو لازماند چون «گفتگو»، «اجرای یک سؤال» و «متن پیام» وضعیت و مسئولیت متفاوت دارند. نگهداری صرف متن پیام برای تشخیص timeout و درخواست تکراری کافی نیست.
|
||||
|
||||
فایل اصلی در مخزن فایل است؛ مسیر تولیدشده آن در خود سند ذخیره میشود. بردارها در pgvector داخل همان PostgreSQL هستند. فایل صوتی خام ذخیره نمیکنیم.
|
||||
|
||||
## ۱۳. سناریو هشتم: حذف سند
|
||||
|
||||
مدیر حذف را تأیید میکند. ابتدا سند از سرچ خارج و deleted ثبت میشود. اگر فعال بوده، زمینه گفتگوها هم نامعتبر میشود. پاسخ API صریحاً میگوید پاکسازی فیزیکی منتظر سیاست نگهداری است؛ «حذف از پاسخگویی» را با «پاکشدن فوری تمام فایلها و تاریخچه» یکی نمیکنیم.
|
||||
|
||||
دلیل نگهداشتن شناسه منبع این است که جواب قدیمی همچنان قابل ردیابی باشد. اینکه متن قطعات، فایل اصلی یا excerptها چه زمانی واقعاً پاک شوند، باید از سازمان مشخص شود. در این اسناد عدد دلخواه برای مدت نگهداری ننوشتهایم.
|
||||
|
||||
منبع غیرفعال/حذفشده در نمایش منابع جدید متن قابل دسترس ارائه نمیکند. تاریخچه پاسخهای قبلی متعلق به کاربر، طبق دسترسی تاریخچه باقی میماند؛ وارد زمینه گفتگوی جدید نمیشود.
|
||||
|
||||
## ۱۴. برنامه عملی توسعه و معیار پیشرفت
|
||||
|
||||
| بازه | چیزی که باید بتوانیم نشان دهیم |
|
||||
| --- | --- |
|
||||
| روز ۱ | بررسی نمونهها، کیفیت استخراج، اعتبار حساب و شبکه و پروفایلهای مدل |
|
||||
| روز ۲ | ورود و آپلود ماندگار |
|
||||
| روز ۳ | استخراج/QC و ایندکس متن، تصویر و جدول نمونه؛ خطای روشن برای خروجی غیرقابل اعتماد |
|
||||
| روز ۴ | سرچ فقط روی اسناد فعال با منبع درست |
|
||||
| روز ۵ | پاسخ مستند متنی و بازیابی نوبت؛ سپس صوت مستقل Gemini Live و متن پاسخ |
|
||||
| روز ۶ | اتصال ابزار دانش به Live، follow-up، تغییر موضوع و وقفه فارسی |
|
||||
| روز ۷ | چهار صفحه و دموی کامل روی HTTPS |
|
||||
| روز ۸ تا ۱۰ | اصلاح کیفیت، تست شکستها، آمادهسازی نسخه ارائه |
|
||||
|
||||
این زمانبندی تضمین بدون شرط نیست. اگر UI از صفر و فایلها پیچیده باشند یا اتصال مدل Live حل نشود، ریسک زمان بالا میرود. اول امکانات تزئینی و اختیاری حذف میشوند؛ دسترسی صحیح و سه قابلیت اصلی نباید پنهانی حذف شوند.
|
||||
|
||||
## ۱۵. چکلیست ارائه و پذیرش
|
||||
|
||||
- کاربر عادی نتواند تنظیمات یا اسناد را تغییر دهد و گفتگوی دیگری را بخواند.
|
||||
- فایل آمادهنشده وارد سرچ نشود.
|
||||
- سؤال مستند جواب و منبع درست داشته باشد.
|
||||
- سؤال بیپاسخ با اطلاعات ساختگی جواب داده نشود.
|
||||
- ارسال تکراری، نوبت یا کار پردازشی تکراری نسازد.
|
||||
- قطع Worker باعث از دست رفتن کار پذیرفتهشده نشود.
|
||||
- مکالمه صوتی فارسی واقعاً از Gemini Live مستقیم، WSS مدیریتشده بکاند و بازیابی سند استفاده کند؛ متن پاسخ موجود و منابع در UI دیده شوند.
|
||||
- خروج کاربر، پایان جلسه یا تغییر منابع فعال، وضعیت Live را درست تغییر دهد.
|
||||
- تاریخچه متن بعد از restart باقی بماند.
|
||||
- دمو روی شبکه و مرورگر محیط ارائه تمرین شده باشد.
|
||||
|
||||
۱۵ تا ۲۰ سؤال مرجع از اسناد واقعی آماده میکنیم؛ برای هرکدام جواب مورد انتظار و قطعه منبع را مینویسیم. نتیجه اجرای متن و صوت جدا ثبت میشود. این مجموعه کوچک، تضمین دقت عمومی محصول نیست.
|
||||
|
||||
## ۱۶. مواردی که قبل از شروع باید قطعی شوند
|
||||
|
||||
| سؤال | مسئول پیشنهادی |
|
||||
| --- | --- |
|
||||
| فایلهای واقعی چه فرمت و ساختاری دارند و حداکثر اندازه چیست؟ | صاحب محصول + توسعهدهنده |
|
||||
| مدل Live منتخب اتصال و کنترل ابزار مورد نیاز را پشتیبانی میکند؟ | توسعهدهنده/تیم AI با آزمایش واقعی |
|
||||
| مدل Embedding و تعداد ابعادش چیست؟ | تیم AI قبل از مایگریشن بردار |
|
||||
| محیط HTTPS و دسترسی به ارائهدهنده آماده است؟ | توسعهدهنده/زیرساخت |
|
||||
| مدت نشست و نگهداری فایل/گفتگو چقدر است؟ | صاحب محصول/سازمان |
|
||||
| شروع کار و تاریخ ارائه دقیقاً چه روزی است؟ | مدیر پروژه |
|
||||
|
||||
## ۱۷. نحوه استفاده از اسناد توسط توسعهدهنده
|
||||
|
||||
ابتدا Implementation Guide برای ترتیب کار و مرز ماژولها؛ سپس API Catalog برای DTO و هماهنگی فرانت؛ بعد Database Design برای مدلهای ORM و مایگریشن. سناریوهای این گزارش باید تبدیل به تستهای یکپارچه شوند.
|
||||
|
||||
قراردادها با جهت MVP جدید هماهنگ شدهاند؛ Gemini Live مستقیم و استخراج تصویر/جدول نمونه تصمیم محدودهاند، اما مدل دقیق، حساب واجد شرایط، بودجه Embedding و کیفیت واقعی هنوز باید بررسی شوند. پس از تأیید فرمت و مدل و اتصال Live، همین اسناد نسخه جدید میگیرند. افزودن قابلیت محصول کامل به کارهای این فاز باید با تغییر صریح محدوده یا زمانبندی انجام شود.
|
||||
|
||||
## ۱۸. فایلهای نمونه و حدود بررسی محلی — ۲۰۲۶/۱۰/۰۶
|
||||
|
||||
هر چهار فایل در `data/documents/` موجود است. بررسی این نوبت بدون نصب وابستگی و بدون ارسال فایل به ارائهدهنده انجام شد:
|
||||
|
||||
| فایل | بررسی انجامشده و زمینه تأمینشده |
|
||||
| --- | --- |
|
||||
| `7364346504113364738_13450847753183.pdf` | بررسی ساختار خام PDF: پنج شیء صفحه و ارجاع فونت/ToUnicode. طبق مشاهده اولیه تأمینشده توسط کاربر، متن دارد ولی ترتیب واژه/عدد گاهی خراب است |
|
||||
| `5905170444656189186_13450510740952.pdf` | بررسی ساختار خام: یک صفحه و ارجاع فونت/ToUnicode. طبق زمینه کاربر، بخشنامه دارای تاریخ، درصد، شرط و استثنا است |
|
||||
| `photo_1_2026-10-06_09-05-11.jpg` | تصویر محلی دیده شد: گروه اصلی سمت راست، گروه سمت چپ و گروه پایین؛ عنوانها و توضیحها باید با گروه خود نگه داشته شوند |
|
||||
| `-2348240626507047168_13449360743721.docx` | XML داخل DOCX خوانده شد: دو جدول و ۲۰۰ ردیف. در ردیفهای بررسیشده سؤال و جواب عمدتاً پشت سر هماند؛ جاینگهدار قیمت/تعرفه و سناریوی رفتاری هم وجود دارد |
|
||||
|
||||
ابزار استخراج/رندر PDF در محیط محلی این نوبت موجود نبود؛ بررسی متن و چیدمان کامل PDF انجام نشد. نتیجه استخراج اولیه کاربر با این بررسی ساختاری یکی نیست. هیچ Gemini، Mistral یا OCR محلی روی این فایلها آزمایش نشده و هیچ برنده benchmark معرفی نشده است.
|
||||
|
||||
## ۱۹. مثال عملی: اینفوگرافیک از تصویر به دانش قابل بازیابی
|
||||
|
||||
این مثال جریان پیشنهادی است، نه خروجی OCR اجراشده. در تصویر، گروه سمت راست با عنوان «هوشمندسازی و ارتقای بهرهوری» دیده میشود و زیرعنوان «استقرار دولت هوشمند و دادهمحور» در همان گروه است. این دو عنوان از مشاهده تصویر آمدهاند؛ متن کامل توضیح عمداً اینجا ساخته نمیشود.
|
||||
|
||||
۱. تصویر به عنوان سند مستقل آپلود و اصل آن حفظ میشود.
|
||||
۲. Flash vision با دستور رونویسی کامل، بلوکهای هر گروه را جدا میکند: عنوان والد، زیرعنوان، توضیح مربوط، محل بصری و هشدار ناخوانایی.
|
||||
۳. بازبین، ارتباط گروه راست، چپ و پایین و نبود بلوک تکراری/افتاده را با تصویر مقایسه میکند. توضیح یک ستون به عنوان ستون دیگر چسبانده نمیشود.
|
||||
۴. برای هر موضوع، عنوان والد و زیرعنوان همراه توضیح همان موضوع قطعه میشوند. محل پیشنهادی `page=null, section=image/group-right/item-1` است، نه شماره صفحه ساختگی.
|
||||
۵. متن وفادار و متن جستوجوی نرمالشده نگه داشته میشوند؛ همان Embedding و index متن استفاده میشود.
|
||||
۶. سؤال نمونه «در این نمودار، بخش دولت هوشمند چه توضیحی دارد؟» باید بلوک مربوط را برگرداند؛ پاسخ فقط از توضیح تأییدشده ساخته شود. اگر ریزنوشته خوانا نیست، محدودیت اعلام و از نمای واضحتر/بازبینی استفاده شود.
|
||||
|
||||
## ۲۰. مثال عملی: بازیابی بخشنامه و سؤال بعدی صوتی
|
||||
|
||||
این مثال سؤال و روند بازیابی است؛ هیچ عدد یا نقلقول استخراجنشده از PDF اختراع نشده است.
|
||||
|
||||
۱. بخشنامه تکصفحهای با استخراج مستقیم شروع میشود. بازبین تاریخ، درصد، شرطها و استثناها را با اصل صفحه کنترل میکند. اگر عدد وارونه یا ترتیب خراب باشد، همان صفحه رندر و با vision/OCR رونویسی میشود.
|
||||
۲. تصمیم، شرایط و موارد مستثنا با هم قطعه میشوند؛ محل منبع صفحه ۱ و عنوان/بند واقعی است. برای مقررات پنجصفحهای نیز ماده، تبصره و یادداشت مرتبط کنار هم میمانند.
|
||||
۳. کاربر میپرسد: «در این بخشنامه، شرایط اعمال درصد اعلامشده چیست؟» اگر چند بخشنامه فعال باشد، مدل ابتدا مشخص میکند کدام.
|
||||
۴. `search_knowledge` سؤال متمرکز را با زمینه مجاز میگیرد؛ سرچ معنایی و تطبیق دقیق شناسه/ماده/تاریخ، قطعه واجد شرط و استثنا را برمیگردانند.
|
||||
۵. مدل درصد یا تاریخ را فقط از متن بررسیشده میخواند؛ شواهد ناسازگار را پنهانی حل نمیکند. UI عنوان، صفحه و محل واقعی را نشان میدهد.
|
||||
|
||||
نمونه follow-up صوتی: «استثناهاش چی بود؟» مدل مرجع را به همان بخشنامه مشخصشده حل و دوباره شواهد استثنا را بازیابی میکند؛ جمله کوتاه فارسی با استثناهای واقعی میسازد. سپس «حالا درباره دولت هوشمند در اینفوگرافیک بگو» موضوع را عوض میکند؛ ماده/تاریخ بخشنامه به سؤال جدید تحمیل نمیشود. عبارت مبهم «ماده بعدی چی؟» بدون ماده/سند مشخص، سؤال روشنکننده میگیرد.
|
||||
|
||||
اگر کاربر وسط پاسخ بگوید «صبر کن، فقط استثناها»، پخش باقیمانده متوقف و نتیجه ابزار لغوشده کنار گذاشته میشود؛ نوبت جدید با محدودیت تازه بازیابی میکند.
|
||||
|
||||
## ۲۱. بانک سؤالوجواب: دانش، رفتار و داده جاری
|
||||
|
||||
| نوع محتوا | استفاده مجاز پیشنهادی |
|
||||
| --- | --- |
|
||||
| واقعیت تأییدشده سازمان، با اعتبار و محل منبع | پس از تأیید صاحب دانش برای retrieval |
|
||||
| انتظار رفتاری، مانند حفظ زمینه یا نحوه پاسخ به وقفه | سناریوی evaluation یا تنظیم صریح بازبینیشده؛ دستور داخل سند سیاست سیستم را عوض نمیکند |
|
||||
| `[قیمت روز]`، `[تعرفه جاری]`، سؤال بدون مقدار معتبر | شواهد پاسخ factual نیست؛ نیاز به داده/ابزار جاری تأییدشده یا اعلام محدودیت |
|
||||
|
||||
بانک DOCX خودبهخود مرجع رسمی همه پاسخها نیست. قیمت جاری، موجودی زمین، مانده حساب و وضعیت پرونده با RAG ایستا قابل تأیید نیستند. ابزار سازمانی برخط در این فاز تعریف نشده؛ دستیار محدودیت را اعلام و مسیر مراجعه مجاز سازمان را پیشنهاد میکند، نه اینکه اتصال/انتقال خودکار ساختهنشده را وعده دهد.
|
||||
|
||||
نمونه کمبود شواهد، متن پاسخ پیشنهادی: «در اسناد فعال، مقدار معتبر تعرفه جاری را پیدا نکردم؛ برای عدد امروز باید منبع رسمی بهروز بررسی شود.» جاینگهدار به عنوان مقدار خوانده نمیشود.
|
||||
|
||||
نمونه شکست ارائهدهنده، متن پاسخ پیشنهادی: «جستوجوی اسناد فعلاً با خطای اتصال روبهرو شد. لطفاً دوباره تلاش کنید.» UI خطای فنی را نشان میدهد؛ نمیگوید «چنین سندی وجود ندارد». اگر خود Live قطع باشد، همین پیام در UI نمایش داده میشود و پاسخ صوتی از ارائهدهنده قطعشده فرض نمیشود.
|
||||
|
||||
## ۲۲. پذیرش و بودجه MVP جدید
|
||||
|
||||
ترتیب عملی: استخراج/کنترل کیفیت/ایندکس نمونهها؛ retrieval و پاسخ مستند متنی؛ صوت مستقل Live؛ اتصال ابزار دانش؛ بررسی فارسی، follow-up، تغییر موضوع و وقفه؛ تمرین کامل روی شبکه و تجهیزات ارائه. بودجه پیشنهادی: ۱۰ دلار Gemini، ۱۰ دلار OpenRouter و ۱۰ دلار ذخیره اختیاری؛ خرج اولیه ۲۰ و بودجه قابل برنامهریزی ۳۰ دلار. حدود ۵ دلار Gemini برای تمرین نهایی/ارائه نگه داشته شود. این تضمین هزینه کل نیست؛ نرخ رسمی، حساب، سقف واقعی و هزینه جداگانه Embedding باید بررسی شوند.
|
||||
|
||||
معیارهای P1-01 تا P1-12 حفظ و P1-13 تا P1-17 در [برنامه تحویل](RAG-AI-Phase1-Delivery-Plan.md) اضافه شدهاند: متن و تصویر، حفظ رابطه عنوانها، عدد/استثنا، صوت فارسی مستند، منبع قابل مشاهده، زمینه/تغییر موضوع، نبود جعل و خطای قابل فهم. evaluation بازیابی با محلهای مستقل علامتگذاریشده انجام میشود؛ کیفیت تولید و صوت جدا ثبت میشود. یک FAQ ایندکسشده تنها شاهد موفقیت خودش نیست.
|
||||
|
||||
تصمیم قطعی محصول با پیشنهاد DTO/مخزن استخراج و شواهد کد فعلی متفاوت است. کد فعلی شامل prototype Markdown/Chroma و foundation/intake است؛ worker، retrieval آپلودها، احراز هویت HTTP و Live هنوز ساخته نشدهاند. این ویرایش مستندات به معنی MVP عملیاتی نیست. اعتبار حساب/شبکه، مدل و بودجه Embedding و تأیید دانش/اعداد، دروازههای وابسته را مسدود میکنند تا واقعاً بررسی شوند.
|
||||
Reference in New Issue
Block a user