Instructor Integration

Purple Flea + Instructor

Instructor gives you type-safe, validated LLM outputs. Purple Flea gives you crypto financial APIs. Together: AI agents that make well-typed trading decisions, validated before execution — eliminating hallucinated parameters.

Get Free API Key → View Docs

Why Structured Outputs Matter for Crypto Agents

When an LLM decides to make a trade, it needs to output precise parameters: symbol, side, size, leverage. A hallucinated value in any field causes real financial loss.

🎯
Validated Trade Parameters
Instructor validates that the LLM's trading decision includes all required fields (symbol, side, size) and that side is "long" or "short" — not "buy" or some hallucinated value.
🔄
Automatic Retries
If the LLM outputs an invalid trade structure (e.g., negative size, leverage > 50x), Instructor automatically retries with the validation error feedback. No silent failures.
🧩
Pydantic Models
Define your trading decisions, casino bets, and payment instructions as Pydantic models. The LLM fills them in; Instructor validates and retries until they're correct.

Integration Examples

Validated Trading Decisions

import instructor import purpleflea as pf from openai import OpenAI from pydantic import BaseModel, Field, validator from typing import Literal class TradeDecision(BaseModel): symbol: str = Field(..., description="e.g. BTC, ETH, SOL") side: Literal["long", "short"] size_usd: float = Field(..., gt=0, le=1000) leverage: int = Field(1, ge=1, le=10) reasoning: str confidence: float = Field(..., ge=0, le=1) @validator('symbol') def symbol_uppercase(cls, v): return v.upper() client = instructor.from_openai(OpenAI()) pf_client = pf.Client(api_key="YOUR_KEY") market_context = pf_client.trading.get_price("BTC") candles = pf_client.trading.get_candles("BTC", "1h", limit=24) decision = client.chat.completions.create( model="gpt-4o", response_model=TradeDecision, messages=[ {"role": "system", "content": "You are a crypto trader. Output your decision."}, {"role": "user", "content": f"BTC data: {market_context}, candles: {candles[-5:]}"} ] ) # decision is a validated TradeDecision object, never None print(f"Trade: {decision.side} {decision.symbol}") print(f"Confidence: {decision.confidence:.0%}") print(f"Reasoning: {decision.reasoning}") if decision.confidence > 0.7: trade = pf_client.trading.open_trade( symbol=decision.symbol, side=decision.side, size=decision.size_usd / market_context['price'], leverage=decision.leverage ) print(f"Executed: {trade['position_id']}")

Casino Bet Sizing with Validation

from pydantic import BaseModel, Field class CasinoBetDecision(BaseModel): game: Literal["dice", "roulette", "blackjack"] bet_amount: float = Field(..., gt=0, le=10) # Dice-specific (optional) dice_target: int | None = Field(None, ge=1, le=98) dice_direction: Literal["over", "under"] | None = None expected_value: float = Field(..., ge=-1, le=1) kelly_fraction: float = Field(..., gt=0, le=0.25) balance = pf_client.wallet.get_balance() bet = client.chat.completions.create( model="gpt-4o", response_model=CasinoBetDecision, messages=[{ "role": "user", "content": f"""Apply Kelly Criterion to decide a casino bet. Current balance: ${balance['total_usd']:.2f} Max bet: $10 (1% of bankroll) Available games: dice (2% house edge), roulette Output a bet decision with kelly_fraction <= 0.25""" }] ) # The bet is always valid — Instructor guarantees it if bet.game == "dice" and bet.dice_target: result = pf_client.casino.play_dice( bet_amount=str(bet.bet_amount), target=bet.dice_target, direction=bet.dice_direction ) print(f"Dice: {result['roll']} | Won: {result['won']}")

Type-Safe Crypto Agents

Instructor eliminates hallucinated parameters. Purple Flea executes with perfect precision. Get your free API key and build validated crypto agents today.