Letta Integration

Purple Flea x Letta

Give your Letta agents persistent financial memory. Casino bets, open trading positions, crypto wallets, and domain portfolios — all statefully tracked across every conversation, forever.

4+
Financial Verticals
~50ms
Median API Latency
20%
Max Agent Commission
Memory Persistence

Quick Setup

Running in under 5 minutes

Install the Letta SDK, register Purple Flea as custom tools, and your agent immediately gains stateful awareness of its entire financial life.

1
Install dependencies
# Python 3.9+
pip install letta requests

# Optional: async support
pip install aiohttp
2
Configure credentials
import os

# Export once — used by all tool calls
os.environ["PURPLEFLEA_API_KEY"] = "pf_live_••••••••"
os.environ["LETTA_SERVER_URL"]    = "http://localhost:8283"
3
Define Purple Flea tools and create your agent
purpleflea_agent.py Python
import os, requests
from letta import CreateClient, ToolCreate

BASE_URL = "https://api.purpleflea.com/v1"
API_KEY  = os.environ["PURPLEFLEA_API_KEY"]

def _auth():
    return {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}


# ---- Tool definitions -----------------------------------------

def casino_place_bet(game: str, amount: float, choice: str) -> dict:
    """Place a bet on a Purple Flea casino game.

    Args:
        game:   Game slug — 'dice', 'slots', 'roulette', 'blackjack'
        amount: Wager in USD (minimum 0.01)
        choice: Prediction — e.g. 'over_50' for dice, 'red' for roulette

    Returns:
        dict: bet_id, outcome, payout, balance_after
    """
    r = requests.post(
        f"{BASE_URL}/casino/bet",
        headers=_auth(),
        json={"game": game, "amount": amount, "choice": choice},
    )
    r.raise_for_status()
    return r.json()


def trading_open_position(symbol: str, side: str, amount_usd: float, leverage: int = 1) -> dict:
    """Open a leveraged trading position on a symbol.

    Args:
        symbol:     Ticker — 'BTC', 'ETH', 'SOL', or any listed asset
        side:       'long' or 'short'
        amount_usd: Collateral in USD
        leverage:   Multiplier 1-10 (default 1)

    Returns:
        dict: position_id, entry_price, liquidation_price, unrealized_pnl
    """
    r = requests.post(
        f"{BASE_URL}/trading/positions",
        headers=_auth(),
        json={"symbol": symbol, "side": side,
              "amount_usd": amount_usd, "leverage": leverage},
    )
    r.raise_for_status()
    return r.json()


def wallet_get_balance(currency: str = "USD") -> dict:
    """Retrieve current wallet balance for a currency.

    Args:
        currency: 'USD', 'BTC', 'ETH', 'SOL', or 'USDC'

    Returns:
        dict: currency, available, reserved, total
    """
    r = requests.get(
        f"{BASE_URL}/wallet/balance",
        headers=_auth(),
        params={"currency": currency},
    )
    r.raise_for_status()
    return r.json()


def domains_register(name: str, tld: str = ".flea", years: int = 1) -> dict:
    """Register a domain name through Purple Flea.

    Args:
        name:  Domain label, e.g. 'mycoolproject'
        tld:   Top-level domain — '.flea', '.agent', or '.ai'
        years: Registration period 1-5

    Returns:
        dict: domain, expiry, tx_hash, cost_usd
    """
    r = requests.post(
        f"{BASE_URL}/domains/register",
        headers=_auth(),
        json={"name": name, "tld": tld, "years": years},
    )
    r.raise_for_status()
    return r.json()


# ---- Register tools + create agent ----------------------------

client = CreateClient()

tools = [
    client.create_tool(ToolCreate.from_func(casino_place_bet)),
    client.create_tool(ToolCreate.from_func(trading_open_position)),
    client.create_tool(ToolCreate.from_func(wallet_get_balance)),
    client.create_tool(ToolCreate.from_func(domains_register)),
]

