Flux

Full-stack AI knowledge workspace built with Next.js 16, React 19, Drizzle ORM, PostgreSQL, Pinecone, Inngest, and the Vercel AI SDK, featuring a HyDE + Reciprocal Rank Fusion RAG pipeline, durable background ingestion, and cross-session memory.

Next.jsNext.js
ReactReact
TypeScriptTypeScript
Tailwind CSSTailwind CSS
PostgreSQLPostgreSQL
DrizzleDrizzle
BetterAuthBetterAuth
OpenAI SDKOpenAI SDK
Pinecone
Inngest
RedisRedis
ZodZod
DockerDocker
BunBun

Project Overview

Flux is a full-stack AI research workspace designed to help students, researchers, and knowledge workers synthesize information across heterogeneous sources. Users organize their work into isolated workspaces, upload documents or import web and video content, ask grounded questions with inline citations, and generate structured learning artifacts such as summaries, flashcards, quizzes, reports, and interactive mind maps.

Rather than treating AI chat as a stateless wrapper around a single prompt, Flux combines a multi-stage Retrieval-Augmented Generation (RAG) pipeline, durable background job orchestration, cross-session user memory, and a three-panel adaptive workspace interface.

Problem Statement

Working across mixed research materials (PDFs, slide decks, spreadsheets, web articles, and lecture videos) typically forces users to switch between disconnected tools and manually synthesize context. Standard single-query vector search also struggles with several common failure modes:

  • Query-document vocabulary mismatch: Short or conversational user questions (e.g., "what are the main insights?") often have low cosine similarity against dense source passages.
  • Redundant context windows: Naive top-K vector retrieval frequently returns adjacent, overlapping chunks from the same section of a document, wasting context budget and crowding out diverse evidence.
  • Long-running ingestion bottlenecks: Extracting, chunking, and embedding large files synchronously inside HTTP request handlers risks timeouts and leaves partial state behind on failure.

The Solution

Flux addresses these challenges through an asynchronous, workspace-scoped knowledge pipeline:

  1. Unified Ingestion: Normalizes PDFs, Word documents, PowerPoint decks, Excel spreadsheets, plain text/Markdown, scraped web pages, and timestamped YouTube transcripts into a single source and source_chunk data model.
  2. Durable Background Orchestration: Offloads extraction, chunking, embedding, artifact generation, and conversation summarization to step-based Inngest workflows with automatic retries and failure tracking.
  3. Hybrid Retrieval Optimization: Uses a batched LLM call for query rewriting and Hypothetical Document Embeddings (HyDE), runs dual parallel Pinecone searches, merges results via Reciprocal Rank Fusion (RRF), and deduplicates adjacent chunks before streaming grounded answers.

Key Features

Multi-Format Source Ingestion

Users can populate a workspace from six distinct input channels:

  • Document Uploads (up to 50 MB): Parses .pdf (unpdf), .docx (mammoth, preserving both raw text and HTML preview), .pptx (jszip XML slide/shape parsing), .xlsx (exceljs, capped at 1,000 rows per sheet for preview safety), .txt, and .md. Raw files are stored in Cloudflare R2 with presigned download URLs.
  • Website Scraping: Extracts clean Markdown and OpenGraph metadata from public URLs via Firecrawl.
  • YouTube Transcripts: Fetches timestamped transcripts ([MM:SS] / [HH:MM:SS]) via Supadata (with async job polling for long videos on cloud IPs) and falls back to yt-caption-kit in local environments without a Supadata key, alongside parallel YouTube oEmbed metadata retrieval.
  • Direct Text & Markdown: Supports pasting raw notes directly into a workspace.
  • User benefit: Answers stay anchored to the user's uploaded materials with verifiable [1], [2] source citations, while an optional web search toggle ([W1], [W2]) fills gaps outside the workspace.
  • Technical implementation: ConversationService.streamWorkspaceChat streams responses via the Vercel AI SDK (streamText) using gpt-5.4-mini or gpt-5.4-nano, persists both user messages and partial/complete assistant responses (including CitationMetadata[]) to PostgreSQL, and optionally attaches a Firecrawl-backed web_search tool capped at 3 agent steps (isStepCount(3)).

Automated Learning Artifacts Studio

  • User benefit: Converts workspace sources into six study formats on demand: Summary, Key Takeaways, Flashcards, Quiz (with explanations), Mind Map, and AI Report.
  • Technical implementation: Triggered asynchronously via Inngest, generateArtifactContent uses generateText and schema-validated generateObject calls over up to 120,000 characters of READY workspace sources. Mind maps are rendered client-side as interactive, depth-styled directed acyclic graphs using React Flow and Dagre (LR layout).

