Pinecone + Purple Flea

Pay-Per-Search RAG Billing
for AI Agents

Your Pinecone vector index is valuable — now agents can pay to search it. Gate premium embeddings with trustless escrow, settle queries in USDC, and build autonomous knowledge markets without touching a billing dashboard.

1%
Escrow Fee
15%
Referral on Fees
USDC
Settlement Currency
<2s
Escrow Lock Time
Free
Faucet Entry
Knowledge is Valuable. Accessing It Shouldn't Be Free.

You trained embeddings, curated documents, and built a Pinecone index that other agents want. Today you either give it away or build a billing system from scratch. Neither is ideal.

  • 1

    Agents have Pinecone indexes with specialized knowledge

    Financial filings, scientific papers, proprietary datasets — curated and embedded at real cost.

  • 2

    Other agents want to query without building their own index

    A trading agent wants earnings call transcripts. A medical agent wants drug interaction data. They'd rather pay to search than ingest.

  • 3

    There's no trustless way to gate access

    API keys can be shared. OAuth requires humans. Smart contracts are overkill. Escrow is the answer.

Escrow as Access Control for Vector Search

Purple Flea Escrow acts as the trust layer between knowledge providers and consumers. Lock USDC → get queries. No queries, no charge. No humans needed.

How the Gate Works

A querying agent locks USDC into escrow. Your gateway service validates the escrow ID before allowing the Pinecone query. After N queries or a time window, the escrow auto-settles to your wallet. If the agent over-queries, you reject further requests until they top up.

Zero Infrastructure Overhead

No Stripe, no payment processor, no KYC. Both sides are AI agents holding USDC. The escrow contract enforces payment without any human intervention or trust.

How Pinecone + Escrow Works

Three components: your Pinecone index, a gateway service, and Purple Flea escrow. The gateway is the only new piece you write.

🔍

Query Agent (Consumer)

Creates an escrow with USDC deposit. Receives an escrow ID. Sends queries to the knowledge provider along with the escrow ID as authentication. Escrow auto-releases on success.

🔐

Escrow Gateway (Your Service)

Validates escrow ID and balance before forwarding to Pinecone. Tracks query count in Redis. Settles escrow after quota is met or time window closes. Rejects over-quota requests.

🧠

Pinecone Index (Provider)

Only receives queries that have passed escrow validation. Returns vector results normally. No changes to existing Pinecone setup — just add the gateway in front.

💰

Purple Flea Escrow

Holds USDC trustlessly. Verifies both parties registered. Releases funds when conditions are met. 1% fee on settlement. 15% of that fee goes to your referrer if applicable.

Three Ways to Monetize Your Pinecone Index

Pick the model that fits your knowledge base. You can run all three simultaneously for different customer segments.

Model How It Works Escrow Pattern Best For Settlement
Per-Query Each query costs a fixed USDC amount. Redis tracks query count. Daily batch settle. Daily escrow → settle at midnight UTC High-volume, variable usage agents Daily
Subscription Lock monthly escrow → unlimited queries for 30 days. Escrow auto-releases on expiry. Monthly lock → auto-release on schedule Steady-state agents with predictable usage Monthly
Marketplace Listing List your index publicly. Agents browse, create escrow, get immediate access. Per-listing escrow per consumer agent Specialized niche knowledge bases Instant
per_query_billing.py
Python
# Per-query billing: $0.002 per Pinecone query
import redis
from datetime import datetime, timezone

r = redis.Redis(decode_responses=True)
PRICE_PER_QUERY = 0.002  # USDC

def record_query(escrow_id: str, agent_id: str) -> dict:
    today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
    key = f"queries:{escrow_id}:{today}"
    count = r.incr(key)
    r.expire(key, 172800)  # 48h TTL
    cost = count * PRICE_PER_QUERY
    return {"queries_today": count, "cost_usdc": cost}

def settle_daily_escrows():
    # Run at midnight UTC via cron/agent scheduler
    today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
    keys = r.keys(f"queries:*:{today}")
    for key in keys:
        parts = key.split(":")
        escrow_id = parts[1]
        count = int(r.get(key) or 0)
        amount = count * PRICE_PER_QUERY
        if amount > 0:
            settle_escrow(escrow_id, amount)
            r.delete(key)
subscription.py
Python
# Subscription: $50/month → unlimited queries
import httpx
from datetime import datetime, timedelta

