Skip to content

Commit 93aceef

Browse files
feat: add AI-powered explanations with multi-provider support and subscription tiers
1 parent 1804a3b commit 93aceef

File tree

22 files changed

+1901
-67
lines changed

22 files changed

+1901
-67
lines changed

.env.example

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,16 @@ NEXT_PUBLIC_APPWRITE_DATABASE_NAME=
88
NEXT_PUBLIC_APPWRITE_ENDPOINT=
99
NEXT_PUBLIC_APPWRITE_PROJECT_ID=
1010
NEXT_PUBLIC_GA_TRACKING_ID=
11+
# Stripe Configuration
12+
STRIPE_SECRET_KEY=sk_test_...
13+
STRIPE_PUBLISHABLE_KEY=pk_test_...
14+
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
15+
16+
# AI Provider Keys (for Ditectrev premium service)
17+
DITECTREV_OPENAI_KEY=sk-...
18+
DITECTREV_GEMINI_KEY=...
19+
DITECTREV_MISTRAL_KEY=...
20+
DITECTREV_DEEPSEEK_KEY=...
21+
22+
# App Configuration
23+
NEXT_PUBLIC_URL=http://localhost:3000

.vscode/settings.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{}

AI_EXPLANATIONS_README.md

Lines changed: 263 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,263 @@
1+
# AI Explanations Feature
2+
3+
This document describes the new AI-powered explanations feature with multiple providers and subscription tiers.
4+
5+
## 🚀 Features
6+
7+
### Multi-Provider AI Support
8+
9+
- **Ollama** - Local AI explanations (privacy-focused)
10+
- **OpenAI GPT** - Industry-leading AI with your API key
11+
- **Google Gemini** - Google's advanced AI model
12+
- **Mistral AI** - European AI excellence
13+
- **DeepSeek** - Cutting-edge reasoning AI
14+
- **Ditectrev Premium** - Our managed AI service
15+
16+
### Subscription Tiers
17+
18+
#### 1. Ads Free (€1.99/month)
19+
20+
- Remove all advertisements
21+
- Access to all practice questions
22+
- Progress tracking
23+
24+
#### 2. Local Explanations (€2.99/month)
25+
26+
- Everything in Ads Free
27+
- Ollama-powered explanations
28+
- Complete privacy (runs locally)
29+
- No API costs
30+
31+
#### 3. BYOK Explanations (€4.99/month) 🌟 Most Popular
32+
33+
- Everything in Local
34+
- Bring Your Own API Keys
35+
- Access to OpenAI, Gemini, Mistral, DeepSeek
36+
- API key management interface
37+
- Multiple provider options
38+
39+
#### 4. Ditectrev Explanations (€9.99/month)
40+
41+
- Everything in BYOK
42+
- Premium AI models with our infrastructure
43+
- No API key management required
44+
- Unlimited explanations
45+
- Priority support
46+
- Advanced AI features
47+
48+
## 🛠 Technical Implementation
49+
50+
### Architecture
51+
52+
```
53+
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
54+
│ QuizForm │───▶│ ExplanationService│───▶│ AI Providers │
55+
│ Component │ │ │ │ │
56+
└─────────────────┘ └──────────────────┘ └─────────────────┘
57+
│ │
58+
▼ ▼
59+
┌──────────────────┐ ┌─────────────────┐
60+
│ User Profile │ │ API Routes │
61+
│ & Preferences │ │ (/api/ai/*) │
62+
└──────────────────┘ └─────────────────┘
63+
```
64+
65+
### Key Components
66+
67+
#### 1. AI Provider Abstraction (`lib/ai-providers.ts`)
68+
69+
- Unified interface for all AI providers
70+
- Factory pattern for provider selection
71+
- Error handling and availability checking
72+
73+
#### 2. Explanation Service (`lib/explanation-service.ts`)
74+
75+
- Business logic for explanation generation
76+
- Subscription tier validation
77+
- Provider availability checking
78+
79+
#### 3. User Profile Management (`app/profile/page.tsx`)
80+
81+
- API key management interface
82+
- Provider preference selection
83+
- Subscription status display
84+
85+
#### 4. Pricing Page (`app/pricing/page.tsx`)
86+
87+
- Subscription tier comparison
88+
- Stripe checkout integration
89+
- Feature explanations
90+
91+
### API Routes
92+
93+
- `POST /api/explanations` - Generate explanations
94+
- `GET /api/profile` - Get user profile
95+
- `POST /api/profile/api-keys` - Save API keys
96+
- `POST /api/profile/preferences` - Update preferences
97+
- `POST /api/stripe/create-checkout-session` - Stripe checkout
98+
- `POST /api/ai/{provider}` - Provider-specific endpoints
99+
100+
## 🔧 Setup Instructions
101+
102+
### 1. Environment Variables
103+
104+
Copy `.env.example` to `.env` and configure:
105+
106+
```bash
107+
# Stripe Configuration
108+
STRIPE_SECRET_KEY=sk_test_...
109+
STRIPE_PUBLISHABLE_KEY=pk_test_...
110+
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
111+
112+
# AI Provider Keys (for Ditectrev premium service)
113+
DITECTREV_OPENAI_KEY=sk-...
114+
DITECTREV_GEMINI_KEY=...
115+
DITECTREV_MISTRAL_KEY=...
116+
DITECTREV_DEEPSEEK_KEY=...
117+
118+
# App Configuration
119+
NEXT_PUBLIC_URL=http://localhost:3000
120+
```
121+
122+
### 2. Database Setup
123+
124+
Implement the database schema from `lib/database-schema.md`:
125+
126+
- Users table with subscription information
127+
- API keys table (encrypted)
128+
- User preferences
129+
- Subscription tracking
130+
131+
### 3. Stripe Configuration
132+
133+
1. Create products and prices in Stripe Dashboard
134+
2. Set up webhooks for subscription events
135+
3. Configure price IDs in the pricing page
136+
137+
### 4. AI Provider Setup
138+
139+
Each provider requires different setup:
140+
141+
#### Ollama (Local)
142+
143+
```bash
144+
# Install Ollama
145+
curl -fsSL https://ollama.com/install.sh | sh
146+
147+
# Pull a model
148+
ollama pull mistral
149+
```
150+
151+
#### OpenAI
152+
153+
- Get API key from https://platform.openai.com/
154+
- Users add their key in profile settings
155+
156+
#### Google Gemini
157+
158+
- Get API key from Google AI Studio
159+
- Users add their key in profile settings
160+
161+
#### Mistral AI
162+
163+
- Get API key from https://console.mistral.ai/
164+
- Users add their key in profile settings
165+
166+
#### DeepSeek
167+
168+
- Get API key from https://platform.deepseek.com/
169+
- Users add their key in profile settings
170+
171+
## 🔒 Security Considerations
172+
173+
### API Key Management
174+
175+
- All user API keys are encrypted before storage
176+
- Keys are never logged or exposed in responses
177+
- Implement proper access controls
178+
179+
### Rate Limiting
180+
181+
- Implement per-user rate limiting
182+
- Different limits per subscription tier
183+
- Prevent abuse of AI services
184+
185+
### Data Privacy
186+
187+
- Ollama runs completely locally
188+
- Other providers: data sent to respective APIs
189+
- Clear privacy policy for each provider
190+
191+
## 🚀 Usage
192+
193+
### For Users
194+
195+
1. **Sign up** and choose a subscription tier
196+
2. **Configure** AI provider in profile settings
197+
3. **Add API keys** if using BYOK tier
198+
4. **Take quizzes** and click "Explain" for AI-powered explanations
199+
200+
### For Developers
201+
202+
```typescript
203+
// Generate explanation
204+
const service = new ExplanationService();
205+
const explanation = await service.generateExplanation({
206+
question: "What is React?",
207+
correctAnswers: ["A JavaScript library"],
208+
userSubscription: "byok",
209+
userPreferences: { explanationProvider: "openai" },
210+
userApiKeys: { openai: "sk-..." },
211+
});
212+
```
213+
214+
## 📊 Analytics & Monitoring
215+
216+
Track key metrics:
217+
218+
- Explanation usage per provider
219+
- Subscription conversion rates
220+
- API costs and usage patterns
221+
- User satisfaction with explanations
222+
223+
## 🔄 Future Enhancements
224+
225+
1. **Caching System** - Cache explanations to reduce costs
226+
2. **Custom Models** - Fine-tuned models for specific domains
227+
3. **Explanation History** - Save and review past explanations
228+
4. **Collaborative Features** - Share explanations with others
229+
5. **Mobile App Integration** - Sync with iOS/Android apps
230+
231+
## 🐛 Troubleshooting
232+
233+
### Common Issues
234+
235+
1. **Ollama not available**
236+
237+
- Ensure Ollama is installed and running
238+
- Check if port 11434 is accessible
239+
240+
2. **API key errors**
241+
242+
- Verify API keys are correctly entered
243+
- Check API key permissions and quotas
244+
245+
3. **Subscription issues**
246+
- Verify Stripe webhook configuration
247+
- Check subscription status in Stripe Dashboard
248+
249+
### Debug Mode
250+
251+
Set `NODE_ENV=development` to enable detailed logging and mock responses for testing.
252+
253+
## 📞 Support
254+
255+
For technical support or questions:
256+
257+
- Check the troubleshooting section above
258+
- Review the database schema and API documentation
259+
- Contact the development team
260+
261+
---
262+
263+
Built with ❤️ by the Ditectrev team

