From 35da3f1d1fe4f46469096e78b63d82a5370f9572 Mon Sep 17 00:00:00 2001 From: ChenZhaoYu <790348264@qq.com> Date: Fri, 10 Feb 2023 11:40:40 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8B=86=E5=88=86=E4=BB=A5=E4=BE=BF?= =?UTF-8?q?=E6=89=A9=E5=B1=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/chatgpt.ts | 19 +++++++++++++++++++ service/index.ts | 24 ++---------------------- 2 files changed, 21 insertions(+), 22 deletions(-) create mode 100644 service/chatgpt.ts 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) })