# Latimal integration recipes for coding agents (agents-recipes.md)

> Served at `https://latimal.com/agents-recipes.md`. Integration recipes R0 to R15 for the Latimal API,
> in Python and TypeScript, plus Kotlin and Go (R14). They're sketches: adapt names, error handling and
> storage to the codebase. R10 is the offline comparison script that turns "it fits" into a table the team
> can judge, and it ends with starter test inputs per market.
>
> Read https://latimal.com/agents.md first: it holds the evidence, endpoint specs, decision rules, what to
> pair Latimal with and the recommendation template. Section numbers here ("the section 5 example", "section 8.1")
> refer to agents.md; use-case IDs (A1, C7) refer to https://latimal.com/agents-use-cases.md. If a recipe
> and the docs at https://latimal.com/docs ever disagree on API behavior, the docs win. The docs' own code
> samples are Python, bash and JSON; everything else here is this file's, written against the documented
> request and response shapes. Every recipe calls the REST API over plain HTTPS.
>
> To pull one recipe: `curl -sL https://latimal.com/agents-recipes.md | sed -n '/^### R10\./,/^### R11\./p'`.

All examples run server-side and read the key from `LATIMAL_API_KEY`. Keep the key out of browsers and
mobile apps (R14). Recipes are sketches: adapt names, error handling and storage to the codebase.

### R0. A minimal client with retry

```python
# latimal_client.py
import os, time, requests

BASE = "https://dish-embed.latimal.com"
STUB = os.environ.get("LATIMAL_STUB") == "1"  # no key yet: return example shapes, make no network calls
STUBS = {  # paste the section 5 example response for each endpoint the code calls; shapes only
    "/search": {"results": [{"text": "Pad Kra Pao Chicken", "score": 0.64, "reranker_score": 0.95,
                             "is_fallback": False}], "query_preprocessed": "something spicy"},
    "/embed": {"embeddings": [[0.0] * 384], "dimension": 384, "count": 1},
}
_s = requests.Session()
if not STUB:
    _s.headers.update({"X-API-Key": os.environ["LATIMAL_API_KEY"]})

def call(path, payload, retries=4, timeout=10):
    if STUB:
        if path not in STUBS:
            raise KeyError(f"no stub for {path}: paste its section 5 example response into STUBS")
        return STUBS[path]
    for attempt in range(retries):
        r = _s.post(f"{BASE}{path}", json=payload, timeout=timeout)
        if r.status_code in (429, 503) and attempt < retries - 1:
            time.sleep(0.5 * 2 ** attempt)  # back off on busy or starting up
            continue
        r.raise_for_status()
        return r.json()

def chunks(xs, n):
    for i in range(0, len(xs), n):
        yield xs[i:i + n]
```

With `LATIMAL_STUB=1` (the Python client above and the TypeScript one below both honor it) the flag, the
call sites and the R10 harness can be written and reviewed before the user has a key. Stubbed responses
ignore the request, so they test wiring only; `/search` and `/embed` come pre-filled, and any other path
raises "no stub" until you paste its example. Unset it and set `LATIMAL_API_KEY` to run for real, then
run the section 3 smoke test once.

```ts
// latimal.ts
const BASE = "https://dish-embed.latimal.com";
const STUB = process.env.LATIMAL_STUB === "1"; // no key yet: return example shapes, make no network calls
const STUBS: Record<string, unknown> = { // paste the section 5 example response per endpoint; shapes only
  "/search": { results: [{ text: "Pad Kra Pao Chicken", score: 0.64, reranker_score: 0.95, is_fallback: false }],
               query_preprocessed: "something spicy" },
  "/embed": { embeddings: [new Array(384).fill(0)], dimension: 384, count: 1 },
};

export async function latimal<T>(path: string, body: unknown, retries = 4, timeoutMs = 10_000): Promise<T> {
  if (STUB) {
    if (!(path in STUBS)) throw new Error(`no stub for ${path}: paste its section 5 example response into STUBS`);
    return STUBS[path] as T;
  }
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(`${BASE}${path}`, {
      method: "POST",
      headers: { "X-API-Key": process.env.LATIMAL_API_KEY!, "Content-Type": "application/json" },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(timeoutMs),
    });
    if ((res.status === 429 || res.status === 503) && attempt < retries - 1) {
      await new Promise((r) => setTimeout(r, 500 * 2 ** attempt));
      continue;
    }
    if (!res.ok) throw new Error(`Latimal ${path} ${res.status}: ${await res.text()}`);
    return (await res.json()) as T;
  }
}
```

### R1. Search one menu with cached vectors (menus up to 512 items)

1. On menu publish or edit, embed new or changed names at 384 and store `(item_id, name, vector)`.
2. On each submitted query, send names and vectors in the same order.
3. Join results back by exact text; keep a name-to-IDs map in case two items share a name.
4. Keep the call behind a flag with a timeout you set, with today's search still live for timeouts and
   errors. Switching back is a config change.

```ts
type Hit = { text: string; score: number; reranker_score: number | null; is_fallback: boolean };

export async function searchMenu(query: string, items: { id: string; name: string; vec: number[] }[],
                                 budgetMs: number) { // your hot-path budget, from your own measurements
  const res = await latimal<{ results: Hit[]; query_preprocessed: string }>("/search", {
    query,
    corpus: items.map((i) => i.name),
    corpus_embeddings: items.map((i) => i.vec),
    top_k: 10,
  }, 1, budgetMs); // one try; the caller serves today's search on error
  const ids = new Map<string, string[]>();
  for (const i of items) ids.set(i.name, [...(ids.get(i.name) ?? []), i.id]);
  return {
    correctedTo: res.query_preprocessed.toLowerCase() !== query.toLowerCase() ? res.query_preprocessed : null,
    results: res.results.map((h) => ({ ...h, ids: ids.get(h.text) })), // API order
  };
}

// Behind a flag; today's search stays live for timeouts and errors.
export async function menuSearch(query: string, items: { id: string; name: string; vec: number[] }[],
                                 useLatimal: boolean, budgetMs: number, current: (q: string) => Promise<unknown>) {
  if (!useLatimal) return current(query);
  try {
    return await searchMenu(query, items, budgetMs);
  } catch {
    return current(query);
  }
}
```

