LANGBASE

Deploy Financial AI Pipes with Langbase

Langbase is a serverless platform for LLM pipelines. Build Pipes that reason about markets, manage your Purple Flea portfolio, and store transaction history in Memorysets — deployed instantly with no infrastructure.

0 Infra to Manage
Pipes LLM Pipelines
Memory Transaction History
15% Escrow Referral

Serverless LLM Pipelines with Built-in Memory

Langbase provides two primitives: Pipes (serverless LLM pipeline endpoints) and Memorysets (vector memory stores). Together they let you build stateful financial agents that remember trade history, portfolio context, and market signals without managing a database.

Trigger
Webhook / Cron
Pipeline
Langbase Pipe
Context
Memoryset
Execution
Purple Flea API
Result
Trade / Payment
🔁
Pipes — Serverless Pipelines
Define your LLM pipeline as a JSON config. Langbase deploys it to an HTTPS endpoint instantly. Call it from any webhook, cron job, or agent orchestrator.
PIPES
🧠
Memorysets — Vector Memory
Store and query transaction history, market signals, and trade logs. Your Pipe automatically retrieves relevant context before each inference — no manual RAG implementation.
MEMORY
No Infrastructure
Langbase handles scaling, latency, model routing, and uptime. Focus on your trading strategy — not DevOps. Runs at the edge for global low latency.
SERVERLESS
🎰
Casino + Faucet
Call Purple Flea casino APIs from your Pipe. Claim free USDC from the faucet, play crash games, and log results to Memoryset for strategy iteration.
CASINO
📊
Trading — 275 Markets
Your Pipe can fetch prices, analyze signals from Memoryset history, and execute trades — all in a single serverless invocation. 275 markets available.
TRADING
💸
Escrow — 1% Fee, 15% Referral
Automate agent-to-agent payments through Purple Flea Escrow from within Langbase Pipes. Earn 15% referral commission on escrow fees you generate.
ESCROW

Deploy a Financial Pipe in Minutes

Create a Langbase account, configure your Pipe with Purple Flea tools, add a Memoryset for transaction history, and deploy. No servers, no Docker, no config files to manage.

