Spaces:
Sleeping
Sleeping
293droid commited on
Commit ·
fd13291
1
Parent(s): 365c885
fix parsing of prompts
Browse files5 unmodified lines6789101125 unmodified lines37383940414281 unmodified lines124125126127128129472 unmodified lines6026036046056066076085 unmodified linesimport osimport reimport gradio as grfrom huggingface_hub import InferenceClientfrom chemistry import (25 unmodified linesEnd your response after giving your advice. Do not ask follow-up questions. Do not say 'How do you want to proceed' or similar."""# ---------------------------------------------------------------------------# AI call# ---------------------------------------------------------------------------81 unmodified linesreturn "recipe"# ---------------------------------------------------------------------------# Mode handlers# ---------------------------------------------------------------------------472 unmodified linesdef run_soap_lab(user_input: str, vegan_only: bool, superfat: float = 5.0, water_hardness: str = "Soft") -> tuple[str, str, str, str]:parsed_recipe = parse_recipe(user_input)total_oil_weight = sum(parsed_recipe.values()) if parsed_recipe else Nonewater_panel = water_hardness_recommendation(water_hardness, total_oil_weight)5 unmodified lines678910111225 unmodified lines3839404142434445464748495051525354555657585960616263646566676869707172737475767781 unmodified lines159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249472 unmodified lines7227237247257267277287297307317327337347357365 unmodified linesimport osimport reimport jsonimport gradio as grfrom huggingface_hub import InferenceClientfrom chemistry import (25 unmodified linesEnd your response after giving your advice. Do not ask follow-up questions. Do not say 'How do you want to proceed' or similar."""# ---------------------------------------------------------------------------# Extraction prompt (LLM -> structured JSON)# ---------------------------------------------------------------------------EXTRACTION_SYSTEM_PROMPT = """You are an extraction assistant. Your job is to extract ingredients and weightsfrom a user's free-form text and return a single JSON object only (no explanation).Requirements:- If the user provided a recipe or ingredient list, return exactly:{"type": "recipe", "ingredients": [{"name": "<ingredient name>", "weight_g": <number>}, ...]}- If the user did NOT provide ingredients (they asked a question or for advice), return exactly:{"type": "advice"}- Normalise ALL weight formats to grams (g). Accept formats like: "300g", "300 grams","0.3kg", "10oz", "1 lb", "1lb", "ounces", "kgs", and convert them to grams.Use 1 oz = 28.3495 g, 1 lb = 453.59237 g, 1 kg = 1000 g.- Use numeric grams (floats allowed). Round to one decimal place only when necessary.- Return only JSON; do not include any trailing text or markdown.- Use deterministic output: set sampling temperature to 0.0 (this will be enforced by the caller).Few-shot examples (input -> JSON):Input: "300g coconut oil, 200g olive oil, 100g shea butter"Output: {"type": "recipe", "ingredients": [{"name": "coconut oil", "weight_g": 300}, {"name": "olive oil", "weight_g": 200}, {"name": "shea butter", "weight_g": 100}]}Input: "0.3kg olive oil and 10oz coconut oil"Output: {"type": "recipe", "ingredients": [{"name": "olive oil", "weight_g": 300}, {"name": "coconut oil", "weight_g": 283.5}]}Input: "I have 1 lb coconut oil and 250 g olive oil"Output: {"type": "recipe", "ingredients": [{"name": "coconut oil", "weight_g": 453.6}, {"name": "olive oil", "weight_g": 250}]}Input: "How can I make a gentle soap for dry sensitive skin?"Output: {"type": "advice"}"""# ---------------------------------------------------------------------------# AI call# ---------------------------------------------------------------------------81 unmodified linesreturn "recipe"# ---------------------------------------------------------------------------# LLM extraction and JSON validation# ---------------------------------------------------------------------------def _find_json_in_text(text: str) -> str | None:m = re.search(r"\{.*\}", text, re.DOTALL)return m.group(0) if m else Nonedef _map_ingredients_to_recipe(ingredients: list[dict]) -> dict[str, float] | None:recipe = {}for item in ingredients:name = (item.get("name") or "").lower()weight = item.get("weight_g")try:weight = float(weight)except Exception:return Noneif weight <= 0:return Nonematched_key = Nonefor alias, key in OIL_ALIASES.items():if alias in name:matched_key = keybreakif not matched_key:for key in OILS:if key in name:matched_key = keybreakif not matched_key:# Could not map ingredient to a known oilreturn Nonerecipe[matched_key] = recipe.get(matched_key, 0.0) + weightreturn recipedef extract_with_llm(user_input: str) -> tuple[str, dict | None]:"""Call the LLM to extract ingredients as JSON. Returns (type, recipe_or_none).type is 'recipe' or 'advice'. If extraction fails or JSON is invalid, returns ('advice', None)."""try:response = client.chat_completion(model=MODEL,messages=[{"role": "system", "content": EXTRACTION_SYSTEM_PROMPT},{"role": "user", "content": user_input},],max_tokens=400,temperature=0.0,)content = response.choices[0].message.contentexcept Exception:return ("advice", None)# Try to extract JSON from the model outputjson_text = Nonetry:json_text = _find_json_in_text(content) or contentparsed = json.loads(json_text)except Exception:return ("advice", None)if not isinstance(parsed, dict) or "type" not in parsed:return ("advice", None)if parsed["type"] == "advice":return ("advice", None)if parsed["type"] == "recipe":ingredients = parsed.get("ingredients")if not isinstance(ingredients, list):return ("advice", None)mapped = _map_ingredients_to_recipe(ingredients)if not mapped:return ("advice", None)return ("recipe", mapped)return ("advice", None)# ---------------------------------------------------------------------------# Mode handlers# ---------------------------------------------------------------------------472 unmodified linesdef run_soap_lab(user_input: str, vegan_only: bool, superfat: float = 5.0, water_hardness: str = "Soft") -> tuple[str, str, str, str]:# First, ask the LLM to extract a structured recipe JSON (temperature=0.0)extraction_type, extracted = extract_with_llm(user_input)if extraction_type == "advice":# Extraction determined this is an advice request or extraction failed.advice_context = "The user did not provide a parseable recipe. Provide concise, practical soap-making advice based on their question."advice = ask_model(user_input, advice_context)return "", "", advice, water_hardness_recommendation(water_hardness, None)parsed_recipe = extracted or {}total_oil_weight = sum(parsed_recipe.values()) if parsed_recipe else Nonewater_panel = water_hardness_recommendation(water_hardness, total_oil_weight)
app.py+129-1