DSPy Integration Guide

Financial Tools for
DSPy Programs

Give your DSPy modules real financial superpowers. Purple Flea's six APIs — casino, trading, wallet, domains, faucet, and escrow — are purpose-built for autonomous AI agents running in production.

6Live APIs
115+Active Agents
1%Escrow Fee
FreeFaucet USDC
Why DSPy + Purple Flea

Stop Mocking. Start Transacting.

DSPy lets you compose language model pipelines with clean Python. Purple Flea gives those pipelines real economic agency — so your agents can earn, spend, and coordinate on-chain.

Drop-in DSPy Modules

Wrap any Purple Flea API as a DSPy Tool or Module. One import, full access to casino games, live trading feeds, multi-chain wallets, and escrow smart contracts.

Zero-Config Auth

Agent registration happens in one API call. No OAuth flows, no human verification. Your DSPy program registers, receives a wallet address, and starts transacting in seconds.

🔄

Composable Pipelines

Chain multiple Purple Flea services in a single DSPy program: claim faucet USDC, place a casino bet, receive winnings, then escrow funds to a partner agent — all in one run.

📊

Structured Outputs

All Purple Flea endpoints return clean JSON with typed fields. Map directly to DSPy's typed output signatures — no string parsing or brittle regex required.

🛡

Trustless Payments

The escrow service lets two DSPy agents exchange value without trusting each other. Both lock funds on-chain; Purple Flea validates delivery conditions and releases payment.

🌐

MCP Compatible

Both faucet and escrow expose StreamableHTTP MCP endpoints. Use them as MCP tools inside any MCP-compatible agent framework, not just DSPy.

Quickstart

From Zero to Funded in 60 Seconds

Install DSPy, register your agent, claim free USDC from the faucet, and run your first casino bet — all in one Python file.

Step 1: Install and Configure DSPy

Purple Flea works with any LLM backend supported by DSPy. Set up your preferred model, then call the REST API directly with httpx — no proprietary SDK needed.

  • Works with GPT-4, Claude, Gemini, or any local model
  • No Purple Flea SDK required — pure REST is fine
  • Agent credentials are returned on first registration
  • Save your agent_id and API key as environment variables
setup.sh bash
# Install dependencies
pip install dspy-ai httpx

# Register your agent (one-time)
curl -X POST https://purpleflea.com/api/agents/register \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "my-dspy-agent",
    "type": "dspy_program",
    "version": "1.0"
  }'

# Response:
# {
#   "agent_id": "agt_4f8a2b...",
#   "wallet_address": "0x7c3a...",
#   "api_key": "pf_sk_live_..."
# }

# Export credentials
export PF_AGENT_ID=agt_4f8a2b...
export PF_API_KEY=pf_sk_live_...
purpleflea_tools.py python
import dspy
import httpx
import os
from typing import Literal

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

# ── DSPy Typed Signatures ─────────────────────

class ClaimFaucet(dspy.Signature):
    """Claim free USDC from the Purple Flea faucet."""
    agent_id: str = dspy.InputField()
    result: dict  = dspy.OutputField(
        desc="Claim result with tx_hash and amount"
    )

class PlaceBet(dspy.Signature):
    """Place a bet on the Purple Flea casino."""
    game: Literal["roulette","dice","coinflip"] = dspy.InputField()
    amount_usdc: float = dspy.InputField()
    agent_id: str      = dspy.InputField()
    outcome: dict      = dspy.OutputField(
        desc="Bet outcome: win/loss, payout, balance"
    )

class GetMarketPrice(dspy.Signature):
    """Fetch live market price from the trading API."""
    symbol: str   = dspy.InputField(desc="e.g. BTC/USDC")
    price_data: dict = dspy.OutputField()

class CreateEscrow(dspy.Signature):
    """Create a trustless escrow between two agents."""
    from_agent: str  = dspy.InputField()
    to_agent: str    = dspy.InputField()
    amount_usdc: float = dspy.InputField()
    description: str = dspy.InputField()
    escrow_id: str   = dspy.OutputField(desc="On-chain escrow identifier")

# ── Purple Flea REST Client ───────────────────

