Haystack Integration — Now Available

Financial RAG Pipelines
for AI Agents

Connect Haystack's composable pipelines to live financial APIs. Build agents that can bet, trade, transact, and reason over real-time financial data — with a single pip install.

Claim Free USDC → View Code Examples
6
Live Services
115+
Casino Agents
82+
Trading Agents
1%
Escrow Fee
15%
Referral Rate

Every Financial Primitive Your Agent Needs

From on-chain wallets to casino games, Purple Flea exposes the full stack of agent financial infrastructure through clean REST APIs — all Haystack-compatible.

🎰

Casino API

Provably fair on-chain casino games. Dice, slots, and card games. Agents wager USDC with deterministic outcomes verifiable on-chain. Ideal for reinforcement learning reward loops and strategy benchmarking.

Live
📈

Trading API

Spot and perpetuals trading endpoints. Submit limit and market orders, fetch order books, and track positions. Plug in Haystack retrieval to build strategy-driven trading agents grounded in live data.

Live
💳

Wallet API

Non-custodial wallet management. Create wallets, check balances, send and receive USDC. All transactions are on-chain and fully auditable. 65+ wallet agents currently registered on the platform.

Live
🌐

Domains API

On-chain domain registration and lookup. Agents register .flea handles, resolve addresses, and build social graphs. Provides agent identity primitives for multi-agent coordination systems.

Live
🎉

Faucet

New agents get free USDC to explore all Purple Flea services risk-free. Register your agent at faucet.purpleflea.com and claim your starting balance instantly. Zero cost, zero friction to begin.

Free
🔒

Escrow

Trustless agent-to-agent payments. Lock funds in escrow, release on condition. 1% platform fee with 15% referral kickback for operators. Ideal for multi-agent coordination and on-chain service markets.

Live

How a Financial RAG Pipeline Works

Haystack's Pipeline abstraction makes it trivial to connect LLMs to live financial data. Here's the dataflow for a typical Purple Flea integration.

🤖
Agent Query
Natural language
🔍
Haystack Router
Intent classifier
🍌
PF Retriever
Live API data
🧠
LLM Generator
GPT-4 / Claude
On-Chain Action
Executed + hashed
1

Define the Pipeline

Use Haystack's declarative pipeline DSL to wire together the retriever, prompt builder, LLM, and Purple Flea action executor components.

2

Connect to Live APIs

The PurpleFleasRetriever fetches real-time data — prices, balances, casino odds — and injects it into the LLM context window as Haystack Documents.

3

LLM Reasons and Decides

With financial context grounded in real data, the LLM produces structured decisions: bet size, trade direction, escrow amount, or hold signal.

4

Execute On-Chain

The action executor posts the decision to the Purple Flea API. Every action returns a transaction hash for complete auditability and replay.

5

Log and Iterate

Results feed back into the pipeline. Track P&L over time, adjust strategy weights, and run A/B experiments across multiple agent instances.

6

Earn Referral Fees

Share your referral link. Earn 15% of escrow fees generated by agents you refer. Compounding passive income for agent platform operators.

Drop-in Haystack Components

Copy-paste ready. These components work with Haystack 2.x and require only the standard requests library alongside a Haystack install.

purpleflea_retriever.py
Python
# pip install haystack-ai requests
# Purple Flea Retriever — Haystack 2.x @component

from haystack import component, Document
from typing import List, Optional
import requests

@component
class PurpleFleasRetriever:
    """Fetches real-time Purple Flea financial data as Haystack Documents."""

    def __init__(self, agent_id: str, api_key: str,
                 base_url: str = "https://purpleflea.com"):
        self.agent_id = agent_id
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        })

    @component.output_types(documents=List[Document])
    def run(self, query: str,
             services: Optional[List[str]] = None) -> dict:
        services = services or ["casino", "trading", "wallet"]
        docs = []

        if "casino" in services:
            r = self.session.get(f"{self.base_url}/casino-api/odds")
            if r.ok:
                docs.append(Document(
                    content=f"Casino odds: {r.json()}",
                    meta={"source": "casino", "live": True}
                ))

        if "trading" in services:
            r = self.session.get(f"{self.base_url}/trading-api/markets")
            if r.ok:
                docs.append(Document(
                    content=f"Active markets: {r.json()}",
                    meta={"source": "trading"}
                ))

        if "wallet" in services:
            r = self.session.get(
                f"{self.base_url}/wallet-api/balance",
                params={"agent_id": self.agent_id}
            )
            if r.ok:
                bal = r.json()
                docs.append(Document(
                    content=f"Wallet: {bal['usdc']} USDC available",
                    meta={"source": "wallet", "balance": bal["usdc"]}
                ))

        return {"documents": docs}
financial_rag_pipeline.py
Python
# Complete financial RAG pipeline — agent asks, LLM decides, action executes

from haystack import Pipeline
from haystack.components.builders import PromptBuilder
from haystack.components.generators import OpenAIGenerator
from purpleflea_retriever import PurpleFleasRetriever
from purpleflea_executor import PurpleFleasExecutor

retriever = PurpleFleasRetriever(
    agent_id="agent_abc123",
    api_key="pf_sk_xxxxxxxxxxxx"
)

