Overview

Vercel AI SDK is a TypeScript toolkit for building AI-powered applications with React, Next.js, Vue, and Svelte. RedPill works seamlessly with Vercel AI SDK using the OpenAI provider.
Perfect for building streaming chat UIs, AI-powered forms, and interactive AI experiences.

Installation

npm install ai openai

Basic Setup

Text Generation

import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

const redpill = createOpenAI({
  apiKey: process.env.REDPILL_API_KEY,
  baseURL: 'https://api.redpill.ai/v1'
});

async function main() {
  const { text } = await generateText({
    model: redpill('openai/gpt-4o'),
    prompt: 'Explain how TEE protects data privacy'
  });

  console.log(text);
}

main();

Streaming Text

import { streamText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

const redpill = createOpenAI({
  apiKey: process.env.REDPILL_API_KEY,
  baseURL: 'https://api.redpill.ai/v1'
});

async function main() {
  const result = streamText({
    model: redpill('openai/gpt-4o'),
    prompt: 'Write a story about privacy-first AI'
  });

  for await (const chunk of result.textStream) {
    process.stdout.write(chunk);
  }
}

main();

Next.js Chat Application

Route Handler (app/api/chat/route.ts)

import { streamText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

const redpill = createOpenAI({
  apiKey: process.env.REDPILL_API_KEY!,
  baseURL: 'https://api.redpill.ai/v1'
});

export async function POST(req: Request) {
  const { messages } = await req.json();

  const result = streamText({
    model: redpill('openai/gpt-4o'),
    messages,
    temperature: 0.7,
    maxTokens: 1000
  });

  return result.toDataStreamResponse();
}

Chat UI Component (app/page.tsx)

'use client';

import { useChat } from 'ai/react';

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
    api: '/api/chat'
  });

  return (
    <div className="flex flex-col h-screen max-w-2xl mx-auto p-4">
      {/* Messages */}
      <div className="flex-1 overflow-y-auto space-y-4 mb-4">
        {messages.map(message => (
          <div
            key={message.id}
            className={`p-4 rounded-lg ${
              message.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'
            }`}
          >
            <div className="font-bold mb-1">
              {message.role === 'user' ? 'You' : 'AI'}
            </div>
            <div>{message.content}</div>
          </div>
        ))}
        {isLoading && <div className="text-gray-500">AI is thinking...</div>}
      </div>

      {/* Input Form */}
      <form onSubmit={handleSubmit} className="flex gap-2">
        <input
          value={input}
          onChange={handleInputChange}
          placeholder="Type your message..."
          className="flex-1 p-2 border rounded"
          disabled={isLoading}
        />
        <button
          type="submit"
          disabled={isLoading}
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:bg-gray-400"
        >
          Send
        </button>
      </form>
    </div>
  );
}

Environment Variables (.env.local)

REDPILL_API_KEY=sk-your-api-key-here

Tool Calling (Function Calling)

import { generateText, tool } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
import { z } from 'zod';

const redpill = createOpenAI({
  apiKey: process.env.REDPILL_API_KEY!,
  baseURL: 'https://api.redpill.ai/v1'
});

async function main() {
  const result = await generateText({
    model: redpill('openai/gpt-4o'),
    prompt: 'What is the weather in Paris and San Francisco?',
    tools: {
      getWeather: tool({
        description: 'Get the current weather in a location',
        parameters: z.object({
          location: z.string().describe('The city name'),
          unit: z.enum(['celsius', 'fahrenheit']).optional()
        }),
        execute: async ({ location, unit = 'celsius' }) => {
          // API call to weather service
          return {
            location,
            temperature: 22,
            unit,
            condition: 'sunny'
          };
        }
      })
    },
    maxSteps: 5  // Allow multiple tool calls
  });

  console.log(result.text);
}

main();

Streaming with Tool Calls

import { streamText, tool } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
import { z } from 'zod';

const redpill = createOpenAI({
  apiKey: process.env.REDPILL_API_KEY!,
  baseURL: 'https://api.redpill.ai/v1'
});

