-
Notifications
You must be signed in to change notification settings - Fork 36
/
chat.js
49 lines (40 loc) · 1.19 KB
/
chat.js
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
import 'dotenv/config'
import readline from 'node:readline'
import { openai } from './openai.js'
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
const newMessage = async (history, message) => {
const chatCompletion = await openai.chat.completions.create({
messages: [...history, message],
model: 'gpt-3.5-turbo',
})
return chatCompletion.choices[0].message
}
const formatMessage = (userInput) => ({ role: 'user', content: userInput })
const chat = () => {
const history = [
{
role: 'system',
content: `You are a helpful AI assistant. Answer the user's questions to the best of you ability.`,
},
]
const start = () => {
rl.question('You: ', async (userInput) => {
if (userInput.toLowerCase() === 'exit') {
rl.close()
return
}
const userMessage = formatMessage(userInput)
const response = await newMessage(history, userMessage)
history.push(userMessage, response)
console.log(`\n\nAI: ${response.content}\n\n`)
start()
})
}
start()
console.log('\n\nAI: How can I help you today?\n\n')
}
console.log("Chatbot initialized. Type 'exit' to end the chat.")
chat()