feat: 拆分以便扩展

This commit is contained in:
ChenZhaoYu 2023-02-10 11:40:40 +08:00
parent 31ea7c5529
commit 35da3f1d1f
2 changed files with 21 additions and 22 deletions

19
service/chatgpt.ts Normal file
View File

@ -0,0 +1,19 @@
import dotenv from 'dotenv'
import { ChatGPTAPI } from 'chatgpt'
dotenv.config()
const apiKey = ''
/**
* More Info: https://github.com/transitive-bullshit/chatgpt-api
*/
const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY || apiKey })
async function chatReply(message: string) {
if (!message)
return
return await api.sendMessage(message)
}
export { chatReply }

View File

@ -1,30 +1,10 @@
import dotenv from 'dotenv'
import { ChatGPTAPI } from 'chatgpt'
import express from 'express'
dotenv.config()
import { chatReply } from './chatgpt'
const app = express()
app.use(express.json())
async function chatAPI(message: string) {
if (!message)
throw new Error('Message is not defined')
if (!process.env.OPENAI_API_KEY)
throw new Error('OPENAI_API_KEY is not defined in .env file')
try {
const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
const res = await api.sendMessage(message)
return res
}
catch (error) {
return error
}
}
app.all('*', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Content-Type')
@ -36,6 +16,6 @@ app.listen(3002, () => globalThis.console.log('Server is running on port 3002'))
app.post('/chat', async (req, res) => {
const { message } = req.body
const response = await chatAPI(message)
const response = await chatReply(message)
res.send(response)
})