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): request = Request(url, json.dumps(payload).encode(), {"Content-Type": "application/json", **headers}, method="POST") with build_opener(ProxyHandler({}), NoRedirect()).open(request, timeout=30) as response: raw = response.read(1048577) if len(raw) > 1048576: raise ValueError("Response too large") return json.loads(raw) def balance(): reply = post("http://127.0.0.1:7070/api/v5/btc/wallet/balance", {"net": "test", "type": "segwit"}, {"X-BTC-KEY": os.environ["BTC_KEY"]}) if reply.get("ok") is not True: raise ValueError("Engine rejected request") sats = reply["result"]["balance_sat"] if type(sats) is not int or sats < 0: raise ValueError("Invalid balance") return {"net": "test", "type": "segwit", "balance_sat": sats} SCHEMA = {"type": "object", "properties": {}, "additionalProperties": False} PROMPT = "Request the bitcoin_balance tool once. Do not estimate a balance." def main(): reply = post('https://api.openai.com/v1/chat/completions', {"model": os.environ["OPENAI_MODEL"], "messages": [{"role": "user", "content": PROMPT}], "stream": False, "tools": [{"type": "function", "function": {"name": "bitcoin_balance", "description": "Read Testnet SegWit balance", "parameters": SCHEMA}}]}, {"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]}) choice = reply["choices"][0] calls = choice["message"].get("tool_calls") or [] if choice.get("finish_reason") != "tool_calls" or len(calls) != 1: raise ValueError("Expected one complete tool request") call = calls[0] fn = call["function"] if call.get("type") != "function" or fn["name"] != "bitcoin_balance" or json.loads(fn["arguments"]) != {}: raise ValueError("Unexpected tool request") print(json.dumps({"tool_call_id": call["id"], "result": balance()})) if __name__ == "__main__": main()