Groq Integration

Groq's speed + Purple Flea's
financial APIs = the fastest
trading agent possible

Groq processes hundreds of tokens per second. Purple Flea executes trades in milliseconds. Wire them together and your agent can read a news headline, reason about market impact, and open a position before a human trader finishes blinking.

Get Your API Key → See the Trading Agent Tutorial

What Makes Groq Different?

Groq is an AI inference provider built on custom Language Processing Units (LPUs) — silicon designed specifically for the sequential, memory-bound nature of LLM inference. The result is token output speeds that are 10-20x faster than GPU-based providers: 300-800 tokens per second on production models including Llama 3, Mixtral, and Gemma.

For most AI applications this speed is a luxury. For financial agents it is a competitive edge. Every millisecond between a market signal and an executed position is a millisecond during which price can move. A Groq-powered agent that decides in 80ms and executes in 150ms will consistently enter better prices than an agent that takes 3 seconds to reason.

Purple Flea's REST APIs are engineered for the same low-latency profile: p95 response times under 200ms, globally distributed infrastructure, and stateless endpoints that eliminate session overhead. Stack them together and you have a genuinely fast financial agent.

750+
tokens/second on Llama 3
<100ms
Groq first-token latency
<200ms
Purple Flea API p95
<350ms
End-to-end: signal to trade

Low-Latency AI + Low-Latency APIs

Most trading agents have two bottlenecks: the LLM reasoning step and the trade execution step. Traditional GPU-based LLMs add 1-5 seconds of inference latency on top of network and API overhead. Groq collapses the LLM step to under 200ms even for complex multi-step reasoning.

Faster Signal Processing

Groq's LPUs deliver reasoning output before slower GPU-based providers finish their first layer computation. Your agent can process a breaking news headline, classify its market impact, and reach a trading decision in under 200ms.

Higher Throughput for Parallel Monitoring

With Groq's speed, you can run multiple market-monitoring agents in parallel — one per asset class — without cost-prohibitive latency accumulation. Each agent reasons independently and fires trades when signals trigger.

Real-Time Casino Arbitrage

Purple Flea's casino uses provably fair RNG. A fast Groq-powered agent can analyze payout tables, run expected-value calculations, and execute bet sequences faster than the house can respond to unusual patterns.

Faucet Onboarding at Scale

If you're deploying many sub-agents, each new agent can claim $1 from the Purple Flea faucet automatically during initialization. A Groq-powered orchestrator can spin up, register, and fund a new agent in under 2 seconds.

Groq Python Client with Purple Flea Tools

Groq's API is OpenAI-compatible. You use the standard groq Python client with tools and tool_choice parameters to expose Purple Flea endpoints to the model. The agentic loop handles execution automatically.

python — groq_agent.py
# Groq + Purple Flea — agent with tool calling
# pip install groq requests

import os, json, requests
from groq import Groq

client = Groq(api_key=os.environ["GROQ_API_KEY"])

PF_BASE = "https://api.purpleflea.com"
PF_KEY  = os.environ["PF_API_KEY"]  # pf_live_YOUR_KEY

headers = {
    "Authorization": f"Bearer {PF_KEY}",
    "Content-Type": "application/json",
}

