File size: 3,668 Bytes
75ea5f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
"""Parse model action responses and dataset reference actions."""

import ast
import json
import math
import re


EXPECTED_SCREEN = (1920, 1080)


ALLOWED_ACTIONS = {"click", "double_click", "type", "finish"}


class RunnerError(RuntimeError):
    pass


class ParsedAction(object):
    def __init__(self, action, parameters, reasoning="", raw=""):
        self.action = action
        self.parameters = parameters
        self.reasoning = reasoning
        self.raw = raw

    def as_dict(self):
        return {
            "action": self.action,
            "parameters": self.parameters,
            "reasoning": self.reasoning,
        }


def _tag_body(text, tag, preserve_payload=False, required=True):
    pattern = r"<%s\b[^>]*>(.*?)</%s>" % (re.escape(tag), re.escape(tag))
    match = re.search(pattern, text, flags=re.IGNORECASE | re.DOTALL)
    if not match:
        if required:
            raise RunnerError("Missing <%s>...</%s> block" % (tag, tag))
        return ""

    body = match.group(1)
    if not preserve_payload:
        return body.strip()

    # Remove exactly the formatting newline after the opening tag and before
    # the closing tag. A second trailing newline belongs to the type payload
    # and means Enter in the SFT schema.
    if body.startswith("\r\n"):
        body = body[2:]
    elif body.startswith("\n"):
        body = body[1:]
    if body.endswith("\r\n"):
        body = body[:-2]
    elif body.endswith("\n"):
        body = body[:-1]
    return body


def _decode_type_payload(payload):
    # Some serving stacks return literal backslash escapes instead of actual
    # control characters. Decode only the control sequences used by this data.
    if "\\t" in payload:
        payload = payload.replace("\\t", "\t")
    if "\\r\\n" in payload:
        payload = payload.replace("\\r\\n", "\n")
    if "\\n" in payload:
        payload = payload.replace("\\n", "\n")
    return payload


def parse_model_output(text):
    if not isinstance(text, str) or not text.strip():
        raise RunnerError("Model output is empty")

    action = _tag_body(text, "action").lower().replace("-", "_")
    if action not in ALLOWED_ACTIONS:
        raise RunnerError("Unsupported action: %r" % action)

    payload = _tag_body(text, "parameters", preserve_payload=True)
    reasoning = _tag_body(text, "ui_reasoning", required=False)

    if action in ("click", "double_click"):
        value = payload.strip()
        try:
            params = json.loads(value)
        except Exception:
            try:
                params = ast.literal_eval(value)
            except Exception as exc:
                raise RunnerError("Invalid click parameters: %r" % value) from exc
        if not isinstance(params, (list, tuple)) or len(params) != 2:
            raise RunnerError("Click parameters must be [x_norm, y_norm]")
        try:
            params = [float(params[0]), float(params[1])]
        except Exception as exc:
            raise RunnerError("Click coordinates must be numeric") from exc
        if not all(math.isfinite(v) and 0.0 <= v <= 1.0 for v in params):
            raise RunnerError("Normalized click coordinates must be in [0, 1]")
    elif action == "type":
        params = _decode_type_payload(payload)
        if not params:
            raise RunnerError("Type payload is empty")
    else:
        params = []

    return ParsedAction(action, params, reasoning=reasoning, raw=text)


def assistant_text(row):
    for message in row.get("messages", []):
        if message.get("role") == "assistant":
            return message.get("content", "")
    raise RunnerError("JSONL row has no assistant message")