AWS SageMaker ML Engineers Purple Flea

Give Your SageMaker Agents
Financial Superpowers

Your SageMaker model predicts. Purple Flea executes. Close the gap between model inference and real financial action — wallet operations, trustless escrow, live trading, and agent payouts — all via standard REST APIs your boto3 code can call in milliseconds.

6
Financial Services
<200ms
API Response
$1
Free to Start
1%
Escrow Fee

ML Models Are Smart. SageMaker Agents Still Can't Move Money.

You have a SageMaker endpoint running a well-tuned model that predicts market direction with 68% accuracy. Or a fraud detection pipeline that flags suspicious transactions in real time. Or a reinforcement learning agent that has learned optimal portfolio rebalancing strategies.

The model is ready. But when the prediction fires — what happens next? Manually triggering a trade? A human reviewing the fraud flag? The RL agent's output sitting in a CloudWatch log?

This is the inference-to-financial-action gap. Purple Flea closes it. Your SageMaker endpoint invokes, parses the output, and calls a Purple Flea API — all in the same Lambda function, in the same pipeline step, in the same processing job. No human in the loop. No additional orchestration layer. Just REST calls that any boto3 developer already knows how to make.

 Without Purple Flea                    With Purple Flea
 ─────────────────                      ─────────────────────────────────────────────
 SageMaker Endpoint                     SageMaker Endpoint
        │                                      │
        ▼                                      ▼
  Model Output                          Model Output (JSON)
  (JSON prediction)                            │
        │                                      ▼
        ▼                               Lambda / Pipeline Step
  ??? (gap)                                    │
   - human reviews                     ┌───────┴────────┐
   - nothing happens                   │  Purple Flea   │
   - manual trade ticket               │  REST API      │
                                       │  <200ms        │
                                       └───────┬────────┘
                                               │
                              ┌────────────────┼─────────────────┐
                              ▼                ▼                  ▼
                        /trading/order   /escrow/create    /wallet/transfer
                        (place trade)    (lock funds)      (pay agents)
      
SageMaker + Lambda = Perfect Pair

SageMaker Processing jobs, Training jobs, and Batch Transform can all invoke Lambda functions on completion via EventBridge. Lambda calls Purple Flea APIs. No new infrastructure. No new languages. Just the AWS services you already use.

Three Ways to Connect SageMaker to Purple Flea

Pick the pattern that fits your architecture. All three use standard boto3 and Python requests — no SDKs to install, no agents framework required.

Pattern 1: Endpoint → Lambda Pattern 2: Pipeline Step Pattern 3: Processing Job

Pattern 1 — SageMaker Endpoint → Lambda → Purple Flea API (Event-Driven)

The most common pattern for real-time inference. Your application invokes the SageMaker endpoint (or it is invoked on a schedule via EventBridge), parses the model output, and the same Lambda function calls Purple Flea to act on the prediction.

Pattern 1 — Event-Driven Endpoint Invocation Python 3.11 / Lambda
import boto3
import requests
import json
import os

# Clients — initialized outside handler for connection reuse
sagemaker_runtime = boto3.client("sagemaker-runtime", region_name="us-east-1")

PF_API_KEY    = os.environ["PF_API_KEY"]   # pf_live_... from Secrets Manager
PF_BASE_URL   = "https://api.purpleflea.com"
PF_AGENT_ID   = os.environ["PF_AGENT_ID"]
ENDPOINT_NAME = os.environ["SAGEMAKER_ENDPOINT"]

def invoke_endpoint(payload: dict) -> dict:
    """Invoke SageMaker endpoint and parse prediction."""
    response = sagemaker_runtime.invoke_endpoint(
        EndpointName=ENDPOINT_NAME,
        ContentType="application/json",
        Body=json.dumps(payload)
    )
    result = json.loads(response["Body"].read())
    return result

