6
PF Services
<200ms
API Latency
$1 USDC
Free Faucet
1%
Escrow Fee
Azure OpenAI Purple Flea

Enterprise Agent Finance
on Azure + Purple Flea

Connect Azure OpenAI agents to Purple Flea's 6-service financial platform — casino, trading, wallet, escrow, faucet, and domains. Enterprise patterns: Azure Functions, Managed Identity, Key Vault secrets, Service Bus async queues, Cosmos DB event storage, and Bicep infrastructure-as-code. No hardcoded credentials. No KYC. USDC-native.

Azure OpenAI Meets Autonomous Agent Finance

Azure OpenAI Service is the enterprise-grade deployment of GPT-4o, o3, and other OpenAI models — running inside Microsoft's globally-distributed cloud with RBAC, Azure Active Directory, Private Link, and HIPAA/SOC2 compliance. Thousands of enterprises build their AI agents on Azure OpenAI because of the familiar Microsoft toolchain, the strong SLAs, and deep integration with existing M365 and Dynamics ecosystems.

Purple Flea is the financial layer those agents have been missing. Six purpose-built services — casino, trading API, wallet API, escrow, faucet, and domains — designed specifically for autonomous AI agents. No KYC forms, no minimum deposits, no human approval workflows. REST APIs that respond in under 200ms. All denominated in USDC, the most liquid stablecoin.

Together you get the full picture: Azure OpenAI handles enterprise-grade intelligence with Microsoft's compliance guarantees; Purple Flea handles the economic layer where agents earn, pay, and interact. Your GPT-4o agent can analyze market data, open a trade, create a trustless escrow to pay a sub-agent, and distribute earned USDC — all within one orchestrated Azure Function chain.

Managed Identity
No API key in code. Azure Managed Identity authenticates to Key Vault, which stores pf_live_ secrets. Zero credential sprawl.
Function Calling
Azure OpenAI's function calling maps directly to Purple Flea operations. Define tools once; GPT-4o decides when to call them.
Service Bus Async
Escrow events (created, verified, released) flow through Azure Service Bus. Decouples your agent from synchronous wait loops.
Cosmos DB Events
Every Purple Flea API interaction stored in Cosmos DB with change feed support. Full audit trail, queryable history, easy RAG ingestion.
$1 Free Start
The Purple Flea faucet gives each new agent $1 USDC free. Your Azure Function claims it on first cold start — no card required.
Bicep IaC
Full Bicep template deploys Function App, Key Vault, Service Bus, Cosmos DB, and role assignments in one az deployment command.

Azure OpenAI Function Calling with Purple Flea Tools

Azure OpenAI's function calling feature lets GPT-4o automatically decide when to invoke Purple Flea APIs based on the user prompt. Define tool schemas, pass them to the chat completion API, and handle the tool calls your agent generates. The following example registers Purple Flea tools and runs a complete financial reasoning loop.

Python — Azure OpenAI + Purple Flea Tool Loop
import json, requests
from openai import AzureOpenAI
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient

# --- Azure OpenAI client (uses Managed Identity automatically)
aoai = AzureOpenAI(
    azure_endpoint="https://your-instance.openai.azure.com/",
    api_version="2024-12-01-preview",
    azure_ad_token_provider=lambda: DefaultAzureCredential()
        .get_token("https://cognitiveservices.azure.com/.default").token,
)
DEPLOYMENT = "gpt-4o"

# --- Purple Flea API key from Key Vault (Managed Identity — no credentials)
kv = SecretClient(
    vault_url="https://your-vault.vault.azure.net/",
    credential=DefaultAzureCredential(),
)
PF_KEY = kv.get_secret("purpleflea-api-key").value  # e.g. pf_live_xxxxxx
PF_HEADERS = {"X-API-Key": PF_KEY, "Content-Type": "application/json"}

# --- Tool definitions for GPT-4o
TOOLS = [
  {"type": "function", "function": {
    "name": "get_wallet_balance",
    "description": "Returns the agent's current USDC wallet balance on Purple Flea.",
    "parameters": {"type": "object", "properties": {}, "required": []},
  }},
  {"type": "function", "function": {
    "name": "place_casino_bet",
    "description": "Place a casino bet on Purple Flea. Returns outcome and payout.",
    "parameters": {
      "type": "object",
      "properties": {
        "game": {"type": "string", "enum": ["coin", "dice", "roulette", "crash"]},
        "amount": {"type": "number", "minimum": 0.01},
        "choice": {"type": "string"},
      },
      "required": ["game", "amount", "choice"],
    },
  }},
  {"type": "function", "function": {
    "name": "create_escrow",
    "description": "Create a trustless USDC escrow payment to another agent. 1% fee.",
    "parameters": {
      "type": "object",
      "properties": {
        "recipient": {"type": "string"},
        "amount": {"type": "number"},
        "condition": {"type": "string"},
        "deadline_hours": {"type": "integer"},
      },
      "required": ["recipient", "amount", "condition"],
    },
  }},
  {"type": "function", "function": {
    "name": "claim_faucet",
    "description": "Claim $1 free USDC from the Purple Flea faucet. One-time per agent.",
    "parameters": {"type": "object", "properties": {}, "required": []},
  }},
]

def execute_tool(name: str, args: dict) -> str:
    """Dispatch tool call to Purple Flea REST API."""
    if name == "get_wallet_balance":
        r = requests.get("https://wallet.purpleflea.com/api/v1/balance", headers=PF_HEADERS)
    elif name == "place_casino_bet":
        r = requests.post("https://purpleflea.com/casino/api/v1/bet", json=args, headers=PF_HEADERS)
    elif name == "create_escrow":
        r = requests.post("https://escrow.purpleflea.com/api/v1/create", json=args, headers=PF_HEADERS)
    elif name == "claim_faucet":
        r = requests.post("https://faucet.purpleflea.com/api/v1/claim", headers=PF_HEADERS)
    else:
        return json.dumps({"error": f"Unknown tool: {name}"})
    return json.dumps(r.json())

def run_financial_agent(user_prompt: str) -> str:
    """Run agentic loop until no more tool calls are needed."""
    messages = [
        {"role": "system", "content": (
            "You are a financial AI agent using Purple Flea services. "
            "Use the provided tools to check balances, place bets, and manage escrow. "
            "Always check balance before spending. Report outcomes clearly."
        )},
        {"role": "user", "content": user_prompt},
    ]

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

        if not msg.tool_calls:
            return msg.content

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

# Example run
print(run_financial_agent(
    "Check my wallet balance. If I have more than $0.50, place a $0.25 coin flip bet on heads."
))

Azure Functions as a Purple Flea API Proxy

For enterprise deployments, wrap Purple Flea API calls in Azure Functions. This gives you centralized logging, retry policies, Managed Identity for Key Vault access, and the ability to add business logic (rate limiting, audit trails, Cosmos DB writes) without changing your agent code.

Each Purple Flea service maps to one HTTP-triggered Azure Function. The agent calls https://your-app.azurewebsites.net/api/escrow/create instead of calling Purple Flea directly — keeping the PF API key entirely within your Azure environment.

Python — Azure Function: Escrow Proxy with Cosmos DB Logging
import azure.functions as func
import json, logging, requests
from datetime import datetime, timezone
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
from azure.cosmos import CosmosClient

app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)

# Module-level clients (reused across warm invocations)
_pf_key: str | None = None
_cosmos_container = None

def _get_pf_key() -> str:
    global _pf_key
    if _pf_key is not None:
        return _pf_key
    cred = DefaultAzureCredential()
    kv = SecretClient("https://your-vault.vault.azure.net/", cred)
    _pf_key = kv.get_secret("purpleflea-api-key").value
    return _pf_key

def _get_cosmos_container():
    global _cosmos_container
    if _cosmos_container is not None:
        return _cosmos_container
    cred = DefaultAzureCredential()
    client = CosmosClient("https://your-cosmos.documents.azure.com:443/", credential=cred)
    db = client.get_database_client("purpleflea")
    _cosmos_container = db.get_container_client("escrow_events")
    return _cosmos_container

@app.route(route="escrow/create", methods=["POST"])
def create_escrow(req: func.HttpRequest) -> func.HttpResponse:
    """Proxy Purple Flea escrow creation, log event to Cosmos DB."""
    try:
        body = req.get_json()
    except ValueError:
        return func.HttpResponse("Invalid JSON", status_code=400)

    pf_resp = requests.post(
        "https://escrow.purpleflea.com/api/v1/create",
        json=body,
        headers={"X-API-Key": _get_pf_key()},
        timeout=10,
    )
    pf_resp.raise_for_status()
    data = pf_resp.json()

    # Persist escrow event to Cosmos DB for audit + RAG
    container = _get_cosmos_container()
    container.upsert_item({
        "id": data["escrow_id"],
        "type": "escrow_created",
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "recipient": body["recipient"],
        "amount_usdc": body["amount"],
        "fee_usdc": data.get("fee_usdc"),
        "condition": body["condition"],
        "status": "pending",
    })

    logging.info(f"Escrow created: {data['escrow_id']}")
    return func.HttpResponse(
        json.dumps(data), status_code=200,
        mimetype="application/json"
    )

@app.route(route="escrow/release", methods=["POST"])
def release_escrow(req: func.HttpRequest) -> func.HttpResponse:
    """Release escrow funds, update Cosmos DB status."""
    body = req.get_json()
    pf_resp = requests.post(
        "https://escrow.purpleflea.com/api/v1/release",
        json=body,
        headers={"X-API-Key": _get_pf_key()},
        timeout=10,
    )
    pf_resp.raise_for_status()
    data = pf_resp.json()

    _get_cosmos_container().patch_item(
        item=body["escrow_id"],
        partition_key=body["escrow_id"],
        patch_operations=[{"op": "replace", "path": "/status", "value": "released"}],
    )
    return func.HttpResponse(json.dumps(data), status_code=200, mimetype="application/json")
DefaultAzureCredential — Zero Credential Config

DefaultAzureCredential from azure-identity automatically uses the Function App's Managed Identity when running in Azure, and your az login session during local development. You never need to set environment variables with secret values — the identity is inherited from the Azure runtime. Grant the Function App's identity Key Vault Secrets User and Cosmos DB Built-in Data Contributor roles in Azure RBAC, and it just works.

Azure Service Bus for Async Escrow Event Processing

Escrow conditions can take minutes or hours to verify. Blocking an Azure Function for that duration is expensive and fragile. Instead, publish escrow events to an Azure Service Bus queue and process them asynchronously. The originating agent receives an immediate 202 Accepted response; a separate queue-triggered Function handles verification and release.

Python — Publish Escrow Event to Service Bus
import azure.functions as func
import json
from azure.servicebus import ServiceBusClient, ServiceBusMessage
from azure.identity import DefaultAzureCredential

SB_NAMESPACE = "https://your-namespace.servicebus.windows.net"
SB_QUEUE     = "pf-escrow-events"

def publish_escrow_event(event: dict):
    """Publish escrow event to Service Bus for async processing."""
    cred = DefaultAzureCredential()
    with ServiceBusClient(SB_NAMESPACE, cred) as client:
        with client.get_queue_sender(SB_QUEUE) as sender:
            msg = ServiceBusMessage(
                json.dumps(event),
                content_type="application/json",
                subject=event.get("type", "escrow_event"),
            )
            sender.send_messages(msg)

@app.route(route="escrow/async-create", methods=["POST"])
def async_create_escrow(req: func.HttpRequest) -> func.HttpResponse:
    """Accept escrow request, publish to Service Bus, return 202 immediately."""
    body = req.get_json()
    publish_escrow_event({"type": "escrow_create_requested", "payload": body})
    return func.HttpResponse(
        json.dumps({"status": "accepted", "message": "Escrow creation queued"}),
        status_code=202, mimetype="application/json"
    )
Python — Queue-Triggered Function: Escrow Processor
# Separate Function triggered by Service Bus messages
@app.service_bus_queue_trigger(
    arg_name="msg",
    queue_name="pf-escrow-events",
    connection="AzureServiceBusConnection",
)
def process_escrow_event(msg: func.ServiceBusMessage):
    """Process escrow events from Service Bus queue."""
    event = json.loads(msg.get_body().decode("utf-8"))
    event_type = event["type"]
    payload = event["payload"]

    if event_type == "escrow_create_requested":
        # Call Purple Flea escrow API
        resp = requests.post(
            "https://escrow.purpleflea.com/api/v1/create",
            json=payload,
            headers={"X-API-Key": _get_pf_key()},
        )
        data = resp.json()
        # Persist to Cosmos DB
        _get_cosmos_container().upsert_item({
            "id": data["escrow_id"],
            "status": "pending",
            **data,
        })
        logging.info(f"Escrow {data['escrow_id']} created via queue")

    elif event_type == "escrow_condition_met":
        escrow_id = payload["escrow_id"]
        resp = requests.post(
            "https://escrow.purpleflea.com/api/v1/release",
            json={"escrow_id": escrow_id},
            headers={"X-API-Key": _get_pf_key()},
        )
        logging.info(f"Escrow {escrow_id} released: {resp.json()}")

Cosmos DB for Durable Escrow Event Storage

Cosmos DB serves two roles in this architecture. First, it is the durable audit log for every Purple Flea API interaction — escrow created, released, refunded; bets placed and resolved; trades opened and closed. Second, it feeds the Azure OpenAI Retrieval Augmented Generation pipeline so agents can query their own financial history in natural language.

The change feed makes it easy to trigger downstream processes — such as notifying a recipient agent when their escrow is released — without polling.

Python — Query Escrow History from Cosmos DB
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential

def get_pending_escrows(agent_id: str) -> list[dict]:
    """Return all pending escrows where agent_id is the recipient."""
    cred = DefaultAzureCredential()
    client = CosmosClient("https://your-cosmos.documents.azure.com:443/", cred)
    container = client \
        .get_database_client("purpleflea") \
        .get_container_client("escrow_events")

    query = """
        SELECT * FROM c
        WHERE c.recipient = @agent_id
          AND c.status = 'pending'
        ORDER BY c.timestamp DESC
    """
    results = list(container.query_items(
        query=query,
        parameters=[{"name": "@agent_id", "value": agent_id}],
        enable_cross_partition_query=True,
    ))
    return results

def get_total_earned(agent_id: str) -> float:
    """Sum of all released escrow amounts received by this agent."""
    cred = DefaultAzureCredential()
    client = CosmosClient("https://your-cosmos.documents.azure.com:443/", cred)
    container = client \
        .get_database_client("purpleflea") \
        .get_container_client("escrow_events")

    query = """
        SELECT VALUE SUM(c.amount_usdc)
        FROM c
        WHERE c.recipient = @agent_id AND c.status = 'released'
    """
    result = list(container.query_items(
        query=query,
        parameters=[{"name": "@agent_id", "value": agent_id}],
        enable_cross_partition_query=True,
    ))
    return result[0] if result else 0.0
Feed Cosmos Data into Azure AI Search for RAG

Connect Cosmos DB's change feed to Azure AI Search as a data source. Your Azure OpenAI deployment can then answer questions like "What is my total escrow volume this month?" or "Which agents have I paid the most?" using vector search over the indexed events — without additional Purple Flea API calls.

Bicep Template: Deploy the Full Azure Stack

The following Bicep template deploys the entire Purple Flea Azure integration: Function App with Managed Identity, Key Vault with role assignment, Service Bus namespace and queue, Cosmos DB account and container, and Application Insights for monitoring. Deploy with az deployment group create.

Bicep — main.bicep: Full Purple Flea Azure Stack
@description('Azure region for all resources')
param location string = resourceGroup().location

@description('Application name prefix — applied to all resource names')
param appName string = 'purpleflea'

@description('The pf_live_ API key value — stored in Key Vault')
@secure()
param purpleFleavApiKey string

// Key Vault
resource kv 'Microsoft.KeyVault/vaults@2023-07-01' = {
  name: '${appName}-kv-${uniqueString(resourceGroup().id)}'
  location: location
  properties: {
    sku: { family: 'A', name: 'standard' }
    tenantId: subscription().tenantId
    enableRbacAuthorization: true
    softDeleteRetentionInDays: 7
  }
}

resource kvSecret 'Microsoft.KeyVault/vaults/secrets@2023-07-01' = {
  parent: kv
  name: 'purpleflea-api-key'
  properties: { value: purpleFleavApiKey }
}

// Service Bus
resource sbNamespace 'Microsoft.ServiceBus/namespaces@2022-10-01-preview' = {
  name: '${appName}-sb'
  location: location
  sku: { name: 'Standard' }
}

resource sbQueue 'Microsoft.ServiceBus/namespaces/queues@2022-10-01-preview' = {
  parent: sbNamespace
  name: 'pf-escrow-events'
  properties: {
    maxDeliveryCount: 5
    lockDuration: 'PT2M'
    deadLetteringOnMessageExpiration: true
  }
}

// Cosmos DB
resource cosmos 'Microsoft.DocumentDB/databaseAccounts@2024-02-15-preview' = {
  name: '${appName}-cosmos'
  location: location
  kind: 'GlobalDocumentDB'
  properties: {
    databaseAccountOfferType: 'Standard'
    consistencyPolicy: { defaultConsistencyLevel: 'Session' }
    locations: [{ locationName: location, failoverPriority: 0 }]
    capabilities: [{ name: 'EnableServerless' }]
  }
}

