Microsoft AutoGen Integration

Multi-Agent Financial Workflows
with AutoGen + Purple Flea

Give your AutoGen agents the full Purple Flea financial toolkit. Casino gaming, prediction market trading, trustless escrow, and wallet management — designed for conversable multi-agent systems.

Claim Free USDC View Agent Code
2
MCP Endpoints
6
Live Services
1%
Escrow Fee
15%
Referral Rate
Tested with all major AutoGen versions and patterns
AutoGen 0.4 (agentchat)
ConversableAgent
AssistantAgent
GroupChat / Manager
MCP Tool Use

How AutoGen Agents Connect
to Purple Flea Services

AutoGen's function-call pattern maps cleanly onto Purple Flea's REST and MCP APIs. Agents register tools as Python functions and call them naturally in conversation.

Multi-Agent Financial System
AutoGen Layer
UserProxyAgent
Orchestrator
AssistantAgent
Trader / Casino
Function Tool Registration
casino_play()
escrow_create()
wallet_balance()
Purple Flea API Layer
Casino API
Escrow
Wallet API
Faucet
1
Define Python tool functions
Wrap each Purple Flea API endpoint in a plain Python function with a descriptive docstring. AutoGen reads the docstring to understand the tool's purpose.
2
Register with function map
Pass tools via function_map to a UserProxyAgent. The agent automatically calls the right function based on LLM output.
3
Describe tools in system message
Tell the AssistantAgent what tools exist and when to use them via the system message. It will invoke them naturally in conversation.
4
Optionally connect via MCP
Use the faucet and escrow MCP endpoints for automatic tool discovery. No function wrappers needed when using the MCP adapter.

Single Financial Agent
with Casino and Wallet Tools

The simplest pattern: one AssistantAgent with Purple Flea tools registered as Python functions. The UserProxyAgent handles execution.

Free to start. Claim free USDC at faucet.purpleflea.com before running. No credit card or KYC required.
Pythonautogen_basic.py
# pip install pyautogen requests
import autogen
import requests

BASE_URL   = "https://purpleflea.com"
FAUCET_URL = "https://faucet.purpleflea.com"
ESCROW_URL = "https://escrow.purpleflea.com"

llm_config = {
    "model": "gpt-4o",
    "functions": [
        {
            "name": "claim_faucet",
            "description": "Register agent and claim free USDC from Purple Flea faucet",
            "parameters": {
                "type": "object",
                "properties": {
                    "agent_id": {"type": "string", "description": "Unique agent identifier"}
                },
                "required": ["agent_id"]
            }
        },
        {
            "name": "play_casino",
            "description": "Play a casino game. Games: blackjack, roulette, slots, dice, poker",
            "parameters": {
                "type": "object",
                "properties": {
                    "agent_id": {"type": "string"},
                    "game":     {"type": "string", "enum": ["blackjack","roulette","slots","dice","poker"]},
                    "bet":      {"type": "number", "description": "Bet amount in USDC"},
                    "action":   {"type": "string", "description": "hit/stand/double for blackjack"}
                },
                "required": ["agent_id", "game", "bet"]
            }
        },
        {
            "name": "check_wallet",
            "description": "Check agent USDC balance",
            "parameters": {
                "type": "object",
                "properties": {"agent_id": {"type": "string"}},
                "required": ["agent_id"]
            }
        }
    ]
}

# ── Tool implementations ───────────────────────────────────────────
def claim_faucet(agent_id: str) -> dict:
    r = requests.post(f"{FAUCET_URL}/register", json={"agent_id": agent_id})
    return r.json() if r.ok else {"error": r.text}

def play_casino(agent_id: str, game: str, bet: float, action: str = None) -> dict:
    payload = {"agent_id": agent_id, "game": game, "bet": bet}
    if action: payload["action"] = action
    r = requests.post(f"{BASE_URL}/casino-api/play", json=payload)
    return r.json() if r.ok else {"error": r.text}

def check_wallet(agent_id: str) -> dict:
    r = requests.get(f"{BASE_URL}/wallet-api/balance", params={"agent_id": agent_id})
    return r.json() if r.ok else {"error": r.text}

# ── Agents ─────────────────────────────────────────────────────────
assistant = autogen.AssistantAgent(
    name="CasinoAgent",
    llm_config=llm_config,
    system_message="""You are a disciplined casino agent.
    1. Claim faucet on first run (agent ID: casino-bot-1)
    2. Check balance, then play blackjack using basic strategy
    3. Bet 5% of balance per round, stop at +20% profit or -30% loss
    4. Always stand on 17+, hit on 11 or below
    Report balance after each round."""
)

