Make AI consultant distinguish direct vs complement recommendations

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.
This commit is contained in:
Jorem Juárez committed 2026-06-15 15:15:35 -06:00
1 parent c001550e4f
commit 1d9498b6d5
4 files changed
+72 -19

No files matched your search

+2 -1
View File
@@ -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",
+2 -1
View File
@@ -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",
+44 -10
View File
@@ -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,
+24 -7
View File
@@ -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 && (
<div className="flex flex-col gap-2">
{answer.intro && <p className="text-sm text-[var(--text)]/80">{answer.intro}</p>}
{answer.recommendations.map((r, i) => (
<div key={i} className="glass-soft rounded-2xl p-3">
<div className="font-semibold text-[var(--accent)]">{r.dish}</div>
<p className="text-sm text-[var(--text)]/80">{r.reason}</p>
</div>
))}
{(() => {
const direct = answer.recommendations.filter((r) => r.type !== 'complement');
const complement = answer.recommendations.filter((r) => r.type === 'complement');
const Card = (r: Recommendation, i: number) => (
<div key={i} className="glass-soft rounded-2xl p-3">
<div className="font-semibold text-[var(--accent)]">{r.dish}</div>
<p className="text-sm text-[var(--text)]/80">{r.reason}</p>
</div>
);
return (
<>
{direct.map(Card)}
{complement.length > 0 && (
<>
<p className="mt-1 text-xs font-semibold uppercase tracking-wide text-[var(--text)]/50">
{t('pairWith')}
</p>
{complement.map((r, i) => Card(r, direct.length + i))}
</>
)}
</>
);
})()}
</div>
)}
</div>