AI Chatbot Demo — RAG Knowledge Base Q&A System
Tech Stack Versions
Precise technology versions used in this project
Screenshots
Main feature screens of the project
Main Chat Interface — SSE streaming with real-time Markdown rendering
Three-Provider Selector — Zero-downtime switching between Gemini / OpenAI / Claude
Document Upload Panel — Supports PDF / TXT / MD / DOCX / CSV (5 formats)
Dark Mode — Full dark theme with sidebar conversation history
Session History Sidebar — Auto-saves and switches between past conversations (dark mode)
Capabilities Demonstrated
Technical and business capabilities demonstrated through this project
- Provider Abstraction — LlmProvider interface unifies Gemini / OpenAI / Claude / Mock with async generator streaming protocol for zero-downtime switching
- pgvector Vector Search — Cosine similarity Top-5 retrieval, batch embedding (20/batch), multi-tenant document isolation enforced at SQL layer
- Instant Demo Access — 'Try Demo' button for one-click experience, 1-hour JWT auto-expiry, isDemoUser() server-side guards blocking destructive operations
- Mock Mode — Auto-detects invalid API keys, simulates full RAG pipeline for zero-cost online demos without any API key configuration
- Security Hardening — CSP / HSTS / Helmet / JWT + bcrypt / rate limiting / Zod env validation / ownership checks, 5/5 security score
Challenges Faced
Main technical challenges encountered during development
- Zero-Config Demo Mode — portfolio demos need to work without API keys for cost and security reasons, but mock responses must feel realistic enough to demonstrate full streaming, source citations, and provider-switching UX
- Cross-Provider LLM Streaming — Gemini, OpenAI, and Claude expose different streaming APIs with incompatible interfaces; consumers must switch providers without modifying business logic
- SSE Streaming in NestJS — NestJS's response pipeline (interceptors, serialization, exception filters) conflicts with SSE's requirement for a persistent, manually-controlled byte stream over a long-lived HTTP connection
- Ownership-Filtered Vector Search — anonymous users should search only public documents; authenticated users their own plus public; User A's private documents must never be visible to User B — enforced at the database layer, not application logic
- Production-Aware Env Validation — startup validation must be strict in production (fail fast on missing JWT_SECRET, FRONTEND_URL) but lenient in development to allow local testing without all credentials
- Demo Account with Server-Side Restrictions — providing instant 'Try Demo' access for portfolio visitors while preventing demo users from modifying seeded showcase data (conversations, documents) requires server-side enforcement on every destructive endpoint
Solutions
Technical solutions and implementation strategies adopted
- LlmModule implements conditional provider instantiation at module load time via isMockMode(). When no valid API keys are detected, only MockProvider is registered under the LLM_PROVIDERS injection token, streaming realistic responses via AsyncGenerator<string> with simulated delays. ChatService is entirely unaware of whether it communicates with a real or mock provider.
- LlmProvider interface exposes a single chat(): AsyncGenerator<string> contract. Each provider wraps its native SDK streaming in an async generator, normalizing Gemini's generateContentStream, OpenAI's delta.content stream, and Claude's event-based text callback to yield string tokens. Runtime dispatch via the LLM_PROVIDERS DI record selects the correct implementation at request time.
- Use @Res() decorator to bypass NestJS's response processing and access the raw Express res object. Set Content-Type: text/event-stream + Cache-Control: no-cache headers, write SSE frames manually via res.write(). Attach res.on('close') to detect client disconnect, accumulating partial response in fullResponse and persisting it to the database before connection drops.
- VectorSearchService executes two distinct raw SQL queries based on authentication status. Authenticated query includes AND (d.user_id IS NULL OR d.user_id = $4::uuid); anonymous query uses AND d.user_id IS NULL. The ownership filter runs inside the SQL WHERE clause — enforced by the database engine, not application-layer post-filtering.
- Zod schema uses superRefine to add conditional validation: FRONTEND_URL and JWT_SECRET are only required when NODE_ENV === 'production'. On validation failure, process.exit(1) ensures the API never starts in a broken state — fail-fast at boot rather than runtime 500 errors on the first request.
- Dedicated /api/auth/demo endpoint creates or reuses demo@example.com with 1-hour JWT expiry. isDemoUser() guard function checks email on every DELETE endpoint for both chat sessions and documents — server-side enforcement as primary control, frontend restrictions as secondary UX hint. Seeded conversation data provides immediate showcase content.
Code Snippets
Key implementation code from the project
// apps/api/src/providers/llm/llm.interface.ts
// Unified contract — all providers implement this interface
export interface LlmProvider {
readonly name: string;
chat(params: LlmChatParams): AsyncGenerator<string>;
}
// apps/api/src/providers/llm/gemini.provider.ts
@Injectable()
export class GeminiProvider implements LlmProvider {
readonly name = 'gemini';
async *chat(params: LlmChatParams): AsyncGenerator<string> {
const model = this.client.getGenerativeModel({
model: 'gemini-2.5-flash',
systemInstruction: buildSystemContent(params.systemPrompt, params.context),
});
const chat = model.startChat({ history });
const result = await chat.sendMessageStream(lastMessage.content);
for await (const chunk of result.stream) {
const text = chunk.text();
if (text) yield text; // Token-by-token streaming
}
}
}
// OpenAI / Claude / MockProvider implement the same interface
// → Runtime DI: providers[dto.provider].chat(params)Architecture Decisions
Key architectural and technical decisions made during development
Context
RAG Pipeline requires storing and searching document embedding vectors, choosing between a dedicated vector database and a PostgreSQL extension.
Options Compared
- Purpose-built for vector search, excellent horizontal scaling
- Managed service, zero operational overhead
- Extra service and cost; cross-service JOINs require an extra network roundtrip
- Document metadata and vectors split across two systems
- Single DB, enables direct JOIN with documents table
- Ownership filter (user_id) and similarity search in one SQL query
- Performance degrades at massive scale (hundreds of millions of vectors) vs dedicated solutions
Decision
Chose pgvector: RAG Demo scale doesn't require billions of vectors; single SQL handles similarity search + ownership validation with no extra infrastructure
Outcome
Cosine similarity, user ownership, and document status filtering in one SQL query; zero additional service cost
Key Takeaways
Important lessons and reflections from this project
Decouple 'Can Run' from 'Has Credentials'
Real Impact: The MockProvider pattern makes the application permanently demo-ready regardless of API key availability. Treating 'no credentials' as a valid operating mode — not an error condition — eliminates demo breakages caused by expiring API keys. This pattern applies to any external service dependency: payment processors, email providers, storage services.
pgvector Eliminates an Infrastructure Tier for AI Apps at Demo Scale
Real Impact: For AI applications below ~1M vectors, PostgreSQL + pgvector is simpler, cheaper, and more maintainable than a dedicated vector database. The ownership-filtered cosine similarity query shows that vector search can be composed naturally with relational constraints (JOINs, WHERE, user ownership) in a single SQL statement — something requiring application-layer joins with a dedicated vector DB.
Demo Accounts Need Server-Side Enforcement from Day One
Real Impact: The demo access feature required isDemoUser() checks on every destructive endpoint. Retrofitting these guards after initial development revealed that permission logic must be designed into the API layer from the start — not bolted onto the frontend. The 1-hour JWT expiry and seeded data approach creates a self-resetting demo environment suitable for portfolio showcasing without manual maintenance.
Interested in this project?
Feel free to reach out to discuss similar technical solutions or how I can help with your project.
Contact Me