Skip to content

Commit

Permalink
feat: 拆分以便扩展
Browse files Browse the repository at this point in the history
  • Loading branch information
Chanzhaoyu committed Feb 10, 2023
1 parent 31ea7c5 commit 35da3f1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 22 deletions.
19 changes: 19 additions & 0 deletions service/chatgpt.ts
Original file line number Diff line number Diff line change
@@ -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 }
24 changes: 2 additions & 22 deletions service/index.ts
Original file line number Diff line number Diff line change
@@ -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')
Expand All @@ -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)
})

0 comments on commit 35da3f1

Please sign in to comment.