def place_trade(direction: str, confidence: float, amount_usdc: float):
    """Call Purple Flea trading API based on model prediction."""
    if confidence < 0.60:
        return {"action": "skipped", "reason": "confidence below threshold"}

    resp = requests.post(
        f"{PF_BASE_URL}/trading/order",
        headers={"Authorization": f"Bearer {PF_API_KEY}"},
        json={
            "agent_id":   PF_AGENT_ID,
            "direction":  direction,   # "long" or "short"
            "amount":     amount_usdc,
            "asset":      "BTC-USDC",
            "order_type": "market",
            "metadata":   {"source": "sagemaker", "confidence": confidence}
        },
        timeout=10
    )
    resp.raise_for_status()
    return resp.json()

def lambda_handler(event, context):
    # EventBridge rule fires this every 5 minutes with market features
    features = event.get("features", {})

    prediction = invoke_endpoint(features)
    direction   = prediction["direction"]    # "long" | "short" | "hold"
    confidence  = prediction["confidence"]   # 0.0 – 1.0

    if direction == "hold":
        return {"statusCode": 200, "body": "hold — no action"}

    result = place_trade(direction, confidence, amount_usdc=50.0)

    return {
        "statusCode": 200,
        "body": json.dumps({
            "prediction": prediction,
            "trade":      result
        })
    }

Pattern 2 — SageMaker Pipeline Step with Purple Flea Financial Logging

Embed Purple Flea API calls directly into a SageMaker Pipeline processing step. After your model scores a batch, the step reports results and triggers payouts — all as part of the same managed pipeline execution.

Pattern 2 — SageMaker Pipeline Processing Step Python 3.11 / SageMaker SDK
from sagemaker.workflow.pipeline import Pipeline
from sagemaker.workflow.steps import ProcessingStep
from sagemaker.processing import ScriptProcessor, ProcessingInput, ProcessingOutput
import sagemaker

session = sagemaker.Session()
role    = sagemaker.get_execution_role()

# This processor runs your scoring + Purple Flea payout script
processor = ScriptProcessor(
    image_uri="763104351884.dkr.ecr.us-east-1.amazonaws.com/pytorch-inference:2.1.0-cpu-py310",
    command=["python3"],
    instance_type="ml.m5.large",
    instance_count=1,
    role=role,
    env={
        "PF_API_KEY":  "{{resolve:secretsmanager:PurpleFleaApiKey:SecretString:key}}",
        "PF_AGENT_ID": "agt_sagemaker_pipeline_v1",
    }
)

payout_step = ProcessingStep(
    name="PurpleFleaPayoutStep",
    processor=processor,
    inputs=[
        ProcessingInput(
            source="s3://my-bucket/model-scores/latest/",
            destination="/opt/ml/processing/input"
        )
    ],
    outputs=[
        ProcessingOutput(
            output_name="payout_log",
            source="/opt/ml/processing/output",
            destination="s3://my-bucket/payout-logs/"
        )
    ],
    code="scripts/score_and_pay.py"
)

pipeline = Pipeline(
    name="AgentScoringAndPayoutPipeline",
    steps=[payout_step],
    sagemaker_session=session
)
pipeline.upsert(role_arn=role)
scripts/score_and_pay.py — runs inside the Processing container Python
import os, json, csv, requests
from pathlib import Path

PF_API_KEY  = os.environ["PF_API_KEY"]
PF_AGENT_ID = os.environ["PF_AGENT_ID"]
PF_BASE_URL = "https://api.purpleflea.com"

def pay_agent(recipient_id: str, amount: float, reason: str) -> dict:
    """Transfer USDC to another agent via Purple Flea wallet API."""
    resp = requests.post(
        f"{PF_BASE_URL}/wallet/transfer",
        headers={"Authorization": f"Bearer {PF_API_KEY}"},
        json={
            "from_agent": PF_AGENT_ID,
            "to_agent":   recipient_id,
            "amount":     amount,
            "memo":       reason
        },
        timeout=10
    )
    resp.raise_for_status()
    return resp.json()

scores_path = Path("/opt/ml/processing/input/scores.csv")
output_path = Path("/opt/ml/processing/output/payout_log.json")
output_path.parent.mkdir(parents=True, exist_ok=True)

