Files
smartmenu-collina/src/lib/json.ts
T
Jorem Juárez c001550e4f Optimize and harden the AI consultant
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.
2026-06-15 15:08:56 -06:00

57 lines
1.9 KiB
TypeScript

// Tolerate models that wrap JSON in prose or code fences.
export function extractJson(text: string): string {
const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/);
if (fenced) return fenced[1];
const start = text.indexOf('{');
const end = text.lastIndexOf('}');
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<T = Record<string, unknown>>(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;
}