diff --git a/service/chatgpt.ts b/service/chatgpt.ts new file mode 100644 index 0000000..874d6d7 --- /dev/null +++ b/service/chatgpt.ts @@ -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 } diff --git a/service/index.ts b/service/index.ts index f3cd600..ce7df19 100644 --- a/service/index.ts +++ b/service/index.ts @@ -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) })