AI Personal Learning
and practical guidance

Vercel AI SDK: Building AI-powered applications with popular front-end frameworks

General Introduction

The Vercel AI SDK is an open source tool developed by the Vercel team to help developers build AI applications using frameworks such as React, Svelte, Vue, and Solid. It supports multiple language modeling vendors, including OpenAI, Anthropic, Google Gemini The SDK provides a unified API interface that enables developers to quickly integrate AI functionality into their projects. The SDK also provides real-time streaming response and user interface generation capabilities, greatly simplifying the development process for AI applications.

 

Function List

  • Unified API interface: supports multiple AI model providers such as OpenAI, Anthropic, Google, etc.
  • Real-time Streaming Response: Allows text responses to be generated and displayed in real-time, enhancing the user experience.
  • Generate the user interface: use the React Server Components generates dynamic UI.
  • Multi-framework support: Compatible with React, Svelte, Vue, and Solid, providing broad applicability.
  • Community Support: Provides a GitHub Discussions community where users can ask questions and share projects.

 

Using Help

mounting

To get started with the Vercel AI SDK, you'll need:

  1. Environmental Preparation:
    • Make sure you have Node.js 18+ and pnpm installed.
    • Create a new project or add this SDK to an existing project.
  2. Install the SDK:
    • Open your terminal and navigate to your project directory.
    • Run the command pnpm add ai to install the SDK.
  3. Configure environment variables:
    • Depending on the AI model provider you are using (e.g. OpenAI), set the appropriate API key. Typically, you will need to add OPENAI_API_KEY or other relevant environment variables to the .env file.

 

Procedure for use

Basic Text Generation

import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
async function main() {
const { text } = await generateText({
model: openai('gpt-4-turbo'), system: 'You are a friendly user.
system: 'You're a friendly helper!' ,
prompt: 'Why is the sky blue?' ,
});
console.log(text);
}
main();
import { generateText } from 'ai' ;
import { OpenAi } '@ai-sdk/openai' ;
Asynchronous Functions Main () {
const {text} = wait for generateText ({
model: OpenAi( 'GPT-4-Turbo' ).
system: 'You're a friendly assistant!' ,
prompt: 'Why is the sky blue?' ,
});
Console.log(text);;
}
main();
  • Description: This code shows how to generate text using OpenAI's models. generateText is one of the core features provided by the Vercel AI SDK, allowing you to quickly generate AI-driven text responses.

Building the Chat InterfaceIf you want to build a chat interface, you can use the useChat or useCompletion hooks:

import { useChat } from 'ai/react' ;
function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat();
return (
<div>
<ul>
{messages.map((m, index) =&gt; (
<li key="{index}">{m.role}: {m.content}</li>
))}
</ul>
<form onsubmit="{handleSubmit}">
<input 
value="{input}" 
onchange="{handleInputChange}" 
placeholder="Say something..."
/>
<button type="submit">Send</button>
<input type="hidden" name="trp-form-language" value="en"/></form>
</div>
);
}
import { useChat } from 'ai/react';
function chat() {
const {message, input, handleinputChange, handlesubmit} = usechat();
Returns (
DIV
3cul
{ messages.map((m, index) = (
li key = {index} {m.role}: {m.content}/li
))}
/ul
form onsubmit = {handlesubmit}
%3points
Value
  • Description: This example demonstrates the use of useChat hooks to quickly build a chat interface that supports real-time responses. Each time the user submits a message, the AI will generate and display a response in real time.

Generate UIFor generating user interfaces, the Vercel AI SDK supports the use of React Server Components (RSC):

import { streamUI } from 'ai/rsc' ;
async function submitMessage() {
'use server'; const stream = await streamUI({{ai/rsc}); async function
const stream = await streamUI({
// ... Fill in your configuration here
}); return { ui: stream.value }; const stream = streamUI({ // ...
return { ui: stream.value }; }
}
import { streamUI } from 'ai/rsc' ;
asynchronous function subtmessage ( ) {
"Using server";
const stream = wait for streamUI ( {
// ... Fill in your configuration here
});
Returns { ui : stream.value}.
}
  • Description: This is a simple example showing how to generate dynamic UI elements using the streamUI function. With RSC, the server can generate and manage UI state directly, providing a smoother user experience.

Advanced Use

  • Multi-model support: Easily switch between different AI model providers by changing model parameters.
  • Error handling and debugging: Use the SDK's error handling mechanisms and debugging tools to ensure that your AI apps run stably.

With these steps and examples, you can start building AI-based applications that utilize the power provided by the Vercel AI SDK to boost your development productivity. If you encounter problems while using it, we recommend visiting Vercel's GitHub Discussions for community support.


May not be reproduced without permission:Chief AI Sharing Circle " Vercel AI SDK: Building AI-powered applications with popular front-end frameworks

Chief AI Sharing Circle

Chief AI Sharing Circle specializes in AI learning, providing comprehensive AI learning content, AI tools and hands-on guidance. Our goal is to help users master AI technology and explore the unlimited potential of AI together through high-quality content and practical experience sharing. Whether you are an AI beginner or a senior expert, this is the ideal place for you to gain knowledge, improve your skills and realize innovation.

Contact Us
en_USEnglish