Skip to content
Dashboard

Introducing the Vercel AI SDK

An interoperable, streaming-enabled, edge-ready software development kit for AI apps built with React and Svelte.

Link to headingThe Vercel AI SDK

npm install ai

Link to headingBuilt-in LLM Adapters

import { OpenAIStream, StreamingTextResponse } from 'ai'
import { Configuration, OpenAIApi } from 'openai-edge'
// Create an OpenAI API client (that's edge friendly!)
const config = new Configuration({
apiKey: process.env.OPENAI_API_KEY
})
const openai = new OpenAIApi(config)
// IMPORTANT! Set the runtime to edge
export const runtime = 'edge'
export async function POST(req: Request) {
// Extract the `messages` from the body of the request
const { messages } = await req.json()
// Ask OpenAI for a streaming chat completion given the prompt
const response = await openai.createChatCompletion({
model: 'gpt-3.5-turbo',
stream: true,
messages
})
// Convert the response into a friendly text-stream
const stream = OpenAIStream(response)
// Respond with the stream
return new StreamingTextResponse(stream)
}

Link to headingStreaming First UI Helpers

'use client'
import { useChat } from 'ai/react'
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat()
return (
<div>
{messages.map(m => (
<div key={m.id}>
{m.role}: {m.content}
</div>
))}
<form onSubmit={handleSubmit}>
<label>
Say something...
<input
value={input}
onChange={handleInputChange}
/>
</label>
</form>
</div>
)
}

Link to headingStream Helpers and Callbacks

export async function POST(req: Request) {
// ... same as above
// Convert the response into a friendly text-stream
const stream = OpenAIStream(response, {
onStart: async () => {
// This callback is called when the stream starts
// You can use this to save the prompt to your database
await savePromptToDatabase(prompt)
},
onToken: async (token: string) => {
// This callback is called for each token in the stream
// You can use this to debug the stream or save the tokens to your database
console.log(token)
},
onCompletion: async (completion: string) => {
// This callback is called when the stream completes
// You can use this to save the final completion to your database
await saveCompletionToDatabase(completion)
}
})
// Respond with the stream
return new StreamingTextResponse(stream)
}

Link to headingVercel Functions ready

Link to headingChat & Prompt Playground

Link to headingWhat’s Next?

Apply to the AI Accelerator

Apply to get access to over $850k in credits from Vercel and our AI partners.

Apply today