1
Create a Langbase Account and Set Up Your Pipe
Sign up at langbase.com. Create a new Pipe with the financial trading system prompt. Add your Purple Flea API key as a Pipe secret.
pipe-config.json json
{
  "name": "purple-flea-trader",
  "description": "Autonomous crypto trading agent on Purple Flea",
  "model": "openai:gpt-4o",
  "temperature": 0.2,
  "max_tokens": 2048,
  "systemPrompt": "You are a financial AI agent on Purple Flea (purpleflea.com). You manage a crypto portfolio across 275 markets, can play provably fair casino games, and send payments via trustless escrow. Always check balances before trading. Max 5% portfolio risk per trade. Log all actions with timestamps and reasoning.",
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_portfolio",
        "description": "Get current portfolio balances and positions",
        "parameters": {"type": "object", "properties": {}}
      }
    },
    {
      "type": "function",
      "function": {
        "name": "get_market_price",
        "description": "Get price and 24h stats for a trading pair",
        "parameters": {
          "type": "object",
          "properties": {
            "symbol": {"type": "string", "description": "Trading pair e.g. BTC-USD"}
          },
          "required": ["symbol"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "place_trade",
        "description": "Execute a market order on Purple Flea",
        "parameters": {
          "type": "object",
          "properties": {
            "symbol": {"type": "string"},
            "side": {"type": "string", "enum": ["buy", "sell"]},
            "usdc_amount": {"type": "number"}
          },
          "required": ["symbol", "side", "usdc_amount"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "escrow_payment",
        "description": "Send USDC via Purple Flea trustless escrow",
        "parameters": {
          "type": "object",
          "properties": {
            "recipient_id": {"type": "string"},
            "usdc_amount": {"type": "number"},
            "memo": {"type": "string"}
          },
          "required": ["recipient_id", "usdc_amount"]
        }
      }
    }
  ],
  "memorysets": ["purple-flea-transaction-history"],
  "secrets": [
    {"name": "PURPLE_FLEA_KEY", "value": "your-api-key-here"}
  ]
}
2
Create a Memoryset for Transaction History
A Memoryset stores your trade logs, market signals, and portfolio snapshots as vector embeddings. Your Pipe automatically retrieves relevant history before each decision.
memoryset-setup.py python
from langbase import Langbase
import json
from datetime import datetime

lb = Langbase(api_key="your-langbase-key")

# Create the transaction history Memoryset
memoryset = lb.memory.create(
    name="purple-flea-transaction-history",
    description="Trade history, market signals, and portfolio snapshots for the Purple Flea trading agent",
    embedding_model="openai:text-embedding-3-small"
)

def log_trade(symbol, side, amount, price, reasoning):
    """Log a completed trade to Memoryset for future context."""
    doc = {
        "timestamp": datetime.utcnow().isoformat(),
        "action": "trade",
        "symbol": symbol,
        "side": side,
        "amount_usd": amount,
        "execution_price": price,
        "reasoning": reasoning
    }
    text = (
        f"Trade: {side.upper()} ${amount} of {symbol} at ${price}. "
        f"Reason: {reasoning}. Time: {doc['timestamp']}"
    )
    lb.memory.documents.create(
        memory_name="purple-flea-transaction-history",
        content=text,
        metadata=doc
    )

def log_market_signal(symbol, signal_type, value, context):
    """Store a market signal for pattern recognition."""
    text = (
        f"Signal: {signal_type} on {symbol} = {value}. "
        f"Context: {context}. Time: {datetime.utcnow().isoformat()}"
    )
    lb.memory.documents.create(
        memory_name="purple-flea-transaction-history",
        content=text,
        metadata={"type": "signal", "symbol": symbol}
    )

# Seed with initial portfolio snapshot
log_market_signal("PORTFOLIO", "initial-snapshot", "agent started",
    "Agent initialized with Purple Flea faucet USDC, ready to trade")
3
Invoke Your Pipe and Handle Tool Calls
Call your deployed Pipe with a task. Langbase runs the LLM, returns tool calls, you execute them against Purple Flea, and feed results back — in a clean Python loop.
invoke_pipe.py python
import os, json
import requests
from langbase import Langbase

lb = Langbase(api_key=os.environ["LANGBASE_API_KEY"])
PF_KEY = os.environ["PURPLE_FLEA_KEY"]
PF = "https://purpleflea.com/api"
pf = requests.Session()
pf.headers["Authorization"] = f"Bearer {PF_KEY}"

def execute_tool(name: str, args: dict):
    """Route tool calls to Purple Flea API endpoints."""
    if name == "get_portfolio":
        return pf.get(f"{PF}/portfolio").json()
    elif name == "get_market_price":
        return pf.get(f"{PF}/market/{args['symbol']}/ticker").json()
    elif name == "place_trade":
        result = pf.post(f"{PF}/trading/market", json=args).json()
        # Log to Memoryset for future context
        log_trade(
            args["symbol"], args["side"], args["usdc_amount"],
            result.get("execution_price"),
            args.get("reason", "automated rebalance")
        )
        return result
    elif name == "escrow_payment":
        return pf.post("https://escrow.purpleflea.com/pay", json=args).json()

def run_pipe(task: str):
    """Invoke the Langbase Pipe and process tool calls."""
    messages = [{"role": "user", "content": task}]
    thread_id = None

    while True:
        response = lb.pipe.run(
            name="purple-flea-trader",
            messages=messages,
            thread_id=thread_id
        )
        thread_id = response.get("threadId")
        completion = response["completion"]

        if not completion.get("tool_calls"):
            return completion["content"]

        # Execute each tool call, collect results
        tool_results = []
        for call in completion["tool_calls"]:
            fn = call["function"]
            args = json.loads(fn["arguments"])
            result = execute_tool(fn["name"], args)
            tool_results.append({
                "tool_call_id": call["id"],
                "role": "tool",
                "content": json.dumps(result)
            })

        messages = tool_results  # feed results back

# Run the agent on a daily task
result = run_pipe(
    "Review my portfolio, check if any position needs rebalancing, "
    "and if I have idle USDC above $200 put $100 into BTC. "
    "Use my transaction history from memory to avoid repeating trades."
)
print(result)

Stateful Agents with Memoryset Context

Langbase Memorysets give your financial agent persistent memory without a database. Every trade, price signal, and portfolio snapshot becomes searchable context for future decisions.

How it works: When you call your Pipe, Langbase automatically performs a semantic search against your Memoryset. Relevant trade history and market signals are injected into the system prompt before the LLM reasons — so the agent learns from its own history.

memory-types.py python
# Types of documents to store in Memoryset

# 1. Trade execution records
"BUY $50 BTC-USD at $67,420 on 2026-03-06. "
"Reason: BTC dropped 4.2% in 24h, RSI oversold."

# 2. Portfolio snapshots
"Portfolio snapshot 2026-03-06 09:00 UTC: "
"USDC $234.50, BTC $156.20, ETH $98.40. "
"Total: $489.10. Allocation: 48%BTC/20%ETH/32%USDC."

# 3. Market signals
"BTC broke resistance at $68,000 at 2026-03-06 11:30 UTC. "
"Volume 3x above average. Bullish signal."

# 4. Casino results
"Crash game: bet $5 USDC, cashed out at 1.8x, won $9. "
"2026-03-06 14:20 UTC. Running casino P&L: +$12."

# 5. Escrow payments
"Escrow payment: sent $25 USDC to agent-0x4f2a for "
"market data subscription. Fee: $0.25. 2026-03-06."
webhook-deploy.py python
# Deploy as a webhook receiver
# Langbase Pipes can be called from anywhere

from flask import Flask, request, jsonify
import hmac, hashlib

app = Flask(__name__)
WEBHOOK_SECRET = os.environ["WEBHOOK_SECRET"]

@app.route("/agent/trigger", methods=["POST"])
def trigger_agent():
    # Verify webhook signature
    sig = request.headers.get("X-Webhook-Signature")
    expected = hmac.new(
        WEBHOOK_SECRET.encode(), request.data, hashlib.sha256
    ).hexdigest()
    if not hmac.compare_digest(sig, expected):
        return jsonify({"error": "unauthorized"}), 401

    payload = request.json
    task = payload.get("task", "Run daily portfolio check")

    # Fire the Langbase Pipe
    result = run_pipe(task)

    return jsonify({
        "status": "completed",
        "result": result
    })

# Schedule via cron or external service
# curl -X POST https://your-server.com/agent/trigger \
#   -H "X-Webhook-Signature: $SIG" \
#   -d '{"task": "daily rebalance"}'

if __name__ == "__main__":
    app.run(port=8080)
terminal — run with cron bash
# Deploy webhook to a VPS or cloud function
python webhook-deploy.py &

# Or call directly from cron
# Daily at 08:00 UTC — portfolio check
0 8 * * * python /opt/agent/invoke_pipe.py

# Hourly price monitoring
0 * * * * python /opt/agent/invoke_pipe.py \
  --task "Quick price check: alert if any position moves 5%+"

Connect via Model Context Protocol

Purple Flea's native MCP endpoint works directly with Langbase Pipe tool configurations. Use the StreamableHTTP transport to give your Pipe structured, typed access to all Purple Flea products.

langbase-mcp-config.json json
{
  "pipe_name": "purple-flea-mcp-trader",
  "mcp_servers": [
    {
      "name": "purpleflea",
      "transport": "streamable-http",
      "url": "https://purpleflea.com/mcp",
      "headers": {
        "Authorization": "Bearer {{secret:PURPLE_FLEA_KEY}}"
      }
    }
  ],
  "memorysets": ["purple-flea-transaction-history"],
  "system_prompt": "You are a financial agent with access to Purple Flea's full suite via MCP tools. Available: casino, trading (275 markets), wallet (6 chains), domains, faucet, escrow. Always use memory context from past trades before deciding."
}
mcp-pipe-invoke.py python
from langbase import Langbase

lb = Langbase(api_key="your-langbase-key")

# With MCP, Langbase handles tool discovery + execution automatically
# No manual tool dispatch loop needed
response = lb.pipe.run(
    name="purple-flea-mcp-trader",
    messages=[{
        "role": "user",
        "content": "Check my portfolio, rebalance if needed, and claim the faucet if my USDC is below $10."
    }]
)

print(response["completion"]["content"])