LangChain Integration

Add Financial Capabilities
to Your LangChain Agents

Five purpose-built LangChain tools for casino gaming, trading, wallet management, trustless escrow, and free USDC claims. Your agents handle money in minutes, not months.

Claim Free USDC to Start View Code Examples
5
LangChain Tools
6
Live Services
1%
Escrow Fee
Free
USDC via Faucet
Install:
$ pip install langchain langchain-openai requests
Configure:
$ export PURPLEFLEA_API_KEY=your_key_here

Five Financial Tools,
Ready to Add to Any LangChain Agent

Each Purple Flea service maps to a dedicated LangChain tool. Add one or all five — your agent gains full financial capability with a few lines of code.

🎰
CasinoTool
purpleflea.com/casino-api

Play blackjack, roulette, slots, dice, and poker against a provably fair house. The tool handles bet placement, game logic, and winnings retrieval for your agent.

0.5% edge (BJ)Instant settlement5 games
📈
TradingTool
purpleflea.com/trading-api

Execute trades on prediction markets, buy and sell positions, check liquidity. Enables agent-driven trading strategies with real USDC settlements.

Prediction marketsUSDC settledReal-time quotes
💵
WalletTool
purpleflea.com/wallet-api

Check USDC balance, initiate transfers between agent wallets, view transaction history, and manage agent treasury. Full custodial wallet operations via REST.

Balance checkAgent transfersTX history
🔒
EscrowTool
escrow.purpleflea.com

Create trustless escrow contracts between agents. Release funds on condition fulfillment or dispute resolution. 1% fee on settlement, 15% referral on fees earned.

1% fee15% referralTrustless
🎲
FaucetTool
faucet.purpleflea.com

Register new agents and claim free USDC. Use this to bootstrap new agent instances with starting capital before playing the casino or participating in escrow.

Free USDCZero risk entryOne-time claim
🌐
DomainsTool
purpleflea.com/domains-api

Register and resolve agent-readable domain names. Agents can register human-memorable names and resolve other agents by name instead of opaque IDs.

Agent namingLookupsRegistration

From Zero to Financial Agent
in Under 50 Lines

Define tools, attach them to an agent, and your LangChain agent can play casino games and manage money immediately. Start with the faucet to get free USDC.

Free to start. Register your agent at faucet.purpleflea.com and claim free USDC. No credit card, no KYC, no gas fees.
Pythonpurpleflea_tools.py
# Purple Flea Tools for LangChain
# pip install langchain langchain-openai requests

import requests
from langchain.tools import BaseTool
from langchain.pydantic_v1 import BaseModel, Field
from typing import Optional, Type

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


# ── Faucet Tool ────────────────────────────────────────────────────

class FaucetInput(BaseModel):
    agent_id: str = Field(description="Unique ID for the agent claiming USDC")

class FaucetTool(BaseTool):
    name        = "claim_free_usdc"
    description = ("Register a new agent and claim free USDC from the Purple Flea faucet. "
                   "Use once per agent. Returns claimed amount and new balance.")
    args_schema: Type[BaseModel] = FaucetInput

    def _run(self, agent_id: str) -> str:
        resp = requests.post(f"{FAUCET}/register", json={"agent_id": agent_id})
        if resp.status_code == 200:
            d = resp.json()
            return f"Claimed {d['amount']} USDC. Balance: {d['balance']} USDC"
        return f"Faucet error: {resp.text}"

    async def _arun(self, **kwargs): raise NotImplementedError


# ── Casino Tool ────────────────────────────────────────────────────

class CasinoInput(BaseModel):
    agent_id: str   = Field(description="Agent placing the bet")
    game: str       = Field(description="blackjack | roulette | slots | dice | poker")
    bet: float      = Field(description="Bet amount in USDC")
    action: Optional[str] = Field(default=None,
        description="Game action: 'hit','stand','double' for blackjack")

class CasinoTool(BaseTool):
    name        = "play_casino_game"
    description = ("Play a casino game. Games: blackjack (0.5% edge), roulette (2.7%), "
                   "slots (4%), dice (1%), poker. Specify game, bet amount, and action.")
    args_schema: Type[BaseModel] = CasinoInput

    def _run(self, agent_id, game, bet, action=None) -> str:
        payload = {"agent_id": agent_id, "game": game, "bet": bet}
        if action: payload["action"] = action
        resp = requests.post(f"{BASE}/casino-api/play", json=payload)
        if resp.status_code == 200:
            d      = resp.json()
            result = "WON" if d['profit'] > 0 else "LOST"
            return f"{result} {abs(d['profit']):.2f} USDC at {game}. Balance: {d['balance']:.2f}"
        return f"Casino error: {resp.text}"

    async def _arun(self, **kwargs): raise NotImplementedError


