example.py
TEXT FILE2.2 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.x.ai/v1/chat/completions', {"model": os.environ["XAI_MODEL"],
34 "messages": [{"role": "user", "content": PROMPT}], "stream": False,
35 "tools": [{"type": "function", "function": {"name": "bitcoin_balance",
36 "description": "Read Testnet SegWit balance", "parameters": SCHEMA}}]},
37 {"Authorization": "Bearer " + os.environ["XAI_API_KEY"]})
38 choice = reply["choices"][0]
39 calls = choice["message"].get("tool_calls") or []
40 if choice.get("finish_reason") != "tool_calls" or len(calls) != 1:
41 raise ValueError("Expected one complete tool request")
42 call = calls[0]
43 fn = call["function"]
44 if call.get("type") != "function" or fn["name"] != "bitcoin_balance" or json.loads(fn["arguments"]) != {}:
45 raise ValueError("Unexpected tool request")
46 print(json.dumps({"tool_call_id": call["id"], "result": balance()}))
47
48if __name__ == "__main__":
49 main()Read-only source · Select a line number to link directly · Raw download above