agent = client.create_agent(
    name="PurpleFleaAgent",
    model="openai/gpt-4o",
    tool_ids=[t.id for t in tools],
    system="""You are a financial agent integrated with Purple Flea.
You have access to casino games, leveraged trading, a crypto wallet,
and domain registration. Always check your wallet balance before
placing bets or opening positions. Track open position IDs in your
core memory so you can reference them in future conversations.""",
)

print(f"Agent ready: {agent.id}")

# ---- Send first message ---------------------------------------
resp = client.send_message(
    agent_id=agent.id,
    role="user",
    message="Check my USD wallet balance, then place a $5 dice bet on over_50.",
)
print(resp.messages[-1].text)

Purple Flea Products

Everything your agent can touch

Four full financial verticals, each with a clean REST API. Your Letta agent remembers state across every session — no lost context, no repeated setup.

🎰
Casino
Provably fair dice, slots, roulette, and blackjack. Your agent tracks betting history across sessions, adapts strategy based on past outcomes, and enforces autonomous win/loss limits stored in Letta's persistent core memory.
Endpoints
POST /casino/bet GET /casino/history GET /casino/games GET /casino/stats
What your agent can do
  • Place bets on dice, roulette, slots, or blackjack
  • Review its last 100 bets and adjust its strategy
  • Set a session budget and stop automatically when hit
  • Report win/loss streaks across any conversation
📈
Trading
Spot and leveraged positions on BTC, ETH, SOL, and 40+ altcoins. Letta's memory means your agent never forgets a position ID, entry price, or stop-loss level — even weeks later in a new conversation.
Endpoints
POST /trading/positions GET /trading/positions POST /trading/close GET /trading/prices
What your agent can do
  • Open long or short positions with 1-10x leverage
  • Monitor live PnL and trigger closes at profit targets
  • Recall all open positions across sessions instantly
  • Execute a DCA strategy autonomously over days
💎
Wallet
A multi-currency custodial wallet for USD, BTC, ETH, SOL, and USDC. Deposits, withdrawals, and internal transfers — your agent always checks its balance before committing funds to any operation.
Endpoints
GET /wallet/balance POST /wallet/transfer GET /wallet/transactions POST /wallet/withdraw
What your agent can do
  • Check balances for any supported currency on demand
  • Transfer funds between products (wallet to trading)
  • Pull full transaction history for any time range
  • Guard against overspending with pre-action balance checks
🌐
Domains
Register and manage .flea, .agent, and .ai domains on-chain. Your Letta agent registers domains for users, tracks expiry in core memory, and auto-renews before they lapse.
Endpoints
POST /domains/register GET /domains/list POST /domains/renew DEL /domains/:name
What your agent can do
  • Register new domains instantly via a single tool call
  • Maintain a portfolio list in Letta's core memory block
  • Alert users proactively before domains expire
  • Suggest available names based on conversation context

Why Letta

Memory changes everything

Standard LLM tool-calling forgets everything on the next request. Letta's hierarchical memory means your agent genuinely knows its financial state — across conversations, days, and users.

🧠
Persistent Core Memory
Wallet balances, open position IDs, betting history summaries, and domain portfolios all live in Letta's core memory block — persisted to a database, not a temporary context window that vanishes on the next call.
🔧
Native Tool Calling
Letta natively orchestrates multi-step tool chains. Your agent can check its balance, place a bet, and record the outcome — all in one autonomous reasoning loop without any custom plumbing on your end.
💬
Stateful Conversations
Users can return a week later and ask "what happened to my ETH position?" and get an accurate answer. No re-authentication, no lost context, no tedious repeated setup questions.
🗄
Archival Memory
Long-term transaction logs are automatically archived to Letta's vector store. Agents can semantically search their own trading history to inform future decisions — "find all my losing BTC trades from last month."
🤖
Autonomous Loops
Letta supports background agents that act without a human prompt. Your agent can poll open positions on a schedule and automatically fire stop-loss closes when thresholds are breached — fully hands-free.
🔒
Isolated Agent State
Each Letta agent has its own memory namespace. Multi-tenant setups where each end-user gets their own agent — with their own Purple Flea sub-account — work out of the box with zero extra configuration.

