-
Notifications
You must be signed in to change notification settings - Fork 0
/
compile-quotes.js
290 lines (244 loc) · 7.85 KB
/
compile-quotes.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/*
compile all quotes from supabase where BookID = X.
Then use GPT to cluster them into a few categories.
Then create a easy to read story about highlights.
*/
import { createClient } from "@supabase/supabase-js";
import dotenv from "dotenv";
import fs from "fs";
import similarity from "compute-cosine-similarity";
import { Configuration, OpenAIApi } from "openai";
import { kmeans } from "ml-kmeans";
dotenv.config();
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
organization: process.env.OPENAI_ORG,
});
const openai = new OpenAIApi(configuration);
dotenv.config();
const BOOK_ID = "1474870";
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_KEY;
const supabase = createClient(supabaseUrl, supabaseKey, {
auth: {
persistSession: false,
},
});
const getBookIDFromTitle = async (title) => {
const { data, error } = await supabase
.from("books")
.select("book_id")
.ilike("title", "%" + title + "%");
if (error) {
console.error(error);
return null;
}
// if undefined, return null
if (data.length === 0) {
return null;
}
return data[0].book_id;
};
const compileQuotesFromTitle = async (bookTitle) => {
const bookId = await getBookIDFromTitle(bookTitle);
if (!bookId) {
console.error("Book not found.");
return [];
}
const quotes = await getQuotes(bookId);
return quotes;
};
const compileQuotesFomID = async (bookID) => {
const quotes = await getQuotes(bookID);
return quotes;
};
const getQuotes = async (bookId) => {
const { data, error } = await supabase
.from("highlights")
.select("*")
.eq("book_id", bookId);
if (error) {
console.error(error);
return [];
}
return data;
};
const assignTopicToCluster = async (cluster) => {
try {
const prompt = `Given the following quotes, what is a good topic for them? Return only the topic as a Markdown heading with no leading #. No bold (**) or italics (*) are needed.`;
const completion = await openai.createChatCompletion({
messages: [
{
role: "system",
content: prompt,
},
{
role: "user",
content: cluster.map((quote) => quote.text).join("\n"),
},
],
model: "gpt-3.5-turbo",
});
const content = completion.data.choices[0].message.content;
return content.trim().replace(/#/, "");
} catch (err) {
console.log("START ERROR");
console.error(err);
console.error(err.response);
console.error(err.response.data);
console.error(err.response.data.error);
console.error(err.response.data.error.message);
console.error(err.response.data.error.code);
console.error(err.response.data.error.status);
console.error(err.response.data.error.request);
console.log("END ERROR");
throw err;
}
};
const highlightQuote = async (quote, topic) => {
console.log(`Highlighting quote: ${quote} for topic: ${topic}`);
try {
const prompt = `Given the following quote, highlight the part related to the topic using ** (MD bold). Return the quote with the relevant part highlighted. Say nothing else. Do not include the topic in the response.`;
const completion = await openai.createChatCompletion({
messages: [
{
role: "system",
content: prompt,
},
{
role: "user",
content: `Quote: <start>${quote}<end>\n\nTopic: ${topic}\n\nHighlighted Quote (Verbatim):`,
},
],
model: "gpt-3.5-turbo",
});
const content = completion.data.choices[0].message.content;
console.log(content);
return content.trim();
} catch (err) {
console.log("START ERROR");
console.error(err);
console.error(err.response);
console.error(err.response.data);
console.error(err.response.data.error);
console.error(err.response.data.error.message);
console.error(err.response.data.error.code);
console.error(err.response.data.error.status);
console.error(err.response.data.error.request);
console.log("END ERROR");
throw err;
}
}
const summarizeCluster = async (cluster) => {
try {
const prompt = `Given the following quotes, summarize them into a two-three sentence summary. Return only the summary`;
const completion = await openai.createChatCompletion({
messages: [
{
role: "system",
content: prompt,
},
{
role: "user",
content: cluster.map((quote) => quote.text).join("\n"),
},
],
model: "gpt-3.5-turbo",
});
const content = completion.data.choices[0].message.content;
return content.trim();
} catch (err) {
console.log("START ERROR");
console.error(err);
console.error(err.response);
console.error(err.response.data);
console.error(err.response.data.error);
console.error(err.response.data.error.message);
console.error(err.response.data.error.code);
console.error(err.response.data.error.status);
console.error(err.response.data.error.request);
console.log("END ERROR");
throw err;
}
};
const followUpQuestions = async (cluster) => {
try {
const prompt = `Given the following quotes, what are some follow up questions you could ask about them? Return only the questions as a bulleted list`;
const completion = await openai.createChatCompletion({
messages: [
{
role: "system",
content: prompt,
},
{
role: "user",
content: cluster.map((quote) => quote.text).join("\n"),
},
],
model: "gpt-3.5-turbo",
});
const content = completion.data.choices[0].message.content;
return content.trim();
} catch (err) {
console.log("START ERROR");
console.error(err);
console.error(err.response);
console.error(err.response.data);
console.error(err.response.data.error);
console.error(err.response.data.error.message);
console.error(err.response.data.error.code);
console.error(err.response.data.error.status);
console.error(err.response.data.error.request);
console.log("END ERROR");
throw err;
}
};
const main = async () => {
const quotes = await compileQuotesFomID(BOOK_ID);
console.log(quotes.length + " quotes found.");
// w want roughly 5-10 quotes per cluster
const k = Math.ceil(quotes.length / 5);
const assignments = kmeans(
quotes
.map((quote) => JSON.parse(quote.embedding))
.filter((embedding) => embedding.length === 1536),
k
);
// convert each cluster into a heading and a list of quotes in markdown under it and write to a file
// use cluster index as heading
// each quote is a bullet point under the heading
let markdown = "";
const clusters = [];
for (let i = 0; i < k; i++) {
clusters.push([]);
}
for (let i = 0; i < assignments.clusters.length; i++) {
clusters[assignments.clusters[i]].push(quotes[i]);
}
for (let i = 0; i < clusters.length; i++) {
const cluster = clusters[i];
console.log(`Cluster ${i} has ${cluster.length} quotes.`);
const topic = await assignTopicToCluster(cluster);
const summary = await summarizeCluster(cluster);
// const followUp = await followUpQuestions(cluster);
markdown += `## ${topic}\n\n`;
markdown += `### Summary\n\n${summary}\n\n`;
markdown += `### Quotes\n\n`;
// // add each quote to the markdown with highlighting
// for (const quote of cluster) {
// markdown += `- ${await highlightQuote(quote.text, topic)}\n`;
// }
// markdown += `\n\n`;
// add each quote to the markdown without highlighting
for (const quote of cluster) {
markdown += `- ${quote.text}\n`;
}
markdown += `\n\n`;
// markdown += `### Follow Up Questions\n\n${followUp}\n\n`;
}
fs.writeFileSync("output.md", markdown);
};
// if env var DEV exists, run main
if (process.env.DEV) {
main();
}