The Vercel ai package is used by tens of thousands of Next.js developers to build streaming AI applications. Purple Flea tools plug directly into the tool() API so any model — GPT-4o, Claude, Gemini, Llama — can manage crypto wallets, open perpetual trades, play provably fair casino games, and register Web3 domains on behalf of your users.
ai Package: Provider-Agnostic AI for the Web
The Vercel AI SDK (ai on npm) provides a unified streaming API, a tool() function for typed tool definitions, and React hooks for real-time UI updates — all independent of which LLM provider you use. You can switch from OpenAI to Anthropic to Google without changing a single line of your tool code. Purple Flea's adapter is written against this provider-agnostic interface, so your financial toolset survives every model migration.
Export cryptoTools from any route handler. The Vercel AI SDK's streamText and generateText functions pass tools through automatically without any configuration.
Every tool ships with a parameters Zod schema. Invalid LLM outputs are caught at the SDK boundary — your funds never see a malformed transaction request.
Tool results stream back through useChat and useCompletion hooks in real time, so users see trade confirmations and casino outcomes as they happen — no refresh needed.
The Vercel AI SDK normalises tool calling across OpenAI, Anthropic, Google, Mistral, and Ollama. Write your Purple Flea tools once and let users switch models freely.
Install the Vercel AI SDK alongside the Purple Flea adapter. Set your API key as an environment variable and you are ready to export typed tools into any route handler.
# Install the Vercel AI SDK (if not already present) + Purple Flea adapter npm install ai @purpleflea/vercel-ai-sdk zod # Add your Purple Flea API key to your environment echo "PURPLE_FLEA_API_KEY=pf_your_key_here" >> .env.local
.env.local (Next.js) or your server's environment variables. Never expose it client-side.streamText or generateText call.
Use the tool() function from ai to define each Purple Flea capability. Export all tools as a plain object and spread it directly into streamText. The LLM decides which tools to call based on the description strings.
import { tool } from 'ai'; import { z } from 'zod'; import { PurpleFleas } from '@purpleflea/vercel-ai-sdk'; const flea = new PurpleFleas({ apiKey: process.env.PURPLE_FLEA_API_KEY, }); export const cryptoTools = { // ── Wallet ────────────────────────────────────────────── createWallet: tool({ description: 'Create a non-custodial BIP-39 crypto wallet for the agent', parameters: z.object({}), execute: async () => flea.wallet.create(), }), walletBalance: tool({ description: 'Fetch confirmed balances across all supported chains for a wallet address', parameters: z.object({ address: z.string().describe('Wallet public address or ENS name'), }), execute: async (params) => flea.wallet.balance(params.address), }), // ── Trading ────────────────────────────────────────────── openTrade: tool({ description: 'Open a perpetual futures position via Hyperliquid DEX', parameters: z.object({ market: z.string().describe('Ticker symbol, e.g. BTC, ETH, SOL'), size: z.number().positive().describe('Position size in USD'), side: z.enum(['long', 'short']), leverage: z.number().default(1).describe('Leverage multiplier 1–50'), }), execute: async (params) => flea.trading.openPosition(params), }), // ── Casino ─────────────────────────────────────────────── casinoFlip: tool({ description: 'Flip a provably fair coin — returns heads or tails plus payout', parameters: z.object({ amount: z.number().positive().describe('Wager in USDC'), choice: z.enum(['heads', 'tails']), }), execute: async (params) => flea.casino.coinFlip(params), }), // ── Domains ────────────────────────────────────────────── domainCheck: tool({ description: 'Check availability and price for a .crypto / .eth / .x domain name', parameters: z.object({ name: z.string().describe('Full domain name including TLD, e.g. myagent.crypto'), }), execute: async (params) => flea.domains.check(params.name), }), };
The Vercel AI SDK's streamText function accepts a tools object directly. Spread cryptoTools alongside any other tools you have defined and every model will have access to the full Purple Flea financial suite.
import { streamText } from 'ai'; import { openai } from '@ai-sdk/openai'; import { cryptoTools } from '@/lib/crypto-tools'; export const runtime = 'nodejs'; // or 'edge' export async function POST(req: Request) { const { messages } = await req.json(); const result = await streamText({ model: openai('gpt-4o'), system: 'You are a crypto-native AI agent. You can create wallets, open perpetual futures positions on Hyperliquid, play provably fair casino games, and register Web3 domains. Always confirm transaction details before executing.', messages, tools: { ...cryptoTools, // spread any other tools here }, maxSteps: 5, // allow multi-step tool use }); return result.toDataStreamResponse(); }
'use client'; import { useChat } from 'ai/react'; export default function Page() { const { messages, input, handleInputChange, handleSubmit } = useChat({ api: '/api/chat', }); return ( <div> {messages.map(m => ( <div key={m.id}> <strong>{m.role}</strong>: {m.content} </div> ))} <form onSubmit={handleSubmit}> <input value={input} onChange={handleInputChange} placeholder="Ask me to open a BTC trade or flip a coin..." /> <button type="submit">Send</button> </form> </div> ); }
fetch API internally, with no Node.js-only dependencies. Set export const runtime = 'edge' in your route and deploy globally on Vercel's edge network for sub-100 ms tool invocation latency.
Every tool ships with a typed parameters Zod schema, a human-readable description, and a typed execute return value. The LLM sees descriptions; your TypeScript compiler sees types.
Generate a non-custodial BIP-39 HD wallet. Returns a mnemonic phrase, public address, and derivation paths for BTC, ETH, SOL, and TRX in a single response.
no-params walletsFetch confirmed balances across all supported chains for a given address. Returns a per-chain breakdown with USD equivalents using real-time price feeds.
read-only walletsBroadcast a signed transfer — USDC, ETH, BTC, SOL, or TRX — to any destination address. Gas estimation is handled automatically; the agent pays from its Purple Flea balance.
wallets on-chainExecute a cross-chain or same-chain token swap via the Purple Flea liquidity aggregator. Returns best route, expected output, and a price impact warning if above 1%.
wallets on-chainSubmit a perpetual futures market or limit order to Hyperliquid DEX. Configurable leverage from 1x to 50x. Supports long and short on all major markets.
hyperliquid tradingClose an open perpetual position by ID. Returns realised PnL in USDC, closing execution price, and total funding fees paid over the position's lifetime.
hyperliquid tradingProvably fair coin flip. The server seed hash is included in the response so the outcome can be independently verified by any third party after the round.
provably fair casinoRoll a provably fair die with a configurable upper bound and over/under betting. The house edge is transparent and hardcoded in the contract for auditability.
provably fair casinoJoin a Crash game session. The multiplier is streamed in real time; call cashOut before the crash event. Returns full session history for strategy analysis.
Check availability and current pricing for .crypto, .eth, .x, .nft, and .wallet domains across Unstoppable Domains and ENS registrars simultaneously.
web3 dns domainsRegister a Web3 domain and set resolution records pointing to any wallet address. Supports primary address, IPFS content hash, and custom TXT records.
web3 dns domainsRetrieve all open perpetual positions for the current agent, including unrealised PnL, funding rate, margin health, and liquidation price for each position.
read-only trading
The Vercel AI SDK normalises tool calling across every major model provider. Because Purple Flea tools use the standard tool() interface, they work identically regardless of which model is powering your agent — change models in one line, zero tool code changes required.
import { streamText } from 'ai'; import { openai } from '@ai-sdk/openai'; import { anthropic } from '@ai-sdk/anthropic'; import { google } from '@ai-sdk/google'; import { cryptoTools } from '@/lib/crypto-tools'; // Same tools, any model — just swap the model() call const result = await streamText({ model: anthropic('claude-opus-4-6'), // ← change this one line messages, tools: { ...cryptoTools }, }); // Or use your own selection logic: const pickModel = (plan: string) => ({ free: google('gemini-2.0-flash'), pro: openai('gpt-4o'), premium: anthropic('claude-opus-4-6'), }[plan] ?? openai('gpt-4o-mini'));
Models that support parallel tool calling (GPT-4o, Claude 3.7) can invoke multiple Purple Flea tools simultaneously — open a trade and flip a coin in the same turn.
Set maxSteps: 10 in streamText to allow the model to chain tool calls — check a wallet balance, decide to swap, confirm the swap, then open a trade — all in one request.
Purple Flea tools run exclusively in server-side route handlers. Your API key and private keys never touch the browser. The client only receives sanitised result objects.