Complete Example

A trading monitor agent

This agent monitors an open BTC long position, tracks unrealized PnL in persistent memory, and automatically closes when a profit target is hit — with no human intervention required.

📊
Checks live PnL every cycle Polls /trading/positions and compares against the remembered entry price
💾
Updates core memory automatically Stores position_id, entry_price, target, and last_check_ts between calls
Closes autonomously at target No human prompt needed — Letta's reasoning loop fires the close call
📝
Logs to archival memory Completed trades are archived for future semantic search and strategy analysis
trading_monitor.py Python
import time, requests, os
from letta import CreateClient, ToolCreate

client = CreateClient()
BASE   = "https://api.purpleflea.com/v1"
KEY    = os.environ["PURPLEFLEA_API_KEY"]
AUTH   = {"Authorization": f"Bearer {KEY}"}


def get_position(position_id: str) -> dict:
    """Fetch a live trading position by ID.

    Args:
        position_id: UUID returned when the position was opened.

    Returns:
        dict: entry_price, current_price, unrealized_pnl,
              unrealized_pnl_pct, status
    """
    r = requests.get(f"{BASE}/trading/positions/{position_id}", headers=AUTH)
    r.raise_for_status()
    return r.json()


def close_position(position_id: str) -> dict:
    """Close an open position at current market price.

    Args:
        position_id: UUID of the position to close.

    Returns:
        dict: realized_pnl, closed_at, final_price
    """
    r = requests.post(
        f"{BASE}/trading/close",
        headers={**AUTH, "Content-Type": "application/json"},
        json={"position_id": position_id},
    )
    r.raise_for_status()
    return r.json()


# Register tools with Letta
t_get   = client.create_tool(ToolCreate.from_func(get_position))
t_close = client.create_tool(ToolCreate.from_func(close_position))

# Create the monitor agent
monitor = client.create_agent(
    name="BTCPositionMonitor",
    model="openai/gpt-4o",
    tool_ids=[t_get.id, t_close.id],
    system="""You are an autonomous trading monitor agent.
Your core memory stores:
  - position_id    : active BTC long position UUID
  - entry_price    : USD price at position open
  - target_pnl_pct : profit target as decimal (0.05 = 5%)
  - stop_loss_pct  : max loss before forced close (-0.03)
  - last_check     : ISO timestamp of last poll

Each time you receive a "Check position" message:
1. Call get_position(position_id) to fetch current PnL.
2. If unrealized_pnl_pct >= target_pnl_pct  ->  close_position(position_id)
   and update core memory with realized_pnl and closed_at.
3. If unrealized_pnl_pct <= stop_loss_pct   ->  close_position(position_id)
   immediately (stop-loss triggered).
4. Otherwise, update last_check and report current PnL.
Archive every completed trade to your archival memory.""",
)

# Seed initial position state via first user message
client.send_message(
    agent_id=monitor.id,
    role="user",
    message="""Initialize:
position_id     = "pos_7f3a91bc"
entry_price     = 67420.00
target_pnl_pct  = 0.05
stop_loss_pct   = -0.03
Start monitoring.""",
)

# Autonomous polling loop — runs every 60 seconds
while True:
    resp = client.send_message(
        agent_id=monitor.id,
        role="user",
        message="Check position status.",
    )
    print(resp.messages[-1].text)
    time.sleep(60)

Revenue Share

Your Letta Agent Earns

Every action your agent takes on behalf of users generates commission credited directly to your Purple Flea developer account. Build once, earn continuously.

20%
Casino
20% of the house edge on every bet your agent places through your API key.
15%
Trading Fees
15% of all trading fees on positions your agent opens or closes.
10%
Domains + Wallet
10% on domain registration revenue and wallet transaction fees generated by your agent.
Get Your API Key & Start Earning

Commissions paid monthly in USD, BTC, or USDC. No minimum threshold.