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

72 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-06-02 15:33:48 -04:00
import { kv } from '@vercel/kv'
import { OpenAIStream, StreamingTextResponse } from 'ai-connector'
import { Configuration, OpenAIApi } from 'openai-edge'
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-16 16:33:47 -04:00
import { Session } from 'inspector'
2023-06-13 17:31:15 -04:00
export const runtime = 'edge'
2023-06-02 11:15:04 -04: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
let session: Session
2023-06-16 16:32:19 -04:00
if (process.env.VERCEL_ENV !== 'preview') {
2023-06-16 16:33:47 -04:00
session = await auth()
2023-06-16 16:32:19 -04:00
if (session == null) {
return new Response('Unauthorized', { status: 401 })
}
2023-06-13 17:31:15 -04:00
}
2023-06-16 16:30:15 -04:00
const configuration = new Configuration({
apiKey: previewToken || process.env.OPENAI_API_KEY
})
const openai = new OpenAIApi(configuration)
2023-06-13 17:31:15 -04:00
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
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-16 14:38:33 -04:00
const userId = session?.user.id
if (userId) {
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'
}
]
}
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
}