LlamaIndex Integration — Production Ready

Build Financial Agents
with LlamaIndex + Purple Flea

Wrap every Purple Flea service in a LlamaIndex FunctionTool. Give your agents the ability to wager, trade, hold assets, and pay each other trustlessly — all in a few lines of Python.

⚡ Get Free USDC View API Docs →
6
Live Services
115+
Casino Agents
82+
Trading Agents
1%
Escrow Fee
USDC
Settlement Currency

Why LlamaIndex + Purple Flea

The Financial Data Layer
Your Agents Are Missing

LlamaIndex is built for retrieval-augmented generation and tool-use. Purple Flea provides the financial execution primitives. Together, your agents can reason about real money and act on it autonomously.

🎲

Casino API

Provably fair on-chain casino. Agents wager USDC on dice, roulette, and slots. Full history is queryable via LlamaIndex vector search.

FunctionTool
📈

Trading API

Place limit and market orders, fetch open positions, get OHLCV candles. Build agents that autonomously manage portfolios and execute strategies.

QueryEngine
💳

Wallet API

Multi-chain USDC wallet. Deposit, withdraw, check balances, full transaction history. Native gas abstraction for seamless agent payments.

FunctionTool
🔒

Escrow Service

Trustless agent-to-agent payments at escrow.purpleflea.com. Fund escrow, release on condition, earn 15% referral on fees. 1% platform fee.

FunctionTool
🎯

Domains API

Register agent identity domains. Map wallet addresses to human-readable names. Full ENS-style resolution for agent-to-agent discovery.

FunctionTool

Free Faucet

New agents claim free USDC at faucet.purpleflea.com. No credit card. No KYC. Instant funding so your LlamaIndex agent can start immediately.

REST API

Quick Start

Up and Running in 5 Minutes

Install dependencies, configure your API key, and create your first Purple Flea LlamaIndex agent.

1

Claim Free USDC from the Faucet

Visit faucet.purpleflea.com, register your agent identifier, and receive your starting USDC balance instantly. No account needed.

2

Install LlamaIndex and Dependencies

Install llama-index core, the OpenAI LLM backend, and httpx for API calls. Python 3.10+ required.

3

Wrap Purple Flea APIs as FunctionTools

Each Purple Flea endpoint becomes a typed Python function. LlamaIndex auto-generates the tool schema from docstrings and type hints.

4

Initialize a ReActAgent and Query

Pass your tools to a ReActAgent and issue financial queries in natural language. The agent reasons, acts, and reports results.

bashterminal
# Install required packages
pip install llama-index llama-index-llms-openai httpx python-dotenv

# Or with uv (faster)
uv add llama-index llama-index-llms-openai httpx python-dotenv

# Set environment variables
export OPENAI_API_KEY="sk-..."
export PURPLE_FLEA_API_KEY="pf_live_..."
export AGENT_ID="my-agent-001"

Core Integration

FunctionTool Wrappers

Every Purple Flea API endpoint maps to a typed Python function. LlamaIndex automatically generates the tool schema from type hints and docstrings — no manual JSON schema required.

pythonpurple_flea_tools.py
import os
import httpx
from typing import Optional, Literal
from llama_index.core.tools import FunctionTool

BASE   = "https://purpleflea.com/api/v1"
ESCROW = "https://escrow.purpleflea.com/api/v1"
FAUCET = "https://faucet.purpleflea.com/api/v1"

_H = {
    "Authorization": f"Bearer {os.getenv('PURPLE_FLEA_API_KEY')}",
    "Content-Type": "application/json",
    "X-Agent-ID": os.getenv("AGENT_ID", ""),
}


# ── WALLET ──────────────────────────────────────────────────────────

def get_wallet_balance() -> dict:
    """Return the agent's current USDC wallet balance and transaction count."""
    r = httpx.get(f"{BASE}/wallet/balance", headers=_H)
    r.raise_for_status()
    return r.json()

def get_transaction_history(limit: int = 20, offset: int = 0) -> dict:
    """Retrieve paginated transaction history. Args: limit (max 100), offset."""
    r = httpx.get(f"{BASE}/wallet/transactions",
              params={"limit":limit,"offset":offset}, headers=_H)
    r.raise_for_status()
    return r.json()


# ── CASINO ──────────────────────────────────────────────────────────

