my-homelab-configs/tests/jeannie/test_ollama_tool_call_adapt...

161 lines
11 KiB
Python

import importlib.util
import json
from pathlib import Path
import unittest
from unittest.mock import patch
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)
PROXY_SPEC = importlib.util.spec_from_file_location("tool_proxy", Path(__file__).resolve().parents[2] / "scripts/ollama-tool-proxy.py")
PROXY = importlib.util.module_from_spec(PROXY_SPEC)
PROXY_SPEC.loader.exec_module(PROXY)
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"})
self.assertIsNotNone(ADAPTER.convert('```json\n{"name":"get_status","arguments":{"service":"demo"}}\n```', self.tools))
def test_invalid_or_ambiguous_calls_are_not_translated(self):
for value in ('prefix {"name":"get_status","arguments":{}}',
'prose\n```json\n{"name":"get_status","arguments":{"service":"demo"}}\n```',
'{"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))
def test_bash_only_excludes_other_tools(self):
bash = {"type": "function", "function": {"name": "bash", "parameters": {}}}
self.assertEqual(PROXY.bash_only(self.tools + [bash]), [bash])
with self.assertRaises(ValueError):
PROXY.bash_only(self.tools)
with self.assertRaises(ValueError):
PROXY.bash_only([bash, bash])
def test_first_prose_answer_retries_and_translates_only_valid_call(self):
tools = [{"type": "function", "function": {"name": "bash", "parameters": {
"type": "object", "properties": {"command": {"type": "string"},
"suggested_prefixes": {"type": "array", "items": {"type": "string"}}},
"required": ["command", "suggested_prefixes"]}}}]
request = {"tools": tools, "messages": [{"role": "user", "content": "investigate"}]}
plan = {"choices": [{"message": {"role": "assistant", "content": "Inspect the pod."}, "finish_reason": "stop"}]}
call = {"choices": [{"message": {"role": "assistant", "content": json.dumps({"name": "bash", "arguments": {
"command": "kubectl get pods", "suggested_prefixes": ["kubectl"]}})}, "finish_reason": "stop"}]}
with patch.object(PROXY, "query_ollama", side_effect=[plan, call]) as query:
result = PROXY.complete(request, True)
self.assertEqual(query.call_count, 2)
self.assertEqual(result["choices"][0]["message"]["tool_calls"][0]["function"]["name"], "bash")
def test_does_not_force_another_tool_after_tool_history(self):
request = {"tools": self.tools, "messages": [{"role": "tool", "content": "ok"}]}
plan = {"choices": [{"message": {"role": "assistant", "content": "Complete."}, "finish_reason": "stop"}]}
with patch.object(PROXY, "query_ollama", return_value=plan) as query:
PROXY.complete(request, True)
self.assertEqual(query.call_count, 1)
def test_bash_requests_limit_model_output(self):
request = {"tools": self.tools, "messages": [], "max_completion_tokens": 64000}
response = {"choices": [{"message": {"role": "assistant", "content": "Done."}}]}
with patch.object(PROXY, "query_ollama", return_value=response) as query:
PROXY.complete(request, True)
sent = query.call_args.args[0]
self.assertEqual(sent["max_tokens"], 1024)
self.assertNotIn("max_completion_tokens", sent)
self.assertEqual(request["max_completion_tokens"], 64000)
def test_resource_echo_prompts_one_valid_next_read_only_check(self):
tools = [{"type": "function", "function": {"name": "bash", "parameters": {
"type": "object", "properties": {"command": {"type": "string"},
"suggested_prefixes": {"type": "array", "items": {"type": "string"}}},
"required": ["command", "suggested_prefixes"]}}}]
previous = {"role": "assistant", "tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({"command": "kubectl -n n8n get pod n8n", "suggested_prefixes": ["kubectl"]})}}]}
request = {"tools": tools, "messages": [{"role": "user", "content": "pvc n8n-data phase=Bound pv=pvc-123"}, previous, {"role": "tool", "content": "pod output"}]}
echo = {"choices": [{"message": {"role": "assistant", "content": '{"name":"n8n","image":"n8n:2"}'}, "finish_reason": "stop"}]}
next_call = {"choices": [{"message": {"role": "assistant", "content": json.dumps({"name": "bash", "arguments": {
"command": "kubectl -n n8n get pvc n8n-data", "suggested_prefixes": ["kubectl"]}})}, "finish_reason": "stop"}]}
with patch.object(PROXY, "query_ollama", side_effect=[echo, next_call]) as query:
result = PROXY.complete(request, True)
self.assertEqual(query.call_count, 2)
self.assertEqual(result["choices"][0]["message"]["tool_calls"][0]["function"]["name"], "bash")
def test_complete_json_diagnosis_is_not_treated_as_resource_echo(self):
self.assertFalse(PROXY.is_resource_extract({"content": '{"status":"bad","diagnosis":"disk"}'}))
self.assertTrue(PROXY.is_resource_extract({"content": '{"response":"Pod is crashing."}'}))
self.assertFalse(PROXY.is_resource_extract({"content": '{"response":"Diagnosis: disk. Mitigation: none. Validation: failed."}'}))
self.assertTrue(PROXY.is_resource_extract({"content": "The pod is running an application and has a container image. " * 3}))
self.assertFalse(PROXY.is_resource_extract({"content": "Diagnosis: bad pod. Mitigation: none. Validation: unavailable."}))
self.assertTrue(PROXY.is_resource_extract({"content": '```json\n{"name":"fetch_pvc_details","arguments":{"pvc_name":"n8n-data"}}\n```'}))
def test_pv_result_leads_to_decision_with_tool_history(self):
tools = [{"type": "function", "function": {"name": "bash", "parameters": {
"type": "object", "properties": {"command": {"type": "string"},
"suggested_prefixes": {"type": "array", "items": {"type": "string"}}},
"required": ["command", "suggested_prefixes"]}}}]
previous = {"role": "assistant", "tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({"command": "kubectl get pv pvc-123"})}}]}
history = [{"role": "user", "content": "investigate"}, previous, {"role": "tool", "content": "volume output"}]
echo = {"choices": [{"message": {"content": '{"kind":"PersistentVolume"}'}}]}
decision = {"choices": [{"message": {"content": "Diagnosis: missing evidence. Mitigation: none. Validation: unavailable."}}]}
with patch.object(PROXY, "query_ollama", side_effect=[echo, decision]) as query:
result = PROXY.complete({"tools": tools, "messages": history}, True)
prompt = query.call_args_list[1].args[0]["messages"]
self.assertEqual(prompt[1], history[0])
self.assertIn("volume output", prompt[2]["content"])
self.assertNotIn(previous, prompt)
self.assertIn("missing evidence", result["choices"][0]["message"]["content"])
def test_last_bash_command_reads_recorded_tool_arguments(self):
messages = [{"role": "assistant", "tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({"command": "kubectl -n n8n get pvc n8n-data"})}}]}, {"role": "tool", "content": "ok"}]
self.assertEqual(PROXY.last_bash_command(messages), "kubectl -n n8n get pvc n8n-data")
def test_seen_bash_command_checks_earlier_calls(self):
def call(command):
return {"function": {"name": "bash", "arguments": json.dumps({"command": command})}}
history = [{"role": "assistant", "tool_calls": [call("kubectl get pvc")]},
{"role": "assistant", "tool_calls": [call("kubectl get pv")]}]
self.assertTrue(PROXY.seen_bash_command({"tool_calls": [call("kubectl get pvc")]}, history))
self.assertFalse(PROXY.seen_bash_command({"tool_calls": [call("kubectl get pod")]}, history))
def test_retry_cannot_turn_a_plan_into_a_mutating_command(self):
tools = [{"type": "function", "function": {"name": "bash", "parameters": {
"type": "object", "properties": {"command": {"type": "string"},
"suggested_prefixes": {"type": "array", "items": {"type": "string"}}},
"required": ["command", "suggested_prefixes"]}}}]
for command in ("kubectl delete pod n8n", "kubectl get pods; rm -rf /", "kubectl get --raw=/api/v1/secrets"):
message = {"tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({
"command": command, "suggested_prefixes": ["kubectl"]})}}]}
self.assertFalse(PROXY.safe_initial_call(message, tools))
def test_pvc_and_pv_names_must_match_the_evidence(self):
tools = [{"type": "function", "function": {"name": "bash", "parameters": {
"type": "object", "properties": {"command": {"type": "string"},
"suggested_prefixes": {"type": "array", "items": {"type": "string"}}},
"required": ["command", "suggested_prefixes"]}}}]
context = "pvc n8n-data phase=Bound pv=pvc-123 storage_class=local"
def call(command):
return {"tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({"command": command, "suggested_prefixes": ["kubectl"]})}}]}
self.assertTrue(PROXY.safe_initial_call(call("kubectl -n n8n get pvc n8n-data"), tools, context))
self.assertTrue(PROXY.safe_initial_call(call("kubectl get pv pvc-123"), tools, context))
self.assertFalse(PROXY.safe_initial_call(call("kubectl -n n8n get pvc pvc-123"), tools, context))
self.assertFalse(PROXY.safe_initial_call(call("kubectl get pv n8n-data"), tools, context))
def test_repeated_command_is_not_forwarded_after_one_retry(self):
args = json.dumps({"command": "printf hello", "suggested_prefixes": ["printf"]})
previous = {"role": "assistant", "tool_calls": [{"function": {"name": "bash", "arguments": args}}]}
request = {"tools": self.tools, "messages": [previous, {"role": "tool", "content": "hello"}]}
repeated = {"choices": [{"message": {"role": "assistant", "tool_calls": [{"function": {"name": "bash", "arguments": args}}]}, "finish_reason": "tool_calls"}]}
with patch.object(PROXY, "query_ollama", side_effect=[repeated, repeated]) as query:
result = PROXY.complete(request, True)
self.assertEqual(query.call_count, 2)
self.assertIn("JEANNIE_STOP_REPEATED_TOOL_CALL", result["choices"][0]["message"]["content"])
self.assertNotIn("tool_calls", result["choices"][0]["message"])