Skip to content

yashrajoria/AI-Platform

Repository files navigation

Genesis — AI Platform

A full-stack, multi-tool AI SaaS platform that lets users generate conversations, images, videos, music, and code — all from a single dashboard. Built with Next.js 14, Clerk authentication, Stripe billing, OpenAI, and Replicate.


Table of Contents


Overview

Genesis is an AI-powered Software-as-a-Service (SaaS) platform that consolidates five popular AI generation capabilities into one seamless interface:

Capability Underlying Model
Conversation OpenAI GPT-3.5 Turbo
Image Generation OpenAI DALL-E
Video Generation Replicate — Zeroscope
Music Generation Replicate — Riffusion
Code Generation OpenAI GPT-3.5 Turbo

New users receive 10 free API calls across all tools. A monthly subscription (powered by Stripe) unlocks unlimited access.


Features

  • 🤖 AI Chat — Multi-turn conversations with GPT-3.5 Turbo.
  • 🖼️ Image Generation — Create images from text prompts with configurable resolution and quantity via DALL-E.
  • 🎬 Video Generation — Generate short video clips from text descriptions using the Zeroscope model on Replicate.
  • 🎵 Music Generation — Compose music from text prompts using the Riffusion model on Replicate.
  • 💻 Code Generation — AI-powered code assistant with syntax-highlighted Markdown output.
  • 🔐 Authentication — Secure sign-up, sign-in, and session management via Clerk.
  • 💳 Stripe Billing — Monthly subscription with a self-service billing portal (upgrade, cancel, manage).
  • 🎁 Free Trial — 10 complimentary API calls tracked per user in PostgreSQL.
  • 📊 API Usage Counter — Visual progress bar showing remaining free-tier usage.
  • 🌗 Theme Support — Light and dark mode via next-themes.
  • 💬 Live Support Widget — Crisp chat widget integrated for user support.
  • 📱 Responsive Design — Mobile-first layout built with Tailwind CSS.

Tech Stack

Frontend

Technology Version Purpose
Next.js 14.1.1 React framework (App Router)
React 18.2.0 UI library
TypeScript 5.2.2 Type safety
Tailwind CSS 3.3.2 Utility-first styling
Radix UI various Accessible headless components
Lucide React 0.259.0 Icon set
Zustand 4.4.1 Client-side state management
React Hook Form 7.45.1 Form handling
Zod 3.21.4 Schema validation
Axios 1.7.4 HTTP client
react-markdown 8.0.7 Markdown rendering for code output
typewriter-effect 2.20.1 Animated hero text
react-hot-toast 2.4.1 Toast notifications
next-themes 0.2.1 Dark/light mode
crisp-sdk-web 1.0.21 Customer support chat

Backend

Technology Version Purpose
Next.js API Routes 14.1.1 Serverless API handlers
Prisma ORM 5.5.2 Database client & migrations
PostgreSQL any Relational database
Clerk 4.29.3 Authentication & user management
Stripe 12.18.0 Payment processing
OpenAI SDK 4.4.0 GPT & DALL-E API client
Replicate 0.12.3 Video & music model inference

Project Structure

AI-Platform/
├── app/                            # Next.js App Router
│   ├── (landing)/                  # Public marketing landing page
│   │   └── page.tsx
│   ├── (auth)/                     # Authentication pages (Clerk hosted UI)
│   │   ├── sign-in/
│   │   └── sign-up/
│   ├── (dashboard)/                # Protected routes (requires login)
│   │   └── (routes)/
│   │       ├── conversation/       # AI chat interface
│   │       ├── image/              # Image generation interface
│   │       ├── video/              # Video generation interface
│   │       ├── music/              # Music generation interface
│   │       ├── code/               # Code generation interface
│   │       └── settings/           # User settings & billing portal
│   └── api/                        # Next.js API route handlers
│       ├── conversation/route.ts   # POST — GPT chat
│       ├── image/route.ts          # POST — DALL-E image generation
│       ├── video/route.ts          # POST — Zeroscope video generation
│       ├── music/route.ts          # POST — Riffusion music generation
│       ├── code/route.ts           # POST — GPT code generation
│       ├── stripe/route.ts         # GET — Stripe checkout / billing portal
│       └── webhook/route.ts        # POST — Stripe webhook handler
├── components/                     # Shared React components (30+)
│   ├── ui/                         # Base UI primitives (button, dialog, etc.)
│   ├── navbar.tsx
│   ├── sidebar.tsx
│   ├── pro-modal.tsx               # Upgrade to Pro modal
│   ├── subscription-button.tsx
│   ├── free-counter.tsx            # API usage progress bar
│   └── ...
├── hooks/                          # Custom React hooks
│   ├── use-pro-modal.ts            # Zustand store for Pro modal state
│   └── ...
├── lib/                            # Shared utilities and server helpers
│   ├── api-limit.ts                # Increment / check free-tier API limit
│   ├── subscription.ts             # Check active Stripe subscription
│   ├── stripe.ts                   # Stripe SDK instance
│   ├── prismadb.ts                 # Singleton Prisma client
│   └── utils.ts                    # Tailwind cn() utility
├── prisma/
│   └── schema.prisma               # Database schema (UserApiLimit, UserSubscription)
├── public/                         # Static assets (images, icons)
├── constants.ts                    # App-wide constants (MAX_FREE_COUNTS = 10)
├── middleware.ts                   # Clerk auth middleware
├── next.config.js                  # Next.js configuration
├── tailwind.config.ts              # Tailwind CSS configuration
├── tsconfig.json                   # TypeScript configuration
└── package.json

