Spaces:
Sleeping

File size: 10,243 Bytes
f45a595
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json

import pytest

from tool_protocol import (
    ToolProtocolError,
    build_tool_instruction,
    normalize_messages,
    parse_embedded_tool_calls,
    parse_generated_tool_calls,
    parse_tool_configuration,
)


def payload(**overrides):
    base = {
        "tools": [
            {
                "type": "function",
                "function": {
                    "name": "read_file",
                    "description": "Read a file",
                    "parameters": {
                        "type": "object",
                        "properties": {"path": {"type": "string"}},
                        "required": ["path"],
                        "additionalProperties": False,
                    },
                },
            }
        ]
    }
    base.update(overrides)
    return base


def native(name="read_file", arguments=None, call_id="q123q"):
    arguments = arguments or {"path": "src/app.py"}
    return (
        f"<|tool_call:begin|>{call_id}<|tool_call:name|>{name}"
        f"<|tool_call:args|>{json.dumps(arguments)}<|tool_call:end|>"
    )


def test_default_auto_and_instruction():
    config = parse_tool_configuration(payload())
    assert config.choice == "auto" and config.enabled
    instruction = build_tool_instruction(config)
    assert "read_file" in instruction
    assert "<|tool_call:begin|>" in instruction
    assert "answer the user normally" in instruction


def test_required_and_specific_choices():
    required = parse_tool_configuration(payload(tool_choice="required"))
    assert required.must_call and required.required_name is None
    specific = parse_tool_configuration(
        payload(tool_choice={"type": "function", "function": {"name": "read_file"}})
    )
    assert specific.choice == "specific"
    assert specific.required_name == "read_file"


def test_none_disables_adapter():
    config = parse_tool_configuration(payload(tool_choice="none"))
    assert not config.enabled
    assert build_tool_instruction(config) == ""


def test_legacy_functions_and_function_call():
    fn = payload()["tools"][0]["function"]
    config = parse_tool_configuration({"functions": [fn], "function_call": "read_file"})
    assert config.required_name == "read_file"


@pytest.mark.parametrize(
    "bad,match",
    [
        ({"tools": "bad"}, "array"),
        ({"tools": [{"type": "web_search"}]}, "Only tools"),
        ({"tools": [{"type": "function", "function": {"name": "bad name"}}]}, "names"),
        (payload(tool_choice="missing"), "tool_choice"),
        ({"tools": [], "tool_choice": "required"}, "at least one"),
    ],
)
def test_invalid_tool_configuration(bad, match):
    with pytest.raises(ToolProtocolError, match=match):
        parse_tool_configuration(bad)


def test_normalize_developer_assistant_calls_and_tool_results():
    config = parse_tool_configuration(payload())
    messages = normalize_messages(
        [
            {"role": "system", "content": "system"},
            {"role": "developer", "content": "developer"},
            {"role": "user", "content": [{"type": "text", "text": "open it"}]},
            {
                "role": "assistant",
                "content": None,
                "tool_calls": [
                    {
                        "id": "call_old",
                        "type": "function",
                        "function": {
                            "name": "read_file",
                            "arguments": '{"path":"a.py"}',
                        },
                    }
                ],
            },
            {"role": "tool", "tool_call_id": "call_old", "content": "print('ok')"},
        ],
        build_tool_instruction(config),
    )
    assert messages[0]["role"] == "system"
    assert "[DEVELOPER]" in messages[0]["content"]
    assert "TOOL GATEWAY PROTOCOL" in messages[0]["content"]
    assert "<|tool_call:name|>read_file" in messages[2]["content"]
    assert messages[3]["role"] == "user"
    assert "function: read_file" in messages[3]["content"]


def test_normalize_rejects_image_content():
    with pytest.raises(ToolProtocolError, match="not supported"):
        normalize_messages(
            [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "look"},
                        {"type": "image_url", "image_url": {"url": "x"}},
                    ],
                }
            ]
        )


def test_parse_native_tool_call_and_schema_validate():
    config = parse_tool_configuration(payload(tool_choice="required"))
    calls = parse_generated_tool_calls(native(), config)
    assert len(calls) == 1
    assert calls[0].name == "read_file"
    assert calls[0].arguments == {"path": "src/app.py"}
    dumped = calls[0].as_openai()
    assert dumped["id"].startswith("call_")
    assert json.loads(dumped["function"]["arguments"])["path"] == "src/app.py"


