File size: 19,002 Bytes
8da747c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
"""Cricket scorebook: the tools an agent can call, the task types built on them, and the answer checker.

One module shared by the dataset pipeline (builds tasks and reference tool traces), the NeMo Gym environment
(serves the tools, scores answers) and the evaluation scripts, so that all three agree. Standard library only.

Data model
  match    : {match_id, date, venue, bat_first, bat_second}
  delivery : state of an innings right after a LEGAL delivery, keyed by (match_id, innings, balls_bowled):
             runs, wickets, target (innings 2), striker, striker_runs, striker_balls, bowler
  A point in an innings is written in cricket notation "overs.balls" (14.3 = 14 overs and 3 balls = 87 balls).

Tools (what the agent sees): find_match, get_score, get_batter, calculate.
The question never contains the numbers needed for the answer; they have to be looked up with the tools.
"""
import ast
import math
import operator
import re

SYSTEM_PROMPT = (
    "You are a cricket analyst with access to a T20 International scorebook through tools. "
    "The question does not contain the numbers you need: look them up with the tools, one call at a time, "
    "and use the calculate tool for arithmetic. Points in an innings are written as overs.balls "
    "(14.3 means 14 overs and 3 balls). When you have the answer, reply with a short explanation and give the "
    "result on its own last line as 'Final answer: <number>'."
)

# Tool definitions in the OpenAI Responses API format used by NeMo Gym task rows.
TOOLS = [
    {"type": "function", "name": "find_match",
     "description": "Find a T20 International by the two teams and the date. Returns match_id, venue and which team batted first and second.",
     "parameters": {"type": "object", "properties": {
         "team_a": {"type": "string", "description": "One of the two teams, for example 'Australia'."},
         "team_b": {"type": "string", "description": "The other team."},
         "date": {"type": "string", "description": "Match date as YYYY-MM-DD."}},
         "required": ["team_a", "team_b", "date"], "additionalProperties": False}, "strict": True},
    {"type": "function", "name": "get_score",
     "description": "Team score of one innings right after the given point: runs, wickets, balls bowled, balls remaining and, for the second innings, the target.",
     "parameters": {"type": "object", "properties": {
         "match_id": {"type": "integer", "description": "match_id returned by find_match."},
         "innings": {"type": "integer", "description": "1 for the team batting first, 2 for the team batting second."},
         "overs": {"type": "string", "description": "Point in the innings as overs.balls, for example '14.3'."}},
         "required": ["match_id", "innings", "overs"], "additionalProperties": False}, "strict": True},
    {"type": "function", "name": "get_batter",
     "description": "The batter on strike for the delivery that completed the given point, with that batter's runs and balls faced so far, and the bowler.",
     "parameters": {"type": "object", "properties": {
         "match_id": {"type": "integer", "description": "match_id returned by find_match."},
         "innings": {"type": "integer", "description": "1 for the team batting first, 2 for the team batting second."},
         "overs": {"type": "string", "description": "Point in the innings as overs.balls, for example '14.3'."}},
         "required": ["match_id", "innings", "overs"], "additionalProperties": False}, "strict": True},
    {"type": "function", "name": "calculate",
     "description": "Evaluate an arithmetic expression. Supports + - * / // % ** and round(x, n), ceil(x), floor(x), abs(x), min(...), max(...).",
     "parameters": {"type": "object", "properties": {
         "expression": {"type": "string", "description": "For example '(152 - 96) * 6 / 33'."}},
         "required": ["expression"], "additionalProperties": False}, "strict": True},
]
TOOL_NAMES = [t["name"] for t in TOOLS]


def chat_tools():
    """The same tools in the Chat Completions format ({"type": "function", "function": {...}})."""
    return [{"type": "function", "function": {k: t[k] for k in ("name", "description", "parameters")}} for t in TOOLS]


# ---------------------------------------------------------------- overs notation
def overs_str(balls: int) -> str:
    return f"{balls // 6}.{balls % 6}"


def parse_overs(text) -> int:
    """'14.3' -> 87 balls. Accepts '14' and 14.0; rejects ball digits above 5."""
    m = re.fullmatch(r"\s*(\d{1,2})(?:\.(\d))?\s*", str(text))
    if not m:
        raise ValueError("overs must look like '14.3' (overs.balls)")
    o, b = int(m.group(1)), int(m.group(2) or 0)
    if b > 5:
        raise ValueError("the balls digit must be 0 to 5")
    return o * 6 + b


# ---------------------------------------------------------------- calculator
_BIN = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv,
        ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod, ast.Pow: operator.pow}