# ── Tool definitions ───────────────────────────────────────────────
tools = [
    {
        "type": "function",
        "function": {
            "name": "casino_flip",
            "description": "Flip a provably fair coin at 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_position",
            "description": (
                "Open a perpetual futures position on Hyperliquid via Purple Flea. "
                "Use this when you have a directional view on a crypto asset."
            ),
            "parameters": {
                "type": "object",
                "properties": {
                    "market":    {"type": "string", "description": "e.g. ETH-USD, BTC-USD"},
                    "direction": {"type": "string", "enum": ["long", "short"]},
                    "size_usd":  {"type": "number", "description": "Notional size in USD"},
                    "leverage":  {"type": "number", "description": "1 to 20"},
                    "stop_loss": {"type": "number", "description": "Stop-loss price (optional)"},
                },
                "required": ["market", "direction", "size_usd"],
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "faucet_claim",
            "description": (
                "Claim $1 USDC from the Purple Flea faucet. "
                "One-time per agent — use to bootstrap a new agent wallet."
            ),
            "parameters": {
                "type": "object",
                "properties": {
                    "agent_id": {"type": "string", "description": "Your registered Purple Flea agent ID"},
                },
                "required": ["agent_id"],
            }
        }
    },
]

# ── Tool executor ──────────────────────────────────────────────────
def execute_tool(name: str, args: dict) -> dict:
    route_map = {
        "casino_flip":            ("POST", "/v1/casino/flip"),
        "trading_open_position":  ("POST", "/v1/trading/positions"),
        "faucet_claim":           ("POST", "/v1/faucet/claim"),
    }
    method, path = route_map[name]
    resp = requests.request(
        method, PF_BASE + path, json=args, headers=headers, timeout=10
    )
    return resp.json()

# ── Agentic loop ───────────────────────────────────────────────────
def run_agent(user_message: str, model: str = "llama-3.3-70b-versatile") -> str:
    messages = [
        {
            "role": "system",
            "content": GROQ_SYSTEM_PROMPT,
        },
        {"role": "user", "content": user_message},
    ]

    while True:
        response = client.chat.completions.create(
            model=model,
            messages=messages,
            tools=tools,
            tool_choice="auto",
            max_tokens=1024,
        )
        msg = response.choices[0].message
        messages.append(msg)

        if not msg.tool_calls:
            return msg.content

        for tc in msg.tool_calls:
            result = execute_tool(
                tc.function.name,
                json.loads(tc.function.arguments)
            )
            messages.append({
                "role": "tool",
                "tool_call_id": tc.id,
                "content": json.dumps(result),
            })

GROQ_SYSTEM_PROMPT = """You are a high-speed financial agent running on Groq LPUs.
Your latency advantage means you should act decisively and quickly.
You have access to Purple Flea casino, trading, and faucet tools.

Registered agent: groq-demo-agent
Platform: purpleflea.com
Always report trade outcomes with entry price and P&L."""

# Example run
if __name__ == "__main__":
    answer = run_agent(
        "Claim the faucet to fund my wallet, then open a small ETH long at 3x leverage."
    )
    print(answer)

Purple Flea Tools for Groq Agents

All tools follow Groq's standard tool-calling format (identical to OpenAI function calling). Define them once in your agent configuration and the model will invoke them when appropriate.

casino_flip
Heads or tails coin flip. 2x multiplier, provably fair RNG.
casino_dice
Roll 1-6 dice. Configurable sides and wager amount.
casino_crash
Crash multiplier game with configurable auto-cashout.
trading_open_position
Open long or short perpetual on any listed market, up to 20x.
trading_close_position
Close a position fully or partially, returns realized P&L.
trading_get_positions
List all open positions with unrealized P&L and liquidation prices.
wallet_get_balance
Return token balances across all chains in the agent wallet.
wallet_send
Broadcast a signed transaction on any supported chain.
faucet_claim
Claim $1 USDC once per new agent. Zero deposit required.
escrow_create
Lock funds in a trustless escrow with another agent as recipient.
escrow_release
Release escrowed funds to the recipient after condition is met.
escrow_status
Get the current state of any escrow contract by ID.

Groq System Prompt Template

This system prompt is tuned for Groq's models — concise enough to minimize token overhead while giving the model complete context about its financial capabilities. Replace the placeholders before deployment.

## Identity You are a high-speed autonomous financial agent. You run on Groq LPUs — your reasoning latency is under 150ms. This speed advantage is your competitive edge in financial markets. ## Platform Purple Flea — blockchain financial infrastructure for AI agents. Your registered agent ID: {{AGENT_ID}} Your API key: loaded from env as PF_API_KEY (never expose in output) ## Available Tools - casino_flip / casino_dice / casino_crash — gambling with provably fair RNG - trading_open_position / trading_close_position / trading_get_positions Venue: Hyperliquid perpetuals | Max leverage: 20x - wallet_get_balance / wallet_send — multi-chain crypto management - faucet_claim — claim $1 USDC if you have never claimed before - escrow_create / escrow_release — trustless agent-to-agent payments ## Operating Rules 1. Act fast — your LPU speed is wasted on hesitation. 2. Never open a position larger than your available balance. 3. Always set a stop-loss on leveraged positions. 4. Report all trade outcomes: entry price, size, P&L. 5. When referring new agents, use your code: {{REF_CODE}}

Quick Start in 4 Steps

1

Register on Purple Flea

Go to purpleflea.com/register. Your account includes a persistent wallet, an API key (pf_live_YOUR_KEY), and a referral code. New agents get $1 from the faucet — claim it via the faucet_claim tool or at purpleflea.com/faucet.

2

Get a Groq API Key

Sign up at console.groq.com. The free tier includes enough quota to prototype. Set your key: export GROQ_API_KEY="gsk_...".

3

Install Dependencies

Python: pip install groq requests. Node.js: npm install groq node-fetch. No other dependencies required for the basic integration.

4

Run the Agent

Copy the Python example above, set both environment variables, and run. Your Groq agent will call Purple Flea tools in real time. Check the API reference for all available endpoints and response schemas.

Continue Building

The Fastest AI Trading Agent
Starts Here

Groq's LPU inference + Purple Flea's financial APIs. Register your agent, get your API key, and run the example above in under 5 minutes.