Google Vertex AI
+
🟣 Purple Flea

Integrate Purple Flea
with Google Vertex AI

Give your Vertex AI agents real economic capabilities — casino, perpetual trading, crypto wallets, trustless escrow, and domain management. Six production-ready financial APIs, one registration.

Enterprise AI Meets Autonomous Finance

Google Vertex AI provides enterprise-grade model hosting, IAM, and audit trails. Purple Flea provides the financial rails for agents to act. Together your agents move from reasoning to real economic action.

🏢

Enterprise Auth Compatibility

Purple Flea Bearer tokens map cleanly to Vertex AI service account permissions. Add Purple Flea keys to Secret Manager and inject at runtime.

🛠️

Native Function Calling

Every Purple Flea action maps to a Vertex AI FunctionDeclaration. Gemini models natively understand how to invoke casino, trading, and escrow tools.

🔌

MCP Protocol Support

All six Purple Flea services expose StreamableHTTP MCP endpoints. Vertex AI agents using MCP can connect to the full suite with a single config block.

📊

Audit-Ready Logs

Every API call is timestamped and attributable to an agent ID. Export to BigQuery or Cloud Logging for compliance and fleet-level analysis.

Low Latency

Purple Flea responds in under 120ms p95. Fast enough for Gemini streaming tool calls to complete without noticeable latency in agentic loops.

🌐

Multi-Agent Fleet Support

Register a fleet of Vertex AI agents under one Purple Flea account, each with isolated API keys, balances, and trade histories.

Python Quickstart

Get a Vertex AI Gemini agent placing casino bets and checking balances in under 50 lines of Python.

ℹ️
Prerequisites: pip install google-cloud-aiplatform requests python-dotenv and a Google Cloud project with Vertex AI API enabled. Store your Purple Flea key as PURPLEFLEA_API_KEY in Secret Manager or a local .env file.
quickstart.py
import os, json, requests
import vertexai
from vertexai.generative_models import GenerativeModel, Tool, FunctionDeclaration
from dotenv import load_dotenv

load_dotenv()

# ── Configure ──────────────────────────────────────────────
vertexai.init(project=os.environ["GCP_PROJECT"], location="us-central1")

PF_KEY  = os.environ["PURPLEFLEA_API_KEY"]   # pf_live_...
PF_BASE = "https://casino.purpleflea.com/v1"
HEADERS = {"Authorization": f"Bearer {PF_KEY}", "Content-Type": "application/json"}

# ── Define Purple Flea tools ───────────────────────────────
casino_bet = FunctionDeclaration(
    name="place_casino_bet",
    description="Place a bet on the Purple Flea casino (coinflip, crash, or dice)",
    parameters={
        "type": "object",
        "properties": {
            "game":       {"type": "string", "enum": ["coinflip", "crash", "dice"]},
            "amount":     {"type": "number", "description": "Bet amount in USD"},
            "prediction": {"type": "string", "description": "heads/tails, crash multiplier, over/under"}
        },
        "required": ["game", "amount", "prediction"]
    }
)

get_balance = FunctionDeclaration(
    name="get_balance",
    description="Get the current balance of this agent's Purple Flea wallet",
    parameters={"type": "object", "properties": {}}
)

pf_tools = Tool(function_declarations=[casino_bet, get_balance])

# ── Tool executor ──────────────────────────────────────────
def execute_tool(name: str, args: dict) -> dict:
    if name == "get_balance":
        r = requests.get(f"{PF_BASE}/balance", headers=HEADERS, timeout=5)
        return r.json()
    elif name == "place_casino_bet":
        r = requests.post(f"{PF_BASE}/bet", json=args, headers=HEADERS, timeout=10)
        return r.json()
    return {"error": "unknown tool"}

# ── Run agentic loop ───────────────────────────────────────
model = GenerativeModel("gemini-2.0-flash-001", tools=[pf_tools])
chat  = model.start_chat()

response = chat.send_message(
    "Check my balance, then place a $1 coinflip bet predicting heads."
)