_FUNCS = {"round": round, "ceil": math.ceil, "floor": math.floor, "abs": abs, "min": min, "max": max}


def _ev(node):
    if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) and not isinstance(node.value, bool):
        return node.value
    if isinstance(node, ast.BinOp) and type(node.op) in _BIN:
        a, b = _ev(node.left), _ev(node.right)
        if isinstance(node.op, ast.Pow) and (abs(a) > 1e6 or abs(b) > 64):
            raise ValueError("power too large")
        return _BIN[type(node.op)](a, b)
    if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)):
        v = _ev(node.operand)
        return -v if isinstance(node.op, ast.USub) else v
    if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in _FUNCS and not node.keywords:
        return _FUNCS[node.func.id](*[_ev(a) for a in node.args])
    raise ValueError("only numbers, + - * / // % **, parentheses and round/ceil/floor/abs/min/max are allowed")


def calculate(expression: str):
    if not isinstance(expression, str) or len(expression) > 300:
        raise ValueError("expression must be a string of at most 300 characters")
    value = _ev(ast.parse(expression.strip(), mode="eval").body)
    if isinstance(value, float):
        if math.isnan(value) or math.isinf(value):
            raise ValueError("result is not a finite number")
        value = round(value, 6)
        if value == int(value) and abs(value) < 1e15:
            value = int(value)
    return value


# ---------------------------------------------------------------- scorebook
class Scorebook:
    """In-memory scorebook. matches: iterable of match dicts; deliveries: iterable of delivery dicts."""

    def __init__(self, matches, deliveries):
        self.matches = {int(m["match_id"]): m for m in matches}
        self.by_key = {}
        for m in self.matches.values():
            for key in ((m["bat_first"], m["bat_second"]), (m["bat_second"], m["bat_first"])):
                self.by_key.setdefault((key[0].lower(), key[1].lower(), m["date"]), []).append(m)
        self.state = {}
        for d in deliveries:
            self.state[(int(d["match_id"]), int(d["innings"]), int(d["balls_bowled"]))] = d

    # each tool returns a JSON-serialisable dict; problems are reported as {"error": "..."} so the agent can recover
    def find_match(self, team_a, team_b, date):
        hits = self.by_key.get((str(team_a).strip().lower(), str(team_b).strip().lower(), str(date).strip()[:10]))
        if not hits:
            return {"error": "no match found for these two teams on that date; check the team names and the date (YYYY-MM-DD)"}
        if len(hits) > 1:
            return {"matches": [dict(m) for m in hits], "note": "more than one match that day; choose by venue"}
        return dict(hits[0])

    def _state(self, match_id, innings, overs):
        try:
            mid, inn = int(match_id), int(innings)
        except (TypeError, ValueError):
            return None, {"error": "match_id and innings must be integers"}
        if mid not in self.matches:
            return None, {"error": f"unknown match_id {match_id}; use find_match first"}
        if inn not in (1, 2):
            return None, {"error": "innings must be 1 or 2"}
        try:
            balls = parse_overs(overs)
        except ValueError as e:
            return None, {"error": str(e)}
        d = self.state.get((mid, inn, balls))
        if d is None:
            return None, {"error": f"no record for innings {inn} after {overs_str(balls)} overs in match {mid}"}
        return d, None

    def get_score(self, match_id, innings, overs):
        d, err = self._state(match_id, innings, overs)
        if err:
            return err
        m = self.matches[int(match_id)]
        inn = int(innings)
        return {"match_id": int(match_id), "innings": inn,
                "batting_team": m["bat_first"] if inn == 1 else m["bat_second"],
                "bowling_team": m["bat_second"] if inn == 1 else m["bat_first"],
                "overs": overs_str(d["balls_bowled"]), "balls_bowled": d["balls_bowled"],
                "balls_remaining": 120 - d["balls_bowled"], "runs": d["runs"], "wickets": d["wickets"],
                "target": d.get("target")}

    def get_batter(self, match_id, innings, overs):
        d, err = self._state(match_id, innings, overs)
        if err:
            return err
        return {"match_id": int(match_id), "innings": int(innings), "overs": overs_str(d["balls_bowled"]),
                "batter": d["striker"], "batter_runs": d["striker_runs"], "batter_balls_faced": d["striker_balls"],
                "bowler": d["bowler"]}

    def call(self, name, args):
        """Dispatch a tool call by name with a dict of arguments. Never raises."""
        try:
            if name == "find_match":
                return self.find_match(args.get("team_a"), args.get("team_b"), args.get("date"))
            if name == "get_score":
                return self.get_score(args.get("match_id"), args.get("innings"), args.get("overs"))
            if name == "get_batter":
                return self.get_batter(args.get("match_id"), args.get("innings"), args.get("overs"))
            if name == "calculate":
                return {"value": calculate(args.get("expression"))}
            return {"error": f"unknown tool {name}"}
        except Exception as e:  # noqa: BLE001
            return {"error": f"{type(e).__name__}: {e}"[:200]}