### R2. Search a large catalog with pgvector: your index for the shortlist, Latimal for the order

1. Backfill with `/embed/batch` (5,000 per call) at 384 into your index beside your filter fields.
   Re-embed only changed items.
2. Per query (two API calls, as the search guide's large-catalog steps say): `/embed` the query at the
   same size, retrieve a filtered shortlist (the docs example uses 200; anything up to 512), then `/search`
   the shortlist with its stored vectors.
3. Blend the returned order with your ETA, rating and ads signals. Measure shortlist recall on real
   queries and widen the shortlist if relevant items are missing.
4. Latency: the hot path is one `/embed` call, your index query and one `/search` call (`/search` runs at
   about 200ms p50 on 200 items). Time the whole path on your traffic with R10 before you fix the shortlist
   size. Ways to keep it short: cache query vectors for head
   queries (they repeat), start the query `/embed` while you resolve filters, and skip the index and the
   query `/embed` entirely when one store's or one restaurant's list fits under 512 (one `/search` call
   with cached vectors, Recipe R1).
5. Rollout: give the `/embed` and `/search` calls a timeout you set, with the current engine's results
   still live for that query on a timeout or error. The vectors sit in your own index, so turning the flag off
   restores today's path.

```python
from latimal_client import call, chunks

# db: a psycopg 3 connection with row_factory=namedtuple_row and pgvector's register_vector()

def backfill(rows):  # rows: [(item_id, name)]
    for batch in chunks(rows, 5000):
        vecs = call("/embed/batch", {"items": [n for _, n in batch], "dimension": 384})["embeddings"]
        with db.cursor() as cur:  # psycopg 3 puts executemany on the cursor
            cur.executemany("UPDATE menu_items SET emb = %s WHERE id = %s",
                            [(v, i) for (i, _), v in zip(batch, vecs)])
        db.commit()

def search(query, city, limit=200):
    qv = call("/embed", {"items": [query], "dimension": 384})["embeddings"][0]
    rows = db.execute(
        "SELECT id, name, emb FROM menu_items WHERE city = %s AND is_available "
        "ORDER BY emb <#> %s::vector LIMIT %s", (city, qv, limit)).fetchall()  # pgvector inner product
    res = call("/search", {"query": query, "corpus": [r.name for r in rows],
                           "corpus_embeddings": [r.emb.tolist() for r in rows], "top_k": 30})
    by_name = {}
    for r in rows:
        by_name.setdefault(r.name, []).append(r.id)
    return [{"ids": by_name[h["text"]], **h} for h in res["results"]]
```

Django: the same flow works with the `pgvector` package's `VectorField(dimensions=384)` on the model and
`MenuItem.objects.filter(city=city, is_available=True).order_by(MaxInnerProduct("emb", qv))[:200]`, then
the `/search` call above on the queryset's names and vectors (`item.emb.tolist()`, since the field returns
a numpy array). Call the API with the R0 client. Prisma and other ORMs without vector support can run the
shortlist query as raw SQL.

### R2b. Search a large catalog with Elasticsearch or OpenSearch

Keep the engine. Add a vector field next to the existing text and filter fields, let kNN with filters
produce the shortlist, and let `/search` order it. The search guide documents the shortlist pattern with
"your own index (pgvector, Pinecone, Weaviate, FAISS or similar)", and this recipe applies it to
Elasticsearch and OpenSearch. Check `dense_vector` and `_source` behavior for the engine version in the
repo.

```python
# mapping addition (Elasticsearch 8.x)
# "name_vec": {"type": "dense_vector", "dims": 384, "index": True, "similarity": "dot_product"}

def es_search(query, store_id, k=200):
    qv = call("/embed", {"items": [query], "dimension": 384})["embeddings"][0]
    hits = es.search(index="menu_items", knn={
        "field": "name_vec", "query_vector": qv, "k": k, "num_candidates": 4 * k,
        "filter": [{"term": {"store_id": store_id}}, {"term": {"in_stock": True}}]},
        source=["name", "name_vec"])["hits"]["hits"]
    names = [h["_source"]["name"] for h in hits]
    vecs = [h["_source"]["name_vec"] for h in hits]
    return call("/search", {"query": query, "corpus": names, "corpus_embeddings": vecs, "top_k": 20})["results"]
```

Index the vectors with the `/embed/batch` backfill from R2 (bulk API). Some ES versions and mappings leave
vectors out of `_source`; if yours does, keep a copy of each vector keyed by item ID and look them up
after the kNN query. OpenSearch uses a `knn_vector` field and a `knn` query with the same shape. Two
ways to use the result: replace BM25 ordering on food queries, or keep BM25 for exact-name queries and use
Latimal's order for everything else (R2c). To measure, run R10 with the current ES query as the baseline
on a set of real queries, including local-language ones.

### R2c. Hybrid ranking: keep exact brand and restaurant-name hits

