import re def parse_answer(output: str) -> str: """ Extract the final answer from a chain-of-thought style LLM output. 1. Look for the last occurrence of 'Answer:' (case-insensitive) and return the text after it. 2. If no 'Answer:' marker is found, return the last non-empty line. """ # Find all occurrences of 'Answer: ...' matches = re.findall(r"Answer\s*:\s*(.+)", output, flags=re.IGNORECASE) if matches: return matches[-1].strip() # Fallback: return the last non-empty line lines = [line.strip() for line in output.strip().splitlines() if line.strip()] if lines: return lines[-1] # If output is empty or no lines found, return the raw output return output.strip()