Here's a comprehensive implementation for multi-character support and tiered subscriptions:
1. Character Management System
Database Schema
// Character Model (MongoDB)
const characterSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
name: { type: String, required: true },
avatar: String, // URL to stored image
description: String,
language: { type: String, required: true }, // e.g., 'hindi', 'tamil'
personality: { type: String, default: 'friendly' }, // e.g., 'sarcastic', 'wise'
visibility: { type: String, enum: ['public', 'private'], default: 'private' },
createdAt: { type: Date, default: Date.now },
});
// Usage Tracking Model
const usageSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
month: { type: Date, default: startOfMonth(new Date()) },
voiceMessagesUsed: { type: Number, default: 0 },
charactersCreated: { type: Number, default: 0 },
});
Character Creation API
// POST /api/characters
app.post('/api/characters', authenticate, async (req, res) => {
const { name, avatar, description, language, personality } = req.body;
const userId = req.user.userId;
// Check subscription limits
const subscription = await Subscription.findOne({ user: userId });
const tierLimits = getTierLimits(subscription?.tier || 'free');
// Check character count
const currentCount = await Character.countDocuments({ user: userId });
if (currentCount >= tierLimits.maxCharacters) {
return res.status(403).json({
error: `Max ${tierLimits.maxCharacters} characters allowed on ${subscription?.tier || 'free'} tier`
});
}
// Create character
const character = await Character.create({
user: userId,
name,
avatar,
description,
language,
personality,
});
// Update usage
await Usage.updateOne(
{ user: userId, month: startOfMonth(new Date()) },
{ $inc: { charactersCreated: 1 } },
{ upsert: true }
);
res.status(201).json(character);
});
Frontend Character Dashboard
// CharacterDashboard.jsx
import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
function CharacterDashboard() {
const [characters, setCharacters] = useState([]);
const [subscription, setSubscription] = useState({ tier: 'free' });
const [usage, setUsage] = useState({ charactersCreated: 0 });
useEffect(() => {
// Fetch data
Promise.all([
fetch('/api/characters').then(res => res.json()),
fetch('/api/subscription').then(res => res.json()),
fetch('/api/usage').then(res => res.json()),
]).then(([chars, sub, use]) => {
setCharacters(chars);
setSubscription(sub);
setUsage(use);
});
}, []);
// Get tier limits
const tierLimits = {
free: { maxCharacters: 3, maxVoice: 50 },
pro: { maxCharacters: 10, maxVoice: 200 },
premium: { maxCharacters: 50, maxVoice: Infinity },
}[subscription.tier];
return (
<div className="dashboard">
<div className="header">
<h2>Your Characters ({characters.length}/{tierLimits.maxCharacters})</h2>
<div className="subscription-badge">
Tier: {subscription.tier.toUpperCase()}
{subscription.tier === 'free' && (
<Link to="/upgrade">Upgrade Plan</Link>
)}
</div>
</div>
<div className="characters-grid">
{characters.map(char => (
<div key={char._id} className="character-card">
<img src={char.avatar} alt={char.name} />
<h3>{char.name}</h3>
<p>Language: {char.language}</p>
<p>Personality: {char.personality}</p>
<Link to={`/chat/${char._id}`}>Chat</Link>
</div>
))}
{characters.length < tierLimits.maxCharacters && (
<div className="create-character">
<Link to="/create-character">
<span>+</span>
<p>Create New Character</p>
</Link>
</div>
)}
</div>
<div className="usage-stats">
<p>Voice Messages Used: {usage.voiceMessagesUsed}/{tierLimits.maxVoice}</p>
</div>
</div>
);
}
2. Tiered Subscription System
Subscription Tiers
// Tier configuration
const tiers = {
free: {
maxCharacters: 3,
maxVoiceMessages: 50,
aiModel: 'basic',
price: 0,
},
pro: {
maxCharacters: 10,
maxVoiceMessages: 200,
aiModel: 'advanced',
price: 299, // INR
},
premium: {
maxCharacters: 50,
maxVoiceMessages: Infinity,
aiModel: 'premium',
price: 599, // INR
},
};
Payment Integration (Stripe Example)
// Backend: Create subscription
app.post('/api/subscriptions', authenticate, async (req, res) => {
const { tier } = req.body;
const user = await User.findById(req.user.userId);
// Get Stripe price ID for tier
const priceIds = {
pro: 'price_1N5X8L2eZvKYlo2C7s8Z7Z7Z',
premium: 'price_1N5X9L2eZvKYlo2C7s8Z7Z7Z',
};
try {
// Create Stripe subscription
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [{
price: priceIds[tier],
quantity: 1,
}],
mode: 'subscription',
success_url: `${process.env.CLIENT_URL}/subscription-success`,
cancel_url: `${process.env.CLIENT_URL}/subscription-canceled`,
customer_email: user.email,
});
res.json({ url: session.url });
} catch (error) {
res.status(500).json({ error: 'Payment failed' });
}
});
Frontend Upgrade Page
// UpgradePage.jsx
import { useState } from 'react';
import { Elements, CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
const stripePromise = loadStripe(process.env.REACT_APP_STRIPE_PUBLIC_KEY);
function UpgradePage() {
const [selectedTier, setSelectedTier] = useState('pro');
const [error, setError] = useState(null);
const stripe = useStripe();
const elements = useElements();
const handleUpgrade = async (e) => {
e.preventDefault();
if (!stripe || !elements) return;
// Create payment method
const { error: stripeError, paymentMethod } = await stripe.createPaymentMethod({
type: 'card',
card: elements.getElement(CardElement),
});
if (stripeError) {
setError(stripeError.message);
return;
}
// Call backend to create subscription
const response = await fetch('/api/subscriptions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tier: selectedTier }),
});
const data = await response.json();
if (data.url) window.location.href = data.url;
};
return (
<div className="upgrade-page">
<h2>Upgrade Your Plan</h2>
<div className="tiers">
<div className={`tier ${selectedTier === 'pro' ? 'selected' : ''}`}>
<h3>Pro</h3>
<p>10 Characters</p>
<p>200 Voice Messages/month</p>
<p>₹299/month</p>
<button onClick={() => setSelectedTier('pro')}>Select</button>
</div>
<div className={`tier ${selectedTier === 'premium' ? 'selected' : ''}`}>
<h3>Premium</h3>
<p>50 Characters</p>
<p>Unlimited Voice</p>
<p>Premium AI Model</p>
<p>₹599/month</p>
<button onClick={() => setSelectedTier('premium')}>Select</button>
</div>
</div>
<form onSubmit={handleUpgrade}>
<CardElement />
{error && <div className="error">{error}</div>}
<button type="submit" disabled={!stripe}>
Upgrade Now
</button>
</form>
</div>
);
}
3. Voice/Chat Feature Integration
AI Model Selection Based on Tier
// Get appropriate AI model for user's tier
function getAIModel(userId) {
const subscription = await Subscription.findOne({ user: userId });
const tierModels = {
free: 'gpt-3.5-turbo',
pro: 'gpt-4',
premium: 'gpt-4-1106-preview',
};
return tierModels[subscription?.tier || 'free'];
}
// Chat API with tier-aware model
app.post('/api/chat', authenticate, async (req, res) => {
const { message, characterId } = req.body;
const character = await Character.findById(characterId);
// Get appropriate model
const model = getAIModel(req.user.userId);
// Call OpenAI with selected model
const completion = await openai.chat.completions.create({
model,
messages: [
{ role: "system", content: `You are ${character.name}, ${character.description}.` },
{ role: "user", content: message }
],
});
res.json({ response: completion.choices[0].message.content });
});
Voice Usage Tracking
// Middleware to track voice usage
const trackVoiceUsage = async (req, res, next) => {
const userId = req.user.userId;
const subscription = await Subscription.findOne({ user: userId });
const tierLimits = getTierLimits(subscription?.tier || 'free');
// Get current month's usage
const usage = await Usage.findOne({
user: userId,
month: startOfMonth(new Date()),
});
if (usage.voiceMessagesUsed >= tierLimits.maxVoice) {
return res.status(403).json({ error: 'Voice message limit reached' });
}
// Increment usage
await Usage.updateOne(
{ _id: usage._id },
{ $inc: { voiceMessagesUsed: 1 } },
{ upsert: true }
);
next();
};
// Apply to voice endpoints
app.post('/api/speech-to-text', authenticate, trackVoiceUsage, ...);
Key Features
-
Character Management:
- Create/edit multiple characters with names, avatars, and personalities
- Public/private visibility controls
- Searchable character list
-
Tiered Subscriptions:
- Free tier: 3 characters, 50 voice messages/month
- Pro tier: 10 characters, 200 voice messages, better AI
- Premium tier: 50 characters, unlimited voice, premium AI
-
Usage Tracking:
- Monthly limits for characters and voice messages
- Clear dashboard showing current usage vs limits
-
Payment Integration:
- Stripe/Payment gateway integration
- Recurring billing
- Upgrade/downgrade functionality
Would you like me to expand on any specific part (e.g., avatar handling, payment gateway setup, or tier feature implementation)?