Add the scoped PostgreSQL/pgvector schema, independent ingestion settings and ports, embedding profile checks, and trusted administrator bootstrap. Include repository contracts and guidance, organized provider-free and PostgreSQL tests, deployment setup, and byte-preserving migration attributes. Validation: 163 tests passed; all 48 PostgreSQL cases passed with pgvector Python 0.5.0 and 0.3.6. No production schema or historical metadata was changed.
632 lines
43 KiB
Markdown
632 lines
43 KiB
Markdown
# Organization Knowledge Assistant — Software Architecture
|
|
|
|
| Document field | Value |
|
|
| --- | --- |
|
|
| Version | 1.1 — simplified document lifecycle |
|
|
| Date | 2026-10-05 |
|
|
| Status | Proposed implementation design; open decisions are listed in Section 19 |
|
|
| Audience | Project management, technical mentor, backend, frontend and AI developers |
|
|
| Application | Organization-managed document RAG with text and direct live voice conversations |
|
|
| 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 system enables authenticated users to ask questions in Persian, including conversational wording, and receive answers grounded in reference documents selected by their organization. It supports text chat and direct speech-to-speech interaction with a live AI model. Organization administrators manage the knowledge base without changing application code.
|
|
|
|
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.
|
|
- OpenAI supplies embedding and text generation capabilities; exact model identifiers remain configurable and must be evaluated.
|
|
- Voice conversations use a live speech-to-speech model and WebRTC. There is no separate application ASR or TTS pipeline.
|
|
- 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_documents`. A separate read-document tool is excluded.
|
|
- Text and voice have separate entry points but share retrieval, access rules, configuration and persistent history services.
|
|
- The dashboard includes login, document management, model configuration, text entry and microphone controls.
|
|
|
|
### 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 initially. LangGraph may continue to orchestrate text-agent turns. The provider-native live session performs the voice conversation loop; LangGraph does not need to process every audio frame.
|
|
|
|
These choices are architecture recommendations, not claims that the existing repository already implements them. File formats, live provider/model, authentication integration, retention rules, capacity targets and delivery dates require confirmation.
|
|
|
|
### 1.3 Scope boundaries
|
|
|
|
The initial system includes document ingestion, organization-scoped retrieval, text and live voice conversations, citations, configuration, operational logging and basic administration. 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. **Direct live audio:** browser-to-provider media is separate from backend session control and tool execution.
|
|
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, chat, microphone/speaker, captions, sources, document and settings screens | Browser over HTTPS |
|
|
| FastAPI application | Authorization, text orchestration, live session control, tools, document APIs and history | Backend process |
|
|
| Ingestion worker | Extraction, chunking, embedding, retries and publication | Separate process from the same codebase |
|
|
| PostgreSQL + pgvector | Metadata, jobs, history, configuration, chunks and vectors | Persistent database |
|
|
| File storage | Original uploaded document bytes | Durable volume or object storage |
|
|
| Text/embedding provider | Text-agent inference and vector generation | External OpenAI API |
|
|
| 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 connects to the provider's WebRTC media endpoint, while the backend owns credentials, session policy and private tool execution.
|
|
|
|
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 | Conversations, turns, messages, citations and summaries | Start; submit turn; read history; close |
|
|
| Live Sessions | Provider session mapping, connection state and live event handling | Create; connect control channel; process event; close |
|
|
| Configuration | Allowed model profiles and retrieval settings | Read and update versioned settings |
|
|
| 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/` | Text turns and persistent history |
|
|
| `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_documents` 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 direct live speech, audio may reach the user before a server-side 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
|
|
|
|
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
|
|
|
|
```json
|
|
{
|
|
"name": "search_documents",
|
|
"description": "Search the organization's selected reference documents for evidence relevant to a question.",
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {
|
|
"query": {"type": "string", "description": "A focused search question preserving the user's constraints."}
|
|
},
|
|
"required": ["query"],
|
|
"additionalProperties": false
|
|
}
|
|
}
|
|
```
|
|
|
|
The tool does not accept organization IDs, arbitrary document paths, SQL, credentials or a model-selected permission scope. The backend supplies identity, allowed documents, embedding profile, retrieval limits and trace identifiers through trusted execution context.
|
|
|
|
### 6.2 Result contract
|
|
|
|
```json
|
|
{
|
|
"status": "ok",
|
|
"search_id": "search_example",
|
|
"selection_revision": 7,
|
|
"results": [
|
|
{
|
|
"source_ref": "S1",
|
|
"document_id": "doc_example",
|
|
"chunk_id": "chunk_example",
|
|
"title": "Working Hours Policy",
|
|
"page": 3,
|
|
"section": "Thursday Schedule",
|
|
"text": "Illustrative evidence text from the uploaded document."
|
|
}
|
|
],
|
|
"warnings": []
|
|
}
|
|
```
|
|
|
|
The sample IDs and content are illustrative. Page and section are nullable when extraction cannot identify them. References are scoped to a turn/search; persistent citations use stable document/chunk IDs. Never fabricate page numbers.
|
|
|
|
Tool statuses distinguish `ok`, `no_results`, `knowledge_unavailable` and `error`. An empty authorized knowledge base is different from an unrelated query; a provider failure must not be presented as proof that no relevant document exists.
|
|
|
|
### 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.
|
|
|
|
The semantic baseline is required. Lexical fusion and reranking are optional improvements enabled after measurement. 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
|
|
|
|
The API validates the configured file allowlist, size and basic file signature, stores the original under a generated storage key, calculates a checksum, creates an independent document and enqueues a durable ingestion job. Client filenames are display metadata and never trusted filesystem paths.
|
|
|
|
Accepted formats remain an open requirement. The extraction interface supports implementations chosen after representative files are received. OCR is enabled only if scanned material requires it. Empty or unreadable extraction must fail visibly rather than publishing an empty index. Table structure and units must be preserved where needed by the actual corpus.
|
|
|
|
### 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. The design must avoid splitting meaningful table rows or dropping headings when those structures carry meaning.
|
|
|
|
Embedding profiles record provider, model, dimensions and preprocessing version. Documents and queries must use the same compatible profile. Changing the embedding model creates a new index generation: re-embed, verify completion and switch the active generation atomically. 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 and WebRTC
|
|
|
|
### 8.1 Connection responsibilities
|
|
|
|
| Channel | Participants | Purpose |
|
|
| --- | --- | --- |
|
|
| HTTPS session request | Browser and FastAPI | Authenticate and initialize an authorized live session |
|
|
| WebRTC media | Browser and live provider | Microphone input and generated speech |
|
|
| Trusted control connection | Backend and live provider | Tool calls/results, policy updates and session events |
|
|
| Application event channel | Backend and browser | Source references, status and normalized captions when available |
|
|
|
|
OpenAI's WebRTC and server-control documentation establish the direct browser media and trusted server connection patterns [R1, R2]. Exact events and signaling depend on the selected API family. The adapter must implement one tested provider contract; event names from different API families must not be mixed.
|
|
|
|
### 8.2 Session establishment
|
|
|
|
1. The authenticated browser obtains microphone permission and creates a WebRTC offer.
|
|
2. The Live Session API verifies ownership, role, usage limits and selected knowledge.
|
|
3. The backend creates a local session record, resolves model/prompt/tool configuration and performs provider signaling.
|
|
4. The controller attaches the trusted control connection and confirms that private tool execution is ready.
|
|
5. The browser receives the session ID and signaling response, then establishes media.
|
|
6. The dashboard presents connected/listening states and enables conversation.
|
|
|
|
A provider-supported short-lived credential flow may replace server signaling. Persistent provider keys remain on the server. Failed setup triggers cleanup of any partially created provider/local session. Readiness of the control path is required before allowing organization-knowledge conversation.
|
|
|
|
### 8.3 Voice tool cycle
|
|
|
|
```mermaid
|
|
sequenceDiagram
|
|
participant U as Browser
|
|
participant L as Live Model
|
|
participant B as Backend Controller
|
|
participant K as Knowledge Service
|
|
U->>L: Audio over WebRTC
|
|
L->>B: search_documents call
|
|
B->>B: Validate identity, scope and call
|
|
B->>K: Execute search
|
|
K-->>B: Evidence and sources
|
|
B-->>L: Correlated tool result
|
|
B-->>U: Source references
|
|
L-->>U: Generated speech
|
|
```
|
|
|
|
The controller invokes the same search application service used by the text agent. Tool results are correlated by provider session and call ID, and executed once or replayed from a saved result on duplicate events. Allow only registered tool names. Partial argument events are accumulated until the call is complete and validated.
|
|
|
|
### 8.4 Turn-taking, interruption and disconnects
|
|
|
|
The live provider handles speech input and output. Its turn-detection and interruption capabilities are configured and tested for Persian conversation. When interrupted, the UI stops queued playback using supported provider/browser controls; history distinguishes a completed response from an interrupted one. Generated text must not automatically be treated as fully heard speech.
|
|
|
|
Closing the session stops microphone tracks, closes the peer connection and provider control connection, and records termination reason and known usage. Abandoned sessions expire. Reconnection creates or resumes a provider session only when supported; it must not imply transparent recovery after a backend restart.
|
|
|
|
If the control connection fails while media remains connected, pause or close knowledge conversation rather than continuing unsupported answers. Late tool results for canceled turns are discarded or recorded without triggering a new response. The dashboard can offer text chat when voice setup fails.
|
|
|
|
### 8.5 History and audio limitations
|
|
|
|
No separate ASR service is introduced for persistence. Save transcripts/captions only when supplied by the provider, with their source and completion state. Missing transcript events remain missing; do not invent them. Provider captions may differ from what a user meant or actually heard.
|
|
|
|
The backend does not automatically possess audio bytes because media travels directly to the provider. Recording audio would require a separate explicit feature and retention decision. Durable history survives a provider session, but continuing a conversation requires explicitly restoring selected history or a summary into the new model context.
|
|
|
|
## 9. Logical Data Model
|
|
|
|
This is a proposed model for the RAG service, independent of the earlier CTI module's database. Exact SQL migrations follow review of these invariants.
|
|
|
|
| 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
|
|
|
|
These are proposed application endpoints, not provider API endpoints. The three core business capabilities are document ingestion, text chat and live voice; supporting administration requires additional routes.
|
|
|
|
| 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
|
|
|
|
```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
|
|
|
|
The baseline request carries `conversation_id`, `client_request_id` and a WebRTC SDP offer. The response carries an application session ID, the provider adapter's signaling answer and normalized connection state. If a credential-based setup is selected, define a separate validated response variant. Never expose a persistent provider key. Do not log SDP or temporary credentials by default.
|
|
|
|
### 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 |
|
|
| Text history | Retry does not duplicate messages; restart preserves completed conversations |
|
|
| Voice | Direct speech-to-speech, searchable document answers, interruption, reconnect 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 text and voice independently even though retrieval is shared.
|
|
|
|
## 17. Migration from the Existing Repository
|
|
|
|
The earlier review inspected commit `cb54a35`; this mapping refers to that snapshot and is not a claim about a newer branch.
|
|
|
|
| Existing area | Required evolution |
|
|
| --- | --- |
|
|
| `app/services/retriever.py` | Replace Chroma/FastEmbed with repository and embedding interfaces backed by pgvector/OpenAI |
|
|
| `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. Confirm representative documents, question set, live provider capabilities and UI expectations.
|
|
2. Implement a small WebRTC spike demonstrating direct audio plus a trusted backend tool call.
|
|
3. Establish the modular backend, database migrations, identity boundary and provider interfaces.
|
|
4. Implement ingestion, document lifecycle, pgvector retrieval and the search tool contract.
|
|
5. Deliver the text agent with evidence, durable history and evaluation.
|
|
6. Connect the live controller to the same tool service; add interruption, sources and failure behavior.
|
|
7. Deliver organization administration, document selection and model configuration.
|
|
8. Validate isolation, performance, recovery and the actual presentation environment.
|
|
|
|
The text path provides an inspectable foundation while the early voice spike exposes provider/network risk. Final calendar dates depend on the confirmed meeting year, corpus and capacity; this document does not infer a deadline from an ambiguous date.
|
|
|
|
## 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 versus per-assistant document selections | Product owner | Selection model and API scope |
|
|
| Live provider/model and supported trusted control features | AI/backend team | Adapter, WebRTC signaling and tool execution |
|
|
| Text and embedding model profiles | AI team | Quality, cost and vector dimensions |
|
|
| Local authentication or SSO | IT / backend | Login contract and identity integration |
|
|
| 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 |
|
|
| Final UI details | Product owner / Mr. Siavash | Frontend flow and review |
|
|
| 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]** [OpenAI — WebRTC](https://developers.openai.com/api/docs/guides/voice-webrtc): browser media connection and signaling patterns.
|
|
- **[R2]** [OpenAI — Server-side controls](https://developers.openai.com/api/docs/guides/voice-server-controls): trusted backend control connection and private tool execution.
|
|
- **[R3]** [OpenAI — Realtime with tools](https://developers.openai.com/api/docs/guides/realtime-mcp): function tool calls and correlated 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_documents"]
|
|
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"]
|
|
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 <-->|"Direct Live Audio — WebRTC"| LIVE
|
|
|
|
TOOL <--> SEARCH
|
|
SEARCH <--> DB
|
|
|
|
DOCS -->|"Upload and Update"| INGEST
|
|
DOCS -->|"Active Document Selection"| SEARCH
|
|
DOCS -->|"Store Original Files"| FILES
|
|
FILES --> INGEST
|
|
INGEST --> DB
|
|
```
|