#!/usr/bin/env python3 """Loopback OpenAI-compatible proxy for schema-checked Ollama text tool calls.""" import importlib.util import json import os import re import shlex from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path import sys import urllib.error import urllib.request import uuid spec = importlib.util.spec_from_file_location("ollama_tool_adapter", Path(__file__).with_name("ollama-tool-call-adapter.py")) adapter = importlib.util.module_from_spec(spec) spec.loader.exec_module(adapter) def bash_only(tools): selected = [tool for tool in tools if isinstance(tool, dict) and tool.get("type") == "function" and isinstance(tool.get("function"), dict) and tool["function"].get("name") == "bash"] if len(selected) != 1: raise ValueError("Holmes did not provide exactly one bash tool") 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 safe_initial_call(message, tools): calls = message.get("tool_calls") if not isinstance(calls, list) or len(calls) != 1: return False function = calls[0].get("function") or {} try: args = json.loads(function.get("arguments", ""), object_pairs_hook=adapter.unique_object) validated = adapter.convert(json.dumps({"name": function.get("name"), "arguments": args}), tools) command = args["command"] if not isinstance(command, str) or re.search(r"[;&|`$><\n\r]", command): return False words = shlex.split(command) if not words or words[0] != "kubectl" or words.count("get") != 1: return False if any(not re.fullmatch(r"[A-Za-z0-9_./:=,\-]+", word) for word in words): return False if any(word.startswith(("--raw", "--watch", "--server", "--token")) for word in words): return False return validated is not None except (ValueError, TypeError, KeyError, AttributeError): return False 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", []) print("initial_response", "tool_call=" + str(bool(message.get("tool_calls"))), "tools=" + str(len(request.get("tools") or [])), "prior_tool=" + str(any(isinstance(m, dict) and (m.get("role") == "tool" or bool(m.get("tool_calls"))) for m in messages)), flush=True) 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) users = [m for m in messages if isinstance(m, dict) and m.get("role") == "user" and isinstance(m.get("content"), str)] if not users: return result retry["messages"] = [{"role": "system", "content": "Use the bash tool to perform one read-only Kubernetes check."}, users[-1], {"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"]) accepted = safe_initial_call(retried["choices"][0]["message"], request["tools"]) print("initial_retry", "tool_call=" + str(bool(retried["choices"][0]["message"].get("tool_calls"))), "accepted=" + str(accepted), flush=True) if accepted: return retried return result class Handler(BaseHTTPRequestHandler): def log_message(self, *_args): pass def do_POST(self): if self.path != "/v1/chat/completions": self.send_error(404) return try: length = int(self.headers.get("Content-Length", "0")) if length <= 0 or length > 4_000_000: raise ValueError("invalid request length") request = json.loads(self.rfile.read(length)) streaming = request.get("stream", False) 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) result = complete(request, bash_mode) choice = result["choices"][0] message = choice["message"] if not streaming: body = json.dumps(result).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Connection", "close") self.end_headers() delta = {"role": "assistant"} if message.get("tool_calls"): delta["tool_calls"] = [dict(call, index=i) for i, call in enumerate(message["tool_calls"])] else: delta["content"] = message.get("content") or "" base = {"id": result.get("id", "chatcmpl-local"), "object": "chat.completion.chunk", "created": result.get("created", 0), "model": result.get("model", request.get("model", ""))} for chunk in (dict(base, choices=[{"index": 0, "delta": delta, "finish_reason": None}]), dict(base, choices=[{"index": 0, "delta": {}, "finish_reason": choice.get("finish_reason", "stop")}] )): self.wfile.write(b"data: " + json.dumps(chunk).encode() + b"\n\n") self.wfile.write(b"data: [DONE]\n\n") except (OSError, ValueError, KeyError, IndexError, TypeError, urllib.error.URLError): self.send_error(502, "Ollama proxy request failed") def main(): if len(sys.argv) != 2: raise SystemExit("usage: ollama-tool-proxy.py PORT_FILE") server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) Path(sys.argv[1]).write_text(str(server.server_port), encoding="utf-8") server.serve_forever() if __name__ == "__main__": main()