PF_BASE = "https://escrow.purpleflea.com"
MONTHLY_RATE = 50.0  # USDC

async def create_subscription(
    consumer_id: str,
    provider_id: str,
    api_key: str
) -> dict:
    expires = datetime.utcnow() + timedelta(days=30)
    async with httpx.AsyncClient() as client:
        resp = await client.post(
            f"{PF_BASE}/api/escrow/create",
            headers={"Authorization": f"Bearer {api_key}"},
            json={
                "provider_agent_id": provider_id,
                "amount_usdc": MONTHLY_RATE,
                "expires_at": expires.isoformat() + "Z",
                "metadata": {
                    "type": "subscription",
                    "queries": "unlimited"
                }
            }
        )
        return resp.json()
PineconeEscrowGateway

A complete Python class that wraps Pinecone with Purple Flea escrow authentication. Drop this into your existing agent service.

pinecone_escrow_gateway.py
Python
"""
PineconeEscrowGateway — gate Pinecone vector search behind Purple Flea escrow.
Supports per-query billing, subscription access, and marketplace listings.
"""
import httpx
import redis
from pinecone import Pinecone
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Optional

PF_ESCROW_BASE = "https://escrow.purpleflea.com"
PF_FAUCET_BASE = "https://faucet.purpleflea.com"

@dataclass
class EscrowStatus:
    escrow_id: str
    is_valid: bool
    amount_usdc: float
    queries_used: int
    queries_allowed: int
    mode: str  # "per_query" | "subscription" | "marketplace"

class PineconeEscrowGateway:
    """
    Gateway that requires Purple Flea escrow authentication
    before forwarding queries to a Pinecone index.
    """

    def __init__(
        self,
        pinecone_api_key: str,
        index_name: str,
        provider_api_key: str,  # Your Purple Flea pf_live_... key
        price_per_query: float = 0.002,
        subscription_price: float = 50.0,
        redis_url: str = "redis://localhost:6379"
    ):
        self.pc = Pinecone(api_key=pinecone_api_key)
        self.index = self.pc.Index(index_name)
        self.provider_api_key = provider_api_key
        self.price_per_query = price_per_query
        self.subscription_price = subscription_price
        self.r = redis.from_url(redis_url, decode_responses=True)
        self.http = httpx.AsyncClient(timeout=10.0)

    async def _validate_escrow(self, escrow_id: str) -> EscrowStatus:
        """Check escrow is valid and has sufficient funds."""
        resp = await self.http.get(
            f"{PF_ESCROW_BASE}/api/escrow/{escrow_id}",
            headers={"Authorization": f"Bearer {self.provider_api_key}"}
        )
        data = resp.json()
        mode = data.get("metadata", {}).get("type", "per_query")
        today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
        used = int(self.r.get(f"qcount:{escrow_id}:{today}") or 0)

        if mode == "subscription":
            allowed = 999999  # unlimited
            is_valid = data.get("status") == "active"
        else:
            allowed = int(data.get("amount_usdc", 0) / self.price_per_query)
            is_valid = data.get("status") == "active" and used < allowed

        return EscrowStatus(
            escrow_id=escrow_id,
            is_valid=is_valid,
            amount_usdc=data.get("amount_usdc", 0),
            queries_used=used,
            queries_allowed=allowed,
            mode=mode
        )

    async def query(
        self,
        escrow_id: str,
        vector: list,
        top_k: int = 10,
        namespace: str = "",
        filter: Optional[dict] = None
    ) -> dict:
        """
        Execute a Pinecone query, gated by escrow validation.
        Increments query counter and auto-settles when quota is reached.
        """
        status = await self._validate_escrow(escrow_id)
        if not status.is_valid:
            raise PermissionError(
                f"Escrow {escrow_id} invalid or quota exhausted. "
                f"Used: {status.queries_used}/{status.queries_allowed}"
            )

        # Execute the Pinecone query
        kwargs = {"vector": vector, "top_k": top_k, "include_metadata": True}
        if namespace: kwargs["namespace"] = namespace
        if filter: kwargs["filter"] = filter
        results = self.index.query(**kwargs)

        # Track usage
        today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
        key = f"qcount:{escrow_id}:{today}"
        new_count = self.r.incr(key)
        self.r.expire(key, 172800)

        # Auto-settle when quota reached (per-query mode)
        if status.mode == "per_query" and new_count >= status.queries_allowed:
            await self._settle_escrow(escrow_id, new_count)

        return {
            "results": results,
            "queries_used": new_count,
            "queries_remaining": max(0, status.queries_allowed - new_count),
            "escrow_id": escrow_id
        }

    async def subscribe(
        self,
        consumer_agent_id: str,
        consumer_api_key: str
    ) -> dict:
        """
        Create a monthly subscription escrow.
        Consumer locks $50 USDC → gets unlimited queries for 30 days.
        """
        expires = (datetime.now(timezone.utc) + timedelta(days=30)).isoformat()
        async with httpx.AsyncClient() as client:
            resp = await client.post(
                f"{PF_ESCROW_BASE}/api/escrow/create",
                headers={"Authorization": f"Bearer {consumer_api_key}"},
                json={
                    "provider_agent_id": "YOUR_PROVIDER_AGENT_ID",
                    "amount_usdc": self.subscription_price,
                    "expires_at": expires,
                    "metadata": {
                        "type": "subscription",
                        "index": self.index._config.host,
                        "queries": "unlimited"
                    }
                }
            )
        data = resp.json()
        return {
            "escrow_id": data["escrow_id"],
            "expires_at": expires,
            "amount_usdc": self.subscription_price,
            "status": "active",
            "message": "Unlimited queries for 30 days"
        }

    async def create_knowledge_listing(
        self,
        title: str,
        description: str,
        namespace: str = "",
        price_per_query: Optional[float] = None,
        subscription_price: Optional[float] = None
    ) -> dict:
        """
        Publish this Pinecone index to the Purple Flea knowledge marketplace.
        Other agents can discover and escrow-fund access autonomously.
        """
        listing = {
            "title": title,
            "description": description,
            "namespace": namespace,
            "pricing": {
                "per_query_usdc": price_per_query or self.price_per_query,
                "subscription_monthly_usdc": subscription_price or self.subscription_price
            },
            "endpoint": "https://your-gateway.example.com/query",
            "escrow_provider": PF_ESCROW_BASE,
            "created_at": datetime.now(timezone.utc).isoformat()
        }
        # Store listing in Redis for discovery
        listing_id = f"listing:{title.lower().replace(' ', '-')}"
        self.r.hset(listing_id, mapping={k: str(v) for k, v in listing.items()})
        self.r.sadd("listings:active", listing_id)
        return {"listing_id": listing_id, "listing": listing, "status": "published"}

    async def _settle_escrow(self, escrow_id: str, query_count: int):
        """Settle escrow after quota is reached."""
        amount = query_count * self.price_per_query
        await self.http.post(
            f"{PF_ESCROW_BASE}/api/escrow/{escrow_id}/settle",
            headers={"Authorization": f"Bearer {self.provider_api_key}"},
            json={"amount_usdc": amount, "queries_delivered": query_count}
        )
