8000 zaidrahmann.github.io/README.md at main · zaidrahmann/zaidrahmann.github.io · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
308 lines (198 loc) · 14.5 KB

README.md

File metadata and controls

308 lines (198 loc) · 14.5 KB

Zaid Rehman — academic site

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.

Install

npm install

Development

npm run dev

The site is served at http://localhost:8000.

Production build

npm run build
npm run preview

The static site is written to dist/.


RAG Chat Assistant

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-001 embeddings). There is no HNSW index.
  • Generation: Gemini gemini-3.5-flash-lite on 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-for and hashed with RATE_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.

Technical reference

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.

Mobile layout

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.

Setup — zero budget (free tier)

1. Prerequisites

2. Environment variables

cp .env.example .env.local

Edit .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_KEY with PUBLIC_. Never commit .env.local. Only .env.example is committed.

3. Apply SQL migrations

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

4. Sync and ingest the knowledge base

# 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:ingest

The first ingest embeds every file and writes chunks to Supabase. Subsequent runs skip unchanged files (hash comparison).

5. Deploy to Vercel

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.


Keeping the knowledge base in sync

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 files

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


PDF ingestion (optional)

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.


Evaluation

Run the labeled evaluation against ~40 questions:

npm run rag:eval

Output: 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.40

Important: Metric scores do not prove factual correctness. Always manually review model answers for invented facts, especially for under-review, in-progress, interest, and proposed evidence classes.

Test rate limiting atomicity with concurrent requests:

npm run rag:test-ratelimit

Unit tests

npm test

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


Changing the embedding model

Warning: This is a breaking change. All existing embeddings become incompatible.

  1. Confirm the new model outputs 768-dimensional vectors (or write a SQL migration to change vector(768) to vector(N)).
  2. Update GEMINI_EMBEDDING_MODEL in .env.local and Vercel.
  3. 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.


Rate limiting

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.

Update personal information

Edit src/data/site.ts.

  • Name, role, introduction, and biography
  • Email
  • Portrait paths (portraits)
  • Public site URL (url), used for the canonical link and Open Graph URL
  • Profile links in the profiles array
  • Navigation labels in the nav array

Update publications

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, year
  • kind: "journal" or "conference"
  • status: "published", "accepted", or "under-review"
  • href and hrefLabel when a DOI or article page exists
  • pages only when you have confirmed proceedings pages
  • results only 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.ts
  • src/data/experience.ts
  • src/data/projects.ts
  • src/data/education.ts
  • src/data/news.ts — dated notes, newest first. A parts entry with href becomes a link.

For a project, add a links entry only when the URL is real. Use note for work that has no public repository.

Replace the portraits

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.

Add or replace the CV

  1. Put the PDF at public/documents/Zaid_Rehman_CV.pdf.
  2. 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.

Deploy

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.

Publication notes

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.

0