Give your Gemini agents real on-chain financial capabilities using Google's native function calling API.
Six production-ready glm.Tool definitions — wallets, trading, casino games,
domain registration, agent faucet, and trustless escrow. Works with Gemini 1.5 Pro, Gemini 1.5 Flash,
and Gemini 2.0 models.
Google's Gemini models support a powerful function calling mechanism that lets agents
request real-world actions mid-inference. Purple Flea exposes six independent financial
services as Gemini-compatible glm.Tool objects so your agent can hold crypto,
execute trades, play provably fair casino games, register blockchain domains, bootstrap
itself with free seed funds, and settle peer-to-peer payments — all from within a single
Gemini chat session.
The Google Generative AI Python SDK uses
genai.GenerativeModel(tools=[...])
to inject function definitions into the model's context. When the model decides to call a
function, it emits a Part.function_call in its response. Your application
inspects this, dispatches the call to the Purple Flea SDK, and returns a
Part.function_response back to the model, which then continues generating with
full knowledge of what the function returned.
Gemini's function calling supports automatic mode (model decides when to call functions),
none mode (functions available but never called), and any mode (model must call a function).
For financial agents, automatic mode is usually the right default — Gemini will call
wallet_get_balance only when the user asks about funds, and
trading_open_position only when the conversation implies a trade should be opened.
Gemini 1.5 Pro and Gemini 2.0 Flash support parallel function calling — the model can request
multiple Purple Flea tools in the same response turn. This is especially useful for portfolio
management agents that need to simultaneously check balances across multiple chains, or for
casino strategy agents that want to check the current funding rate on BTC perpetuals while
placing a roulette bet. The response will contain multiple
function_call parts, and
your dispatcher can execute them concurrently with asyncio.gather().
Every Purple Flea API call is authenticated via your API key, stored as an environment
variable and never included in the glm.Tool definitions themselves. Agent wallets
are non-custodial BIP-39 HD wallets — Purple Flea never holds your private key. Casino
games are provably fair with on-chain settlement. Trading positions open against live
perpetual futures markets. Escrow contracts are atomic smart contracts with no trusted
third party.
Gemini 1.5 Pro and 2.0 Flash can call multiple Purple Flea tools per turn. Dispatch concurrently with asyncio for maximum throughput.
BIP-39 HD wallets with per-agent derivation paths. Purple Flea never stores or accesses private keys.
Open leveraged positions on BTC, ETH, SOL, and 40+ additional markets with real-time funding rate data.
Coin flip, dice, roulette, and crash — all with cryptographic fairness proofs. Every game result is verifiable on-chain.
New agents claim $1 USDC with zero deposit. Ideal for agent-spawning workflows where sub-agents need seed funds instantly.
Atomic agent-to-agent payments with configurable timeout, 1% service fee on release, and 15% referral on fees.
All Gemini models that support function calling can use Purple Flea tools. Here is a quick reference to help you choose based on your agent's requirements.
| Model | Function Calling | Parallel Tools | Context Window | Best For |
|---|---|---|---|---|
gemini-2.0-flash |
Yes | Yes | 1M tokens | Production agents, low latency |
gemini-1.5-pro |
Yes | Yes | 2M tokens | Complex reasoning, long sessions |
gemini-1.5-flash |
Yes | Yes | 1M tokens | High-volume, cost-optimised |
gemini-1.0-pro |
Yes | — | 32K tokens | Legacy, single-turn tool use |
Recommendation: use gemini-2.0-flash for new production deployments. It offers the best balance of speed, tool call accuracy, and cost.
Each Purple Flea service is represented as a glm.Tool containing one or more
glm.FunctionDeclaration objects. Import all six or cherry-pick the services
your agent needs to keep the tool list small and focused.
Non-custodial HD wallet management across seven chains. Function declarations include
wallet_get_address,
wallet_get_balance,
wallet_send, and
wallet_swap.
Supports Ethereum, Bitcoin, Solana, BNB Chain, Polygon, Avalanche, and Tron. DEX swaps are
routed through 1inch, Jupiter, and Paraswap for optimal pricing. Private keys are
derived client-side from your BIP-39 mnemonic — never stored by Purple Flea.
Full-featured perpetual futures trading. Gemini can call
trading_open_position to go long or short with 1x–100x leverage,
trading_close_position to exit with a realized PnL report,
trading_get_positions to audit the portfolio, and
trading_get_markets to scan funding rates and 24h volume across
40+ perpetual pairs before deciding where to allocate collateral.
Four provably fair on-chain games accessible via four Gemini function declarations:
casino_coin_flip (pick heads or tails, set wager),
casino_dice (1–6 dice, configurable sides),
casino_roulette (full European roulette, all bet types), and
casino_crash (configurable auto-cashout multiplier). Every result includes
a cryptographic fairness proof that can be independently verified on-chain.
Register and manage .eth (ENS), .sol (Solana Name Service), and Web2 TLD domains without
leaving the chat session. Three function declarations:
domains_check (returns availability and pricing),
domains_register (handles payment and on-chain ownership transfer), and
domains_list (lists all domains owned by the connected wallet).
Agents can build autonomous domain-squatting or identity-management strategies natively.
Bootstrap new agents with $1 USDC at no cost using the
faucet_claim function declaration.
Agent registration and fund delivery happen atomically in a single HTTP call — no manual
approval, no KYC, no deposit required. One claim per unique agent identity. Use
faucet_stats to retrieve public distribution metrics: total agents onboarded,
USDC distributed to date, and daily claim volume.
Trustless agent-to-agent payments via four function declarations:
escrow_create (lock USDC, specify counterparty and task),
escrow_complete (counterparty signals task done),
escrow_release (creator releases locked funds; 1% fee deducted), and
escrow_status (get state, event log, and payout details).
Your referral ID earns 15% of the 1% service fee on every release — automatically.
The Google Generative AI SDK uses glm.Tool and
glm.FunctionDeclaration to describe callable functions.
Below is a complete working example showing how to define tools, send a message, intercept function
calls, dispatch to the Purple Flea SDK, and return results.
pip install google-generativeai purpleflea-python
import google.generativeai as genai import google.ai.generativelanguage as glm # ── Wallet balance tool declaration ───────────────────── wallet_tool = glm.Tool( function_declarations=[ glm.FunctionDeclaration( name="wallet_get_balance", description=( "Returns the native token and stablecoin balance of the agent's " "non-custodial HD wallet on the specified blockchain network. " "Supported chains: ethereum, bitcoin, solana, bnb, polygon, avalanche, tron." ), parameters=glm.Schema( type=glm.Type.OBJECT, properties={ "chain": glm.Schema( type=glm.Type.STRING, description="Blockchain to query (e.g. 'ethereum')", enum=["ethereum", "bitcoin", "solana", "bnb", "polygon", "avalanche", "tron"], ), "include_tokens": glm.Schema( type=glm.Type.BOOLEAN, description="Include ERC-20/SPL token balances alongside native", ), }, required=["chain"], ), ), ] ) # ── Trading tool declaration ───────────────────────────── trading_tool = glm.Tool( function_declarations=[ glm.FunctionDeclaration( name="trading_open_position", description=( "Opens a leveraged perpetual futures position on the specified market. " "Returns position_id, entry_price, liquidation_price, and notional_size." ), parameters=glm.Schema( type=glm.Type.OBJECT, properties={ "market": glm.Schema(type=glm.Type.STRING, description="Perpetual market, e.g. BTC-PERP"), "side": glm.Schema(type=glm.Type.STRING, enum=["long", "short"]), "collateral": glm.Schema(type=glm.Type.NUMBER, description="USDC collateral amount"), "leverage": glm.Schema(type=glm.Type.INTEGER, description="Leverage 1–100", format="int32"), }, required=["market", "side", "collateral", "leverage"], ), ), glm.FunctionDeclaration( name="trading_get_markets", description="Returns available perpetual markets with funding rates and 24h volume.", parameters=glm.Schema(type=glm.Type.OBJECT, properties={}, required=[]), ), ] ) # ── Casino tool declaration ────────────────────────────── casino_tool = glm.Tool( function_declarations=[ glm.FunctionDeclaration( name="casino_coin_flip", description="Flips a provably fair coin. Returns outcome, multiplier, and fairness proof.", parameters=glm.Schema( type=glm.Type.OBJECT, properties={ "choice": glm.Schema(type=glm.Type.STRING, enum=["heads", "tails"]), "wager": glm.Schema(type=glm.Type.NUMBER, description="USDC wager amount"), }, required=["choice", "wager"], ), ), ] )
import os, json import google.generativeai as genai from purpleflea import PurpleFlea # ── Configure API keys ────────────────────────────────── genai.configure(api_key=os.environ["GEMINI_API_KEY"]) pf = PurpleFlea(api_key=os.environ["PURPLEFLEA_API_KEY"]) # ── Initialise model with all six Purple Flea tools ───── model = genai.GenerativeModel( model_name="gemini-2.0-flash", tools=[wallet_tool, trading_tool, casino_tool, domains_tool, faucet_tool, escrow_tool], generation_config=genai.GenerationConfig(temperature=0.1), ) # ── Tool dispatcher ────────────────────────────────────── def dispatch(fn_name: str, fn_args: dict) -> dict: match fn_name: case "wallet_get_balance": return pf.wallet.get_balance(**fn_args) case "wallet_send": return pf.wallet.send(**fn_args) case "wallet_swap": return pf.wallet.swap(**fn_args) case "trading_open_position": return pf.trading.open_position(**fn_args) case "trading_close_position": return pf.trading.close_position(**fn_args) case "trading_get_markets": return pf.trading.get_markets(**fn_args) case "casino_coin_flip": return pf.casino.coin_flip(**fn_args) case "casino_dice": return pf.casino.dice(**fn_args) case "casino_roulette": return pf.casino.roulette(**fn_args) case "domains_check": return pf.domains.check(**fn_args) case "domains_register": return pf.domains.register(**fn_args) case "faucet_claim": return pf.faucet.claim(**fn_args) case "escrow_create": return pf.escrow.create(**fn_args) case "escrow_release": return pf.escrow.release(**fn_args) case _: return {"error": f"Unknown tool: {fn_name}"} # ── Agentic loop ──────────────────────────────────────── chat = model.start_chat(enable_automatic_function_calling=False) user_msg = ( "Claim the faucet for my new agent, then check my Ethereum " "balance, and open a 3x BTC long using 50 USDC collateral." ) response = chat.send_message(user_msg) while True: # Collect all function_call parts from the response fc_parts = [ part for candidate in response.candidates for part in candidate.content.parts if part.function_call.name # truthy when a function call is present ] if not fc_parts: # No more function calls — print the final text response print(response.text) break # Build function_response parts and dispatch each call response_parts = [] for part in fc_parts: fc = part.function_call result = dispatch(fc.name, dict(fc.args)) response_parts.append( genai.protos.Part( function_response=genai.protos.FunctionResponse( name=fc.name, response={"result": result}, ) ) ) # Send all function responses back in a single turn response = chat.send_message(response_parts)
When Gemini emits multiple function calls in a single response, you can execute them
concurrently using asyncio.gather() for significantly lower latency — especially
useful when Gemini requests balance checks on multiple chains simultaneously.
import asyncio, os import google.generativeai as genai from purpleflea import AsyncPurpleFlea genai.configure(api_key=os.environ["GEMINI_API_KEY"]) pf = AsyncPurpleFlea(api_key=os.environ["PURPLEFLEA_API_KEY"]) async def dispatch_async(fn_name: str, fn_args: dict) -> dict: match fn_name: case "wallet_get_balance": return await pf.wallet.get_balance(**fn_args) case "trading_open_position": return await pf.trading.open_position(**fn_args) case "casino_coin_flip": return await pf.casino.coin_flip(**fn_args) case "faucet_claim": return await pf.faucet.claim(**fn_args) case _: return {"error": f"Unknown: {fn_name}"} async def run_agent(): model = genai.GenerativeModel("gemini-2.0-flash", tools=[wallet_tool, casino_tool]) chat = model.start_chat(enable_automatic_function_calling=False) resp = chat.send_message("Check my ETH and SOL balance, then flip a coin for 1 USDC.") while True: fc_parts = [ p for c in resp.candidates for p in c.content.parts if p.function_call.name ] if not fc_parts: print(resp.text) break # Dispatch all function calls concurrently results = await asyncio.gather( *[dispatch_async(p.function_call.name, dict(p.function_call.args)) for p in fc_parts] ) response_parts = [ genai.protos.Part( function_response=genai.protos.FunctionResponse( name=fc_parts[i].function_call.name, response={"result": results[i]}, ) ) for i in range(len(fc_parts)) ] resp = chat.send_message(response_parts) asyncio.run(run_agent())
You need a Google AI Studio API key (or a Vertex AI service account), a Purple Flea API key, and Python 3.10 or later. The setup takes under five minutes.
pip install google-generativeai purpleflea-python in your virtual environment.
For async support install pip install purpleflea-python[async] which pulls in
httpx[asyncio] automatically.
PURPLEFLEA_API_KEY. Your HD wallet is created
automatically on first API use; you do not need to provision it separately.
glm.Tool definitions from the code examples above, or import the
pre-built definitions from purpleflea.integrations.gemini:
from purpleflea.integrations.gemini import all_tools.
Pass them to GenerativeModel(tools=all_tools).
function_call parts in the response, dispatch to the Purple Flea SDK,
and return function_response parts. The model continues until it
produces a final text answer with no further function calls. Call
faucet_claim on first run to seed the agent with $1 USDC.
# Instead of writing glm.Tool definitions by hand, import them: from purpleflea.integrations.gemini import ( wallet_tool, trading_tool, casino_tool, domains_tool, faucet_tool, escrow_tool, all_tools, # convenience list of all six ) model = genai.GenerativeModel( model_name="gemini-2.0-flash", tools=all_tools, # all six Purple Flea services )
Every Purple Flea API call that generates a fee — casino house edge, trading commission, escrow service fee — can carry a referral tag. If you built the agent, the integration layer, or the orchestration system driving those calls, you earn 20% of all fees your referred agents generate, paid in USDC on a weekly basis with no cap and no minimum.
Pass your referral ID to the SDK constructor: PurpleFlea(referral_id="your_id").
Every subsequent API call will automatically attach the referral header. This is fully transparent
in the Gemini function dispatching pattern — no changes to your tool definitions or dispatcher logic required.
pf = PurpleFlea( api_key = os.environ["PURPLEFLEA_API_KEY"], referral_id = "your_referral_id", # earn 20% of all agent-generated fees ) # Escrow referral: escrow_create includes a referral_id param that gives # the referrer 15% of the 1% escrow fee — separate from the 20% base referral. # Both stack automatically when both are configured.
Purple Flea supports every major AI framework and standalone REST access. Explore other integrations and deep-dive API documentation below.
Get your free API key in under a minute. Your agent wallet is provisioned automatically on first use. Claim $1 USDC from the faucet and start experimenting with live markets — no credit card required.