Overview
Vercel AI SDK is a TypeScript toolkit for building AI-powered applications with React, Next.js, Vue, and Svelte. The platform 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.API_KEY,
baseURL: 'https://api.redpill.ai/v1'
});
async function main() {
const { text } = await generateText({
model: redpill('openai/gpt-5'),
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.API_KEY,
baseURL: 'https://api.redpill.ai/v1'
});
async function main() {
const result = streamText({
model: redpill('openai/gpt-5'),
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.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-5'),
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)
API_KEY=YOUR_API_KEY
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.API_KEY!,
baseURL: 'https://api.redpill.ai/v1'
});
async function main() {
const result = await generateText({
model: redpill('openai/gpt-5'),
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.API_KEY!,
baseURL: 'https://api.redpill.ai/v1'
});
async function main() {
const result = streamText({
model: redpill('openai/gpt-5'),
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.API_KEY!,
baseURL: 'https://api.redpill.ai/v1'
});
// Use GPU TEE for sensitive reasoning
const teeResult = await generateText({
model: redpill('z-ai/glm-5.1'),
prompt: 'Process this confidential information...'
});
// Use confidential (is_tee) model for systems engineering
const nearResult = await generateText({
model: redpill('z-ai/glm-5'),
prompt: 'Analyze this architecture...'
});
// Use GPT-5 for general tasks
const gptResult = await generateText({
model: redpill('openai/gpt-5'),
prompt: 'Summarize this article...'
});
// Use Claude for analysis
const claudeResult = await generateText({
model: redpill('anthropic/claude-sonnet-4.5'),
prompt: 'Analyze this data...'
});
// Use DeepSeek for coding
const deepseekResult = await generateText({
model: redpill('deepseek/deepseek-chat-v3.1'),
prompt: 'Write a React component...'
});
React Server Components
// app/generate/page.tsx
import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
const redpill = createOpenAI({
apiKey: process.env.API_KEY!,
baseURL: 'https://api.redpill.ai/v1'
});
export default async function Page() {
const { text } = await generateText({
model: redpill('openai/gpt-5'),
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.API_KEY!,
baseURL: 'https://api.redpill.ai/v1'
});
async function main() {
const { object } = await generateObject({
model: redpill('openai/gpt-5'),
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.API_KEY!,
baseURL: 'https://api.redpill.ai/v1'
});
async function main() {
try {
const result = await generateText({
model: redpill('openai/gpt-5'),
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 available models work with Vercel AI SDK:| Model | Use Case |
|---|---|
z-ai/glm-5.1 | Confidential reasoning (GPU TEE) |
z-ai/glm-5 | Confidential systems engineering (GPU TEE) |
qwen/qwen3.5-27b | Confidential general purpose (GPU TEE) |
openai/gpt-5 | General purpose, chat |
anthropic/claude-sonnet-4.5 | Reasoning, analysis |
deepseek/deepseek-chat-v3.1 | Coding, technical tasks |
google/gemini-2.5-flash | Fast responses |
View All Models
Browse 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
OpenAI SDK
Use the official OpenAI SDK
LangChain
Build with LangChain framework