60 lines
2.0 KiB
TypeScript
60 lines
2.0 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { z } from "zod";
|
|
import { generateObject } from "ai";
|
|
import { requireSession } from "@/lib/api-auth";
|
|
import { applyRateLimit } from "@/lib/rate-limit";
|
|
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
|
|
import { resolveModel } from "@/lib/ai/factory";
|
|
import { getUserPrivateBio, buildUserBioContext } from "@/lib/ai/user-bio";
|
|
|
|
const InputSchema = z.object({
|
|
prompt: z.string().max(300).optional(),
|
|
});
|
|
|
|
const IdeasSchema = z.object({
|
|
ideas: z.array(z.object({
|
|
title: z.string(),
|
|
description: z.string(),
|
|
tags: z.array(z.string()).max(4),
|
|
difficulty: z.enum(["easy", "medium", "hard"]),
|
|
totalMins: z.number().int().optional(),
|
|
})).length(6),
|
|
});
|
|
|
|
export async function POST(req: NextRequest) {
|
|
const { session, response } = await requireSession();
|
|
if (response) return response;
|
|
|
|
const body = await req.json() as unknown;
|
|
const parsed = InputSchema.safeParse(body);
|
|
if (!parsed.success) {
|
|
return NextResponse.json({ error: "Validation error" }, { status: 400 });
|
|
}
|
|
|
|
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
|
|
if (limited) return limited;
|
|
|
|
const [config, privateBio] = await Promise.all([
|
|
getModelConfigForUseCase(session!.user.id, "text"),
|
|
getUserPrivateBio(session!.user.id),
|
|
]);
|
|
const model = resolveModel(config);
|
|
const bioContext = buildUserBioContext(privateBio);
|
|
|
|
const userContext = bioContext
|
|
? `Consider the following user preferences when suggesting ideas:${bioContext}\n\n`
|
|
: "";
|
|
|
|
const prompt = parsed.data.prompt?.trim()
|
|
? `${userContext}Generate 6 diverse recipe ideas based on: "${parsed.data.prompt}". Include a mix of difficulty levels.`
|
|
: `${userContext}Generate 6 diverse, creative recipe ideas. Include different cuisines, difficulty levels, and meal types.`;
|
|
|
|
const { object } = await generateObject({
|
|
model,
|
|
schema: IdeasSchema,
|
|
prompt,
|
|
});
|
|
|
|
return NextResponse.json(object.ideas);
|
|
}
|