#!/usr/bin/env python3 """Loopback OpenAI-compatible proxy for schema-checked Ollama text tool calls.""" import importlib.util import json import os 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 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) if os.environ.get("JEANNIE_HOLMES_BASH_ONLY") == "true" 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) 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) 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()