Skip to content

Architecture

PantheraNestah edited this page Nov 5, 2026 · 2 revisions

Architecture

Overview

flowchart LR
  C[Client / robot] -->|POST /query, /learn/*| API[FastAPI routes]
  API --> P[RAGPipeline]
  P --> R[Retriever: Chroma + BM25 -> RRF -> cross-encoder]
  P --> G[Generator -> llm.complete tier]
  G --> L[(Anthropic / DeepSeek / OpenAI)]
  API -. background task .-> V[NLI verifier] --> D[(SQLite log)]
Loading
Component Module Role
Routes app/api/routes.py HTTP endpoints; schedule background logging
Pipeline app/services/pipeline.py Orchestrates preprocess, retrieve, generate
Retriever app/services/retriever.py Hybrid retrieval (Retrieval Pipeline)
Generator app/services/generator.py Prompts and output handling (Prompts and Lessons)
LLM layer app/services/llm.py Provider-agnostic completion by tier (LLM Layer)
Verifier app/core/verifier.py Grounding check (Grounding Verification)
Logger app/services/interaction_logger.py Verification then database write (Data and Logging)
Warm-up app/services/warmup.py Startup model preload

Original design concept

The project began from this earlier design sketch. It is kept for context and does not match the current implementation.

Original NutriPepper RAG design: input filtering, query embedding, ChromaDB retrieval, prompt contextualisation, LLM, claim verification, response reconstruction, output filtering

What changed since the sketch:

In the sketch In the current code
Input filtering No filtering stage. The query is trimmed and lower-cased, and a small-talk shortcut skips retrieval (API Reference)
Semantic search plus a metadata-filtered result Semantic search and BM25 keyword search, fused with Reciprocal Rank Fusion, then a cross-encoder re-ranker. No metadata filtering (Retrieval Pipeline)
OpenAI gpt-3.5-turbo / gpt-4-turbo Tiered, configurable models from Anthropic, DeepSeek or OpenAI (LLM Layer)
Claim verification gates the answer Verification runs after the response is sent, in the background, and only logs a score (Grounding Verification)
Response reconstruction (keep only verified claims, add citations) Not implemented. The model cites sources itself and the answer is returned as generated
Output filtering Not implemented (Known Issues and Limitations)

What stayed: MPNet embeddings (all-mpnet-base-v2), ChromaDB as the vector store, and retrieved context placed in the prompt together with a system prompt.

Startup

The FastAPI lifespan hook does two things before the server accepts requests:

  1. init_db() creates the SQLite tables if missing.
  2. Unless PRELOAD_MODELS=false, warm_up() runs in a worker thread. It loads the vector store, BM25 index, embedding model, re-ranker and NLI model, and runs one tiny inference through each. A failure is logged and that model loads on first use instead.

Life of a /query request

  1. The route calls RAGPipeline.run_query.
  2. The query is trimmed and lower-cased. If it matches a small-talk trigger, retrieval is skipped and the easy tier answers.
  3. Otherwise retrieve() returns the top 3 chunks (in a worker thread, one at a time).
  4. generate_response() builds the prompt from the chunks and calls the medium tier (in a worker thread).
  5. Citation markers [n] in the answer are counted.
  6. The route returns the response and schedules a background task.
  7. The background task runs the NLI verification (in a worker thread, one at a time), then writes the interaction, details and retrieved chunks to SQLite.

/learn/structured and /learn/text follow the same shape without steps 2 and 5, and are logged without verification.

Concurrency model

Everything that blocks (language model calls, retrieval, verification) runs in worker threads through asyncio.to_thread, so the event loop stays free to serve other requests and finish database writes.

  • Retrieval is serialised by a lock, because it lazily initialises shared models and the BM25 index.
  • Verification is serialised by a lock, for the same reason and because it is CPU-heavy.
  • SQLite runs in WAL mode with a 30 second busy timeout, so concurrent background writers wait for each other instead of failing.

This design came from a real bug: blocking work on the event loop froze it for tens of seconds, a write transaction in another task could not finish, and the next writer failed with database is locked. The regression tests are in tests/test_concurrency.py (Testing).

Design choices

  • Hand-written pipeline, no orchestration framework. The flow is short and explicit, which keeps it easy to inspect and test.
  • Lazy singletons plus startup preload. Models load once per process.
  • Verification after the response. Slow NLI scoring never delays the user.
  • Tiers instead of model names in code. Callers say how demanding a task is; configuration says which model serves it (LLM Layer).

Not in scope

Authentication, rate limiting, streaming responses, the robot (NAOqi) bridge and a dedicated safety classifier are not implemented (Known Issues and Limitations).

Clone this wiki locally