Capstone project - build a full-stack AI application integrating chat, image generation, document analysis, cost tracking, and production best practices. Deploy a real-world AI solution.
This is your final challenge - build a complete, production-ready AI application that integrates everything you've learned. You'll create an AI-powered content creation platform that combines chat interfaces, image generation, document analysis, and intelligent automation.
Your application will include authentication, real-time chat, image generation, document processing, cost tracking, error handling, caching, and monitoring - all the components of a professional AI product. This project demonstrates your mastery of AI integration and readiness to build production AI applications.
By completing this project, you'll have a portfolio piece that showcases your skills in AI/ML integration, full-stack development, and production engineering. Let's build something amazing!
Design a scalable, production-ready AI application with proper separation of concerns and best practices.
System Architecture:
1// Complete AI Application Architecture
2
3/**
4 * AI Content Creation Platform
5 *
6 * Features:
7 * - Multi-turn chat conversations
8 * - Image generation with DALL-E
9 * - Document analysis and summarization
10 * - Content moderation and safety
11 * - Cost tracking and budget management
12 * - User authentication and authorization
13 * - Real-time updates and notifications
14 */
15
16// 1. Backend Service Architecture
17class AIContentPlatform {
18 constructor() {
19 // AI Providers
20 this.openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
21 this.anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
22
23 // Infrastructure
24 this.db = new Database(process.env.DATABASE_URL);
25 this.cache = new Redis(process.env.REDIS_URL);
26 this.storage = new S3Storage(process.env.AWS_BUCKET);
27
28 // Services
29 this.chatService = new ChatService(this);
30 this.imageService = new ImageGenerationService(this);
31 this.documentService = new DocumentAnalysisService(this);
32 this.moderationService = new ContentModerationService(this);
33 this.costTracker = new CostTrackingService(this);
34 this.analytics = new AnalyticsService(this);
35
36 // Monitoring
37 this.monitor = new MonitoringService();
38 this.logger = new StructuredLogger();
39 }
40
41 // Main request handler
42 async handleRequest(userId, request) {
43 const requestId = this.generateRequestId();
44 const startTime = Date.now();
45
46 try {
47 // Authenticate and authorize
48 const user = await this.authenticateUser(userId);
49 await this.authorizeRequest(user, request);
50
51 // Check budget
52 await this.costTracker.checkBudget(userId);
53
54 // Route to appropriate service
55 let result;
56 switch (request.type) {
57 case 'chat':
58 result = await this.chatService.handleChat(user, request);
59 break;
60 case 'image':
61 result = await this.imageService.generateImage(user, request);
62 break;
63 case 'document':
64 result = await this.documentService.analyzeDocument(user, request);
65 break;
66 default:
67 throw new Error(`Unknown request type: ${request.type}`);
68 }
69
70 // Track cost and usage
71 await this.costTracker.recordUsage(userId, result.cost);
72
73 // Log success
74 this.logger.info('Request completed', {
75 requestId,
76 userId,
77 type: request.type,
78 duration: Date.now() - startTime,
79 cost: result.cost
80 });
81
82 return result;
83
84 } catch (error) {
85 this.handleError(error, { requestId, userId, request });
86 throw error;
87 }
88 }
89}
90
91// 2. Chat Service with Conversation Management
92class ChatService {
93 constructor(platform) {
94 this.platform = platform;
95 }
96
97 async handleChat(user, request) {
98 // Get conversation history
99 const conversation = await this.platform.db.getConversation(
100 user.id,
101 request.conversationId
102 );
103
104 // Build messages with context
105 const messages = this.buildMessages(conversation, request.message);
106
107 // Moderate input
108 await this.platform.moderationService.moderateInput(request.message);
109
110 // Generate response with caching
111 const cacheKey = this.getCacheKey(messages);
112 let response = await this.platform.cache.get(cacheKey);
113
114 if (!response) {
115 response = await this.platform.openai.chat.completions.create({
116 model: this.selectModel(request),
117 messages: messages,
118 stream: request.stream || false
119 });
120
121 // Cache non-streaming responses
122 if (!request.stream) {
123 await this.platform.cache.setex(cacheKey, 3600, JSON.stringify(response));
124 }
125 }
126
127 // Save to conversation history
128 await this.saveToHistory(user.id, request.conversationId, {
129 role: 'user',
130 content: request.message
131 }, {
132 role: 'assistant',
133 content: response.choices[0].message.content
134 });
135
136 return {
137 content: response.choices[0].message.content,
138 cost: this.calculateCost(response.usage),
139 conversationId: request.conversationId
140 };
141 }
142
143 selectModel(request) {
144 // Intelligent model selection
145 if (request.preferQuality) return "gpt-4";
146 if (request.preferSpeed) return "gpt-3.5-turbo";
147
148 // Auto-select based on complexity
149 const complexity = this.analyzeComplexity(request.message);
150 return complexity > 0.7 ? "gpt-4" : "gpt-3.5-turbo";
151 }
152}
153
154// 3. Image Generation Service
155class ImageGenerationService {
156 constructor(platform) {
157 this.platform = platform;
158 }
159
160 async generateImage(user, request) {
161 // Moderate prompt
162 await this.platform.moderationService.moderateInput(request.prompt);
163
164 // Check cache for similar prompts
165 const similar = await this.findSimilarImage(request.prompt);
166 if (similar && request.allowCache) {
167 return { ...similar, cached: true };
168 }
169
170 // Generate image
171 const response = await this.platform.openai.images.generate({
172 model: "dall-e-3",
173 prompt: request.prompt,
174 size: request.size || "1024x1024",
175 quality: request.quality || "standard",
176 n: 1
177 });
178
179 // Download and store image
180 const imageUrl = response.data[0].url;
181 const storedUrl = await this.platform.storage.uploadFromUrl(
182 imageUrl,
183 `images/${user.id}/${Date.now()}.png`
184 );
185
186 // Save to database
187 await this.platform.db.saveImage({
188 userId: user.id,
189 prompt: request.prompt,
190 url: storedUrl,
191 size: request.size,
192 quality: request.quality,
193 cost: this.calculateImageCost(request)
194 });
195
196 return {
197 url: storedUrl,
198 revisedPrompt: response.data[0].revised_prompt,
199 cost: this.calculateImageCost(request)
200 };
201 }
202
203 calculateImageCost(request) {
204 const pricing = {
205 "standard": { "1024x1024": 0.04, "1024x1792": 0.08, "1792x1024": 0.08 },
206 "hd": { "1024x1024": 0.08, "1024x1792": 0.12, "1792x1024": 0.12 }
207 };
208 return pricing[request.quality || "standard"][request.size || "1024x1024"];
209 }
210}
211
212// 4. Document Analysis Service
213class DocumentAnalysisService {
214 constructor(platform) {
215 this.platform = platform;
216 }
217
218 async analyzeDocument(user, request) {
219 // Extract text from document
220 const text = await this.extractText(request.fileUrl);
221
222 // Analyze based on task
223 let result;
224 switch (request.task) {
225 case 'summarize':
226 result = await this.summarize(text);
227 break;
228 case 'extract-entities':
229 result = await this.extractEntities(text);
230 break;
231 case 'sentiment':
232 result = await this.analyzeSentiment(text);
233 break;
234 case 'qa':
235 result = await this.answerQuestion(text, request.question);
236 break;
237 default:
238 throw new Error(`Unknown task: ${request.task}`);
239 }
240
241 return {
242 ...result,
243 wordCount: text.split(/\s+/).length,
244 cost: this.calculateCost(result.usage)
245 };
246 }
247
248 async summarize(text) {
249 const response = await this.platform.openai.chat.completions.create({
250 model: "gpt-3.5-turbo",
251 messages: [
252 {
253 role: "system",
254 content: "Summarize the following document concisely."
255 },
256 { role: "user", content: text }
257 ],
258 max_tokens: 500
259 });
260
261 return {
262 summary: response.choices[0].message.content,
263 usage: response.usage
264 };
265 }
266}Build a modern React frontend with real-time updates, professional UI, and excellent UX.
React Frontend Architecture:
1// React + TypeScript Frontend
2
3import React, { useState, useEffect } from 'react';
4import { useAuth } from './hooks/useAuth';
5import { useAI } from './hooks/useAI';
6
7// Main Application Component
8function AIContentPlatform() {
9 const { user, loading, signIn, signOut } = useAuth();
10 const [activeTab, setActiveTab] = useState<'chat' | 'image' | 'document'>('chat');
11
12 if (loading) return <LoadingScreen />;
13 if (!user) return <LoginPage onSignIn={signIn} />;
14
15 return (
16 <div className="min-h-screen bg-gray-50">
17 <Header user={user} onSignOut={signOut} />
18
19 <div className="max-w-7xl mx-auto px-4 py-8">
20 <div className="grid grid-cols-4 gap-6">
21 {/* Sidebar */}
22 <div className="col-span-1">
23 <Sidebar activeTab={activeTab} onTabChange={setActiveTab} />
24 <CostTracker userId={user.id} />
25 </div>
26
27 {/* Main Content */}
28 <div className="col-span-3">
29 {activeTab === 'chat' && <ChatInterface userId={user.id} />}
30 {activeTab === 'image' && <ImageGenerator userId={user.id} />}
31 {activeTab === 'document' && <DocumentAnalyzer userId={user.id} />}
32 </div>
33 </div>
34 </div>
35 </div>
36 );
37}
38
39// Chat Interface Component
40function ChatInterface({ userId }: { userId: string }) {
41 const { sendMessage, messages, loading, error } = useAI();
42 const [input, setInput] = useState('');
43
44 async function handleSend() {
45 if (!input.trim()) return;
46
47 await sendMessage({
48 type: 'chat',
49 message: input,
50 conversationId: 'current'
51 });
52
53 setInput('');
54 }
55
56 return (
57 <div className="bg-white rounded-lg shadow-lg h-[600px] flex flex-col">
58 {/* Messages */}
59 <div className="flex-1 overflow-y-auto p-6 space-y-4">
60 {messages.map((msg, i) => (
61 <Message key={i} message={msg} />
62 ))}
63 {loading && <TypingIndicator />}
64 {error && <ErrorMessage error={error} />}
65 </div>
66
67 {/* Input */}
68 <div className="border-t p-4">
69 <div className="flex gap-3">
70 <input
71 type="text"
72 value={input}
73 onChange={(e) => setInput(e.target.value)}
74 onKeyPress={(e) => e.key === 'Enter' && handleSend()}
75 placeholder="Type your message..."
76 className="flex-1 px-4 py-2 border rounded-lg"
77 />
78 <button
79 onClick={handleSend}
80 disabled={loading}
81 className="px-6 py-2 bg-blue-600 text-white rounded-lg"
82 >
83 Send
84 </button>
85 </div>
86 </div>
87 </div>
88 );
89}
90
91// Image Generator Component
92function ImageGenerator({ userId }: { userId: string }) {
93 const { generateImage, loading, error } = useAI();
94 const [prompt, setPrompt] = useState('');
95 const [image, setImage] = useState<string | null>(null);
96
97 async function handleGenerate() {
98 const result = await generateImage({
99 type: 'image',
100 prompt,
101 size: '1024x1024',
102 quality: 'standard'
103 });
104
105 setImage(result.url);
106 }
107
108 return (
109 <div className="bg-white rounded-lg shadow-lg p-6">
110 <h2 className="text-2xl font-bold mb-6">Image Generation</h2>
111
112 <textarea
113 value={prompt}
114 onChange={(e) => setPrompt(e.target.value)}
115 placeholder="Describe the image you want to generate..."
116 rows={4}
117 className="w-full px-4 py-3 border rounded-lg mb-4"
118 />
119
120 <button
121 onClick={handleGenerate}
122 disabled={loading}
123 className="w-full py-3 bg-purple-600 text-white rounded-lg"
124 >
125 {loading ? 'Generating...' : 'Generate Image'}
126 </button>
127
128 {image && (
129 <div className="mt-6">
130 <img src={image} alt="Generated" className="w-full rounded-lg" />
131 </div>
132 )}
133
134 {error && <ErrorMessage error={error} />}
135 </div>
136 );
137}
138
139// Custom Hook for AI Operations
140function useAI() {
141 const [loading, setLoading] = useState(false);
142 const [error, setError] = useState<string | null>(null);
143 const [messages, setMessages] = useState<any[]>([]);
144
145 async function sendMessage(request: any) {
146 setLoading(true);
147 setError(null);
148
149 try {
150 const response = await fetch('/api/ai', {
151 method: 'POST',
152 headers: { 'Content-Type': 'application/json' },
153 body: JSON.stringify(request)
154 });
155
156 if (!response.ok) throw new Error('Request failed');
157
158 const data = await response.json();
159
160 setMessages(prev => [
161 ...prev,
162 { role: 'user', content: request.message },
163 { role: 'assistant', content: data.content }
164 ]);
165
166 return data;
167
168 } catch (err: any) {
169 setError(err.message);
170 throw err;
171
172 } finally {
173 setLoading(false);
174 }
175 }
176
177 return { sendMessage, messages, loading, error };
178}Full-stack AI content platform with chat, image generation, document analysis, authentication, and monitoring.
1// Complete AI Application - Backend + Frontend
2
3// Backend API Route
4export async function POST(req: Request) {
5 const session = await getSession(req);
6 if (!session) return new Response('Unauthorized', { status: 401 });
7
8 const request = await req.json();
9
10 const platform = new AIContentPlatform();
11
12 try {
13 const result = await platform.handleRequest(session.userId, request);
14
15 return Response.json({
16 success: true,
17 data: result
18 });
19
20 } catch (error: any) {
21 return Response.json({
22 success: false,
23 error: error.message
24 }, { status: 500 });
25 }
26}
27
28// Frontend Application
29export default function App() {
30 return (
31 <AuthProvider>
32 <AIContentPlatform />
33 </AuthProvider>
34 );
35}Production-ready AI application integrating all course concepts - chat, images, documents, auth, monitoring, cost tracking.
Congratulations! You've completed the AI/ML Integration course! You now have production-ready skills to build AI applications. Next steps: Build your own AI projects, contribute to open-source AI tools, and explore advanced topics like fine-tuning and custom models.
Your progress is saved in this browser, on this device only.