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

68 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-06-02 15:33:48 -04:00
import { kv } from '@vercel/kv'
2023-06-16 22:43:24 +02:00
import { OpenAIStream, StreamingTextResponse } from 'ai'
2023-11-26 12:32:01 -06:00
import OpenAI from 'openai';
2023-06-16 21:52:01 +04:00
2023-06-16 12:03:09 -04:00
import { auth } from '@/auth'
2023-06-16 21:52:01 +04:00
import { nanoid } from '@/lib/utils'
2023-06-13 17:31:15 -04:00
export const runtime = 'edge'
2023-06-02 11:15:04 -04:00
2023-11-26 12:32:01 -06:00
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
2023-06-21 11:17:59 -07:00
2023-06-13 17:31:15 -04:00
export async function POST(req: Request) {
2023-06-16 16:33:47 -04:00
const json = await req.json()
const { messages, previewToken } = json
2023-11-26 12:32:01 -06:00
const userId = (await auth())?.user.id // this doesn't seem to work getting the id
console.log('auth', await auth())
2023-06-16 16:35:27 -04:00
2023-06-27 20:03:01 +02:00
if (!userId) {
2023-06-22 10:37:35 -07:00
return new Response('Unauthorized', {
status: 401
})
2023-06-13 17:31:15 -04:00
}
2023-06-21 11:17:59 -07:00
if (previewToken) {
2023-11-26 12:32:01 -06:00
openai.apiKey = previewToken
2023-06-21 11:17:59 -07:00
}
2023-06-13 17:31:15 -04:00
2023-11-26 12:32:01 -06:00
const res = await openai.chat.completions.create({
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,
2023-06-02 15:33:48 -04:00
stream: true
})
2023-06-02 11:15:04 -04:00
2023-06-13 17:31:15 -04:00
const stream = OpenAIStream(res, {
2023-06-02 11:15:04 -04:00
async onCompletion(completion) {
const title = json.messages[0].content.substring(0, 100)
2023-06-27 20:03:01 +02:00
const id = json.id ?? nanoid()
const createdAt = Date.now()
const path = `/chat/${id}`
const payload = {
id,
title,
userId,
createdAt,
path,
messages: [
...messages,
{
content: completion,
role: 'assistant'
}
]
2023-06-02 15:33:48 -04:00
}
2023-06-27 20:03:01 +02:00
await kv.hmset(`chat:${id}`, payload)
await kv.zadd(`user:chat:${userId}`, {
score: createdAt,
member: `chat:${id}`
})
2023-06-02 15:33:48 -04:00
}
})
2023-06-02 11:15:04 -04:00
2023-06-02 15:33:48 -04:00
return new StreamingTextResponse(stream)
2023-06-13 17:31:15 -04:00
}