AI SDK by Vercel
The AI SDK by Vercel provides a unified interface for building AI applications, supporting various models like ChatGPT, Claude, and Gemini, either directly or via the Vercel AI Gateway. It simplifies interactions with providers such as OpenAI, Anthropic, and Google, offering features like tool-calling, structured output, and agentic capabilities. The current stable version is 6.0.168, with frequent patch releases and major version updates as new features and providers are integrated.
Common errors
-
Error: Missing OpenAI API key. Please set the OPENAI_API_KEY environment variable.
cause The required API key for the chosen AI provider is not set in the environment variables.fixSet the `OPENAI_API_KEY` environment variable with your actual OpenAI API key (or equivalent for other providers) before running your application. -
SyntaxError: Cannot use import statement outside a module
cause You are attempting to use ES Module (ESM) `import` syntax in a CommonJS (CJS) environment.fixEnsure your project is configured for ESM. For Node.js, add `"type": "module"` to your `package.json` file, or save your file with a `.mjs` extension. -
Error: Zod is a peer dependency of @ai-sdk/core. Please install it with 'npm install zod'.
cause The `zod` package, a required peer dependency for structured output and other features, is not installed in your project.fixInstall Zod: `npm install zod` or `yarn add zod`. -
Error: The engine "node" is incompatible with this module. Expected version ">=18". Got "16.14.0".
cause Your current Node.js version is older than the minimum required version (18) for the AI SDK.fixUpgrade your Node.js installation to version 18 or higher. Use a version manager like `nvm use 18` or `volta install node@18`.
Warnings
- breaking Version 6 of the AI SDK introduced significant API changes and a modular provider architecture. Direct usage of the `ai` package's core functions might require updates to adapt to the new API surface and separate provider packages.
- gotcha The AI SDK requires `zod` as a peer dependency, especially for features like structured output and tool definitions. It must be installed separately in your project.
- gotcha The AI SDK requires Node.js version 18 or higher due to its use of modern JavaScript features and API compatibility.
- gotcha API keys for AI providers (e.g., OpenAI, Anthropic, Google) are typically expected as environment variables (e.g., `OPENAI_API_KEY`). Not setting them will result in authentication errors.
Install
-
npm install ai -
yarn add ai -
pnpm add ai
Imports
- generate
const { generate } = require('ai');import { generate } from 'ai';
Quickstart
import { generate, openai } from 'ai';
async function main() {
// Ensure OPENAI_API_KEY is set in your environment variables
const result = await generate({
model: openai('gpt-4o-mini'),
prompt: 'Tell me a short, funny story about a robot.',
maxTokens: 100,
});
console.log('Generated text:', result.text);
}
main().catch(console.error);