File size: 1,734 Bytes
32030e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Extract the answer JSON object from free-form model output."""

from __future__ import annotations

import json
import re

_THINK = re.compile(r"<think>.*?</think>", re.DOTALL | re.IGNORECASE)


def extract_json(text: str | None) -> dict | None:
    """Return the outermost JSON object that ends last in ``text`` (None if there is none).

    Reasoning text, code fences and earlier drafts are tolerated: the final complete
    object is taken as the answer.
    """
    if not text:
        return None
    text = _THINK.sub("", text)
    decoder = json.JSONDecoder()
    best: tuple[int, int, dict] | None = None
    for start in [i for i, ch in enumerate(text) if ch == "{"]:
        try:
            value, end = decoder.raw_decode(text, start)
        except json.JSONDecodeError:
            continue
        if not isinstance(value, dict):
            continue
        if best is None or end > best[1] or (end == best[1] and start < best[0]):
            best = (start, end, value)
    return None if best is None else best[2]


def strip_thinking(text: str) -> str:
    return _THINK.sub("", text)


def extract_tool_calls(text: str) -> list[tuple[dict, int]]:
    """Top-level JSON objects with a ``tool`` key, in order, each with the offset where it ends."""
    decoder = json.JSONDecoder()
    calls: list[tuple[dict, int]] = []
    position = text.find("{")
    while position != -1:
        try:
            value, end = decoder.raw_decode(text, position)
        except json.JSONDecodeError:
            position = text.find("{", position + 1)
            continue
        if isinstance(value, dict) and "tool" in value:
            calls.append((value, end))
        position = text.find("{", end)
    return calls