From 1d9498b6d52975b95a130e53fb0a6a824fc45563 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorem=20Ju=C3=A1rez?= Date: Mon, 15 Jun 2026 15:15:35 -0600 Subject: [PATCH] Make AI consultant distinguish direct vs complement recommendations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The consultant could surface an unrelated dish as if it directly answered the request. Now each recommendation is classified and presented accordingly. - Prompt: model classifies each recommendation as type 'direct' (answers what was asked) or 'complement' (pairs with it). Direct first and primary; complements are optional and never used to pad to a count. Reasons must be anchored to a real dish attribute or the dish isn't recommended. If nothing matches directly, the intro says so gracefully instead of inventing a false direct match. - Route: parse/validate the type (defaults to 'direct' if missing), keep existing existence validation, order direct-first then complements, cap at 3. - UI: AiConsultant renders direct cards first, then a 'Para acompañar' / 'To pair with' header before complements (glassmorphism preserved). - i18n: ai.pairWith in es/en (parity); the type field itself is internal, not translated. Keeps prompt caching and the compact menu context. Verified: build passes; parser orders direct-first, drops non-existent dishes, defaults missing type to direct. --- messages/en.json | 3 +- messages/es.json | 3 +- src/app/api/[slug]/ai-consult/route.ts | 54 +++++++++++++++++++++----- src/components/public/AiConsultant.tsx | 31 +++++++++++---- 4 files changed, 72 insertions(+), 19 deletions(-) diff --git a/messages/en.json b/messages/en.json index 2fa5f67..8f70a7a 100644 --- a/messages/en.json +++ b/messages/en.json @@ -43,7 +43,8 @@ "title": "Menu consultant", "placeholder": "What do you recommend if I'm diabetic?", "thinking": "Thinking…", - "intro": "Tell me what you're after and I'll recommend dishes from the menu." + "intro": "Tell me what you're after and I'll recommend dishes from the menu.", + "pairWith": "To pair with" }, "editor": { "save": "Save", diff --git a/messages/es.json b/messages/es.json index 5fd9a1e..407da34 100644 --- a/messages/es.json +++ b/messages/es.json @@ -43,7 +43,8 @@ "title": "Consultor del menú", "placeholder": "¿Qué me recomiendas si soy diabético?", "thinking": "Pensando…", - "intro": "Cuéntame qué buscas y te recomiendo platillos del menú." + "intro": "Cuéntame qué buscas y te recomiendo platillos del menú.", + "pairWith": "Para acompañar" }, "editor": { "save": "Guardar", diff --git a/src/app/api/[slug]/ai-consult/route.ts b/src/app/api/[slug]/ai-consult/route.ts index 059aa8f..c5c9704 100644 --- a/src/app/api/[slug]/ai-consult/route.ts +++ b/src/app/api/[slug]/ai-consult/route.ts @@ -77,15 +77,39 @@ export async function POST(req: Request, { params }: { params: { slug: string } locale === 'en' ? `You are a friendly menu consultant for the restaurant "${menu.restaurant.name}". ` + `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}]}.` + + `Always answer in English. Each reason must be ONE concise sentence anchored to a REAL ` + + `attribute of the dish (an ingredient, preparation, diet tag, etc.) — if you can't give a ` + + `concrete reason why it fits, do not recommend it.\n` + + `Classify every recommendation with "type":\n` + + `- "direct": directly answers what the diner asked (they asked for salmon -> a dish with salmon).\n` + + `- "complement": something that pairs with or complements the request (e.g. a drink or dessert).\n` + + `Rules: put direct recommendations FIRST; they are the main answer. Complements are OPTIONAL — ` + + `include them only if they add real value, NEVER to pad to a number. If there are enough direct ` + + `matches there may be no complement. If the request is very specific and only 1 dish matches, ` + + `it's fine to return that 1 direct + 1 labeled complement instead of forcing a second weak "direct". ` + + `Max 3 recommendations total.\n` + + `If the menu has nothing that directly matches the request, SAY SO gracefully in "intro" ` + + `("We don't have a dish specifically of X, but the closest would be...") instead of inventing a ` + + `false direct match; in that case recommendations may all be complement / closest alternatives.\n` + + `Reply ONLY with JSON: {"intro": string, "recommendations": [{"dish": string, "reason": string, "type": "direct"|"complement"}]}.` + `\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, 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}]}.` + + `Responde siempre en español. Cada razón debe ser UNA oración concisa anclada a un atributo REAL ` + + `del platillo (un ingrediente, preparación, tag de dieta, etc.) — si no puedes dar una razón ` + + `concreta de por qué encaja, no lo recomiendes.\n` + + `Clasifica cada recomendación con "type":\n` + + `- "direct": responde directamente a lo que pidió el comensal (pidió salmón -> un platillo con salmón).\n` + + `- "complement": algo que acompaña o complementa lo pedido (p. ej. una bebida o un postre).\n` + + `Reglas: las recomendaciones direct van PRIMERO; son la respuesta principal. Los complement son ` + + `OPCIONALES — inclúyelos solo si aportan valor real, NUNCA para rellenar hasta un número. Si hay ` + + `suficientes matches directos puede no haber ningún complemento. Si lo pedido es muy específico y ` + + `solo encaja 1 platillo, está bien devolver ese 1 direct + 1 complement etiquetado en vez de forzar ` + + `un segundo "direct" que no encaje. Máximo 3 recomendaciones en total.\n` + + `Si el menú no tiene nada que encaje directamente, DILO con gracia en "intro" ` + + `("No tenemos un platillo específicamente de X, pero lo más cercano sería...") en vez de inventar un ` + + `match directo falso; en ese caso las recomendaciones pueden ser todas complement / lo más cercano.\n` + + `Responde SOLO con JSON: {"intro": string, "recommendations": [{"dish": string, "reason": string, "type": "direct"|"complement"}]}.` + `\n\nMENÚ:\n${context}`; try { @@ -103,13 +127,23 @@ export async function POST(req: Request, { params }: { params: { slug: string } 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 }) + const valid = raw + .map((r) => r as { dish?: unknown; reason?: unknown; type?: 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 })); + .map((r) => ({ + dish: r.dish as string, + reason: r.reason as string, + // Default to 'direct' if the model omits/garbles the type. + type: r.type === 'complement' ? ('complement' as const) : ('direct' as const), + })); + + // Direct first (main answer), complements after; cap at 3 total. + const recommendations = [ + ...valid.filter((r) => r.type === 'direct'), + ...valid.filter((r) => r.type === 'complement'), + ].slice(0, 3); return NextResponse.json({ intro: typeof json?.intro === 'string' ? json.intro : undefined, diff --git a/src/components/public/AiConsultant.tsx b/src/components/public/AiConsultant.tsx index 292cd1d..706c37f 100644 --- a/src/components/public/AiConsultant.tsx +++ b/src/components/public/AiConsultant.tsx @@ -3,7 +3,7 @@ import { useState } from 'react'; import { useLocale, useTranslations } from 'next-intl'; -type Recommendation = { dish: string; reason: string }; +type Recommendation = { dish: string; reason: string; type?: 'direct' | 'complement' }; export default function AiConsultant({ slug, onClose }: { slug: string; onClose: () => void }) { const t = useTranslations('ai'); @@ -54,12 +54,29 @@ export default function AiConsultant({ slug, onClose }: { slug: string; onClose: {answer && (
{answer.intro &&

{answer.intro}

} - {answer.recommendations.map((r, i) => ( -
-
{r.dish}
-

{r.reason}

-
- ))} + {(() => { + const direct = answer.recommendations.filter((r) => r.type !== 'complement'); + const complement = answer.recommendations.filter((r) => r.type === 'complement'); + const Card = (r: Recommendation, i: number) => ( +
+
{r.dish}
+

{r.reason}

+
+ ); + return ( + <> + {direct.map(Card)} + {complement.length > 0 && ( + <> +

+ {t('pairWith')} +

+ {complement.map((r, i) => Card(r, direct.length + i))} + + )} + + ); + })()}
)}