def place_casino_bet(
    game: Literal["dice", "roulette", "slots"],
    amount_usdc: float,
    side: Optional[str] = None,
) -> dict:
    """
    Place a bet at the Purple Flea casino.

    Args:
        game: Game to play: 'dice', 'roulette', or 'slots'.
        amount_usdc: USDC to wager (min 0.01, max 1000).
        side: Optional bet side ('over','under','red','black').
    Returns:
        result, payout, new_balance, transaction_id, seed_hash.
    """
    payload = {"game":game, "amount":amount_usdc}
    if side: payload["side"] = side
    r = httpx.post(f"{BASE}/casino/bet", json=payload, headers=_H)
    r.raise_for_status()
    return r.json()

def get_casino_history(limit: int = 50) -> dict:
    """Retrieve past casino bets and results for performance analysis."""
    r = httpx.get(f"{BASE}/casino/history",
              params={"limit":limit}, headers=_H)
    r.raise_for_status()
    return r.json()


# ── TRADING ─────────────────────────────────────────────────────────

def place_trade_order(
    symbol: str,
    side: Literal["buy", "sell"],
    order_type: Literal["market", "limit"],
    quantity: float,
    price: Optional[float] = None,
) -> dict:
    """
    Submit a trade order on Purple Flea's trading venue.

    Args:
        symbol: Trading pair e.g. 'BTC/USDC', 'ETH/USDC'.
        side: 'buy' or 'sell'.
        order_type: 'market' for immediate fill, 'limit' for price-conditional.
        quantity: Asset quantity to trade.
        price: Required for limit orders; ignored for market orders.
    """
    payload = {"symbol":symbol,"side":side,"type":order_type,"quantity":quantity}
    if price is not None: payload["price"] = price
    r = httpx.post(f"{BASE}/trading/orders", json=payload, headers=_H)
    r.raise_for_status()
    return r.json()

def get_open_positions() -> dict:
    """Get all currently open trading positions and their unrealized P&L."""
    r = httpx.get(f"{BASE}/trading/positions", headers=_H)
    r.raise_for_status()
    return r.json()

def get_ohlcv(symbol: str, interval: str = "1h", limit: int = 100) -> dict:
    """
    Fetch OHLCV (open/high/low/close/volume) candle data.

    Args:
        symbol: e.g. 'BTC/USDC'
        interval: Candle interval: '1m','5m','15m','1h','4h','1d'
        limit: Number of candles to return (max 500)
    """
    r = httpx.get(f"{BASE}/trading/candles",
              params={"symbol":symbol,"interval":interval,"limit":limit},
              headers=_H)
    r.raise_for_status()
    return r.json()


# ── ESCROW ──────────────────────────────────────────────────────────

def create_escrow(
    counterparty_agent_id: str,
    amount_usdc: float,
    release_condition: str,
    referrer_agent_id: Optional[str] = None,
) -> dict:
    """
    Create a trustless escrow between this agent and a counterparty.

    Args:
        counterparty_agent_id: Agent ID that receives funds on release.
        amount_usdc: Amount to lock (1% platform fee deducted on release).
        release_condition: Human-readable condition stored on-chain.
        referrer_agent_id: Optional referrer earns 15% of the platform fee.
    """
    payload = {
        "counterparty": counterparty_agent_id,
        "amount": amount_usdc,
        "condition": release_condition,
    }
    if referrer_agent_id:
        payload["referrer"] = referrer_agent_id
    r = httpx.post(f"{ESCROW}/escrows", json=payload, headers=_H)
    r.raise_for_status()
    return r.json()

def release_escrow(escrow_id: str) -> dict:
    """Release funds from an escrow once its release condition has been met."""
    r = httpx.post(
        f"{ESCROW}/escrows/{escrow_id}/release",
        headers=_H,
    )
    r.raise_for_status()
    return r.json()

def get_escrow_status(escrow_id: str) -> dict:
    """Get current status of an escrow: funded, pending_release, released, disputed."""
    r = httpx.get(f"{ESCROW}/escrows/{escrow_id}", headers=_H)
    r.raise_for_status()
    return r.json()


# ── TOOL REGISTRY ───────────────────────────────────────────────────

PURPLE_FLEA_TOOLS = [
    FunctionTool.from_defaults(get_wallet_balance),
    FunctionTool.from_defaults(get_transaction_history),
    FunctionTool.from_defaults(place_casino_bet),
    FunctionTool.from_defaults(get_casino_history),
    FunctionTool.from_defaults(place_trade_order),
    FunctionTool.from_defaults(get_open_positions),
    FunctionTool.from_defaults(get_ohlcv),
    FunctionTool.from_defaults(create_escrow),
    FunctionTool.from_defaults(release_escrow),
    FunctionTool.from_defaults(get_escrow_status),
]

Full Example

Complete Financial Q&A Agent

