OpenAI Function Calling

Purple Flea for
OpenAI Assistants

The OpenAI Assistants API with function calling combined with Purple Flea financial APIs creates agents that can transact on-chain, trade perpetual futures, play provably fair casino games, and register domains — all from inside a managed thread. No extra SDK required: define the JSON schemas once and call the Purple Flea REST API directly from your tool execution loop.


JSON schemas for every
Purple Flea operation.

The OpenAI Assistants API requires each tool to be defined as a JSON object with a name, description, and parameters schema. Copy the schemas below directly into your assistant creation call. No SDK dependency — just standard OpenAI JSON Schema format, which GPT-4o and GPT-4o-mini understand natively.

tool_schemas.json — wallet tools
// wallet_get_balance { "name": "wallet_get_balance", "description": "Get the crypto balance of the agent's wallet on a specific chain", "parameters": { "type": "object", "properties": { "chain": { "type": "string", "enum": ["eth", "btc", "sol", "tron", "bnb", "matic"], "description": "The blockchain network to query" } }, "required": ["chain"] } }, // wallet_send { "name": "wallet_send", "description": "Send crypto from the agent's wallet to any address", "parameters": { "type": "object", "properties": { "chain": { "type": "string", "enum": ["eth", "btc", "sol", "tron", "bnb", "matic"] }, "to": { "type": "string", "description": "Recipient wallet address" }, "amount": { "type": "number", "description": "Amount of native token to send" }, "token": { "type": "string", "description": "Token symbol, e.g. 'USDC'. Omit for native token." } }, "required": ["chain", "to", "amount"] } }, // wallet_swap { "name": "wallet_swap", "description": "Swap tokens on the same chain or across chains via best-rate DEX routing", "parameters": { "type": "object", "properties": { "from_token": { "type": "string" }, "to_token": { "type": "string" }, "amount": { "type": "number" }, "chain": { "type": "string", "enum": ["eth", "bnb", "matic", "sol"] } }, "required": ["from_token", "to_token", "amount", "chain"] } }
tool_schemas.json — trading, casino, and domains tools
// trading_open_position { "name": "trading_open_position", "description": "Open a long or short perpetual futures position on any of 275 markets", "parameters": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Market symbol, e.g. 'BTC-PERP'" }, "side": { "type": "string", "enum": ["long", "short"] }, "size_usd": { "type": "number", "description": "Position size in USD notional" }, "leverage": { "type": "integer", "minimum": 1, "maximum": 50 } }, "required": ["symbol", "side", "size_usd", "leverage"] } }, // trading_get_price { "name": "trading_get_price", "description": "Get current mark price for a perpetual futures market", "parameters": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Market symbol, e.g. 'ETH-PERP'" } }, "required": ["symbol"] } }, // casino_flip_coin { "name": "casino_flip_coin", "description": "Place a provably fair coin flip bet. Returns outcome and updated balance.", "parameters": { "type": "object", "properties": { "amount_usd": { "type": "number", "description": "Bet size in USD" }, "choice": { "type": "string", "enum": ["heads", "tails"] } }, "required": ["amount_usd", "choice"] } }, // domains_search { "name": "domains_search", "description": "Check availability and registration price for a domain name", "parameters": { "type": "object", "properties": { "domain": { "type": "string", "description": "Domain name to search, e.g. 'myagent.com'" } }, "required": ["domain"] } }, // domains_register { "name": "domains_register", "description": "Register a domain and pay with crypto from the agent's wallet", "parameters": { "type": "object", "properties": { "domain": { "type": "string" }, "years": { "type": "integer", "minimum": 1, "maximum": 10 } }, "required": ["domain", "years"] } }

The run loop: poll, extract,
execute, submit.

When a run reaches requires_action status, your code must extract the tool calls, dispatch each one to the Purple Flea REST API, and submit the outputs back to OpenAI before the run times out. The pattern below handles this reliably for any number of parallel tool calls.

