#Integration with OpenAI API
1 messages · Page 1 of 1 (latest)
To integrate your Vercel project with OpenAI's API, you need to follow these steps:
- Get your OpenAI API Key: First, ensure you have an OpenAI account. Log into your OpenAI Dashboard and view API keys. Click on "Create new secret key" and copy the generated API key securely. Always keep your API keys confidential and do not expose them in client-side code. Use Vercel Environment Variables for safe storage and do not commit these values to git. Finally, add the
OPENAI_API_KEYenvironment variable in your project. Here's how you can do it:
.env.local
OPENAI_API_KEY='sk-...3Yu5'
Source (https://vercel.com/docs/integrations/ai/openai#getting-your-openai-api-key)
- Install the Vercel AI SDK: You can install the Vercel AI SDK in your project with your favorite package manager:
pnpm i ai
Source (https://vercel.com/docs/integrations/ai/openai#building-chat-interfaces-with-vercel-ai-sdk)
- Use the Vercel AI SDK: The Vercel AI SDK provides you with a few hooks and utilities that you can use to implement streaming chat experiences for your AI application. Here's an example of how you can use it:
'use client'
import { useChat } from 'ai/react'import { toast } from 'sonner' // this can be any toast library of your choice
export default function Chat() { const { messages, input, handleInputChange, handleSubmit } = useChat({ onError: err => { toast.error(err.message) } })
return ( <div className="flex flex-col w-full max-w-md py-24 mx-auto stretch"> {messages.length > 0 ? messages.map(m => ( <div key={m.id} className="whitespace-pre-wrap"> {m.role === 'user' ? 'User: ' : 'AI: '} {m.content} </div> )) : null}
<form onSubmit={handleSubmit}> <input className="fixed bottom-0 w-full max-w-md p-2 mb-8 border border-gray-300 rounded shadow-xl" value={input} placeholder="Say something..." onChange={handleInputChange} /> </form> </div> )}
Source (https://vercel.com/guides/securing-ai-app-rate-limiting#step-4:-adding-vercel-ai-sdk)
- Create a Route Handler: Then, create a Route Handler to stream in your chat response from OpenAI:
import { Configuration, OpenAIApi } from 'openai-edge'import { OpenAIStream, StreamingTextResponse } from 'ai'import { kv } from '@vercel/kv'import { Ratelimit } from '@upstash/ratelimit'
// Create an OpenAI API client (that's edge friendly!)const config = new Configuration({ apiKey: process.env.OPENAI_API_KEY})const openai = new OpenAIApi(config)
// Set the runtime to edge to allow for Edge Streaming (<https://vercel.fyi/streaming>)export const runtime = 'edge'
Source (https://vercel.com/guides/securing-ai-app-rate-limiting#step-4:-adding-vercel-ai-sdk)