Spaces:
Running
Running
File size: 9,585 Bytes
1291157 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | // API Service Layer for LearnFlow Frontend
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000';
// Service URLs
const SERVICES = {
triage: process.env.NEXT_PUBLIC_TRIAGE_URL || 'http://localhost:8001',
concepts: process.env.NEXT_PUBLIC_CONCEPTS_URL || 'http://localhost:8002',
codeReview: process.env.NEXT_PUBLIC_CODE_REVIEW_URL || 'http://localhost:8003',
debug: process.env.NEXT_PUBLIC_DEBUG_URL || 'http://localhost:8004',
exercise: process.env.NEXT_PUBLIC_EXERCISE_URL || 'http://localhost:8005',
progress: process.env.NEXT_PUBLIC_PROGRESS_URL || 'http://localhost:8006',
};
// Auth token management
let authToken: string | null = null;
export const setAuthToken = (token: string) => {
authToken = token;
if (typeof window !== 'undefined') {
localStorage.setItem('learnflow_token', token);
}
};
export const getAuthToken = (): string | null => {
if (authToken) return authToken;
if (typeof window !== 'undefined') {
return localStorage.getItem('learnflow_token');
}
return null;
};
export const clearAuthToken = () => {
authToken = null;
if (typeof window !== 'undefined') {
localStorage.removeItem('learnflow_token');
}
};
// Generic fetch wrapper
async function apiFetch<T>(
url: string,
options: RequestInit = {}
): Promise<T> {
const token = getAuthToken();
const headers: HeadersInit = {
'Content-Type': 'application/json',
...(token && { Authorization: `Bearer ${token}` }),
...options.headers,
};
const response = await fetch(url, {
...options,
headers,
});
if (!response.ok) {
const error = await response.json().catch(() => ({ message: 'Request failed' }));
throw new Error(error.message || `HTTP error! status: ${response.status}`);
}
return response.json();
}
// ==================== AUTH API ====================
export interface LoginRequest {
email: string;
password: string;
}
export interface RegisterRequest {
name: string;
email: string;
password: string;
role: 'student' | 'teacher';
}
export interface AuthResponse {
token: string;
user: {
id: string;
name: string;
email: string;
role: 'student' | 'teacher';
};
}
export const authAPI = {
login: async (data: LoginRequest): Promise<AuthResponse> => {
return apiFetch<AuthResponse>(`${API_BASE_URL}/auth/login`, {
method: 'POST',
body: JSON.stringify(data),
});
},
register: async (data: RegisterRequest): Promise<AuthResponse> => {
return apiFetch<AuthResponse>(`${API_BASE_URL}/auth/register`, {
method: 'POST',
body: JSON.stringify(data),
});
},
me: async (): Promise<AuthResponse['user']> => {
return apiFetch<AuthResponse['user']>(`${API_BASE_URL}/auth/me`);
},
};
// ==================== TRIAGE API ====================
export interface QueryRequest {
query: string;
user_id: string;
}
export interface RoutingResponse {
agent: string;
message: string;
params: Record<string, any>;
}
export const triageAPI = {
routeQuery: async (data: QueryRequest): Promise<RoutingResponse> => {
return apiFetch<RoutingResponse>(`${SERVICES.triage}/query`, {
method: 'POST',
body: JSON.stringify(data),
});
},
health: async (): Promise<{ status: string }> => {
return apiFetch<{ status: string }>(`${SERVICES.triage}/health`);
},
};
// ==================== CONCEPTS API ====================
export interface ExplainRequest {
topic: string;
level?: 'beginner' | 'intermediate' | 'advanced';
user_context?: Record<string, any>;
}
export interface ExplanationResponse {
topic: string;
explanation: string;
examples: string[];
level: string;
}
export const conceptsAPI = {
explain: async (data: ExplainRequest): Promise<ExplanationResponse> => {
return apiFetch<ExplanationResponse>(`${SERVICES.concepts}/explain`, {
method: 'POST',
body: JSON.stringify(data),
});
},
health: async (): Promise<{ status: string }> => {
return apiFetch<{ status: string }>(`${SERVICES.concepts}/health`);
},
};
// ==================== EXERCISE API ====================
export interface ExerciseRequest {
module: string;
topic: string;
difficulty?: 'beginner' | 'intermediate' | 'advanced';
user_id?: string;
}
export interface ExerciseResponse {
id: string;
module: string;
topic: string;
problem: string;
starter_code: string;
test_cases: Array<{ input: string; expected_output: string }>;
difficulty: string;
}
export interface SubmissionRequest {
quiz_id: string;
user_id: string;
code: string;
}
export interface GradeResponse {
quiz_id: string;
user_id: string;
score: number;
feedback: string;
passed_tests: number;
total_tests: number;
}
export const exerciseAPI = {
generate: async (data: ExerciseRequest): Promise<ExerciseResponse> => {
return apiFetch<ExerciseResponse>(`${SERVICES.exercise}/generate`, {
method: 'POST',
body: JSON.stringify(data),
});
},
grade: async (data: SubmissionRequest): Promise<GradeResponse> => {
return apiFetch<GradeResponse>(`${SERVICES.exercise}/grade`, {
method: 'POST',
body: JSON.stringify(data),
});
},
health: async (): Promise<{ status: string }> => {
return apiFetch<{ status: string }>(`${SERVICES.exercise}/health`);
},
};
// ==================== CODE REVIEW API ====================
export interface ReviewRequest {
code: string;
context?: string;
user_id?: string;
}
export interface ReviewResponse {
overall_quality: string;
issues: Array<{
type: string;
line: number;
message: string;
suggestion: string;
}>;
suggestions: string[];
score: number;
}
export const codeReviewAPI = {
review: async (data: ReviewRequest): Promise<ReviewResponse> => {
return apiFetch<ReviewResponse>(`${SERVICES.codeReview}/review`, {
method: 'POST',
body: JSON.stringify(data),
});
},
health: async (): Promise<{ status: string }> => {
return apiFetch<{ status: string }>(`${SERVICES.codeReview}/health`);
},
};
// ==================== DEBUG API ====================
export interface DebugRequest {
code: string;
error_message: string;
user_id?: string;
}
export interface DebugResponse {
error_type: string;
explanation: string;
fix_suggestion: string;
corrected_code: string;
learning_tip: string;
}
export const debugAPI = {
analyze: async (data: DebugRequest): Promise<DebugResponse> => {
return apiFetch<DebugResponse>(`${SERVICES.debug}/analyze`, {
method: 'POST',
body: JSON.stringify(data),
});
},
health: async (): Promise<{ status: string }> => {
return apiFetch<{ status: string }>(`${SERVICES.debug}/health`);
},
};
// ==================== PROGRESS API ====================
export interface ProgressData {
user_id: string;
overall_mastery: number;
modules_completed: number;
current_module: string;
modules: Record<string, Record<string, { mastery_score: number }>>;
}
export interface UpdateProgressRequest {
user_id: string;
module: string;
topic: string;
score: number;
activity_type: 'quiz' | 'exercise' | 'lesson';
}
export const progressAPI = {
getProgress: async (userId: string): Promise<ProgressData> => {
return apiFetch<ProgressData>(`${SERVICES.progress}/progress/${userId}`);
},
updateProgress: async (data: UpdateProgressRequest): Promise<ProgressData> => {
return apiFetch<ProgressData>(`${SERVICES.progress}/progress`, {
method: 'POST',
body: JSON.stringify(data),
});
},
health: async (): Promise<{ status: string }> => {
return apiFetch<{ status: string }>(`${SERVICES.progress}/health`);
},
};
// ==================== AI CHAT API ====================
export interface ChatMessage {
role: 'user' | 'assistant';
content: string;
}
export interface ChatRequest {
messages: ChatMessage[];
user_id: string;
context?: string;
}
export interface ChatResponse {
response: string;
agent_used: string;
}
export const chatAPI = {
sendMessage: async (data: ChatRequest): Promise<ChatResponse> => {
// First route through triage
const routing = await triageAPI.routeQuery({
query: data.messages[data.messages.length - 1].content,
user_id: data.user_id,
});
// Then call the appropriate agent
if (routing.agent === 'concepts-agent') {
const response = await conceptsAPI.explain({
topic: data.messages[data.messages.length - 1].content,
level: 'intermediate',
});
return {
response: `${response.explanation}\n\nExamples:\n${response.examples.join('\n')}`,
agent_used: routing.agent,
};
}
// Default response
return {
response: routing.message,
agent_used: routing.agent,
};
},
};
// ==================== UTILITY FUNCTIONS ====================
export const checkServicesHealth = async (): Promise<Record<string, boolean>> => {
const services = ['triage', 'concepts', 'codeReview', 'debug', 'exercise', 'progress'] as const;
const results: Record<string, boolean> = {};
await Promise.all(
services.map(async (service) => {
try {
const api = {
triage: triageAPI,
concepts: conceptsAPI,
codeReview: codeReviewAPI,
debug: debugAPI,
exercise: exerciseAPI,
progress: progressAPI,
}[service];
await api.health();
results[service] = true;
} catch {
results[service] = false;
}
})
);
return results;
};
|