run_loop.py — poll → extract → execute → submit
import time, json, requests from openai import OpenAI client = OpenAI() PF_BASE = "https://api.purpleflea.com/v1" PF_HEADERS = {"Authorization": "Bearer pf_sk_..."} def call_purpleflea(name: str, args: dict) -> str: """Dispatch a tool call to the Purple Flea REST API.""" routes = { "wallet_get_balance": ("GET", "/wallet/balance"), "wallet_send": ("POST", "/wallet/send"), "wallet_swap": ("POST", "/wallet/swap"), "trading_open_position": ("POST", "/trading/positions"), "trading_get_price": ("GET", "/trading/price"), "casino_flip_coin": ("POST", "/casino/coinflip"), "domains_search": ("GET", "/domains/search"), "domains_register": ("POST", "/domains/register"), } method, path = routes[name] url = PF_BASE + path resp = (requests.get(url, params=args, headers=PF_HEADERS) if method == "GET" else requests.post(url, json=args, headers=PF_HEADERS)) return json.dumps(resp.json()) def run_until_done(thread_id: str, run_id: str) -> str: """Poll a run, handle tool calls, and return the final assistant message.""" while True: run = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run_id) if run.status == "completed": msgs = client.beta.threads.messages.list(thread_id=thread_id) return msgs.data[0].content[0].text.value if run.status == "requires_action": tool_calls = run.required_action.submit_tool_outputs.tool_calls outputs = [] for tc in tool_calls: result = call_purpleflea( tc.function.name, json.loads(tc.function.arguments) ) outputs.append({"tool_call_id": tc.id, "output": result}) client.beta.threads.runs.submit_tool_outputs( thread_id=thread_id, run_id=run_id, tool_outputs=outputs ) elif run.status in ("failed", "cancelled", "expired"): raise RuntimeError(f"Run ended with status: {run.status}") time.sleep(0.5)

A full agent in under
60 lines of Python.

This self-contained script creates an OpenAI Assistant with all Purple Flea tools attached, starts a thread, runs it with a financial task, and handles the tool call loop automatically. Drop in your API keys and run it directly.

agent.py — complete working example
import time, json, requests, os from openai import OpenAI from purpleflea_schemas import ALL_TOOL_SCHEMAS # or paste schemas inline client = OpenAI(api_key=os.environ["OPENAI_API_KEY"]) PF_BASE = "https://api.purpleflea.com/v1" PF_KEY = os.environ["PURPLEFLEA_API_KEY"] # 1. Create an assistant with all Purple Flea tools assistant = client.beta.assistants.create( name="PurpleFleasFinancialAgent", model="gpt-4o", instructions="""You are an autonomous financial agent. You have a crypto wallet, access to 275 perpetual futures markets, a provably fair casino, and domain registration. Always verify balances before transacting. Report exact figures — never round.""", tools=[{"type": "function", "function": schema} for schema in ALL_TOOL_SCHEMAS], ) # 2. Create a thread and add a user message thread = client.beta.threads.create() client.beta.threads.messages.create( thread_id=thread.id, role="user", content="Check my ETH balance. If above 0.05 ETH, flip a coin for 0.01 ETH.", ) # 3. Run the assistant run = client.beta.threads.runs.create( thread_id=thread.id, assistant_id=assistant.id, ) # 4. Tool call dispatch helper def dispatch(name, args): routes = { "wallet_get_balance": ("GET", "/wallet/balance"), "casino_flip_coin": ("POST", "/casino/coinflip"), "trading_open_position": ("POST", "/trading/positions"), "domains_search": ("GET", "/domains/search"), "domains_register": ("POST", "/domains/register"), } method, path = routes.get(name, ("POST", f"/{name.replace('_', '/')}")) hdrs = {"Authorization": f"Bearer {PF_KEY}"} r = (requests.get(PF_BASE + path, params=args, headers=hdrs) if method == "GET" else requests.post(PF_BASE + path, json=args, headers=hdrs)) return json.dumps(r.json()) # 5. Poll until done, handling tool calls while True: run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id) if run.status == "completed": break if run.status == "requires_action": tcs = run.required_action.submit_tool_outputs.tool_calls client.beta.threads.runs.submit_tool_outputs( thread_id=thread.id, run_id=run.id, tool_outputs=[{ "tool_call_id": tc.id, "output": dispatch(tc.function.name, json.loads(tc.function.arguments)) } for tc in tcs] ) elif run.status in ("failed", "expired", "cancelled"): raise RuntimeError(run.last_error) time.sleep(0.5) # 6. Print the final response msgs = client.beta.threads.messages.list(thread_id=thread.id) print(msgs.data[0].content[0].text.value)

Also works with the
Responses API.

OpenAI's Responses API (released March 2025) is a stateless alternative to Assistants that handles conversation state server-side without requiring thread management. Purple Flea tool schemas work identically — pass the same JSON objects to the tools array and handle function_call outputs the same way, without polling.

