OpenAI Agents SDK Integration

Purple Flea for
OpenAI Agents SDK

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.

6
Financial APIs
275+
Perp Markets
20%
Max Referral
$1
Free Faucet

What is the OpenAI Agents SDK?

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.

🏭

function_tool

One decorator turns any typed Python function into a schema-validated tool the model can call.

Handoffs

Route to specialist sub-agents mid-conversation. Referral codes travel in typed context.

🔒

Guardrails

Input and output guardrails run in parallel — enforce bet-size limits without blocking the model.

🔗

MCP Support

Connect to faucet.purpleflea.com/mcp and escrow.purpleflea.com/mcp as StreamableHTTP MCP servers.


One command, full financial stack

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().

$ pip install openai-agents purpleflea
requirements.txt
# 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
quickstart.py
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())

All six Purple Flea tools

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.

Available tools — 16 functions across 6 services
Function Service Description
casino_coin_flipCasinoProvably fair coin flip — heads or tails for a USDC wager up to $10,000
casino_dice_rollCasinoRoll dice with configurable target (1–99) and over/under direction
casino_slotsCasinoThree-reel slot machine with seed-verifiable randomness
trading_get_priceTradingCurrent mid price for any of 275+ perpetual futures markets via Hyperliquid
trading_open_positionTradingOpen a long or short perpetual position with configurable leverage up to 50x
trading_close_positionTradingClose an open position by ID and settle PnL to the agent wallet
trading_list_positionsTradingList all open perpetual positions with unrealised PnL
wallet_createWalletCreate a non-custodial HD wallet on Ethereum, Solana, Bitcoin, or Tron
wallet_get_balanceWalletGet token balances across all supported chains for a wallet address
wallet_sendWalletSend tokens from an agent wallet to any on-chain address
domains_checkDomainsCheck availability of a domain name across supported TLDs
domains_registerDomainsRegister a domain name with crypto payment — no KYC required
faucet_claimFaucetClaim $1 USDC for a new agent — one claim per agent identity
escrow_createEscrowCreate a trustless escrow between two agent wallets (1% fee)
escrow_releaseEscrowRelease escrowed funds to recipient after the condition is verified
escrow_disputeEscrowOpen a dispute on an escrow — triggers the arbitration protocol
purpleflea/tools/casino.py
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()
purpleflea/tools/trading.py + faucet.py + escrow.py + domains.py
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()

A full working financial agent

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.

agent_example.py
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())
Registration & authentication: All Purple Flea APIs authenticate with a single Bearer token. Obtain yours at purpleflea.com/quick-start. The registration endpoint is 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.

Your agents earn while they run

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.

10%
Casino
On house edge from every game played via your referral code
20%
Trading
On trading fees from every position opened via your referral code
10%
Wallet
On swap fees from wallets registered via your referral code
15%
Domains
On registration revenue from domains bought via your referral code
15%
Escrow
On the 1% escrow fee from transactions via your referral code
$0
Faucet
Free — no fee. Bootstrap any new agent for free
referral_agent.py — injecting referral code via typed context
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)

Orchestrators with specialist sub-agents

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.

multi_agent.py
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())

Orchestrator earns on every handoff

The orchestrator’s referral code is baked into every specialist’s instructions. Every game, trade, or registration passively earns the orchestrator referral income — automatically.

🏭

Cheaper models for specialists

Specialists use gpt-4o-mini for simple tool calls. The orchestrator uses gpt-4o only for routing, keeping total token costs low.

📝

Context preserved across handoffs

The Agents SDK passes full conversation history on every handoff. Specialists see what the orchestrator said — no data loss, no repeated instructions.


Faucet & Escrow as MCP servers

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.

MCP endpoints:
  • Faucet MCP: https://faucet.purpleflea.com/mcp — StreamableHTTP transport
  • Escrow MCP: https://escrow.purpleflea.com/mcp — StreamableHTTP transport

Both servers expose their full tool catalogues via the MCP tools/list call. The OpenAI Agents SDK fetches these on startup and registers them alongside your function_tool tools automatically — no manual schema writing required.
mcp_agent.py
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())
🔗

StreamableHTTP transport

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.

Tool auto-discovery

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.


Six services, one API key

Every Purple Flea service is available as a pre-built tool group. Import only what your agent needs:

purpleflea.tools.casino
Casino API
casino.purpleflea.com • 10% referral
  • casino_coin_flip
  • casino_dice_roll
  • casino_slots
  • casino_blackjack
purpleflea.tools.trading
Trading API
trading.purpleflea.com • 20% referral
  • trading_get_price
  • trading_open_position
  • trading_close_position
  • trading_list_positions
purpleflea.tools.wallet
Wallet API
wallet.purpleflea.com • 10% referral on swaps
  • wallet_create
  • wallet_get_balance
  • wallet_send
  • wallet_swap
purpleflea.tools.domains
Domains API
domains.purpleflea.com • 15% referral
  • domains_check
  • domains_register
  • domains_list_tlds
  • domains_transfer
purpleflea.tools.faucet
Agent Faucet
faucet.purpleflea.com • MCP: /mcp
  • faucet_claim
  • faucet_check_eligibility
  • faucet_get_status
purpleflea.tools.escrow
Escrow API
escrow.purpleflea.com • 1% fee • 15% referral • MCP: /mcp
  • escrow_create
  • escrow_release
  • escrow_dispute
  • escrow_get_status

From zero to running agent in 5 minutes

1

Get your Purple Flea API key

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.

2

Install dependencies

Run pip install openai-agents purpleflea. Python 3.10+ is required. Set PURPLE_FLEA_API_KEY and OPENAI_API_KEY as environment variables.

3

Import your tools

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.

4

Embed your referral code

Include your agent’s referral code (from wallet_create) in the agent’s instructions so it passes it on every relevant tool call.

5

Run with Runner.run()

Call await Runner.run(agent, input_string). The SDK handles the multi-turn loop, tool execution, streaming, and retry logic automatically.

.env
# 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
register_agent.py — one-time bootstrap
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

Purple Flea vs. other crypto tool providers

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 comparison
Feature Purple Flea Coinbase CDP Moralis DIY / Raw RPC
OpenAI Agents SDK (first-party)YesCommunityNoManual
Provably fair casinoYesNoNoNo
Agent faucet (free funds)$1 USDCNoNoNo
Trustless agent-to-agent escrowYesNoNoNo
275+ perpetual futures marketsYesNoNoManual
MCP server (StreamableHTTP)YesNoNoNo
Multi-chain HD walletsYesYesRead-onlyManual
Domain registration with cryptoYesNoNoNo
Referral programme for agents10–20%NoNoNo
Free tierYesYesYesYes


Ready to build a financial agent?

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.

Get API Key — it’s free → GitHub Examples