Skip to content

Repository files navigation

Product AI Assistant

A small Next.js app that helps people ask product-building questions while you iterate on a fictional commerce platform (Chica). Each answer is generated with OpenRouter, then graded and reviewed (with at most one automatic revision). Everything is stored in PostgreSQL via Prisma.

Features

  • Chat UI at /chat — matcha + strawberry themed layout, light / dark toggle (stored in localStorage as product_ai_theme), question in / answer out, status badges (approved, needs revision, pending review, etc.).
  • Session-scoped threads — the browser keeps one active conversation id in sessionStorage (product_ai_assistant_conversation_id); New chat starts a fresh conversation. The assistant still answers each question from the same system prompts (no cross-session memory in the model).
  • Persistence — conversations, messages, and evaluation payloads in Postgres.
  • Pipeline — answer model → grader (JSON scores) → reviewer (JSON decision) → optional single revision.
  • Evaluator switch — see OpenRouter vs Braintrust below.
  • Rate limits — sliding window on POST /api/ask (in-memory; configurable via env).
  • Eval dataset — curated Chica questions: evals/product-assistant-eval-set.json, runnable with npm run eval:chica.

Stack

  • Next.js (App Router), TypeScript, Tailwind CSS
  • PostgreSQL + Prisma ORM
  • OpenRouter for LLM calls
  • Optional Braintrust SDK for eval logging

OpenRouter vs Braintrust (where to switch)

What Where
Switch mode .env.local: EVALUATOR_PROVIDER=multi (default), braintrust, langsmith (stub), or single (stub). Restart npm run dev.
Factory that reads that env lib/evaluator.ts — getEvaluator() returns MultiModelEvaluator, BraintrustEvaluator, LangSmithEvaluator (placeholder), or SingleModelEvaluator (placeholder).
OpenRouter HTTP calls (answer, grader, reviewer, revision) lib/openrouter.ts — retries, model fallback lists from OPENROUTER_*_MODELS env vars.
Grader + reviewer prompts lib/prompts.ts
Braintrust logging (only when braintrust mode + BRAINTRUST_API_KEY set) lib/braintrustLog.ts — initLogger + traced span ProductAssistant_pipeline_eval.
Pipeline order lib/pipeline.ts — calls getEvaluator() after the draft answer exists.

Summary: OpenRouter always powers the LLM calls for this MVP. Braintrust adds observability (logs/scores to your Braintrust project); it does not replace OpenRouter unless you build a different integration later.

Prerequisites

  • Node.js 20+ recommended
  • A PostgreSQL database (e.g. Neon)
  • An OpenRouter API key

Setup

  1. Clone and install

    npm install
  2. Environment

    Copy .env.example to .env.local and fill in at least:

    • DATABASE_URL — Postgres connection string
    • OPENROUTER_API_KEY — from OpenRouter

    Optional:

    • EVALUATOR_PROVIDER=braintrust and BRAINTRUST_API_KEY — log evals to Braintrust (docs)
    • BRAINTRUST_PROJECT_NAME — defaults to Product AI Assistant
    • OPENROUTER_*_MODELS — comma-separated model ids (see .env.example)
    • RATE_LIMIT_MAX, RATE_LIMIT_WINDOW_MS, or RATE_LIMIT_DISABLED=1 for local stress tests
  3. Database schema

    From the project root (loads .env.local via dotenv-cli):

    npm run db:push

    For migration-based workflows:

    npm run db:migrate
  4. Run locally

    npm run dev

    Open http://localhost:3000/chat.

Scripts

Command Purpose
npm run dev Development server
npm run build prisma generate + production Next build
npm run start Run production build
npm run lint ESLint
npm run db:push Push Prisma schema to DB (uses .env.local)
npm run db:migrate Create/apply migrations (uses .env.local)
npm run eval:chica POST every Chica eval question to a running app (see below)

Chica eval batch script

With the dev server already running (npm run dev with valid .env.local):

npm run eval:chica

Optional env:

  • EVAL_BASE_URL — default http://localhost:3000
  • EVAL_DELAY_MS — pause between requests (default 600)

The script reads evals/product-assistant-eval-set.json and prints each row’s HTTP outcome. Exit code is non-zero if any request fails.

API routes

Method Path Description
POST /api/ask Body: { "question": string, "conversationId"?: uuid } — rate-limited; max question length 8000 chars
GET /api/history Query ?conversationId=<uuid> (required for data) — returns at most one conversation and its messages. Missing or invalid id → { "conversations": [] } (avoids listing everyone’s chats).
GET /api/metrics Aggregate evaluation scores from the DB

Rate limiting

  • POST /api/ask uses an in-memory sliding window per client IP (x-forwarded-for → first hop, else x-real-ip, else unknown).
  • Defaults: 15 requests per 60s per IP (RATE_LIMIT_MAX, RATE_LIMIT_WINDOW_MS).
  • 429 responses include Retry-After and a JSON body with error: "rate_limited".
  • On serverless with many cold instances, each instance has its own counter; for strict global limits use Redis (e.g. Upstash) later.
  • Disable for local abuse tests: RATE_LIMIT_DISABLED=1 in .env.local.

CI

GitHub Actions workflow .github/workflows/ci.yml runs npm ci, npm run lint, and npm run build on pushes/PRs to main/master.

Project layout (high level)

  • app/ — pages and API routes
  • components/ — AppHeader, ThemeToggle, ChatWindow, AskBox, MessageList
  • lib/ — openrouter, pipeline, evaluator, prompts, retry, rateLimit, db, braintrustLog
  • scripts/ — run-chica-evals.mjs
  • prisma/ — schema and migrations
  • types/ — Zod-backed evaluation shapes + evaluator types
  • evals/ — Chica eval question set (JSON)

Security notes

  • Never commit .env or .env.local (they are gitignored).
  • Rotate keys if they were ever pasted into chat, tickets, or screenshots.
  • GET /api/history only returns a conversation when you pass a valid conversationId; it does not enumerate all rows. For true multi-tenant isolation, still add auth and server-side checks that the caller may access that id.

What’s left (optional)

  • Deploy — Vercel (or similar): set env vars, run migrations against prod DB.
  • Auth / sessions — per-user conversations and history.
  • Redis-based rate limits — shared limiter across serverless instances.
  • LangSmith SDK — LangSmithEvaluator is a stub today; fork contributors can replace it with real LangChain/LangSmith calls.

Chica is a fictional classroom platform name used for eval prompts and demos.

Releases

Packages

Contributors

Languages