responses_api.py — Responses API with Purple Flea tools
from openai import OpenAI from purpleflea_schemas import ALL_TOOL_SCHEMAS import json, requests, os client = OpenAI() PF_KEY = os.environ["PURPLEFLEA_API_KEY"] response = client.responses.create( model="gpt-4o", input="What is the current BTC-PERP mark price?", tools=[{"type": "function", "function": s} for s in ALL_TOOL_SCHEMAS], ) # Handle tool calls synchronously — no polling required while response.status == "requires_action": tool_results = [] for tc in response.required_action.submit_tool_outputs.tool_calls: args = json.loads(tc.function.arguments) result = requests.get( f"https://api.purpleflea.com/v1/trading/price", params=args, headers={"Authorization": f"Bearer {PF_KEY}"}, ).json() tool_results.append({"tool_call_id": tc.id, "output": json.dumps(result)}) response = client.responses.submit_tool_outputs( response_id=response.id, tool_outputs=tool_results ) print(response.output_text)

Every function schema.
Every API.

All schemas follow the OpenAI JSON Schema spec. They are tested against gpt-4o, gpt-4o-mini, and o1. No additional SDK or wrapper layer is required — define the schemas and handle function calls in your own run loop.

Function Name API Description
wallet_get_balanceWalletGet token balances across ETH, BTC, SOL, TRON, BNB, MATIC
wallet_get_addressWalletGet agent's wallet address for any supported chain
wallet_sendWalletSend native tokens or ERC-20s to any address
wallet_swapWalletSame-chain and cross-chain token swaps via best-rate DEX routing
trading_get_priceTradingFetch current mark price for any of 275 perpetual markets
trading_open_positionTradingOpen long or short perpetual position with configurable leverage (1x–50x)
trading_close_positionTradingClose an open perpetual position by ID
trading_list_positionsTradingList all open positions with unrealized PnL
casino_flip_coinCasinoProvably fair coin flip with on-chain seed verification
casino_roll_diceCasinoRoll dice with custom target and payout multipliers
casino_rouletteCasinoEuropean roulette with full bet type support
casino_crashCasinoCrash game with auto-cashout at configurable multiplier
domains_searchDomainsCheck availability and price for any domain or TLD
domains_registerDomainsRegister domains and pay with crypto from agent wallet
domains_listDomainsList all domains owned by the agent
faucet_claimFaucetClaim free $1 USDC for a new agent wallet — zero cost bootstrapping
faucet_statsFaucetGet faucet stats: total claims, USDC distributed
escrow_createEscrowCreate a trustless USDC escrow contract with a counterparty agent
escrow_completeEscrowMark an escrow contract as completed (counterparty action)
escrow_releaseEscrowRelease escrowed funds to counterparty (1% fee deducted)
escrow_statusEscrowGet status of any escrow contract by ID

No SDK. Just REST and
JSON schemas.

🤖

gpt-4o, gpt-4o-mini, o1

Function schemas are tested against all current OpenAI models including o1 series. Parallel tool calls are supported — the run loop above handles multiple simultaneous Purple Flea calls in a single round trip.

📦

No SDK dependency

Define the JSON schemas, call Purple Flea's REST API from your tool execution handler, and submit outputs back to OpenAI. No additional package installs or wrapper layer required beyond the official OpenAI SDK.

Async compatible

The run loop pattern works identically with AsyncOpenAI and aiohttp for Purple Flea REST calls. All API endpoints support concurrent requests from multiple threads.

🔑

Non-custodial wallets

Each assistant gets a unique HD wallet derived from a BIP-39 mnemonic. Private keys are encrypted at rest. Your assistant owns its keys — no custodian holds funds on its behalf.

🛡️

Provably fair casino

Casino schemas include server seed hash and client seed fields. Every outcome is cryptographically verifiable. Your assistant can audit its own bet history and verify fairness on-chain without trusting the server.

💸

Referral commissions

Every Purple Flea API call your assistant makes earns you a commission — 20% on trading fees, 10% on wallet swaps, 10% on casino, 15% on domains. Commissions accumulate in your wallet automatically.


From zero to financial agent
in four steps.

01

Register your agent

Sign up at wallet.purpleflea.com or call POST /agent/register. You receive a Purple Flea API key and a BIP-39 mnemonic for your HD wallet — one address per supported chain, derived deterministically.

02

Create your OpenAI Assistant

Call client.beta.assistants.create with the Purple Flea tool schemas in the tools array. Choose any OpenAI model that supports function calling — gpt-4o, gpt-4o-mini, or o1.

03

Handle tool calls in your run loop

Poll the run for requires_action status. When reached, extract tool calls, dispatch each to the Purple Flea REST API using your agent's key, and submit all outputs back before the run times out (10-minute window).

04

Deploy and earn commissions

Run your assistant against any task that requires financial operations. Every Purple Flea API call earns you a referral commission — 20% on trading fees alone. Commissions stack across all six products and accumulate in your wallet automatically.


More integrations.

Give your OpenAI Assistant
a financial superpower.

Free to start. No KYC. Earn commissions on every call your assistant makes.