Skip to main content

Quickstart

This quickstart guide will walk you through building your first AI application using the AI SDK. You’ll learn how to generate text, stream responses, and create structured outputs.

Prerequisites

Before you begin, make sure you have:

Setup

1

Create a new project

Create a new directory and initialize a Node.js project:
2

Install dependencies

Install the AI SDK and a provider package:
3

Configure your API key

Create a .env file and add your API key:
Never commit your .env file to version control. Add it to .gitignore.

Generate text

Let’s start with the most basic example - generating text from a prompt. Create a file called generate-text.ts:
Run the example:

What’s happening here?

  • generateText: The core function for generating text completions
  • model: Specifies which AI model to use (GPT-4o in this case)
  • prompt: The input text that guides the model’s response
  • result.text: The generated text response
  • result.usage: Token usage information (prompt tokens, completion tokens, total tokens)
  • result.finishReason: Why the model stopped generating (e.g., “stop”, “length”)

Stream text

For longer responses, streaming provides a better user experience by showing results as they’re generated. Create a file called stream-text.ts:
Run the example:

Key differences

  • streamText: Returns a stream instead of waiting for the complete response
  • result.textStream: An async iterable that yields text chunks as they arrive
  • Properties like usage and finishReason are promises that resolve when streaming completes

Generate structured data

Generate type-safe structured outputs using Zod schemas:
1

Install Zod

2

Create the example

Create a file called generate-object.ts:
3

Run the example

Why structured outputs?

  • Type safety: Full TypeScript support with schema validation
  • Reliability: The model is constrained to follow your schema
  • Integration: Easy to integrate with databases and APIs

Use tools

Tools allow AI models to perform actions and retrieve real-time information:

How tools work

  1. You define tools with input schemas and execute functions
  2. The model decides when to call tools based on the prompt
  3. The SDK automatically executes the tools and sends results back to the model
  4. The model uses the tool results to generate its final response

Using Vercel AI Gateway

If you prefer using the Vercel AI Gateway instead of direct provider packages:
Make sure your .env file has:

Next steps

Now that you’ve learned the basics, explore more advanced features:

Build a chat interface

Use React, Vue, or Svelte hooks to build chat UIs

Create agents

Build autonomous agents with tools and multi-step reasoning

Explore providers

Learn about all available AI providers and models

API reference

Dive into the complete API documentation

Example projects

Check out complete example applications:

Get help

If you run into issues: