Vercel AI SDK

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

README

Vercel AI SDK


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

Features


SWR -powered React, Svelte, Vue and Solid helpers for streaming text responses and building chat and completion UIs
First-class support for LangChain and OpenAI , Anthropic , Cohere , Hugging Face , and Replicate
Node.js, Serverless, and Edge Runtime support
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 OpenAI from 'openai'
  4. import { OpenAIStream, StreamingTextResponse } from 'ai'

  5. const openai = new OpenAI({
  6.   apiKey: process.env.OPENAI_API_KEY
  7. })

  8. export const runtime = 'edge'

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

  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