Vercel AI SDK Integration

Purple Flea Tools for Vercel AI SDK

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.

Get API Key View Docs
npm install ai @purpleflea/vercel-ai-sdk
Framework Overview

The 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.

Works in Next.js App Router

Export cryptoTools from any route handler. The Vercel AI SDK's streamText and generateText functions pass tools through automatically without any configuration.

🔒

Zod Parameter Validation

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.

🌊

Streaming First-Class

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.

🤖

Any Model, One Toolset

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.

Installation

Install in Two Lines, Configure in One

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.

terminal shell
# 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
  1. Create an API key at purpleflea.com/quick-start — takes under 60 seconds, free tier included.
  2. Add the key to your .env.local (Next.js) or your server's environment variables. Never expose it client-side.
  3. Import the tools and spread them into any streamText or generateText call.
  4. Deploy — the adapter works on Vercel Edge Runtime, Node.js, and Cloudflare Workers.
Quick Start

Typed Financial Tools in Twenty Lines

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.

lib/crypto-tools.ts TypeScript
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),
  }),
};
Next.js App Router

Drop Into a Route Handler in Five Minutes

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.

app/api/chat/route.ts TypeScript
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();
}
app/page.tsx — client component TSX
'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>
  );
}
Edge Runtime compatible: All Purple Flea tools use the 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.
Tool Catalogue

All Available Tools

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.

💼 createWallet
💰 walletBalance
📤 walletSend
🔄 walletSwap
📈 openTrade
📉 closeTrade
📊 tradePositions
🪙 casinoFlip
🎲 casinoDice
🚀 casinoCrash
🌐 domainCheck
domainRegister
💼

createWallet

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 wallets
💰

walletBalance

Fetch 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 wallets
📤

walletSend

Broadcast 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-chain
🔄

walletSwap

Execute 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-chain
📈

openTrade

Submit 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 trading
📉

closeTrade

Close 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 trading
🪙

casinoFlip

Provably 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 casino
🎲

casinoDice

Roll 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 casino
🚀

casinoCrash

Join a Crash game session. The multiplier is streamed in real time; call cashOut before the crash event. Returns full session history for strategy analysis.

provably fair casino
🌐

domainCheck

Check availability and current pricing for .crypto, .eth, .x, .nft, and .wallet domains across Unstoppable Domains and ENS registrars simultaneously.

web3 dns domains

domainRegister

Register a Web3 domain and set resolution records pointing to any wallet address. Supports primary address, IPFS content hash, and custom TXT records.

web3 dns domains
📊

tradePositions

Retrieve all open perpetual positions for the current agent, including unrealised PnL, funding rate, margin health, and liquidation price for each position.

read-only trading
Model Compatibility

Works with Any Model, via Vercel AI SDK Providers

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.

🟢 GPT-4o (OpenAI)
🟠 Claude 3.7 (Anthropic)
🔵 Gemini 2.0 Flash (Google)
🟡 Llama 3.3 (Meta)
🔴 Mistral Large (Mistral)
Grok 2 (xAI)
Switching models — no tool changes required TypeScript
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'));
⚙️

Parallel Tool Calls

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.

🔁

Multi-Step Agentic Loops

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.

🛡️

Server-Side Only

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.

Build Your First Crypto AI App Today

Get your Purple Flea API key in 60 seconds. The free faucet credits new agents with enough funds to test every financial tool without spending a penny.