Files
rag-technical-docs-assistant/data/documents/RAG-Phase1-API-Catalog (1).md
T
amirhosein mazaheri baf58da562 feat(ingestion): add Phase 1 database and application foundation
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.
2026-10-05 16:38:28 +03:30

20 KiB

RAG Assistant — Phase 1 API Catalog

Version 1.1 · 2026-10-05 · Proposed application contract; no running endpoints are claimed.

Companions: RAG-Phase1-Implementation-Guide.md, RAG-Phase1-Database-Design.md, RAG-Phase1-Scenario-Report-FA.md. Scope follows RAG-AI-Phase1-Delivery-Plan.md. No document versioning is implemented: every upload is a new document; there is no version-upload route, model selector, mixed conversation or SSE in Phase 1.

1. Transport and common conventions

Base path /api/v1; UTF-8 JSON except multipart upload; same-origin HTTPS. UUIDs identify application records. Timestamps are UTC RFC3339. null means unavailable, not an invented source location. Unexpected request fields return 422. Example UUIDs are illustrative.

Secure HttpOnly rag_session cookie authenticates requests. Login and all mutations enforce trusted Origin; authenticated mutations also require X-CSRF-Token. /me returns a CSRF token for refresh. No frontend persistent provider key, organization ID override or model override is accepted.

Roles: admin and user. Both can chat and read their own history/live state. Only admin manages documents, selection and settings. Hidden resource access returns 404. Admin does not implicitly own all conversations.

Lists use limit (default 20, maximum 100) and opaque cursor. Stable ordering is (created_at DESC,id DESC) except messages, ordered by ascending sequence_no. Responses use {items:[],next_cursor:null}. Unknown/invalid cursor returns 422. No total count is promised.

X-Request-ID response header and error.request_id correlate logs. Servers generate one if none is valid. Idempotency-Key is required on upload, manual ingestion retry and delete; UUID client_request_id is required in create-conversation, chat and create-live bodies. Keys are scoped to actor/organization and operation as specified below. Reuse with different normalized input returns 409.

Proposed field limits: text message 8000 characters; assistant name 120; instruction 8000; search query 2000; conversation title 120; document title 200. File limits/formats and SDP byte cap come from deployment configuration and are exposed as capabilities where useful. These are implementation defaults to confirm, not provider guarantees.

2. Endpoint inventory

ID Method and path Access Success
A01 POST /auth/login Public, trusted Origin 200 + cookie
A02 POST /auth/logout Authenticated; expired/missing session accepted 204
A03 GET /me Authenticated 200
D01 POST /documents Admin 202
D02 GET /documents Admin 200
D03 GET /documents/{document_id} Admin 200
D04 POST /documents/{document_id}/retry Admin 202
D05 DELETE /documents/{document_id}?expected_revision=N Admin 202
K01 GET /knowledge-selection Admin 200
K02 PATCH /knowledge-selection Admin 200
F01 GET /configuration Authenticated 200
F02 PATCH /configuration Admin 200
C01 POST /conversations Authenticated 201
C02 GET /conversations Owner 200
C03 GET /conversations/{conversation_id}/messages Owner 200
T01 POST /chat Owner of text conversation 200 or 202
T02 GET /conversations/{conversation_id}/turns/{client_request_id} Owner 200
V01 POST /voice/sessions Owner of voice conversation 201 or 202
V02 GET /voice/sessions/{session_id} Owner 200
V03 GET /voice/sessions/by-request/{client_request_id} Owner 200
V04 POST /voice/sessions/{session_id}/close Owner 200
H01 GET /health/live Deployment health access 200
H02 GET /health/ready Deployment health access 200 or 503

Health paths are outside /api/v1. Register /voice/sessions/by-request/... before dynamic routes if the router needs that ordering. search_documents is internal and has no public HTTP route.

3. Authentication

A01 — Login

{"username":"demo.admin","password":"<password>"}
{"user":{"id":"01000000-0000-4000-8000-000000000001","username":"demo.admin","role":"admin","organization_id":"02000000-0000-4000-8000-000000000001"},"csrf_token":"<session-csrf-token>","expires_at":"2026-10-05T18:00:00Z"}

Credentials invalid: 401 INVALID_CREDENTIALS; throttled: 429. Do not distinguish missing username from wrong password. Expiry above is illustrative. Set Secure/HttpOnly/SameSite=Lax cookie; rotate tokens after successful login.

A02 — Logout

