File size: 2,224 Bytes
7e962a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""MiniGrid v1 grammar and native policy action IDs (drop/done are not actions)."""

import re
from dataclasses import dataclass

ACTIONS = {"left": 0, "right": 1, "forward": 2, "pickup": 3, "toggle": 5}
_ASCII_LOWER = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")


def normalize_action(action):
    normalized = str(action).strip().translate(_ASCII_LOWER)
    if normalized not in ACTIONS:
        raise ValueError("MiniGrid action must be left, right, forward, pickup, or toggle")
    return normalized


@dataclass(frozen=True)
class ParsedAction:
    action: str | None
    reason: str = ""
    attempted_action: str = "unavailable"

    @property
    def valid(self):
        return self.action is not None


def parse_response(response, *, hit_limit=False):
    # Padding/terminal special tokens are removed by the tokenizer, never prose.
    text = str(response)
    blocks = re.findall(r"<action>(.*?)</action>", text, re.S)
    attempted = "unavailable"
    if len(blocks) == 1 and text.count("<action>") == text.count("</action>") == 1:
        try:
            attempted = normalize_action(blocks[0])
        except ValueError:
            pass
    reason = ""
    tags = ("<think>", "</think>", "<action>", "</action>")
    if hit_limit and not blocks:
        reason = "truncated_action"
    elif any(text.count(tag) > 1 for tag in tags):
        reason = "multiple_blocks"
    elif not all(tag in text for tag in tags[:2]):
        reason = "missing_think_block"
    elif not all(tag in text for tag in tags[2:]):
        reason = "missing_action_block"
    else:
        match = re.fullmatch(r"\s*<think>(.*?)</think>\s*<action>(.*?)</action>\s*", text, re.S)
        if match is None or any(tag in match[1] or tag in match[2] for tag in tags):
            reason = "malformed_format"
        else:
            payload = match[2].strip().translate(_ASCII_LOWER)
            if payload in ACTIONS:
                return ParsedAction(payload, attempted_action=payload)
            words = re.findall("[a-z]+", payload)
            reason = "multiple_actions" if sum(word in ACTIONS for word in words) >= 2 else "unsupported_action"
    return ParsedAction(None, reason, attempted)