Keyword search is good at exact names (a restaurant brand, a chain's signature item name, a SKU). Keep it
for those and use `/search` for intent. Pin exact hits first and append the `/search` order, since `/search` scores rank results
within one response.

```python
def hybrid(query, corpus, exact_lookup):
    exact = exact_lookup(query)                      # your ILIKE / prefix / brand match, a few rows at most
    ranked = [h["text"] for h in call("/search", {"query": query, "corpus": corpus[:512], "top_k": 20})["results"]]
    seen, out = set(), []
    for name in exact + ranked:                      # exact hits pinned first, then Latimal's order
        if name not in seen:
            seen.add(name); out.append(name)
    return out
```

Postgres FTS with per-language configs slots in as `exact_lookup`: keep `to_tsvector('french',
unaccent(name)) @@ websearch_to_tsquery('french', unaccent(q))` (or `'german'`, `'dutch'`, `'spanish'`) for
exact and near-exact hits, pin them first, and let `/search` order the rest from a pgvector shortlist (R2).
Give `/search` a vector shortlist as well as FTS: FTS matches on shared stemmed words, so items that share
no word with the query (synonyms, other languages) reach the ranking step through the vector shortlist.

### R3. Nightly catalog normalization

For each restaurant whose menu changed since the last run:

1. `/classify` changed items (512 per call); store `cuisine`, `confidence`; recompute restaurant tags.
2. `/dedup` the full menu (up to 2000) at the default 0.85; when a false merge is costly, raise it (for
   example, try 0.90) and confirm on a labeled sample; write clusters to a
   review table.
3. `/embed` changed items for search and matching.
4. Weekly: `/report` per restaurant; log `quality_score` and components; alert on drops below your threshold.

```python
from collections import Counter
from latimal_client import call, chunks

# the 16 food cuisine labels; Bakery, Beverages and Desserts sit out of the restaurant-tag vote
CUISINES = {"Italian", "Chinese", "Japanese", "Thai", "Mexican", "American", "Korean", "Vietnamese",
            "SE Asian", "Middle Eastern", "Mediterranean", "European", "Continental", "North Indian",
            "South Indian", "Mughlai"}

def normalize(restaurant_id, items):  # items: [(item_id, name)]
    labels = []
    for batch in chunks(items, 512):
        labels += call("/classify", {"items": [n for _, n in batch]})["results"]
    save_labels(restaurant_id, [(i, r["cuisine"], r["confidence"]) for (i, _), r in zip(items, labels)])

    votes = Counter(r["cuisine"] for r in labels if r["cuisine"] in CUISINES and r["confidence"] >= 0.6)
    total = sum(votes.values()) or 1
    tags = [c for c, n in votes.most_common() if n / total >= 0.25]  # your thresholds
    save_restaurant_tags(restaurant_id, tags)

    if len(items) <= 2000:
        d = call("/dedup", {"items": [n for _, n in items], "cosine_threshold": 0.85})
        queue_merge_review(restaurant_id, d["clusters"])  # never auto-delete
```

### R4. Onboarding pipeline (new merchant or migration)

1. Parse the upload or OCR output into one name per line, prices and sizes in your own fields.
2. `/report` with `restaurant_name`; hold go-live if duplicates, noise or non-food rows exceed your bar.
3. Show the merchant `noise_analysis.examples`, `dedup_summary.top_clusters` and `non_food_items` as fixes.
4. For migrations, map old items to the new catalog with `/embed/batch` candidates plus `/match` (R6 pattern).
5. On pass: `/classify` for cuisine prefill, `/embed` for search, publish.

```ts
export async function gateMenu(name: string, items: string[]) {
  const r = await latimal<any>("/report", { restaurant_name: name, items });
  const problems = {
    duplicates: r.dedup_summary.total_duplicate_items,
    noisy: r.noise_analysis.items_with_noise,
    nonFood: r.non_food_items.length,
  };
  const pass = problems.duplicates === 0 && problems.nonFood === 0 && r.noise_analysis.noise_percentage < 10;
  return { pass, score: r.quality_score, problems,
           fixes: { cleanups: r.noise_analysis.examples, merges: r.dedup_summary.top_clusters, remove: r.non_food_items },
           cuisine: r.cuisine_breakdown?.distribution ?? null };
}
```

### R5. Checkout upsell call placement

- Call `/suggest` when the cart view opens and after add-to-cart, debounced.
- Send that restaurant's currently available items as `menu` (remove sold-out items first; max 500).
  Filter `menu` by your own verified dietary tags first when the customer has set a preference.
- Cache by `(restaurant_id, menu_version, sorted cart)`; carts repeat often.
- Give the call a short timeout of your choosing and render nothing on timeout; checkout must never wait
  on it. Set the budget from your own measurements.
- Show `reason` as the subtitle; apply margin, promotion or sponsorship rules after the call.

```ts
const cache = new Map<string, unknown>();

export async function addOns(restaurantId: string, menuVersion: string, cart: string[], menu: string[],
                             budgetMs: number) { // a budget you set from your own measurements
  const key = `${restaurantId}:${menuVersion}:${[...cart].sort().join("|")}`;
  if (cache.has(key)) return cache.get(key);
  try {
    const res = await latimal<any>("/suggest", { cart, menu, top_k: 3 }, 1, budgetMs); // one try
    cache.set(key, res.suggestions);
    return res.suggestions;
  } catch {
    return []; // degrade silently
  }
}
```

### R6. Price comparison grouping across restaurants

1. Embed every item (with restaurant, price and your parsed size) into your index.
2. For each item, take the nearest few items from other restaurants above a cosine floor you tune as
   candidates (the embeddings concept page reads 0.8 and up as likely the same dish; start there and lower
   it if R10 shows missed matches, since `/match` decides each pair); block by city or zone and by
   category to keep pair counts down (two 300-item menus make 90,000 raw pairs). The matching guide also
   suggests blocking on a `/classify` label.
3. `/match` candidates 100 pairs per call; keep `match` with both flags false, and on local-language menus
   also drop pairs that R15's `local_conflict` or `local_protein_conflict` flags.
4. Union matched pairs into groups; compare prices only within the same size bucket and currency.

```python
from latimal_client import call, chunks
from local_protein import local_conflict, local_protein_conflict  # Recipe R15, saved as local_protein.py

def match_groups(items, candidates):  # items: {id: (name, size)}; candidates: [(id_a, id_b)]
    parent = {i: i for i in items}
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    for batch in chunks(candidates, 100):
        res = call("/match", {"pairs": [{"text_a": items[a][0], "text_b": items[b][0]} for a, b in batch]})
        for (a, b), r in zip(batch, res["results"]):
            na, nb = items[a][0], items[b][0]
            same_size = items[a][1] == items[b][1]  # sizes are stripped by the API; check your own field
            flagged = (r["dietary_conflict"] or r["protein_conflict"]
                       or local_conflict(na, nb) or local_protein_conflict(na, nb))
            if r["match"] and not flagged and same_size:
                parent[find(a)] = find(b)
    groups = {}
    for i in items:
        groups.setdefault(find(i), []).append(i)
    return [g for g in groups.values() if len(g) > 1]
```

### R7. Multilingual markets

- Send names exactly as written, in any script. Do not translate first.
- Keep one index and one vector size for every market; cross-lingual neighbors land close together.
- Use the same 19 `/classify` labels everywhere and map them to local display names.
- Log `query_preprocessed` per market as a launch-health signal.
- Before launch, run R10 on labels and matches per market, with R15's local list next to the conflict
  flags. agents.md section 8.1 has the per-market notes.

### R8. Safety gate for merges and substitutions

```python
from latimal_client import call
from local_protein import local_conflict, local_protein_conflict  # Recipe R15

def safe_substitutes(original, in_stock):
    ranked = call("/search", {"query": original, "corpus": in_stock[:512], "top_k": 5})["results"]
    cands = [h["text"] for h in ranked]
    if not cands:
        return []
    checks = call("/match", {"pairs": [{"text_a": original, "text_b": c} for c in cands]})["results"]
    # for substitutes, read only the flags; a substitute is a different dish by design
    return [c for c, r in zip(cands, checks)
            if not (r["dietary_conflict"] or r["protein_conflict"]
                    or local_conflict(original, c) or local_protein_conflict(original, c))]
```

For merges (dedup, item mapping, rename carry-over), require `match: true` **and** both API flags false,
plus both R15 checks false on non-English menus.

### R9. Grounded menu tool for an LLM agent

```ts
// Tool definition exposed to the model
export const searchMenuTool = {
  name: "search_menu",
  description: "Find orderable dishes on the current restaurant's menu. Returns exact menu names only. " +
    "Add items with direct: true when the customer asks for them; offer the others as a question first.",
  input_schema: {
    type: "object",
    properties: { query: { type: "string", description: "What the customer wants, in their words" } },
    required: ["query"],
  },
};

// One allow-list per conversation. Store it with the conversation (Redis, your session table) in
// production; a module-level Set would be shared by every user on the server.
const returnedBySession = new Map<string, Set<string>>();

export async function runSearchMenu(sessionId: string, query: string, menu: string[]) {
  const res = await latimal<any>("/search", { query, corpus: menu.slice(0, 512), top_k: 5 });
  const allowed = returnedBySession.get(sessionId) ?? new Set<string>();
  for (const h of res.results) allowed.add(h.text);
  returnedBySession.set(sessionId, allowed);
  // is_fallback: false marks a direct match; other hits are related picks from the query's category,
  // so the agent adds direct matches and offers related picks as a question (search reference)
  return res.results.map((h: any) => ({ name: h.text, direct: !h.is_fallback })); // API order
}

export function addToCart(sessionId: string, name: string) {
  if (!returnedBySession.get(sessionId)?.has(name)) throw new Error("Only items returned by search_menu can be added");
  // ...map name to SKU and add
}

export function endSession(sessionId: string) {
  returnedBySession.delete(sessionId);
}
```

Read each picked item back and add it on the customer's confirmation. Pair it with R8 before commit
(`/match` the customer's phrase against the resolved item, D7) for voice and chat.
Per chat turn, the calls you chain (`/search`, then `/match`, then `/suggest` before the summary) add up,
so run independent calls in parallel, cache menu vectors, and time a full turn on real conversations
before you set a budget.

### R10. Offline proof: replay real data through the current path and Latimal

The fastest way from "it fits" to "the team believes it". Run it on the user's own data and show them the
table. Plug the codebase's current function in as the baseline (an `ILIKE` query, an ES call, a rapidfuzz
matcher, a keyword dict or an LLM prompt).

```python
#!/usr/bin/env python3
"""Compare the current search path with Latimal on labeled queries and print a markdown report.

Usage:
    python latimal_eval.py queries.csv menu.txt > latimal_eval.md
queries.csv columns: query,expected  (expected = one correct item, exactly as written in menu.txt)
    e.g.  warm soup for winter,Sundubu Jjigae   |   chiken parm,Chicken Parmesan   |   ラーメン,Tonkotsu Ramen
menu.txt: one item name per line, at most 512 (one /search call ranks 512; for a bigger catalog, build
    the shortlist first with R2 and replay per shortlist). The menu is embedded once and the vectors are
    passed as corpus_embeddings, as production does with cached vectors (R1).
"""
import argparse, csv, sys, time
from latimal_client import call

def current_search(query, corpus, k):
    q = query.lower()                                  # replace with the codebase's real search
    return [c for c in corpus if q in c.lower()][:k]

def latimal_search(query, corpus, k, vecs):
    res = call("/search", {"query": query, "corpus": corpus, "corpus_embeddings": vecs, "top_k": k})
    return [h["text"] for h in res["results"]]

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("queries"); ap.add_argument("menu"); ap.add_argument("--k", type=int, default=5)
    a = ap.parse_args()
    corpus = [l.strip() for l in open(a.menu, encoding="utf-8") if l.strip()]
    if len(corpus) > 512:  # never compare Latimal on a truncated menu against a baseline that sees it all
        sys.exit(f"{a.menu} has {len(corpus)} items; /search ranks at most 512 per call. "
                 "Shortlist first (R2), or split the file per restaurant.")
    rows = list(csv.DictReader(open(a.queries, encoding="utf-8")))
    vecs = call("/embed", {"items": corpus, "dimension": 384})["embeddings"]  # once, outside the timing
    systems = {"current": current_search,
               "Latimal": lambda q, c, k: latimal_search(q, c, k, vecs)}
    hits = {s: 0 for s in systems}; secs = {s: 0.0 for s in systems}
    table = ["| query | expected | current top 3 | Latimal top 3 |", "|---|---|---|---|"]
    for r in rows:
        tops = {}
        for name, fn in systems.items():
            t = time.perf_counter(); res = fn(r["query"], corpus, a.k); secs[name] += time.perf_counter() - t
            hits[name] += r["expected"] in res
            tops[name] = ", ".join(res[:3]) or "(none)"
        table.append(f"| {r['query']} | {r['expected']} | {tops['current']} | {tops['Latimal']} |")
    n = len(rows) or 1
    where = {"current": "in process; swap in the real call to time it", "Latimal": "includes the network round trip"}
    for s in systems:
        print(f"- {s}: hit@{a.k} {hits[s]}/{n}, mean latency {1000 * secs[s] / n:.0f} ms ({where[s]})")
    print("\n" + "\n".join(table))

if __name__ == "__main__":
    main()
```

Variants: for matching, read `text_a,text_b,same` rows and compare the current matcher (for example
`fuzz.token_set_ratio(a, b) > 85`) with `/match` (`match and not dietary_conflict and not
protein_conflict`, plus `not local_conflict(a, b) and not local_protein_conflict(a, b)` from R15 for
non-English markets); report precision, recall and the pairs each one gets wrong. Put protein swaps in the
labeled set ("Hähnchenschnitzel" / "Schweineschnitzel" as `same = false`) so the report shows them
caught. For `/classify`, read
`item,label` rows, map the 19 labels to the user's taxonomy, and report agreement against their current
rule. For `/suggest`, show 20 real carts side by side with the current add-ons and let the team judge,
then A/B test. Use 100-300 real rows from production logs or the catalog, and include
the user's hardest languages (starter inputs per market close this recipe).

Threshold sweep for `/match`, run once per market on labeled pairs (this is how a `token_set_ratio > 85`
cut-off gets replaced with a measured one):

```python
from latimal_client import call, chunks
from local_protein import local_conflict, local_protein_conflict  # Recipe R15

def sweep(rows, thresholds=(0.75, 0.80, 0.85, 0.90), local=True):  # rows: [(text_a, text_b, same: bool)]
    for th in thresholds:
        tp = fp = fn = 0
        for batch in chunks(rows, 100):
            res = call("/match", {"pairs": [{"text_a": a, "text_b": b} for a, b, _ in batch],
                                  "cosine_threshold": th})["results"]
            for (a, b, same), r in zip(batch, res):
                pred = r["match"] and not r["dietary_conflict"] and not r["protein_conflict"]
                if local:  # R15 checks for non-English names
                    pred = pred and not local_conflict(a, b) and not local_protein_conflict(a, b)
                tp += pred and same; fp += pred and not same; fn += (not pred) and same
        p, rc = tp / max(tp + fp, 1), tp / max(tp + fn, 1)
        print(f"threshold {th}: precision {p:.2f}, recall {rc:.2f}")
```

Pick the threshold whose precision matches the cost of a false merge in that market.

**R10 starter inputs per market.** Test inputs for the first day of a pilot, to run and read; replace them
with real rows from the user's logs and catalog as soon as you have them.

| Market | Queries to replay over a real menu | Pairs for `/match` | Items to `/classify` first |
|---|---|---|---|
| US, UK, Australia | "chiken parm", "something spicy", "gluten free pizza", "flat white", "iced oat latte" | "Chicken Parm" / "Chicken Parmigiana (Serves 1)"; "Chicken burger" / "Mushroom burger" | Mac and Cheese, Fish and Chips, Poke Bowl, Buffalo Wings, Biscuits and Gravy |
| France, Belgium | "quelque chose de chaud", "croque monsieur", "poulet roti" | "Poulet rôti" / "Roast chicken"; "Croque-monsieur" / "Croque Monsieur au jambon" | Coq au vin, Ratatouille, Moules-frites, Tarte Tatin |
| Germany, Austria, Switzerland | "etwas Scharfes", "schnitzel mit pommes", "currywurst" | "Hähnchenschnitzel" / "Chicken Schnitzel"; "Schweineschnitzel" / "Schnitzel vom Schwein"; "Hähnchenschnitzel" / "Schweineschnitzel" (protein swap: R15's `local_protein_conflict` catches it) | Jägerschnitzel, Käsespätzle, Currywurst, Sauerbraten, Apfelstrudel |
| Netherlands | "iets met kip", "kibbeling", "broodje haring" | "Kipsaté" / "Saté van kip"; "Broodje haring" / "Haring op brood" | Stamppot, Kibbeling, Kipsaté, Poffertjes |
| Spain, Italy, Portugal | "algo picante", "pasta senza glutine", "bacalhau" | "Tortilla española" / "Spanish omelette"; "Pollo alla Parmigiana" / "Chicken Parmesan" | Paella, Patatas bravas, Lasagne, Bacalhau à Brás, Pastel de nata |
| Mexico, US Hispanic | "tacos de pastor", "algo sin carne", "horchata grande" | "Tacos al pastor (3)" / "Orden de tacos al pastor"; "Tacos de pollo" / "Tacos de frijol" | Tinga de pollo, Chilaquiles, Pozole, Tamales, Elote |
| Brazil | "x-tudo", "pizza meio a meio", "açaí" | "Frango a passarinho" / "Fried chicken bites"; "X-Frango" / "Sanduíche de frango" | Moqueca de peixe, Coxinha, Pão de queijo, Moqueca, Brigadeiro |
| Japan | "ラーメン", "らーめん", "辛いもの", "karaage" | "唐揚げ" / "Karaage"; "ラーメン" / "拉麺"; "照り焼きチキン丼" / "Teriyaki Chicken Don"; "親子丼 並" / "親子丼 大盛" (size, R12) | 親子丼, Tonkotsu Ramen, Okonomiyaki, Matcha Latte |
| Southeast Asia | "nasi lemak ayam spicy", "khao mun kai", "bakmie" | "Khao man gai" / "Khao mun kai"; "Nasi lemak" / "Nasik lemak"; "Adobong manok" / "Chicken adobo" | Nasi goreng, Adobo, Laksa, Satay, Phở gà, Bánh mì |
| Korea | "매운 거", "bibimbap", "kimchi jjigae" | "비빔밥" / "Bibimbap"; "Dakgalbi" / "닭갈비"; "Kimchi jjigae" / "Kimchi stew" | 김치찌개, Tteokbokki, Japchae, Kimbap, Hotteok |
| Greater China (mainland, Hong Kong, Taiwan) | "辣的", "鸡肉饭", "xiao long bao" | "小笼包" / "Xiaolongbao"; "宫保鸡丁" / "Kung Pao Chicken"; "叉燒飯" / "Char siu rice" | 麻婆豆腐, Dim sum platter, 珍珠奶茶, Chicken chow mein, Egg tart |
| Middle East and North Africa (Arabic) | "شي حار", "shawarma", "فلافل" | "شكشوكة" / "Shakshuka"; "شاورما دجاج" / "Chicken shawarma"; "Mansaf" / "منسف" | Hummus, Kabsa, Mandi, Kunafa, Koshari |
| South Asia | "kuch teekha", "biryani", "momos" | "Chicken Biryani" / "Murgh Biryani"; "Paneer Tikka" / "Chicken Tikka" | Masala Dosa, Chole Bhature, Kottu Roti, Momos, Gulab Jamun |

For `/classify`, note which label each item gets, with its confidence, and map the results onto the user's
filters.

### R11. Bulk throughput for scrape-scale or catalog-scale jobs

- Batch to the limits: 100 pairs per `/match`, 5,000 items per `/embed/batch`, 2,000 per `/dedup`, 512 per
  `/classify`.
- Cut the work before you call: block candidates by city, category or cuisine; send only new or changed
  names (keyed by exact text); cache `/match` verdicts by `(text_a, text_b, cosine_threshold)` and re-check
  when you change the threshold.
- Run a small, fixed pool of concurrent requests with R0's retry, and grow it only while 429 responses stay
  rare. A 429 also covers "too many in flight".
- Schedule big refreshes off-peak and make jobs resumable (write results per batch).
- Size a nightly job from a pilot: run an hour of real batches at your planned concurrency, record pairs
  or items per minute and the 429 rate, then extrapolate with headroom.

```python
from concurrent.futures import ThreadPoolExecutor
from latimal_client import call, chunks
from local_protein import local_conflict, local_protein_conflict  # Recipe R15

def match_all(pairs, cache, workers=4, local=True):  # pairs: [(text_a, text_b)]; cache: dict you persist
    todo = [p for p in dict.fromkeys(pairs) if p not in cache]
    def run(batch):
        res = call("/match", {"pairs": [{"text_a": a, "text_b": b} for a, b in batch]})["results"]
        return batch, res
    with ThreadPoolExecutor(workers) as ex:
        for batch, res in ex.map(run, list(chunks(todo, 100))):
            for p, r in zip(batch, res):
                ok = r["match"] and not r["dietary_conflict"] and not r["protein_conflict"]
                if local:  # R15 checks for non-English names, as in R6, R8 and the R10 sweep
                    ok = ok and not local_conflict(*p) and not local_protein_conflict(*p)
                cache[p] = ok
    return [cache[p] for p in pairs]
```

### R12. Keep legitimate size SKUs out of dedup merges

`/dedup` and `/match` treat size variants as one dish. When a POS or CSV keeps sizes as separate rows
("Latte Small", "Latte Large", "Margherita 12in", "Margherita 16in"), parse the size into its own field and
drop clusters whose members differ only by that field.

```python
import re

SIZE = re.compile(
    r"\b(small|regular|medium|large|xl|kids|grande|venti|tall|petit|klein|gro(?:ß|ss)|grand|"
    r"chico|chica|mediano|mediana|familiar|media\s+orden|orden|piezas?|pzas?|brotos?|m[eé]dia|fam[ií]lia|"
    r"\d+(?:[.,]\d+)?\s?(?:oz|ml|cl|l|g|kg|in|inch|cm|pcs?|pzs?))\b|\d+\"|\(\d+\)", re.I)
# CJK size words get their own pattern: \b doesn't fire between adjacent CJK characters ("ラーメン大盛").
SIZE_CJK = re.compile(r"大盛り?|特盛り?|並盛り?|小盛り?|並|[SMLＳＭＬ]サイズ|ハーフ|大份|小份")  # bare 並 can over-match; review

def base_and_size(name):
    sizes = [m.group(0).lower() for p in (SIZE, SIZE_CJK) for m in p.finditer(name)]
    base = SIZE_CJK.sub("", SIZE.sub("", name))
    return re.sub(r"\s+", " ", base).strip().lower(), tuple(sizes)

def real_duplicates(clusters):
    out = []
    for c in clusters:
        parsed = [base_and_size(m) for m in c["members"]]
        bases, sizes = {b for b, _ in parsed}, [s for _, s in parsed]
        if len(bases) == 1 and len(set(sizes)) == len(sizes) and all(sizes):
            continue  # same base name, every member a different size: legitimate SKUs
        out.append(c)
    return out
```

Extend both patterns with the size and portion words your markets use ("Portion", "porción", "meia
porção", "pieces"); your own size field is what price comparison needs.

### R13. A finer cuisine taxonomy, or your own item categories, on top of `/embed`

For finer cuisines than the 19 labels (French vs Spanish vs Greek for a European marketplace, Peruvian vs
Brazilian for Latin America, Indonesian vs Malaysian vs Filipino for Southeast Asia), label a few hundred
items per cuisine yourself and classify new items by their nearest labeled neighbors. It votes in the
0.5-0.7 band the embeddings concept page calls "related (same category or cuisine)", hence `min_sim=0.5`. The same code
labels item or menu categories (Burgers, Sides, Drinks) from rows a team already mapped; see the last
paragraph.

```python
from collections import Counter
import numpy as np
from latimal_client import call

def embed(items):
    return np.array(call("/embed/batch", {"items": items, "dimension": 384})["embeddings"])

LABELED = [("Coq au Vin", "French"), ("Paella Valenciana", "Spanish"), ("Moussaka", "Greek"),
           ("İskender Kebap", "Turkish"), ("Bacalhau à Brás", "Portuguese"), ("Jägerschnitzel", "German"),
           ("Ceviche", "Peruvian"), ("Nasi Goreng", "Indonesian")]  # use hundreds per label in practice
X, y = embed([t for t, _ in LABELED]), [l for _, l in LABELED]

def predict(names, k=7, min_sim=0.5):
    out = []
    for row in embed(names) @ X.T:
        top = [i for i in np.argsort(-row)[:k] if row[i] >= min_sim]
        out.append(Counter(y[i] for i in top).most_common(1)[0][0] if top else None)  # None: review
    return out
```

Keep `/classify` for the coarse layer if it suits the UI, and measure this layer with R10 on the user's
own held-out labels before choosing.

The same code works for any label set the team already holds, since nothing in it is cuisine-specific. An
integrator that has hand-mapped thousands of items to each marketplace's categories (Burgers, Sides, Drinks)
can use those rows as `LABELED` (chunk `embed()` at 5,000 items per call) and propose categories for new
items, with `None` routed to review. That's a customer-built classifier on `/embed` vectors; hold out a
slice of the mapped rows and measure accuracy on it before switching anything.

### R14. Mobile apps and other stacks

- **Mobile (React Native, iOS, Android):** the app calls your backend, and only the backend calls Latimal
  with the key. Cache menu vectors on the server so each search is one request. The docs' authentication
  page says to keep the key in environment variables and rotate it if it's ever exposed in client-side
  code; the backend route below is this file's way of meeting that.

```ts
// server route, e.g. POST /api/menu-search; the mobile app calls this route, and only the server holds the key
export async function menuSearchHandler(body: { restaurantId: string; query: string }) {
  const items = await loadMenuWithVectors(body.restaurantId); // your DB: id, name, stored 384-size vector
  return searchMenu(body.query, items, SEARCH_BUDGET_MS);     // Recipe R1; the budget is your config value
}
```

- **JVM, Go, Ruby, PHP, .NET:** it's plain HTTPS and JSON, so any HTTP client works. The docs' code samples are
  Python, bash and JSON; the Kotlin and Go clients below are this file's, written against the same
  documented request and response shapes.

```kotlin
// Large catalog from a JVM backend: embed the query, shortlist from your index, rank with /search.
// Uses kotlinx.serialization; swap in Jackson or Moshi if that's what the codebase uses.
import kotlinx.serialization.json.*

val http = java.net.http.HttpClient.newHttpClient()

fun latimal(path: String, body: JsonObject): JsonObject {
    val req = java.net.http.HttpRequest.newBuilder(java.net.URI("https://dish-embed.latimal.com$path"))
        .header("X-API-Key", System.getenv("LATIMAL_API_KEY"))
        .header("Content-Type", "application/json")
        .POST(java.net.http.HttpRequest.BodyPublishers.ofString(body.toString())).build()
    val res = http.send(req, java.net.http.HttpResponse.BodyHandlers.ofString())
    check(res.statusCode() == 200) { "Latimal $path ${res.statusCode()}" }  // add R0-style retry on 429 and 503
    return Json.parseToJsonElement(res.body()).jsonObject
}

data class Item(val id: String, val name: String, val vec: List<Float>)

fun searchCatalog(query: String, shortlist: (List<Float>) -> List<Item>): List<String> {
    val qv = latimal("/embed", buildJsonObject {
        putJsonArray("items") { add(query) }
        put("dimension", 384)
    })["embeddings"]!!.jsonArray[0].jsonArray.map { it.jsonPrimitive.float }
    val items = shortlist(qv)  // your Elasticsearch/OpenSearch kNN or pgvector query with filters, up to 512
    val res = latimal("/search", buildJsonObject {
        put("query", query)
        putJsonArray("corpus") { items.forEach { add(it.name) } }
        putJsonArray("corpus_embeddings") { items.forEach { i -> addJsonArray { i.vec.forEach { add(it) } } } }
        put("top_k", 20)
    })
    return res["results"]!!.jsonArray.map { it.jsonObject["text"]!!.jsonPrimitive.content }
}
```

```go
// Go (net/http, encoding/json only): the R0 client with retry on 429 and 503.
package latimal

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"
)

var client = &http.Client{Timeout: 10 * time.Second}

func Call(path string, payload any, out any) error {
	body, err := json.Marshal(payload)
	if err != nil {
		return err
	}
	for attempt := 0; ; attempt++ {
		req, err := http.NewRequest("POST", "https://dish-embed.latimal.com"+path, bytes.NewReader(body))
		if err != nil {
			return err
		}
		req.Header.Set("X-API-Key", os.Getenv("LATIMAL_API_KEY"))
		req.Header.Set("Content-Type", "application/json")
		res, err := client.Do(req)
		if err != nil {
			return err
		}
		if (res.StatusCode == 429 || res.StatusCode == 503) && attempt < 3 {
			res.Body.Close()
			time.Sleep(time.Duration(500<<attempt) * time.Millisecond)
			continue
		}
		defer res.Body.Close()
		if res.StatusCode != http.StatusOK {
			return fmt.Errorf("latimal %s: %d", path, res.StatusCode)
		}
		return json.NewDecoder(res.Body).Decode(out)
	}
}

type Hit struct {
	Text          string   `json:"text"`
	Score         float64  `json:"score"`
	RerankerScore *float64 `json:"reranker_score"`
	IsFallback    bool     `json:"is_fallback"`
}

type SearchResponse struct {
	Results           []Hit  `json:"results"`
	QueryPreprocessed string `json:"query_preprocessed"`
}

// var r SearchResponse
// err := latimal.Call("/search", map[string]any{"query": q, "corpus": names, "top_k": 10}, &r)
```

For a single menu under 512 items, skip the `/embed` and shortlist steps and send the menu with its cached
vectors (Recipe R1).

### R15. A local-language protein list next to the conflict flags

The API flags read the published English word lists. For Spanish, Portuguese, French, Italian, German,
Dutch, Japanese, Chinese, Thai, Vietnamese, Indonesian, Malay or Filipino menus, add this local list and
block a merge or substitution when any check fires: the API flags, `local_conflict` (vegetarian vs
non-vegetarian) or `local_protein_conflict` (two different protein families, such as poultry and pork).
The words are grouped by family (poultry, pork, lamb, fish, shellfish), and the same lists drive both
checks. German and Dutch build compounds ("Hähnchenbrustfilet", "Schweineschnitzel", "Lammkeule",
"kipsaté"), so those stems are matched as substrings; whole-word matching would miss them. Treat the lists
below as a starting point your team owns and extends, and review the known collisions in `EXCLUDE` and
`REWRITE` ("kipper" is fish and would otherwise read as the Dutch poultry stem "kip"). Save it as
`local_protein.py`; R6, R8 and R10 import from it.

```python
# local_protein.py
import re, unicodedata

def fold(s):  # lowercase and strip accents, for the Latin-script lists
    s = s.lower().replace("œ", "oe")
    return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c))

# Non-vegetarian words by protein family: (whole words, accent-folded; substring stems for German and
# Dutch compounds; substrings for CJK and Thai). English words are included so mixed-language pairs
# ("Chicken Schnitzel" / "Schweineschnitzel") are checked too. "meat" means non-vegetarian with no family.
NON_VEG = {
    "poultry": ({"chicken", "turkey", "duck", "pollo", "pavo", "frango", "poulet", "canard", "ayam", "ga",
                 "manok"},
                {"hahnchen", "haehnchen", "huhn", "hendl", "puten", "entenbrust", "kip"},
                {"鶏", "鳥", "鸡", "ไก่"}),
    "pork": ({"pork", "bacon", "ham", "cerdo", "puerco", "jamon", "tocino", "chorizo", "pastor", "carnitas",
              "porco", "presunto", "calabresa", "linguica", "porc", "jambon", "lardons", "maiale",
              "prosciutto", "salsiccia", "spek", "babi", "heo", "baboy"},
             {"schwein", "schinken", "speck", "varken"},
             {"豚", "猪", "หมู"}),
    "lamb": ({"lamb", "mutton", "cordero", "agneau", "kambing"}, {"lamm"}, set()),  # lamb, mutton, goat
    "fish": ({"fish", "salmon", "tuna", "pescado", "atun", "peixe", "bacalhau", "saumon", "thon", "tonno",
              "zalm", "ikan", "atum"},
             {"fisch", "lachs"},
             {"魚", "鮭", "鱼", "ปลา"}),
    "shellfish": ({"prawns", "shrimp", "crab", "lobster", "camaron", "camarones", "mariscos", "pulpo",
                   "camarao", "gambas", "crevettes", "gamberi", "udang"},
                  {"garnele", "garnaal"},
                  {"海老", "えび", "エビ", "虾", "กุ้ง"}),
    "meat": ({"carne", "barbacoa", "birria", "tripa", "daging", "egg", "pepperoni", "salami", "salame"},
             {"wurst", "gehakt"}, set()),
}
VEG = ({"tofu", "seitan", "tempeh", "tempe", "tahu", "frijol", "frijoles", "champinon", "champinones",
        "setas", "hongos", "cogumelos", "champignons", "funghi", "vegano", "vegana", "vegetariano",
        "vegetariana", "vegetarien", "vegetarienne", "paneer", "mushroom", "soya", "jackfruit"},
       {"pilz", "vegetarisch"},
       {"豆腐", "เต้าหู้"})
EXCLUDE = ("al dente", "flammkuchen", "kipferl", "skipjack", "spekulatius")  # Latin-script collisions
REWRITE = {"kipper": " fish "}  # smoked herring is fish; keeps the Dutch "kip" stem from reading poultry
EXCLUDE_SCRIPT = ("牛乳",)                         # milk; dairy sits outside the protein lists, as in the API

def _has(name, lists):
    words, stems, script = lists
    latin, raw = fold(name), name
    for x, y in REWRITE.items():
        latin = latin.replace(x, y)
    for x in EXCLUDE:
        latin = latin.replace(x, " ")
    for x in EXCLUDE_SCRIPT:
        raw = raw.replace(x, " ")
    return (bool(set(re.findall(r"\w+", latin)) & words) or any(s in latin for s in stems)
            or any(s in raw for s in script))

def local_protein(name):  # the protein families a name carries, e.g. {"poultry"}
    return {f for f, lists in NON_VEG.items() if f != "meat" and _has(name, lists)}

def local_signal(name):
    if any(_has(name, lists) for lists in NON_VEG.values()):
        return "non_veg"
    return "veg" if _has(name, VEG) else None

def local_conflict(a, b):  # vegetarian vs non-vegetarian
    return {local_signal(a), local_signal(b)} == {"veg", "non_veg"}

def local_protein_conflict(a, b):  # both sides name a protein family, and the families differ
    pa, pb = local_protein(a), local_protein(b)
    return bool(pa and pb) and pa != pb
```

Spot-check it on your own menus: `local_signal("Hähnchenbrustfilet")`,
`local_signal("Tacos al pastor")` and `local_signal("唐揚げ定食 (鶏)")` should read `non_veg`, and
`local_signal("Tacos de frijol")` should read `veg`. `local_protein("Hähnchenschnitzel")` should read
`{"poultry"}` and `local_protein("Schweineschnitzel")` `{"pork"}`, so
`local_protein_conflict("Hähnchenschnitzel", "Schweineschnitzel")` is true: that's the chicken-to-pork merge
this list catches on German names. A name that carries both signals ("Veggie-Wurst") reads `non_veg`, the
safe side for a merge guard. Names with no listed word ("Wiener Schnitzel", which is veal) read `None`, so
extend the lists for your markets. Generic meat words (carne, Wurst, birria) count as non-vegetarian with no
family, so they never set `local_protein_conflict` on their own.
