1. Overview#
Delulu CEO ("Your worst decisions. Our next unicorn.") is a full-stack AI web application created for the Build With AI: Basics Hackathon. Given a confession of an everyday questionable decision or procrastination habit (up to 1,000 characters), the application generates a structured 4-part satirical startup pitch deck:
- 01. Startup Pitch: Company name (
startupName), business model (startupConcept), and VC FOMO rationale (investmentRationale). - 02. Forbes Cover: Sensationalized headline (
forbesHeadline). - 03. Risk Analysis: Obvious personal or financial red flags reframed as competitive moats (
riskAnalysis). - 04. CEO Verdict: The highlighted executive roast balancing hype with reality (
ceoVerdict).
Users can export the generated deck in one click via a formatted plain-text clipboard template (with manual fallback) or download a 1080×1350 (4:5 portrait) PNG share card rendered entirely client-side on an HTML5 <canvas>.
2. The Problem#
Even small AI web applications routinely fail in production demos due to three preventable engineering issues:
- Unstructured or truncated model outputs breaking the UI: Relying on prompt instructions like "Respond in JSON" frequently results in markdown code fences, missing keys, or empty strings when output tokens run low, crashing frontend card grids.
- Unbounded inputs and stalled upstream requests: Without strict character caps, rate limiting, and explicit request timeouts, a single long prompt or slow upstream model call hangs the UI indefinitely or exhausts API quotas.
- Scope creep during hackathon builds: Jumping straight into code without a written specification often leads to half-finished auth systems or unverified UI states.
3. The Approach#
I built Delulu CEO using a strict plan-first, spec-driven methodology, authoring devpost/scope.md, devpost/prd.md, devpost/spec.md, and devpost/checklist.md before implementing five vertical slices:
- Provider Adapter Pattern (`PitchProvider`): The route handler (
app/api/pitch/route.ts) depends on an abstractPitchProviderinterface (lib/ai/types.ts) implemented byGeminiPitchAdapter(lib/ai/providers/gemini-adapter.ts), allowing unit tests to inject deterministic mock providers without hitting live network endpoints. - Dual-Layer Schema Validation: We combine Google Gemini's native structured output config (
responseMimeType: "application/json"+ explicitresponseSchema) with server-side Zod validation (PitchResponseSchema.safeParse()), guaranteeing that every field is a non-empty trimmed string before returning200 OK. - Stateless Client-Side Export: Both the formatted text export (
lib/clipboard/format-pitch.ts) and the 1080×1350 portrait PNG generator (lib/share-card/render-share-card.ts) execute in the browser without storing user confessions on a server.
| Guardrail Layer | Implementation File | Enforcement Rule |
|---|---|---|
| Request Input Bounds | lib/validation/pitch-request.ts | Trimmed non-empty string, max(1000) characters enforced on client & server |
| Sliding-Window Rate Limiter | lib/security/rate-limit.ts | 15 requests per 60,000ms window per IP with automatic map eviction |
| Upstream Timeout | lib/ai/generate-pitch.ts | 15,000ms AbortController signal passed into generatePitch() |
| Output Contract | gemini-adapter.ts + pitch-response.ts | Gemini Type.OBJECT schema + Zod PitchResponseSchema.safeParse() |
4. System Architecture#
The request lifecycle flows through a five-stage pipeline from client validation to server-side rate limiting, provider execution, Zod verification, and multi-format client export.
1,000-char counter, client Zod check, and accessible aria-live loading status
Renders 4 satire cards, clipboard plain-text copy, and 1080×1350 Canvas PNG download
15 requests / 60s window per IP with periodic expired-key cleanup
Rejects empty, whitespace-only, or >1,000 character payloads with HTTP 400
Enforces system prompt rules, maxOutputTokens: 800, and native Type.OBJECT responseSchema
Verifies all 6 fields are non-empty trimmed strings via PitchResponseSchema.safeParse()
5. Engineering Deep Dive#
5.1 Constrained Generation in `GeminiPitchAdapter`#
In lib/ai/providers/gemini-adapter.ts, the adapter treats the user's confession as untrusted data (explicitly instructing the model in rule 6 not to obey prompt-injection instructions inside the confession) and configures @google/genai with responseMimeType: "application/json" and a strict Type.OBJECT responseSchema:
import { GoogleGenAI, Type } from "@google/genai";
import { PitchProvider } from "../types";
export class GeminiPitchAdapter implements PitchProvider {
private client: GoogleGenAI | null = null;
private modelName: string;
constructor(apiKey?: string, modelName: string = "gemini-3.8-flash") {
const key = apiKey || process.env.AI_API_KEY || process.env.GEMINI_API_KEY;
if (key && key !== "your_gemini_api_key_here") {
this.client = new GoogleGenAI({ apiKey: key });
}
this.modelName = modelName;
}
async generatePitch(confession: string, signal?: AbortSignal): Promise<unknown> {
if (!this.client) {
throw new Error("API_KEY is not configured on the server.");
}
if (signal?.aborted) {
throw new Error("Request was aborted before provider execution.");
}
const response = await this.client.models.generateContent({
model: this.modelName,
contents: [
{
role: "user",
parts: [{ text: `Confession to turn into a startup pitch:\n"${confession}"` }],
},
],
config: {
systemInstruction: SYSTEM_PROMPT,
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
startupName: { type: Type.STRING },
startupConcept: { type: Type.STRING },
investmentRationale: { type: Type.STRING },
forbesHeadline: { type: Type.STRING },
riskAnalysis: { type: Type.STRING },
ceoVerdict: { type: Type.STRING },
},
required: [
"startupName",
"startupConcept",
"investmentRationale",
"forbesHeadline",
"riskAnalysis",
"ceoVerdict",
],
},
maxOutputTokens: 800,
temperature: 0.85,
},
});
if (!response.text) {
throw new Error("Provider returned an empty response.");
}
return JSON.parse(response.text);
}
}5.2 Runtime Zod Verification (`lib/validation/pitch-response.ts`)#
Even when an LLM API enforces a JSON schema at token-sampling time, it can still emit whitespace-only strings (" ") if generation degrades. PitchResponseSchema ensures every single card field contains visible text after .trim() before the API route returns a 200 OK response:
import { z } from "zod";
export const PitchResponseSchema = z.object({
startupName: z.string().trim().min(1, { message: "Startup name is required" }),
startupConcept: z.string().trim().min(1, { message: "Startup concept is required" }),
investmentRationale: z.string().trim().min(1, { message: "Investment rationale is required" }),
forbesHeadline: z.string().trim().min(1, { message: "Forbes headline is required" }),
riskAnalysis: z.string().trim().min(1, { message: "Risk analysis is required" }),
ceoVerdict: z.string().trim().min(1, { message: "CEO verdict is required" }),
});
export type PitchResponse = z.infer<typeof PitchResponseSchema>;5.3 Bounded In-Memory Rate Limiter (`lib/security/rate-limit.ts`)#
To protect the API key during live demonstrations without introducing Redis infrastructure for a stateless PoC, checkRateLimit() tracks request counts per IP across a 60-second window (MAX_REQUESTS_PER_WINDOW = 15) and periodically evicts expired entries when the map exceeds 1,000 keys:
interface RateLimitRecord {
count: number;
resetTime: number;
}
const ipRequestStore = new Map<string, RateLimitRecord>();
const WINDOW_MS = 60 * 1000;
const MAX_REQUESTS_PER_WINDOW = 15;
export function checkRateLimit(ip: string): { allowed: boolean; remaining: number } {
const now = Date.now();
const record = ipRequestStore.get(ip);
if (ipRequestStore.size > 1000) {
ipRequestStore.forEach((val, key) => {
if (now > val.resetTime) ipRequestStore.delete(key);
});
}
if (!record || now > record.resetTime) {
ipRequestStore.set(ip, { count: 1, resetTime: now + WINDOW_MS });
return { allowed: true, remaining: MAX_REQUESTS_PER_WINDOW - 1 };
}
if (record.count >= MAX_REQUESTS_PER_WINDOW) {
return { allowed: false, remaining: 0 };
}
record.count += 1;
return { allowed: true, remaining: MAX_REQUESTS_PER_WINDOW - record.count };
}6. Technical Demo#
Technical walkthrough recording coming soon
Walkthrough of Delulu CEO's spec-driven engineering flow: input bounds, POST /api/pitch orchestration, dual-layer Gemini + Zod schema validation, and the 1080×1350 HTML5 Canvas share-card renderer.
Walkthrough Sequence & Checkpoints
- 00:00Plan-First Spec Workflow (Scope → PRD → Spec → Slices) — How defining explicit boundaries in devpost/ prevented scope creep and guided implementation.
- 01:05Dual-Layer Schema Validation (Gemini + Zod) — Why native responseSchema alone is not enough and how PitchResponseSchema.safeParse() guards the UI.
- 02:15Abuse Prevention: Rate Limiting & 15s AbortController — Inspecting lib/security/rate-limit.ts and upstream stall protection.
- 03:10Client-Side 1080×1350 Canvas Share Card & Clipboard Loop — Exporting formatted plain text and creator-ready portrait PNGs without server storage.
View Written Walkthrough Summary / Transcript ▾
Delulu CEO takes a playful premise—turning everyday questionable habits or impulsive purchases into deadpan, Series A-backed startup pitch decks—and uses it as a vehicle for practicing a disciplined, spec-driven AI engineering workflow.
Before writing application code, I authored four planning artifacts in devpost/: scope.md, prd.md, spec.md, and checklist.md. That planning phase established strict non-goals (zero user accounts, zero database persistence, and a hard 1,000-character input cap) so the proof of concept could be finished and verified cleanly.
On the backend, POST /api/pitch enforces an in-memory sliding-window IP rate limiter (15 requests/minute), a 15-second AbortController timeout, and double-layer schema validation: Gemini's native JSON responseSchema paired with server-side Zod safeParse verification.
7. Challenges and Trade-offs#
- Privacy-Preserving Share Cards: When designing Slice 5 (the downloadable 1080×1350 portrait PNG for social sharing), we realized users wanted to share the funny generated Startup Name, Forbes Headline, and CEO Verdict, but often did not want their raw personal confession printed on the image. Excluding the original confession from
render-share-card.tsmade the exported PNG both cleaner and safer to post publicly. - Running Automated Tests Under Node Native ESM Without TS Transpilation Overhead: Rather than adding heavy Jest/Babel dependencies, the test suite uses Node's built-in test runner (
node --test). As noted indevpost/checklist.md, we structuredtests/api/pitch-route.test.mjssonpm testruns cleanly in native Node ESM without requiring a separate TypeScript compilation step. - In-Memory Rate Limiter Scope: An in-memory
Mapresets across serverless cold starts. For a single-process local demonstration or small hackathon PoC, this trade-off avoided external database configuration while still blocking rapid-fire button spamming within warm instances.
8. Testing and Validation#
- Automated Test Suite (`npm test`): Executed via Node's native test runner (
node --test), verifying request validation boundaries (empty strings, >1,000-character strings), response schema validation (PitchResponseSchema), plain-text clipboard formatting (formatPitchwith zero bracket placeholders), and route error envelopes. - Production Build Check: Verified zero TypeScript or Next.js build errors via
npm run build. - Interactive Architecture Map: Generated
devpost/app-map.htmldirectly from the finished codebase to document the end-to-end data flow across all five slices.
9. What I Learned#
- Spec-driven slices eliminate mid-build Thrashing: Writing
scope.md,prd.md,spec.md, andchecklist.mdbefore touchingapp/page.tsxkept every commit focused on a single verifiable slice and prevented feature creep. - Always pair provider-level structured output with application-level Zod validation: Treating the LLM adapter return type as
Promise<unknown>and narrowing it only throughPitchResponseSchema.safeParse()guarantees type safety and runtime resilience regardless of which AI provider is swapped in.
10. Future Improvements#
- Distributed Upstash/Redis Rate Limiting: Replace the single-process
Mapinlib/security/rate-limit.tswith a sliding-window counter backed by Redis for multi-region serverless deployments. - Side-by-Side Pitch Comparison: Allow users to compare two different "Pivot" angles for the same confession using parallel seeded temperature calls.