my-homelab-configs/scripts/ollama-tool-call-adapter.py

81 lines
3.2 KiB
Python

#!/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 re
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."""
if not isinstance(content, str):
return None
try:
text = content.strip()
fenced = re.fullmatch(r"```(?:json)?[ \t]*\r?\n(.*?)\r?\n```", text, re.IGNORECASE | re.DOTALL)
request = json.loads(fenced.group(1) if fenced else text, 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
# Holmes strict schemas mark the documented optional Bash timeout as
# required-but-nullable. Preserve its default without inventing a
# command or relaxing validation of other required arguments.
timeout = schema.get('properties', {}).get('timeout', {})
if name == 'bash' and arguments.get('timeout') is None and 'timeout' in schema.get('required', []):
nullable = timeout.get('type') == 'null' or any(x.get('type') == 'null' for x in timeout.get('anyOf', []) if isinstance(x, dict))
if nullable:
arguments = dict(arguments, timeout=30)
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())