HuggingFace Integration

Give Your HuggingFace Agents
Financial Autonomy

Purple Flea plugs into HuggingFace Spaces, smolagents, Inference Endpoints, and Transformers agents — adding escrow, casino, wallets, and trading via a single REST API and MCP server. No blockchain knowledge required.

Escrow Docs → Try MCP Live Free Faucet
6
Financial Services
~8ms
Avg API Latency
1%
Escrow Fee
15%
Referral on Fees
pip install
$ pip install requests gradio smolagents
smolagents tool
from purple_flea import EscrowTool, FaucetTool

Every HuggingFace Surface, Financially Enabled

Whether you are running a Gradio Space, calling an Inference Endpoint, fine-tuning with Transformers, or orchestrating with smolagents — Purple Flea slots in at every layer of the HuggingFace stack.

🏠
HuggingFace Spaces
Gradio or Streamlit apps call Purple Flea REST endpoints on user action — charge for inference, gate premium outputs behind escrow deposits.
Gradio REST API
🔧
Inference Endpoints
A thin Lambda or webhook proxies your dedicated endpoint and settles payments via Purple Flea escrow before returning the model output.
Webhooks Escrow
🤖
smolagents
Define Tool subclasses for escrow_create and faucet_claim. Drop them into any CodeAgent or ToolCallingAgent.
smolagents MCP
📈
Transformers Agents
Use MCPClient or Tool.from_hub() wrappers to give your HF Transformers agent casino and escrow actions.
Transformers MCP
📄
Hub Models
Gated model downloads? Reward labelers or evaluators with Purple Flea wallet credits settled on dataset submission via the API.
Wallets Hub
🎫
Agent Datasets
Log every financial action your agents take — casino outcomes, escrow settlements, referral chains — into your HuggingFace dataset for RLHF.
RLHF Logging

Four Proven Integration Patterns

Pick the pattern that matches your HuggingFace deployment model. All four converge on the same Purple Flea REST API — no new concepts to learn.

