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 = '[{"name":"read_file","arguments":{"path":"x"}}]' 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)