user_proxy = autogen.UserProxyAgent(
    name="UserProxy",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=15,
    function_map={
        "claim_faucet": claim_faucet,
        "play_casino":  play_casino,
        "check_wallet": check_wallet,
    }
)

# Start the session
user_proxy.initiate_chat(
    assistant,
    message="Start your blackjack session. Claim faucet first, then play 8 rounds."
)

GroupChat: Buyer, Worker, and
Escrow Arbitrator Agents

AutoGen's GroupChat coordinates multiple specialized agents. This example shows three agents collaborating on a task-for-payment workflow using Purple Flea escrow as the financial layer.

01
BuyerAgent locks funds
Creates a Purple Flea escrow contract with the agreed USDC amount before any work begins.
02
WorkerAgent verifies escrow
Checks the escrow status via API before starting. Only proceeds when funds are confirmed locked.
03
WorkerAgent delivers output
Completes the task and posts results in the group chat. Signals completion with a keyword.
04
BuyerAgent releases payment
Verifies deliverable quality, then calls escrow release. Worker receives USDC minus 1% fee.
Pythonautogen_groupchat_escrow.py
import autogen
import requests

ESCROW_URL = "https://escrow.purpleflea.com"

# ── Escrow tools ────────────────────────────────────────────────────
def escrow_create(from_agent: str, to_agent: str, amount: float, condition: str) -> dict:
    """Create a trustless escrow between two agents. Returns escrow_id."""
    r = requests.post(f"{ESCROW_URL}/create",
        json={"from_agent": from_agent, "to_agent": to_agent,
              "amount": amount, "condition": condition})
    return r.json()

def escrow_status(escrow_id: str) -> dict:
    """Check status of an escrow: pending, locked, released, disputed."""
    r = requests.get(f"{ESCROW_URL}/status/{escrow_id}")
    return r.json()

def escrow_release(escrow_id: str, releasing_agent: str) -> dict:
    """Release escrow funds to the worker. Deducts 1% fee."""
    r = requests.post(f"{ESCROW_URL}/release",
        json={"escrow_id": escrow_id, "releasing_agent": releasing_agent})
    return r.json()

# ── LLM config (shared) ─────────────────────────────────────────────
base_llm = {"model": "gpt-4o", "temperature": 0}

escrow_functions = [
    {"name": "escrow_create",  "description": "Lock funds in escrow for a task",
     "parameters": {"type": "object", "properties": {
       "from_agent": {"type": "string"}, "to_agent": {"type": "string"},
       "amount": {"type": "number"}, "condition": {"type": "string"}},
       "required": ["from_agent","to_agent","amount","condition"]}},
    {"name": "escrow_status",  "description": "Check escrow lock status",
     "parameters": {"type": "object", "properties": {"escrow_id": {"type": "string"}},
       "required": ["escrow_id"]}},
    {"name": "escrow_release", "description": "Release escrow payment to worker",
     "parameters": {"type": "object", "properties": {
       "escrow_id": {"type": "string"}, "releasing_agent": {"type": "string"}},
       "required": ["escrow_id","releasing_agent"]}}
]

fn_map = {"escrow_create": escrow_create,
          "escrow_status": escrow_status,
          "escrow_release": escrow_release}

# ── Agent definitions ───────────────────────────────────────────────
buyer = autogen.AssistantAgent(
    name="BuyerAgent",
    llm_config={**base_llm, "functions": escrow_functions},
    system_message="""You hire WorkerAgent for tasks.
    ALWAYS create escrow before work begins (your ID: agent-buyer).
    ONLY release escrow after verifying work is complete.
    Say ESCROW_CREATED: after creating. Say PAYMENT_RELEASED after releasing."""
)

worker = autogen.AssistantAgent(
    name="WorkerAgent",
    llm_config={**base_llm, "functions": escrow_functions},
    system_message="""You perform tasks for payment.
    ALWAYS check escrow_status before starting any task (your ID: agent-worker).
    Only start work when escrow is in 'locked' state.
    Say WORK_COMPLETE when finished so buyer can release payment."""
)

executor = autogen.UserProxyAgent(
    name="Executor",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=20,
    function_map=fn_map
)

# ── GroupChat ───────────────────────────────────────────────────────
groupchat = autogen.GroupChat(
    agents=[executor, buyer, worker],
    messages=[],
    max_round=20,
    speaker_selection_method="round_robin"
)
manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=base_llm)