Prerequisites

Before getting started, make sure the following are installed and available:

You will also need accounts and API keys for:


Environment Variables

Create a .env file in the project root and populate it with the following variables:

# ─── Database ─────────────────────────────────────────────────────────────────
DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE"

# ─── Clerk Authentication ─────────────────────────────────────────────────────
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_live_...
CLERK_SECRET_KEY=sk_live_...

# Clerk redirect paths (optional — defaults shown)
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/dashboard
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/dashboard

# ─── OpenAI ───────────────────────────────────────────────────────────────────
OPENAI_API_KEY=sk-...

# ─── Replicate ────────────────────────────────────────────────────────────────
REPLICATE_API_TOKEN=r8_...

# ─── Stripe ───────────────────────────────────────────────────────────────────
STRIPE_KEY=sk_live_...
STRIPE_WEBHOOK_SECRET=whsec_...

# ─── App URL (used for Stripe redirect) ───────────────────────────────────────
NEXT_PUBLIC_APP_URL=http://localhost:3000

Security: Never commit .env to version control. Add it to .gitignore.


Installation

# 1. Clone the repository
git clone https://github.com/yashrajoria/AI-Platform.git
cd AI-Platform

# 2. Install dependencies (also runs `prisma generate` via postinstall)
npm install

Running the Application

Development

npm run dev

The app will be available at http://localhost:3000.

Production

# Build the Next.js application
npm run build

# Start the production server
npm run start

Database Setup

This project uses Prisma with PostgreSQL.

1. Apply the database schema

# Push the Prisma schema to your database (creates tables)
npx prisma db push

2. (Optional) Open Prisma Studio

npx prisma studio

Prisma Studio provides a visual interface for browsing and editing your database at http://localhost:5555.

Database Schema

