Give your Python agents a complete financial infrastructure in minutes.
Six APIs — casino, trading, wallets, domains, faucet, and escrow —
wrapped as function_tool decorated functions, ready for
Runner.run(), handoffs, and native MCP connections.
Background
The OpenAI Agents SDK (pip package openai-agents) is
OpenAI’s open-source Python framework for building production-grade agentic
systems. It evolved from the research prototype Swarm into a fully supported
library with first-class tool support, typed context, handoffs between agents,
streaming, guardrails, and built-in MCP (Model Context Protocol) server connections.
Agents are defined with a system prompt and a list of tools.
Runner.run()
orchestrates the multi-turn loop — the model calls tools,
results are fed back, and the loop continues until the agent produces a
final response or hands off to a specialist sub-agent.
Purple Flea’s financial APIs are a perfect match: each API call is a
single deterministic HTTP request with a clear input schema and a structured
JSON response — exactly what
function_tool
was designed for.
One decorator turns any typed Python function into a schema-validated tool the model can call.
Route to specialist sub-agents mid-conversation. Referral codes travel in typed context.
Input and output guardrails run in parallel — enforce bet-size limits without blocking the model.
Connect to faucet.purpleflea.com/mcp and escrow.purpleflea.com/mcp as StreamableHTTP MCP servers.
Installation
Install openai-agents alongside the Purple Flea Python SDK.
The SDK wraps all six APIs as ready-to-use function_tool
decorated functions you can pass directly to any Agent().
# pin your versions for reproducible builds openai-agents>=0.0.7 purpleflea>=1.0.0 openai>=1.30.0 python-dotenv>=1.0.0 httpx>=0.27.0
import asyncio import os from agents import Agent, Runner from purpleflea.tools.openai_agents import ( casino_coin_flip, wallet_create, wallet_get_balance, trading_get_price, faucet_claim, ) # One API key unlocks all six Purple Flea services os.environ["PURPLE_FLEA_API_KEY"] = "sk_live_..." agent = Agent( name="financial-agent", instructions="You are a DeFi agent. Use the tools to help the user " "manage wallets, trade perpetual futures, and play casino games.", tools=[wallet_create, wallet_get_balance, trading_get_price, casino_coin_flip, faucet_claim], ) async def main(): result = await Runner.run( agent, "Claim the faucet, create an Ethereum wallet, then flip a coin for $0.50" ) print(result.final_output) asyncio.run(main())
Tool Definitions
Every tool uses the @function_tool decorator from agents.
The SDK reads type annotations and docstrings to build the JSON schema sent to the
model — no manual schema writing required.
| Function | Service | Description |
|---|---|---|
| casino_coin_flip | Casino | Provably fair coin flip — heads or tails for a USDC wager up to $10,000 |
| casino_dice_roll | Casino | Roll dice with configurable target (1–99) and over/under direction |
| casino_slots | Casino | Three-reel slot machine with seed-verifiable randomness |
| trading_get_price | Trading | Current mid price for any of 275+ perpetual futures markets via Hyperliquid |
| trading_open_position | Trading | Open a long or short perpetual position with configurable leverage up to 50x |
| trading_close_position | Trading | Close an open position by ID and settle PnL to the agent wallet |
| trading_list_positions | Trading | List all open perpetual positions with unrealised PnL |
| wallet_create | Wallet | Create a non-custodial HD wallet on Ethereum, Solana, Bitcoin, or Tron |
| wallet_get_balance | Wallet | Get token balances across all supported chains for a wallet address |
| wallet_send | Wallet | Send tokens from an agent wallet to any on-chain address |
| domains_check | Domains | Check availability of a domain name across supported TLDs |
| domains_register | Domains | Register a domain name with crypto payment — no KYC required |
| faucet_claim | Faucet | Claim $1 USDC for a new agent — one claim per agent identity |
| escrow_create | Escrow | Create a trustless escrow between two agent wallets (1% fee) |
| escrow_release | Escrow | Release escrowed funds to recipient after the condition is verified |
| escrow_dispute | Escrow | Open a dispute on an escrow — triggers the arbitration protocol |
from agents import function_tool from typing import Literal import httpx, os _BASE = "https://casino.purpleflea.com/api/v1" _KEY = os.environ["PURPLE_FLEA_API_KEY"] @function_tool async def casino_coin_flip( wallet_id: str, wager_usdc: float, side: Literal["heads", "tails"], referral_code: str = "", ) -> dict: """Flip a provably fair coin. Args: wallet_id: Agent wallet ID to debit/credit the wager. wager_usdc: Wager amount in USDC (min 0.01, max 10000). side: Your prediction — "heads" or "tails". referral_code: Optional referral code (earns 10% of house edge). Returns: dict with keys: result, won, payout_usdc, seed_hash, verify_url """ async with httpx.AsyncClient() as client: r = await client.post( f"{_BASE}/games/coin-flip", headers={"Authorization": f"Bearer {_KEY}"}, json={"wallet_id": wallet_id, "wager_usdc": wager_usdc, "side": side, "referral_code": referral_code}, timeout=10, ) r.raise_for_status() return r.json() @function_tool async def casino_dice_roll( wallet_id: str, wager_usdc: float, target: int, direction: Literal["over", "under"], referral_code: str = "", ) -> dict: """Roll a provably fair die (1–100). Args: wallet_id: Agent wallet ID. wager_usdc: Wager in USDC (min 0.01). target: Number to beat (1–99). direction: "over" or "under" the target. referral_code: Optional referral code (earns 10% of house edge). Returns: dict with keys: roll, won, multiplier, payout_usdc, seed_hash """ async with httpx.AsyncClient() as client: r = await client.post( f"{_BASE}/games/dice", headers={"Authorization": f"Bearer {_KEY}"}, json={"wallet_id": wallet_id, "wager_usdc": wager_usdc, "target": target, "direction": direction, "referral_code": referral_code}, timeout=10, ) r.raise_for_status() return r.json()
from agents import function_tool from typing import Literal import httpx, os # ── Trading — 275+ Hyperliquid perp markets, 20% referral on fees ─────────── @function_tool async def trading_get_price(asset: str) -> dict: """Get the current mid price for a perpetual futures market. Args: asset: Market symbol e.g. "BTC-PERP", "ETH-PERP", "SOL-PERP". Returns: dict with keys: asset, mid_price, bid, ask, funding_rate, open_interest """ async with httpx.AsyncClient() as client: r = await client.get( f"https://trading.purpleflea.com/api/v1/markets/{asset}", headers={"Authorization": f"Bearer {os.environ['PURPLE_FLEA_API_KEY']}"}, timeout=10, ) r.raise_for_status() return r.json() @function_tool async def trading_open_position( wallet_id: str, asset: str, side: Literal["long", "short"], size_usdc: float, leverage: int = 1, referral_code: str = "", ) -> dict: """Open a leveraged perpetual futures position. Args: wallet_id: Agent wallet to fund the position margin. asset: Market symbol e.g. "ETH-PERP". side: "long" to bet price rises, "short" to bet falls. size_usdc: Notional position size in USDC. leverage: Leverage multiplier 1–50 (default 1 = no leverage). referral_code: Earns 20% of trading fees generated by this position. Returns: dict with keys: position_id, asset, side, entry_price, size, margin, liquidation_price """ async with httpx.AsyncClient() as client: r = await client.post( "https://trading.purpleflea.com/api/v1/positions", headers={"Authorization": f"Bearer {os.environ['PURPLE_FLEA_API_KEY']}"}, json={"wallet_id": wallet_id, "asset": asset, "side": side, "size_usdc": size_usdc, "leverage": leverage, "referral_code": referral_code}, timeout=10, ) r.raise_for_status() return r.json() # ── Faucet — free $1 USDC for new agents (MCP: faucet.purpleflea.com/mcp) ─── @function_tool async def faucet_claim(agent_id: str, wallet_address: str) -> dict: """Claim $1 USDC from the Purple Flea agent faucet. One-time claim per agent identity. Use this first to fund a new agent. Also available as an MCP server at faucet.purpleflea.com/mcp. Args: agent_id: A unique identifier for this agent instance. wallet_address: EVM-compatible address to receive the USDC. Returns: dict with keys: claimed, amount_usdc, tx_hash, wallet_address, message """ async with httpx.AsyncClient() as client: r = await client.post( "https://faucet.purpleflea.com/api/v1/claim", headers={"Authorization": f"Bearer {os.environ['PURPLE_FLEA_API_KEY']}"}, json={"agent_id": agent_id, "wallet_address": wallet_address}, timeout=15, ) r.raise_for_status() return r.json() # ── Escrow — trustless payments, 1% fee, 15% referral (MCP: escrow.purpleflea.com/mcp) ── @function_tool async def escrow_create( payer_wallet_id: str, payee_wallet_id: str, amount_usdc: float, condition: str, referral_code: str = "", ) -> dict: """Create a trustless escrow between two AI agents. Funds are held until the condition is met. 1% fee on release. Also available as an MCP server at escrow.purpleflea.com/mcp. Args: payer_wallet_id: Wallet ID of the agent funding the escrow. payee_wallet_id: Wallet ID of the agent receiving funds on release. amount_usdc: Amount to hold in escrow (min $0.10). condition: Human-readable condition string for release. referral_code: Earns 15% of the 1% escrow fee. Returns: dict with keys: escrow_id, status, amount_usdc, fee_usdc, condition, expires_at """ async with httpx.AsyncClient() as client: r = await client.post( "https://escrow.purpleflea.com/api/v1/escrows", headers={"Authorization": f"Bearer {os.environ['PURPLE_FLEA_API_KEY']}"}, json={"payer_wallet_id": payer_wallet_id, "payee_wallet_id": payee_wallet_id, "amount_usdc": amount_usdc, "condition": condition, "referral_code": referral_code}, timeout=10, ) r.raise_for_status() return r.json() # ── Domains — crypto domain registration, 15% referral ────────────────────── @function_tool async def domains_register( name: str, tld: str, wallet_id: str, years: int = 1, referral_code: str = "", ) -> dict: """Register a domain name and pay with crypto — no KYC. Args: name: Domain name without TLD e.g. "myagent". tld: Top-level domain e.g. ".com", ".io", ".ai", ".xyz". wallet_id: Wallet to charge for the registration fee. years: Registration period in years (1–10). referral_code: Earns 15% of registration revenue. Returns: dict with keys: domain, status, expires_at, tx_hash, ns_records """ async with httpx.AsyncClient() as client: r = await client.post( "https://domains.purpleflea.com/api/v1/register", headers={"Authorization": f"Bearer {os.environ['PURPLE_FLEA_API_KEY']}"}, json={"name": name, "tld": tld, "wallet_id": wallet_id, "years": years, "referral_code": referral_code}, timeout=20, ) r.raise_for_status() return r.json()
Complete Example
This agent starts with zero funds, claims the faucet, creates a wallet,
places a leveraged trade, and plays casino games — all in a single
Runner.run() call. The agent decides the order of operations
from its tools and system prompt.
import asyncio import os from agents import Agent, Runner, RunConfig from purpleflea.tools.openai_agents import ( faucet_claim, wallet_create, wallet_get_balance, wallet_send, trading_get_price, trading_open_position, trading_close_position, trading_list_positions, casino_coin_flip, casino_dice_roll, casino_slots, domains_check, domains_register, escrow_create, escrow_release, ) os.environ["PURPLE_FLEA_API_KEY"] = os.getenv("PURPLE_FLEA_API_KEY", "sk_live_...") os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "sk-...") financial_agent = Agent( name="purple-flea-financial-agent", model="gpt-4o", instructions="""You are a fully autonomous DeFi agent powered by Purple Flea. You have access to the complete Purple Flea financial stack: • Faucet — claim $1 USDC to bootstrap a new agent • Wallet — create multi-chain wallets and check balances • Trading — open and close perpetual futures positions (275+ markets) • Casino — play provably fair games (coin flip, dice, slots) • Domains — register crypto-paid domain names, no KYC • Escrow — hold funds between two agents with trustless release When demonstrating your capabilities: 1. Claim the faucet to get seed capital 2. Create an Ethereum wallet for yourself 3. Check the ETH-PERP price, then open a small long position 4. Flip a coin for $0.10 as a casino demo 5. Report your balances and open positions at the end Always include your referral code (returned by wallet_create) in every subsequent tool call to earn passive income on activity.""", tools=[ faucet_claim, wallet_create, wallet_get_balance, wallet_send, trading_get_price, trading_open_position, trading_close_position, trading_list_positions, casino_coin_flip, casino_dice_roll, casino_slots, domains_check, domains_register, escrow_create, escrow_release, ], ) async def main(): config = RunConfig(max_turns=20) result = await Runner.run( financial_agent, input="Bootstrap yourself: claim faucet, create wallet, check ETH-PERP price, " "open a $0.50 long at 2x leverage, flip a coin for $0.10. " "Summarise everything at the end.", run_config=config, ) print("─" * 60) print(result.final_output) print("─" * 60) print(f"Tool calls made: {len(result.new_items)}") asyncio.run(main())
https://api.purpleflea.com/api/v1/register — it
returns a sk_live_... token and your first referral code in one call. New agents
can call faucet_claim() with no prior balance to receive $1 USDC as seed capital.
Referral Integration
Every revenue-generating tool accepts an optional
referral_code parameter. Pass your agent’s referral code
(returned by wallet_create) on every call and earn a percentage
of each transaction fee — automatically, on-chain, no withdrawal required.
from agents import Agent, Runner, RunContextWrapper, function_tool from dataclasses import dataclass import httpx, os, asyncio @dataclass class AgentContext: """Carries the agent's own referral code through the entire run.""" referral_code: str = "" wallet_id: str = "" @function_tool async def casino_coin_flip_ref( ctx: RunContextWrapper[AgentContext], wager_usdc: float, side: str, ) -> dict: """Flip a coin for a USDC wager. The referral code is injected automatically from context — you never need to specify it manually in the tool call. Args: wager_usdc: Amount to wager in USDC (0.01 to 10000). side: "heads" or "tails". """ # Referral code is automatically attached from typed context ref = ctx.context.referral_code wallet = ctx.context.wallet_id async with httpx.AsyncClient() as client: r = await client.post( "https://casino.purpleflea.com/api/v1/games/coin-flip", headers={"Authorization": f"Bearer {os.environ['PURPLE_FLEA_API_KEY']}"}, json={"wallet_id": wallet, "wager_usdc": wager_usdc, "side": side, "referral_code": ref}, # auto-injected ) r.raise_for_status() return r.json() referral_agent = Agent[AgentContext]( name="referral-aware-agent", instructions="You are a casino agent. Your referral code earns 10% on every game.", tools=[casino_coin_flip_ref], ) # Inject referral code and wallet at run time via typed context ctx = AgentContext(referral_code="REF-MYAGENT-7F2A", wallet_id="wlt_abc123") result = asyncio.get_event_loop().run_until_complete( Runner.run(referral_agent, "Flip a coin for $1 on heads", context=ctx) ) print(result.final_output)
Multi-Agent Pattern
The OpenAI Agents SDK’s handoff primitive lets an orchestrator delegate to specialist agents mid-conversation. Each specialist carries its own referral code — meaning the orchestrator earns passive income from every sub-agent action.
import asyncio, os from agents import Agent, Runner, handoff from purpleflea.tools.openai_agents import ( casino_coin_flip, casino_dice_roll, casino_slots, trading_get_price, trading_open_position, trading_close_position, trading_list_positions, wallet_create, wallet_get_balance, wallet_send, domains_check, domains_register, escrow_create, escrow_release, ) ORCH_REF = "REF-ORCH-0001" # orchestrator earns referral on all sub-agent activity # ── Specialist: Casino ─────────────────────────────────────────────────────── casino_agent = Agent( name="casino-specialist", model="gpt-4o-mini", instructions=f"""You specialise in provably fair casino games. Always include referral_code='{ORCH_REF}' in every tool call. Explain the game result clearly: what was rolled/flipped, did we win, how much.""", tools=[casino_coin_flip, casino_dice_roll, casino_slots], ) # ── Specialist: Trading ────────────────────────────────────────────────────── trading_agent = Agent( name="trading-specialist", model="gpt-4o", instructions=f"""You specialise in perpetual futures via Hyperliquid (275+ markets). Always include referral_code='{ORCH_REF}' in every tool call. Before opening a position always fetch the current price. Explain entry price, position size, leverage, and liquidation risk.""", tools=[trading_get_price, trading_open_position, trading_close_position, trading_list_positions], ) # ── Specialist: Wallet + Escrow ────────────────────────────────────────────── wallet_agent = Agent( name="wallet-specialist", model="gpt-4o-mini", instructions=f"""You specialise in wallet management and agent-to-agent escrow payments. Always include referral_code='{ORCH_REF}' in escrow tool calls. Summarise balances clearly: token, amount, USD value. Note all escrow IDs.""", tools=[wallet_create, wallet_get_balance, wallet_send, escrow_create, escrow_release], ) # ── Specialist: Domains ────────────────────────────────────────────────────── domains_agent = Agent( name="domains-specialist", model="gpt-4o-mini", instructions=f"""You specialise in registering domain names with crypto. Always include referral_code='{ORCH_REF}' in domain registration calls. Report registration status, expiry date, and nameserver records.""", tools=[domains_check, domains_register], ) # ── Orchestrator — routes tasks, earns referral commissions ───────────────── orchestrator = Agent( name="purple-flea-orchestrator", model="gpt-4o", instructions="""You are the Purple Flea master orchestrator. Route tasks to the right specialist via handoff: - Casino games → casino-specialist - Trading / futures → trading-specialist - Wallets / escrow → wallet-specialist - Domain registration → domains-specialist After each handoff summarise what the specialist did. You earn 10–20% referral commission on every specialist action.""", handoffs=[ handoff(casino_agent), handoff(trading_agent), handoff(wallet_agent), handoff(domains_agent), ], ) async def main(): result = await Runner.run( orchestrator, "Create a wallet, check BTC-PERP price, open a $10 long, " "then flip a coin for $1. Show me full results." ) print(result.final_output) asyncio.run(main())
The orchestrator’s referral code is baked into every specialist’s instructions. Every game, trade, or registration passively earns the orchestrator referral income — automatically.
Specialists use gpt-4o-mini for simple tool calls.
The orchestrator uses gpt-4o only for routing, keeping
total token costs low.
The Agents SDK passes full conversation history on every handoff. Specialists see what the orchestrator said — no data loss, no repeated instructions.
MCP Integration
The OpenAI Agents SDK has first-class support for MCP servers via
MCPServerStreamableHTTP. Purple Flea’s Faucet and Escrow
services expose /mcp endpoints — drop them in alongside your
function_tool tools and the SDK discovers and registers their
tools automatically.
https://faucet.purpleflea.com/mcp — StreamableHTTP transporthttps://escrow.purpleflea.com/mcp — StreamableHTTP transporttools/list call. The OpenAI Agents SDK fetches these on startup
and registers them alongside your function_tool tools
automatically — no manual schema writing required.
import asyncio, os from agents import Agent, Runner from agents.mcp import MCPServerStreamableHTTP from purpleflea.tools.openai_agents import ( wallet_create, wallet_get_balance, trading_get_price, trading_open_position, casino_coin_flip, ) PF_KEY = os.environ["PURPLE_FLEA_API_KEY"] # ── Connect Faucet + Escrow as StreamableHTTP MCP servers ─────────────────── faucet_mcp = MCPServerStreamableHTTP( url="https://faucet.purpleflea.com/mcp", headers={"Authorization": f"Bearer {PF_KEY}"}, # Tools auto-discovered: claim_faucet, get_faucet_status ) escrow_mcp = MCPServerStreamableHTTP( url="https://escrow.purpleflea.com/mcp", headers={"Authorization": f"Bearer {PF_KEY}"}, # Tools auto-discovered: create_escrow, release_escrow, # dispute_escrow, get_escrow_status ) # ── Mix function_tool + MCP server tools in a single Agent ────────────────── mcp_agent = Agent( name="mcp-financial-agent", model="gpt-4o", instructions="""You have both function tools (wallet, trading, casino) and MCP-powered tools (faucet, escrow). Use claim_faucet from MCP to get seed capital. Use create_escrow and release_escrow from MCP for payments. Use the function tools for wallet, trading, and casino operations.""", tools=[ wallet_create, wallet_get_balance, trading_get_price, trading_open_position, casino_coin_flip, ], mcp_servers=[faucet_mcp, escrow_mcp], # MCP tools auto-discovered ) async def main(): # SDK initialises MCP connections and fetches tool lists async with faucet_mcp, escrow_mcp: result = await Runner.run( mcp_agent, "1. Claim the faucet for wallet 0xABCD...1234. " "2. Create an escrow of $0.50 from wlt_aaa to wlt_bbb " "with condition 'task completed'. " "3. Release the escrow once set up." ) print(result.final_output) asyncio.run(main())
Both Purple Flea MCP servers use the StreamableHTTP transport — no
stdio subprocess required. Connect from any cloud environment,
container, or serverless function over plain HTTPS.
On startup the SDK calls tools/list on each MCP server. Schemas,
descriptions, and parameter types are fetched automatically — your agent
always has the latest tool definitions without code changes.
All Services
Every Purple Flea service is available as a pre-built tool group. Import only what your agent needs:
Setup Guide
Register at purpleflea.com/quick-start or
POST to https://api.purpleflea.com/api/v1/register.
The response includes your sk_live_... key and first referral code.
Run pip install openai-agents purpleflea.
Python 3.10+ is required. Set
PURPLE_FLEA_API_KEY and OPENAI_API_KEY as environment variables.
Import the function_tool decorated functions from
purpleflea.tools.openai_agents
and pass them to Agent(tools=[...]).
Add mcp_servers=[...] for faucet and escrow if needed.
Include your agent’s referral code (from
wallet_create) in the agent’s
instructions so it passes it on every relevant tool call.
Call await Runner.run(agent, input_string).
The SDK handles the multi-turn loop, tool execution, streaming,
and retry logic automatically.
# Purple Flea PURPLE_FLEA_API_KEY=sk_live_yourkey # OpenAI OPENAI_API_KEY=sk-... # Your referral code (from wallet_create or /api/v1/register) PURPLE_FLEA_REFERRAL=REF-YOURAGENT-0001
import httpx resp = httpx.post( "https://api.purpleflea.com/api/v1/register", json={"agent_name": "my-trading-bot"}, ) data = resp.json() print(f"API key: {data['api_key']}") print(f"Referral code: {data['referral_code']}") # → Save api_key to PURPLE_FLEA_API_KEY # → Save referral_code to PURPLE_FLEA_REFERRAL # → Include referral_code in every tool call to earn fees
Comparison
Purple Flea is the only provider with a complete financial stack designed specifically for AI agents, including a free faucet, trustless escrow, and first-party MCP servers.
| Feature | Purple Flea | Coinbase CDP | Moralis | DIY / Raw RPC |
|---|---|---|---|---|
| OpenAI Agents SDK (first-party) | Yes | Community | No | Manual |
| Provably fair casino | Yes | No | No | No |
| Agent faucet (free funds) | $1 USDC | No | No | No |
| Trustless agent-to-agent escrow | Yes | No | No | No |
| 275+ perpetual futures markets | Yes | No | No | Manual |
| MCP server (StreamableHTTP) | Yes | No | No | No |
| Multi-chain HD wallets | Yes | Yes | Read-only | Manual |
| Domain registration with crypto | Yes | No | No | No |
| Referral programme for agents | 10–20% | No | No | No |
| Free tier | Yes | Yes | Yes | Yes |
Get your API key in 30 seconds. No credit card required on the free tier.
The faucet gives every new agent $1 USDC to start immediately.