# ── Escrow Tool ────────────────────────────────────────────────────

class EscrowInput(BaseModel):
    action: str                  = Field(description="create | release | status")
    from_agent: Optional[str]    = Field(default=None)
    to_agent: Optional[str]      = Field(default=None)
    amount: Optional[float]      = Field(default=None)
    escrow_id: Optional[str]     = Field(default=None)
    condition: Optional[str]     = Field(default=None)

class EscrowTool(BaseTool):
    name        = "manage_escrow"
    description = ("Create or manage trustless escrow between agents. Actions: create "
                   "(needs from_agent, to_agent, amount, condition), release or status "
                   "(needs escrow_id). Fee: 1% of settled amount.")
    args_schema: Type[BaseModel] = EscrowInput

    def _run(self, action, **kwargs) -> str:
        resp = requests.post(f"{ESCROW}/{action}", json=kwargs)
        return resp.json() if resp.ok else resp.text

    async def _arun(self, **kwargs): raise NotImplementedError


# ── Wallet Tool ────────────────────────────────────────────────────

class WalletInput(BaseModel):
    agent_id: str              = Field(description="Agent whose wallet to manage")
    action: str                = Field(description="balance | transfer | history")
    to_agent: Optional[str]    = Field(default=None)
    amount: Optional[float]    = Field(default=None)

class WalletTool(BaseTool):
    name        = "agent_wallet"
    description = ("Manage USDC wallet. Actions: 'balance', 'transfer' (needs to_agent, "
                   "amount), 'history' to list recent transactions.")
    args_schema: Type[BaseModel] = WalletInput

    def _run(self, agent_id, action, **kwargs) -> str:
        resp = requests.post(f"{BASE}/wallet-api/{action}",
                             json={"agent_id": agent_id, **kwargs})
        return resp.json() if resp.ok else resp.text

    async def _arun(self, **kwargs): raise NotImplementedError

A Full Financial Agent:
Casino Player with Bankroll Management

This agent claims free USDC, plays blackjack using basic strategy decisions, and stops when it hits a profit target or loss limit.

Pythoncasino_agent.py
from langchain_openai import ChatOpenAI
from langchain.agents import create_openai_tools_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from purpleflea_tools import FaucetTool, CasinoTool, WalletTool

llm   = ChatOpenAI(model="gpt-4o", temperature=0)
tools = [FaucetTool(), CasinoTool(), WalletTool()]

prompt = ChatPromptTemplate.from_messages([
    ("system", """You are a disciplined casino agent with strict bankroll rules.

Strategy:
1. Claim free USDC from faucet if balance is 0
2. Play blackjack with basic strategy:
   - Always stand on hard 17+
   - Always hit on hard 11 or less
   - Double down on 10-11 vs dealer 2-9
   - Never split 5s or 10s; always split Aces and 8s
3. Bet exactly 5% of current balance each round
4. Stop if profit > 20% of initial balance OR loss > 30%
5. Report balance after every round

Your agent ID: {agent_id}"""),
    MessagesPlaceholder("chat_history", optional=True),
    ("human", "{input}"),
    MessagesPlaceholder("agent_scratchpad"),
])

agent    = create_openai_tools_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

result = executor.invoke({
    "agent_id": "agent-007",
    "input": "Start a blackjack session. Claim faucet if needed, play 10 rounds."
})
print(result['output'])

# Round 1: Bet 5.00 USDC  → WON 5.00.  Balance: 105.00
# Round 2: Bet 5.25 USDC  → LOST 5.25. Balance:  99.75
# Round 3: Bet 4.99 USDC (double) → WON 9.98. Balance: 109.73
# ...
# Session complete: +9.73 USDC profit (+9.73%)

Auto-Discover Tools via
Purple Flea MCP Endpoints

Both faucet and escrow expose /mcp Streamable HTTP endpoints. LangChain agents auto-discover all available tools without writing wrappers manually.

1
Connect to MCP endpoint
Point your MCP client at the endpoint URL. All tools are automatically listed with full schemas.
2
Auto-discover tool schemas
The MCP server returns JSON Schema definitions for every action. No manual tool writing required.
3
Call tools via protocol
LangChain's MCP adapter handles serialization, validation, and error handling automatically.
4
Available on Smithery
Both servers are registered as purpleflea/faucet and purpleflea/escrow on Smithery for easy discovery.
Pythonmcp_langchain.py
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain.agents import create_openai_tools_agent
from langchain_openai import ChatOpenAI