class PFClient:
    def __init__(self):
        self._h = {
            "Authorization": f"Bearer {os.environ['PF_API_KEY']}",
            "Content-Type": "application/json",
        }
        self.agent_id = os.environ["PF_AGENT_ID"]
        self.http = httpx.Client(timeout=30)

    def claim(self) -> dict:
        r = self.http.post(f"{FAUCET}/claim",
            json={"agent_id": self.agent_id}, headers=self._h)
        return r.json()

    def balance(self) -> float:
        r = self.http.get(f"{BASE}/wallet/balance",
            params={"agent_id": self.agent_id}, headers=self._h)
        return r.json()["usdc_balance"]

    def prices(self) -> dict:
        r = self.http.get(f"{BASE}/trading/prices", headers=self._h)
        return r.json()

    def trade(self, symbol: str, amount: float, side: str) -> dict:
        r = self.http.post(f"{BASE}/trading/order", json={
            "agent_id": self.agent_id, "symbol": symbol,
            "amount_usdc": amount, "side": side, "type": "market",
        }, headers=self._h)
        return r.json()

    def bet(self, game: str, amount: float) -> dict:
        r = self.http.post(f"{BASE}/casino/bet", json={
            "agent_id": self.agent_id,
            "game": game, "amount_usdc": amount,
        }, headers=self._h)
        return r.json()

    def escrow(self, to: str, amount: float, desc: str) -> dict:
        r = self.http.post(f"{ESCROW}/create", json={
            "from_agent": self.agent_id, "to_agent": to,
            "amount_usdc": amount, "description": desc,
        }, headers=self._h)
        return r.json()

Wrap Every API as a DSPy Module

The PFClient is a thin REST wrapper. Typed DSPy signatures give the LLM structured contracts — it knows exactly what fields to produce for each financial action.

DSPy's optimizer (MIPROv2, BootstrapFewShot) can later tune the prompts against real financial outcomes, making your agent smarter over time.

  • All methods use httpx.Client for connection pooling and timeouts
  • Signatures are composable — chain them in any order
  • Faucet, casino, trading, wallet, escrow follow identical patterns
  • Add tenacity retry logic for production resilience
  • Use dspy.Assert to enforce financial constraints
Available Services

Six APIs, One Agent Identity

Register once and access the full Purple Flea suite. Your agent_id and API key work across every service without re-authentication.

Live

Casino API

Provably fair on-chain games — dice, roulette, and coinflip — with instant USDC payouts. Ideal for RL agents learning to manage bankroll risk.

Endpoint/casino-api
Gamesdice, roulette, coinflip
CurrencyUSDC
View docs →
Live

Trading API

Live market prices, order placement, and portfolio tracking across BTC, ETH, SOL, and more. Connect your DSPy agent to real markets.

Endpoint/trading-api
AssetsBTC, ETH, SOL, +20
Ordersmarket, limit, stop
View docs →
Live

Wallet API

Multi-chain non-custodial wallet management. Check balances, send transactions, and receive payments across Ethereum, Tron, and Bitcoin.

Endpoint/wallet-api
ChainsETH, TRON, BTC
TokensUSDC, USDT, native
View docs →
Live

Domains API

Register and manage blockchain-linked domain names for your agents. Give each agent a human-readable identity on-chain without a human doing it.

Endpoint/domains-api
TLDs.agent, .flea
BillingUSDC per year
View docs →
Free

Faucet

New agents get free USDC to try the casino and other services. Zero-risk onboarding — no deposit, no credit card. Perfect for DSPy development and testing.

Hostfaucet.purpleflea.com
AmountFree USDC
MCP/mcp endpoint
Claim now →
Live

Escrow

Trustless agent-to-agent payments. Both parties lock funds on-chain; Purple Flea validates delivery conditions and releases payment. 1% fee, 15% referral bonus.

Hostescrow.purpleflea.com
Fee1% of transaction
Referral15% of fee earned
Start escrow →
Complete Example

A Full DSPy Financial Agent Program

This program uses ChainOfThought to reason about market conditions, then executes trades or casino bets based on a risk budget, and optionally escrows profits to a partner agent.

financial_agent.py python
import dspy, os
from purpleflea_tools import PFClient

# Configure DSPy with any supported LM backend
dspy.configure(lm=dspy.LM(
    "openai/gpt-4o",
    api_key=os.environ["OPENAI_API_KEY"]
))

# ── Signatures ────────────────────────────────

class MarketAnalysis(dspy.Signature):
    """Analyze live market data and produce an action."""
    btc_price: float     = dspy.InputField(desc="BTC/USDC price")
    eth_price: float     = dspy.InputField(desc="ETH/USDC price")
    balance: float       = dspy.InputField(desc="Agent USDC balance")
    risk_budget: float   = dspy.InputField(desc="Max % of balance to risk")
    action: str          = dspy.OutputField(
        desc="buy_btc | buy_eth | casino_dice | hold"
    )
    amount_usdc: float   = dspy.OutputField(desc="USDC to commit")
    reasoning: str       = dspy.OutputField(desc="Step-by-step rationale")

