Skip to content

A production-ready SaaS platform that unifies multiple AI models (GPT-4, Claude, Gemini, DeepSeek, and more) into a single, powerful chat interface.

License

Notifications You must be signed in to change notification settings

Pratham-Prog861/mi-chat

Repository files navigation

MI Chat - Multi-Model AI Chat Platform

One Platform. All AI Models.

A production-ready SaaS platform that unifies multiple AI models (GPT-4, Claude, Gemini, DeepSeek, and more) into a single, powerful chat interface.


✨ Features

πŸ€– Core Features

  • Multiple AI Models - Access GPT-4, Claude 3.5, Gemini 2.0, DeepSeek R1, Qwen3 Coder, and more
  • Instant Model Switching - Switch between different AI models mid-conversation
  • Real-time Streaming - Fast, real-time responses with streaming support
  • Conversation Management - Save, organize, and revisit all your conversations
  • Smart Context - AI maintains conversation context for relevant responses

πŸ’Ž Premium Features

  • Credit System - Flexible pay-as-you-use pricing model
  • Usage Analytics - Track AI usage, token consumption, and costs
  • Rate Limiting - Fair usage policies with tier-based limits
  • Secure Authentication - Enterprise-grade auth powered by Clerk
  • Dark Theme - Beautiful dark UI with glassmorphism effects

🎨 Design & UX

  • Modern Bento Grid - Eye-catching asymmetric layout
  • Animated Components - Smooth animations with Framer Motion
  • Responsive Design - Perfect on desktop, tablet, and mobile
  • Premium UI - Built with shadcn/ui and Aceternity UI components
  • Accessibility - WCAG compliant with keyboard navigation

πŸ› οΈ Tech Stack

Frontend

Backend

  • Authentication: Clerk
  • Database: Supabase (PostgreSQL)
  • AI Gateway: OpenRouter
  • API: Next.js API Routes with Edge Runtime

Deployment

  • Hosting: Vercel
  • CI/CD: GitHub Actions (optional)
  • Analytics: Vercel Analytics (optional)

πŸ“ Project Structure

mi-chat/
β”œβ”€β”€ public/                   # Static assets
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ (public)/        # Public landing page
β”‚   β”‚   β”œβ”€β”€ (auth)/          # Authentication pages
β”‚   β”‚   β”‚   β”œβ”€β”€ sign-in/
β”‚   β”‚   β”‚   └── sign-up/
β”‚   β”‚   β”œβ”€β”€ (app)/           # Protected app routes
β”‚   β”‚   β”‚   └── chat/        # Main chat interface
β”‚   β”‚   β”œβ”€β”€ api/             # API routes
β”‚   β”‚   β”‚   β”œβ”€β”€ chat/        # Streaming chat endpoint
β”‚   β”‚   β”‚   └── webhook/     # Clerk webhooks
β”‚   β”‚   β”œβ”€β”€ layout.tsx       # Root layout
β”‚   β”‚   └── globals.css      # Global styles
β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”œβ”€β”€ ui/              # shadcn/ui base components
β”‚   β”‚   β”‚   β”œβ”€β”€ button.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ card.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ dialog.tsx
β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   β”œβ”€β”€ chat/            # Chat-specific components
β”‚   β”‚   β”‚   β”œβ”€β”€ chat-input.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ chat-sidebar.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ message-item.tsx
β”‚   β”‚   β”‚   └── message-list.tsx
β”‚   β”‚   └── landing/         # Landing page sections
β”‚   β”‚       β”œβ”€β”€ hero.tsx
β”‚   β”‚       β”œβ”€β”€ features.tsx
β”‚   β”‚       β”œβ”€β”€ pricing.tsx
β”‚   β”‚       └── navbar.tsx
β”‚   β”œβ”€β”€ lib/
β”‚   β”‚   β”œβ”€β”€ ai/              # AI integration
β”‚   β”‚   β”‚   └── openrouter.ts
β”‚   β”‚   β”œβ”€β”€ db/              # Database layer
β”‚   β”‚   β”‚   β”œβ”€β”€ supabase.ts
β”‚   β”‚   β”‚   └── queries.ts
β”‚   β”‚   β”œβ”€β”€ rate-limit.ts    # Rate limiting logic
β”‚   β”‚   └── utils.ts         # Utility functions
β”‚   β”œβ”€β”€ actions/             # Server actions
β”‚   β”‚   β”œβ”€β”€ conversations.ts
β”‚   β”‚   └── messages.ts
β”‚   β”œβ”€β”€ hooks/               # Custom React hooks
β”‚   β”‚   └── use-chat.ts
β”‚   β”œβ”€β”€ types/               # TypeScript definitions
β”‚   β”‚   └── index.ts
β”‚   └── middleware.ts        # Next.js middleware
β”œβ”€β”€ supabase-schema.sql      # Database schema
β”œβ”€β”€ components.json          # shadcn/ui config
β”œβ”€β”€ tailwind.config.ts       # Tailwind configuration
β”œβ”€β”€ tsconfig.json            # TypeScript configuration
└── next.config.ts           # Next.js configuration

