THAMER
Sovereign Bitcoin Wallet

WALLET AI BITCOIN

Your Bitcoin Wallet. Your Keys. Your Engine.

Self-hosted Bitcoin software built for developers, applications, and AI agents.

CREATE WALLET

LocalAI and Bitcoin: Self-hosted Bitcoin tools across inference backends

permalink THAMER
#ai-agents#bitcoin#localai#python#wab-engine

Research question

Can a local inference runtime select a Bitcoin tool without becoming the wallet execution authority? This study treats LocalAI as a model-serving component, not a complete autonomous agent.

Runtime architecture

LocalAI exposes an OpenAI-compatible interface, but function calling behavior depends on the selected backend and model configuration. The host program owns the tool catalog and dispatches only a single recognized call with empty arguments. The model never receives the wallet key or chooses the engine URL, network, or address type. The program prints the actual tool result rather than asking the model to invent a balance.

Engine contract

The example calls POST /api/v5/btc/wallet/balance on the local WAB Engine at port 7070, using X-BTC-KEY and a fixed Testnet SegWit request. It validates the success envelope and integer balance. No SEND or identity recovery is exposed. The signed fee law is untouched.

Reference implementation

Python · 55 lines
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    payload["tool_choice"] = "auto"
47    reply = post("http://127.0.0.1:8080/v1/chat/completions", payload)
48    message = reply["choices"][0]["message"]
49    calls = message.get("tool_calls") or []
50    if len(calls) != 1:
51        raise ValueError("Expected exactly one tool call; no wallet request executed")
52    print(json.dumps(dispatch(calls[0])))
53
54if __name__ == "__main__":
55    main()

Developer workflow

Configure a model with function calling support; do not assume every backend implements the same tool parser. Set LOCAL_MODEL to the configured model identifier and supply BTC_KEY privately to the host process. The example assumes an unauthenticated loopback inference server at port 8080; adapt authentication and networking to your deployment. Python 3 standard library is sufficient for the client. First replace balance() with a synthetic result and exercise missing, multiple and malformed tool calls. Then review the real engine contract before any operator-controlled Testnet use.

Security and limitations

Local inference does not itself provide isolation. Keep the inference server separate from the credential-bearing executor; do not give the model shell access to its environment. The sample disables HTTP redirects and environment proxies and limits response size. It intentionally stops after one tool result rather than implementing a conversation loop. Wallet balances are private data. This is an educational reference, not a production integration; runtime versions, model compatibility and live requests have not been tested. Local software and model licenses and hardware costs vary.

References

  • Upstream implementation reference: https://localai.io/features/openai-functions/
  • Engine API: https://thamer.org/api
  • Engine overview: https://thamer.org/engine
  • Source: https://thamer.org/repo/ai-agents/stage06/localai/example.py

Questions & Answers

Explore all questions →

Latest from the Lab

THAMER illustrated developer portrait and signature

ABOUT THE DEVELOPER

Independent Software Developer specializing in Bitcoin Script, Golang, and AI Agents.

Software engineering · Independent research · Open-source projects