A document-grounded question-answering system. Users upload PDFs, ask questions, and get answers sourced from their own documents — produced by a self-correcting LangGraph pipeline that cites its sources, gates each answer through a self-consistency faithfulness check and abstains instead of hallucinating, then runs a second model from a different provider as an independent, after-the-fact cross-check.
Live demo: agentic-research-engine.vercel.app · runs on all-free, no-card infrastructure (demo credentials available on request).
- Cross-provider cross-check — Claude answers and gates itself inline (k=3 self-consistency vote); an independent OpenAI model (GPT-5 nano) re-runs the same faithfulness check afterward as a second opinion that surfaces disagreement. It's advisory, not a gate — but it isn't one model grading itself.
- Self-correction — when retrieved context is insufficient, the graph rewrites its own query and retries, then abstains rather than guess.
- Measured retrieval — the retriever was chosen from data: BM25 and a cross-encoder reranker were benchmarked head-to-head against dense vector, and dense won — so rerank ships disabled (see below).
- Security & multi-tenancy — AES-256-GCM encryption at rest, JWT-derived tenant isolation, a found-and-fixed BOLA/IDOR flaw on Redis traces, and shared-secret internal routes.
- MCP Server Integration — natively exposes an authenticated Model Context Protocol (MCP) server, allowing local IDEs (Cursor, Claude Desktop) to query the cloud vector store.
The browser only ever talks to Next.js, which acts as a Backend-for-Frontend: it holds the
HttpOnly auth cookies and injects the bearer token, then proxies a Server-Sent-Events stream to
Express. Express owns all state (Postgres, Redis, correlation IDs) and the retrieval logic.
FastAPI owns only the reasoning graph — and calls back into Express (EXPRESS_URL) for
anything stateful. Inference is hosted: Claude Haiku drives the pipeline and the inline critic;
OpenAI serves the independent verifier (GPT-5 nano) and the embeddings (text-embedding-3-small).
The distinctive part is the retrieval callback: the Python graph's retriever node posts to
Express /api/internal/retrieve, which runs the dense pgvector search (with OpenAI embeddings)
and — when enabled — the cross-encoder rerank, then returns ranked chunks to the graph.
| Service | Stack | Responsibility |
|---|---|---|
frontend/ |
Next.js 16, React 19, TypeScript, Tailwind | Chat UI, live SSE trace panel, API key management |
backend/ |
Node.js, Express 5 | Orchestration, auth, API keys, retrieval, state, rate limiting |
ai-service/ |
Python, FastAPI, LangGraph | The self-correcting reasoning graph + cross-encoder /rerank |
mcp-server/ |
TypeScript, MCP SDK | Official Model Context Protocol server for IDE/agent integration |
infra/ |
Docker Compose, SQL migrations | Postgres (pgvector) + Redis |
Every completed graph node streams an SSE progress event, so the UI shows the reasoning live.
flowchart TD
A([question]) --> IR[intent router]
IR -- not information-seeking --> X[abstain]
IR -- information-seeking --> CC[cache check]
CC -- hit --> CF[cache formatter] --> AQ
CC -- miss --> QR[query reformulator]
QR --> R[retriever]
R -->|callback to Express: pgvector + optional rerank| PG{parity gate}
PG -- cache parity --> CF
PG -- fresh --> V[validator]
V -- insufficient --> RW[rewrite query]
RW --> R
V -- sufficient --> SY[synthesizer]
SY --> AQ[answers_question / relevance]
AQ -- not grounded --> X
AQ -- grounded --> CR[critic · k=3 vote]
CR -- unfaithful --> X
CR -- faithful --> CW[cache writer] --> D([stream answer])
D -. background .-> SO[OpenAI second opinion → Redis]
- Next.js refreshes/injects the bearer token and proxies to Express (
fetchrather thanEventSource, so HTTP 401/403 surface as real states, not a generic stream error). - Express authenticates, applies the rate limiter, and streams the request to FastAPI.
- FastAPI drives the graph above, emitting one SSE event per node.
- A cache hit skips synthesis/critic — but only after retrieval runs (never skipped).
- After the answer streams, GPT-5 nano re-runs the faithfulness check as a background task; the
UI polls
/api/trace/:idand flips an Agreed / Disagreed badge — cross-provider agreement.
Retrieval strategy was chosen from data, not vibes — and the data changed the answer once the benchmark got serious.
- BM25 (lexical) was reimplemented as an in-app Okapi index (
bm25Service.js, benchmark-only — the original Postgres full-text path returns zero rows once encryption-at-rest generates itstsvectorover ciphertext, so it's kept as a documented dead path). - Dense vector (pgvector) and a cross-encoder reranker were scored against it head-to-head
via
backend/eval/runEval.js.
The first pass used only 12 questions from one paper. Expanding the golden set to 52 questions across two documents (Attention Is All You Need + RFC 6749, OAuth 2.0) reversed the earlier read: at n=12 the cross-encoder edged ahead on ranking; at n=52 dense vector leads on all three metrics.
| Config | Hit@5 | MRR | nDCG |
|---|---|---|---|
| Pure vector (dense, pgvector) — chosen | 0.96 | 0.83 | 0.85 |
| Cross-encoder rerank | 0.85 | 0.69 | 0.73 |
| BM25 (lexical) | 0.83 | 0.64 | 0.69 |
n = 52, top-5, stratified (factual / multi-hop / entity / negation) across both docs. Relevance is keyword-in-retrieved-chunk; the 2 questions that miss on all three retrievers (strict multi-keyword matches on split PDF tables) are kept, not tuned away.
Why dense wins here: the set is rich in factual, keyword-findable questions. Dense retrieval already surfaces those; the cross-encoder reorders by semantic relevance and sometimes demotes the exact-answer chunk, so it loses ground on lexical questions. Reranking earns its cost on paraphrased/semantic queries — a minority of this workload.
That is why the production retriever is dense-only (ENABLE_RERANK=false): the cross-encoder is
implemented and benchmarked, it just doesn't beat dense on this workload — so disabling it is the
principled default, not merely a CPU-budget compromise.
Honest note: the earlier n=12 numbers were a directional signal, not a calibrated benchmark; expanding the set is what surfaced the reversal. See ADR-003.
- Self-correction — retries up to 3×; each retry rewrites the query first.
- Cross-provider critic — Claude gates inline (k=3 self-consistency vote, threshold 0.6); GPT-5 nano re-runs the identical faithfulness prompt asynchronously as an independent second opinion.
- Prompt-injection defense — untrusted document content is fenced in explicit delimiters and aggressively sanitized to strip malicious escape tags (
<<<UNTRUSTED_DOCUMENT_END>>>) before reaching the LLM context. - Sentence-Aware Chunking — uses Langchain's
RecursiveCharacterTextSplitterto ensure chunks break cleanly at semantic sentence boundaries rather than splitting mid-word. - Graceful degradation by dependency type (ADR-001) — structural requirements fail closed (zero chunks, final safety checks); semantic heuristics fail open.
Measured on a 10-question adversarial set (false-premise / cross-domain / out-of-scope), the system
correctly refused all 10 — nothing fabricated. Harness: backend/eval/runAbstainEval.js.
- Encryption at rest — chunk text is AES-256-GCM (
iv:authTag:ciphertext). - Tenant isolation —
user_idis always derived from the verified JWT, never the request body; internal server-to-server routes require a shared secret. - Rate limiting — Redis-backed, per user, atomic counter+expiry (fails closed).
A query is dominated by sequential model calls — the self-consistency critic alone was 45% of end-to-end.
Parallelising its $0.012/query** (modelled).k votes (asyncio.gather) cut that step ~3.1× (~4.6s/query), and a semantic-cache hit
short-circuits generation (~2.5× faster). Cost is **
Correlation IDs propagate across all three services (AsyncLocalStorage in Node, contextvars
in Python). Langfuse captures per-node traces, token counts, and cost.
A semantic query cache (pgvector, per user) short-circuits repeat questions.
- Docker (Postgres + Redis), Node.js 20+, Python 3.11+
- API keys:
ANTHROPIC_API_KEY(Claude) andOPENAI_API_KEY(embeddings + verifier)
git clone https://github.com/Prathamesh51-debug/Agentic-Research-Engine.git
cd Agentic-Research-Engine
docker compose up -d # Postgres (pgvector) on :5433, Redis on :6379openssl rand -hex 32 # use for ENCRYPTION_KEY (must be 32 bytes = 64 hex)
openssl rand -hex 32 # JWT_ACCESS_SECRET
openssl rand -hex 32 # JWT_REFRESH_SECRET
openssl rand -hex 24 # INTERNAL_API_KEY (must be IDENTICAL in both .env files)backend/.env — Postgres runs on 5433 (the Docker mapping); the rest match the compose defaults:
DB_PORT=5433
REDIS_URL=redis://localhost:6379
JWT_ACCESS_SECRET=<hex>
JWT_REFRESH_SECRET=<hex>
ENCRYPTION_KEY=<64 hex chars>
INTERNAL_API_KEY=<shared secret>
OPENAI_API_KEY=<key> # query embeddings (text-embedding-3-small)
# FASTAPI_URL defaults to http://127.0.0.1:8000 (set only if the AI service is elsewhere)
ai-service/.env:
INTERNAL_API_KEY=<same shared secret as backend>
ANTHROPIC_API_KEY=<key> # primary model (Claude Haiku)
OPENAI_API_KEY=<key> # independent verifier (GPT-5 nano)
# EXPRESS_URL defaults to http://localhost:3001 (set only if Express is elsewhere)
LANGFUSE_PUBLIC_KEY=<optional>
LANGFUSE_SECRET_KEY=<optional>
LANGFUSE_BASE_URL=https://us.cloud.langfuse.com
frontend/.env.local:
BACKEND_URL=http://localhost:3001
cd backend && npm install
for f in $(ls ../infra/migrations/*.sql | sort); do
node src/config/runMigration.js "$(basename "$f")"
done
cd ..# Terminal 1 — Express API (:3001)
cd backend && npm run dev
# Terminal 2 — AI service (:8000)
cd ai-service && python -m venv venv
source venv/Scripts/activate # macOS/Linux: source venv/bin/activate
pip install -r requirements.txt
python -m uvicorn main:app --port 8000
# Terminal 3 — Frontend (:3000)
cd frontend && npm install && npm run dev- Open http://localhost:3000, sign up, and sign in.
- Go to Upload, upload a PDF (e.g. a research paper), and wait for embedding to finish.
- Go to Ask and query it — you'll see the live pipeline trace, the answer with citations, and the verification badge.
| Symptom | Cause / fix |
|---|---|
Backend ECONNREFUSED to Postgres |
Postgres is on 5433, not 5432 — set DB_PORT=5433. |
| Every answer abstains | No corpus for your account — upload a PDF (step 6), or you're on an empty account. |
AI service failed with status 401/403 |
INTERNAL_API_KEY differs between the two .env files — make them identical. |
AI service unreachable |
The FastAPI service isn't up on :8000 (or FASTAPI_URL is wrong). |
| Rate-limited after 5 questions | By design: limit=5 / 60s per user in rateLimiter.js — raise it for local testing. |
| Deployed answer fails ~10–15s in | Serverless function timeout — fixed via maxDuration=60 on the streaming routes. |
Hosted infrastructure: Next.js on Vercel, Express + FastAPI on Render, Postgres + pgvector on Neon, Redis on Upstash (TLS). Inter-service URLs and model selection are environment-driven.
See ADR-002 for the move off local Ollama to hosted models.
- Golden set is expanded (n=52) but still entirely synthetic and constrained to two technical documents (Attention Is All You Need, RFC 6749). It needs real-world user telemetry to become a truly calibrated benchmark.
- Secrets are environment-held; production would use a KMS.
Tech stack Backend: Node.js · Express 5 · PostgreSQL · pgvector · Redis · JWT · bcrypt AI service: Python · FastAPI · LangGraph · sentence-transformers (cross-encoder) MCP: TypeScript · Model Context Protocol SDK Frontend: Next.js 16 · React 19 · TypeScript · Tailwind CSS · Server-Sent Events Models: Claude Haiku (primary + inline critic) · OpenAI (GPT-5 nano verifier + text-embedding-3-small) Ops: Docker · Vercel · Render · Neon · Upstash · Langfuse · correlation-ID tracing
MIT © 2026 Prathamesh Prasad