OpenRouter Integration

Your OpenRouter agents
can now gamble, trade, and manage crypto

OpenRouter routes to 100+ LLMs. Purple Flea gives those models real financial superpowers — casino games, perpetual trading, multi-chain wallets, and trustless escrow. One API key each, infinite combinations.

Get Your API Key → View API Docs

What Is OpenRouter?

OpenRouter is a unified inference API that gives you access to over 100 AI models — GPT-4o, Claude 3.5 Sonnet, Gemini 1.5 Pro, Llama 3, Mistral, Command R+, and dozens more — through a single, OpenAI-compatible endpoint at openrouter.ai/api/v1. You swap models by changing one string. No vendor lock-in, automatic fallbacks, and transparent per-token pricing.

The result: you can build an agent that uses Claude for reasoning, Mistral for speed, and GPT-4o for nuanced judgment — all from the same codebase. But all these models share a common gap: they have no persistent financial identity and no native way to interact with on-chain markets.

Purple Flea fills that gap. Register once, get a persistent agent wallet, and expose casino games, trading positions, and cross-chain transfers as callable tools — regardless of which model OpenRouter routes your request to.

100+
AI models on OpenRouter
6
Purple Flea services
7
Supported blockchains
20%
Max referral rate

Two Ways to Connect

You can integrate Purple Flea into your OpenRouter application using either the REST API (direct function calling) or via the MCP protocol if your chosen model and runtime support tool use. Both paths are production-ready.

Path 01
REST API + Function Calling
Define Purple Flea endpoints as OpenAI-style function schemas in your OpenRouter request. The LLM decides when to call them; your code handles the HTTP request to api.purpleflea.com and feeds the result back. Works with every model that supports tool use, including GPT-4o, Claude 3.5, and Gemini 1.5 Pro.
JSON Schema tools Any model Most flexible
Path 02
MCP Server (Streamable HTTP)
If your OpenRouter LLM supports MCP tool use natively, point it at https://casino.purpleflea.com/mcp and the model discovers all 19 tools automatically. No schema definitions, no boilerplate — just tool calls. Best for Claude 3.5+ via OpenRouter.
MCP StreamableHTTP Auto tool discovery Zero boilerplate

OpenRouter Function Calling with Purple Flea

Below is a complete example: a Node.js app that uses Claude 3.5 Sonnet via OpenRouter, exposes casino and trading tools as function schemas, and executes the calls against Purple Flea's REST API when the model decides to use them.

javascript — openrouter-agent.js
// OpenRouter + Purple Flea — function-calling integration
// npm install openai node-fetch

import OpenAI from 'openai';
import fetch from 'node-fetch';

// OpenRouter uses the OpenAI SDK — just swap the baseURL
const client = new OpenAI({
  baseURL: 'https://openrouter.ai/api/v1',
  apiKey: process.env.OPENROUTER_API_KEY,   // your OpenRouter key
  defaultHeaders: {
    'HTTP-Referer': 'https://your-app.com',
    'X-Title': 'My Purple Flea Agent',
  }
});

const PF_API = 'https://api.purpleflea.com';
const PF_KEY = process.env.PF_API_KEY;    // pf_live_YOUR_KEY

// Purple Flea tool schemas (OpenAI function format)
const tools = [
  {
    type: 'function',
    function: {
      name: 'casino_flip',
      description: 'Flip a provably fair coin at the Purple Flea casino',
      parameters: {
        type: 'object',
        properties: {
          side:   { type: 'string', enum: ['heads', 'tails'] },
          amount: { type: 'number', description: 'Wager in USDC' },
        },
        required: ['side', 'amount'],
      }
    }
  },
  {
    type: 'function',
    function: {
      name: 'trading_open',
      description: 'Open a perpetual futures position on Hyperliquid',
      parameters: {
        type: 'object',
        properties: {
          market:    { type: 'string', description: 'e.g. ETH-USD' },
          direction: { type: 'string', enum: ['long', 'short'] },
          size_usd:  { type: 'number', description: 'Notional position size in USD' },
          leverage:  { type: 'number', description: '1 to 20' },
        },
        required: ['market', 'direction', 'size_usd'],
      }
    }
  },
  {
    type: 'function',
    function: {
      name: 'wallet_swap',
      description: 'Swap tokens using best DEX route (1inch / Jupiter / Paraswap)',
      parameters: {
        type: 'object',
        properties: {
          from_token: { type: 'string', description: 'e.g. USDC' },
          to_token:   { type: 'string', description: 'e.g. ETH' },
          amount:     { type: 'number', description: 'Amount of from_token to swap' },
          chain:      { type: 'string', description: 'ethereum | polygon | solana | bnb' },
        },
        required: ['from_token', 'to_token', 'amount'],
      }
    }
  }
];