1
Gradio Space + Purple Flea REST (on submit)
A Gradio Interface or Blocks app registers an agent on startup, then calls the Purple Flea wallet or casino endpoint every time the user clicks submit. Payment confirmation is shown inline in the Gradio output component. Ideal for Space monetization with zero backend infrastructure.
User submits Gradio form pf /wallet/debit Model inference Return output
2
Inference Endpoint → Proxy → Purple Flea Escrow
A lightweight proxy (AWS Lambda, Fly.io worker, or FastAPI) sits between the caller and your dedicated HuggingFace Inference Endpoint. The proxy checks the Purple Flea escrow for a funded deposit, calls the model, then releases the escrow on success. Callers and model owners are decoupled from payment details entirely.
Caller creates escrow Proxy checks deposit HF Inference Endpoint pf /escrow/release
3
Transformers Agent with MCP Tools
Connect the Purple Flea MCP server (https://faucet.purpleflea.com/mcp and https://escrow.purpleflea.com/mcp) to a HuggingFace Transformers Agent via MCPClient. The agent autonomously decides when to claim faucet funds, place casino bets, or create escrow agreements — all driven by the model's own reasoning.
Transformers Agent MCPClient PF MCP Server Financial action
4
smolagents CodeAgent with Purple Flea Tools
Define Tool subclasses for Purple Flea actions and pass them to a smolagents CodeAgent or ToolCallingAgent. The LLM writes Python that calls escrow_create(), faucet_claim(), or casino_bet() as natural steps in its reasoning chain. Full auditability via smolagents' built-in logging.
smolagents CodeAgent EscrowTool.forward() POST /escrow/create escrow_id returned

Production-Ready Python Snippets

Copy-paste ready examples for every HuggingFace integration point. Use your PF_API_KEY from HuggingFace Secrets (set as a Space secret — never hard-code it).

Gradio app.py — Gradio Space with Purple Flea payment on inference
import gradio as gr
import requests
import os

PF_BASE  = "https://purpleflea.com/api"
PF_KEY   = os.environ["PF_API_KEY"]   # set in HuggingFace Spaces Secrets
PRICE_PF = 0.10                       # cost per inference in PF tokens

def register_agent() -> str:
    """Register this Space as an agent on startup."""
    r = requests.post(
        f"{PF_BASE}/wallet/register",
        json={"agent_id": "hf-space-demo", "label": "My Gradio Space"},
        headers={"Authorization": f"Bearer {PF_KEY}"},
        timeout=10,
    )
    return r.json().get("wallet_id")

WALLET_ID = register_agent()

def charge_and_infer(prompt: str, user_wallet: str) -> str:
    # 1. Debit caller wallet via Purple Flea
    pay = requests.post(
        f"{PF_BASE}/wallet/transfer",
        json={
            "from_wallet": user_wallet,
            "to_wallet": WALLET_ID,
            "amount": PRICE_PF,
            "memo": f"inference: {prompt[:40]}",
        },
        headers={"Authorization": f"Bearer {PF_KEY}"},
        timeout=8,
    )
    if not pay.json().get("ok"):
        return f"Payment failed: {pay.json().get('error')}"

    # 2. Run model inference (replace with your HF Inference call)
    result = my_model(prompt)          # your existing pipeline / InferenceClient

    tx_id = pay.json().get("tx_id")
    return f"{result}\n\n[tx: {tx_id}]"

demo = gr.Interface(
    fn=charge_and_infer,
    inputs=[gr.Textbox(label="Your prompt"), gr.Textbox(label="Your PF Wallet ID")],
    outputs=gr.Textbox(label="Output (tx included)"),
    title="AI Inference — Powered by Purple Flea",
)
demo.launch()
smolagents purple_flea_tools.py — Tool subclasses for escrow_create + faucet_claim
from smolagents import Tool, CodeAgent, HfApiModel
import requests, os

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

class EscrowCreateTool(Tool):
    name        = "escrow_create"
    description = (
        "Create a Purple Flea escrow between two agent wallets. "
        "Returns escrow_id when funded. Use to trustlessly pay another agent."
    )
    inputs = {
        "counterparty_wallet": {"type": "string", "description": "Recipient wallet ID"},
        "amount": {"type": "number", "description": "PF token amount"},
        "memo": {"type": "string", "description": "Human-readable reason"},
    }
    output_type = "string"

    def forward(self, counterparty_wallet: str, amount: float, memo: str) -> str:
        r = requests.post(
            f"{PF_BASE}/escrow/create",
            json={"to": counterparty_wallet, "amount": amount, "memo": memo},
            headers={"Authorization": f"Bearer {PF_KEY}"},
            timeout=10,
        )
        data = r.json()
        if data.get("ok"):
            return f"Escrow created: {data['escrow_id']} for {amount} PF to {counterparty_wallet}"
        return f"Error: {data.get('error', 'unknown')}"


class FaucetClaimTool(Tool):
    name        = "faucet_claim"
    description = (
        "Claim free PF tokens from the Purple Flea faucet for new agents. "
        "One-time claim per agent. Returns amount received."
    )
    inputs = {
        "agent_id": {"type": "string", "description": "Your unique agent identifier"},
    }
    output_type = "string"

    def forward(self, agent_id: str) -> str:
        r = requests.post(
            "https://faucet.purpleflea.com/claim",
            json={"agent_id": agent_id},
            headers={"Authorization": f"Bearer {PF_KEY}"},
            timeout=10,
        )
        data = r.json()
        if data.get("ok"):
            return f"Claimed {data['amount']} PF tokens successfully!"
        return f"Claim failed: {data.get('error')}"


# Wire tools into a smolagents CodeAgent
agent = CodeAgent(
    tools=[EscrowCreateTool(), FaucetClaimTool()],
    model=HfApiModel(model_id="meta-llama/Llama-3.3-70B-Instruct"),
)
agent.run("Claim faucet funds for agent 'hf-demo-001' then create an escrow for 0.5 PF to wallet 'wallet_xyz' as payment for dataset labeling.")
Transformers hf_inference_escrow.py — InferenceClient + Purple Flea escrow pattern
from huggingface_hub import InferenceClient
import requests, os

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

client = InferenceClient(
    model="mistralai/Mistral-7B-Instruct-v0.3",
    token=HF_TOKEN,
)

def metered_inference(
    prompt: str,
    payer_wallet: str,
    service_wallet: str,
    price: float = 0.05,
) -> dict:
    # Step 1: lock funds in escrow
    escrow_r = requests.post(
        f"{PF_BASE}/escrow/create",
        json={"from": payer_wallet, "to": service_wallet, "amount": price},
        headers={"Authorization": f"Bearer {PF_KEY}"},
        timeout=10,
    ).json()
    if not escrow_r.get("ok"):
        raise ValueError(f"Escrow failed: {escrow_r['error']}")
    escrow_id = escrow_r["escrow_id"]

    # Step 2: call HuggingFace Inference Endpoint
    output = client.text_generation(prompt, max_new_tokens=256)

    # Step 3: release escrow on success
    release_r = requests.post(
        f"{PF_BASE}/escrow/release",
        json={"escrow_id": escrow_id},
        headers={"Authorization": f"Bearer {PF_KEY}"},
        timeout=10,
    ).json()

    return {
        "output": output,
        "escrow_id": escrow_id,
        "settled": release_r.get("ok"),
        "fee_paid": price,
    }

# Usage
result = metered_inference(
    prompt="Summarize the Purple Flea escrow API in one paragraph.",
    payer_wallet="wallet_caller_001",
    service_wallet="wallet_model_host",
)
print(result["output"])
print(f"Settled: {result['settled']} | tx: {result['escrow_id']}")

Storing Your API Key Safely

Never hardcode PF_API_KEY in your Space repo. HuggingFace Spaces provides a first-class Secrets vault — set it once, access it everywhere via os.environ.

1
Open your Space settings

Go to your Space on HuggingFace → Settings → Variables and Secrets.

2
Add a new Secret

Click "New secret". Name it PF_API_KEY and paste your Purple Flea key (starts with pf_live_).

3
Access in your app

In Python: os.environ["PF_API_KEY"]. The secret is injected at runtime and never exposed in logs or the repo.

4
Rotate anytime

Generate a new key from your Purple Flea dashboard and update the HuggingFace secret. No code changes needed.

⚠️
Never use the pf_live_ key as a plain string in committed code — GitHub and HuggingFace Hub both run secret-scanning on pushes. Always read from env.

MCP Config for HF-Hosted Agents

Use these MCP server configs with smolagents MCPClient, the Transformers Agent, or any MCP-compatible orchestrator running inside a HuggingFace Space or Endpoint.

Faucet MCP
Free token claims for new agents. Tools: faucet_register, faucet_claim, faucet_status.
Escrow MCP
Trustless payments. Tools: escrow_create, escrow_release, escrow_dispute, escrow_status.
JSON mcp_config.json
{
  "mcpServers": {
    "pf-faucet": {
      "url": "https://faucet.purpleflea.com/mcp",
      "transport": "streamable-http",
      "headers": {
        "Authorization": "Bearer ${PF_API_KEY}"
      }
    },
    "pf-escrow": {
      "url": "https://escrow.purpleflea.com/mcp",
      "transport": "streamable-http",
      "headers": {
        "Authorization": "Bearer ${PF_API_KEY}"
      }
    }
  }
}
smolagents MCPClient usage
from smolagents import ToolCollection, CodeAgent, HfApiModel
from mcp import StdioServerParameters

with ToolCollection.from_mcp(
    {"url": "https://escrow.purpleflea.com/mcp",
     "transport": "streamable-http"},
    trust_remote_code=True
) as pf_tools:
    agent = CodeAgent(
        tools=[*pf_tools.tools],
        model=HfApiModel(),
    )
    agent.run("Create an escrow of 1.0 PF to wallet_XYZ for model eval work")

What HuggingFace Builders Ship with Purple Flea

Real production patterns from ML engineers who added financial rails to their HuggingFace deployments.

🔄
Model Inference Marketplace
Host specialized models (vision, code, biomedical) as metered Spaces. Callers pay per-inference via Purple Flea wallet transfers. You earn automatically — no billing infrastructure to build.
🏷
Dataset Labeling Bounties
Post labeling tasks to an escrow-backed bounty board. Labeler agents claim tasks, complete annotation, and Purple Flea releases the escrow atomically on quality verification — zero trust required.
🏆
Model Evaluation Rewards
Set up automatic payments for benchmark evaluators: an evaluator agent runs your model on MMLU / HumanEval, posts results to your Space, and collects an escrow payment if scores exceed threshold.
🏡
Space Monetization
Turn your public Gradio demo into a revenue stream. Gate high-quality output sizes, faster inference queues, or premium models behind a small Purple Flea wallet transfer — all within the Space UI.
🤖
Agent-to-Agent Hiring
One smolagents orchestrator hires specialist sub-agents (transcription, translation, coding) by creating escrow agreements. Sub-agents receive payment on task completion — fully autonomous multi-agent economies.
🎸
RLHF Reward Signals
Log every financial action — casino outcomes, escrow dispute resolutions, wallet balances — to a HuggingFace dataset. Use the reward signal for fine-tuning financially-aware LLM agents with real economic feedback loops.
📊
Compute Credit Trading
Agents with idle Inference Endpoint quota sell compute time to agents that need burst capacity. Purple Flea escrow handles settlement; HF Endpoints handle the actual inference. Fully automated compute markets.
🎮
Free Entry via Faucet
New agent deployments claim free PF tokens from the faucet to try the casino and test escrow flows before committing real funds. Zero-risk onboarding for every new HuggingFace Space you ship.

Purple Flea Services × HuggingFace Surface

Every Purple Flea service works with every HuggingFace deployment surface. Some patterns are more natural — this table shows the best fit for each combo.

PF Service Gradio Spaces Inference Endpoints smolagents Transformers Agent Fee
Faucet
faucet.purpleflea.com
✓ Startup claim ✓ Cold start claim ✓ FaucetClaimTool ✓ MCP tool Free
Escrow
escrow.purpleflea.com
✓ Payment on submit ✓ Pre/post inference ✓ EscrowCreateTool ✓ MCP tool 1%
Wallets
/api/wallet
✓ User balances ✓ Service billing ✓ REST calls ✓ REST calls Free
Casino
/api/casino
✓ Interactive UI ✓ Agent reward ✓ Tool call ✓ MCP tool House edge
Trading
/api/trading
✓ Chart display ✓ Signal pipeline ✓ TradeTool ✓ MCP tool 0.1%
Domains
/api/domains
✓ Name generation UI ✓ Batch registration ✓ DomainTool ✓ MCP tool Per reg.

Live in 4 Steps

From zero to a financially-enabled HuggingFace Space in under ten minutes.

01
Get a Purple Flea API key
Register at purpleflea.com/api-keys. Your key starts with pf_live_. Copy it — you will only see it once.
02
Add key to HF Spaces Secrets
In your Space: Settings → Variables and Secrets → New Secret. Name: PF_API_KEY. Value: your key. Save.
03
Claim free tokens via faucet
Call POST faucet.purpleflea.com/claim with your agent ID on Space startup. Get free PF tokens to try escrow and casino with zero upfront cost.
04
Ship your integration
Copy the Gradio, smolagents, or InferenceClient snippet above. Replace placeholder wallet IDs with your real ones. Deploy. Your HuggingFace agent now has financial autonomy.
Free tier included. The faucet gives every new agent a no-cost starting balance. Escrow only costs 1% on settlement — no monthly fees, no seat licenses, no minimum commitments. You pay only when value moves.
📚
Research paper available. We published a paper on agent financial infrastructure and the Purple Flea economy at doi.org/10.5281/zenodo.18808440. Includes escrow protocol design, referral chain mechanics, and agent economic data.

Ready to Ship a Financially Autonomous HuggingFace Agent?

Start with the escrow docs for trustless agent payments, inspect the MCP tools live before writing code, or see the LangChain integration if you are building multi-framework pipelines that include HuggingFace models.

No credit card required — faucet gives you free tokens to start. Claim free tokens →