DEV Community

Alex Spinov
Alex Spinov

Posted on

Vercel AI SDK Has a Free API — Here's How to Build AI Chat Apps in 20 Lines of Code

Why Vercel AI SDK?

The Vercel AI SDK gives you unified API for building AI apps. One SDK, every LLM provider: OpenAI, Anthropic, Google, Mistral, and more. Plus streaming, tool calling, and structured output built-in.

Free and open source. Works with any framework.

Getting Started

npm install ai @ai-sdk/openai
Enter fullscreen mode Exit fullscreen mode

Simple Chat

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

const { text } = await generateText({
  model: openai("gpt-4o"),
  prompt: "Explain Docker in 3 sentences."
});
console.log(text);
Enter fullscreen mode Exit fullscreen mode

Streaming Chat

import { streamText } from "ai";
import { anthropic } from "@ai-sdk/anthropic";

const result = streamText({
  model: anthropic("claude-sonnet-4-20250514"),
  messages: [
    { role: "user", content: "Write a haiku about coding" }
  ]
});

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

Tool Calling

import { generateText, tool } from "ai";
import { z } from "zod";

const { text, toolResults } = await generateText({
  model: openai("gpt-4o"),
  tools: {
    weather: tool({
      description: "Get weather for a city",
      parameters: z.object({ city: z.string() }),
      execute: async ({ city }) => ({ temp: 22, condition: "sunny" })
    })
  },
  prompt: "Whats the weather in Tokyo?"
});
Enter fullscreen mode Exit fullscreen mode

Structured Output

import { generateObject } from "ai";
import { z } from "zod";

const { object } = await generateObject({
  model: openai("gpt-4o"),
  schema: z.object({
    name: z.string(),
    pros: z.array(z.string()),
    cons: z.array(z.string()),
    rating: z.number().min(1).max(10)
  }),
  prompt: "Review TypeScript as a programming language"
});

console.log(object);
Enter fullscreen mode Exit fullscreen mode

Next.js Route Handler

// app/api/chat/route.ts
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";

export async function POST(req: Request) {
  const { messages } = await req.json();
  const result = streamText({ model: openai("gpt-4o"), messages });
  return result.toDataStreamResponse();
}
Enter fullscreen mode Exit fullscreen mode

Supported Providers

Provider Package
OpenAI @ai-sdk/openai
Anthropic @ai-sdk/anthropic
Google @ai-sdk/google
Mistral @ai-sdk/mistral
Cohere @ai-sdk/cohere
AWS Bedrock @ai-sdk/amazon-bedrock

Need data for your AI app? Check out my Apify actors or email spinov001@gmail.com.

What AI SDK do you use? Share below!

Top comments (0)