Prototype validated Ollama tool call translation
This commit is contained in:
parent
9bcb44802e
commit
3581d4bc73
|
|
@ -0,0 +1,67 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Validate an Ollama text response against the supplied OpenAI tool schemas.
|
||||
|
||||
This is a testing utility: it never executes a tool or starts a network service.
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
import jsonschema
|
||||
|
||||
|
||||
def unique_object(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise ValueError("duplicate JSON key")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def has_external_reference(value):
|
||||
if isinstance(value, dict):
|
||||
return any((key == "$ref" and (not isinstance(item, str) or not item.startswith("#/")))
|
||||
or has_external_reference(item) for key, item in value.items())
|
||||
if isinstance(value, list):
|
||||
return any(has_external_reference(item) for item in value)
|
||||
return False
|
||||
|
||||
|
||||
def convert(content, tools):
|
||||
"""Return a structured call only for a single exact, schema-valid request."""
|
||||
try:
|
||||
request = json.loads(content, object_pairs_hook=unique_object)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if not isinstance(request, dict) or set(request) != {"name", "arguments"}:
|
||||
return None
|
||||
name = request["name"]
|
||||
arguments = request["arguments"]
|
||||
if not isinstance(name, str) or not isinstance(arguments, dict) or not isinstance(tools, list):
|
||||
return None
|
||||
matches = [tool.get("function") for tool in tools if isinstance(tool, dict)
|
||||
and tool.get("type") == "function" and isinstance(tool.get("function"), dict)
|
||||
and tool["function"].get("name") == name]
|
||||
if len(matches) != 1 or not isinstance(matches[0].get("parameters"), dict):
|
||||
return None
|
||||
try:
|
||||
schema = matches[0]["parameters"]
|
||||
if has_external_reference(schema):
|
||||
return None
|
||||
validator = jsonschema.validators.validator_for(schema)
|
||||
validator.check_schema(schema)
|
||||
validator(schema).validate(arguments)
|
||||
except (jsonschema.exceptions.ValidationError, jsonschema.exceptions.SchemaError, TypeError, ValueError):
|
||||
return None
|
||||
return {"type": "function", "function": {"name": name, "arguments": arguments}}
|
||||
|
||||
|
||||
def main():
|
||||
payload = json.load(sys.stdin)
|
||||
call = convert(payload.get("content"), payload.get("tools"))
|
||||
print(json.dumps({"tool_call": call}))
|
||||
return 0 if call is not None else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location("tool_adapter", Path(__file__).resolve().parents[2] / "scripts/ollama-tool-call-adapter.py")
|
||||
ADAPTER = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(ADAPTER)
|
||||
|
||||
|
||||
class ToolAdapterTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tools = [{"type": "function", "function": {"name": "get_status", "parameters": {
|
||||
"type": "object", "properties": {"service": {"type": "string"}},
|
||||
"required": ["service"], "additionalProperties": False}}}]
|
||||
|
||||
def test_valid_call(self):
|
||||
result = ADAPTER.convert(json.dumps({"name": "get_status", "arguments": {"service": "demo"}}), self.tools)
|
||||
self.assertEqual(result["function"]["arguments"], {"service": "demo"})
|
||||
|
||||
def test_invalid_or_ambiguous_calls_are_not_translated(self):
|
||||
for value in ('prefix {"name":"get_status","arguments":{}}',
|
||||
'{"name":"unknown","arguments":{}}',
|
||||
'{"name":"get_status","arguments":{"service":42}}',
|
||||
'{"name":"get_status","arguments":{"service":"demo","extra":1}}',
|
||||
'{"name":"get_status","name":"other","arguments":{"service":"demo"}}',
|
||||
'{"name":"get_status","arguments":{"service":"demo"},"extra":true}'):
|
||||
self.assertIsNone(ADAPTER.convert(value, self.tools))
|
||||
self.assertIsNone(ADAPTER.convert('{"name":"get_status","arguments":{"service":"demo"}}', self.tools * 2))
|
||||
Loading…
Reference in New Issue