Search Tutorials
--Ads--Serving RAG as an API with FastAPI
Wrap your pipeline in a typed, streaming HTTP API.
Up to now, our RAG pipelines have been Python scripts. To serve a web app, a chat widget or other services, the pipeline needs an HTTP API. This lesson wraps it in FastAPI: typed requests and responses, the index loaded once at startup, a streaming endpoint with Server-Sent Events, and the production concerns around it.
The service
pip install fastapi uvicorn anthropic
app.py
import json
from contextlib import asynccontextmanager
from pathlib import Path
import anthropic
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from retriever import DenseRetriever # from the top-k search lesson
MODEL = "claude-opus-5-5"
SYSTEM = ("You are the Zentrix Labs policy assistant. Answer using only the sources, cite source "
"ids like [1], and say so if the sources do not contain the answer.")
state: dict = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
# Load heavy resources ONCE at startup, not per request
records = json.loads(Path("index/chunks.json").read_text(encoding="utf-8"))
state["retriever"] = DenseRetriever(records)
state["llm"] = anthropic.AsyncAnthropic()
yield
await state["llm"].close()
app = FastAPI(title="RAG API", lifespan=lifespan)
class AskRequest(BaseModel):
question: str = Field(min_length=2, max_length=2000)
k: int = Field(default=4, ge=1, le=10)
class Source(BaseModel):
id: int
chunk_id: str
text: str
class AskResponse(BaseModel):
answer: str
sources: list[Source]
input_tokens: int
output_tokens: int
def build_prompt(question: str, k: int) -> tuple[str, list[Source]]:
hits = state["retriever"].search(question, k=k)
sources = [Source(id=i, chunk_id=h.id, text=h.text) for i, h in enumerate(hits, start=1)]
context = "\n".join(f'<source id="{s.id}">\n{s.text}\n</source>' for s in sources)
return f"<sources>\n{context}\n</sources>\n\nQuestion: {question}", sources
@app.get("/health")
async def health():
return {"status": "ok"}
@app.post("/ask", response_model=AskResponse)
async def ask(req: AskRequest):
prompt, sources = build_prompt(req.question, req.k)
try:
msg = await state["llm"].messages.create(
model=MODEL, max_tokens=2000, output_config={"effort": "low"},
system=[{"type": "text", "text": SYSTEM, "cache_control": {"type": "ephemeral"}}],
messages=[{"role": "user", "content": prompt}])
except anthropic.RateLimitError:
raise HTTPException(status_code=429, detail="Busy, please retry shortly.")
except anthropic.APIError:
raise HTTPException(status_code=502, detail="The language model is unavailable.")
answer = "".join(b.text for b in msg.content if b.type == "text")
return AskResponse(answer=answer, sources=sources,
input_tokens=msg.usage.input_tokens, output_tokens=msg.usage.output_tokens)
@app.post("/ask/stream")
async def ask_stream(req: AskRequest):
prompt, sources = build_prompt(req.question, req.k)
async def events():
yield f"data: {json.dumps({'type': 'sources', 'sources': [s.model_dump() for s in sources]})}\n\n"
try:
async with state["llm"].messages.stream(
model=MODEL, max_tokens=2000, output_config={"effort": "low"},
system=SYSTEM, messages=[{"role": "user", "content": prompt}]) as stream:
async for text in stream.text_stream:
yield f"data: {json.dumps({'type': 'token', 'text': text})}\n\n"
final = await stream.get_final_message()
yield f"data: {json.dumps({'type': 'done', 'stop_reason': final.stop_reason})}\n\n"
except anthropic.APIError:
yield f"data: {json.dumps({'type': 'error', 'message': 'Generation failed'})}\n\n"
return StreamingResponse(events(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
Run and call it
uvicorn app:app --host 0.0.0.0 --port 8000
curl -X POST http://localhost:8000/ask -H "Content-Type: application/json" -d "{\"question\": \"How many sick days do I get?\"}"
FastAPI also generates interactive documentation at http://localhost:8000/docs.
Reading the stream in a browser
const res = await fetch("/ask/stream", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({question: "Can I work from home on Fridays?"}),
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const {value, done} = await reader.read();
if (done) break;
buffer += decoder.decode(value, {stream: true});
const events = buffer.split("\n\n");
buffer = events.pop(); // keep any incomplete event
for (const e of events) {
const data = JSON.parse(e.replace(/^data: /, ""));
if (data.type === "token") answerEl.textContent += data.text;
if (data.type === "sources") renderSources(data.sources);
}
}
Production checklist
- Authentication: require a token or session on every endpoint, and pass the user's identity to retrieval for permission filtering (Access Control).
- Rate limiting per user, to protect your LLM budget.
- Timeouts on retrieval and generation, with friendly errors.
- Blocking work: local embedding and reranking are CPU-bound. In an async app, run them in a thread pool (
await asyncio.to_thread(...)) or a separate service, so they do not block other requests. - Several workers (
uvicorn --workers 4or multiple containers), each loading the index; large indexes belong in a vector database server rather than in each process's memory. - Logging and tracing of every request (Observability).
Key takeaways
- Load indexes and clients once at startup with FastAPI's lifespan handler.
- Use typed request and response models with validation limits.
- Offer a streaming endpoint with Server-Sent Events: sources, tokens, then a done event.
- Add authentication, rate limits, timeouts and tracing before going live.