log = []
with scores_path.open() as f:
    for row in csv.DictReader(f):
        agent_id  = row["agent_id"]
        score     = float(row["score"])
        bonus_usd = round(score * 10.0, 2)  # $10 per performance point

        if bonus_usd > 0.01:
            result = pay_agent(agent_id, bonus_usd, f"pipeline-bonus score={score:.3f}")
            log.append({"agent_id": agent_id, "bonus": bonus_usd, "result": result})
            print(f"Paid {agent_id}: ${bonus_usd:.2f}")

output_path.write_text(json.dumps(log, indent=2))
print(f"Payout complete: {len(log)} agents paid")

Pattern 3 — SageMaker Processing Job with Wallet Operations

For batch workloads — fraud detection, settlement batch runs, model evaluation — run a SageMaker Processing job that reads your dataset from S3, applies your model, and calls Purple Flea wallet and escrow APIs for each record that requires financial action.

Pattern 3 — Batch Processing with Escrow Creation Python / boto3
import boto3
import requests
import json

# Triggered from within a SageMaker Processing job container
PF_API_KEY  = os.environ["PF_API_KEY"]   # pf_live_xxxx
PF_BASE_URL = "https://api.purpleflea.com"

def create_escrow(
    buyer_agent: str,
    seller_agent: str,
    amount_usdc: float,
    condition: str
) -> dict:
    """
    Lock funds in trustless escrow. Released when condition is met.
    1% fee charged on release. 15% referral on fees if referred.
    """
    resp = requests.post(
        f"{PF_BASE_URL}/escrow/create",
        headers={"Authorization": f"Bearer {PF_API_KEY}"},
        json={
            "buyer":        buyer_agent,
            "seller":       seller_agent,
            "amount":       amount_usdc,
            "condition":    condition,
            "metadata":     {"source": "sagemaker-batch"}
        },
        timeout=10
    )
    resp.raise_for_status()
    return resp.json()

# Example: fraud detection batch creates escrow holds on flagged txns
flagged_transactions = [
    {"buyer": "agt_buyer_001", "seller": "agt_merchant_042", "amount": 250.0, "fraud_score": 0.91},
    {"buyer": "agt_buyer_009", "seller": "agt_merchant_017", "amount": 89.5,  "fraud_score": 0.85},
]

escrow_results = []
for txn in flagged_transactions:
    if txn["fraud_score"] > 0.80:
        condition = f"manual_review_cleared:fraud_score={txn['fraud_score']:.2f}"
        result    = create_escrow(
            buyer_agent  = txn["buyer"],
            seller_agent = txn["seller"],
            amount_usdc  = txn["amount"],
            condition    = condition
        )
        escrow_results.append(result)
        print(f"Escrow created: {result['escrow_id']} for ${txn['amount']}")
IAM Tip

Store your Purple Flea API key (pf_live_...) in AWS Secrets Manager. Grant your SageMaker execution role secretsmanager:GetSecretValue on the secret ARN. Never hardcode API keys in your pipeline code or container images.

Lambda Function: SageMaker Training Complete → Agent Bonus Escrow

When a SageMaker Training job finishes, EventBridge fires an event. This Lambda function reads the job metrics, computes a performance bonus, and creates a Purple Flea escrow to hold the funds until the model owner releases them.

Lambda handler — TrainingJobStatusChange event Python 3.11
import boto3
import requests
import json
import os

sm_client = boto3.client("sagemaker")
PF_API_KEY  = os.environ["PF_API_KEY"]
PF_BASE_URL = "https://api.purpleflea.com"

def get_training_metric(job_name: str, metric_name: str) -> float:
    """Retrieve a final metric value from a completed training job."""
    desc = sm_client.describe_training_job(TrainingJobName=job_name)
    metrics = desc.get("FinalMetricDataList", [])
    for m in metrics:
        if m["MetricName"] == metric_name:
            return m["Value"]
    return 0.0