Cross-Session Memory & Rolling Conversation Summaries

  • User benefit: Long conversations remain fast and coherent without losing earlier context, while user preferences and facts persist across sessions.
  • Technical implementation: Every 8 persisted messages (CONVERSATION_SUMMARY_INTERVAL = 8), an Inngest job generates a rolling summary (under 250 words) and extracts user facts into Mem0. Subsequent turns send only the rolling summary plus the most recent 12 messages (RECENT_MESSAGE_WINDOW = 12). Users can also inspect, add, edit, and delete stored memories via a dedicated UI sheet and /api/memories endpoints.

Adaptive 3-Panel Workspace & Interactive Landing Demo

  • User benefit: Keeps sources, chat, and generated artifacts visible side by side on desktop while adapting cleanly to mobile viewports.
  • Technical implementation: Desktop renders resizable left (Sources) and right (Studio) rails backed by a custom usePanelResize hook with localStorage persistence; mobile switches to a bottom tab bar. The public landing page also includes a deterministic, cursor-driven interactive workspace demo (WorkspaceDemo) with reduced-motion support.

Technology Stack

CategoryTechnologiesPurpose in Flux
FrontendNext.js 16, React 19, TypeScript, Tailwind CSS v4, Radix UIApp Router SSR/client shell, component primitives, and responsive styling
State & DataTanStack React Query v5Client cache management, optimistic source mutations, and conditional 4s polling
VisualizationReact Flow (@xyflow/react), Dagre, react-markdown, prism-react-rendererInteractive mind map DAGs, GFM markdown, and syntax-highlighted code blocks
AI & RAGVercel AI SDK (ai, @ai-sdk/openai), OpenAI API, Pinecone, Mem0Streaming chat, structured artifact generation, 512-dim embeddings, vector search, and long-term memory
Background JobsInngest (inngest)Step-based durable execution for source ingestion, artifact generation, and summarization
PersistencePostgreSQL, Drizzle ORM, Cloudflare R2 (@aws-sdk/client-s3)Relational storage for workspaces/sources/messages and S3-compatible object storage for uploaded files
Ingestion Parsersunpdf, mammoth, jszip, exceljs, Firecrawl, Supadata, yt-caption-kitLocal document parsing, web scraping to Markdown, and YouTube transcript extraction
Auth & SecurityBetter Auth (better-auth), Upstash Redis & Ratelimit, Zod, PinoEmail/password + OAuth sessions with JWT cookie cache, sliding-window rate limits, env/input validation, and structured logging
InfrastructureDocker, Docker Compose, Bun, Node.js 20Multi-stage container build and local orchestration for app, PostgreSQL, and Inngest

System Architecture

Flux follows a modular, layered full-stack architecture inside a single Next.js App Router codebase. HTTP requests flow through authenticated API route handlers into thin controllers, domain services (which enforce workspace ownership), and Drizzle ORM repositories, while heavy AI and ingestion workloads are dispatched to Inngest background functions.

Loading diagram...

Data Model

The PostgreSQL schema (server/db/schema/) is anchored by workspace, with cascading workspace-scoped entities:

  • workspace: Owned by user.id, stores title, description, icon, and defaultModel.
  • source & source_chunk: Tracks type (PDF, WEBSITE, YOUTUBE, TEXT, MARKDOWN), status (PENDING, PROCESSING, READY, FAILED), JSONB metadata, extracted text, and ordered chunks (unique(sourceId, index)).
  • conversation & message: Stores rolling summary, summaryMessageCount, summarizedAt, message role (USER, ASSISTANT), and JSONB citations.
  • learning_artifact: Stores type (SUMMARY, TAKEAWAYS, FLASHCARDS, QUIZ, MINDMAP, REPORT), status, sourceIds, and structured JSONB content.

Technical Implementation

1. Multi-Stage RAG Pipeline (Query Enhancement + HyDE + RRF)

