AI Hints
Home›RAG Tutorial›Serving RAG
RAG · Lesson 101 of 120

Serving RAG

FastAPI.

⏱ 2 min read▶ Video at 1:39:22🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Our RAG system runs in a script. To use it from a website or an app, we serve it as a web API. FastAPI makes that easy, and the index is built once, when the server starts.

Serving RAG
From the video: Serving RAG
  • Script to service
  • Web API
  • Build index once

An ask endpoint

Question is the request body. The ask endpoint searches, answers, and returns the answer with its sources. The test client calls the API, just like a browser would. Run it. We get a JSON reply, with the sources.

api.pypython
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
from rag_kit import load_docs, make_chunks, Index
from llm import answer

app = FastAPI()
index = Index(make_chunks(load_docs()))

class Question(BaseModel):
    text: str

@app.post("/ask")
def ask(q: Question):
    chunks = [c for s, c in index.search(q.text)]
    return {"sources": sorted({c["source"] for c in chunks}), "answer": answer(q.text, chunks)}

reply = TestClient(app).post("/ask", json={"text": "When is the York shop open?"})
print(reply.status_code, reply.json()["sources"])
Output
200 ['servicing.md', 'stores.md']
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses llm.py
from langchain.chat_models import init_chat_model

llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".

Context:
{context}

Question: {question}"""

def answer(question, chunks):
    context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
    return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()

Serving tips

Build the index at start up, not per request. Run it with uvicorn. Add a timeout to model calls. And return sources with every answer, so the website can show links.

keyvalue
Indexbuilt at start-up
Run withuvicorn
Model callswith a timeout
Returnanswer + sources

Summary

FastAPI serves RAG over HTTP, with the index built once at start up. Next, streaming over HTTP.

Key takeaways
  • POST /ask
  • Answer + sources
  • Built once
Next up: Streaming over HTTP — text as it arrives