forked from Chanzhaoyu/chatgpt-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatgpt.ts
54 lines (40 loc) · 1.28 KB
/
chatgpt.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import dotenv from 'dotenv'
import { ChatGPTAPI } from 'chatgpt'
interface ChatContext {
conversationId?: string
parentMessageId?: string
}
dotenv.config()
const apiKey = process.env.OPENAI_API_KEY
if (apiKey === undefined)
throw new Error('OPENAI_API_KEY is not defined')
const chatContext = new Set<ChatContext>()
/**
* More Info: https://github.com/transitive-bullshit/chatgpt-api
*/
const api = new ChatGPTAPI({ apiKey })
async function chatReply(message: string) {
if (!message)
return
// Get the last context from the chat context
// If there is a last context, add it to the options
let options = {}
const lastContext = Array.from(chatContext).pop()
if (lastContext) {
const { conversationId, parentMessageId } = lastContext
options = { conversationId, parentMessageId }
}
// Send the message to the API
const response = await api.sendMessage(message, { ...options })
const { conversationId, id } = response
// Add the new context to the chat context
if (conversationId && id)
chatContext.add({ conversationId, parentMessageId: id })
return response
}
async function clearChatContext() {
// Clear the chat context
chatContext.clear()
return Promise.resolve({ message: 'Chat context cleared' })
}
export { chatReply, clearChatContext }