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

AG2 and Bitcoin: Separating tool selection from execution

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

Research question

How can a developer use AG2 to read Bitcoin wallet information without granting a model unrestricted wallet access?

Framework design

AG2 distinguishes the assistant that proposes a tool call from the executor that runs it. Register the same function with these roles; do not give the assistant arbitrary shell execution. Configure the agents and their termination policy outside this example.

Engine contract

The example uses POST /api/v5/btc/wallet/balance with net: test and type: segwit. The local operator provides BTC_KEY outside the model conversation. The HTTP request uses X-BTC-KEY, disables redirects and proxies, and checks the engine response envelope before projecting the integer balance_sat. The model cannot choose an endpoint through this tool. This is a read operation, not a payment or proof of confirmation.

Reference implementation

Python · 39 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 RuntimeError("Redirect refused")
8
9def balance() -> int:
10    """Read the operator-selected Testnet SegWit wallet balance in satoshis."""
11    key = os.environ["BTC_KEY"]
12    request = Request("http://127.0.0.1:7070/api/v5/btc/wallet/balance",
13                      data=b'{"net":"test","type":"segwit"}',
14                      headers={"Content-Type": "application/json", "X-BTC-KEY": key},
15                      method="POST")
16    try:
17        with build_opener(ProxyHandler({}), NoRedirect()).open(request, timeout=10) as response:
18            raw = response.read(1048577)
19        if len(raw) > 1048576:
20            raise ValueError("Oversized response")
21        envelope = json.loads(raw)
22        if envelope.get("ok") is not True:
23            raise ValueError("Engine rejected request")
24        sats = envelope["result"]["balance_sat"]
25        if type(sats) is not int or sats < 0:
26            raise ValueError("Invalid balance")
27        return sats
28    except Exception:
29        raise RuntimeError("Balance unavailable") from None
30
31from autogen import register_function
32
33def bitcoin_balance() -> str:
34    """Read Testnet SegWit balance in satoshis."""
35    return json.dumps({"balance_sat": balance()})
36
37def register_balance(caller, executor):
38    register_function(bitcoin_balance, caller=caller, executor=executor,
39                      name="bitcoin_balance", description="Read Testnet balance")
Source: /repo/ai-agents/stage05/ag2/example.py · Raw file · Read-only excerpt

Developer workflow

Install ag2 in a dedicated environment and consult the upstream documentation for compatible versions. Review the framework-specific registration fragment before attaching it to a model. First substitute a synthetic balance function and verify that the framework returns only the intended value. Check failure envelopes, missing fields, negative and Boolean amounts, timeout and oversized responses. Only then consider an operator-controlled Testnet request. No model API key is needed to study the HTTP contract.

Security and limitations

A function boundary is not a process sandbox. A model with shell access or arbitrary code execution in the same environment may read BTC_KEY or bypass the tool. Use an isolated credential-bearing process for such deployments. Balance is private financial data; do not forward it to hosted models without operator consent. No SEND, recovery, or removal tool is provided. The engine's signed fee law remains unchanged. This is an untested reference fragment, not a production SDK or verified native integration. Framework dependencies and current signatures were not verified against installed versions.

References

  • Upstream documentation: https://docs.ag2.ai/
  • Engine API: https://thamer.org/api
  • Engine overview: https://thamer.org/engine
  • Source: https://thamer.org/repo/ai-agents/stage05/ag2/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