A single-page academic portfolio with an AI-powered RAG (Retrieval-Augmented Generation) chat assistant. The stack is Astro + TypeScript + Tailwind CSS + Supabase pgvector + Gemini API. Content lives in src/data so the page components do not need to change for ordinary updates.
The site supports Light, Dark, and System themes. See docs/THEME.md for the colour-token architecture, flash-prevention strategy, and guidance on writing theme-compatible styles.
npm installnpm run devThe site is served at http://localhost:8000.
npm run build
npm run previewThe static site is written to dist/.
Visitors use the floating widget to ask about Zaid's public research, publications, projects, experience, and contact details. Direct lookups for email, profiles, age, the public city, and private or financial questions are answered in TypeScript and do not call a model. Every other question is embedded with Gemini, searched in Supabase with pgvector, answered by Gemini on Vercel (or by a local Sonnet deployment when that is configured), and then checked by a deterministic grounding pass before it is rendered. The stack is Astro, TypeScript, Tailwind CSS, Supabase Postgres with pgvector, and the Gemini API. PDF text is extracted with unpdf and embedded by a separate worker.
The authoritative write-up is in docs/ai-assistant/:
Operational defaults used by that system:
- Retrieval: Supabase PostgreSQL + pgvector (cosine similarity, 768-dimensional
gemini-embedding-001embeddings). There is no HNSW index. - Generation: Gemini
gemini-3.5-flash-liteon Vercel, with structured JSON. Local development uses Azure Sonnet when the Sonnet variables are set. Embeddings stay on Gemini either way. - Rate limiting: PostgreSQL advisory locks. The visitor IP is taken from
x-vercel-forwarded-forand hashed withRATE_LIMIT_SECRET. LLM traffic has a per-visitor cap and a shared cap. Directory lookups use a separate daily cap and a burst cap. - Knowledge base: Markdown in
knowledge-base/, plus optional PDFs in a private Storage bucket. Chat does not read the Markdown files directly.
A visitor message is classified in the chat API before any model call. Contact details, age, the public city, and matching private or financial questions are answered from site data and do not call Gemini. Other questions are embedded, retrieved from Supabase pgvector, answered by Gemini as JSON, and then filtered by a deterministic evidence check that can remove unsupported sentences and choose public source links. Local development can send the answer step to Azure Anthropic instead; embeddings stay on Gemini, and production forces Gemini.
Stack: Astro, TypeScript, Tailwind, Vercel, Supabase Postgres with pgvector, and the Gemini API (gemini-embedding-001 for vectors, gemini-3.5-flash-lite by default for answers).
The pages under docs/ai-assistant/ are the source of truth for request flow, rate limits, and ingestion. The setup steps below remain the short operational path.
On a phone, including landscape, the open assistant fills the screen. The desktop popup is unchanged. The keyboard path does not use window.innerHeight and does not pin merely because the composer is focused. See docs/MOBILE_CHAT.md for the media query, the 72px threshold, the scroll lock, and what not to regress.
tests/rag/chat-panel.test.ts locks the pin decision. The production site at zaidrehman.vercel.app keeps the previous behavior until this change is deployed.
- Node ≥ 20.12 (uses
process.loadEnvFile) - A Supabase project (free plan)
- A Google AI Studio API key (free tier)
- A Vercel account (Hobby plan)
cp .env.example .env.localEdit .env.local and fill in:
| Variable | Where to find it |
|---|---|
GEMINI_API_KEY |
Google AI Studio → API Keys |
SUPABASE_URL |
Supabase → Project Settings → API → Project URL |
SUPABASE_SECRET_KEY |
Supabase → Project Settings → API Keys → sb_secret_... |
RATE_LIMIT_SECRET |
Any random 32+ character string (e.g. openssl rand -hex 32) |
Leave all other variables at their defaults for the first run.
Security: Never prefix
SUPABASE_SECRET_KEYwithPUBLIC_. Never commit.env.local. Only.env.exampleis committed.
In the Supabase SQL editor, run each file in order:
supabase/migrations/001_enable_pgvector.sql
supabase/migrations/002_create_documents_and_chunks.sql
supabase/migrations/003_replace_document_chunks.sql
supabase/migrations/004_create_similarity_search.sql
supabase/migrations/005_create_rate_limits.sql
# Generate Markdown from src/data/ (run this whenever src/data changes)
npm run rag:sync-knowledge
# Check for drift between src/data and knowledge-base/
npm run rag:check-knowledge
# Dry run — see what would be ingested (no API calls)
npm run rag:ingest:dry
# Ingest all changed files into Supabase
npm run rag:ingestThe first ingest embeds every file and writes chunks to Supabase. Subsequent runs skip unchanged files (hash comparison).
Add all variables from .env.local to Vercel → Project Settings → Environment Variables.
The /api/chat endpoint uses export const prerender = false — it is the only server-rendered route. All other pages remain fully static.
src/data/ is the authoritative source. After every content edit:
npm run rag:sync-knowledge # update knowledge-base/ front matter
npm run rag:check-knowledge # CI-style drift check (exits 1 on mismatch)
npm run rag:ingest # re-embed changed filesThe sync script updates only structured front matter fields (category, evidence_class, record_id, href). Body text in knowledge-base/*.md files is authoritative and is never overwritten.
Upload a PDF and ingest it as a citable document:
# Validate and preview (no uploads, no API calls)
npm run rag:pdf -- dry-run path/to/paper.pdf
# Upload to Supabase Storage and register
npm run rag:pdf -- upload path/to/paper.pdf --title "My Paper" --category publication
# Embed and index (after upload)
npm run rag:pdf -- process "pdf/<uuid>/paper.pdf"
# Re-embed with updated content (preserves previous version on failure)
npm run rag:pdf -- reprocess "pdf/<uuid>/paper.pdf"
# List all PDF documents
npm run rag:pdf -- list
# Delete a PDF document and its chunks
npm run rag:pdf -- delete "pdf/<uuid>/paper.pdf"Note: Signed PDF URLs expose private storage objects. Do not upload confidential files.
Run the labeled evaluation against ~40 questions:
npm run rag:evalOutput: a summary table + tests/evaluation/report-YYYY-MM-DD.json.
Sweep the similarity threshold to tune retrieval:
npm run rag:eval -- --threshold 0.35
npm run rag:eval -- --threshold 0.40Important: Metric scores do not prove factual correctness. Always manually review model answers for invented facts, especially for
under-review,in-progress,interest, andproposedevidence classes.
Test rate limiting atomicity with concurrent requests:
npm run rag:test-ratelimitnpm testTests cover: chunking (token 69C0 estimation, hash, front matter, pack logic), validation (question, model answer, chat request), source reference building (URL safety, deduplication, trusted hrefs), and answer JSON parsing (code fence stripping, edge cases).
Warning: This is a breaking change. All existing embeddings become incompatible.
- Confirm the new model outputs 768-dimensional vectors (or write a SQL migration to change
vector(768)tovector(N)). - Update
GEMINI_EMBEDDING_MODELin.env.localand Vercel. - Run
npm run rag:ingest— this re-embeds all files because the model metadata no longer matches.
Changing dimensions requires a SQL migration (drop and recreate the knowledge_chunks table with a new vector(N) column). npm run rag:reembed exits early with instructions.
Limits are enforced atomically in PostgreSQL (advisory locks). The chat route classifies the question first, then consumes only the matching policy. A denied request does not increment a counter. Directory defaults are independent and more generous because those answers never call a model.
The shared LLM cap is an emergency cost limit for every visitor. Each visitor already has a separate per-IP allowance (10 requests per 10 minutes), keyed by a hash of the trusted IP, so a burst from one client cannot walk through the shared cap. That per-IP bucket is the visitor limiter; a third counter is not added. One visitor can still reach the shared cap by waiting out the 10-minute windows. That is what the shared cap is for.
The 24-hour windows are fixed from the moment they open. They do not reset at midnight, and they are not a sliding log of individual timestamps.
| Variable | Default | Description |
|---|---|---|
RATE_LIMIT_MAX_REQUESTS |
10 | LLM/RAG requests per visitor IP per window |
RATE_LIMIT_WINDOW_SECONDS |
600 | LLM/RAG per-IP window (10 minutes) |
GLOBAL_RATE_LIMIT_MAX_REQUESTS |
100 | Shared LLM/RAG allowance for all visitors |
GLOBAL_RATE_LIMIT_WINDOW_SECONDS |
86400 | Shared window length (24 hours from when it opened) |
DIRECTORY_RATE_LIMIT_MAX_REQUESTS |
100 | Directory lookups per visitor per day |
DIRECTORY_RATE_LIMIT_WINDOW_SECONDS |
86400 | Directory visitor window (24 hours) |
DIRECTORY_BURST_MAX_REQUESTS |
20 | Directory lookups per visitor per burst window |
DIRECTORY_BURST_WINDOW_SECONDS |
60 | Directory burst window (1 minute) |
Visitor IPs are hashed with RATE_LIMIT_SECRET and never stored in raw form. The endpoint reads only x-vercel-forwarded-for (Vercel's trusted header) and never falls back to other IP headers. Apply supabase/migrations/009_dual_rate_limit.sql before relying on the split in a live database. The migration is not applied automatically.
Edit src/data/site.ts.
- Name, role, introduction, and biography
- Portrait paths (
portraits) - Public site URL (
url), used for the canonical link and Open Graph URL - Profile links in the
profilesarray - Navigation labels in the
navarray
Edit src/data/publications.ts. Add an object to the publications array. Journal articles, conference papers, and manuscripts under review are grouped automatically.
For each paper, set:
title,authors,venue,yearkind:"journal"or"conference"status:"published","accepted", or"under-review"hrefandhrefLabelwhen a DOI or article page existspagesonly when you have confirmed proceedings pagesresultsonly for numbers that belong to that paper
Leave href unset when a manuscript has no public link. The page will not render a dead link.
Research themes, experience, projects, and education are the same kind of edit:
src/data/research.tssrc/data/experience.tssrc/data/projects.tssrc/data/education.tssrc/data/news.ts— dated notes, newest first. Apartsentry withhrefbecomes a link.
For a project, add a links entry only when the URL is real. Use note for work that has no public repository.
The hero cycles through the photographs listed in portraits inside src/data/site.ts. The files live in public/images/portraits/.
To change them, replace or add image files in that folder and edit the portraits array. The first entry is the photograph shown on load.
- Put the PDF at
public/documents/Zaid_Rehman_CV.pdf. - Restart the dev server, or run a new production build.
The homepage, navigation, and CV section offer the CV only when that file is present at server start. View CV opens /cv in a new tab. That page displays the document inline, so the link itself is not a .pdf address. Download CV is a separate action and is the only link that uses the download attribute. public/documents/Zaid_Rehman_CV.pdf is committed, so a push publishes it. Replace that file, commit, and push to update the live CV. A copy at the repo root is a local duplicate and stays out of git.
The site is published on Vercel at https://zaidrehman.vercel.app. The build command is npm run vercel-build and the output directory is dist.
npm run vercel-build runs astro build first, then — on Production deployments only — runs npm run rag:ingest -- --prune to synchronize the Markdown knowledge base. Preview deployments build the site but skip ingest. Set the four required environment variables (GEMINI_API_KEY, SUPABASE_URL, SUPABASE_SECRET_KEY, RATE_LIMIT_SECRET) under Production in the Vercel project settings. If the Vercel project settings Build Command field is set explicitly it overrides vercel.json; clear it or set it to npm run vercel-build.
url in src/data/site.ts is that public address. Vercel builds from git, so the published CV is whatever public/documents/Zaid_Rehman_CV.pdf contains in the commit being built.
Author lists, titles, venues, and page ranges for the published papers were checked against Crossref or the journal page. The Bulletin of Electrical Engineering and Informatics article is linked from the journal site; a volume and DOI were not added because they were not on that record. The two “under review” manuscripts are listed as they appear on the CV and have no DOI.