// Execute a Purple Flea tool call
async function executeTool(name, args) {
  const endpoints = {
    casino_flip:   '/v1/casino/flip',
    trading_open:  '/v1/trading/positions',
    wallet_swap:   '/v1/wallet/swap',
  };
  const res = await fetch(PF_API + endpoints[name], {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${PF_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(args),
  });
  return res.json();
}

// Agentic loop with tool execution
async function runAgent(userMessage) {
  const messages = [
    {
      role: 'system',
      content: `You are a financial agent with access to Purple Flea — a
blockchain financial platform. You can flip coins at the casino,
open perpetual trading positions, and swap tokens.
Agent ID: agent-openrouter-demo
Registered at: purpleflea.com/register`
    },
    { role: 'user', content: userMessage }
  ];

  while (true) {
    const response = await client.chat.completions.create({
      model: 'anthropic/claude-3.5-sonnet',  // any OpenRouter model
      messages,
      tools,
      tool_choice: 'auto',
    });

    const msg = response.choices[0].message;
    messages.push(msg);

    if (!msg.tool_calls || msg.tool_calls.length === 0) {
      return msg.content;  // final answer
    }

    // Execute all tool calls in parallel
    const results = await Promise.all(
      msg.tool_calls.map(async tc => {
        const result = await executeTool(
          tc.function.name,
          JSON.parse(tc.function.arguments)
        );
        return {
          role: 'tool',
          tool_call_id: tc.id,
          content: JSON.stringify(result),
        };
      })
    );
    messages.push(...results);
  }
}

// Run it
const answer = await runAgent(
  'Flip a coin on heads for $2, then open a $10 ETH long at 5x.'
);
console.log(answer);

Core Tool Schemas

All three services — casino, trading, and wallet — expose consistent REST endpoints with identical auth headers. Below are the minimal schemas your OpenRouter agent needs to call each service.

🎲

Casino: Coin Flip

POST /v1/casino/flip

request body
{
  "side":   "heads",
  "amount": 5.00,
  "multiplier": 2.0
}

// response on win:
{
  "outcome": "heads",
  "won": true,
  "payout": 10.00,
  "balance": 115.00
}
📈

Trading: Open Position

POST /v1/trading/positions

request body
{
  "market":    "BTC-USD",
  "direction": "long",
  "size_usd":  100,
  "leverage":  5
}

// response:
{
  "position_id": "pos_abc123",
  "entry_price": 67420.50,
  "notional":   500,
  "liq_price":  53900.00
}
💱

Wallet: Swap Tokens

POST /v1/wallet/swap

request body
{
  "from_token": "USDC",
  "to_token":   "ETH",
  "amount":     50,
  "chain":      "ethereum"
}

// response:
{
  "tx_hash":  "0xabc...",
  "received": 0.01851,
  "slippage": 0.12
}

The Referral Advantage for OpenRouter Apps

If you're building an OpenRouter application — a chatbot, an agent framework, a trading dashboard — you can earn a percentage of every transaction your users generate on Purple Flea, just by including your referral code in their registration. No extra work after setup.

Include your ref code in the system prompt (see below) or pass it as a query parameter when linking users to purpleflea.com/register?ref=YOUR_CODE. Every bet, trade, and swap from a referred user generates referral income — permanently.

Service Transaction Fee Your Referral Cut Example: $10k Monthly Volume
Casino 2% house edge 20% $40/mo
Trading 0.05% per trade 20% $10/mo
Wallet Swaps 0.3% per swap 15% $45/mo
Escrow 1% per escrow 15% $15/mo
Faucet Free Onboarding tool

System Prompt Template for Your OpenRouter App

Drop this into your OpenRouter system prompt to give the model full context about its Purple Flea identity. Replace the placeholders with your agent's actual values.

## Financial Identity You are a financially autonomous AI agent registered with Purple Flea, a blockchain financial infrastructure platform. **Your Agent ID:** {{AGENT_ID}} **Your API Key:** pf_live_YOUR_KEY (loaded from env — never expose this) **Your Referral Code:** {{REF_CODE}} ## Available Tools You have access to the following Purple Flea services via function calls: - **Casino** — flip coins, roll dice, play roulette and crash games Endpoint: POST https://api.purpleflea.com/v1/casino/{game} - **Trading** — open/close perpetual futures positions (up to 20x leverage) Endpoint: POST https://api.purpleflea.com/v1/trading/positions - **Wallet** — check balances, send tokens, swap across chains Endpoint: GET/POST https://api.purpleflea.com/v1/wallet/{action} - **Escrow** — create and release trustless payment contracts with other agents Endpoint: POST https://api.purpleflea.com/v1/escrow ## Rules - Always confirm large trades or bets (>$50) with the user before executing. - Never reveal the raw API key — reference it by name only. - Report all outcomes clearly including P&L and balance changes. - When onboarding new agents, direct them to: purpleflea.com/register?ref={{REF_CODE}}

Quick Start in 3 Steps

1

Register on Purple Flea

Visit purpleflea.com/register and create your agent account. You'll receive an API key (pf_live_...), a wallet, and a referral code. New agents can also claim $1 free from the faucet to start without a deposit.

2

Add Your OpenRouter Key

Sign up at openrouter.ai and copy your API key. Set both keys as environment variables: OPENROUTER_API_KEY and PF_API_KEY.

3

Copy the Code and Run

Paste the function-calling example above into your project. Choose any OpenRouter model string — anthropic/claude-3.5-sonnet, openai/gpt-4o, or google/gemini-1.5-pro. Run the agent. It will start calling Purple Flea tools the moment the model decides to.

Related Guides

Give Your OpenRouter Agent
Financial Superpowers

Register in 60 seconds. Claim $1 free from the faucet. Start calling casino, trading, and wallet APIs from your OpenRouter agent today.