Integration
Hybrid menu search with Typesense
On this page
Typesense can store your own vectors next to regular fields and fuse keyword and vector rankings in a single query. That makes it a natural home for Latimal vectors: keyword matching keeps exact dish names sharp, and the vector side catches synonyms, other languages, misspellings and descriptive queries like "late-night street food". This recipe adds a cuisine facet from /classify too.
Prerequisites
- A Latimal API key in
LATIMAL_API_KEY. See Authentication. - A Typesense server or Typesense Cloud cluster with vector search support, and an admin API key in
TYPESENSE_API_KEY. - Python 3.9+ with requests and the Typesense client.
pip install requests typesense1. Enrich menu items with Latimal
This helper calls /embed/batch for vectors and /classify for a cuisine label, and stores a hash of the name so you can spot renamed items later.
import hashlib
import os
import requests
class Latimal:
"""A thin client for the Latimal REST API, built on requests."""
def __init__(self, api_key, base_url="https://dish-embed.latimal.com"):
self.base_url = base_url
self.session = requests.Session()
self.session.headers["X-API-Key"] = api_key
def _post(self, path, payload):
response = self.session.post(f"{self.base_url}{path}", json=payload, timeout=60)
response.raise_for_status()
return response.json()
def embed(self, items): # /embed: up to 512 items
return self._post("/embed", {"items": items})["embeddings"]
def embed_batch(self, items): # /embed/batch: up to 5,000 items
return self._post("/embed/batch", {"items": items})["embeddings"]
def classify(self, items): # /classify: up to 512 items
return self._post("/classify", {"items": items})["results"]
def search(self, query, corpus, top_k=10): # /search: up to 512 corpus items
return self._post("/search", {"query": query, "corpus": corpus, "top_k": top_k})
def match(self, pairs): # /match: up to 100 pairs
return self._post("/match", {"pairs": pairs})
latimal = Latimal(os.environ["LATIMAL_API_KEY"])
def chunked(seq, size):
for start in range(0, len(seq), size):
yield seq[start:start + size]
def text_hash(name):
return hashlib.sha256(name.encode("utf-8")).hexdigest()
def enrich(items):
"""Attach a Latimal vector, a cuisine label and a text hash to each item."""
names = [item["name"] for item in items]
vectors, labels = [], []
for batch in chunked(names, 5000): # /embed/batch: up to 5,000 items per call
vectors.extend(latimal.embed_batch(batch))
for batch in chunked(names, 512): # /classify: up to 512 items per call
labels.extend(latimal.classify(batch))
for item, vector, label in zip(items, vectors, labels):
item["embedding"] = vector
item["text_hash"] = text_hash(item["name"])
if label["cuisine"] != "uncertain":
item["cuisine"] = label["cuisine"]
item["cuisine_confidence"] = label["confidence"]
return items
menu = [
{"id": "seoul-06-0014", "restaurant_id": "seoul-06", "name": "Dolsot Bibimbap", "price": 9.50, "currency": "USD"},
{"id": "hanoi-02-0001", "restaurant_id": "hanoi-02", "name": "Phở Gà", "price": 2.50, "currency": "USD"},
{"id": "napoli-12-0005", "restaurant_id": "napoli-12", "name": "Pizza Margherita", "price": 8.50, "currency": "EUR"},
{"id": "nyc-30-0022", "restaurant_id": "nyc-30", "name": "Margarita Pizza 12\" Large", "price": 18.00, "currency": "USD"},
{"id": "istanbul-04-0010", "restaurant_id": "istanbul-04", "name": "Adana Kebab", "price": 12.00, "currency": "USD"},
{"id": "cdmx-05-0019", "restaurant_id": "cdmx-05", "name": "Tacos al Pastor", "price": 5.00, "currency": "USD"},
]
items = enrich(menu)
dims = len(items[0]["embedding"]) # read the vector size from the response, never hardcode itSend names exactly as they appear in your catalog. Latimal cleans promo text, sizes and prices before encoding, so you don't need a preprocessing step of your own.
2. Create the collection
The num_dim on the embedding field comes from the dims value you read in step 1.
import typesense
ts = typesense.Client({
"nodes": [{"host": os.environ["TYPESENSE_HOST"], "port": "443", "protocol": "https"}],
"api_key": os.environ["TYPESENSE_API_KEY"],
"connection_timeout_seconds": 10,
})
COLLECTION = "menu_items"
def ensure_collection(dims):
existing = {c["name"] for c in ts.collections.retrieve()}
if COLLECTION in existing:
return
ts.collections.create({
"name": COLLECTION,
"fields": [
{"name": "restaurant_id", "type": "string", "facet": True},
{"name": "name", "type": "string"},
{"name": "price", "type": "float"},
{"name": "currency", "type": "string", "facet": True},
{"name": "cuisine", "type": "string", "facet": True, "optional": True},
{"name": "cuisine_confidence", "type": "float", "optional": True},
{"name": "text_hash", "type": "string", "index": False, "optional": True},
{"name": "embedding", "type": "float[]", "num_dim": dims},
],
})
ensure_collection(dims)Typesense uses cosine distance for vector fields by default, which suits Latimal's L2-normalized vectors.
3. Import the items
results = ts.collections[COLLECTION].documents.import_(items, {"action": "upsert"})
failed = [r for r in results if not r.get("success")]
if failed:
raise RuntimeError(f"{len(failed)} documents failed to import: {failed[:3]}")The import endpoint reports success per document, so check each result line. For big imports, raise connection_timeout_seconds on the client.
4. Run a hybrid search
Embed the query with Latimal and send it as a vector_query alongside the keyword q. Typesense ranks each side separately and fuses the two ranks. alpha sets the vector side's weight. Use multi_search because query vectors are too long for a GET query string.
from functools import lru_cache
@lru_cache(maxsize=10_000)
def embed_query(query):
# One /embed call per uncached query. Popular queries hit the cache.
return tuple(latimal.embed([query])[0])
def search_menu(query, cuisine=None, restaurant_id=None, per_page=10, alpha=0.5):
vector = ",".join(str(x) for x in embed_query(query))
filters = []
if cuisine:
filters.append(f"cuisine:={cuisine}")
if restaurant_id:
filters.append(f"restaurant_id:={restaurant_id}")
search = {
"collection": COLLECTION,
"q": query,
"query_by": "name",
"vector_query": f"embedding:([{vector}], k:100, alpha:{alpha})",
"facet_by": "cuisine",
"exclude_fields": "embedding",
"per_page": per_page,
}
if filters:
search["filter_by"] = " && ".join(filters)
result = ts.multi_search.perform({"searches": [search]}, {})["results"][0]
hits = [hit["document"] for hit in result["hits"]]
facets = {c["value"]: c["count"] for f in result.get("facet_counts", []) for c in f["counts"]}
return hits, facets
hits, facets = search_menu("margarita pizza")
for hit in hits:
print(f"{hit['name']} ({hit['price']} {hit['currency']})")
print(facets)Typesense's default alpha is 0.3, which leans toward keywords. Menu queries are often descriptive or misspelled, so start around 0.5 and tune on a sample of your real search logs. To run a pure semantic search, set q to * and drop query_by.
If a cuisine name contains spaces (for example "Middle Eastern"), wrap it in backticks inside filter_by: cuisine:=`Middle Eastern`.
5. Keep the collection fresh when menus change
Only a name change needs Latimal. Price and currency updates are partial updates, and removed dishes are deletes.
import json
def sync_restaurant(restaurant_id, current_items):
"""Bring one restaurant's documents in line with its current menu."""
exported = ts.collections[COLLECTION].documents.export({
"filter_by": f"restaurant_id:={restaurant_id}",
"include_fields": "id,text_hash",
})
existing = {}
for line in exported.splitlines():
if line.strip():
doc = json.loads(line)
existing[doc["id"]] = doc.get("text_hash")
to_enrich, to_patch = [], []
for item in current_items:
if existing.get(item["id"]) == text_hash(item["name"]):
to_patch.append({"id": item["id"], "price": item["price"], "currency": item["currency"]})
else:
to_enrich.append(item)
docs = ts.collections[COLLECTION].documents
if to_enrich:
docs.import_(enrich(to_enrich), {"action": "upsert"}) # full replace, stale labels go too
if to_patch:
docs.import_(to_patch, {"action": "update"}) # partial update, no Latimal call
current_ids = {item["id"] for item in current_items}
for doc_id in existing:
if doc_id not in current_ids:
docs[doc_id].delete()Trigger it from whatever already tells you a menu changed: a POS webhook, a partner feed import, or a nightly job. A batch of up to 5,000 renamed items is still a single embedding call.
Related
- POST /embed and POST /embed/batch for vectors
- POST /classify for cuisine labels
- POST /search if you'd rather let Latimal rank a menu directly
- Search integration guide
- Benchmarks
- Aggregator search use case
- All integrations