From c001550e4f8eb042f23116c603e0a25e0ea8cabf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorem=20Ju=C3=A1rez?= Date: Mon, 15 Jun 2026 15:08:56 -0600 Subject: [PATCH] Optimize and harden the AI consultant MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A) Token optimization: - Prompt caching: the stable block (system instructions + full menu) is now a single cached system text block with cache_control:ephemeral and goes first; the variable diner question stays in messages, after the cache breakpoint, so the cached prefix is byte-identical between queries of the same restaurant/locale - Compact context: only name, price, short description (<=120 chars), diet tags and allergens; macros are omitted (rarely change a recommendation). Inactive dishes still skipped B) Hardening: - Validate existence: each recommended dish must match a real active menu name (accent/case/space-insensitive, both locales); non-existent dishes are dropped - Fewer than 3 valid is fine — return what's valid, never pad with non-fitting dishes - Robust parsing: reuse the import's tolerant parser (extractJson + repairTruncatedJson, now shared in lib/json.ts) so truncated/prose replies don't 502 - max_tokens 700 -> 900 and system prompt asks for one-sentence reasons Refactor: repairTruncatedJson + parseLenientJson moved into lib/json.ts and shared by import.ts and ai-consult. No behavior change to import. Verified: build passes; existence filter drops fake dishes, recovers truncated+prose replies, and returns <3 without padding. --- src/app/api/[slug]/ai-consult/route.ts | 91 ++++++++++++++++++-------- src/lib/import.ts | 52 +-------------- src/lib/json.ts | 47 +++++++++++++ 3 files changed, 113 insertions(+), 77 deletions(-) diff --git a/src/app/api/[slug]/ai-consult/route.ts b/src/app/api/[slug]/ai-consult/route.ts index 46d4f13..059aa8f 100644 --- a/src/app/api/[slug]/ai-consult/route.ts +++ b/src/app/api/[slug]/ai-consult/route.ts @@ -1,35 +1,57 @@ import { NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import { getAnthropic, HAIKU_MODEL } from '@/lib/anthropic'; -import { extractJson } from '@/lib/json'; +import { parseLenientJson } from '@/lib/json'; import { pickText } from '@/lib/text'; import type { Locale } from '@/i18n/config'; import type { MenuSnapshot } from '@/lib/types'; export const dynamic = 'force-dynamic'; -// Build a compact text context of the published menu for the model. +// Normalize a dish name for existence matching (accent/case/space-insensitive). +function normName(s: string): string { + return s + .toLowerCase() + .normalize('NFD') + .replace(/\p{Diacritic}/gu, '') + .replace(/\s+/g, ' ') + .trim(); +} + +// Compact menu context for the consultant: name, price, short description, diet +// tags and allergens. Macros are intentionally OMITTED — they rarely change a +// recommendation and cost tokens. Inactive products are skipped. function buildMenuContext(menu: MenuSnapshot, locale: Locale): string { const lines: string[] = []; for (const section of menu.sections) { lines.push(`## ${pickText(section.name, locale)}`); for (const p of section.products) { if (!p.isActive) continue; - const macros = Object.entries(p.macros) - .filter(([, v]) => v != null) - .map(([k, v]) => `${k}:${v}`) - .join(', '); + const desc = pickText(p.description, locale).slice(0, 120); lines.push( - `- ${pickText(p.name, locale)} ($${p.price.toFixed(2)}): ${pickText(p.description, locale)}` + + `- ${pickText(p.name, locale)} ($${p.price.toFixed(2)})` + + (desc ? `: ${desc}` : '') + (p.dietTags.length ? ` | dieta: ${p.dietTags.join(', ')}` : '') + - (p.allergens.length ? ` | alérgenos: ${p.allergens.join(', ')}` : '') + - (macros ? ` | macros: ${macros}` : ''), + (p.allergens.length ? ` | alérgenos: ${p.allergens.join(', ')}` : ''), ); } } return lines.join('\n'); } +// Set of every active dish name (both locales) for existence validation. +function buildNameSet(menu: MenuSnapshot): Set { + const set = new Set(); + for (const section of menu.sections) { + for (const p of section.products) { + if (!p.isActive) continue; + if (p.name.es) set.add(normName(p.name.es)); + if (p.name.en) set.add(normName(p.name.en)); + } + } + return set; +} + export async function POST(req: Request, { params }: { params: { slug: string } }) { const body = await req.json().catch(() => null); const question = String(body?.question ?? '').trim(); @@ -46,37 +68,52 @@ export async function POST(req: Request, { params }: { params: { slug: string } const menu = restaurant.publishedVersion.snapshot as unknown as MenuSnapshot; const context = buildMenuContext(menu, locale); + const nameSet = buildNameSet(menu); - const system = + // Stable, cacheable block: system instructions + full menu. Must be identical + // byte-for-byte between queries of the same restaurant/locale for the cache to + // hit. The variable diner question goes AFTER the cache breakpoint, in messages. + const cacheable = locale === 'en' ? `You are a friendly menu consultant for the restaurant "${menu.restaurant.name}". ` + - `Recommend ONLY dishes that appear in the menu below. Always answer in English. ` + - `Give exactly 3 recommendations, each citing the real dish name and a short reason it fits. ` + - `Reply ONLY with JSON: {"intro": string, "recommendations": [{"dish": string, "reason": string}]}.` + `Recommend ONLY dishes that appear in the menu below, citing the real dish name exactly. ` + + `Always answer in English. Give up to 3 recommendations (fewer if few dishes truly fit; ` + + `never pad with dishes that don't fit). Each reason must be concise — ONE sentence. ` + + `Reply ONLY with JSON: {"intro": string, "recommendations": [{"dish": string, "reason": string}]}.` + + `\n\nMENU:\n${context}` : `Eres un consultor amable del menú del restaurante "${menu.restaurant.name}". ` + - `Recomienda SOLO platillos que aparezcan en el menú de abajo. Responde siempre en español. ` + - `Da exactamente 3 recomendaciones, cada una citando el nombre real del platillo y una razón breve. ` + - `Responde SOLO con JSON: {"intro": string, "recommendations": [{"dish": string, "reason": string}]}.`; + `Recomienda SOLO platillos que aparezcan en el menú de abajo, citando el nombre real exacto. ` + + `Responde siempre en español. Da hasta 3 recomendaciones (menos si pocos platillos encajan de verdad; ` + + `nunca rellenes con platillos que no encajan). Cada razón debe ser concisa — UNA oración. ` + + `Responde SOLO con JSON: {"intro": string, "recommendations": [{"dish": string, "reason": string}]}.` + + `\n\nMENÚ:\n${context}`; try { const client = getAnthropic(); const msg = await client.messages.create({ model: HAIKU_MODEL, - max_tokens: 700, - system, - messages: [ - { - role: 'user', - content: `MENÚ:\n${context}\n\nPREGUNTA: ${question}`, - }, - ], + max_tokens: 900, + system: [{ type: 'text', text: cacheable, cache_control: { type: 'ephemeral' } }], + messages: [{ role: 'user', content: question }], }); const text = msg.content.find((c) => c.type === 'text')?.text ?? '{}'; - const json = JSON.parse(extractJson(text)); + // Lenient parse (shared with import): tolerates prose/fences/truncation so a + // malformed reply doesn't 502. + const json = parseLenientJson<{ intro?: unknown; recommendations?: unknown }>(text); + + const raw = Array.isArray(json?.recommendations) ? json!.recommendations : []; + const recommendations = raw + .map((r) => r as { dish?: unknown; reason?: unknown }) + .filter((r) => typeof r.dish === 'string' && typeof r.reason === 'string') + // Drop any recommendation whose dish doesn't exist in the real menu. + .filter((r) => nameSet.has(normName(r.dish as string))) + .slice(0, 3) + .map((r) => ({ dish: r.dish as string, reason: r.reason as string })); + return NextResponse.json({ - intro: typeof json.intro === 'string' ? json.intro : undefined, - recommendations: Array.isArray(json.recommendations) ? json.recommendations.slice(0, 3) : [], + intro: typeof json?.intro === 'string' ? json.intro : undefined, + recommendations, }); } catch (err) { console.error('ai-consult error', err); diff --git a/src/lib/import.ts b/src/lib/import.ts index 117e49a..710274f 100644 --- a/src/lib/import.ts +++ b/src/lib/import.ts @@ -1,7 +1,7 @@ import * as XLSX from 'xlsx'; import Anthropic from '@anthropic-ai/sdk'; import { getAnthropic, HAIKU_MODEL, SONNET_MODEL } from './anthropic'; -import { extractJson } from './json'; +import { parseLenientJson } from './json'; import type { Locale } from '@/i18n/config'; // Structure returned for review (NOT yet applied to the draft). @@ -181,7 +181,7 @@ export async function extractMenu( }); const text = msg.content.find((c) => c.type === 'text')?.text ?? '{}'; - const parsed = parseMenuJson(text); + const parsed = parseLenientJson<{ sections?: unknown }>(text); if (!parsed) { // Truncation (hit the token ceiling) vs other malformed output. throw new Error(msg.stop_reason === 'max_tokens' ? 'output_truncated' : 'parse_failed'); @@ -189,54 +189,6 @@ export async function extractMenu( return { sections: normalizeSections(parsed.sections) }; } -// Parse the model's JSON tolerantly: handle fences/surrounding prose via -// extractJson, and attempt to repair JSON truncated by the token limit by -// closing any open strings/brackets and dropping a trailing partial entry. -// Returns null if it still can't be parsed (caller maps to a friendly error). -function parseMenuJson(text: string): { sections?: unknown } | null { - const candidate = extractJson(text); - const attempts = [candidate, repairTruncatedJson(candidate)]; - for (const a of attempts) { - try { - const obj = JSON.parse(a); - if (obj && typeof obj === 'object') return obj as { sections?: unknown }; - } catch { - /* try next */ - } - } - return null; -} - -// Best-effort repair of JSON cut off mid-output: close an open string, drop a -// dangling trailing fragment, then balance the remaining open { and [. -function repairTruncatedJson(input: string): string { - let inStr = false; - let esc = false; - const stack: string[] = []; - for (let i = 0; i < input.length; i++) { - const ch = input[i]; - if (inStr) { - if (esc) esc = false; - else if (ch === '\\') esc = true; - else if (ch === '"') inStr = false; - continue; - } - if (ch === '"') inStr = true; - else if (ch === '{' || ch === '[') stack.push(ch); - else if (ch === '}' || ch === ']') stack.pop(); - } - - let out = input; - if (inStr) out += '"'; - // Drop a trailing incomplete property like `"price":` or a dangling comma. - out = out.replace(/[\s,]*("[^"]*"\s*:\s*)?$/u, ''); - out = out.replace(/[\s,]+$/u, ''); - for (let i = stack.length - 1; i >= 0; i--) { - out += stack[i] === '{' ? '}' : ']'; - } - return out; -} - // Defensive normalization so a partially-malformed model reply can't crash apply. function normalizeSections(sections: unknown): ImportedSection[] { if (!Array.isArray(sections)) return []; diff --git a/src/lib/json.ts b/src/lib/json.ts index aafc9ee..0d4c00f 100644 --- a/src/lib/json.ts +++ b/src/lib/json.ts @@ -7,3 +7,50 @@ export function extractJson(text: string): string { if (start !== -1 && end !== -1) return text.slice(start, end + 1); return text; } + +// Best-effort repair of JSON cut off mid-output (e.g. hit the token ceiling): +// close an open string, drop a dangling trailing fragment, then balance the +// remaining open { and [. +export function repairTruncatedJson(input: string): string { + let inStr = false; + let esc = false; + const stack: string[] = []; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (inStr) { + if (esc) esc = false; + else if (ch === '\\') esc = true; + else if (ch === '"') inStr = false; + continue; + } + if (ch === '"') inStr = true; + else if (ch === '{' || ch === '[') stack.push(ch); + else if (ch === '}' || ch === ']') stack.pop(); + } + + let out = input; + if (inStr) out += '"'; + // Drop a trailing incomplete property like `"price":` or a dangling comma. + out = out.replace(/[\s,]*("[^"]*"\s*:\s*)?$/u, ''); + out = out.replace(/[\s,]+$/u, ''); + for (let i = stack.length - 1; i >= 0; i--) { + out += stack[i] === '{' ? '}' : ']'; + } + return out; +} + +// Parse a model reply tolerantly: strip fences/prose via extractJson, then try +// the raw candidate and a truncation-repaired version. Returns the parsed object +// (or null if still unparseable) so callers never crash on malformed output. +export function parseLenientJson>(text: string): T | null { + const candidate = extractJson(text); + for (const a of [candidate, repairTruncatedJson(candidate)]) { + try { + const obj = JSON.parse(a); + if (obj && typeof obj === 'object') return obj as T; + } catch { + /* try next */ + } + } + return null; +}