Tag: RAG

  • Self-Hosted RAG: A Reference Architecture for Private, Secure AI

    Self-Hosted RAG: A Reference Architecture for Private, Secure AI

    “Self-hosted RAG” gets said a lot and specified rarely. If you are responsible for standing up an AI knowledge system inside your own perimeter — for reasons of data residency, compliance, or simple sovereignty — you need more than a diagram with an arrow labelled “magic.” This is a reference architecture for a private, secure retrieval-augmented generation platform, drawn from how Swifbit is built.

    We will walk the whole stack: connectors, the ingestion pipeline, storage, retrieval, the model layer, and the security model that has to wrap all of it. Wherever there is a decision to make, we will name the trade-off.

    Design goals

    Before components, principles. A credible self-hosted RAG platform should satisfy five goals at once:

    • Data stays put. Documents, embeddings, and prompts never leave the customer’s environment.
    • Model independence. The same platform runs on a local model or a hosted endpoint, swappable without a rewrite.
    • Permission-aware retrieval. Access control is enforced during search, not painted on afterwards.
    • Operability. Sync health, failures, and quality signals are observable by the people who run it.
    • Portability. It deploys on any VM or container platform, without a proprietary cloud dependency.

    The high-level shape

    At the coarsest level, the system is four planes: a connector plane that pulls documents in, an ingestion plane that turns them into searchable vectors, a retrieval and generation plane that answers questions, and a control plane for identity, permissions, and audit. Keeping these separated is what lets each scale and fail independently.

    Connectors ─▶ Ingestion ─▶ Vector store ─▶ Retrieval ─▶ Model
         (isolated)   (chunk +      (pgvector)     (permission   (local or
                       embed)                        filtered)     hosted)
            └──────────────── Control plane: authn, RBAC, audit ───────────┘

    The connector plane

    Connectors are where most of the operational risk lives, because they hold credentials to other systems. The key architectural choice is isolation: each connector should run in its own process with its own scoped credentials, so a bug or a compromised integration cannot reach the rest of the platform or the other connectors’ secrets.

    Connectors should also be incremental. Re-indexing an entire wiki every sync is wasteful and slow; a good connector tracks modification timestamps or change cursors and only processes what moved. Every sync should record what it did — documents added, updated, skipped, and any errors — so operators can see health at a glance.

    Credential handling

    Store connector credentials encrypted at rest with authenticated encryption, decrypt them only in the connector process that needs them, and never return them to any client. In Swifbit, secrets are masked in every API response by default — the UI shows that a credential exists without ever shipping it back to the browser.

    The ingestion plane

    Ingestion is a pipeline: normalise, chunk, embed, index. Each stage has a decision worth making deliberately.

    Chunking strategy

    Chunk on semantic boundaries — headings, paragraphs, list items — rather than blindly every N characters, and keep a small overlap so a passage that straddles a boundary is not lost. Attach metadata to every chunk: source document, section, timestamps, and the access scope it inherits. That metadata is what makes permission-aware retrieval and precise citations possible downstream.

    Embeddings

    The embedding model is a swappable dependency, and it should be treated as one. Record which model and version produced each vector, because changing embedding models means re-indexing — mixing vector spaces silently degrades retrieval. For a fully private deployment, run the embedding model locally; for higher throughput you can point at a hosted embedding endpoint you control.

    Storage: why pgvector

    You can bolt on a dedicated vector database, but for most self-hosted deployments a single PostgreSQL instance with the pgvector extension is the pragmatic choice. It keeps your documents, metadata, and vectors in one transactional store you already know how to back up, secure, and operate — no second system to run, and no eventual-consistency gaps between your metadata and your index.

    ConcernDedicated vector DBPostgreSQL + pgvector
    Operational surfaceExtra system to runOne database you already know
    Transactional metadataSeparate store, sync riskSame transaction as vectors
    Backup / DRBespokeStandard Postgres tooling
    Scale ceilingVery highHigh — ample for most orgs

    Retrieval and generation

    Retrieval takes the embedded query, runs a nearest-neighbour search, and — before anything else — filters candidates against the requesting user’s permissions. Only the surviving chunks are assembled into the prompt. This ordering matters: filtering after generation risks leaking restricted content into an answer even if you strip the citation.

    Generation then runs under explicit constraints — answer only from context, cite sources, mark unverified facts. The output carries citations and a confidence signal derived from match strength. If retrieval returns nothing above a threshold, the honest response is “I don’t have that,” not a fabrication.

    The model layer

    Model independence is a first-class requirement, not a nice-to-have. The platform should talk to the model through a thin, uniform interface so that the same deployment can run against:

    • a fully local model via Ollama, for maximum privacy and zero egress;
    • an OpenAI-compatible endpoint hosted inside your own network;
    • a managed endpoint such as Vertex AI when you have a contractual data boundary you trust.

    Because the interface is uniform, switching providers is a configuration change, not a migration. That protects you from vendor lock-in and lets you match the model to the sensitivity of the workload.

    The control plane: security and observability

    Everything above is wrapped by identity, role-based access control, and an audit trail. Authentication gates the system; RBAC decides who can administer what; team-scoped source access decides whose knowledge each person can retrieve. The audit trail records questions, drafts, syncs, edits, and configuration changes — the raw material for accountability and compliance evidence.

    A retrieval system without a permission model is a data-leak generator with excellent UX. Build the access model first.

    Deployment

    The whole stack should run from containers on any VM or orchestrator, with configuration through environment variables and secrets injected by your platform. A typical footprint is the application, a PostgreSQL instance with pgvector, and a model runtime — all inside one network boundary you control.

    # minimal self-hosted footprint
    services:
      app:        # retrieval, generation, control plane
      postgres:   # documents + metadata + pgvector index
      ollama:     # optional local model runtime

    Hybrid search: why vectors alone are not enough

    Pure vector search is excellent at meaning and poor at specifics. Ask for an exact error code, a SKU, or a person’s name and semantic similarity can drift right past the literal match. The fix is hybrid retrieval: run a keyword (lexical) search alongside the vector search and fuse the results, so you get both conceptual recall and exact-match precision.

    A common fusion approach is reciprocal rank fusion, which blends the two ranked lists without needing the scores to be on the same scale. The practical upshot: “how do I reset my password” still finds the right article, and “error E-4021” still finds the exact page that mentions it.

    Failure modes, and how to design against them

    A RAG system does not usually fail with an exception; it fails quietly, by returning a plausible answer built on the wrong context. These are the failure modes worth engineering against from day one.

    Stale index

    A document changes but its vectors do not, so retrieval serves yesterday’s truth. Defend against it with incremental sync tied to change cursors, and surface last-synced timestamps so operators can see freshness at a glance.

    Embedding drift

    Someone swaps the embedding model without re-indexing, and new queries are compared against vectors from a different space. Retrieval quality silently craters. Defend against it by stamping every vector with its model and version, and refusing to mix spaces.

    Context overflow

    Too many chunks are stuffed into the prompt, the important passage falls into the model’s “lost in the middle” blind spot, and the answer ignores it. Defend against it by ranking hard, capping the context budget, and preferring a few high-relevance chunks over many mediocre ones.

    Permission leakage

    The single most dangerous failure. A restricted document slips into context and its content — or even just its citation — reaches someone who should not see it. Defend against it by filtering at retrieval time, testing with restricted-user fixtures, and treating any leak as a release blocker.

    Evaluation and monitoring

    You cannot improve what you cannot measure, and “it feels good” is not a metric. Stand up a small evaluation harness before you scale usage.

    • A golden question set. Twenty to fifty real questions with known-correct source documents. Re-run it on every change to catch retrieval regressions.
    • Retrieval metrics. Track whether the correct source appears in the top-k results (recall@k) and how highly it ranks.
    • Groundedness checks. Sample answers and confirm every claim traces to a cited passage.
    • Operational signals. Watch low-confidence rates, negative feedback, sync failures, and stale sources — each is a maintenance to-do in disguise.

    In Swifbit these signals are first-class: low-confidence answers, thumbs-down feedback, failed syncs, and ageing sources roll up into an admin view, so improving coverage becomes a routine operational loop rather than a research project.

    Scaling considerations

    Most organisations never approach the ceiling of this architecture, but it is worth knowing where the pressure points are. Embedding throughput at ingestion is usually the first bottleneck — batch it and run it off the request path. The vector index in Postgres benefits from an approximate index (such as HNSW) once you pass a few hundred thousand chunks, trading a sliver of recall for a large latency win. Generation is best decoupled behind a queue so a burst of questions degrades gracefully instead of timing out. None of this requires leaving your own infrastructure.

    Putting it together

    None of these pieces is exotic on its own. The engineering is in how they fit: isolated connectors, metadata-rich chunks, a single transactional store, hybrid permission-aware retrieval, a swappable model layer, and a control plane that makes the whole thing auditable. Get that composition right and you have a RAG platform you can actually put in front of regulated data.

    That is precisely the architecture Swifbit ships. If you would like the deep-dive on any single layer, read the security model or book a technical walkthrough.

  • Grounded AI: Building Answers Your Team Can Actually Trust

    Grounded AI: Building Answers Your Team Can Actually Trust

    Ask a generic AI assistant a question about your own company and you will often get a fluent, confident, and completely wrong answer. The model has no access to your policies, your product, or your customers — so it fills the gap with plausible-sounding invention. For a consumer toy, that is a curiosity. For a bank, a hospital, or a support desk, it is a liability.

    This is the core problem grounded AI solves. Instead of answering from a model’s parametric memory, a grounded system retrieves the relevant passages from your approved knowledge, hands them to the model as context, and constrains the response to what those passages actually say — with citations you can click. This article explains what grounding is, why it matters, and how Swifbit implements it end to end.

    Why fluent is not the same as correct

    Large language models are trained to predict the next token. That objective produces remarkable fluency, but fluency is orthogonal to truth. A model will happily complete “our refund window is” with “30 days” because that is a statistically common phrase — even if your actual policy is 14 days. The output looks authoritative precisely because the model was optimised to sound authoritative.

    The failure mode has a name — hallucination — and it is not a bug you can prompt your way out of. It is a direct consequence of asking a model to answer from memory it does not have. The fix is architectural: stop asking the model to remember, and start giving it the source material to reason over.

    Grounding flips the question from “what does the model think?” to “what do our documents say?” The model becomes a reader and a writer, not an oracle.

    What grounding actually means

    A grounded answer has three properties that an ungrounded one does not. Together they turn a black box into something you can trust and audit.

    1. Provenance. Every claim maps back to a specific source document, and the reader can open that source to verify it.
    2. Boundedness. The system answers from retrieved context only. If the knowledge is not there, it says so instead of guessing.
    3. Confidence. The system signals how well-supported an answer is, so a weak match is visible rather than disguised as certainty.

    These properties are what separate a knowledge platform from a chatbot. A chatbot optimises for a satisfying reply. A grounded platform optimises for a defensible one.

    The retrieval pipeline, step by step

    Under the hood, grounding is powered by retrieval-augmented generation (RAG). Here is the path a question takes through Swifbit, from keystroke to cited answer.

    1. Ingestion and chunking

    Documents arrive through connectors — helpdesks, wikis, drives, email, and file systems — and are normalised into clean text. Long documents are split into overlapping chunks small enough to embed precisely but large enough to preserve meaning. Good chunking is quietly one of the highest-leverage decisions in the whole system: split too coarsely and retrieval drags in noise; split too finely and you sever the context a passage needs to make sense.

    2. Embeddings and the vector index

    Each chunk is converted into a high-dimensional vector by an embedding model, then stored in a vector index. Semantically similar text lands near itself in that space, which is what lets the system match a question like “how do I get my money back?” to a policy titled “Refunds and returns” even though they share no keywords.

    3. Retrieval and permission-aware filtering

    When a question comes in, it is embedded with the same model and used to find the nearest chunks. Crucially, this is where access control lives: Swifbit filters candidates by the asker’s team permissions inside retrieval, so a result the user is not cleared to see never enters the context in the first place. Security that is enforced at render time is theatre; security enforced at retrieval time is real.

    4. Generation under constraint

    The retrieved passages are assembled into a prompt with explicit instructions: answer only from this context, cite the sources, and flag anything unverified. The model writes the answer, attaches numbered citations, and the system computes a confidence signal from the strength of the underlying matches.

    Question  ──▶  embed  ──▶  vector search (permission-filtered)
                                      │
                                      ▼
                top-k chunks ──▶  prompt assembly ──▶  LLM
                                                        │
                                                        ▼
                                       grounded answer + citations + confidence

    Citations and confidence are product features, not footnotes

    Most teams treat citations as a nicety. They are actually the mechanism that makes AI adoption safe. When every sentence can be traced to a source, three things happen: reviewers can verify in seconds, subject-matter experts can spot a stale document, and end users learn to trust the tool because it shows its work.

    Confidence scoring does the opposite job — it makes absence of knowledge visible. A low-confidence answer is a signal, not a failure. It tells an administrator exactly where coverage is thin, which turns your knowledge base into a system that improves itself over time as gaps surface and get filled.

    PropertyGeneric assistantGrounded platform
    Source of answerModel memoryYour approved documents
    VerifiabilityNoneClick-through citations
    Unknown questionsInvents an answerSays it does not know
    Access controlN/AEnforced in retrieval
    Improves over timeOn vendor retrainAs you close gaps

    Grounding does not have to cost you control

    A common objection is that all of this requires shipping your knowledge to a third-party AI cloud. It does not. Swifbit runs entirely inside your own infrastructure and is model-agnostic: point it at a fully local model through Ollama, or at an OpenAI-compatible or Vertex AI endpoint you control. Your documents, embeddings, and prompts never leave your perimeter unless you decide they should.

    That combination — grounded answers plus self-hosting — is what makes the approach viable for regulated industries. You get the productivity of modern AI without handing your crown-jewel knowledge to someone else’s data centre.

    A worked example: the refund question

    Abstractions are easy to nod along to, so make it concrete. A customer writes in: “I cancelled last week — can I get a refund for the rest of my year?” Watch how the two approaches diverge.

    The ungrounded assistant pattern-matches to the millions of refund policies in its training data and produces something like: “Yes, you are eligible for a full refund within 30 days of purchase.” Confident, friendly, and — for your business — potentially wrong. If your real policy is a 14-day pro-rata window, you have just created a support escalation and a broken promise.

    The grounded system does something different. It retrieves your actual billing policy and the customer’s contract, then answers: “Annual plans are refundable pro-rata within 14 days of the invoice date; after that, remaining months convert to account credit,” with a citation pointing at the exact policy clause. If the customer’s specific contract cannot be found, it says so and leaves a placeholder rather than guessing the date. One of these systems you can put in front of a customer; the other you cannot.

    Common objections, answered

    “Doesn’t the model already know this?”

    It knows the shape of the answer, not the substance of yours. A model trained on the public internet has never read your pricing page, your runbooks, or last Tuesday’s policy change. Grounding is how you supply the substance it lacks — and how you keep the answer current without retraining anything.

    “Isn’t retrieval slower than just asking the model?”

    Retrieval adds tens of milliseconds — imperceptible next to model generation time, and a rounding error next to the minutes a human would spend searching for the same source. You are not trading speed for safety; you are getting both.

    “What happens when our knowledge is wrong or out of date?”

    Then the answer is wrong in a traceable way — you can see exactly which document produced it and fix that document, and every future answer improves at once. Compare that to an ungrounded model, where a wrong answer has no source to correct. Grounding turns quality into something you can manage instead of something you hope for.

    How to evaluate a grounded system

    If you are assessing platforms, the marketing will all sound identical. These are the questions that actually separate them:

    • Can it say “I don’t know”? Ask something deliberately absent from the knowledge base. A trustworthy system declines; a chatbot invents.
    • Are citations precise? Do they point to the specific passage, or vaguely to a whole document? Precision is what makes verification fast.
    • Is access control enforced in retrieval? Ask as a restricted user for something they should not see. It must never appear — not even in a citation.
    • Does it surface confidence? Weak matches should look weak, so reviewers know when to slow down.
    • Where does the data live? If the answer is “our cloud,” your knowledge and your compliance posture are no longer yours.

    The takeaway

    Fluency is cheap; trust is expensive. The teams winning with AI are not the ones with the flashiest chatbot — they are the ones whose answers can be traced, verified, and defended. Grounding is how you get there, and it is the principle every part of Swifbit is built around.

    If you want to see grounded answers on your own knowledge, request a demo and we will walk you through it.