chatbot-template/app/api/chat/route.ts

71 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-06-02 15:33:48 -04:00
import { auth } from '@/auth'
import { kv } from '@vercel/kv'
import { nanoid } from '@/lib/utils'
import { OpenAIStream, StreamingTextResponse } from 'ai-connector'
import { Configuration, OpenAIApi } from 'openai-edge'
2023-06-02 11:15:04 -04:00
// export const runtime = 'edge'
2023-06-02 11:15:04 -04:00
2023-06-02 14:32:46 -04:00
const configuration = new Configuration({
2023-06-02 15:33:48 -04:00
apiKey: process.env.OPENAI_API_KEY
})
2023-06-02 14:32:46 -04:00
2023-06-02 15:33:48 -04:00
const openai = new OpenAIApi(configuration)
2023-06-02 14:32:46 -04:00
if (!process.env.OPENAI_API_KEY) {
2023-06-02 15:33:48 -04:00
throw new Error('Missing env var from OpenAI')
2023-06-02 14:32:46 -04:00
}
2023-06-02 11:15:04 -04:00
export const POST = auth(async function POST(req: Request) {
2023-06-02 15:33:48 -04:00
const json = await req.json()
2023-06-02 11:15:04 -04:00
// @ts-ignore
2023-06-02 15:33:48 -04:00
console.log(req.auth) // todo fix types
2023-06-02 11:57:44 -04:00
const messages = json.messages.map((m: any) => ({
content: m.content,
2023-06-02 15:33:48 -04:00
role: m.role
}))
2023-06-02 11:15:04 -04:00
const res = await openai.createChatCompletion({
2023-06-02 15:33:48 -04:00
model: 'gpt-3.5-turbo',
2023-06-02 11:57:44 -04:00
messages,
2023-06-02 11:15:04 -04:00
temperature: 0.7,
top_p: 1,
frequency_penalty: 1,
max_tokens: 500,
n: 1,
2023-06-02 15:33:48 -04:00
stream: true
})
2023-06-02 11:15:04 -04:00
const stream = await OpenAIStream(res, {
async onCompletion(completion) {
// @ts-ignore
if (req.auth?.user?.email == null) {
2023-06-02 15:33:48 -04:00
return
2023-06-02 11:15:04 -04:00
}
2023-06-02 15:33:48 -04:00
const title = json.messages[0].content.substring(0, 20)
const userId = (req as any).auth?.user?.email
const id = json.id ?? nanoid()
const createdAt = Date.now()
2023-06-02 11:33:17 -04:00
const payload = {
2023-06-02 15:15:35 -04:00
id,
2023-06-02 11:15:04 -04:00
title,
2023-06-02 15:15:35 -04:00
userId,
createdAt,
2023-06-02 11:57:44 -04:00
messages: [
...messages,
{
content: completion,
2023-06-02 15:33:48 -04:00
role: 'assistant'
}
]
}
await kv.hmset(`chat:${id}`, payload)
2023-06-02 15:15:35 -04:00
await kv.zadd(`user:chat:${userId}`, {
score: createdAt,
2023-06-02 15:33:48 -04:00
member: `chat:${id}`
})
}
})
2023-06-02 11:15:04 -04:00
2023-06-02 15:33:48 -04:00
return new StreamingTextResponse(stream)
})