Technology

Building AI Agents with Vercel AI SDK

Date Published

Curving abstract shapes with an orange and blue gradient

Introduction

AI agents are transforming how we interact with applications by automating complex workflows and providing intelligent responses. Vercel AI SDK simplifies AI agent development by offering seamless integration with AI models while leveraging Vercel's edge network for fast, scalable deployments. In this article, we’ll explore how to approach building an AI agent using the Vercel AI SDK.

Why Use Vercel AI SDK?

The Vercel AI SDK provides several benefits when building AI-powered applications:

Optimized Performance: Deploy AI agents on the edge for reduced latency.

Seamless Integration: Easily connect with OpenAI, Anthropic, Hugging Face, and other AI providers.

Streaming Responses: Enable real-time AI interactions with efficient streaming.

Built-in Security: Leverage Vercel's secure environment to manage API keys and protect sensitive data.

Serverless Scalability: Automatically scale your AI agents with Vercel’s infrastructure.

Prerequisites

To build an AI agent using the Vercel AI SDK, ensure you have the following:

A Vercel account

Node.js and npm installed

A Next.js project

API access to an AI provider like OpenAI

Step 1: Install Vercel AI SDK

Start by installing the required dependencies in your Next.js project:

npm install @vercel/ai openai

Step 2: Set Up an API Route

Create an API route in your Next.js project to handle AI responses. Inside the pages/api directory, create a file named chat.js:

import { OpenAI } from '@vercel/ai';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method Not Allowed' });
}

const { messages } = req.body;

try {
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages,
stream: true, // Enable real-time streaming
});

response.pipe(res);
} catch (error) {
res.status(500).json({ error: error.message });
}
}

Step 3: Create the Frontend UI

Now, create a simple UI component that interacts with the API:

import { useState } from 'react';

export default function ChatBot() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');

const sendMessage = async () => {
const newMessages = [...messages, { role: 'user', content: input }];
setMessages(newMessages);
setInput('');

const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: newMessages }),
});

const reader = response.body.getReader();
let result = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
result += new TextDecoder().decode(value);
setMessages([...newMessages, { role: 'assistant', content: result }]);
}
};

return (
<div>
<div>
{messages.map((msg, index) => (
<p key={index}><strong>{msg.role}:</strong> {msg.content}</p>
))}
</div>
<input value={input} onChange={(e) => setInput(e.target.value)} />
<button onClick={sendMessage}>Send</button>
</div>
);
}

Step 4: Deploy to Vercel

Once your AI agent is ready, deploy it on Vercel with a single command:

vercel

Ensure your environment variables (OPENAI_API_KEY) are set correctly in your Vercel project settings.

Conclusion

Building AI agents with the Vercel AI SDK enables you to create intelligent, scalable, and real-time applications with minimal effort. By leveraging Vercel’s infrastructure, you can deploy high-performing AI solutions that enhance user experiences. Start experimenting with AI agents today and integrate them into your applications seamlessly!