def test_parse_multiple_native_calls():
    tools = payload()["tools"] + [
        {
            "type": "function",
            "function": {
                "name": "write_file",
                "parameters": {
                    "type": "object",
                    "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
                    "required": ["path", "content"],
                },
            },
        }
    ]
    config = parse_tool_configuration({"tools": tools, "tool_choice": "required"})
    text = native() + native("write_file", {"path": "b.py", "content": "x"}, "q2q")
    calls = parse_generated_tool_calls(text, config)
    assert [call.name for call in calls] == ["read_file", "write_file"]


def test_parallel_false_rejects_multiple():
    tools = payload()["tools"] * 2
    tools[1] = {"type": "function", "function": {"name": "other", "parameters": {"type": "object"}}}
    config = parse_tool_configuration(
        {"tools": tools, "tool_choice": "required", "parallel_tool_calls": False}
    )
    with pytest.raises(ToolProtocolError, match="multiple"):
        parse_generated_tool_calls(native() + native("other", {}, "two"), config)


def test_parse_xml_and_raw_json_fallbacks():
    config = parse_tool_configuration(payload())
    xml = '<tool_calls>[{"name":"read_file","arguments":{"path":"x"}}]</tool_calls>'
    assert parse_generated_tool_calls(xml, config)[0].arguments["path"] == "x"
    raw = '{"name":"read_file","arguments":{"path":"y"}}'
    assert parse_generated_tool_calls(raw, config)[0].arguments["path"] == "y"


def test_ordinary_json_is_not_misclassified():
    config = parse_tool_configuration(payload())
    assert parse_generated_tool_calls('{"answer":42}', config) == []


def test_unknown_function_rejected():
    config = parse_tool_configuration(payload())
    with pytest.raises(ToolProtocolError, match="unknown"):
        parse_generated_tool_calls(native("delete_everything", {"path": "x"}), config)


def test_forced_function_enforced():
    config = parse_tool_configuration(
        payload(tool_choice={"type": "function", "function": {"name": "read_file"}})
    )
    with pytest.raises(ToolProtocolError, match="was forced"):
        parse_generated_tool_calls(native("other", {}), config)


def test_invalid_json_and_schema_rejected():
    config = parse_tool_configuration(payload())
    malformed = "<|tool_call:begin|>x<|tool_call:name|>read_file<|tool_call:args|>{bad}<|tool_call:end|>"
    with pytest.raises(ToolProtocolError, match="not valid JSON"):
        parse_generated_tool_calls(malformed, config)
    with pytest.raises(ToolProtocolError, match="required property"):
        parse_generated_tool_calls(native(arguments={"wrong": "x"}), config)


def test_prose_around_tool_call_rejected():
    config = parse_tool_configuration(payload())
    with pytest.raises(ToolProtocolError, match="prose outside"):
        parse_generated_tool_calls("I will call it: " + native(), config)


def test_embedded_json_recovery_prefers_last_valid_call():
    tools = payload()["tools"] + [
        {
            "type": "function",
            "function": {
                "name": "write_file",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "path": {"type": "string"},
                        "content": {"type": "string"},
                    },
                    "required": ["path", "content"],
                },
            },
        }
    ]
    config = parse_tool_configuration({"tools": tools})
    narration = (
        'For example {"name":"read_file","arguments":{"path":"old"}}. '
        'I will now use {"name":"write_file","arguments":'
        '{"path":"hello.py","content":"def hello():\\n    return \\"world\\""}}'
    )
    calls = parse_embedded_tool_calls(narration, config)
    assert len(calls) == 1 and calls[0].name == "write_file"
    assert calls[0].arguments["path"] == "hello.py"


def test_repair_truncated_double_escaped_tool_json():
    config = parse_tool_configuration(
        {
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "write_file",
                        "parameters": {
                            "type": "object",
                            "properties": {
                                "path": {"type": "string"},
                                "content": {"type": "string"},
                            },
                            "required": ["path", "content"],
                        },
                    },
                }
            ]
        }
    )
    malformed = (
        r'{"name":"write_file","arguments":{"path":"hello.py",'
        r'"content":"def hello():\\n    return \\"world\\""}'
    )
    calls = parse_generated_tool_calls(malformed, config)
    assert calls[0].name == "write_file"
    assert calls[0].arguments["path"] == "hello.py"
    assert "world" in calls[0].arguments["content"]


def test_incomplete_marker_rejected():
    config = parse_tool_configuration(payload())
    with pytest.raises(ToolProtocolError, match="incomplete"):
        parse_generated_tool_calls("<|tool_call:begin|>oops", config)