Retry Ollama initial prose as a tool request
This commit is contained in:
parent
4940a283d3
commit
cf30954e14
|
|
@ -115,6 +115,10 @@ Holmes pipx Python environment for `jsonschema`; override that interpreter with
|
|||
to Holmes. Doctor exposes only the Bash tool to the local model, to reduce
|
||||
tool-selection errors; Bash still has host-level access. This compatibility layer does not establish that a model's proposed
|
||||
actions are correct; repair mode still allows host-level Bash commands.
|
||||
If the initial model answer is prose and no tool has run, the adapter makes one
|
||||
additional request for an initial read-only Bash check. It translates the reply
|
||||
only if the tool name and arguments satisfy the supplied schema; it does not
|
||||
invent a call from the prose. It does not force a tool after tool history exists.
|
||||
|
||||
For native K3s on the Orange Pi, `doctor opi5` collects the K3s service state,
|
||||
data and runtime mount identities, USB ext4 candidates and recent storage
|
||||
|
|
|
|||
|
|
@ -23,6 +23,48 @@ def bash_only(tools):
|
|||
return selected
|
||||
|
||||
|
||||
def query_ollama(request):
|
||||
url = os.environ.get("OLLAMA_API_BASE", "http://127.0.0.1:11434").rstrip("/") + "/v1/chat/completions"
|
||||
upstream = urllib.request.Request(url, data=json.dumps(request).encode(), headers={"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(upstream, timeout=600) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def translate(result, tools):
|
||||
choice = result["choices"][0]
|
||||
message = choice["message"]
|
||||
if not message.get("tool_calls"):
|
||||
call = adapter.convert(message.get("content"), tools)
|
||||
if call:
|
||||
call["id"] = "call_" + uuid.uuid4().hex
|
||||
call["function"]["arguments"] = json.dumps(call["function"]["arguments"])
|
||||
message["tool_calls"] = [call]
|
||||
message["content"] = None
|
||||
choice["finish_reason"] = "tool_calls"
|
||||
return result
|
||||
|
||||
|
||||
def complete(request, bash_mode):
|
||||
"""Retry an initial prose-only answer once; never fabricate a tool call."""
|
||||
result = translate(query_ollama(request), request.get("tools", []))
|
||||
message = result["choices"][0]["message"]
|
||||
messages = request.get("messages", [])
|
||||
if (bash_mode and request.get("tools") and not message.get("tool_calls")
|
||||
and isinstance(message.get("content"), str) and message["content"].strip()
|
||||
and not any(isinstance(m, dict) and (m.get("role") == "tool" or m.get("tool_calls")) for m in messages)):
|
||||
retry = dict(request)
|
||||
retry["messages"] = messages + [message, {"role": "user", "content":
|
||||
"Start the investigation now by calling the bash tool for one simple read-only kubectl get check. "
|
||||
"Use kubectl -n NAMESPACE get RESOURCE NAME when the resource is namespaced; "
|
||||
"kubectl ns is not a command. Use one command only, with no pipes, shell operators or SSH. "
|
||||
"Return only a JSON object with name bash and arguments containing command and suggested_prefixes. "
|
||||
"Do not modify resources in this first check."}]
|
||||
retried = translate(query_ollama(retry), request["tools"])
|
||||
if retried["choices"][0]["message"].get("tool_calls"):
|
||||
return retried
|
||||
return result
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_args):
|
||||
pass
|
||||
|
|
@ -37,25 +79,14 @@ class Handler(BaseHTTPRequestHandler):
|
|||
raise ValueError("invalid request length")
|
||||
request = json.loads(self.rfile.read(length))
|
||||
streaming = request.get("stream", False)
|
||||
if os.environ.get("JEANNIE_HOLMES_BASH_ONLY") == "true" and request.get("tools"):
|
||||
bash_mode = os.environ.get("JEANNIE_HOLMES_BASH_ONLY") == "true"
|
||||
if bash_mode and request.get("tools"):
|
||||
request["tools"] = bash_only(request["tools"])
|
||||
request["stream"] = False
|
||||
request.pop("stream_options", None)
|
||||
data = json.dumps(request).encode()
|
||||
url = os.environ.get("OLLAMA_API_BASE", "http://127.0.0.1:11434").rstrip("/") + "/v1/chat/completions"
|
||||
upstream = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(upstream, timeout=600) as response:
|
||||
result = json.load(response)
|
||||
result = complete(request, bash_mode)
|
||||
choice = result["choices"][0]
|
||||
message = choice["message"]
|
||||
if not message.get("tool_calls"):
|
||||
call = adapter.convert(message.get("content"), request.get("tools", []))
|
||||
if call:
|
||||
call["id"] = "call_" + uuid.uuid4().hex
|
||||
call["function"]["arguments"] = json.dumps(call["function"]["arguments"])
|
||||
message["tool_calls"] = [call]
|
||||
message["content"] = None
|
||||
choice["finish_reason"] = "tool_calls"
|
||||
if not streaming:
|
||||
body = json.dumps(result).encode()
|
||||
self.send_response(200)
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ 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)
|
||||
|
|
@ -40,3 +41,24 @@ class ToolAdapterTests(unittest.TestCase):
|
|||
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)
|
||||
|
|
|
|||
Loading…
Reference in New Issue