Initial commit — AI-powered coding tutor (Professor)
Next.js 16, React 19, Monaco editor, Anthropic SDK, multi-provider AI, Wandbox Python execution, iframe HTML preview, SQLite auth + session persistence. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
184
app/api/ai/route.ts
Normal file
184
app/api/ai/route.ts
Normal file
@@ -0,0 +1,184 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import Anthropic from '@anthropic-ai/sdk';
|
||||
import {
|
||||
buildTaskGenerationPrompt,
|
||||
buildCodeReviewPrompt,
|
||||
buildChatPrompt,
|
||||
buildLessonPrompt,
|
||||
buildClassroomChatPrompt,
|
||||
} from '@/lib/prompts';
|
||||
import { PROVIDER_MAP } from '@/lib/providers';
|
||||
import type { AIRequestBody, ProviderConfig } from '@/types';
|
||||
|
||||
// ─── Anthropic streaming ────────────────────────────────────────────────────
|
||||
|
||||
async function streamAnthropic(
|
||||
config: ProviderConfig,
|
||||
systemPrompt: string,
|
||||
messages: Anthropic.MessageParam[],
|
||||
controller: ReadableStreamDefaultController
|
||||
) {
|
||||
const client = config.apiKey
|
||||
? new Anthropic({ apiKey: config.apiKey })
|
||||
: new Anthropic(); // falls back to ANTHROPIC_API_KEY env var
|
||||
|
||||
const stream = await client.messages.stream({
|
||||
model: config.model,
|
||||
max_tokens: 2048,
|
||||
system: systemPrompt,
|
||||
messages,
|
||||
});
|
||||
|
||||
for await (const chunk of stream) {
|
||||
if (chunk.type === 'content_block_delta' && chunk.delta.type === 'text_delta') {
|
||||
controller.enqueue(new TextEncoder().encode(chunk.delta.text));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── OpenAI-compatible streaming (OpenRouter, LM Studio, Ollama) ────────────
|
||||
|
||||
async function streamOpenAICompatible(
|
||||
config: ProviderConfig,
|
||||
systemPrompt: string,
|
||||
messages: Array<{ role: 'user' | 'assistant'; content: string }>,
|
||||
controller: ReadableStreamDefaultController
|
||||
) {
|
||||
const providerDef = PROVIDER_MAP[config.provider];
|
||||
const baseUrl = config.baseUrl ?? providerDef.defaultBaseUrl;
|
||||
const apiKey = config.apiKey || 'none'; // LM Studio / Ollama accept any value
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
};
|
||||
|
||||
// OpenRouter requires attribution headers
|
||||
if (config.provider === 'openrouter') {
|
||||
headers['HTTP-Referer'] = 'http://localhost:3000';
|
||||
headers['X-Title'] = 'Professor';
|
||||
}
|
||||
|
||||
const res = await fetch(`${baseUrl}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
model: config.model,
|
||||
messages: [{ role: 'system', content: systemPrompt }, ...messages],
|
||||
stream: true,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok || !res.body) {
|
||||
const text = await res.text().catch(() => res.statusText);
|
||||
throw new Error(`${providerDef.label} error ${res.status}: ${text}`);
|
||||
}
|
||||
|
||||
// Parse SSE stream
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() ?? '';
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed.startsWith('data: ')) continue;
|
||||
const data = trimmed.slice(6);
|
||||
if (data === '[DONE]') return;
|
||||
try {
|
||||
const json = JSON.parse(data);
|
||||
const content = json.choices?.[0]?.delta?.content;
|
||||
if (content) controller.enqueue(new TextEncoder().encode(content));
|
||||
} catch {
|
||||
// ignore malformed SSE lines
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Route handler ──────────────────────────────────────────────────────────
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
let body: AIRequestBody;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { mode, topic, code, executionResult, messages, userMessage, providerConfig, responseMode } = body;
|
||||
|
||||
if (!mode || !topic || !providerConfig) {
|
||||
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Build system prompt
|
||||
let systemPrompt: string;
|
||||
switch (mode) {
|
||||
case 'generate_task':
|
||||
systemPrompt = buildTaskGenerationPrompt(topic);
|
||||
break;
|
||||
case 'review_code':
|
||||
systemPrompt = buildCodeReviewPrompt(topic, code, executionResult, responseMode);
|
||||
break;
|
||||
case 'chat':
|
||||
systemPrompt = buildChatPrompt(topic, code, responseMode);
|
||||
break;
|
||||
case 'generate_lesson':
|
||||
systemPrompt = buildLessonPrompt(topic);
|
||||
break;
|
||||
case 'classroom_chat':
|
||||
systemPrompt = buildClassroomChatPrompt(topic);
|
||||
break;
|
||||
default:
|
||||
return NextResponse.json({ error: 'Invalid mode' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Build message list
|
||||
const chatMessages: Array<{ role: 'user' | 'assistant'; content: string }> =
|
||||
mode === 'generate_task'
|
||||
? [{ role: 'user', content: 'Generate a task for this topic.' }]
|
||||
: mode === 'review_code'
|
||||
? [{ role: 'user', content: 'Please review my code and give me feedback.' }]
|
||||
: mode === 'generate_lesson'
|
||||
? [{ role: 'user', content: 'Write the lesson.' }]
|
||||
: [
|
||||
...(messages ?? []).map((m) => ({
|
||||
role: m.role as 'user' | 'assistant',
|
||||
content: m.content,
|
||||
})),
|
||||
...(userMessage ? [{ role: 'user' as const, content: userMessage }] : []),
|
||||
];
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
try {
|
||||
if (providerConfig.provider === 'anthropic') {
|
||||
await streamAnthropic(providerConfig, systemPrompt, chatMessages, controller);
|
||||
} else {
|
||||
await streamOpenAICompatible(providerConfig, systemPrompt, chatMessages, controller);
|
||||
}
|
||||
controller.close();
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'AI error';
|
||||
controller.enqueue(new TextEncoder().encode(`\n\n[Error: ${message}]`));
|
||||
controller.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'Transfer-Encoding': 'chunked',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
});
|
||||
}
|
||||
23
app/api/auth/login/route.ts
Normal file
23
app/api/auth/login/route.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/db';
|
||||
import { users } from '@/db/schema';
|
||||
import { verifyPassword, signToken, setAuthCookie } from '@/lib/auth';
|
||||
import { eq } from 'drizzle-orm';
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { email, password } = await req.json();
|
||||
|
||||
if (!email || !password) {
|
||||
return NextResponse.json({ error: 'Email and password are required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const user = await db.select().from(users).where(eq(users.email, email)).get();
|
||||
if (!user || !(await verifyPassword(password, user.passwordHash))) {
|
||||
return NextResponse.json({ error: 'Invalid email or password' }, { status: 401 });
|
||||
}
|
||||
|
||||
const token = await signToken({ userId: user.id, email: user.email });
|
||||
await setAuthCookie(token);
|
||||
|
||||
return NextResponse.json({ user: { id: user.id, email: user.email } });
|
||||
}
|
||||
7
app/api/auth/logout/route.ts
Normal file
7
app/api/auth/logout/route.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { clearAuthCookie } from '@/lib/auth';
|
||||
|
||||
export async function POST() {
|
||||
await clearAuthCookie();
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
8
app/api/auth/me/route.ts
Normal file
8
app/api/auth/me/route.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getAuthUser } from '@/lib/auth';
|
||||
|
||||
export async function GET() {
|
||||
const user = await getAuthUser();
|
||||
if (!user) return NextResponse.json({ user: null });
|
||||
return NextResponse.json({ user: { id: user.userId, email: user.email } });
|
||||
}
|
||||
30
app/api/auth/register/route.ts
Normal file
30
app/api/auth/register/route.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/db';
|
||||
import { users } from '@/db/schema';
|
||||
import { hashPassword, signToken, setAuthCookie } from '@/lib/auth';
|
||||
import { eq } from 'drizzle-orm';
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { email, password } = await req.json();
|
||||
|
||||
if (!email || typeof email !== 'string' || !email.includes('@')) {
|
||||
return NextResponse.json({ error: 'Valid email is required' }, { status: 400 });
|
||||
}
|
||||
if (!password || typeof password !== 'string' || password.length < 8) {
|
||||
return NextResponse.json({ error: 'Password must be at least 8 characters' }, { status: 400 });
|
||||
}
|
||||
|
||||
const existing = await db.select().from(users).where(eq(users.email, email)).get();
|
||||
if (existing) {
|
||||
return NextResponse.json({ error: 'Email already registered' }, { status: 409 });
|
||||
}
|
||||
|
||||
const id = crypto.randomUUID();
|
||||
const passwordHash = await hashPassword(password);
|
||||
await db.insert(users).values({ id, email, passwordHash, createdAt: new Date().toISOString() });
|
||||
|
||||
const token = await signToken({ userId: id, email });
|
||||
await setAuthCookie(token);
|
||||
|
||||
return NextResponse.json({ user: { id, email } });
|
||||
}
|
||||
38
app/api/execute/route.ts
Normal file
38
app/api/execute/route.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { executePython } from '@/lib/pistonClient';
|
||||
import type { ExecuteRequestBody } from '@/types';
|
||||
|
||||
const MAX_CODE_LENGTH = 10_000;
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
let body: ExecuteRequestBody;
|
||||
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { language, code, stdin } = body;
|
||||
|
||||
if (!language || !code) {
|
||||
return NextResponse.json({ error: 'Missing language or code' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (code.length > MAX_CODE_LENGTH) {
|
||||
return NextResponse.json({ error: 'Code exceeds maximum length of 10,000 characters' }, { status: 400 });
|
||||
}
|
||||
|
||||
// HTML is rendered client-side via iframe — no backend execution needed
|
||||
if (language === 'html') {
|
||||
return NextResponse.json({
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
exitCode: 0,
|
||||
timedOut: false,
|
||||
});
|
||||
}
|
||||
|
||||
const result = await executePython(code, stdin ?? '');
|
||||
return NextResponse.json(result);
|
||||
}
|
||||
84
app/api/models/route.ts
Normal file
84
app/api/models/route.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import type { ProviderId } from '@/types';
|
||||
import { PROVIDER_MAP } from '@/lib/providers';
|
||||
|
||||
interface ModelsRequestBody {
|
||||
provider: ProviderId;
|
||||
apiKey?: string;
|
||||
baseUrl?: string;
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
let body: ModelsRequestBody;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { provider, apiKey, baseUrl } = body;
|
||||
const def = PROVIDER_MAP[provider];
|
||||
const base = baseUrl?.trim() || def.defaultBaseUrl;
|
||||
|
||||
try {
|
||||
let models: string[] = [];
|
||||
|
||||
if (provider === 'anthropic') {
|
||||
const key = apiKey?.trim() || process.env.ANTHROPIC_API_KEY;
|
||||
if (!key) {
|
||||
return NextResponse.json({ error: 'No API key — enter one above or set ANTHROPIC_API_KEY in .env.local' }, { status: 400 });
|
||||
}
|
||||
const res = await fetch('https://api.anthropic.com/v1/models?limit=100', {
|
||||
headers: {
|
||||
'x-api-key': key,
|
||||
'anthropic-version': '2023-06-01',
|
||||
},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '');
|
||||
return NextResponse.json({ error: `Anthropic: ${res.status} ${text}` }, { status: res.status });
|
||||
}
|
||||
const data = await res.json();
|
||||
models = (data.data ?? []).map((m: { id: string }) => m.id);
|
||||
}
|
||||
|
||||
else if (provider === 'openrouter') {
|
||||
const headers: Record<string, string> = {};
|
||||
if (apiKey?.trim()) headers['Authorization'] = `Bearer ${apiKey.trim()}`;
|
||||
|
||||
const res = await fetch('https://openrouter.ai/api/v1/models', { headers });
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '');
|
||||
return NextResponse.json({ error: `OpenRouter: ${res.status} ${text}` }, { status: res.status });
|
||||
}
|
||||
const data = await res.json();
|
||||
// Sort by id for easier browsing
|
||||
models = (data.data ?? [])
|
||||
.map((m: { id: string }) => m.id)
|
||||
.sort((a: string, b: string) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
else {
|
||||
// LM Studio and Ollama — OpenAI-compatible /v1/models
|
||||
const res = await fetch(`${base}/models`, {
|
||||
headers: { Authorization: 'Bearer none' },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '');
|
||||
return NextResponse.json({ error: `${def.label}: ${res.status} ${text || 'Connection refused'}` }, { status: res.status });
|
||||
}
|
||||
const data = await res.json();
|
||||
models = (data.data ?? []).map((m: { id: string }) => m.id);
|
||||
}
|
||||
|
||||
return NextResponse.json({ models });
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : 'Unknown error';
|
||||
const isTimeout = msg.includes('timeout') || msg.includes('abort');
|
||||
return NextResponse.json(
|
||||
{ error: isTimeout ? `Could not reach ${def.label} — is it running?` : msg },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
62
app/api/session/route.ts
Normal file
62
app/api/session/route.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/db';
|
||||
import { savedSessions } from '@/db/schema';
|
||||
import { getAuthUser } from '@/lib/auth';
|
||||
import { eq } from 'drizzle-orm';
|
||||
|
||||
export async function GET() {
|
||||
const authUser = await getAuthUser();
|
||||
if (!authUser) return NextResponse.json({ session: null }, { status: 401 });
|
||||
|
||||
const row = await db
|
||||
.select()
|
||||
.from(savedSessions)
|
||||
.where(eq(savedSessions.userId, authUser.userId))
|
||||
.get();
|
||||
|
||||
if (!row) return NextResponse.json({ session: null });
|
||||
|
||||
return NextResponse.json({
|
||||
session: {
|
||||
topicId: row.topicId,
|
||||
task: row.taskJson ? JSON.parse(row.taskJson) : null,
|
||||
code: row.code,
|
||||
messages: row.messagesJson ? JSON.parse(row.messagesJson) : [],
|
||||
executionResult: row.executionResultJson ? JSON.parse(row.executionResultJson) : null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest) {
|
||||
const authUser = await getAuthUser();
|
||||
if (!authUser) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
|
||||
const { topicId, task, code, messages, executionResult } = await req.json();
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(savedSessions)
|
||||
.where(eq(savedSessions.userId, authUser.userId))
|
||||
.get();
|
||||
|
||||
const data = {
|
||||
userId: authUser.userId,
|
||||
topicId: topicId ?? null,
|
||||
taskJson: task ? JSON.stringify(task) : null,
|
||||
code: code ?? null,
|
||||
messagesJson: messages ? JSON.stringify(messages) : null,
|
||||
executionResultJson: executionResult ? JSON.stringify(executionResult) : null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
if (existing) {
|
||||
await db
|
||||
.update(savedSessions)
|
||||
.set(data)
|
||||
.where(eq(savedSessions.userId, authUser.userId));
|
||||
} else {
|
||||
await db.insert(savedSessions).values({ id: crypto.randomUUID(), ...data });
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
Reference in New Issue
Block a user