feat(ai): Vercel AI SDK provider factory with BYOK and per-use-case model prefs

Provider factory (OpenAI/Anthropic/OpenRouter/Ollama). generateObject for all outputs.
Features: recipe generation, photo-to-recipe vision, variations, drink/meal pairings,
ingredient substitution, recipe adaptation, nutrition analysis, URL import, meal plan gen.
User BYOK keys (AES-256-GCM). Per-use-case model preferences (text/vision/mealPlan).
Site-level key override via admin settings.
This commit is contained in:
Arnaud
2026-07-01 08:10:19 +02:00
parent 84d6cfeb07
commit d9d58fd01a
26 changed files with 1656 additions and 0 deletions
+114
View File
@@ -0,0 +1,114 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { checkTierLimit, incrementUsage } from "@/lib/tiers";
import { adaptRecipe } from "@/lib/ai/features/adapt-recipe";
import { withUserKey } from "@/lib/ai/resolve-user-key";
const Schema = z.object({
excludeIngredients: z.array(z.string()).default([]),
extraConstraints: z.string().max(500).optional(),
provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]).optional(),
model: z.string().optional(),
});
type Params = { params: Promise<{ id: string }> };
export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const userId = session!.user.id;
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id)),
with: {
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
steps: { orderBy: (t, { asc }) => asc(t.order) },
},
});
if (!recipe || (recipe.visibility === "private" && recipe.authorId !== userId)) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
if (parsed.data.excludeIngredients.length === 0 && !parsed.data.extraConstraints?.trim()) {
return NextResponse.json({ error: "Provide at least one constraint" }, { status: 400 });
}
await checkTierLimit(userId, session!.user.tier as "free" | "pro", "aiCall");
const aiConfig = await withUserKey(userId, { provider: parsed.data.provider, model: parsed.data.model });
const adapted = await adaptRecipe(
{
title: recipe.title,
description: recipe.description,
baseServings: recipe.baseServings,
ingredients: recipe.ingredients,
steps: recipe.steps,
},
{
excludeIngredients: parsed.data.excludeIngredients,
extraConstraints: parsed.data.extraConstraints,
},
aiConfig,
(session!.user as { locale?: string }).locale ?? "en"
);
await incrementUsage(userId, "aiCall");
const newId = crypto.randomUUID();
const now = new Date();
await db.transaction(async (tx) => {
await tx.insert(recipes).values({
id: newId,
authorId: userId,
title: adapted.title,
description: adapted.description,
baseServings: adapted.baseServings,
visibility: "private",
difficulty: adapted.difficulty,
prepMins: adapted.prepMins,
cookMins: adapted.cookMins,
dietaryTags: adapted.dietaryTags ?? {},
aiGenerated: true,
createdAt: now,
updatedAt: now,
});
if (adapted.ingredients.length > 0) {
await tx.insert(recipeIngredients).values(
adapted.ingredients.map((ing, i) => ({
id: crypto.randomUUID(),
recipeId: newId,
rawName: ing.rawName,
quantity: ing.quantity !== undefined ? String(ing.quantity) : undefined,
unit: ing.unit,
note: ing.note,
order: i,
}))
);
}
if (adapted.steps.length > 0) {
await tx.insert(recipeSteps).values(
adapted.steps.map((step, i) => ({
id: crypto.randomUUID(),
recipeId: newId,
instruction: step.instruction,
timerSeconds: step.timerSeconds,
order: i,
}))
);
}
});
return NextResponse.json({ id: newId, adaptationNotes: adapted.adaptationNotes });
}
@@ -0,0 +1,55 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { checkTierLimit, incrementUsage } from "@/lib/tiers";
import { suggestDrinks } from "@/lib/ai/features/suggest-drinks";
import { withUserKey } from "@/lib/ai/resolve-user-key";
const Schema = z.object({
count: z.number().int().min(1).max(6).default(4),
provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]).optional(),
model: z.string().optional(),
});
type Params = { params: Promise<{ id: string }> };
export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id)),
with: { ingredients: true },
});
if (!recipe || (recipe.visibility === "private" && recipe.authorId !== session!.user.id)) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body ?? {});
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
await checkTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
const aiConfig = await withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model });
const drinks = await suggestDrinks(
{
title: recipe.title,
description: recipe.description,
difficulty: recipe.difficulty,
dietaryTags: recipe.dietaryTags as Record<string, boolean> | null,
ingredients: recipe.ingredients,
},
parsed.data.count,
aiConfig,
(session!.user as { locale?: string }).locale ?? "en"
);
await incrementUsage(session!.user.id, "aiCall");
return NextResponse.json({ drinks });
}
+39
View File
@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { checkTierLimit, incrementUsage } from "@/lib/tiers";
import { generateRecipe } from "@/lib/ai/features/generate-recipe";
const Schema = z.object({
prompt: z.string().min(3).max(500),
language: z.string().max(10).default("en"),
provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]).optional(),
model: z.string().optional(),
});
export async function POST(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
if (limited) return limited;
await checkTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
const recipe = await generateRecipe(parsed.data.prompt, {
provider: parsed.data.provider,
model: parsed.data.model,
language: parsed.data.language,
});
await incrementUsage(session!.user.id, "aiCall");
return NextResponse.json(recipe);
}
@@ -0,0 +1,104 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { checkTierLimit, incrementUsage } from "@/lib/tiers";
import { importFromPhoto } from "@/lib/ai/features/import-photo";
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
const Schema = z.object({
imageBase64: z.string().max(14_000_000),
mimeType: z.enum(["image/jpeg", "image/png", "image/webp"]),
});
export async function POST(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 5, 60);
if (limited) return limited;
try {
await checkTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : "Tier limit reached";
return NextResponse.json({ error: msg }, { status: 403 });
}
const userId = session!.user.id;
const locale = (session!.user as { locale?: string }).locale ?? "en";
const aiConfig = await getModelConfigForUseCase(userId, "vision");
// Fall back to vision-capable defaults if no explicit model configured
if (!aiConfig.model) {
if (aiConfig.provider === "openai") aiConfig.model = "gpt-4o";
else if (aiConfig.provider === "anthropic") aiConfig.model = "claude-sonnet-4-6";
}
let recipe;
try {
recipe = await importFromPhoto(parsed.data.imageBase64, parsed.data.mimeType, aiConfig, locale);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : "AI analysis failed";
return NextResponse.json({ error: msg }, { status: 502 });
}
await incrementUsage(userId, "aiCall");
const newRecipeId = crypto.randomUUID();
const now = new Date();
await db.transaction(async (tx) => {
await tx.insert(recipes).values({
id: newRecipeId,
authorId: userId,
title: recipe.title,
description: recipe.description,
baseServings: recipe.baseServings ?? 4,
visibility: "private",
difficulty: recipe.difficulty,
prepMins: recipe.prepMins,
cookMins: recipe.cookMins,
dietaryTags: recipe.dietaryTags ?? {},
aiGenerated: true,
createdAt: now,
updatedAt: now,
});
if (recipe.ingredients.length > 0) {
await tx.insert(recipeIngredients).values(
recipe.ingredients.map((ing, i) => ({
id: crypto.randomUUID(),
recipeId: newRecipeId,
rawName: ing.rawName,
quantity: ing.quantity !== undefined ? String(ing.quantity) : undefined,
unit: ing.unit,
note: ing.note,
order: i,
}))
);
}
if (recipe.steps.length > 0) {
await tx.insert(recipeSteps).values(
recipe.steps.map((step, i) => ({
id: crypto.randomUUID(),
recipeId: newRecipeId,
instruction: step.instruction,
timerSeconds: step.timerSeconds,
order: i,
}))
);
}
});
return NextResponse.json({ id: newRecipeId });
}
@@ -0,0 +1,37 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { checkTierLimit, incrementUsage } from "@/lib/tiers";
import { importFromUrl } from "@/lib/ai/features/import-url";
const Schema = z.object({
url: z.string().url(),
provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]).optional(),
model: z.string().optional(),
});
export async function POST(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 10, 60);
if (limited) return limited;
await checkTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
const recipe = await importFromUrl(parsed.data.url, {
provider: parsed.data.provider,
model: parsed.data.model,
});
await incrementUsage(session!.user.id, "aiCall");
return NextResponse.json(recipe);
}
@@ -0,0 +1,142 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, recipes, recipeIngredients, recipeSteps, mealPlans, mealPlanEntries, pantryItems, eq, and } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
import { generateMealPlan } from "@/lib/ai/features/generate-meal-plan";
const DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
const Schema = z.object({
weekStart: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
dietaryPrefs: z.string().max(200).optional(),
servings: z.number().int().min(1).max(20).default(2),
days: z.array(z.enum(DAYS)).min(1).max(7).default([...DAYS]),
usePantry: z.boolean().default(false),
pantryMode: z.boolean().default(false),
});
export async function POST(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
const limited = await applyRateLimit(`rl:ai:${session!.user.id}`, 3, 60);
if (limited) return limited;
const userId = session!.user.id;
const locale = (session!.user as { locale?: string }).locale ?? "en";
const config = await getDefaultProviderWithKey(userId);
// pantryMode forces usePantry on so pantry items are always fetched when maximizing pantry use
const effectiveUsePantry = parsed.data.usePantry || parsed.data.pantryMode;
// Optionally fetch pantry items
let pantryItemNames: string[] = [];
if (effectiveUsePantry) {
const pantry = await db
.select({ rawName: pantryItems.rawName })
.from(pantryItems)
.where(eq(pantryItems.userId, userId));
pantryItemNames = pantry.map((p) => p.rawName);
}
const plan = await generateMealPlan(
{
dietaryPrefs: parsed.data.dietaryPrefs,
servings: parsed.data.servings,
pantryItems: pantryItemNames,
days: parsed.data.days,
pantryMode: parsed.data.pantryMode,
},
config,
locale
);
// Ensure meal plan row exists for the week
let mealPlan = await db.query.mealPlans.findFirst({
where: and(eq(mealPlans.userId, userId), eq(mealPlans.weekStart, parsed.data.weekStart)),
});
if (!mealPlan) {
const planId = crypto.randomUUID();
await db.insert(mealPlans).values({ id: planId, userId, weekStart: parsed.data.weekStart });
mealPlan = { id: planId, userId, weekStart: parsed.data.weekStart, createdAt: new Date() };
}
const createdEntries: Array<{ id: string; day: string; mealType: string; recipeId: string; recipeTitle: string }> = [];
for (const entry of plan.entries) {
// Create draft recipe
const recipeId = crypto.randomUUID();
await db.insert(recipes).values({
id: recipeId,
authorId: userId,
title: entry.recipe.title,
description: entry.recipe.description,
baseServings: entry.servings,
visibility: "private",
aiGenerated: true,
difficulty: entry.recipe.difficulty ?? null,
prepMins: entry.recipe.prepMins ?? null,
cookMins: entry.recipe.cookMins ?? null,
});
if (entry.recipe.ingredients.length > 0) {
await db.insert(recipeIngredients).values(
entry.recipe.ingredients.map((ing, i) => ({
id: crypto.randomUUID(),
recipeId,
rawName: ing.rawName,
quantity: ing.quantity ?? null,
unit: ing.unit ?? null,
order: i,
}))
);
}
if (entry.recipe.steps.length > 0) {
await db.insert(recipeSteps).values(
entry.recipe.steps.map((step, i) => ({
id: crypto.randomUUID(),
recipeId,
instruction: step.instruction,
order: i,
}))
);
}
// Remove any existing entry for this day+mealType, then insert new
const existingEntry = await db.query.mealPlanEntries.findFirst({
where: and(
eq(mealPlanEntries.mealPlanId, mealPlan!.id),
eq(mealPlanEntries.day, entry.day),
eq(mealPlanEntries.mealType, entry.mealType)
),
});
if (existingEntry) {
await db.delete(mealPlanEntries).where(eq(mealPlanEntries.id, existingEntry.id));
}
const entryId = crypto.randomUUID();
await db.insert(mealPlanEntries).values({
id: entryId,
mealPlanId: mealPlan!.id,
day: entry.day,
mealType: entry.mealType,
recipeId,
servings: entry.servings,
});
createdEntries.push({ id: entryId, day: entry.day, mealType: entry.mealType, recipeId, recipeTitle: entry.recipe.title });
}
return NextResponse.json({ weekStart: parsed.data.weekStart, entries: createdEntries });
}
@@ -0,0 +1,56 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { checkTierLimit, incrementUsage } from "@/lib/tiers";
import { suggestPairings } from "@/lib/ai/features/suggest-pairings";
import { withUserKey } from "@/lib/ai/resolve-user-key";
const Schema = z.object({
count: z.number().int().min(1).max(6).default(4),
provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]).optional(),
model: z.string().optional(),
});
type Params = { params: Promise<{ id: string }> };
export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
// Allow pairings for own recipes or public recipes
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id)),
with: { ingredients: true },
});
if (!recipe || (recipe.visibility === "private" && recipe.authorId !== session!.user.id)) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body ?? {});
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
await checkTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
const aiConfig = await withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model });
const pairings = await suggestPairings(
{
title: recipe.title,
description: recipe.description,
difficulty: recipe.difficulty,
dietaryTags: recipe.dietaryTags as Record<string, boolean> | null,
ingredients: recipe.ingredients,
},
parsed.data.count,
aiConfig,
(session!.user as { locale?: string }).locale ?? "en"
);
await incrementUsage(session!.user.id, "aiCall");
return NextResponse.json({ pairings });
}
+62
View File
@@ -0,0 +1,62 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, recipes, eq, and, or } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { getDefaultProviderWithKey } from "@/lib/ai/resolve-user-key";
import { checkTierLimit, incrementUsage } from "@/lib/tiers";
import { scaleRecipe } from "@/lib/ai/features/scale-recipe";
const Schema = z.object({
recipeId: z.string(),
targetServings: z.number().int().min(1).max(100),
});
export async function POST(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const limited = await applyRateLimit(`rl:ai:scale:${session!.user.id}`, 20, 60);
if (limited) return limited;
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
const { recipeId, targetServings } = parsed.data;
const recipe = await db.query.recipes.findFirst({
where: and(
eq(recipes.id, recipeId),
or(
eq(recipes.authorId, session!.user.id),
eq(recipes.visibility, "public")
)
),
with: { ingredients: true },
});
if (!recipe) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
await checkTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
const aiConfig = await getDefaultProviderWithKey(session!.user.id);
const scaledIngredients = await scaleRecipe(
{
title: recipe.title,
baseServings: recipe.baseServings,
ingredients: recipe.ingredients,
},
targetServings,
recipe.baseServings,
aiConfig,
(session!.user as { locale?: string }).locale ?? "en"
);
await incrementUsage(session!.user.id, "aiCall");
return NextResponse.json({ ingredients: scaledIngredients });
}
@@ -0,0 +1,36 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { requireSession } from "@/lib/api-auth";
import { checkTierLimit, incrementUsage } from "@/lib/tiers";
import { substituteIngredient } from "@/lib/ai/features/substitute-ingredient";
const Schema = z.object({
ingredient: z.string().min(1).max(200),
recipeTitle: z.string().max(200).optional(),
provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]).optional(),
model: z.string().optional(),
});
export async function POST(req: NextRequest) {
const { session, response } = await requireSession();
if (response) return response;
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
await checkTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
const context = parsed.data.recipeTitle
? `recipe "${parsed.data.recipeTitle}"`
: "a general recipe";
const substitutions = await substituteIngredient(
parsed.data.ingredient,
context,
{ provider: parsed.data.provider, model: parsed.data.model }
);
await incrementUsage(session!.user.id, "aiCall");
return NextResponse.json({ substitutions });
}
@@ -0,0 +1,102 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes, recipeIngredients, recipeSteps } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { checkTierLimit, incrementUsage } from "@/lib/tiers";
import { translateRecipe } from "@/lib/ai/features/translate-recipe";
const Schema = z.object({
targetLanguage: z.string().min(2).max(50),
provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]).optional(),
model: z.string().optional(),
});
type Params = { params: Promise<{ id: string }> };
export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
with: {
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
steps: { orderBy: (t, { asc }) => asc(t.order) },
},
});
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
await checkTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
const translation = await translateRecipe(
{
title: recipe.title,
description: recipe.description,
ingredients: recipe.ingredients,
steps: recipe.steps,
},
parsed.data.targetLanguage,
{ provider: parsed.data.provider, model: parsed.data.model }
);
await incrementUsage(session!.user.id, "aiCall");
// Save as new draft recipe
const newId = crypto.randomUUID();
const now = new Date();
await db.transaction(async (tx) => {
await tx.insert(recipes).values({
id: newId,
authorId: session!.user.id,
title: translation.title,
description: translation.description,
baseServings: recipe.baseServings,
visibility: "private",
difficulty: recipe.difficulty,
prepMins: recipe.prepMins,
cookMins: recipe.cookMins,
dietaryTags: recipe.dietaryTags ?? {},
aiGenerated: true,
createdAt: now,
updatedAt: now,
});
if (translation.ingredients.length > 0) {
await tx.insert(recipeIngredients).values(
translation.ingredients.map((ing, i) => ({
id: crypto.randomUUID(),
recipeId: newId,
rawName: ing.rawName,
quantity: recipe.ingredients[i]?.quantity ?? undefined,
unit: recipe.ingredients[i]?.unit ?? undefined,
note: ing.note ?? undefined,
order: i,
}))
);
}
if (translation.steps.length > 0) {
await tx.insert(recipeSteps).values(
translation.steps.map((step, i) => ({
id: crypto.randomUUID(),
recipeId: newId,
instruction: step.instruction,
timerSeconds: recipe.steps[i]?.timerSeconds ?? undefined,
order: i,
}))
);
}
});
return NextResponse.json({ id: newId });
}
@@ -0,0 +1,59 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { and, eq } from "@epicure/db";
import { db, recipes } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { checkTierLimit, incrementUsage } from "@/lib/tiers";
import { suggestVariations } from "@/lib/ai/features/suggest-variations";
import { withUserKey } from "@/lib/ai/resolve-user-key";
const Schema = z.object({
count: z.number().int().min(1).max(5).default(3),
directions: z.string().max(500).optional(),
provider: z.enum(["openai", "anthropic", "openrouter", "ollama"]).optional(),
model: z.string().optional(),
});
type Params = { params: Promise<{ id: string }> };
export async function POST(req: NextRequest, { params }: Params) {
const { session, response } = await requireSession();
if (response) return response;
const { id } = await params;
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
with: {
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
steps: { orderBy: (t, { asc }) => asc(t.order) },
},
});
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
const body = await req.json() as unknown;
const parsed = Schema.safeParse(body ?? {});
if (!parsed.success) {
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
}
await checkTierLimit(session!.user.id, session!.user.tier as "free" | "pro", "aiCall");
const aiConfig = await withUserKey(session!.user.id, { provider: parsed.data.provider, model: parsed.data.model });
const variations = await suggestVariations(
{
title: recipe.title,
description: recipe.description,
ingredients: recipe.ingredients,
steps: recipe.steps,
},
parsed.data.count,
aiConfig,
parsed.data.directions,
(session!.user as { locale?: string }).locale ?? "en"
);
await incrementUsage(session!.user.id, "aiCall");
return NextResponse.json({ variations });
}