diff --git a/GramAddict/core/navigation/brain.py b/GramAddict/core/navigation/brain.py index 6738bc3..66d4a42 100644 --- a/GramAddict/core/navigation/brain.py +++ b/GramAddict/core/navigation/brain.py @@ -55,12 +55,32 @@ def ask_brain_for_action( result = response if isinstance(response, str) else response.get("response", "") result = result.strip().strip("'\"") - # Fuzzy match to available actions just in case + # 1. Exact match check (ideal case) for act in available_actions: - if act.lower() in result.lower(): + if act.lower() == result.lower(): return act + + # 2. Strict line-by-line check (often the model outputs the action on the last line) + for line in reversed(result.splitlines()): + line = line.strip().strip("'\"") + for act in available_actions: + if act.lower() == line.lower(): + return act - logger.warning(f"🧠 [Brain] LLM returned an invalid action: '{result}'. Falling back.") + # 3. Fuzzy match (find the LAST mentioned action in the text, assuming it's the conclusion) + best_act = None + best_idx = -1 + for act in available_actions: + idx = result.lower().rfind(act.lower()) + if idx > best_idx: + best_idx = idx + best_act = act + + if best_act: + logger.warning(f"🧠 [Brain] Extracted action '{best_act}' from verbose LLM output.") + return best_act + + logger.warning(f"🧠 [Brain] LLM returned an invalid action or no action found: '{result[:100]}...'. Falling back.") except Exception as e: logger.debug(f"🧠 [Brain] Error querying LLM: {e}")