πŸš€ Getting Started

Prerequisites

  • Node.js 18.17 or later
  • npm or yarn or pnpm
  • Clerk Account (for authentication)
  • Supabase Account (for database)
  • OpenRouter Account (for AI models)

1. Clone the Repository

git clone https://github.com/pratham-prog861/mi-chat.git
cd mi-chat

2. Install Dependencies

npm install
# or
yarn install
# or
pnpm install

3. Set Up Clerk Authentication

  1. Go to clerk.com and create a new application
  2. Select Email/Password and Google as authentication methods
  3. Navigate to API Keys in your Clerk dashboard
  4. Copy your keys to .env.local:
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...
CLERK_SECRET_KEY=sk_test_...
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up

4. Set Up Supabase Database

  1. Create a new project at supabase.com
  2. Wait for your database to be provisioned
  3. Go to SQL Editor in your Supabase dashboard
  4. Copy and run the entire contents of supabase-schema.sql
  5. Navigate to Settings > API to get your keys
  6. Copy your connection details to .env.local:
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Note: Keep your SUPABASE_SERVICE_ROLE_KEY secret! Never expose it in client-side code.

5. Set Up OpenRouter

  1. Sign up at openrouter.ai
  2. Add credits to your account (minimum $5 recommended)
  3. Navigate to Keys and create a new API key
  4. Add to .env.local:
OPENROUTER_API_KEY=sk-or-v1-...

6. Configure Environment Variables

Create a .env.local file in the root directory:

cp .env.example .env.local

Update all values with your actual credentials:

# Clerk Authentication
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...
CLERK_SECRET_KEY=sk_test_...
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up

# Supabase Database
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key

# OpenRouter AI
OPENROUTER_API_KEY=sk-or-v1-...

# App Configuration
NEXT_PUBLIC_APP_URL=http://localhost:3000

7. Run Development Server

npm run dev

Open http://localhost:3000 in your browser to see the application!

8. Build for Production

npm run build
npm start

Environment Variables

Variable Description Required
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY Clerk publishable key βœ…
CLERK_SECRET_KEY Clerk secret key βœ…
NEXT_PUBLIC_SUPABASE_URL Supabase project URL βœ…
NEXT_PUBLIC_SUPABASE_ANON_KEY Supabase anonymous key βœ…
SUPABASE_SERVICE_ROLE_KEY Supabase service role key βœ…
OPENROUTER_API_KEY OpenRouter API key βœ…
NEXT_PUBLIC_APP_URL Your app URL βœ…

Database Schema

The application uses the following tables:

  • users - User accounts with credits and plan information
  • conversations - Chat conversations
  • messages - Individual messages in conversations
  • usage_logs - Track token usage and credits

See supabase-schema.sql for the complete schema.

πŸ“Š Available AI Models

The platform currently supports the following free models via OpenRouter:

Model Provider Description Best For
DeepSeek R1 DeepSeek Advanced reasoning model Complex problem-solving
Qwen3 Coder Qwen Specialized coding model Programming tasks
Gemma 3 27B Google Instruction following General conversations
GPT-OSS 120B OpenAI OSS Fast responses Quick queries
GLM 4.5 Air Z-AI Lightweight & efficient Simple tasks
Gemini 2.0 Flash Google Ultra-fast processing Speed-critical tasks

Adding Custom Models

Models can be easily added or modified in src/lib/ai/openrouter.ts:

export const AVAILABLE_MODELS = [
  {
    id: "provider/model-name:free",
    name: "Model Name",
    category: "Pro",
    description: "Model description",
    free: true,
    badge: "New",
  },
  // Add more models...
];

🎯 Features Overview

🏠 Landing Page

  • Hero Section

    • Animated spotlight effects
    • Sparkles particle animation
    • Call-to-action buttons
    • Feature badges
  • Features Section

    • Modern bento grid layout (4Γ—4)
    • Asymmetric card sizes
    • Gradient icon backgrounds
    • Hover animations with glow effects
    • Responsive design
  • Pricing Section

    • Free and Pro tier comparison
    • Credit-based pricing model
    • Feature lists with checkmarks
    • Glassmorphism cards

πŸ’¬ Chat Interface

  • Conversation Sidebar

    • List of all conversations
    • Create new conversation
    • Delete conversations
    • Auto-update on changes
  • Message Display

    • User and assistant messages
    • Markdown rendering support
    • Code syntax highlighting
    • Copy message functionality
    • Streaming message indicator
  • Input & Controls

    • Multi-line text input
    • AI model selector dropdown
    • Credit balance display
    • Send button with loading state
    • Keyboard shortcuts (Enter to send)

πŸ’³ Credit & Subscription System