No body. Revoke current session, clear cookie and close owned live sessions linked to it. Repeated logout returns 204. For a valid session require CSRF; missing/expired session may simply clear cookie after Origin validation.

A03 — Current identity

No body. Same identity/CSRF/expiry shape as login. Missing/expired session returns 401 AUTH_REQUIRED.

4. Documents and selected knowledge

D01 — Upload

multipart/form-data: required file; optional title. Required Idempotency-Key. The server creates one independent document and ingestion job. New document is inactive.

{"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","is_active":false,"searchable":false}

202 acknowledges durable metadata/job creation, not completed processing. Replay same upload returns these stable identities with current processing state and header Idempotency-Replayed: true. Scope key to organization; hash bytes and normalized title. 413 FILE_TOO_LARGE, 415 UNSUPPORTED_FILE_TYPE, 422 INVALID_FILE, 409 IDEMPOTENCY_CONFLICT. A parser failure after acceptance is represented by document status, not a later HTTP response to upload.

D02 — List

Query: common pagination; optional status=queued|processing|ready|failed, is_active=true|false. Exclude deleted documents. Items use the D03 shape, except potentially omit verbose error detail. Return current knowledge_revision alongside the list.

D03 — Detail / processing polling

{"id":"10000000-0000-4000-8000-000000000001","title":"Working Hours","filename":"working-hours.pdf","status":"ready","is_active":false,"searchable":false,"created_at":"2026-10-05T09:00:00Z","chunk_count":8,"job":{"id":"40000000-0000-4000-8000-000000000001","status":"succeeded","stage":"publish","attempt_count":1,"retry_generation":0,"can_retry":false,"error":null}}

searchable = ready AND active AND not deleted. Poll while queued/processing; proposed interval 2 seconds, slow down when tab is hidden. Failed job exposes {code,message,retryable} without internal stack traces. can_retry means server allows retry of the unchanged original; corrupt input generally requires new upload. Return 404 for deleted/hidden ID.

D04 — Retry failed processing

No body; required Idempotency-Key. Eligible only for failed undeleted document and retained original. Requeue same job, reset attempt count, increment retry generation and audit. Same key replays without incrementing twice.

{"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","retry_generation":1}

409 DOCUMENT_NOT_RETRYABLE for running/ready/permanent failure; 404 hidden/deleted. The retry-key record is retained in audit metadata with a database uniqueness constraint.

D05 — Delete

Required expected_revision is the current knowledge revision; required idempotency key. Transaction locks selection and document. Mark deleted and inactive; if formerly active, increment knowledge revision and access epoch and invalidate sessions. Physical cleanup is not promised by this response.

{"document_id":"10000000-0000-4000-8000-000000000001","deleted":true,"knowledge_revision":3,"access_epoch":2,"cleanup_status":"pending_policy"}

202; 409 REVISION_CONFLICT on stale initial request. Replay same delete/key returns recorded result before revision validation. A new delete request for an already-deleted owned document can return its tombstone result without changing revisions. No read or search route restores eligibility.

K01 — Get selection

{"revision":1,"access_epoch":1,"document_ids":[]}

K02 — Replace selected set

This replaces the entire set, not a delta. UI reads current selection before toggling a document.

{"expected_revision":1,"document_ids":["10000000-0000-4000-8000-000000000001"]}
{"revision":2,"access_epoch":1,"document_ids":["10000000-0000-4000-8000-000000000001"],"conversations_invalidated":false}

Duplicate IDs: 422. Any unready item: 409 DOCUMENT_NOT_READY, with rejected IDs in details; no partial update. Hidden ID: 404. Stale revision: 409 REVISION_CONFLICT. No-op preserves revision. Removing an active ID increments epoch and sets conversations_invalidated=true; all older organization conversations become unusable for new turns. After a timeout GET current state instead of blindly repeating with an old revision.

5. Configuration

F01 — Read

{"revision":1,"assistant_name":"Organization Assistant","instruction":"پاسخ‌ها کوتاه و بر اساس اسناد سازمان باشند.","capabilities":{"text":true,"voice":true,"captions":false,"supported_upload_types":["<confirmed-MIME-type>"],"max_upload_bytes":null}}

Runtime must replace illustrative capability placeholders with actual configuration; max_upload_bytes is a positive integer in deployed responses. No model secrets or selectable model list. Non-admin may read presentation settings/capabilities.

F02 — Update

