Skip to main content
08 // ENGINEERING SPECIFICATIONShipped — Build With AI Hackathon

Delulu CEO: Spec-Driven AI Pitch Engine with Dual-Layer Schema Validation

A proof-of-concept AI web application built for the Build With AI: Basics Hackathon using a strict plan-first specification workflow, combining Gemini native JSON responseSchema with server-side Zod validation, sliding-window IP rate limiting, 15s AbortController timeouts, and client-side HTML5 Canvas image export.

Published 2026-10-20Updated 2026-10-268 min readGitHub Repository
Next.js 14TypeScriptGemini API (@google/genai)ZodHTML5 CanvasTailwind CSSNode Test Runner

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:

  1. 01. Startup Pitch: Company name (startupName), business model (startupConcept), and VC FOMO rationale (investmentRationale).
  2. 02. Forbes Cover: Sensationalized headline (forbesHeadline).
  3. 03. Risk Analysis: Obvious personal or financial red flags reframed as competitive moats (riskAnalysis).
  4. 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:

  1. 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.
  2. 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.
  3. 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 abstract PitchProvider interface (lib/ai/types.ts) implemented by GeminiPitchAdapter (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" + explicit responseSchema) with server-side Zod validation (PitchResponseSchema.safeParse()), guaranteeing that every field is a non-empty trimmed string before returning 200 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.
Specification table (Guardrail Layer, Implementation File, Enforcement Rule)
Guardrail LayerImplementation FileEnforcement Rule
Request Input Boundslib/validation/pitch-request.tsTrimmed non-empty string, max(1000) characters enforced on client & server
Sliding-Window Rate Limiterlib/security/rate-limit.ts15 requests per 60,000ms window per IP with automatic map eviction
Upstream Timeoutlib/ai/generate-pitch.ts15,000ms AbortController signal passed into generatePitch()
Output Contractgemini-adapter.ts + pitch-response.tsGemini 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.

SYSTEM SCHEMATIC // DELULU CEO REQUEST PIPELINE & DUAL-LAYER VALIDATION ARCHITECTURE
01. Client Interface & Export Layer (Next.js App Router)
Confession Form & Sample Chips

1,000-char counter, client Zod check, and accessible aria-live loading status

components/confession-form.tsx
2×2 Pitch Deck & Export Actions

Renders 4 satire cards, clipboard plain-text copy, and 1080×1350 Canvas PNG download

pitch-deck.tsx · render-share-card.ts
POST /api/pitch (JSON)
02. API Route Boundary & Abuse Prevention (app/api/pitch/route.ts)
In-Memory IP Rate Limiter

15 requests / 60s window per IP with periodic expired-key cleanup

lib/security/rate-limit.ts
Request Schema Validator

Rejects empty, whitespace-only, or >1,000 character payloads with HTTP 400

lib/validation/pitch-request.ts
Validated Confession + AbortSignal (15s)
03. AI Orchestration & Dual-Layer Schema Verification
Gemini Pitch Adapter

Enforces system prompt rules, maxOutputTokens: 800, and native Type.OBJECT responseSchema

lib/ai/providers/gemini-adapter.ts
Zod Runtime Output Gate

Verifies all 6 fields are non-empty trimmed strings via PitchResponseSchema.safeParse()

lib/validation/pitch-response.ts
Figure: Delulu CEO Request Pipeline & Dual-Layer Validation Architecture

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:

lib/ai/providers/gemini-adapter.tstypescript
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:

lib/validation/pitch-response.tstypescript
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:

lib/security/rate-limit.tstypescript
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 & Verification
Recorded video walkthrough coming soon

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

  1. 00:00
    Plan-First Spec Workflow (Scope → PRD → Spec → Slices) — How defining explicit boundaries in devpost/ prevented scope creep and guided implementation.
  2. 01:05
    Dual-Layer Schema Validation (Gemini + Zod) — Why native responseSchema alone is not enough and how PitchResponseSchema.safeParse() guards the UI.
  3. 02:15
    Abuse Prevention: Rate Limiting & 15s AbortController — Inspecting lib/security/rate-limit.ts and upstream stall protection.
  4. 03:10
    Client-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.ts made 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 in devpost/checklist.md, we structured tests/api/pitch-route.test.mjs so npm test runs cleanly in native Node ESM without requiring a separate TypeScript compilation step.
  • In-Memory Rate Limiter Scope: An in-memory Map resets 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 (formatPitch with 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.html directly 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, and checklist.md before touching app/page.tsx kept 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 through PitchResponseSchema.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 Map in lib/security/rate-limit.ts with 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.