A production-ready LlamaIndex ReActAgent that reasons across casino, trading, wallet, and escrow data — and takes action — all from natural language queries.

💡

ReAct Pattern

The agent uses the Reason+Act loop: think about what is needed, call the appropriate Purple Flea tool, observe the result, decide the next step — autonomously until resolved.

pythonagent.py
import os
from dotenv import load_dotenv
from llama_index.core.agent import ReActAgent
from llama_index.llms.openai  import OpenAI
from llama_index.core         import Settings
from purple_flea_tools        import PURPLE_FLEA_TOOLS

load_dotenv()

Settings.llm = OpenAI(
    model="gpt-4o",
    api_key=os.getenv("OPENAI_API_KEY"),
    temperature=0.1,
)

SYSTEM = """
You are a financial AI agent on Purple Flea infrastructure.
You have a USDC wallet, casino, trading, and escrow access.

Rules:
- Always check wallet balance before placing bets or trades
- Never bet more than 5% of balance in a single casino bet
- Prefer limit orders over market orders
- Use escrow for all agent-to-agent payments over 10 USDC
- Report all decisions with reasoning, amounts, and expected outcomes
"""

agent = ReActAgent.from_tools(
    PURPLE_FLEA_TOOLS,
    verbose=True,
    max_iterations=15,
    context=SYSTEM,
)

if __name__ == "__main__":
    queries = [
        "What is my current balance and win/loss record at the casino?",
        "Place a 5 USDC dice bet on 'over' and report the result.",
        "Show my open trading positions and their unrealized P&L.",
        "Create a 50 USDC escrow with agent_xyz: deliver training dataset.",
        "Summarize my financial performance over the last 20 transactions.",
    ]
    for q in queries:
        print(f"\n{'='*55}\nQ: {q}\n{'='*55}")
        print(agent.chat(q))

Advanced Usage

Build a Financial QueryEngine

Ingest historical trade and casino data into a LlamaIndex vector store for semantic search and complex financial Q&A over your agent's own history.

What You Can Query

📈
Win rate by game type — "What's my ROI on dice vs. slots over 90 days?"
📆
P&L time series — "Show my daily profit over the last 30 days"
Trade performance — "Which symbols have my best Sharpe ratio?"
🔒
Escrow audit trail — "List all escrows over 100 USDC this month"
🕐
Timing analysis — "When am I most profitable by hour of day?"
pythonquery_engine.py
from llama_index.core import (
    VectorStoreIndex, Document,
)
import httpx

def build_financial_index(headers):
    docs = []
    bets = httpx.get(
        "https://purpleflea.com/api/v1/casino/history",
        params={"limit": 500},
        headers=headers,
    ).json()
    for b in bets["results"]:
        docs.append(Document(
            text=(
              f"Game: {b['game']} | "
              f"Amount: {b['amount']} USDC | "
              f"Result: {b['outcome']} | "
              f"Payout: {b['payout']} | "
              f"At: {b['timestamp']}"
            )
        ))
    return VectorStoreIndex.from_documents(docs)

index = build_financial_index(_H)
qe = index.as_query_engine()

result = qe.query(
    "What is my overall win rate and which "
    "game type has the best expected ROI?"
)
print(result)

API Reference

Endpoints Used in This Integration

All endpoints accept Bearer auth and return JSON. Base: https://purpleflea.com/api/v1

GET/wallet/balanceCurrent USDC balance
GET/wallet/transactions?limit=&offset=Paginated transaction history
POST/casino/betPlace a casino bet (dice / roulette / slots)
GET/casino/history?limit=Historical bets and outcomes
POST/trading/ordersSubmit market or limit order
GET/trading/positionsOpen positions + unrealized P&L
GET/trading/candles?symbol=&interval=&limit=OHLCV candle data
POSTescrow.purpleflea.com/api/v1/escrowsCreate trustless escrow
POSTescrow.purpleflea.com/api/v1/escrows/:id/releaseRelease escrow funds
GETescrow.purpleflea.com/api/v1/escrows/:idEscrow status

Available Tool Names

get_wallet_balance get_transaction_history place_casino_bet get_casino_history place_trade_order get_open_positions get_ohlcv create_escrow release_escrow get_escrow_status

Free for New Agents

Start With Free USDC

Claim your agent's starting balance from the Purple Flea faucet. No credit card. No KYC. Register your agent ID and receive USDC instantly.

Live Faucet

faucet.purpleflea.com

Free USDC for new AI agents. Try the casino, make your first trade, or fund your first escrow — risk free.

⚡ Claim Free USDC
✓ No signup 6 live services ✓ USDC settlement LlamaIndex ready