import json import os from urllib.request import Request, build_opener, ProxyHandler, HTTPRedirectHandler class NoRedirect(HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): raise ValueError("Redirect refused") def post(url, payload, headers=None): req = Request(url, json.dumps(payload).encode(), {"Content-Type": "application/json", **(headers or {})}, method="POST") with build_opener(ProxyHandler({}), NoRedirect()).open(req, timeout=30) as r: raw = r.read(1048577) if len(raw) > 1048576: raise ValueError("Response too large") return json.loads(raw) def balance(): result = post("http://127.0.0.1:7070/api/v5/btc/wallet/balance", {"net": "test", "type": "segwit"}, {"X-BTC-KEY": os.environ["BTC_KEY"]}) if result.get("ok") is not True: raise ValueError("Engine rejected request") sats = result["result"]["balance_sat"] if type(sats) is not int or sats < 0: raise ValueError("Invalid balance") return sats TOOL = {"type": "function", "function": {"name": "bitcoin_balance", "description": "Read the selected Testnet SegWit balance in satoshis", "parameters": {"type": "object", "properties": {}, "additionalProperties": False}}} MESSAGES = [{"role": "user", "content": "Read my Testnet Bitcoin balance using the tool."}] def dispatch(call): fn = call["function"] args = fn["arguments"] if isinstance(args, str): args = json.loads(args) if fn["name"] != "bitcoin_balance" or args != {}: raise ValueError("Unexpected tool request") return {"balance_sat": balance(), "net": "test", "type": "segwit"} def main(): payload = {"model": os.environ["LOCAL_MODEL"], "messages": MESSAGES, "tools": [TOOL], "stream": False} payload["tool_choice"] = "auto" reply = post("http://127.0.0.1:8000/v1/chat/completions", payload) message = reply["choices"][0]["message"] calls = message.get("tool_calls") or [] if len(calls) != 1: raise ValueError("Expected exactly one tool call; no wallet request executed") print(json.dumps(dispatch(calls[0]))) if __name__ == "__main__": main()