# ---------------------------------------------------------------- answers
RATE_TOL = 0.011  # rates are rounded to 2 decimals; allow one unit of rounding difference
_NUM = r"[-+]?\d[\d,]*(?:\.\d+)?"


def parse_answer(text):
    """Number on the LAST 'Final answer:' line of the reply, or None."""
    if not text:
        return None
    hits = re.findall(rf"Final answer\s*:\s*\**\s*({_NUM})", text, flags=re.I)
    if not hits:
        return None
    try:
        return float(hits[-1].replace(",", ""))
    except ValueError:
        return None


def is_correct(pred, gold, kind) -> bool:
    if pred is None:
        return False
    if kind == "int":
        return abs(pred - gold) < 1e-9
    return abs(pred - gold) <= RATE_TOL


def round_half_up(x: float) -> int:
    return int(math.floor(x + 0.5))


# ---------------------------------------------------------------- task types
# Every task type: which tool lookups the reference solution makes, the question text, the exact answer and the
# expression the reference solution passes to `calculate`.
QTYPES = ("run_rate", "required_rate", "projection", "phase_runs", "phase_rate", "phase_wickets",
          "innings_compare", "strike_rate", "milestone", "batter_share")
MULTI_POINT = {"phase_runs", "phase_rate", "phase_wickets", "innings_compare", "batter_share"}


def _intro(m, d=None):
    return f"T20 International {m['bat_first']} v {m['bat_second']} at {m['venue']} on {m['date']}."


def _team(m, innings):
    return m["bat_first"] if innings == 1 else m["bat_second"]


