Files
amirhosein mazaheri 6f0561c490 docs(voice): freeze OpenAI Realtime Phase 0 contracts
Align voice specifications and the MVP plan with OpenAI Realtime.
Document audio admission, bounded playback, cancellation ownership,
turn correlation, cleanup barriers and calibration prerequisites.
Preserve historical checkpoints and record unrun acceptance gates.
2026-10-08 18:07:38 +03:30

59 KiB
Raw Permalink Blame History

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 follows the delivery plan's scoped Phase 0 amendment and the Realtime MVP backend plan; its conditional 3-5 day estimate supersedes the earlier four-day integration sequence. 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; OpenAI Realtime 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 OpenAI Realtime 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 OpenAI Realtime 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 OpenAI Realtime 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.

{
  "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. 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.

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 and 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:

{
  "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.

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

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 backend-managed OpenAI Realtime

8.1 Connection responsibilities

Use backend-managed OpenAI Realtime for voice, as authorized in the Realtime MVP plan. The provider connection is stateful WSS; the backend relays client audio and controls private tools. The browser uses the application stream, not provider SDP or credentials. See Realtime conversations.

OpenRouter is for bounded comparisons of two or three text/vision candidates. Its audio interface supports request audio and streamed response audio; that does not establish a compatible bidirectional OpenAI Realtime 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 OpenAI Realtime 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 audio/event fields are frozen in API catalog Section 7.

8.3 Voice tool cycle

sequenceDiagram
    participant U as Browser or approved audio bridge
    participant B as Backend Live controller
    participant L as OpenAI Realtime
    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. Realtime function calling requires application handling of function results and authorized response continuation through private provider call IDs.

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 frozen application stream uses raw mono signed PCM16LE at 24 kHz in both directions, governed by API Section 7.1. Capture/resample browser audio and convert output for playback; do not forward compressed blobs as PCM. user_speech_started, audio_started and validated playback_progress correlate turns and reported playback. One audio_ref covers one provider item/audio content part; audio_ended seals generation, not playback. API 7.1.1-7.1.4 governs integer sample coordinates, retained references, final reports after interruption, acknowledged private cleanup before continuation, transport bounds and sixteen walkthroughs. API 7.1.5 separately bounds generated audio and paces delivery using validated progress credits; 7.1.6 preserves delayed user ASR and gates response release on current committed input, valid authority/epoch and all cleanup barriers. Both VAD flags are false with backend-owned response-specific cancellation and narrow completion-race handling; normal exchanges are not relabeled interrupted. Interruption clears playback; cleanup failure closes the session instead of continuing with unheard context. See Realtime audio and interruption.

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)

{
  "conversation_id": "conv_example",
  "client_request_id": "request_example",
  "message": "What are the organization's Thursday working hours?"
}
{
  "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

{
  "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 OpenAI Realtime. No SDP or provider credential is returned. See the canonical API catalog for proposed events and ownership/replay behavior.

10.4 Error envelope

{
  "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 OpenAI Realtime 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
Configured OpenAI Realtime 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.

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

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

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 OpenAI Realtime 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 (historical; superseded for voice by Phase 0); Flash vision extraction candidate; OpenRouter comparisons; historical 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 for local inspection limits and worked examples, and delivery plan Section 14 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 OpenAI Realtime 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, LangChain tools, retrieve and rerank.