-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
256 lines (236 loc) · 7.22 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
const dotenv = require("dotenv");
dotenv.config();
const OpenAI = require("openai");
const openai = new OpenAI();
const fs = require("fs");
const readline = require("node:readline");
const { setInterval, clearInterval } = require("timers");
const { getFilesFromFolders } = require("./fileHelper");
const blueText = (text) => {
console.log("\x1b[34m", text, "\x1b[0m");
};
const configCache = process.env.OPENAI_CONFIG_CACHE || "config.json";
let config;
try {
config = require(`./${configCache}`);
} catch (e) {
config = {};
}
const saveToCache = (key, value) => {
config[key] = value;
fs.writeFileSync(configCache, JSON.stringify(config, null, 2));
};
async function vectorizeFiles(folderPaths) {
if (config.vectorStoreId) {
if (config.fileProcessed) {
return config.vectorStoreId;
}
return config.vectorStoreId;
}
folderPaths = folderPaths || process.env.DEFAULT_PATHS;
const { files, totalSize } = getFilesFromFolders(folderPaths.split(","));
console.log(
"Indexing ",
files.length,
" files with total size of ",
totalSize / (1024 * 1024),
"MB"
);
const fileStreams = files.map((path) => fs.createReadStream(path));
let vectorStore;
if (config.vectorStoreId) {
vectorStore = await openai.beta.vectorStores.retrieve(config.vectorStoreId);
} else {
vectorStore = await openai.beta.vectorStores.create({
name: process.env.VECTOR_STORE_NAME || "AssistantRAGFileStore",
});
}
saveToCache("vectorStoreId", vectorStore.id);
await openai.beta.vectorStores.fileBatches.uploadAndPoll(vectorStore.id, {
files: fileStreams,
});
saveToCache("fileProcessed", true);
console.log("Finished uploading files to vector store");
console.log("Size of the vector store: ", vectorStore.size);
return vectorStore.id;
}
async function createAssistant(paths) {
if (config.assistantId) {
return config.assistantId;
}
const assistant = await openai.beta.assistants.create({
name: process.env.ASSISTANT_NAME || "File Assistant",
instructions:
process.env.DEFAULT_INSTRUCTIONS ||
"You are an assistant who can help users find files on their computer, summarize them and provide information about the files. You can search for files by name, type, content or symantics. DO NOT show any sensitive information like name, address, SSN, date of birth, in your responses. Hide and redact them if needed. If the question is not about the document or can't be found in documents, you can use your own knowledge to provide the answer.",
model: "gpt-4o",
tools: [{ type: "file_search" }],
});
const vectorStoreId = await vectorizeFiles(paths);
await openai.beta.assistants.update(assistant.id, {
tool_resources: { file_search: { vector_store_ids: [vectorStoreId] } },
});
saveToCache("assistantId", assistant.id);
return assistant.id;
}
const initRun = async (assistantId, threadId) => {
const stream = openai.beta.threads.runs
.stream(threadId, {
assistant_id: assistantId,
})
.on("messageDone", async (event) => {
if (event.content[0].type === "text") {
showProgress(false);
const { text } = event.content[0];
const { annotations } = text;
let citations = [];
let index = 0;
for (let annotation of annotations) {
text.value = text.value.replace(annotation.text, "[" + index + "]");
const { file_citation } = annotation;
if (file_citation) {
const citedFile = await openai.files.retrieve(
file_citation.file_id
);
citations.push(citedFile.filename);
}
index++;
}
blueText(text.value);
citations = [...new Set(citations)].map((c, i) => `${i + 1}. ${c}`);
blueText(citations.join("\n"));
console.log("\n\n");
ask();
}
});
};
let progressInterval = null;
const showProgress = (status) => {
if (status === true) {
let progress = 0;
progressInterval = setInterval(() => {
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
process.stdout.write("...." + progress++ + "s");
}, 1000);
} else {
if (progressInterval) {
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
process.stdout.write("");
clearInterval(progressInterval);
progressInterval = null;
progress = 0;
}
}
};
const initAll = async (paths) => {
//create assistant
const assistantId = await createAssistant();
//create thread
let threadId = config.threadId;
if (!threadId) {
const thread = await openai.beta.threads.create();
threadId = thread.id;
saveToCache("threadId", threadId);
}
//init run
await initRun(assistantId, threadId);
return { assistantId, threadId };
};
const createMessage = async (prompt) => {
const { assistantId, threadId } = await initAll();
await openai.beta.threads.messages.create(threadId, {
role: "user",
content: prompt,
});
showProgress(true);
};
module.exports = {
createMessage,
};
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
});
const ask = async () => {
rl.question("Singh: ", async (question) => {
try {
if (question === "exit") {
process.exit(0);
}
if (question === "new") {
await cleanThread();
console.log("New thread created\n\n");
ask();
return;
}
if (question === "index") {
await cleanThread();
await vectorizeFiles();
ask();
return;
}
if (question === "reset") {
await cleanUp();
// await vectorizeFiles();
ask();
return;
}
if (question.trim() === "") {
console.clear();
console.log("\n");
ask();
return;
}
await createMessage(question);
// console.log("\n\n");
// await ask();
} catch (error) {
console.error(error);
}
});
};
const cleanThread = async () => {
if (config.threadId) {
const runs = await openai.beta.threads.runs.list(config.threadId);
for (let run of runs.data) {
if (run.status in ["queued", "in_progress", "requires_action"]) {
console.log("Canceling run", run.id);
await openai.beta.threads.runs.cancel(config.threadId, run.id);
}
}
await openai.beta.threads.del(config.threadId);
config.threadId = null;
saveToCache("threadId", null);
}
};
const cleanUp = async () => {
await cleanThread();
const assistants = await openai.beta.assistants.list();
for (let ast of assistants.data) {
console.log("Deleting assistant", ast.id);
await openai.beta.assistants.del(ast.id);
}
const list = await openai.files.list();
console.log("Deleting", list.data.length, "files");
let f = 0;
for await (const file of list) {
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
process.stdout.write("...." + f++);
await openai.files.del(file.id);
}
const vectorStores = await openai.beta.vectorStores.list();
for (let vs of vectorStores.data) {
console.log("Deleting vs", vs.id);
await openai.beta.vectorStores.del(vs.id);
}
config = {};
fs.writeFileSync(configCache, JSON.stringify(config, null, 2));
};
(async () => {
// await cleanUp();
await ask();
})();