Instead of embedding the raw user prompt directly, retrieveWorkspaceContextAdvanced executes a five-stage retrieval pipeline:

  1. Query Enhancement + HyDE: A single structured LLM call (gpt-5.4-mini via Output.object) rewrites the user's question into a self-contained retrieval query and generates a 2–4 sentence hypothetical passage (hydePassage).
  2. Parallel Dual Embedding: Embeds both strings concurrently using text-embedding-3-small at 512 dimensions.
  3. Dual Pinecone Search: Queries Pinecone in parallel (topK = 12, minScore = 0.2) filtered by workspaceId and optional sourceIds.
  4. Reciprocal Rank Fusion (RRF): Merges both ranked lists using 1 / (60 + rank + 1).
  5. Adjacent-Chunk Deduplication: Greedily keeps only the highest-scored chunk per (sourceId, Math.floor(chunkIndex / 2)) bucket and trims to the top 8 chunks.
// lib/ai/rag.ts
function rrfFuse(rankedLists: string[][], k = 60): Map<string, number> {
  const scores = new Map<string, number>();

  for (const list of rankedLists) {
    list.forEach((id, rank) => {
      const contribution = 1 / (k + rank + 1);
      scores.set(id, (scores.get(id) ?? 0) + contribution);
    });
  }

  return scores;
}

2. Durable Source Ingestion & Maintenance Scripts

Source processing runs as a multi-step Inngest function (process-source, 3 retries) with discrete memoized steps (mark-processing, extract-content, chunk-content, embed-and-index).

  • Chunking uses a recursive separator strategy (["\n\n", "\n", ". ", " ", ""]) targeting 1,000 characters with 100-character overlap, or page-preserving chunkPages when page arrays are present.
  • Embeddings are generated in batches of 50 (clamped to 24,000 characters per chunk) and upserted to Pinecone in batches of 100.
  • Chunk text is stored directly in Pinecone metadata (text.slice(0, 35000)) to avoid PostgreSQL joins during retrieval, while full source text remains in PostgreSQL for artifact generation and re-indexing (scripts/reindex.ts).

3. Resilient Streaming Chat & Partial Persistence

ConversationService.streamWorkspaceChat wraps streamText in a custom ReadableStream that accumulates streamed tokens and persists the assistant message, along with pre-computed CitationMetadata[], once the stream completes. If the client aborts mid-stream, the catch block attempts to persist any partial assistant response accumulated so far so conversation history is not lost.

Engineering Decisions

DecisionRationaleTrade-offs
512-dim text-embedding-3-small embeddingsReduces Pinecone vector storage and query latency while maintaining semantic quality; RAG_MIN_SCORE is tuned to 0.2 for broad thematic queries.Slightly lower fine-grained recall compared to 1536-dim or text-embedding-3-large embeddings.
Denormalized chunk text in Pinecone metadataEliminates database round-trips/joins during RAG retrieval.Duplicates chunk text between PostgreSQL and Pinecone, requiring synchronized cleanup on delete (removeSourceFromIndex) and a reindex.ts script.
Local async fallback for source ingestionIf inngest.send fails (e.g., local dev without Inngest running), SourceService.enqueueSourceProcessing falls back to an in-process async processSourcePipeline call.Ensures sources still process in degraded environments, though without Inngest's cross-restart durability.
Dual-provider YouTube transcript strategyUses Supadata in cloud/Vercel deployments where direct YouTube scraping is blocked, and falls back to yt-caption-kit locally when SUPADATA_API_KEY is unset.Requires managing two transcript response formats (millisecond vs. second offsets) and polling Supadata jobs for long videos.
Conditional Redis rate limiting with in-memory fallbackUses Upstash Redis sliding-window rate limiting in distributed environments and falls back to a local Map with 5-minute pruning when Redis credentials are omitted.Simplifies local setup, though the in-memory fallback is per-instance and not shared across serverless workers.

Technical Challenges & Solutions

1. Preventing Context Redundancy in Chunked Retrieval

  • Challenge: Standard vector search often returns multiple consecutive chunks from the same paragraph or page, reducing topical diversity in the LLM's context window.
  • Approach: deduplicateChunks groups chunks by ${sourceId}:${Math.floor(chunkIndex / 2)} after RRF scoring and greedily retains only the highest-ranked representative per adjacent pair.
  • Outcome: Surfaces broader coverage across workspace sources within the 8-chunk budget.

2. Cloud-Reliable YouTube Transcript Ingestion

  • Challenge: Direct YouTube caption scraping libraries frequently fail from cloud/datacenter IPs (such as Vercel), and long videos can exceed synchronous API response limits.
  • Approach: getYoutubeTranscript routes requests through Supadata when SUPADATA_API_KEY is configured (polling getJobStatus up to 10 times at 3-second intervals when a jobId is returned), while running oEmbed metadata fetching in parallel.
  • Outcome: Reliable transcript ingestion across both local development and cloud deployments without blocking metadata resolution.