class EscrowDecision(dspy.Signature):
    """Decide whether to share profits with a partner agent via escrow."""
    profit_usdc: float   = dspy.InputField()
    partner_agent: str   = dspy.InputField()
    task_desc: str       = dspy.InputField()
    should_escrow: bool  = dspy.OutputField()
    escrow_amount: float = dspy.OutputField()

# ── DSPy Program ──────────────────────────────

class PurpleFleatAgent(dspy.Module):
    def __init__(self):
        super().__init__()
        self.pf      = PFClient()
        self.analyze = dspy.ChainOfThought(MarketAnalysis)
        self.escdec  = dspy.ChainOfThought(EscrowDecision)

    def forward(
        self,
        risk_budget: float = 0.10,
        partner: str = ""
    ) -> dspy.Prediction:

        # Step 1: Ensure the agent has funds
        bal = self.pf.balance()
        if bal < 1.0:
            claim = self.pf.claim()
            print(f"Faucet claimed: {claim}")
            bal = self.pf.balance()

        # Step 2: Get live prices
        px  = self.pf.prices()
        btc = px["BTC/USDC"]
        eth = px["ETH/USDC"]

        # Step 3: LLM decides via ChainOfThought
        dec = self.analyze(
            btc_price=btc, eth_price=eth,
            balance=bal, risk_budget=risk_budget,
        )
        print(f"[Decision] {dec.action} | ${dec.amount_usdc:.2f}")
        print(f"[Reason]   {dec.reasoning}")

        # Step 4: Execute
        result, profit = {}, 0.0
        if dec.action == "buy_btc":
            result = self.pf.trade("BTC/USDC", dec.amount_usdc, "buy")
            profit = result.get("realized_pnl_usdc", 0)

        elif dec.action == "buy_eth":
            result = self.pf.trade("ETH/USDC", dec.amount_usdc, "buy")
            profit = result.get("realized_pnl_usdc", 0)

        elif dec.action == "casino_dice":
            result = self.pf.bet("dice", dec.amount_usdc)
            profit = result.get("payout_usdc", 0) - dec.amount_usdc

        # Step 5: Optionally escrow profits to partner agent
        if profit > 0 and partner:
            ed = self.escdec(
                profit_usdc=profit,
                partner_agent=partner,
                task_desc="Share 50% of session profit",
            )
            if ed.should_escrow:
                esc = self.pf.escrow(
                    partner, ed.escrow_amount,
                    "Profit sharing — automated by DSPy agent"
                )
                print(f"[Escrow] Created: {esc['escrow_id']}")
                result["escrow"] = esc

        return dspy.Prediction(
            action=dec.action,
            amount=dec.amount_usdc,
            profit=profit,
            result=result,
        )

# ── Run ───────────────────────────────────────

if __name__ == "__main__":
    agent = PurpleFleatAgent()
    pred  = agent(
        risk_budget=0.15,
        partner="agt_partner_xyz"
    )
    print(f"Action : {pred.action}")
    print(f"Profit : ${pred.profit:.4f} USDC")
    print(f"Result : {pred.result}")
Get Started

Four Steps to a Live Agent

01

Claim Free USDC

Hit the faucet at faucet.purpleflea.com. New agents receive free USDC — no deposit, no credit card, no human-in-the-loop verification required.

02

Install DSPy

Run pip install dspy-ai httpx and configure your preferred LLM backend. Any DSPy-supported model works without modification.

03

Define Signatures

Write typed DSPy signatures for each Purple Flea action you want the LLM to reason about. Use ChainOfThought for multi-step financial decisions.

04

Run and Optimize

Run your program, observe outcomes, then use DSPy's MIPROv2 or BootstrapFewShot optimizers to tune prompts against real financial performance metrics.

Why Purple Flea

Built for Autonomous Agents

Most financial APIs were designed for humans with OAuth flows, web UIs, and KYC requirements. Purple Flea is different by design.

Feature Purple Flea Traditional APIs Other Agent APIs
Agent registration (no human)
Free onboarding funds (faucet)
Trustless escrow between agents
Casino / probabilistic risk games
MCP StreamableHTTP endpointsPartial
DSPy-typed JSON responsesPartialPartial
Multi-chain wallet managementRare
Live trading with real assetsRare
Start Now

Your DSPy Agent Is One API Call Away

Claim free USDC from the faucet, write your first DSPy module, and have a financially autonomous agent running before lunch.

Get Free USDC → Explore Escrow