// Tracks free-tier API usage per user
model UserApiLimit {
  id        String   @id @default(cuid())
  userId    String   @unique          // Clerk user ID
  count     Int      @default(0)      // Number of API calls made
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

// Stores Stripe subscription data per user
model UserSubscription {
  id                     String    @id @default(cuid())
  userId                 String    @unique
  stripeCustomerId       String?   @unique
  stripeSubscriptionId   String?   @unique
  stripePriceId          String?
  stripeCurrentPeriodEnd DateTime?
}

API Reference

All API routes require a valid Clerk session cookie (authenticated user) except /api/webhook.

POST /api/conversation

Chat with the GPT-3.5 Turbo model.

Request body:

{
  "messages": [
    { "role": "user", "content": "Explain quantum computing in simple terms." }
  ]
}

Response: OpenAI ChatCompletion message object.


POST /api/image

Generate images using DALL-E.

Request body:

{
  "prompt": "A futuristic city skyline at sunset",
  "amount": "1",
  "resolution": "512x512"
}
Field Type Options Default
prompt string any text required
amount string "1""5" required
resolution string "256x256", "512x512", "1024x1024" required

Response: Array of image objects [{ url: string }].


POST /api/video

Generate a short video clip using Replicate's Zeroscope model.

Request body:

{
  "prompt": "A dog running on the beach"
}

Response: Array of video URLs [string].


POST /api/music

Generate music using Replicate's Riffusion model.

Request body:

{
  "prompt": "An upbeat jazz melody"
}

Response: Object with an audio URL { audio: string }.


POST /api/code

Generate code using GPT-3.5 Turbo with a system prompt for code output.

Request body:

{
  "messages": [
    { "role": "user", "content": "Write a Python function to reverse a string." }
  ]
}

Response: OpenAI ChatCompletion message object (content rendered as Markdown).


GET /api/stripe

Create a Stripe Checkout session (new subscribers) or open the Stripe Billing Portal (existing subscribers).

Response: { url: string } — redirect URL for Stripe-hosted page.


POST /api/webhook

Stripe webhook handler. Processes checkout.session.completed and invoice.payment_succeeded events to create or update UserSubscription records.

This route is public (no Clerk auth required). Requests are verified using the STRIPE_WEBHOOK_SECRET.


Authentication

Authentication is managed by Clerk. The middleware.ts file protects all routes by default:

export default authMiddleware({
  publicRoutes: ["/", "/api/webhook"],
});
  • / (landing page) and /api/webhook (Stripe webhook) are the only public routes.
  • All other routes — including all /api/* routes — require an active Clerk session.
  • Clerk provides hosted sign-in and sign-up UIs at /sign-in and /sign-up.

Subscription & Billing

Billing is handled by Stripe:

  1. Upgrade flow — A user clicks "Upgrade" which calls GET /api/stripe, creating a Stripe Checkout session and redirecting the user to Stripe's hosted payment page.
  2. Webhook — On successful payment, Stripe sends a webhook to POST /api/webhook. The handler stores or updates the UserSubscription record in PostgreSQL.
  3. Billing Portal — Existing subscribers calling GET /api/stripe are redirected to the Stripe Customer Portal to manage or cancel their subscription.
  4. Subscription check — Before every AI API call, lib/subscription.ts queries the UserSubscription table to confirm the subscription is active (i.e., stripeCurrentPeriodEnd is in the future).

Setting up Stripe Webhooks locally

# Install the Stripe CLI
brew install stripe/stripe-cli/stripe

# Log in
stripe login

# Forward webhooks to your local dev server
stripe listen --forward-to localhost:3000/api/webhook

Copy the webhook signing secret printed by the CLI and set it as STRIPE_WEBHOOK_SECRET in your .env.


Free Tier Limits

Non-subscribed users can make 10 free API calls across all AI tools combined. This is controlled by:

  • constants.tsMAX_FREE_COUNTS = 10
  • lib/api-limit.tsincrementApiLimit() and checkApiLimit() functions that read/write the UserApiLimit table.
  • Every AI API route calls checkApiLimit() before processing and returns HTTP 403 when the limit is exceeded.
  • The <FreeCounter /> component in the sidebar displays a progress bar of remaining free calls.

To change the free-tier limit, update MAX_FREE_COUNTS in constants.ts.


Deployment

Vercel (Recommended)

Deploy with Vercel

  1. Push your code to GitHub.
  2. Import the repository in Vercel.
  3. Add all environment variables from the Environment Variables section to the Vercel project settings.
  4. Set NEXT_PUBLIC_APP_URL to your Vercel production URL (e.g., https://your-app.vercel.app).
  5. Deploy.

Other Platforms

The app is a standard Next.js application and can be deployed on any platform that supports Node.js:

For non-Vercel deployments, ensure the production server can handle long-running Replicate inference requests (video/music generation can take 30–60 seconds).

Database in Production

Use a managed PostgreSQL provider:

Provider Notes
Supabase Free tier available, easy setup
Neon Serverless Postgres, Vercel-friendly
Railway Postgres add-on available

After provisioning, set DATABASE_URL and run:

npx prisma db push

Scripts

Command Description
npm run dev Start the Next.js development server with hot reload
npm run build Build the application for production
npm run start Start the production server (requires build first)
npm run lint Run ESLint across the codebase
npm run postinstall Automatically runs prisma generate after npm install

Contributing

Contributions are welcome! To get started:

  1. Fork the repository.
  2. Create a branch for your feature or bug fix:
    git checkout -b feature/your-feature-name
  3. Make your changes and ensure the app runs without errors:
    npm run dev
    npm run lint
  4. Commit your changes with a descriptive message:
    git commit -m "feat: add your feature description"
  5. Push to your fork and open a Pull Request.

Code Style

  • TypeScript is enforced throughout — avoid any types where possible.
  • Follow the existing component structure in /components.
  • Use the cn() utility from lib/utils.ts for conditional Tailwind classes.
  • API route handlers should always verify authentication via Clerk and check checkApiLimit() or checkSubscription() before calling any external AI API.

License

This project is licensed under the MIT License.


Built with Next.js, OpenAI, Replicate, Clerk, and Stripe.

About

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors