Skip to content

About

An enterprise-grade, agentic research engine featuring autonomous self-correction, cross-model verification, and a zero-tolerance architecture for hallucinations.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Agentic Research Engine

License: MIT Stack Stack Stack

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).


What makes it more than a RAG wrapper

  • 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.

Architecture

System architecture

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

The query pipeline

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]
Loading
  1. Next.js refreshes/injects the bearer token and proxies to Express (fetch rather than EventSource, so HTTP 401/403 surface as real states, not a generic stream error).
  2. Express authenticates, applies the rate limiter, and streams the request to FastAPI.
  3. FastAPI drives the graph above, emitting one SSE event per node.
  4. A cache hit skips synthesis/critic — but only after retrieval runs (never skipped).
  5. After the answer streams, GPT-5 nano re-runs the faithfulness check as a background task; the UI polls /api/trace/:id and flips an Agreed / Disagreed badge — cross-provider agreement.

Retrieval science (measured)

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 its tsvector over 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.

Retrieval benchmark

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.


Trust & safety

  • 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 RecursiveCharacterTextSplitter to 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.

Abstain eval

  • Encryption at rest — chunk text is AES-256-GCM (iv:authTag:ciphertext).
  • Tenant isolation — user_id is 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).

Cost & latency

Cost and latency

A query is dominated by sequential model calls — the self-consistency critic alone was 45% of end-to-end. Parallelising its 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 **$0.012/query** (modelled).

Observability

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.


Local setup (step by step)

Prerequisites

  • Docker (Postgres + Redis), Node.js 20+, Python 3.11+
  • API keys: ANTHROPIC_API_KEY (Claude) and OPENAI_API_KEY (embeddings + verifier)

1 · Clone & start infrastructure

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 :6379

2 · Generate secrets

openssl 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)

3 · Environment 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

4 · Run migrations (in order)

cd backend && npm install
for f in $(ls ../infra/migrations/*.sql | sort); do
  node src/config/runMigration.js "$(basename "$f")"
done
cd ..

5 · Run the three services (three terminals)

# 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

6 · Seed a corpus (required — an empty DB makes every answer abstain)

  1. Open http://localhost:3000, sign up, and sign in.
  2. Go to Upload, upload a PDF (e.g. a research paper), and wait for embedding to finish.
  3. Go to Ask and query it — you'll see the live pipeline trace, the answer with citations, and the verification badge.

Troubleshooting

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.

Deployment

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.


Known limitations

  • 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

License

MIT © 2026 Prathamesh Prasad

About

An enterprise-grade, agentic research engine featuring autonomous self-correction, cross-model verification, and a zero-tolerance architecture for hallucinations.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages