File size: 3,779 Bytes
f03667b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
from typing import Any


def extract_tool_actions(text: str) -> list[dict[str, Any]]:
    parsed = extract_json_value(text)
    if isinstance(parsed, dict):
        if "actions" in parsed:
            raw_actions = parsed["actions"]
        elif "tool_calls" in parsed:
            raw_actions = parsed["tool_calls"]
        else:
            raw_actions = [parsed]
    elif isinstance(parsed, list):
        raw_actions = parsed
    else:
        raise ValueError("tool call JSON must be an object or array")

    if not isinstance(raw_actions, list) or not raw_actions:
        raise ValueError("actions must be a non-empty array")

    actions: list[dict[str, Any]] = []
    for index, raw_action in enumerate(raw_actions, start=1):
        if not isinstance(raw_action, dict):
            raise ValueError(f"action #{index} must be an object")
        actions.append(normalize_tool_action(raw_action))
    return actions


def normalize_tool_action(raw_action: dict[str, Any]) -> dict[str, Any]:
    if "function" in raw_action and isinstance(raw_action["function"], dict):
        function = raw_action["function"]
        return normalize_named_tool_action(function.get("name"), function.get("arguments", {}))
    if "tool" in raw_action or "name" in raw_action:
        return normalize_named_tool_action(
            raw_action.get("tool", raw_action.get("name")),
            raw_action.get("arguments", {}),
        )
    if "action" in raw_action:
        return dict(raw_action)
    raise ValueError("action object must contain 'tool', 'name', 'function', or 'action'")


def normalize_named_tool_action(name: Any, arguments: Any) -> dict[str, Any]:
    if not isinstance(name, str) or not name.strip():
        raise ValueError("tool name must be a non-empty string")
    if isinstance(arguments, str):
        try:
            arguments = json.loads(arguments) if arguments.strip() else {}
        except json.JSONDecodeError as exc:
            raise ValueError(f"tool arguments are not valid JSON: {exc}") from exc
    if arguments is None:
        arguments = {}
    if not isinstance(arguments, dict):
        raise ValueError("tool arguments must be an object")
    action = dict(arguments)
    action["action"] = name.strip()
    return action


def extract_json_value(text: str) -> Any:
    stripped = strip_code_fence(text.strip())
    try:
        return json.loads(stripped)
    except json.JSONDecodeError:
        return json.loads(find_first_json_value(stripped))


def strip_code_fence(text: str) -> str:
    if not text.startswith("```"):
        return text
    lines = text.splitlines()
    if len(lines) >= 3 and lines[-1].strip() == "```":
        return "\n".join(lines[1:-1]).strip()
    return text


def find_first_json_value(text: str) -> str:
    object_start = text.find("{")
    array_start = text.find("[")
    starts = [index for index in (object_start, array_start) if index != -1]
    if not starts:
        raise ValueError("no JSON object or array found")
    start = min(starts)
    opening = text[start]
    closing = "}" if opening == "{" else "]"

    depth = 0
    in_string = False
    escaped = False
    for index in range(start, len(text)):
        char = text[index]
        if in_string:
            if escaped:
                escaped = False
            elif char == "\\":
                escaped = True
            elif char == '"':
                in_string = False
            continue

        if char == '"':
            in_string = True
        elif char == opening:
            depth += 1
        elif char == closing:
            depth -= 1
            if depth == 0:
                return text[start : index + 1]
    raise ValueError("unterminated JSON value")