# Handle tool calls
while response.candidates[0].finish_reason.name == "TOOL_CALLS":
    tool_call = response.candidates[0].content.parts[0].function_call
    result    = execute_tool(tool_call.name, dict(tool_call.args))
    response  = chat.send_message([{"function_response": {"name": tool_call.name, "response": result}}])

print(response.text)

ReAct Trading Agent

A full ReAct-pattern agent that uses Vertex AI to analyze market conditions, then executes trades on Purple Flea Trading's perpetual futures API.

react_trader.py
import os, time, requests, vertexai
from vertexai.generative_models import GenerativeModel, Tool, FunctionDeclaration, Part

vertexai.init(project=os.environ["GCP_PROJECT"], location="us-central1")
PF_KEY  = os.environ["PURPLEFLEA_API_KEY"]
HEADERS = {"Authorization": f"Bearer {PF_KEY}", "Content-Type": "application/json"}
TRADE   = "https://trading.purpleflea.com/v1"

# ── Tool declarations ──────────────────────────────────────
tools = Tool(function_declarations=[
    FunctionDeclaration(
        name="get_market_data",
        description="Fetch current OHLCV price data and order book for a trading pair",
        parameters={
            "type": "object",
            "properties": {
                "pair":     {"type": "string", "description": "e.g. BTC-USDT, ETH-USDT"},
                "interval": {"type": "string", "enum": ["1m","5m","15m","1h"]},
                "limit":    {"type": "integer", "description": "Number of candles (max 200)"}
            },
            "required": ["pair"]
        }
    ),
    FunctionDeclaration(
        name="open_position",
        description="Open a leveraged perpetual futures position on Purple Flea Trading",
        parameters={
            "type": "object",
            "properties": {
                "pair":       {"type": "string"},
                "side":       {"type": "string", "enum": ["long", "short"]},
                "size_usd":   {"type": "number", "description": "Position size in USD"},
                "leverage":   {"type": "integer", "description": "Leverage 1-20x"},
                "stop_loss":  {"type": "number", "description": "Stop loss price"},
                "take_profit":{"type": "number", "description": "Take profit price"}
            },
            "required": ["pair", "side", "size_usd", "leverage"]
        }
    ),
    FunctionDeclaration(
        name="get_positions",
        description="List all open positions for this agent",
        parameters={"type": "object", "properties": {}}
    ),
    FunctionDeclaration(
        name="close_position",
        description="Close an open position by position_id",
        parameters={
            "type": "object",
            "properties": {"position_id": {"type": "string"}},
            "required": ["position_id"]
        }
    )
])

# ── Tool executor ──────────────────────────────────────────
def execute(name: str, args: dict) -> dict:
    if name == "get_market_data":
        return requests.get(f"{TRADE}/market/{args['pair']}/ohlcv",
            params={"interval": args.get("interval","1h"), "limit": args.get("limit",50)},
            headers=HEADERS, timeout=5).json()
    elif name == "open_position":
        return requests.post(f"{TRADE}/positions", json=args, headers=HEADERS, timeout=10).json()
    elif name == "get_positions":
        return requests.get(f"{TRADE}/positions", headers=HEADERS, timeout=5).json()
    elif name == "close_position":
        return requests.delete(f"{TRADE}/positions/{args['position_id']}", headers=HEADERS, timeout=10).json()
    return {"error": "unknown tool"}

SYSTEM_PROMPT = """You are a disciplined trading agent operating on Purple Flea.
Rules:
- Never risk more than 2% of wallet balance per trade
- Always set a stop-loss at entry price minus 1.5%
- Use max 5x leverage
- Analyze market data before opening any position
- Close losing positions when stop-loss is hit; do not move stop-losses wider"""

# ── Agentic loop ───────────────────────────────────────────
model = GenerativeModel("gemini-2.0-flash-001", tools=[tools], system_instruction=SYSTEM_PROMPT)
chat  = model.start_chat()

print("Starting ReAct trading cycle...")
response = chat.send_message(
    "Analyze BTC-USDT 1h data for the last 50 candles. "
    "Check open positions. If no open BTC position and trend looks bullish, open a long. "
    "If there are losing positions beyond stop-loss, close them."
)

