Google Gemini Bitcoin Agent Integration: Using the OpenAI-compatible interface
Google Gemini Bitcoin Agent Integration: Using the OpenAI-compatible interface
Research question
How can a developer use Google Gemini to select a Bitcoin operation without granting the hosted model direct access to wallet credentials? This study uses a single fixed Testnet SegWit balance query as a narrow experiment design. It is a reference implementation, not a tested integration or an official provider extension.
Protocol boundary
The application sends a tool definition and a fixed prompt to https://generativelanguage.googleapis.com/v1beta/openai/chat/completions. The provider returns a proposed function invocation. The local Python process checks the response before contacting WAB ENGINE. The model cannot choose a URL, network, wallet type or credential. Using the OpenAI-compatible interface is the specific protocol concern in this example.
This example uses a chat-completions-style function declaration. Arguments arrive as JSON text and the tool call ID identifies the proposed invocation. A continuation normally uses a tool-role message linked to that ID; provider-specific reasoning and continuation requirements must be checked separately.
Source 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):
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://generativelanguage.googleapis.com/v1beta/openai/chat/completions', {"model": os.environ["GEMINI_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["GEMINI_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()Developer setup
Use Python 3 and a locally restored Testnet wallet. Configure BTC_KEY, GEMINI_API_KEY and GEMINI_MODEL through a trusted local environment; select a model that supports function calling. Run python3 example.py only when you intend to make a potentially billable provider request and a local balance query. No SEND operation is exposed. The engine address is fixed to loopback; adapt deployment networking deliberately rather than accepting a model-supplied URL.
Evidence and failure handling
A provider response is a proposal, not proof of a wallet balance. The local process requires exactly one completed tool request, the expected name and empty arguments. It checks the engine success envelope and a nonnegative integer balance. Missing fields, timeouts and unsupported response formats stop execution. The printed JSON is local evidence, not a generated answer. No second model request is made, so wallet balance is not returned to the hosted model. Do not log secrets or automatically retry financial operations. The credential may authorize more than this example exposes; the tool restriction is application-level, not an engine-issued read-only credential.
Limitations and extension
No provider calls, engine calls or dependency compatibility tests were performed for this study. Endpoint and model availability may change; consult the provider documentation before use. The example is intentionally a single-turn protocol fragment, not a complete agent loop. A production application needs explicit user authorization, isolation, redacted errors, rate limits and a deliberate policy for disclosing wallet data. Payment tools require a separate approval and idempotency design; the engine's signed fee law remains unchanged.
References
- Provider documentation: https://ai.google.dev/gemini-api/docs/openai
- Engine API: https://thamer.org/api
- Engine: https://thamer.org/engine
- Source repository: https://thamer.org/repo/
