-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (62 loc) · 2.06 KB
/
index.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { ChatOpenAI } from "langchain/chat_models/openai";
import { SystemMessage, HumanMessage, AIMessage } from "langchain/schema";
import { input, select, editor } from '@inquirer/prompts';
import fs from 'fs';
import path from 'path';
const model = new ChatOpenAI({
modelName: "gpt-3.5-turbo", // optionally change to gpt-4
streaming: true,
callbacks: [{
handleLLMStart() {
process.stdout.write(`\nAI: `);
},
// stream chat output to console
handleLLMNewToken(token) {
process.stdout.write(token);
},
handleLLMEnd() {
process.stdout.write(`\n\n`);
}
}]
});
const loadTemplatesFromDirectory = (directory) => fs.readdirSync(directory)
.filter(file => file.endsWith('.txt'))
.map(filename => ({
name: path.basename(filename, '.txt'),
value: fs.readFileSync(path.join(directory, filename), 'utf-8')
}));
const promptUserForTemplate = async (templates) => select({
message: 'Select your template:',
choices: templates
});
const promptUserForMessage = async () => {
let userInput = await input({ message: 'You:' });
// Provide an editor for multiline input
if (userInput.trim() === '') {
userInput = await editor({
message: 'Write your message in the editor:',
waitForUseInput: false
});
}
return userInput;
}
// Recursively handle chat sessions
const initiateChatSession = async () => {
let chatMessages = [];
const templates = loadTemplatesFromDirectory('templates');
const template = await promptUserForTemplate([{ name: 'ChatGPT', value: '' }, ...templates]);
if (template.trim() !== '') {
chatMessages.push(new SystemMessage(template));
}
// loop chat until user types 'exit'
while (true) {
const userInput = await promptUserForMessage();
if (userInput.trim() === '') continue;
if (userInput.trim().toLowerCase() === 'exit') break;
chatMessages.push(new HumanMessage(userInput));
const aiResponse = await model.call(chatMessages);
chatMessages.push(new AIMessage(aiResponse.content));
}
initiateChatSession(templates);
};
initiateChatSession();