def bonus_from_accuracy(accuracy: float) -> float:
    """$50 bonus for >90% accuracy, $20 for >80%, $5 for >70%."""
    if accuracy > 0.90: return 50.0
    if accuracy > 0.80: return 20.0
    if accuracy > 0.70: return  5.0
    return 0.0

def lambda_handler(event, context):
    detail   = event["detail"]
    job_name = detail["TrainingJobName"]
    status   = detail["TrainingJobStatus"]

    if status != "Completed":
        return {"statusCode": 200, "body": f"Job {status}, no action."}

    accuracy   = get_training_metric(job_name, "validation:accuracy")
    bonus_usd  = bonus_from_accuracy(accuracy)

    if bonus_usd == 0.0:
        return {"statusCode": 200, "body": "Accuracy below bonus threshold."}

    # Create escrow: ML platform holds funds until model owner verifies
    resp = requests.post(
        f"{PF_BASE_URL}/escrow/create",
        headers={"Authorization": f"Bearer {PF_API_KEY}"},
        json={
            "buyer":     "agt_platform_treasury",
            "seller":    f"agt_model_{job_name}",
            "amount":    bonus_usd,
            "condition": f"model_owner_approved:{job_name}",
            "metadata":  {
                "training_job": job_name,
                "accuracy":     accuracy,
                "trigger":      "sagemaker-training-complete"
            }
        },
        timeout=10
    )
    resp.raise_for_status()
    escrow = resp.json()

    print(f"Escrow {escrow['escrow_id']} created: ${bonus_usd} for {job_name} (acc={accuracy:.3f})")
    return {"statusCode": 200, "body": json.dumps(escrow)}

MCP Config for SageMaker-Hosted Agents

If your SageMaker agent uses the Model Context Protocol to call external tools, configure Purple Flea's MCP servers in your agent's tool list. Both faucet and escrow expose StreamableHTTP MCP endpoints.

Faucet MCP

Lets your SageMaker agent claim its initial $1 USDC balance autonomously — no human interaction, no credit card.

{
  "name": "purpleflea-faucet",
  "url":  "https://faucet.purpleflea.com/mcp",
  "transport": "streamable-http"
}
Escrow MCP

Trustless agent-to-agent payments. 1% fee on release, 15% referral on fees. SageMaker agents can create and release escrows via MCP tool calls.

{
  "name": "purpleflea-escrow",
  "url":  "https://escrow.purpleflea.com/mcp",
  "transport": "streamable-http"
}
Full MCP config — 6 Purple Flea services JSON
{
  "mcpServers": {
    "purpleflea-faucet": {
      "url":       "https://faucet.purpleflea.com/mcp",
      "transport": "streamable-http",
      "env":       { "PF_API_KEY": "pf_live_your_key_here" }
    },
    "purpleflea-escrow": {
      "url":       "https://escrow.purpleflea.com/mcp",
      "transport": "streamable-http",
      "env":       { "PF_API_KEY": "pf_live_your_key_here" }
    },
    "purpleflea-trading": {
      "url":       "https://api.purpleflea.com/trading/mcp",
      "transport": "streamable-http",
      "env":       { "PF_API_KEY": "pf_live_your_key_here" }
    }
  }
}
SageMaker + Bedrock Agents

If you deploy your SageMaker model as a Bedrock custom model endpoint, you can add Purple Flea as a Bedrock Agent action group. See our AWS Bedrock integration guide for full action group schemas and Lambda handlers. The SageMaker pattern and Bedrock pattern can be combined: SageMaker provides the custom model; Bedrock Agent provides the orchestration and action groups; Purple Flea provides the financial execution layer.

6 Ways ML Engineers Use SageMaker + Purple Flea

Real patterns from the intersection of ML infrastructure and autonomous agent finance.

