OpenAI Swarm Integration

Give your OpenAI Swarm agents
economic superpowers.

Purple Flea ships plain Python functions that drop straight into any Swarm agent. Casino, trading, wallet, and domain tools — each one a function your orchestrator can hand off to a specialised worker agent.


Lightweight
multi-agent orchestration.

OpenAI Swarm is a lightweight, experimental framework for building multi-agent systems in Python. Rather than a monolithic agent, Swarm lets you define a network of specialised agents — each owning a narrow set of tools — and an orchestrator that routes tasks between them via handoffs.

Agents expose capabilities as plain Python functions. The orchestrator calls those functions or transfers control entirely to a specialised agent by returning an Agent object from a function. This makes Swarm extremely composable and easy to test.

Purple Flea functions are standard Python callables — no special adapters required. Drop them into any Swarm agent's functions list and they are immediately available to that agent and any orchestrator that controls it.

Multi-agent topology

Orchestrator Agent
Casino Agent
Trading Agent
Wallet Agent
Each agent carries the orchestrator's referral_code — commissions flow back automatically.

One install.
Works via REST with any framework.

The crewai-purpleflea package ships standalone REST helpers that work with Swarm, CrewAI, or any other Python agent framework. Install once, use everywhere.

$ pip install crewai-purpleflea
setup.py
import os from swarm import Swarm, Agent from purpleflea import PurpleFleatClient # Configure once — shared across all agents pf = PurpleFleatClient( api_key=os.environ["PURPLEFLEA_API_KEY"], referral_code=os.environ["PURPLEFLEA_REFERRAL_CODE"], ) client = Swarm()

Casino function
for a Swarm agent.

Any plain Python function becomes a Swarm tool. The function calls the Purple Flea casino API and returns a human-readable string the LLM can reason about.

casino_agent.py
import requests def casino_flip(amount: float, side: str) -> str: """Flip a provably fair coin on Purple Flea Casino. Args: amount: Bet size in USDC (minimum 0.01). side: Which side to bet on — 'heads' or 'tails'. Returns: Result string describing outcome and new balance. """ resp = requests.post( "https://casino.purpleflea.com/api/v1/flip", headers={"Authorization": f"Bearer {pf.api_key}"}, json={ "amount": amount, "side": side, "referral_code": pf.referral_code, }, timeout=10, ) data = resp.json() outcome = data["outcome"] # "heads" | "tails" payout = data["payout"] # 0.0 (loss) or amount * 1.98 (win) balance = data["new_balance"] # updated USDC balance won = outcome == side return ( f"Flipped {'heads' if outcome == 'heads' else 'tails'}. " f"You {'won' if won else 'lost'} {payout if won else amount} USDC. " f"Balance: {balance} USDC." ) casino_agent = Agent( name="Casino Agent", instructions="""You are a casino agent with a gambling budget. Place bets conservatively — never wager more than 5% of balance per flip. Always report outcomes clearly.""", functions=[casino_flip], )

Trading functions
for a Swarm agent.

Two functions give a Swarm trading agent the ability to open and close perpetual futures positions across 275 markets on Hyperliquid.

trading_agent.py
def trading_open( market: str, side: str, size_usd: float, leverage: int = 5, ) -> str: """Open a perpetual futures position. Args: market: Ticker symbol, e.g. 'BTC-PERP', 'ETH-PERP', 'SOL-PERP'. side: 'long' or 'short'. size_usd: Notional position size in USD. leverage: Leverage multiplier from 1 to 50 (default 5). Returns: Order ID, entry price, and liquidation price. """ resp = requests.post( "https://trading.purpleflea.com/api/v1/positions/open", headers={"Authorization": f"Bearer {pf.api_key}"}, json={ "market": market, "side": side, "size_usd": size_usd, "leverage": leverage, "referral_code": pf.referral_code, }, timeout=10, ) d = resp.json() return ( f"Opened {side} on {market}. Order ID: {d['order_id']}. " f"Entry: ${d['entry_price']:,.2f}. Liq: ${d['liquidation_price']:,.2f}." ) def trading_close(order_id: str) -> str: """Close an open perpetual futures position by order ID. Args: order_id: The order ID returned when the position was opened. Returns: Realised PnL and closing price. """ resp = requests.post( f"https://trading.purpleflea.com/api/v1/positions/{order_id}/close", headers={"Authorization": f"Bearer {pf.api_key}"}, timeout=10, ) d = resp.json() pnl_sign = "+" if d["realised_pnl"] >= 0 else "" return ( f"Closed {order_id} at ${d['close_price']:,.2f}. " f"PnL: {pnl_sign}{d['realised_pnl']:.4f} USDC." ) trading_agent = Agent( name="Trading Agent", instructions="""You manage perpetual futures positions. Open positions only when you have a clear directional thesis. Close positions if PnL drops below -10% of notional.""", functions=[trading_open, trading_close], )

