File size: 2,942 Bytes
7ff74f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""From a raw model reply to the ``parsed`` dict that ``np_answers.score`` takes.

``_strip_thinking`` and ``_json_objects`` are copied unchanged from the benchmark's ``tools/evaluation/prompts.py``
(the harness that ran the models); ``parse_reply`` is that harness's ``parse`` for np answer forms plus the TRUNCATED
rule of its ``runner.py``. The scoring files (np_answers.py and what it imports) are untouched.

Pass the question text as ``question`` to match the harness exactly: like ``prompts.parse`` it then builds the
letter map of questions that list their options as "A. 右前;B. 左前;…" (``np_answers.lettered_options``), so a
direction-sector reply ``{"answer": "A"}`` is read as that option. Without ``question`` letters are not accepted
for such questions (the behaviour of the first version of this file).
"""
import json
import re

try:
    from . import np_answers
except ImportError:
    import np_answers

# runner.py: finish reasons that mean the token budget ran out
TRUNCATED = {'length', 'max_tokens', 'MAX_TOKENS'}


def _json_objects(text):
    """Every balanced {...} substring, in order, that parses as JSON."""
    found, depth, start, in_str, esc = [], 0, None, False, False
    for i, ch in enumerate(text):
        if in_str:
            esc = (ch == '\\') and not esc
            if ch == '"' and not esc:
                in_str = False
            continue
        if ch == '"':
            in_str = True
        elif ch == '{':
            if depth == 0:
                start = i
            depth += 1
        elif ch == '}' and depth:
            depth -= 1
            if depth == 0:
                try:
                    found.append(json.loads(text[start:i + 1]))
                except json.JSONDecodeError:
                    pass
    return found


def _strip_thinking(text):
    return re.sub(r'<think>.*?</think>', '', text or '', flags=re.S).strip()


def parse_reply(text, spec, finish_reason=None, question=None):
    """``{'status': 'PARSED'|'UNPARSED'|'TRUNCATED', 'value': ..., 'how': ...}`` for one reply.

    ``spec`` is ``json.loads(row['answer_spec'])``. The JSON object ``{"answer": ...}`` is read first (the last one
    that converts), then a last-line fallback. A reply with no answer is UNPARSED, or TRUNCATED when its
    ``finish_reason`` is ``length`` (token budget used up, often inside the reasoning); both score 0.
    """
    body = _strip_thinking(text)
    texts = list(question.values()) if isinstance(question, dict) else [question]
    letters = next((m for m in (np_answers.lettered_options(q, spec) for q in texts if q) if m), None)
    if letters:                                     # same as prompts.parse
        spec = {**spec, 'letters': letters}
    parsed = np_answers.parse(body, _json_objects(body), spec)
    if parsed['status'] == 'UNPARSED' and finish_reason in TRUNCATED:
        parsed = {**parsed, 'status': 'TRUNCATED'}
    return parsed