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=None):
10 req = Request(url, json.dumps(payload).encode(),
11 {"Content-Type": "application/json", **(headers or {})}, method="POST")
12 with build_opener(ProxyHandler({}), NoRedirect()).open(req, timeout=30) as r:
13 raw = r.read(1048577)
14 if len(raw) > 1048576:
15 raise ValueError("Response too large")
16 return json.loads(raw)
17
18def balance():
19 result = 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 result.get("ok") is not True:
23 raise ValueError("Engine rejected request")
24 sats = result["result"]["balance_sat"]
25 if type(sats) is not int or sats < 0:
26 raise ValueError("Invalid balance")
27 return sats
28
29TOOL = {"type": "function", "function": {"name": "bitcoin_balance",
30 "description": "Read the selected Testnet SegWit balance in satoshis",
31 "parameters": {"type": "object", "properties": {}, "additionalProperties": False}}}
32MESSAGES = [{"role": "user", "content": "Read my Testnet Bitcoin balance using the tool."}]
33
34def dispatch(call):
35 fn = call["function"]
36 args = fn["arguments"]
37 if isinstance(args, str):
38 args = json.loads(args)
39 if fn["name"] != "bitcoin_balance" or args != {}:
40 raise ValueError("Unexpected tool request")
41 return {"balance_sat": balance(), "net": "test", "type": "segwit"}
42
43def main():
44 payload = {"model": os.environ["LOCAL_MODEL"], "messages": MESSAGES,
45 "tools": [TOOL], "stream": False}
46 reply = post("http://127.0.0.1:11434/api/chat", payload)
47 message = reply["message"]
48 calls = message.get("tool_calls") or []
49 if len(calls) != 1:
50 raise ValueError("Expected exactly one tool call; no wallet request executed")
51 print(json.dumps(dispatch(calls[0])))
52
53if __name__ == "__main__":
54 main()Read-only source · Select a line number to link directly · Raw download above
