Spaces:
Sleeping
Sleeping
Download routes/menu.py from brocode12/bell-backend: direct link, hf CLI and curl.
- Browser
- Download file 7.19 kB
-
https://huggingface.co/spaces/brocode12/bell-backend/resolve/main/routes/menu.py
- Command line
-
hf download hf://spaces/brocode12/bell-backend/routes/menu.py
-
curl -L -o menu.py https://huggingface.co/spaces/brocode12/bell-backend/resolve/main/routes/menu.py
7.19 kB
| """Menu tools called by the Bolna agent (get_menu, get_dish_details). | |
| Tool endpoints always return 200 with {success: bool, ...} β the agent's | |
| scripted retry/fallback lines depend on never seeing a transport error. | |
| """ | |
| from fastapi import APIRouter, Depends, Query | |
| from pydantic import BaseModel | |
| import config | |
| import sanitize | |
| from auth import require_token | |
| from matcher import find_dish | |
| from store import get_store | |
| router = APIRouter(prefix="/api/menu", tags=["menu"]) | |
| MAX_ITEMS = 12 | |
| # Single source of truth mapping the agent's category vocabulary β filters. | |
| # A filter is (field, value) checked against each menu row. | |
| CATEGORY_ALIASES: dict[str, dict] = { | |
| "all": {}, | |
| # veg/non-veg mean food in the agent's vocabulary β beers excluded | |
| "veg": {"is_veg": True, "category": ["starters", "mains", "sides", "desserts"]}, | |
| "vegetarian": {"is_veg": True, "category": ["starters", "mains", "sides", "desserts"]}, | |
| "non-veg": {"is_veg": False, "category": ["starters", "mains", "sides", "desserts"]}, | |
| "nonveg": {"is_veg": False, "category": ["starters", "mains", "sides", "desserts"]}, | |
| "non veg": {"is_veg": False, "category": ["starters", "mains", "sides", "desserts"]}, | |
| "starters": {"category": "starters"}, | |
| "appetizers": {"category": "starters"}, | |
| "mains": {"category": "mains"}, | |
| "main course": {"category": "mains"}, | |
| "sides": {"category": "sides"}, | |
| "desserts": {"category": "desserts"}, | |
| "dessert": {"category": "desserts"}, | |
| "mocktails": {"category": "mocktails"}, | |
| "mocktail": {"category": "mocktails"}, | |
| "drinks": {"category": ["mocktails", "craft-beer", "beverages"]}, | |
| "beverages": {"category": ["mocktails", "craft-beer", "beverages"]}, | |
| "craft-beer": {"category": "craft-beer"}, | |
| "craft beer": {"category": "craft-beer"}, | |
| "beer": {"category": "craft-beer"}, | |
| "beers": {"category": "craft-beer"}, | |
| "food": {"category": ["starters", "mains", "sides", "desserts"]}, | |
| } | |
| def _matches(item: dict, filters: dict) -> bool: | |
| for field, expected in filters.items(): | |
| actual = item.get(field) | |
| if isinstance(expected, list): | |
| if actual not in expected: | |
| return False | |
| elif actual != expected: | |
| return False | |
| return True | |
| def _at_outlet(item: dict, outlet: str | None) -> bool: | |
| if not outlet: | |
| return True | |
| outlets = [o.lower() for o in (item.get("outlet_location") or [])] | |
| # Unknown outlet name β don't filter (better to show menu than nothing). | |
| return outlet.lower() in outlets if outlets else True | |
| def _compact(item: dict) -> dict: | |
| out = { | |
| "name": item["name"], | |
| "price": item["price"], | |
| "category": item["category"], | |
| "is_veg": item.get("is_veg"), | |
| "description": (item.get("description") or "")[:140], | |
| "rating": item.get("rating"), | |
| "tags": item.get("tags") or [], | |
| } | |
| if item.get("abv"): | |
| out["abv"] = item["abv"] | |
| out["style"] = item.get("style") | |
| return out | |
| async def get_menu_full(outlet_location: str = Query(default="")): | |
| """All menu items grouped by category β no cap, full fields. Used by the visual menu browser.""" | |
| try: | |
| menu = get_store().get_menu() | |
| outlet = sanitize.clean(outlet_location) | |
| rows = [m for m in menu if _at_outlet(m, outlet)] | |
| grouped: dict[str, list] = {} | |
| for item in rows: | |
| cat = item.get("category", "other") | |
| grouped.setdefault(cat, []).append(item) | |
| # Sort each category by rating desc | |
| for cat in grouped: | |
| grouped[cat].sort(key=lambda m: (m.get("rating") or 0), reverse=True) | |
| return {"success": True, "grouped": grouped, "total": len(rows)} | |
| except Exception as exc: | |
| return {"success": False, "message": f"Menu temporarily unavailable: {exc}"} | |
| class AvailabilityBody(BaseModel): | |
| name: str | |
| is_available: bool | |
| async def set_menu_availability( | |
| body: AvailabilityBody, | |
| admin_key: str = Query(default=""), | |
| ): | |
| if config.ADMIN_KEY and admin_key != config.ADMIN_KEY: | |
| return {"success": False, "message": "Invalid admin key."} | |
| updated = get_store().update_menu_availability(body.name, body.is_available) | |
| if not updated: | |
| return {"success": False, "message": f"No item named '{body.name}' found."} | |
| return { | |
| "success": True, | |
| "message": f"'{body.name}' is now {'available' if body.is_available else 'unavailable'}.", | |
| } | |
| async def get_menu( | |
| category: str = Query(default="all"), | |
| outlet_location: str = Query(default=""), | |
| ): | |
| try: | |
| menu = get_store().get_menu() | |
| key = (sanitize.clean(category) or "all").lower() | |
| filters = CATEGORY_ALIASES.get(key) | |
| if filters is None: | |
| # Unknown category from the LLM β fuzzy-fall back to everything | |
| # rather than failing the tool call. | |
| filters = {} | |
| outlet = sanitize.clean(outlet_location) | |
| rows = [m for m in menu if _matches(m, filters) and _at_outlet(m, outlet)] | |
| rows.sort(key=lambda m: (m.get("rating") or 0), reverse=True) | |
| items = [_compact(m) for m in rows[:MAX_ITEMS]] | |
| if not items: | |
| return { | |
| "success": True, | |
| "items": [], | |
| "message": f"No items found for category '{category}'. Try another category.", | |
| } | |
| return {"success": True, "category": key, "count": len(items), "items": items} | |
| except Exception as exc: # never 500 a tool call | |
| return {"success": False, "message": f"Menu temporarily unavailable: {exc}"} | |
| async def get_dish_details(dish_name: str = Query(default="")): | |
| try: | |
| name = sanitize.clean(dish_name) | |
| if not name: | |
| return {"success": False, "found": False, "message": "No dish name provided."} | |
| menu = get_store().get_menu() | |
| item, confidence = find_dish(name, menu) | |
| if item is None: | |
| return { | |
| "success": True, | |
| "found": False, | |
| "message": f"No close match for '{dish_name}' on the menu.", | |
| } | |
| return { | |
| "success": True, | |
| "found": True, | |
| "confidence": confidence, | |
| "dish": { | |
| "name": item["name"], | |
| "price": item["price"], | |
| "currency": "INR", | |
| "category": item["category"], | |
| "is_veg": item.get("is_veg"), | |
| "description": item.get("description"), | |
| "rating": item.get("rating"), | |
| "spice_level": item.get("spice_level"), | |
| "abv": item.get("abv"), | |
| "style": item.get("style"), | |
| "allergens": item.get("allergens") or [], | |
| "tags": item.get("tags") or [], | |
| "available_at": item.get("outlet_location") or [], | |
| }, | |
| } | |
| except Exception as exc: | |
| return {"success": False, "message": f"Dish lookup failed: {exc}"} | |