3. Optimistic UI vs. Background Polling Race Conditions

  • Challenge: Immediately polling GET /api/sources while an import mutation is still in flight can overwrite optimistic source placeholders in React Query's cache.
  • Approach: useSources checks useIsMutating() and pauses its 4-second refetchInterval while mutations are active, then swaps the temporary optimistic-* item with the server-returned record in onSuccess.
  • Outcome: Smooth optimistic feedback during uploads and automatic status transitions from PENDING to READY once background jobs finish.

User Experience & Design

  • Adaptive Layout: Desktop features collapsible, drag-resizable left and right rails (SidebarSources, SidebarArtifacts) with collapsed icon rails; mobile (below md) transitions to a bottom tab bar.
  • Loading, Empty & Error States: Dedicated skeleton loaders (DashboardContentSkeleton, WorkspaceViewSkeleton, ChatSkeleton), empty-state prompts guiding users to upload their first source, and toast notifications via Sonner.
  • Rich Content Rendering: Assistant messages and prose artifacts render GitHub-Flavored Markdown with syntax-highlighted code blocks (prism-react-renderer). Mind maps dynamically import MindmapFlow with ssr: false and a spinner fallback, and support node selection/dimming to focus on connected branches.
  • Theming & Typography: Light and dark themes via next-themes, pairing Schibsted Grotesk headings, Inter body text, and Geist Mono metadata/code.

Performance, Security & Reliability

  • Authentication & Route Protection: Better Auth manages email/password and optional GitHub/Google OAuth sessions with JWT cookie caching. proxy.ts redirects unauthenticated users away from /dashboard and /workspace, while every API controller calls getAuthenticatedUser and services verify workspace ownership (WorkspaceService.getWorkspaceById).
  • Input & Environment Validation: All API payloads and query parameters are validated with Zod (safeParse + structured field errors via getZodFieldErrors), file uploads are capped at 50 MB and restricted to six extensions, and lib/env.ts validates required secrets (including a 32+ character BETTER_AUTH_SECRET) at startup.
  • Rate Limiting: Chat streaming and all source import endpoints enforce a 15-requests-per-minute sliding window per user (checkRateLimit).
  • Error Handling & Observability: asyncHandler normalizes thrown ApiError and unexpected errors into consistent JSON responses, sanitizeExternalError hides raw external service errors in production, and Pino provides structured module-scoped logging.
  • Containerization: Multi-stage Dockerfile builds a standalone Next.js bundle with Bun and runs as an unprivileged nextjs user on Node 20 Alpine with a /-route HEALTHCHECK.

Results & Impact

Flux demonstrates a complete end-to-end AI research platform with:

  • 6 supported ingestion formats/channels (.pdf, .docx, .pptx, .xlsx, .txt/.md, websites, YouTube videos, and raw text).
  • 6 structured learning artifact types generated asynchronously and rendered with specialized interactive viewers.
  • 5-stage RAG retrieval pipeline combining query rewriting, HyDE, dual vector search, RRF fusion, and adjacent-chunk deduplication.
  • Containerized 3-service local stack (app, postgres:16-alpine, inngest) ready for reproducible deployment.

Learnings & Skills Demonstrated

  • Full-Stack TypeScript Architecture: Designing clean controller → service → repository boundaries in Next.js App Router with end-to-end Zod validation and Drizzle ORM.
  • Applied Information Retrieval (RAG): Implementing HyDE, Reciprocal Rank Fusion, metadata filtering, and chunk deduplication to improve retrieval quality over naive vector search.
  • Distributed & Durable Workflows: Decoupling slow document parsing, embedding, and LLM generation from HTTP request lifecycles using Inngest step functions.
  • Real-Time & Optimistic Frontend Engineering: Coordinating ReadableStream AI responses, abort handling, React Query cache synchronization, and interactive React Flow visualizations.

Future Improvements

  • Automated Test Suite: Add unit tests for chunker.ts, rrfFuse, deduplicateChunks, and API validators, plus integration tests for workspace access control and RAG retrieval.
  • Artifact Generation Fallback & Streaming: Mirror SourceService's local fallback in LearningArtifactService when Inngest is unavailable, and consider streaming artifact generation progress.
  • Token-Accurate Chunking: Replace the Math.ceil(length / 4) character-length approximation in chunkSourceContent with a tokenizer (e.g., tiktoken) for tighter context-window budgeting.
  • Multi-Conversation Switching UI: Expose full conversation switching/history management in the workspace UI if users create multiple threads per workspace.