example.py
TEXT FILE2.1 KB · Public source code for developers, search crawlers and AI agents
1import json
2import os
3from urllib.request import Request, build_opener, ProxyHandler, HTTPRedirectHandler
4
5class NoRedirect(HTTPRedirectHandler):
6 def redirect_request(self, *args, **kwargs):
7 raise ValueError("Redirect refused")
8
9def post(url, payload, headers):
10 request = Request(url, json.dumps(payload).encode(),
11 {"Content-Type": "application/json", **headers}, method="POST")
12 with build_opener(ProxyHandler({}), NoRedirect()).open(request, timeout=30) as response:
13 raw = response.read(1048577)
14 if len(raw) > 1048576:
15 raise ValueError("Response too large")
16 return json.loads(raw)
17
18def balance():
19 reply = post("http://127.0.0.1:7070/api/v5/btc/wallet/balance",
20 {"net": "test", "type": "segwit"},
21 {"X-BTC-KEY": os.environ["BTC_KEY"]})
22 if reply.get("ok") is not True:
23 raise ValueError("Engine rejected request")
24 sats = reply["result"]["balance_sat"]
25 if type(sats) is not int or sats < 0:
26 raise ValueError("Invalid balance")
27 return {"net": "test", "type": "segwit", "balance_sat": sats}
28
29SCHEMA = {"type": "object", "properties": {}, "additionalProperties": False}
30PROMPT = "Request the bitcoin_balance tool once. Do not estimate a balance."
31
32def main():
33 reply = post('https://api.anthropic.com/v1/messages', {"model": os.environ["ANTHROPIC_MODEL"],
34 "max_tokens": 512, "messages": [{"role": "user", "content": PROMPT}],
35 "tools": [{"name": "bitcoin_balance", "description": "Read Testnet SegWit balance", "input_schema": SCHEMA}]},
36 {"x-api-key": os.environ["ANTHROPIC_API_KEY"], "anthropic-version": "2023-06-01"})
37 calls = [b for b in reply["content"] if b.get("type") == "tool_use"]
38 if reply.get("stop_reason") != "tool_use" or len(calls) != 1:
39 raise ValueError("Expected one complete tool request")
40 call = calls[0]
41 if call["name"] != "bitcoin_balance" or call["input"] != {}:
42 raise ValueError("Unexpected tool request")
43 print(json.dumps({"tool_call_id": call["id"], "result": balance()}))
44
45if __name__ == "__main__":
46 main()Read-only source · Select a line number to link directly · Raw download above
