Files
heala-backend/docs/rag.md
T
2026-11-27 20:46:29 +03:30

12 KiB

Article-grounded answers

RAG is off by default. The existing chatbot remains at /v1/chatbot/chat and /v1/chatbot/stream. Set RAG_ENABLED=true after applying both RAG migrations and starting the embedding service.

Architecture

NestJS owns article metadata, private files, ingestion, vector retrieval and conversation history. The FastAPI service owns the tokenizer and CPU inference. OpenRouter generates the final text through the existing SDK client and configured OPENROUTER_MODEL. Redis runs BullMQ and never receives articles, questions or embeddings.

  1. An administrator uploads a PDF, DOCX or UTF-8 TXT file. NestJS stores the file under a generated UUID and records a pending article.
  2. A recurring dispatcher reconciles PostgreSQL status with deterministic BullMQ job IDs. The worker extracts text, normalizes Unicode and asks the Python service to split it into token windows. It embeds chunks in batches and publishes the new index and ready status in a single transaction.
  3. Chat embeds the latest question locally. PostgreSQL searches ready chunks with the matching model and revision. NestJS filters repetitive excerpts, caps sources and builds the model prompt with the original medical safety policy.
  4. NestJS validates the citation IDs returned by OpenRouter and persists the answer and source metadata in the existing conversation. It returns a localized fallback if there is insufficient evidence or the completion cannot be validated.

The worker uses a generation number and a per-attempt token to fence stale workers. Transient failures retry up to four attempts with exponential backoff starting at five seconds. Document errors such as unreadable files or PDFs requiring OCR fail immediately. Redis recovery redispatches pending work. Reprocessing makes the old chunks ineligible for retrieval until the new generation is ready.

Storage

  • rag_article stores metadata, private storage key, status, generation, model identity and a sanitized failure code.
  • rag_article_chunk stores text, zero-based chunk index, optional source location and vector(384). It has a unique article/chunk key, cascading article foreign key and HNSW cosine index.
  • message.sources is a nullable JSONB citation snapshot. Existing messages retain their original response shape.
  • Source URLs are stored as metadata. The backend never fetches them.

TypeORM uses its native vector column type and synchronization stays off. The migration installs the vector extension and creates the index explicitly. A rollback of the RAG schema discards indexed article metadata and citations. It leaves the shared vector extension and private files in place. Prefer disabling the flag and reverting the app release when troubleshooting a rollout.

Local development

Use Node 22.13 or newer in the 22.x line, PostgreSQL 17 with pgvector 0.8 or newer, Redis and Python 3.12. Prepare the existing development environment using .env.example as a reference. The existing database, Redis and OpenRouter variables still apply.

From the repository root:

npm ci
npm run migration:run:dev
npm run start:dev

Run the embedding service in a dedicated Python virtual environment:

cd embedding-service
python -m venv .venv
# Activate the venv using your shell's activation script.
python -m pip install torch==2.9.1 --index-url https://download.pytorch.org/whl/cpu
python -m pip install -r requirements.txt
python -m uvicorn main:app --host 127.0.0.1 --port 8080 --no-access-log

The first startup downloads the pinned Hugging Face snapshot. HF_HOME controls the cache directory. Compose mounts a persistent cache at /cache. Prewarm that cache before restricting egress. Set HF_HUB_OFFLINE=1 in the embedding runtime once the exact snapshot is cached if the deployment must operate offline. The runtime loads model weights once, on CPU, using safetensors. GET /health checks readiness and GET /model reports the model identity, token limit, dimensions and device. The service accepts at most 32 inputs per request and validates the token limit before encoding. E5 model card

Configuration

Variable Default and behavior
RAG_ENABLED false. Enables article routes, ingestion and grounded chatbot answers
RAG_EMBEDDING_URL http://localhost:8080. Compose uses http://embedding:8080
RAG_EMBEDDING_MODEL, RAG_EMBEDDING_REVISION The model repository and pinned 40-character revision in .env.example. Both runtimes must agree
RAG_EMBEDDING_TIMEOUT_MS, RAG_BATCH_SIZE 30,000 ms and 8 texts. The latter accepts up to 32
RAG_CHUNK_SIZE, RAG_CHUNK_OVERLAP 440 and 88 E5 tokens. E5 supports up to 512 including prefix and special tokens
RAG_TOP_K, RAG_SIMILARITY_THRESHOLD 5 and 0.78. Calibrate the threshold on representative Persian questions
RAG_CONTEXT_BYTES, RAG_PROMPT_BYTES 10,000 and 14,000 UTF-8 bytes. Includes a conservative budget for prompt, references and recent history. Set the prompt budget below the selected model's input window after reserving 768 output tokens and provider formatting overhead
OPENROUTER_MODEL Existing required model ID. Use a model that follows the grounded JSON answer instructions and supports the configured context budget
RAG_INGESTION_CONCURRENCY 1 worker job per app replica, configurable up to 4
RAG_UPLOAD_MAX_BYTES, RAG_UPLOAD_MIME_TYPES 10 MiB and PDF, DOCX, TXT. The multipart parser has a 20 MiB hard ceiling
RAG_STORAGE_DIR ./private-articles. Compose mounts the private volume at /var/lib/heala/articles

Article and chat APIs