Orchestrator spawns
specialised financial agents.

A complete Swarm multi-agent system. The orchestrator analyses incoming requests and hands off to casino, trading, or wallet agents — each registered with the orchestrator's referral code so commissions accumulate centrally.

multi_agent_system.py
from swarm import Swarm, Agent import os, requests REFERRAL = os.environ["PURPLEFLEA_REFERRAL_CODE"] API_KEY = os.environ["PURPLEFLEA_API_KEY"] HEADERS = {"Authorization": f"Bearer {API_KEY}"} # ── Worker: Casino ──────────────────────────────────────────────────────── def casino_flip(amount: float, side: str) -> str: """Flip a provably fair coin. side: 'heads' | 'tails'.""" d = requests.post("https://casino.purpleflea.com/api/v1/flip", headers=HEADERS, json={"amount": amount, "side": side, "referral_code": REFERRAL}, timeout=10).json() won = d["outcome"] == side return f"{'Won' if won else 'Lost'} {amount} USDC. Balance: {d['new_balance']} USDC." def casino_dice(amount: float, target: int, over: bool = True) -> str: """Roll a dice. Win if result is over/under target (1-99).""" d = requests.post("https://casino.purpleflea.com/api/v1/dice", headers=HEADERS, json={"amount": amount, "target": target, "over": over, "referral_code": REFERRAL}, timeout=10).json() return f"Rolled {d['result']}. {'Won' if d['won'] else 'Lost'}. Balance: {d['new_balance']} USDC." casino_agent = Agent(name="Casino Agent", functions=[casino_flip, casino_dice], instructions="You handle casino games. Bet conservatively, max 5% bankroll per game.") # ── Worker: Trading ─────────────────────────────────────────────────────── def trading_open(market: str, side: str, size_usd: float, leverage: int = 5) -> str: """Open a perp futures position. market e.g. 'BTC-PERP'.""" d = requests.post("https://trading.purpleflea.com/api/v1/positions/open", headers=HEADERS, json={"market": market, "side": side, "size_usd": size_usd, "leverage": leverage, "referral_code": REFERRAL}, timeout=10).json() return f"Opened {side} {market}. ID: {d['order_id']}. Entry: ${d['entry_price']:,.2f}." def trading_close(order_id: str) -> str: """Close an open position by order ID.""" d = requests.post(f"https://trading.purpleflea.com/api/v1/positions/{order_id}/close", headers=HEADERS, timeout=10).json() return f"Closed {order_id}. PnL: {d['realised_pnl']:+.4f} USDC." trading_agent = Agent(name="Trading Agent", functions=[trading_open, trading_close], instructions="You manage perp positions. Max 20% of balance per position.") # ── Worker: Wallet ──────────────────────────────────────────────────────── def wallet_create(chain: str = "ethereum") -> str: """Create a new sub-wallet on the given chain.""" d = requests.post("https://wallet.purpleflea.com/api/v1/wallets", headers=HEADERS, json={"chain": chain, "referral_code": REFERRAL}, timeout=10).json() return f"Created {chain} wallet: {d['address']}" def wallet_swap(from_token: str, to_token: str, amount: float) -> str: """Swap tokens at best available rate.""" d = requests.post("https://wallet.purpleflea.com/api/v1/swap", headers=HEADERS, json={"from_token": from_token, "to_token": to_token, "amount": amount, "referral_code": REFERRAL}, timeout=15).json() return f"Swapped {amount} {from_token} → {d['received']} {to_token}. Tx: {d['tx_hash']}" wallet_agent = Agent(name="Wallet Agent", functions=[wallet_create, wallet_swap], instructions="You manage crypto wallets and token swaps. Confirm all swaps before executing.") # ── Orchestrator ────────────────────────────────────────────────────────── def transfer_to_casino(): return casino_agent def transfer_to_trading(): return trading_agent def transfer_to_wallet(): return wallet_agent orchestrator = Agent( name="Orchestrator", instructions="""You are the financial orchestrator. Analyse each request and route it to the correct specialist agent: - Casino games → transfer_to_casino - Trading / futures → transfer_to_trading - Wallet / swap → transfer_to_wallet Each specialist carries our referral code — commissions flow back automatically.""", functions=[transfer_to_casino, transfer_to_trading, transfer_to_wallet], ) # ── Run ─────────────────────────────────────────────────────────────────── client = Swarm() response = client.run( agent=orchestrator, messages=[{"role": "user", "content": "Flip a coin for 0.5 USDC on heads, then open a long on ETH-PERP"}], ) print(response.messages[-1]["content"])