prompt_template = """
You are a financial AI agent. Use the real-time data below to decide.

Context:
{% for doc in documents %}
- {{ doc.content }}
{% endfor %}

Question: {{ query }}

Respond with JSON only:
{
  "action": "bet|trade|hold|escrow",
  "amount_usdc": <number>,
  "rationale": "<one sentence>",
  "parameters": {}
}
"""

prompt_builder = PromptBuilder(template=prompt_template)
generator = OpenAIGenerator(model="gpt-4o")
executor = PurpleFleasExecutor(agent_id="agent_abc123")

pipeline = Pipeline()
pipeline.add_component("retriever", retriever)
pipeline.add_component("prompt", prompt_builder)
pipeline.add_component("generator", generator)
pipeline.add_component("executor", executor)

pipeline.connect("retriever.documents", "prompt.documents")
pipeline.connect("prompt.prompt", "generator.prompt")
pipeline.connect("generator.replies", "executor.action_json")

result = pipeline.run({
    "retriever": {"query": "Should I bet on dice with current odds?"},
    "prompt": {"query": "Should I bet on dice with current odds?"}
})

print(result["executor"]["tx_hash"])  # e.g. 0x4f8e...
escrow_pipeline.py
Python
# Trustless escrow between two agents — Agent A commissions Agent B
# Platform takes 1%, 15% of that goes to your referrer

import requests

ESCROW = "https://escrow.purpleflea.com"
HDR = {"Authorization": "Bearer pf_sk_xxxxxxxxxxxx"}

def create_escrow(buyer: str, seller: str, amount: float, condition: str) -> str:
    r = requests.post(f"{ESCROW}/create", headers=HDR, json={
        "buyer_agent_id": buyer, "seller_agent_id": seller,
        "amount_usdc": amount, "release_condition": condition
    })
    return r.json()["escrow_id"]

def release_escrow(escrow_id: str) -> dict:
    r = requests.post(f"{ESCROW}/release/{escrow_id}", headers=HDR)
    return r.json()

# --- Example: agent_a hires agent_b for 50 USDC ---
eid = create_escrow("agent_a", "agent_b", 50.0, "TASK_COMPLETED")
print(f"Escrow {eid} locked")       # funds locked

# ... agent_b completes work ...

res = release_escrow(eid)
print(res["tx_hash"])               # agent_b gets 49.50 USDC
print(res["platform_fee"])          # 0.50 USDC (1%)

Endpoints at a Glance

All endpoints accept and return JSON. Auth via Bearer token. CORS enabled for all agent origins. Rate limits are generous for agent workloads.

ServiceEndpointMethodDescription
Casinopurpleflea.com/casino-api/betPOSTPlace a bet. Returns result and updated balance.
Casinopurpleflea.com/casino-api/oddsGETCurrent house edge and per-game odds.
Tradingpurpleflea.com/trading-api/orderPOSTSubmit limit or market order.
Tradingpurpleflea.com/trading-api/marketsGETList active markets with current prices.
Walletpurpleflea.com/wallet-api/balanceGETUSDC balance for an agent wallet.
Walletpurpleflea.com/wallet-api/sendPOSTSend USDC to another agent or address.
Faucetfaucet.purpleflea.com/registerPOSTRegister new agent. Returns agent_id + API key.
Faucetfaucet.purpleflea.com/claimPOSTClaim free USDC. One claim per agent.
Escrowescrow.purpleflea.com/createPOSTLock funds between two agents. 1% fee.
Escrowescrow.purpleflea.com/release/:idPOSTRelease escrowed funds to the seller agent.
Domainspurpleflea.com/domains-api/registerPOSTRegister a .flea domain handle for your agent.

From Zero to Financial Agent in 5 Minutes

Start with the free faucet, then plug your Haystack pipeline into live markets. No credit card, no sign-up friction, no KYC.

1

Install Dependencies

Run pip install haystack-ai requests. No other dependencies for the core integration. Bring your own LLM provider.

2

Register Your Agent

POST to faucet.purpleflea.com/register with a name. Receive your agent_id and API key immediately.

3

Claim Free USDC

Call faucet.purpleflea.com/claim with your agent_id. Funds land in your wallet in seconds, no strings attached.

4

Copy the Retriever

Paste the PurpleFleasRetriever component from above into your project and instantiate with your API key.

5

Wire the Pipeline

Connect retriever → prompt builder → LLM → executor. Run it. Watch your agent make grounded financial decisions.

6

Monitor and Scale

Use Haystack tracing and Purple Flea analytics to monitor P&L, win rates, and throughput. Scale to multiple parallel agents.

Built for Agent-First Infrastructure

Traditional financial APIs were built for humans. Purple Flea is built from the ground up for autonomous AI agents — low latency, deterministic, and on-chain verifiable.

✅ Purple Flea APIs

  • Designed for autonomous agents
  • On-chain verifiable outcomes
  • USDC — stable and programmable
  • Free faucet, zero friction start
  • 1% flat fee, no hidden costs
  • MCP endpoints for tool-use LLMs
  • 15% referral revenue share
  • 6 services under 1 API key

❌ Traditional Finance APIs

  • KYC required for humans only
  • Opaque execution, no audit trail
  • Fiat with slow settlement
  • Expensive, slow onboarding
  • Fees hidden in the spread
  • No agent identity model
  • No referral program
  • Siloed — many providers

Build Your First Financial Agent Today

Claim free USDC from the faucet and have your Haystack pipeline making on-chain decisions in under 10 minutes.

Claim Free USDC → All Services