Skip to content

Commit 4844d2c

Browse files
authored
Use readline for better chat input (#360)
1 parent 0ff0a2b commit 4844d2c

File tree

1 file changed

+28
-20
lines changed

1 file changed

+28
-20
lines changed

bin/chat.js

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import readline from 'readline'
12
import { tools } from './tools/tools.js'
23

34
/** @type {'text' | 'tool'} */
@@ -241,26 +242,33 @@ function writeWithColor() {
241242
export function chat() {
242243
/** @type {Message[][]} */
243244
const messages = []
244-
process.stdin.setEncoding('utf-8')
245-
246-
write(colors.system, 'question: ', colors.normal)
245+
const rl = readline.createInterface({
246+
input: process.stdin,
247+
output: process.stdout,
248+
terminal: true,
249+
})
247250

248-
process.stdin.on('data', async (/** @type {string} */ input) => {
249-
input = input.trim()
250-
if (input === 'exit') {
251-
process.exit()
252-
} else if (input) {
253-
try {
254-
write(colors.user, 'answer: ', colors.normal)
255-
outputMode = 'text' // switch to text output mode
256-
messages.push([{ role: 'user', content: input.trim() }])
257-
await sendMessages(messages)
258-
} catch (error) {
259-
console.error(colors.error, '\n' + error)
260-
} finally {
261-
write('\n\n')
251+
function prompt() {
252+
rl.question(`${colors.system}question: ${colors.normal}`, async (input) => {
253+
input = input.trim()
254+
if (input === 'exit') {
255+
rl.close()
256+
process.exit()
257+
} else if (input) {
258+
try {
259+
write(colors.user, 'answer: ', colors.normal)
260+
outputMode = 'text' // switch to text output mode
261+
messages.push([{ role: 'user', content: input }])
262+
await sendMessages(messages)
263+
} catch (error) {
264+
console.error(colors.error, '\n' + error)
265+
} finally {
266+
write('\n\n')
267+
}
262268
}
263-
}
264-
write(colors.system, 'question: ', colors.normal)
265-
})
269+
prompt()
270+
})
271+
}
272+
273+
prompt()
266274
}

0 commit comments

Comments
 (0)