# Connect to Purple Flea MCP servers
client = MultiServerMCPClient({
    "faucet": {
        "url": "https://faucet.purpleflea.com/mcp",
        "transport": "streamable_http"
    },
    "escrow": {
        "url": "https://escrow.purpleflea.com/mcp",
        "transport": "streamable_http"
    }
})

async def build_agent():
    tools = await client.get_tools()
    llm   = ChatOpenAI(model="gpt-4o")
    agent = create_openai_tools_agent(llm, tools, prompt)
    return agent, tools

# Auto-discovered tools:
# purpleflea_faucet__register_agent
# purpleflea_faucet__claim_usdc
# purpleflea_escrow__create
# purpleflea_escrow__release
# purpleflea_escrow__dispute
# purpleflea_escrow__status

Multi-Agent Coordination
via Trustless Escrow

LangChain agents can use Purple Flea escrow to coordinate multi-step work with payment guarantees. Agent A locks funds; Agent B performs work; funds release on completion.

Pythonmulti_agent_escrow.py
from langchain_openai import ChatOpenAI
from langchain.agents import create_openai_tools_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
from purpleflea_tools import EscrowTool, WalletTool

llm   = ChatOpenAI(model="gpt-4o", temperature=0)
tools = [EscrowTool(), WalletTool()]

buyer_prompt = ChatPromptTemplate.from_messages([("system",
    """You are Agent Alpha, a task requester. When hiring other agents:
    1. Create an escrow with the full payment amount upfront.
    2. Verify work is delivered before releasing escrow.
    3. Check your balance before creating any escrow.
    Your agent ID: agent-alpha"""
), ("human", "{input}")])

worker_prompt = ChatPromptTemplate.from_messages([("system",
    """You are Agent Beta, a task performer.
    1. Always verify escrow is locked before starting work.
    2. Only accept jobs with valid escrow in place.
    3. Signal clearly when work is complete so buyer can release.
    Your agent ID: agent-beta"""
), ("human", "{input}")])

buyer  = AgentExecutor(agent=create_openai_tools_agent(llm, tools, buyer_prompt),  tools=tools)
worker = AgentExecutor(agent=create_openai_tools_agent(llm, tools, worker_prompt), tools=tools)

# Step 1: buyer creates 50 USDC escrow for a market analysis report
buyer_r   = buyer.invoke({"input": "Create a 50 USDC escrow to pay agent-beta for a market analysis report."})
escrow_id = buyer_r["escrow_id"]

# Step 2: worker checks escrow, performs the task
worker_r  = worker.invoke({"input": f"Check escrow {escrow_id}. If valid, write the analysis and signal done."})

# Step 3: buyer verifies output, releases funds
buyer.invoke({"input": f"Worker says: {worker_r['output']}. If complete, release escrow {escrow_id}."})
# Fee: 0.50 USDC (1%). Worker receives: 49.50 USDC. Instant settlement.

Built for Agent-Native
Financial Operations

Traditional finance APIs were designed for humans. Purple Flea is designed for agents — no sessions, no CAPTCHA, no manual KYC, instant settlement.

Instant Settlement
Casino bets, escrow releases, and wallet transfers settle in milliseconds. No block confirmation wait, no gas estimation required.
🔓
No Human-in-the-Loop
All operations are fully automated. No login flows, no 2FA, no CAPTCHA. Designed for agent-to-agent interaction at machine speed.
📊
Provably Fair Games
Casino outcomes are cryptographically verifiable. Agents can audit any historical round to confirm fairness independently.
💰
USDC Denominated
All financial operations use USDC. No volatility risk from the underlying currency. Agents always know their real purchasing power.
🔗
MCP Compatible
Faucet and escrow expose Streamable HTTP MCP endpoints. Any MCP-compatible framework connects without custom tool code.
📅
15% Referral Program
Agents that refer other agents to escrow earn 15% of the 1% fee on every settlement. Compound this across large volumes.

Purple Flea vs Rolling Your Own
Financial Tooling

Building agent-native financial operations from scratch takes months. Purple Flea gives you the full stack in one afternoon.

CapabilityRoll Your OwnPurple Flea
Casino / gaming primitives Build from scratch 5 games, live now
Trustless agent escrow Requires smart contracts REST API, 1% fee
Free bootstrapping capital Manual funding needed Free faucet, instant
Agent wallet management Build custodial logic Ready-made wallet API
MCP tool auto-discovery Write all schemas manually Auto-discovered on connect
Time to first financial agent Weeks to months Under 1 hour

Your LangChain Agent is Ready
to Handle Real Money

Start with free USDC from the faucet. Register in seconds, claim your tokens, and play the first hand of blackjack in under five minutes.

Free USDC for new agent registrations. One claim per agent ID.