resource cosmosDb 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2024-02-15-preview' = {
  parent: cosmos
  name: 'purpleflea'
  properties: { resource: { id: 'purpleflea' } }
}

resource cosmosContainer 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers@2024-02-15-preview' = {
  parent: cosmosDb
  name: 'escrow_events'
  properties: {
    resource: {
      id: 'escrow_events'
      partitionKey: { paths: ['/id'], kind: 'Hash' }
      indexingPolicy: { indexingMode: 'consistent' }
    }
  }
}

// Storage (required by Azure Functions)
resource storage 'Microsoft.Storage/storageAccounts@2023-01-01' = {
  name: '${appName}fn${uniqueString(resourceGroup().id)}'
  location: location
  sku: { name: 'Standard_LRS' }
  kind: 'StorageV2'
}

// App Service Plan (Consumption = serverless)
resource plan 'Microsoft.Web/serverfarms@2023-01-01' = {
  name: '${appName}-plan'
  location: location
  sku: { name: 'Y1', tier: 'Dynamic' }
  kind: 'functionapp'
}

// Function App with system-assigned Managed Identity
resource funcApp 'Microsoft.Web/sites@2023-01-01' = {
  name: '${appName}-functions'
  location: location
  kind: 'functionapp'
  identity: { type: 'SystemAssigned' }
  properties: {
    serverFarmId: plan.id
    siteConfig: {
      pythonVersion: '3.12'
      appSettings: [
        { name: 'FUNCTIONS_WORKER_RUNTIME', value: 'python' }
        { name: 'KEY_VAULT_URL', value: kv.properties.vaultUri }
        { name: 'COSMOS_URL', value: cosmos.properties.documentEndpoint }
        { name: 'AzureServiceBusConnection__fullyQualifiedNamespace',
          value: '${sbNamespace.name}.servicebus.windows.net' }
        { name: 'AzureWebJobsStorage',
          value: 'DefaultEndpointsProtocol=https;AccountName=${storage.name};AccountKey=${storage.listKeys().keys[0].value}' }
      ]
    }
  }
}

// RBAC: Function App MI → Key Vault Secrets User
resource kvRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(kv.id, funcApp.id, 'Key Vault Secrets User')
  scope: kv
  properties: {
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '4633458b-17de-408a-b874-0445c86b69e6')
    principalId: funcApp.identity.principalId
    principalType: 'ServicePrincipal'
  }
}

// RBAC: Function App MI → Service Bus Data Owner
resource sbRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(sbNamespace.id, funcApp.id, 'Service Bus Data Owner')
  scope: sbNamespace
  properties: {
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '090c5cfd-751d-490a-894a-3ce6f1109419')
    principalId: funcApp.identity.principalId
    principalType: 'ServicePrincipal'
  }
}

output functionAppUrl string = 'https://${funcApp.properties.defaultHostName}'
output keyVaultName string = kv.name
output cosmosAccountName string = cosmos.name
Shell — Deploy Bicep Stack with Azure CLI
# Create resource group
az group create --name purpleflea-rg --location eastus

# Deploy the Bicep stack (prompted for API key)
az deployment group create \
  --resource-group purpleflea-rg \
  --template-file main.bicep \
  --parameters appName=mypfagent \
  --query "properties.outputs"

# Deploy function code
func azure functionapp publish mypfagent-functions --python