{"expected_revision":1,"assistant_name":"HR Assistant","instruction":"فارسی و رسمی پاسخ بده؛ نبود اطلاعات را اعلام کن."}

200 returns F01 with incremented revision. Both fields are required; no-op preserves revision. Stale value: 409 REVISION_CONFLICT. Text applies on subsequent turns; existing live session keeps its snapshot until restarted. Settings cannot relax system authorization or grounding rules.

6. Conversations and text

C01 — Create

{"client_request_id":"50000000-0000-4000-8000-000000000001","mode":"text","title":"Working hours"}
{"id":"60000000-0000-4000-8000-000000000001","mode":"text","title":"Working hours","status":"active","access_epoch":1,"created_at":"2026-10-05T09:05:00Z"}

mode is text or voice, never mixed. Title optional. Idempotency scope (owner,client_request_id); same payload replays original 201. Different payload 409. New conversation snapshots current epoch. Voice history cannot be continued as text in Phase 1.

C02 — List own conversations

Common pagination, optional mode. Items use C01 response plus updated_at; derive status=stale when epoch differs. Status values: active, stale, closed. List excludes other users regardless of role.

C03 — Read messages

Common pagination, ascending sequence. Voice can return no messages because transcripts are not guaranteed. Old text history remains viewable even when stale.

{"conversation_id":"60000000-0000-4000-8000-000000000001","conversation_status":"active","items":[{"id":"70000000-0000-4000-8000-000000000001","turn_id":"80000000-0000-4000-8000-000000000001","sequence_no":1,"role":"user","content":"پنجشنبه تا چه ساعتی باز هستید؟","created_at":"2026-10-05T09:06:00Z","sources":[]}],"next_cursor":null}

Assistant items also expose turn_status and source objects. Failed turns remain visible as state, not fabricated assistant answers. A user message may exist without an assistant reply; UI follows turn status.

T01 — Submit text turn

{"conversation_id":"60000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","message":"پنجشنبه تا چه ساعتی باز هستید؟"}
{"conversation_id":"60000000-0000-4000-8000-000000000001","turn_id":"80000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","status":"answered","message_id":"70000000-0000-4000-8000-000000000002","answer":"طبق سند ساعات کاری، پنجشنبه‌ها تا ساعت ۱۲ باز هستیم.","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Working Hours","excerpt":"پنجشنبه‌ها از ساعت ۸ تا ۱۲","location":{"page":2,"section":null},"available":true}],"error":null}

200 returns terminal execution: answered, needs_clarification, insufficient_information or failed. answer/message_id are null on failed, with normalized error. A successfully processed unsupported question uses insufficient_information, human-readable answer and usually empty sources. Failed generation is not reported as a successful answer.

202 returns a running turn shape with answer:null, message_id:null, empty sources, error:null and Location pointing to T02. This occurs on duplicate running request or when the initial response deadline expires while the owned task is still running. Do not start a second task. Client disconnection must not silently create duplicate execution.

Scope key (conversation_id,client_request_id). Changed message under same key: 409. Another different request while one runs: 409 CONVERSATION_BUSY. Wrong mode: 409 MODE_MISMATCH. Stale epoch: 409 CONVERSATION_STALE. Admission failures use the common HTTP error envelope; failures after a turn is persisted use its failed terminal result. Retry completed failures only with a new request ID.

T02 — Recover/poll turn

Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.

7. Voice contract — provisional signaling, fixed ownership rules

The SDP variant below is the target application contract, conditional on Day 1 provider proof. It is not a claim that every Live provider supports it. Freeze a compatible variant before frontend implementation.

V01 — Create session

{"conversation_id":"61000000-0000-4000-8000-000000000001","client_request_id":"91000000-0000-4000-8000-000000000001","sdp_offer":"<browser-generated SDP>"}
{"session_id":"a0000000-0000-4000-8000-000000000001","conversation_id":"61000000-0000-4000-8000-000000000001","status":"connecting","sdp_answer":"<provider-generated SDP>","expires_at":"2026-10-05T09:30:00Z","poll_url":"/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001"}

Conversation must be voice, current epoch and owned by caller. Scope key (owner,client_request_id); hash conversation and SDP. Changed offer under same key is 409. One nonterminal session per conversation. A duplicate during creation returns 202 with session ID/state and null SDP answer, never another provider session. Completed replay returns 201 and the same short-lived answer while still valid. Closed/failed/expired reservations return 409 LIVE_SESSION_UNUSABLE; start a fresh request after resolving the old one.

