File size: 1,267 Bytes
51e4c5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import re
from typing import Optional

_FINAL_ANSWER_RE = re.compile(
    r"FINAL\s*ANSWER\s*:\s*(.+)$",
    re.IGNORECASE | re.DOTALL,
)


def extract_final_answer(text: Optional[str]) -> str:
    """Pull the GAIA-style final answer out of a free-form model reply."""
    if not text:
        return ""

    text = str(text).strip()
    match = _FINAL_ANSWER_RE.search(text)
    raw = match.group(1).strip() if match else text

    if "FINAL ANSWER:" in raw.upper():
        raw = re.split(r"FINAL\s*ANSWER\s*:", raw, flags=re.IGNORECASE)[-1].strip()

    first_line = raw.splitlines()[0].strip()
    first_line = first_line.strip(" `\"'")
    first_line = re.sub(r"^\*\*?|\*\*?$", "", first_line).strip()
    return normalize_gaia_answer(first_line)


def normalize_gaia_answer(answer: str) -> str:
    """Light cleanup that matches common GAIA scoring pitfalls."""
    answer = answer.strip()
    answer = answer.strip(" `\"'")
    if answer.endswith("."):
        answer = answer[:-1].strip()

    compact = answer.replace(" ", "")
    if re.fullmatch(r"[+-]?\d{1,3}(,\d{3})+(\.\d+)?", answer):
        return answer.replace(",", "")
    if re.fullmatch(r"[+-]?\d+(\.\d+)?%?", compact) and "," in answer:
        return answer.replace(",", "")

    return answer