Orchestrators earn on
every agent action.

Swarm handoffs preserve context across agent boundaries. By embedding your referral code in the shared client object, every Purple Flea API call — regardless of which worker agent makes it — credits your account.

referral_pattern.py
# Pattern 1: Shared module-level referral code # All agent functions in the module close over REFERRAL REFERRAL = os.environ["PURPLEFLEA_REFERRAL_CODE"] def any_api_call(...): requests.post(url, json={..., "referral_code": REFERRAL}) # Pattern 2: Pass referral through Swarm context_variables def casino_flip(context_variables: dict, amount: float, side: str): referral = context_variables.get("referral_code", "") requests.post(url, json={"amount": amount, "side": side, "referral_code": referral}) # Pass it at runtime: client.run( agent=orchestrator, messages=[...], context_variables={"referral_code": "my_code_123"}, )

20% trading fee commission

Every position your Swarm trading agent opens or closes earns 20% of the exchange fee back to your referral account.

10% casino house edge share

Casino bets placed by your agents generate 10% commission on house edge. Compounds quickly across many agents.

10% swap & 15% domain fees

Wallet swaps and domain registrations made by any of your worker agents also earn referral income automatically.


Every available function.

These are the standard Purple Flea Swarm functions. Each is a plain Python callable — add any subset to any agent's functions list.

Function API Description
casino_flip(amount, side)CasinoProvably fair coin flip — 'heads' or 'tails', 1.98x payout
casino_dice(amount, target, over)CasinoRoll dice against a target from 1–99, configurable payout multiplier
trading_open(market, side, size_usd, leverage)TradingOpen a long or short perpetual futures position, 1x–50x leverage
trading_close(order_id)TradingClose an open position and realise PnL
wallet_create(chain)WalletCreate a new HD wallet on ETH, BTC, SOL, TRON, BNB, or MATIC
wallet_swap(from_token, to_token, amount)WalletCross-chain or same-chain token swap via best-rate DEX routing
domain_search(query)DomainsCheck availability and price for any domain name or TLD
domain_register(name, years)DomainsRegister a domain and pay with USDC from the agent wallet

Up and running
in four steps.

01

Register your agent

Sign up at wallet.purpleflea.com. You receive an API key, a referral code, and a BIP-39 mnemonic for your agent's HD wallet. Store all three in environment variables.

02

Install the package

Run pip install openai-swarm crewai-purpleflea. The Purple Flea package provides pre-written function implementations; Swarm provides the orchestration runtime.

03

Define your agents

Create worker agents with Purple Flea functions in their functions list. Create an orchestrator with handoff functions that return worker agents. Pass your referral code via the shared client or context_variables.

04

Run and earn

Call client.run(agent=orchestrator, messages=[...]). Every API call your Swarm makes earns referral commissions automatically. Check earnings at wallet.purpleflea.com.


Why Purple Flea
for Swarm.

🔗

Plain Python functions

No wrappers, no base classes. Swarm uses plain callables — Purple Flea functions are exactly that. Paste them into any agent without modification.

🔁

Handoff-safe referral codes

Referral codes survive agent handoffs when stored as module-level constants or passed through Swarm's context_variables. Commissions never get lost.

Provably fair randomness

Casino functions include server seed hashes and client seed mixing. Every outcome is cryptographically verifiable — your agent can audit its own bets on-chain.

📊

275 perpetual markets

Trading functions cover all Hyperliquid perpetual futures markets. Up to 50x leverage, no KYC, instant settlement — accessed via a simple function call.

🔗

Non-custodial HD wallets

Each agent gets a unique wallet derived from a BIP-39 mnemonic. Six chains supported. Your agent controls its own keys — Purple Flea never holds funds.

💰

Passive commission income

Orchestrators earn 10–20% commissions on every API call any of their worker agents makes. The larger your Swarm, the more you earn.


More integrations.

Give your Swarm
a financial backbone.

Free to start. No KYC. Earn commissions on every call your agents make.