TypeScript AI Development: Building LLM Apps with Vercel AI SDK 2026
Build streaming AI applications with TypeScript, Next.js, and Vercel AI SDK
TypeScript AI Development: Vercel AI SDK 2026
The Vercel AI SDK has become the standard for TypeScript AI application development. Here's how to build production-quality AI features.
Installation
bash
npm install ai @ai-sdk/openai @ai-sdk/anthropic @ai-sdk/google
npm install zod # For structured generation
Basic Streaming Chat
typescript
// app/api/chat/route.ts
import { streamText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: anthropic('claude-sonnet-4-5'),
system: 'You are a helpful assistant.',
messages,
});
return result.toDataStreamResponse();
}
typescript
// app/components/chat.tsx
'use client';
import { useChat } from 'ai/react';export function Chat() {
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
api: '/api/chat',
});
return (
{messages.map((message) => (
p-3 rounded-lg ${message.role === 'user' ? 'bg-blue-100 ml-auto' : 'bg-gray-100'}}
>
{message.content}
))}
{isLoading && Thinking...}
);
}
Tool Calling
typescript
import { streamText, tool } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai('gpt-5'),
messages,
tools: {
getWeather: tool({
description: 'Get the current weather for a city',
parameters: z.object({
city: z.string().describe('City name'),
unit: z.enum(['celsius', 'fahrenheit']).default('celsius'),
}),
execute: async ({ city, unit }) => {
// Call weather API
const data = await fetch(https://api.weather.com?city=${city}&unit=${unit});
return await data.json();
},
}),
searchDatabase: tool({
description: 'Search the product database',
parameters: z.object({
query: z.string(),
limit: z.number().min(1).max(20).default(5),
}),
execute: async ({ query, limit }) => {
// Search vector database
return await vectorSearch(query, limit);
},
}),
},
maxSteps: 5, // Allow multi-step tool use
});
return result.toDataStreamResponse();
}
Structured Object Generation
typescript
import { generateObject } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { z } from 'zod';const ProductSchema = z.object({
name: z.string(),
price: z.number().positive(),
category: z.enum(['electronics', 'clothing', 'food', 'other']),
features: z.array(z.string()).min(1).max(10),
inStock: z.boolean(),
rating: z.number().min(0).max(5).optional(),
});
type Product = z.infer;
export async function extractProduct(description: string): Promise {
const { object } = await generateObject({
model: anthropic('claude-sonnet-4-5'),
schema: ProductSchema,
prompt: Extract product information from this description: ${description},
});
return object;
}
// Usage
const product = await extractProduct(
'Sony WH-1000XM5 wireless headphones, $349, great noise cancellation and 30-hour battery'
);
console.log(product);
// { name: 'Sony WH-1000XM5', price: 349, category: 'electronics', ... }
Multi-Model Router
typescript
import { anthropic } from '@ai-sdk/anthropic';
import { openai } from '@ai-sdk/openai';
import { google } from '@ai-sdk/google';
import type { LanguageModelV1 } from 'ai';type TaskType = 'coding' | 'analysis' | 'creative' | 'fast' | 'reasoning';
function selectModel(taskType: TaskType, tokenEstimate: number): LanguageModelV1 {
// Fast/cheap tasks
if (tokenEstimate < 2000 && taskType === 'fast') {
return openai('gpt-5-mini');
}
// Coding tasks
if (taskType === 'coding') {
return anthropic('claude-sonnet-4-5'); // Best for code
}
// Large context tasks
if (tokenEstimate > 100000) {
return google('gemini-2.5-pro'); // 1M context window
}
// Reasoning tasks
if (taskType === 'reasoning') {
return openai('o3'); // Best reasoning
}
// Default
return anthropic('claude-sonnet-4-5');
}
export async function smartGenerate(prompt: string, taskType: TaskType = 'analysis') {
const tokenEstimate = prompt.length / 4; // Rough estimate
const model = selectModel(taskType, tokenEstimate);
const { text } = await generateText({ model, prompt });
return text;
}
Embeddings + Vector Search
typescript
import { embed, embedMany } from 'ai';
import { openai } from '@ai-sdk/openai';// Generate embeddings for documents
export async function embedDocuments(texts: string[]) {
const { embeddings } = await embedMany({
model: openai.embedding('text-embedding-3-small'),
values: texts,
});
return embeddings; // number[][]
}
// Generate embedding for a query
export async function embedQuery(text: string) {
const { embedding } = await embed({
model: openai.embedding('text-embedding-3-small'),
value: text,
});
return embedding; // number[]
}
// Cosine similarity search
export function cosineSimilarity(a: number[], b: number[]): number {
const dot = a.reduce((sum, val, i) => sum + val * b[i], 0);
const magA = Math.sqrt(a.reduce((sum, val) => sum + val ** 2, 0));
const magB = Math.sqrt(b.reduce((sum, val) => sum + val ** 2, 0));
return dot / (magA * magB);
}
Conclusion
Vercel AI SDK is the TypeScript standard for AI apps in 2026. The unified API across all major providers, first-class streaming, and Zod-powered structured generation make it the best choice for Next.js and Node.js applications.
Also available in 中文.