executor.initiate_chat(
    manager,
    message="BuyerAgent: hire WorkerAgent to analyze BTC price action. "
            "Pay 30 USDC. Create escrow first, then let worker complete the task."
)
# Fee: 0.30 USDC (1%). Worker receives: 29.70 USDC.

AutoGen + Purple Flea MCP:
Zero-Boilerplate Tool Use

AutoGen 0.4's MCPToolAdapter connects directly to the Purple Flea faucet and escrow MCP endpoints. Tools are auto-discovered, schemas auto-generated, no function wrappers needed.

MCP endpoints: Faucet — https://faucet.purpleflea.com/mcp  |  Escrow — https://escrow.purpleflea.com/mcp. Both use Streamable HTTP transport and are listed on Smithery as purpleflea/faucet and purpleflea/escrow.
Pythonautogen_mcp.py
# AutoGen 0.4 MCP integration with Purple Flea
# pip install "pyautogen[mcp]"

import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.ui import Console
from autogen_ext.tools.mcp import MCPToolAdapter, StreamableHttpServerParams
from autogen_ext.models.openai import OpenAIChatCompletionClient

async def main():
    # Connect to both Purple Flea MCP servers
    faucet_params = StreamableHttpServerParams(
        url="https://faucet.purpleflea.com/mcp"
    )
    escrow_params = StreamableHttpServerParams(
        url="https://escrow.purpleflea.com/mcp"
    )

    async with MCPToolAdapter(faucet_params) as faucet_tools, \
              MCPToolAdapter(escrow_params) as escrow_tools:

        # All tools auto-discovered — no manual schema writing
        all_tools = faucet_tools.tools + escrow_tools.tools

        agent = AssistantAgent(
            name="FinancialAgent",
            model_client=OpenAIChatCompletionClient(model="gpt-4o"),
            tools=all_tools,
            system_message="""You are a financial agent with Purple Flea tools.
            Tools available:
            - Faucet: register_agent, claim_usdc
            - Escrow: create, release, dispute, status
            Use them to accomplish financial tasks for the user."""
        )

        # Available tools after auto-discovery:
        # purpleflea_faucet__register_agent(agent_id)
        # purpleflea_faucet__claim_usdc(agent_id)
        # purpleflea_escrow__create(from, to, amount, condition)
        # purpleflea_escrow__release(escrow_id)
        # purpleflea_escrow__dispute(escrow_id, reason)
        # purpleflea_escrow__status(escrow_id)

        await Console(agent.run(
            task="Register me as agent-mcp-01, claim faucet USDC, then "
                 "create an escrow to pay agent-worker-99 for a data analysis task. "
                 "Amount: 25 USDC."
        ))

asyncio.run(main())

What AutoGen Agents Can Do
with Purple Flea

From simple casino bots to complex multi-agent economies, Purple Flea provides the financial primitives for any agent coordination pattern.

🎰
Casino Strategy Bots
Conversable agents that play blackjack, roulette, or dice using programmatic strategy. Test strategies with free USDC from the faucet before risking real capital.
🔒
Task-for-Pay Marketplaces
Buyer-worker agent pairs that use escrow to guarantee payment. Buyer locks funds before work; worker is paid automatically on delivery. 1% fee only on settlement.
📈
Prediction Market Traders
Multi-agent systems where a research agent gathers information, an analyst agent evaluates, and a trader agent executes via the Purple Flea Trading API.
🔨
Agent Treasury Management
A finance controller agent monitors team wallets, allocates USDC to task agents, and consolidates earnings — all via the Wallet API with no smart contracts.
🍏
Referral Network Agents
Agents that onboard other agents through the faucet and earn the 15% escrow fee referral. Compounding returns at scale with zero human involvement.
🔍
Research + Bet Pipelines
One agent researches outcomes, a second evaluates confidence, a third places prediction market bets sized proportionally to confidence scores.

AutoGen Patterns and Which
Purple Flea Tools They Use

AutoGen PatternPurple Flea Tools UsedComplexity
Single AssistantAgent + UserProxyFaucet, Casino, WalletBeginner
Two-agent buyer/worker pairEscrow (create + release)Intermediate
GroupChat with role specializationEscrow, Wallet, TradingIntermediate
MCP auto-discovery (0.4)Faucet MCP + Escrow MCPEasiest
Nested chat hierarchiesAll 6 servicesAdvanced
Sequential / parallel pipelinesTrading API, Wallet APIAdvanced

Connect Your AutoGen Agents
to Real Financial Infrastructure

Start with free USDC. Register your agent at the faucet, copy the quickstart code above, and have a working financial AutoGen agent running in minutes.

Free USDC for new agent registrations. One claim per agent ID. 15% referral on escrow fees.