Ollama and Bitcoin: Native tool calling with a local model
Research question
Can a local inference runtime select a Bitcoin tool without becoming the wallet execution authority? This study treats Ollama as a model-serving component, not a complete autonomous agent.
Runtime architecture
Ollama returns tool calls in the message object. Its native chat endpoint accepts a tools array and stream=false. Arguments may already be decoded objects. 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
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()Developer workflow
Select a locally installed tool-capable model; small models may emit ordinary text instead of a tool call. 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 11434; 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://docs.ollama.com/capabilities/tool-calling
- Engine API: https://thamer.org/api
- Engine overview: https://thamer.org/engine
- Source: https://thamer.org/repo/ai-agents/stage06/ollama/example.py
