-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.js
More file actions
45 lines (38 loc) · 1.03 KB
/
chat.js
File metadata and controls
45 lines (38 loc) · 1.03 KB
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
import { stdin } from 'node:process'
import { openai } from './openai.js'
import readline from 'node:readline'
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
const newMessage = async (history, message) => {
const results = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [...history, message],
})
return results.choices[0].message
}
const formatMessage = (userInput) => ({ role: 'user', content: userInput })
const chat = () => {
const history = [
{
role: 'system',
content: 'You are an AI assistant. Answer questions or else!',
},
]
const start = () => {
rl.question('You: ', async (userInput) => {
if (userInput.toLowerCase() === 'exit') {
rl.close()
return
}
const message = formatMessage(userInput)
const response = await newMessage(history, newMessage)
history.push(message, response)
console.log(`\n\nAI: ${response.content}\n\n`)
start()
})
}
start()
}
chat()