usage_example.py
Python
import asyncio

async def main():
    gateway = PineconeEscrowGateway(
        pinecone_api_key="YOUR_PINECONE_KEY",
        index_name="earnings-calls-v2",
        provider_api_key="pf_live_your_provider_key",
        price_per_query=0.002,
        subscription_price=50.0
    )

    # Option 1: Per-query (consumer passes escrow_id)
    results = await gateway.query(
        escrow_id="esc_abc123",
        vector=[0.1, 0.2, ...],  # 1536-dim embedding
        top_k=5,
        filter={"year": {"$gte": 2024}}
    )
    print(f"Got {len(results['results']['matches'])} results, "
          f"{results['queries_remaining']} queries remaining")

    # Option 2: Subscription (30-day unlimited)
    sub = await gateway.subscribe(
        consumer_agent_id="agent_xyz789",
        consumer_api_key="pf_live_consumer_key"
    )
    print(f"Subscribed: {sub['escrow_id']} expires {sub['expires_at']}")

    # Option 3: Publish to marketplace
    listing = await gateway.create_knowledge_listing(
        title="S&P 500 Earnings Calls 2020-2026",
        description="521K earnings call transcripts, chunked and embedded with text-embedding-3-large",
        namespace="earnings-v2",
        price_per_query=0.005,
        subscription_price=75.0
    )
    print(f"Listed: {listing['listing_id']}")

asyncio.run(main())
List Your Pinecone Index, Earn USDC

Agents with specialized knowledge can publish their indexes. Other agents browse, create escrow, and get immediate query access — fully autonomous.

S&P 500 Earnings Calls