async function main() {
  const result = streamText({
    model: redpill('openai/gpt-4o'),
    prompt: 'Calculate the sum of 15 and 27, then multiply by 3',
    tools: {
      calculate: tool({
        description: 'Perform mathematical calculations',
        parameters: z.object({
          expression: z.string().describe('Math expression to evaluate')
        }),
        execute: async ({ expression }) => {
          return { result: eval(expression) };
        }
      })
    }
  });

  for await (const chunk of result.fullStream) {
    if (chunk.type === 'text-delta') {
      process.stdout.write(chunk.textDelta);
    } else if (chunk.type === 'tool-call') {
      console.log('\nTool call:', chunk.toolName, chunk.args);
    } else if (chunk.type === 'tool-result') {
      console.log('Tool result:', chunk.result);
    }
  }
}

main();

Multi-Model Support

Switch between different AI providers seamlessly:
import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

const redpill = createOpenAI({
  apiKey: process.env.REDPILL_API_KEY!,
  baseURL: 'https://api.redpill.ai/v1'
});

// Use GPT-4o for general tasks
const gpt4Result = await generateText({
  model: redpill('openai/gpt-4o'),
  prompt: 'Summarize this article...'
});

// Use Claude for analysis
const claudeResult = await generateText({
  model: redpill('anthropic/claude-3.5-sonnet'),
  prompt: 'Analyze this data...'
});

// Use DeepSeek for coding
const deepseekResult = await generateText({
  model: redpill('deepseek/deepseek-chat'),
  prompt: 'Write a React component...'
});

// Use Phala for sensitive data
const phalaResult = await generateText({
  model: redpill('phala/qwen-2.5-7b-instruct'),
  prompt: 'Process this confidential information...'
});

React Server Components

// app/generate/page.tsx
import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

const redpill = createOpenAI({
  apiKey: process.env.REDPILL_API_KEY!,
  baseURL: 'https://api.redpill.ai/v1'
});

export default async function Page() {
  const { text } = await generateText({
    model: redpill('openai/gpt-4o'),
    prompt: 'Generate a creative tagline for a privacy-first AI platform'
  });

  return (
    <div className="p-8">
      <h1 className="text-2xl font-bold mb-4">Generated Tagline</h1>
      <p className="text-lg">{text}</p>
    </div>
  );
}

Structured Output

Generate type-safe structured data:
import { generateObject } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
import { z } from 'zod';

const redpill = createOpenAI({
  apiKey: process.env.REDPILL_API_KEY!,
  baseURL: 'https://api.redpill.ai/v1'
});

async function main() {
  const { object } = await generateObject({
    model: redpill('openai/gpt-4o'),
    schema: z.object({
      name: z.string(),
      age: z.number(),
      occupation: z.string(),
      skills: z.array(z.string())
    }),
    prompt: 'Generate a profile for a software engineer named Alice'
  });

  console.log(object);
  // TypeScript knows the exact shape:
  // { name: string, age: number, occupation: string, skills: string[] }
}

main();

Error Handling

import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

const redpill = createOpenAI({
  apiKey: process.env.REDPILL_API_KEY!,
  baseURL: 'https://api.redpill.ai/v1'
});

async function main() {
  try {
    const result = await generateText({
      model: redpill('openai/gpt-4o'),
      prompt: 'Hello!'
    });

    console.log(result.text);
  } catch (error) {
    if (error instanceof Error) {
      console.error('Error:', error.message);

      // Handle specific error types
      if (error.message.includes('rate limit')) {
        console.log('Rate limited, retrying...');
      } else if (error.message.includes('insufficient credits')) {
        console.log('Please add credits to your account');
      }
    }
  }
}

main();

Supported Models

All RedPill models work with Vercel AI SDK:
ModelUse Case
openai/gpt-4oGeneral purpose, chat
anthropic/claude-3.5-sonnetReasoning, analysis
deepseek/deepseek-chatCoding, technical tasks
google/gemini-2.0-flashFast responses
phala/qwen-2.5-7b-instructConfidential data (TEE)

View All Models

Browse 218+ supported models →

Example Use Cases

Chatbot

Build a streaming chat interface with Next.js

Content Generator

Generate blog posts, summaries, and creative content

AI Forms

Create forms with AI-powered suggestions

Data Extraction

Extract structured data from unstructured text

Resources

Next Steps