Plan Credits Messages/Min Tokens/Min Price
Free 100 5 10,000 $0
Pro 10,000/month 50 100,000 $19/month

Credit Calculation:

  • 1 credit = ~100 tokens
  • Tokens used = prompt tokens + completion tokens
  • Credits automatically deducted after each message

πŸ”’ Security Features

  • Authentication

    • Clerk-powered auth
    • Email/password & Google OAuth
    • Protected API routes
    • Session management
  • Database Security

    • Row Level Security (RLS) policies
    • Service role key for server operations
    • User ownership validation
    • SQL injection prevention
  • Rate Limiting

    • Per-user message limits
    • Token usage caps
    • In-memory rate limit store
    • Automatic reset after 60 seconds

🚒 Deployment

Deploy to Vercel (Recommended)

  1. Push to GitHub

    git add .
    git commit -m "Initial commit"
    git push origin main
  2. Import to Vercel

    • Go to vercel.com
    • Click "New Project"
    • Import your GitHub repository
    • Vercel will auto-detect Next.js
  3. Configure Environment Variables

    • Add all environment variables from .env.local
    • Make sure to use production URLs and keys
  4. Deploy

    • Click "Deploy"
    • Your app will be live in minutes!
  5. Post-Deployment

    • Update NEXT_PUBLIC_APP_URL to your Vercel domain
    • Update Clerk redirect URLs
    • Configure Clerk webhook to point to your domain

Manual Build

# Install dependencies
npm install

# Build the application
npm run build

# Start production server
npm start

Development

# Development mode
npm run dev

# Build for production
npm run build

# Start production server
npm start

# Lint code
npm run lint

Security

  • API keys stored server-side only
  • Row Level Security (RLS) enabled in Supabase
  • User ownership validated on all queries
  • Rate limiting prevents abuse
  • Clerk handles authentication securely

πŸ”§ Customization

Adding New AI Models

Edit src/lib/ai/openrouter.ts:

export const AVAILABLE_MODELS = [
  {
    id: "provider/model-name",
    name: "Model Display Name",
    category: "Pro", // or "Fast", "Thinking"
    description: "Brief description",
    free: true, // or false for paid models
    badge: "New", // or "Recommended", "Rate Limited"
  },
  // Add more models...
];

Modifying Credit Costs

Edit src/lib/rate-limit.ts:

export function calculateCreditsUsed(tokens: number): number {
  // Change the ratio (currently 1 credit per 100 tokens)
  return Math.ceil(tokens / 100);
}

Adjusting Rate Limits

Edit src/types/index.ts:

export const PLAN_CONFIGS: Record<
  UserPlan,
  { credits: number; rateLimit: RateLimitConfig }
> = {
  free: {
    credits: 100, // Initial free credits
    rateLimit: {
      messagesPerMinute: 5, // Max messages per minute
      tokensPerMinute: 10000, // Max tokens per minute
    },
  },
  pro: {
    credits: 10000,
    rateLimit: {
      messagesPerMinute: 50,
      tokensPerMinute: 100000,
    },
  },
};

Customizing UI Theme

Edit src/app/globals.css:

@layer base {
  :root {
    --background: 0 0% 100%;
    --foreground: 240 10% 3.9%;
    /* Modify other CSS variables... */
  }

  .dark {
    --background: 0 0% 0%;
    --foreground: 0 0% 98%;
    /* Modify dark theme colors... */
  }
}

Adding Custom Components

  1. Install shadcn/ui component:

    npx shadcn-ui@latest add [component-name]
  2. Import and use in your files:

    import { ComponentName } from "@/components/ui/component-name";
    

πŸ› Troubleshooting

Common Issues

"Missing environment variable" error

  • Solution: Ensure all required env vars are set in .env.local
  • Restart dev server after adding environment variables
  • Check for typos in variable names

Database connection issues

  • Solution:
    • Verify Supabase credentials are correct
    • Ensure database schema is properly created
    • Check if service role key is used for server-side operations
    • Test connection in Supabase dashboard

Authentication not working

  • Solution:
    • Verify Clerk API keys
    • Check if redirect URLs are configured correctly
    • Clear browser cookies and try again
    • Ensure webhooks are properly configured

Streaming responses not working

  • Solution:
    • Check OpenRouter API key is valid
    • Verify you have credits in OpenRouter account
    • Ensure Edge runtime is enabled in API route
    • Check browser console for errors

Rate limiting errors

  • Solution:
    • Wait 60 seconds for rate limit to reset
    • Upgrade to Pro plan for higher limits
    • Check rate limit configuration in code

Build failures

  • Solution:
    • Clear .next folder: rm -rf .next
    • Delete node_modules and reinstall: rm -rf node_modules && npm install
    • Check TypeScript errors: npm run type-check
    • Ensure all environment variables are set

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

About

A production-ready SaaS platform that unifies multiple AI models (GPT-4, Claude, Gemini, DeepSeek, and more) into a single, powerful chat interface.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published