app/api/ai/deepseek/route.ts

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { NextRequest, NextResponse } from "next/server";
2+
3+
export async function POST(request: NextRequest) {
4+
try {
5+
const { question, correctAnswers, apiKey } = await request.json();
6+
7+
if (!apiKey) {
8+
return NextResponse.json(
9+
{ error: "DeepSeek API key is required" },
10+
{ status: 400 },
11+
);
12+
}
13+
14+
const prompt = `Question: ${question}\n\nCorrect answers: ${correctAnswers.join(
15+
", ",
16+
)}\n\nPlease provide a clear and concise explanation of why these answers are correct.`;
17+
18+
// TODO: Replace with actual DeepSeek API call
19+
// const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
20+
// method: 'POST',
21+
// headers: {
22+
// 'Authorization': `Bearer ${apiKey}`,
23+
// 'Content-Type': 'application/json',
24+
// },
25+
// body: JSON.stringify({
26+
// model: 'deepseek-chat',
27+
// messages: [
28+
// {
29+
// role: 'user',
30+
// content: prompt
31+
// }
32+
// ],
33+
// max_tokens: 500,
34+
// }),
35+
// });
36+
37+
// const data = await response.json();
38+
// const explanation = data.choices[0].message.content;
39+
40+
// Mock response for now
41+
const explanation = `[DeepSeek Mock] Analysis of the correct answers: ${correctAnswers.join(
42+
", ",
43+
)}. These selections are optimal because they represent the most logical and evidence-based approach to solving this type of problem.`;
44+
45+
return NextResponse.json({ explanation });
46+
} catch (error) {
47+
console.error("Error with DeepSeek API:", error);
48+
return NextResponse.json(
49+
{ error: "Failed to generate explanation" },
50+
{ status: 500 },
51+
);
52+
}
53+
}

0 commit comments

Comments
 (0)