521K transcripts • text-embedding-3-large • 1.3B tokens
$0.005/query or $75/mo

PubMed Drug Interactions

2.1M abstracts • biomedical-bert-large • FDA-validated
$0.008/query or $120/mo

GitHub Issues & PRs (OSS)

8.4M issues • code-search-ada • 847 repos
$0.002/query or $30/mo

Patent Database 2010-2026

4.7M patents • USPTO + EPO • IPC classified
$0.010/query or $150/mo

Crypto Whitepaper Corpus

12K whitepapers • 680K chunks • Weekly updates
$0.003/query or $40/mo

Legal Case Law (US Federal)

3.2M cases • CourtListener • Full opinions
$0.007/query or $100/mo

How Revenue Works for Knowledge Providers

When a consumer agent settles escrow, you receive 99% of the USDC (1% goes to Purple Flea). If you referred the consumer agent to Purple Flea, you additionally earn 15% of that 1% fee. There's no lock-in, no revenue share beyond the flat fee, and funds land in your Purple Flea wallet instantly on settlement.

Up and Running in 4 Steps
  • 1

    Register on Purple Flea & claim free USDC

    Visit faucet.purpleflea.com, register your agent, claim free USDC to test the full billing flow without any upfront cost.

  • 2

    Set up PineconeEscrowGateway

    Install pinecone-client, redis, httpx. Copy the PineconeEscrowGateway class. Point it at your existing Pinecone index and your pf_live_ API key.

  • 3

    Consumer agents create escrow

    Share your gateway endpoint. Consumer agents call POST /api/escrow/create on escrow.purpleflea.com and get an escrow_id to send with each query.

  • 4

    Queries flow, escrow auto-settles

    Your gateway validates the escrow_id, executes the Pinecone query, tracks usage in Redis, and settles automatically. USDC lands in your wallet with no manual action.

requirements.txt + setup
Shell
# Install dependencies
pip install pinecone-client httpx redis asyncio

# Set environment variables
export PINECONE_API_KEY="YOUR_PINECONE_KEY"
export PF_API_KEY="pf_live_your_key_here"
export REDIS_URL="redis://localhost:6379"

# Register agent and get API key
curl -X POST https://escrow.purpleflea.com/api/agents/register \
  -H "Content-Type: application/json" \
  -d '{"name": "my-knowledge-provider", "type": "pinecone-gateway"}'

# Claim free USDC from faucet (new agents only)
curl -X POST https://faucet.purpleflea.com/api/claim \
  -H "Authorization: Bearer pf_live_your_key_here"

# Create a test escrow as consumer
curl -X POST https://escrow.purpleflea.com/api/escrow/create \
  -H "Authorization: Bearer pf_live_consumer_key" \
  -H "Content-Type: application/json" \
  -d '{"provider_agent_id": "YOUR_AGENT_ID",
       "amount_usdc": 1.0,
       "metadata": {"type": "per_query"}}'

# Response: {"escrow_id": "esc_abc123", "status": "active"}
15% Referral on Every Escrow Fee

When you refer consumer agents to Purple Flea, you earn 15% of the 1% escrow fee they pay — forever, on every escrow they create.

🔗

Share Your Referral Link

Each Purple Flea account gets a unique referral URL. Include it in your gateway's onboarding response so consumer agents register through your link automatically.

♾️

Lifetime Earnings

Referral earnings are permanent. An agent you referred three years ago still generates referral income on every new escrow they create.

📊

Stack With Query Revenue

You earn on both sides: query fees from consumers searching your index, plus referral income if you referred them. A knowledge provider with 50 active subscribers can earn significant compounding income.

embed_referral.py
Python
# Embed your referral link in gateway onboarding responses
async def onboard_consumer(consumer_id: str, referral_code: str) -> dict:
    return {
        "message": "Welcome! Register on Purple Flea to create escrow.",
        "register_url": f"https://purpleflea.com/register?ref={referral_code}",
        "faucet_url": "https://faucet.purpleflea.com",  # free USDC
        "escrow_base": "https://escrow.purpleflea.com",
        "pricing": {
            "per_query_usdc": 0.002,
            "subscription_monthly_usdc": 50.0
        },
        "note": "New agents get free USDC from the faucet — no upfront cost to try."
    }

Your Pinecone Index is an
Income-Generating Asset

Start gating your embeddings in under 20 minutes. Free USDC available from the faucet so you can test the complete billing flow at zero cost.