Persist only encrypted short-lived SDP answer for replay, purge at close/expiry; do not store raw offer or log SDP. Provider creation timeout marks failed/uncertain, never blind automatic recreation. Validate trusted tool-control availability before returning usable signaling. 503 may be used for pre-reservation provider capability failure; a persisted reservation can be inspected with V03.

V02 — Poll state and recent retrieved sources

{"session_id":"a0000000-0000-4000-8000-000000000001","status":"connected","close_reason":null,"expires_at":"2026-10-05T09:30:00Z","recent_tool_results":[{"tool_call_id":"b0000000-0000-4000-8000-000000000001","status":"succeeded","created_at":"2026-10-05T09:08:00Z","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Working Hours","excerpt":"پنجشنبه‌ها از ساعت ۸ تا ۱۲","location":{"page":2,"section":null},"available":true}]}]}

Return at most 20 recent tool results in chronological order; clients deduplicate by tool_call_id. This is a bounded status snapshot, not a durable full event stream. Sources are retrieved evidence, not guaranteed spoken citations. Redact excerpts of revoked sources and mark unavailable. State is creating, connecting, connected, closed or failed. UI polling suggested every 2 seconds; terminal state stops polling. No client route can claim a session connected or inject a trusted tool result.

V03 — Recover creation by request ID

200 returns V01 signaling shape while creating/connecting and still eligible; connected/terminal returns state with null SDP answer if replay is no longer useful. Owner-only; 404 if no reservation. This lookup does not create sessions. A client that has lost its peer connection must close/reconcile the old session before starting another, not apply an old SDP answer to a new offer.

V04 — Close

No body. 200 {session_id,status:"closed",close_reason:"user_requested"}. Idempotent: already closed/failed returns its existing terminal state. Mark locally closed and attempt provider cleanup; unresolved cleanup is logged and bounded by provider expiry. Revocation/auth expiry/control loss can also terminate sessions; UI displays returned reason.

8. Health

H01: 200 {"status":"ok"} when the process is alive. H02: 200 {"status":"ready","ingestion":"available"} or degraded ingestion marker if worker heartbeat is stale; 503 {"status":"not_ready"} for required DB/schema/storage failure. Health responses never disclose connection strings or provider keys. Provider outages surface in relevant business operations, not liveness.

9. Error envelope and mapping

{"error":{"code":"REVISION_CONFLICT","message":"Selection changed; reload and try again.","request_id":"req-example","retryable":false,"details":{"current_revision":3}}}
HTTP Codes / use Client action
401 AUTH_REQUIRED, INVALID_CREDENTIALS Login; do not retry provider work
403 FORBIDDEN, CSRF_INVALID Show denial or refresh session token
404 NOT_FOUND Stop; do not expose ownership details
409 REVISION_CONFLICT Read latest selection/configuration
409 IDEMPOTENCY_CONFLICT Correct client request/key handling
409 CONVERSATION_BUSY, CONVERSATION_STALE, MODE_MISMATCH Poll current turn, start fresh conversation, or correct mode
409 DOCUMENT_NOT_READY, DOCUMENT_NOT_RETRYABLE, LIVE_SESSION_UNUSABLE Follow returned state
413/415/422 FILE_TOO_LARGE, UNSUPPORTED_FILE_TYPE, VALIDATION_ERROR Correct input
429 RATE_LIMITED Honor Retry-After; reuse key when retrying same operation
503 DEPENDENCY_UNAVAILABLE Show service failure; reconcile state before retry

Inside persisted failed turns/jobs, normalized codes include PROVIDER_TIMEOUT, PROVIDER_UNAVAILABLE, SEARCH_FAILED, INVALID_CITATION, PROCESS_INTERRUPTED and CONVERSATION_STALE. An HTTP 200 failed-turn result still represents application failure. Technical retryability does not authorize automatic regeneration under a new key.

10. Frontend implementation order and exclusions

Build A01/A03 and upload polling first, selection next, then C01/T01/T02/messages, then voice and settings. Display request progress and state rather than a fake percentage. Disable selection on non-ready documents. On stale conversation explain that sources changed and offer New Conversation. Do not automatically copy revoked context.

Out of scope: file-version API, raw downloads for ordinary users, document text editing, search HTTP endpoint, model selector, raw audio recording, streamed chat, mixed-mode history, full event replay. Sources needed by normal users are supplied in authorized message/session responses.