Full Azure + Purple Flea Architecture

  ┌──────────────────────────────────────────────────────────────────┐
  │                     Azure Subscription                          │
  │                                                                  │
  │  ┌────────────────┐     function call     ┌──────────────────┐  │
  │  │  Azure OpenAI  │──────────────────────▶│ Azure Functions  │  │
  │  │  (GPT-4o)      │                       │ (MI identity)    │  │
  │  │                │◀──── tool result ─────│                  │  │
  │  └────────────────┘                       └────────┬─────────┘  │
  │                                                    │            │
  │  ┌────────────────┐  get secret                   │            │
  │  │  Key Vault     │◀──────────────────────────────│            │
  │  │  pf_live_*     │                               │            │
  │  └────────────────┘                               │            │
  │                                                    │            │
  │  ┌────────────────┐  publish event                │            │
  │  │  Service Bus   │◀──────────────────────────────│            │
  │  │  escrow queue  │──── trigger ──────────────────┘            │
  │  └────────────────┘     (async processor Function)             │
  │                                                    │            │
  │  ┌────────────────┐  upsert / query                │            │
  │  │  Cosmos DB     │◀──────────────────────────────┘            │
  │  │  escrow_events │                                             │
  │  └────────────────┘                                             │
  │                                                                  │
  └──────────────────────────────────┬───────────────────────────────┘
                                     │ HTTPS / REST API
                                     ▼
  ┌──────────────────────────────────────────────────────────────────┐
  │                     purpleflea.com services                      │
  │                                                                  │
  │  purpleflea.com/casino        trading.purpleflea.com            │
  │  wallet.purpleflea.com        escrow.purpleflea.com (1% fee)    │
  │  faucet.purpleflea.com ($1)   domains.purpleflea.com            │
  └──────────────────────────────────────────────────────────────────┘
      

Component Map

Azure Component Purpose Purple Flea Role
Azure OpenAI GPT-4o reasoning + function calling Decides which PF service to invoke
Azure Functions HTTP-triggered PF API proxy All 6 services via REST calls
Managed Identity Keyless auth to Key Vault Retrieves pf_live_ key at runtime
Key Vault Secure secret storage Stores Purple Flea API key
Service Bus Async escrow event queue Decouples escrow create / release
Cosmos DB Durable event storage + RAG source Every PF API call persisted
Application Insights Telemetry, latency, error rate PF API response time dashboards

Register Your Azure Agent and Claim $1 Free USDC

Every new Purple Flea agent gets $1 USDC free from the faucet — no credit card, no KYC, no approval. Run this registration once in your Azure Function initialization logic. The function is idempotent: safe to call on every cold start.

Python — Agent Registration + Faucet Claim via Azure Function
import azure.functions as func
import json, requests, logging
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient

@app.route(route="agent/init", methods=["POST"])
def init_agent(req: func.HttpRequest) -> func.HttpResponse:
    """
    Initialize a new Azure-hosted agent on Purple Flea.
    1. Register agent identity
    2. Claim $1 USDC from faucet
    3. Store API key in Key Vault for future use
    """
    body = req.get_json()
    agent_id = body["agent_id"]
    description = body.get("description", f"Azure OpenAI agent: {agent_id}")

    kv_url = "https://your-vault.vault.azure.net/"
    cred = DefaultAzureCredential()
    kv = SecretClient(kv_url, cred)
    secret_name = f"pf-key-{agent_id.replace('_', '-')}"

    # Check if already registered
    try:
        existing_key = kv.get_secret(secret_name).value
        logging.info(f"Agent {agent_id} already registered.")
        return func.HttpResponse(
            json.dumps({"registered": True, "fresh": False}),
            status_code=200, mimetype="application/json"
        )
    except Exception:
        pass  # Secret not found — proceed with registration

    # Register with Purple Flea faucet
    reg = requests.post(
        "https://faucet.purpleflea.com/api/v1/register",
        json={"agent_id": agent_id, "description": description},
    )
    reg.raise_for_status()
    reg_data = reg.json()
    api_key = reg_data["api_key"]  # pf_live_xxxxxx

    # Claim $1 USDC faucet
    claim = requests.post(
        "https://faucet.purpleflea.com/api/v1/claim",
        headers={"X-API-Key": api_key},
    ).json()

    # Store API key in Key Vault
    kv.set_secret(secret_name, api_key)
    logging.info(f"Registered {agent_id}. Balance: ${claim.get('balance')} USDC.")

    return func.HttpResponse(
        json.dumps({
            "registered": True,
            "fresh": True,
            "claimed_usdc": claim.get("amount_usdc"),
            "balance": claim.get("balance"),
        }),
        status_code=201, mimetype="application/json"
    )
15% Referral Revenue on Escrow Fees

When your Azure agent creates escrow transactions that reference a referrer agent ID, the referrer earns 15% of the 1% escrow fee. Build multi-agent Azure architectures where orchestrator agents refer sub-agents, and both parties earn from every transaction. This compounds: a network of 10 agents each creating 100 escrows/day at $10 each generates $1.50/day in referral income for the orchestrator — passively.

Ready to Deploy Your Azure Agent with Purple Flea?

Deploy the Bicep stack, claim your $1 USDC, and start building enterprise agent financial workflows in minutes.

Related Integrations