def make_task(qtype, m, a, b=None):
    """Build one task. a (and b) are delivery states of match m. Returns None if the type does not apply.

    Result: {"qtype", "question", "gold", "answer_kind", "lookups": [(tool, args)], "expression"}.
    """
    mid = int(m["match_id"])
    intro = _intro(m)
    team = _team(m, a["innings"])
    pa = overs_str(a["balls_bowled"])
    look_a = ("get_score", {"match_id": mid, "innings": a["innings"], "overs": pa})
    bat_a = ("get_batter", {"match_id": mid, "innings": a["innings"], "overs": pa})
    bb = a["balls_bowled"]
    if qtype == "run_rate":
        q = f"What was {team}'s run rate in runs per over after {pa} overs of their innings? Round to 2 decimal places."
        return _t(qtype, intro, q, round(a["runs"] * 6 / bb, 2), "rate", [look_a], f"round({a['runs']} * 6 / {bb}, 2)")
    if qtype == "required_rate":
        if a["innings"] != 2 or not a.get("target") or a["target"] <= a["runs"] or bb >= 120:
            return None
        need, rem = a["target"] - a["runs"], 120 - bb
        q = (f"{team} were chasing. After {pa} overs of the chase, what run rate (runs per over) did they need over "
             f"the rest of their 20 overs to reach the target? Round to 2 decimal places.")
        return _t(qtype, intro, q, round(need * 6 / rem, 2), "rate", [look_a], f"round(({a['target']} - {a['runs']}) * 6 / {rem}, 2)")
    if qtype == "projection":
        q = (f"Take {team}'s run rate after {pa} overs of their innings (runs so far divided by overs bowled so far). "
             f"If they had kept scoring at exactly that rate for all 20 overs, what total would they have finished on? "
             f"Round to the nearest whole run (halves round up).")
        return _t(qtype, intro, q, round_half_up(a["runs"] * 120 / bb), "int", [look_a], f"floor({a['runs']} * 120 / {bb} + 0.5)")
    if qtype == "strike_rate":
        if a["striker_balls"] < 1:
            return None
        q = (f"Look at the delivery that completed {pa} overs of {team}'s innings. What was the strike rate (runs per "
             f"100 balls faced) of the batter on strike at that point? Round to 2 decimal places.")
        return _t(qtype, intro, q, round(a["striker_runs"] * 100 / a["striker_balls"], 2), "rate", [bat_a],
                  f"round({a['striker_runs']} * 100 / {a['striker_balls']}, 2)")
    if qtype == "milestone":
        br, bf = a["striker_runs"], a["striker_balls"]
        if br < 1 or bf < 4:
            return None
        ms = (br // 50 + 1) * 50
        q = (f"Look at the delivery that completed {pa} overs of {team}'s innings. If the batter on strike had kept "
             f"scoring at their own strike rate up to that point (runs per ball faced), how many more balls would they "
             f"have needed to reach {ms} runs? Round up to a whole number of balls.")
        return _t(qtype, intro, q, -(-(ms - br) * bf // br), "int", [bat_a], f"ceil(({ms} - {br}) * {bf} / {br})")
    if qtype == "batter_share":
        if a["runs"] < 1:
            return None
        q = (f"Look at the delivery that completed {pa} overs of {team}'s innings. What percentage of {team}'s total "
             f"runs at that point had been scored by the batter on strike? Round to 2 decimal places.")
        return _t(qtype, intro, q, round(a["striker_runs"] * 100 / a["runs"], 2), "rate", [look_a, bat_a],
                  f"round({a['striker_runs']} * 100 / {a['runs']}, 2)")
    if b is None:
        return None
    pb = overs_str(b["balls_bowled"])
    look_b = ("get_score", {"match_id": mid, "innings": b["innings"], "overs": pb})
    if qtype == "innings_compare":
        if a["innings"] != 2 or b["innings"] != 1 or a["balls_bowled"] != b["balls_bowled"]:
            return None
        other = _team(m, 1)
        q = (f"Compare the two innings at the same stage: after {pa} overs of each innings, how many runs ahead of "
             f"{other} were {team}? Give {team}'s runs minus {other}'s runs (negative if {team} were behind).")
        return _t(qtype, intro, q, a["runs"] - b["runs"], "int", [look_a, look_b], f"{a['runs']} - {b['runs']}")
    if a["innings"] != b["innings"] or b["balls_bowled"] <= a["balls_bowled"]:
        return None
    span = b["balls_bowled"] - a["balls_bowled"]
    if qtype == "phase_runs":
        q = f"How many runs did {team} score between the {pa}-over point and the {pb}-over point of their innings?"
        return _t(qtype, intro, q, b["runs"] - a["runs"], "int", [look_a, look_b], f"{b['runs']} - {a['runs']}")
    if qtype == "phase_rate":
        q = (f"What was {team}'s run rate (runs per over) between the {pa}-over point and the {pb}-over point of "
             f"their innings? Round to 2 decimal places.")
        return _t(qtype, intro, q, round((b["runs"] - a["runs"]) * 6 / span, 2), "rate", [look_a, look_b],
                  f"round(({b['runs']} - {a['runs']}) * 6 / {span}, 2)")
    if qtype == "phase_wickets":
        q = f"How many wickets did {team} lose between the {pa}-over point and the {pb}-over point of their innings?"
        return _t(qtype, intro, q, b["wickets"] - a["wickets"], "int", [look_a, look_b], f"{b['wickets']} - {a['wickets']}")
    return None


def _t(qtype, intro, question, gold, kind, lookups, expression):
    return {"qtype": qtype, "question": f"{intro}\n\n{question}", "gold": gold, "answer_kind": kind,
            "lookups": lookups, "expression": expression}


def reference_trace(book: Scorebook, m, task):
    """Reference solution as chat messages: find_match, the lookups, one calculate call, the final answer.

    Tool results come from the scorebook itself, so the trace is exactly what the environment would return.
    Returns (messages, n_tool_calls). The final number is checked against the task's gold answer by the caller.
    """
    import json

    msgs = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": task["question"]}]
    calls = [("find_match", {"team_a": m["bat_first"], "team_b": m["bat_second"], "date": m["date"]})]
    calls += list(task["lookups"]) + [("calculate", {"expression": task["expression"]})]
    result = None
    for i, (name, args) in enumerate(calls):
        cid = f"call_{i + 1}"
        result = book.call(name, args)
        msgs.append({"role": "assistant", "content": "", "tool_calls": [
            {"id": cid, "type": "function", "function": {"name": name, "arguments": json.dumps(args)}}]})
        msgs.append({"role": "tool", "tool_call_id": cid, "name": name, "content": json.dumps(result)})
    value = result.get("value") if isinstance(result, dict) else None
    shown = f"{value:.2f}" if task["answer_kind"] == "rate" and value is not None else str(value)
    msgs.append({"role": "assistant", "content": f"Using the scorebook figures, {task['expression']} = {shown}.\n\nFinal answer: {shown}"})
    return msgs, len(calls)