Vercel AI SDK

Build AI-powered applications with React, Svelte, and Vue

README

Vercel AI SDK


The Vercel AI SDK is a library for building edge-ready AI-powered streaming text and chat UIs.

Features


SWR -powered React, Svelte and Vue helpers for streaming text responses and building chat and completion UIs
First-class support for LangChain and OpenAI , Anthropic , and HuggingFace
Edge Runtime compatibility
Callbacks for saving completed streaming responses to a database (in the same request)

Installation


  1. ``` shell
  2. pnpm install ai
  3. ```

View the full documentation and examples on sdk.vercel.ai/docs

Example: An AI Chatbot with Next.js and OpenAI


With the Vercel AI SDK, you can build a ChatGPT-like app in just a few lines of code:

  1. ``` tsx
  2. // ./app/api/chat/route.js
  3. import { Configuration, OpenAIApi } from 'openai-edge'
  4. import { OpenAIStream, StreamingTextResponse } from 'ai'

  5. const config = new Configuration({
  6.   apiKey: process.env.OPENAI_API_KEY
  7. })
  8. const openai = new OpenAIApi(config)

  9. export const runtime = 'edge'

  10. export async function POST(req) {
  11.   const { messages } = await req.json()
  12.   const response = await openai.createChatCompletion({
  13.     model: 'gpt-4',
  14.     stream: true,
  15.     messages
  16.   })
  17.   const stream = OpenAIStream(response)
  18.   return new StreamingTextResponse(stream)
  19. }
  20. ```

  1. ``` tsx
  2. // ./app/page.js
  3. 'use client'

  4. import { useChat } from 'ai/react'

  5. export default function Chat() {
  6.   const { messages, input, handleInputChange, handleSubmit } = useChat()

  7.   return (
  8.     <div>
  9.       {messages.map(m => (
  10.         <div key={m.id}>
  11.           {m.role}: {m.content}
  12.         </div>
  13.       ))}

  14.       <form onSubmit={handleSubmit}>
  15.         <input
  16.           value={input}
  17.           placeholder="Say something..."
  18.           onChange={handleInputChange}
  19.         />
  20.       </form>
  21.     </div>
  22.   )
  23. }
  24. ```

View the full documentation and examples on sdk.vercel.ai/docs

Authors


This library is created by Vercel and Next.js team members, with contributions from:

Jared Palmer (@jaredpalmer ) -Vercel
Shu Ding (@shuding_ ) -Vercel
Max Leiter (@max_leiter ) -Vercel
Malte Ubl (@cramforce ) -Vercel
Justin Ridgewell (@jridgewell ) -Vercel

Contributors