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.anthropic.com/v1/messages', {"model": os.environ["ANTHROPIC_MODEL"], "max_tokens": 512, "messages": [{"role": "user", "content": PROMPT}], "tools": [{"name": "bitcoin_balance", "description": "Read Testnet SegWit balance", "input_schema": SCHEMA}]}, {"x-api-key": os.environ["ANTHROPIC_API_KEY"], "anthropic-version": "2023-06-01"}) calls = [b for b in reply["content"] if b.get("type") == "tool_use"] if reply.get("stop_reason") != "tool_use" or len(calls) != 1: raise ValueError("Expected one complete tool request") call = calls[0] if call["name"] != "bitcoin_balance" or call["input"] != {}: raise ValueError("Unexpected tool request") print(json.dumps({"tool_call_id": call["id"], "result": balance()})) if __name__ == "__main__": main()