while response.candidates[0].finish_reason.name == "TOOL_CALLS":
    part      = response.candidates[0].content.parts[0]
    tool_name = part.function_call.name
    tool_args = dict(part.function_call.args)
    print(f"  → Calling {tool_name}({tool_args})")
    result    = execute(tool_name, tool_args)
    response  = chat.send_message(
        [Part.from_function_response(name=tool_name, response=result)]
    )

print("Agent decision:", response.text)

MCP Integration with Vertex AI Agents

Purple Flea exposes all six services as StreamableHTTP MCP endpoints. Vertex AI agents supporting the Model Context Protocol can connect to the full suite with a single configuration block.

mcp_config.json — add to your Vertex AI agent config
{
  "mcpServers": {
    "purpleflea-faucet": {
      "url": "https://faucet.purpleflea.com/mcp",
      "transport": "streamable-http",
      "headers": {
        "Authorization": "Bearer ${PURPLEFLEA_API_KEY}"
      }
    },
    "purpleflea-escrow": {
      "url": "https://escrow.purpleflea.com/mcp",
      "transport": "streamable-http",
      "headers": {
        "Authorization": "Bearer ${PURPLEFLEA_API_KEY}"
      }
    }
  }
}
🔌
Generate your full MCP config — use our MCP Config Generator to build a config for all six services with your API key pre-filled.

Faucet MCP — faucet.purpleflea.com/mcp

Tools: register_agent, claim_faucet. New Vertex AI agents get free credits to start without any wallet funding.

Escrow MCP — escrow.purpleflea.com/mcp

Tools: create_escrow, confirm_receipt, refund_expired. Trustless agent-to-agent payments with 1% fee and 15% referral.

Enterprise Features

Purple Flea is built for production agent deployments at scale. These capabilities are available to all registered agents and integrate cleanly with Google Cloud's enterprise tooling.

📋

Structured Audit Logs

Every API call is logged with agent ID, timestamp, endpoint, request hash, and response status. Export via Pub/Sub or pull via /v1/logs endpoint into BigQuery.

📦

Compliance Export

Generate a signed JSON export of all transactions for any date range. Useful for financial audits, tax reporting, or feeding into Vertex AI datasets for agent performance analysis.

🚀

Fleet Management

Register up to 1,000 sub-agents under one parent key. Set per-agent spending limits, isolate balances, and monitor fleet-level P&L from a single API call.

🔔

Webhooks

Receive real-time POST callbacks to your Cloud Run service or Cloud Functions endpoint on trade fills, balance thresholds, or escrow state changes.

Rate Limits and Service SLAs

All limits are per API key. Contact us if your Vertex AI fleet needs higher throughput.

100
Requests / minute
<120ms
p95 latency
99.5%
Uptime SLA
TLS 1.3
Transport security
Endpoint Method Limit Notes
/v1/bet POST 60/min Casino bets
/v1/positions POST 30/min New trade positions
/v1/market/* GET 100/min Market data reads
/v1/escrow POST 30/min Escrow creation
/mcp POST 100/min MCP StreamableHTTP
429 handling: When rate limited, the response includes Retry-After: N (seconds). Build this into your Vertex AI tool executor with exponential backoff.

Register Your Vertex AI Agent

Register once and get access to all six Purple Flea services. The registration endpoint returns a pf_live_ API key immediately.

Register via curl
curl -X POST https://trading.purpleflea.com/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "agent_name": "my-vertex-trader",
    "agent_type": "trading",
    "platform": "google-vertex-ai",
    "model": "gemini-2.0-flash-001"
  }'

# Response:
# {
#   "agent_id":  "agt_abc123",
#   "api_key":   "pf_live_...",
#   "balance":   0,
#   "faucet_url": "https://faucet.purpleflea.com"
# }
🟣
First time? After registering, visit faucet.purpleflea.com to claim free credits for your new Vertex AI agent — no wallet required to get started.