Use an access token for a user with the existing admin or superuser role.

curl -f -H "Authorization: Bearer $ADMIN_ACCESS_TOKEN" \
  -F "title=Patient education article" \
  -F "file=@article.pdf;type=application/pdf" \
  "$API_BASE/v1/articles"
curl -f -H "Authorization: Bearer $ADMIN_ACCESS_TOKEN" \
  "$API_BASE/v1/articles/$ARTICLE_ID"

Upload returns HTTP 202 and the existing success/data envelope. An optional sourceUrl field accepts HTTP or HTTPS. Ingestion status progresses through pending, processing, and ready or failed. Use GET /v1/articles?page=1&limit=20 to enumerate articles. PUT /v1/articles/:id accepts the same multipart fields and replaces the original file. It returns 409 during active ingestion. POST /v1/articles/:id/reprocess queues the stored file and returns the active status if ingestion is already underway.

Ordinary authenticated users keep using the current chatbot request, with message and optional conversationId. When RAG is enabled, the response adds data.sources with cited IDs such as S1, article ID, chunk ID, title, filename, source URL, similarity and page or section when indexed. The SSE route uses the existing event envelope and emits one validated answer event with its citations. The conversation-details route returns saved citation snapshots. Query rewriting is omitted, so users should restate the topic on ambiguous follow-ups.

The app bounds extraction to 400 PDF pages, 500,000 characters and 4,000 indexed chunks per article. Document parsing does not run OCR. PDF page numbers are available for extractable text. Styled DOCX headings are retained as sections. DOCX page numbers require document rendering. Verify representative right-to-left PDFs before loading a full corpus.

Production rollout

  1. Take a PostgreSQL backup and verify restore, existing volume identity and PostgreSQL major 17. Check that the migration role can install pgvector or ask a database administrator to provision the extension first. The Compose image preserves major 17 and the existing data mount. pgvector installation and image tags
  2. Set the production environment values with your deployment secret store. Inside Compose use DATABASE_HOST=postgres and REDIS_HOST=redis, align REDIS_PASSWORD across app and Redis, and provide the existing production OpenRouter proxy settings. Keep RAG disabled for the initial migration. Compose's env file path defaults to .env.production and can be set with APP_ENV_FILE. Preserve your Compose project name so the existing database volume is reused.
  3. Build the app and prepare the services. PostgreSQL, Redis and the embedding service use internal container networking with no host ports. Only the existing app port is published.
docker compose --env-file .env.production --profile rag config --quiet
docker compose --env-file .env.production --profile rag build app embedding
docker compose --env-file .env.production --profile rag up -d --wait postgres redis embedding
docker compose --env-file .env.production run --rm --no-deps app \
  node node_modules/typeorm/cli.js -d dist/database/data-source.js migration:run
docker compose --env-file .env.production --profile rag up -d app
  1. Enable RAG_ENABLED=true in the deployment environment and recreate the app. Upload a small approved article. Poll until ready, ask a question it supports and check the cited excerpt against the original. Ask an unrelated question to verify the fallback. Test an urgent symptom and a personalized dosage request. Review backup, restore and volume permissions. Multiple app replicas need shared private storage and should use the same embedding model and Redis queue.

The feature sends selected excerpts and bounded conversation text to the configured OpenRouter provider. Use publications approved for that processing. Citation validation checks IDs and format. Factual attribution and clinical behavior still need evaluation against your corpus before rollout.

Model replacement

Choose a compatible 384-dimensional model with a fast tokenizer and E5-style query: and passage: prefixes. Set model and revision in both runtimes, redeploy and verify /model from the app network. Enumerate articles and call POST /v1/articles/:id/reprocess for each, then wait for ready status. Queries ignore vectors from older revisions. A change of dimension or embedding protocol requires a schema or provider change. If using a rolling deployment, coordinate the cutover so ingestion workers do not process with different model identities.

Verification and troubleshooting

npm test -- --runInBand
npm run test:e2e -- --runInBand
npx tsc --noEmit --incremental false
npm run build
npx eslint "src/**/*.ts" "test/**/*.ts"

Set PGVECTOR_TEST_URL to a disposable PostgreSQL instance with pgvector and run npm test -- --runInBand pgvector.spec. This test uses a temporary schema inside a rolled-back transaction. It never needs an OpenRouter key. For the Python API tests, install -r requirements.txt, httpx and pytest in the Python environment and run python -m pytest -q embedding-service from the repository root. Those tests use a fake CPU model.

Set RAG_REAL_MODEL_TEST=1 and run python -m pytest -q embedding-service -k real_model to load the pinned model and check normalization, dimensions and CPU execution with Persian and English input.

  • Pending for an extended period. Check the NestJS worker log, Redis health, password, queue and model readiness.
  • pdf_no_text_ocr_required. Upload a text-exported PDF, DOCX or UTF-8 TXT version.
  • ingestion_dependency_failure. Check model identity, timeouts, disk and database permissions, then reprocess.
  • No sources available. Confirm the article is ready and indexed with the active model revision. Test the configured threshold on the corpus.
  • Storage failure. Check the private mount across app replicas and compare its objects with rag_article.storageKey. A process failure between storing a file and committing metadata can leave an unreferenced file. Review such files offline before cleanup.