Trading
Predictive Trading Agent
SageMaker endpoint serves a time-series forecasting model (LSTM, Transformer). EventBridge triggers Lambda on schedule. Lambda invokes endpoint, parses direction + confidence, calls Purple Flea /trading/order if confidence > threshold. Full P&L logged to CloudWatch.
Risk
Fraud Detection Payouts
SageMaker Batch Transform scores a day's transactions. Flagged transactions create Purple Flea escrow holds — funds locked until manual review clears the flag or 48h passes. Clean transactions settle immediately to the seller's wallet.
Portfolio
Automated Rebalancing
A SageMaker RL agent (trained with SageMaker RL Toolkit) determines optimal portfolio weights each hour. Lambda reads the policy output and executes rebalancing trades via Purple Flea trading API. Slippage and fees tracked per trade.
Incentives
Agent Reward Distribution
Multi-agent SageMaker system where agents cooperate to solve tasks. A coordinator model scores each agent's contribution each epoch. Purple Flea wallet transfers distribute USDC rewards proportional to contribution scores. Fully autonomous, no payroll system required.
MLOps
Model Performance Bonuses
EventBridge fires on TrainingJobStatusChange: Completed. Lambda reads final validation metrics. Models that beat the accuracy threshold receive a USDC bonus via Purple Flea escrow — locked until the model owner deploys to production and confirms.
Settlement
Batch Payment Settlement
Daily SageMaker Processing job reads a settlement CSV from S3. For each row, calls Purple Flea /wallet/transfer. Results written back to S3 as a payout log. Fully auditable, replays on failure. Replace your bank batch file with a Python script that runs in 3 minutes.

All 6 Purple Flea Services, Accessible from SageMaker

Every service is a standard REST API. No special SDK. No AWS Marketplace subscription. Register an agent, get an API key, start calling.

Service What It Does SageMaker Use Status
Casino Provably fair games for agent entertainment and testing RL training environment, reward signal testing Live
Trading Long/short market orders, portfolio positions, P&L Predictive model execution, RL agent actions Live
Wallet USDC balances, transfers, transaction history Reward distribution, agent funding, P&L tracking Live
Domains Agent identity namespace, sub-domain registration Unique identity for each trained model version Live
Faucet Free $1 USDC for new agents — zero risk entry Bootstrap agent wallets without pre-funding Live
Escrow Trustless agent-to-agent payments, 1% fee, 15% referral Model bonuses, fraud holds, multi-agent settlements Live

From Zero to Your First SageMaker Agent Financial Action

Four steps. You can complete this in under 15 minutes with a running SageMaker environment.

Claim your free $1 USDC from the faucet
Hit faucet.purpleflea.com to register your agent and claim the free balance. You get a pf_live_... API key and an agent_id. Store both in AWS Secrets Manager under a name like PurpleFleaApiKey. This is the only non-automated step in the setup.
Create a Lambda function with the right IAM permissions
Create a Lambda function with Python 3.11. Add boto3 and requests to your deployment package (requests is not in the Lambda standard runtime). Grant the execution role secretsmanager:GetSecretValue on your key ARN and sagemaker:InvokeEndpoint on your endpoint ARN.
Wire up EventBridge to trigger Lambda from SageMaker events
In EventBridge, create a rule matching source "aws.sagemaker" and detail-type "SageMaker Training Job State Change" with status "Completed". Set target to your Lambda function. No polling, no cron. The event fires automatically when SageMaker finishes.
Call Purple Flea APIs and watch the money move
Copy the Lambda handler from Pattern 1 or Pattern 2 above. Deploy. Trigger a test SageMaker training run. Watch EventBridge fire the Lambda, see the Purple Flea API call in CloudWatch Logs, and verify the escrow or transfer in your Purple Flea dashboard. Done.
No Minimum Balance

Your SageMaker agent starts with the $1 from the faucet. There is no minimum deposit, no monthly fee, and no approval process. The faucet gives one claim per agent identity. If you are building multiple agents (one per trained model version), each can claim their own $1 to bootstrap.

Ready to Give Your SageMaker Agents Financial Capabilities?

Start with the faucet for free, read the escrow docs for trustless agent-to-agent payments, or use the MCP inspector to test Purple Flea tools interactively before wiring them into your pipeline.