only_ever_generator 8.4.5 → 8.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/bootstrap/app.d.ts +6 -3
  2. package/dist/bootstrap/app.d.ts.map +1 -1
  3. package/dist/bootstrap/app.js +11 -17
  4. package/dist/bootstrap/app.js.map +1 -1
  5. package/dist/card_gen/generate_cards.d.ts +2 -3
  6. package/dist/card_gen/generate_cards.d.ts.map +1 -1
  7. package/dist/card_gen/generate_cards.js +22 -15
  8. package/dist/card_gen/generate_cards.js.map +1 -1
  9. package/dist/constants/prompt_data.d.ts +4 -4
  10. package/dist/constants/prompt_data.js +302 -302
  11. package/dist/constants/prompts/card_gen_prompt.js +160 -160
  12. package/dist/constants/prompts/typology_prompt.js +131 -131
  13. package/dist/constants/source_data.d.ts +171 -171
  14. package/dist/constants/source_data.js +973 -973
  15. package/dist/embedding_generation/local_consolidation.js +104 -104
  16. package/dist/helper/build_concept_facts_schema.d.ts +42 -42
  17. package/dist/helper/build_concept_facts_schema.js +44 -44
  18. package/dist/helper/qdrant_db_methods.d.ts.map +1 -1
  19. package/dist/helper/schema_helper/build_card_schema.d.ts +1 -9
  20. package/dist/helper/schema_helper/build_card_schema.d.ts.map +1 -1
  21. package/dist/helper/schema_helper/build_card_schema.js +47 -50
  22. package/dist/helper/schema_helper/build_card_schema.js.map +1 -1
  23. package/dist/helper/schema_helper/build_concept_facts_schema.d.ts +1 -1
  24. package/dist/helper/schema_helper/build_concept_facts_schema.d.ts.map +1 -1
  25. package/dist/helper/schema_helper/build_concept_facts_schema.js +20 -5
  26. package/dist/helper/schema_helper/build_concept_facts_schema.js.map +1 -1
  27. package/dist/helper/schema_helper/build_summary_schema.d.ts +1 -1
  28. package/dist/helper/schema_helper/build_summary_schema.d.ts.map +1 -1
  29. package/dist/helper/schema_helper/build_summary_schema.js +18 -7
  30. package/dist/helper/schema_helper/build_summary_schema.js.map +1 -1
  31. package/dist/index.js +6 -8
  32. package/dist/index.js.map +1 -1
  33. package/dist/parse/response_format_card.d.ts +176 -176
  34. package/dist/parse/response_format_card.js +371 -371
  35. package/dist/parse/response_format_typology.d.ts +1 -1
  36. package/dist/parse/response_format_typology.js +46 -46
  37. package/dist/services/get_prompts.d.ts +8 -7
  38. package/dist/services/get_prompts.d.ts.map +1 -1
  39. package/dist/services/get_prompts.js +69 -21
  40. package/dist/services/get_prompts.js.map +1 -1
  41. package/dist/typology_gen/generate_concept_facts.d.ts +2 -3
  42. package/dist/typology_gen/generate_concept_facts.d.ts.map +1 -1
  43. package/dist/typology_gen/generate_concept_facts.js +25 -15
  44. package/dist/typology_gen/generate_concept_facts.js.map +1 -1
  45. package/dist/typology_gen/generate_typology.d.ts +2 -1
  46. package/dist/typology_gen/generate_typology.d.ts.map +1 -1
  47. package/dist/typology_gen/generate_typology.js +24 -13
  48. package/dist/typology_gen/generate_typology.js.map +1 -1
  49. package/dist/typology_gen/summarize.d.ts +2 -3
  50. package/dist/typology_gen/summarize.d.ts.map +1 -1
  51. package/dist/typology_gen/summarize.js +24 -13
  52. package/dist/typology_gen/summarize.js.map +1 -1
  53. package/package.json +39 -38
  54. package/src/bootstrap/app.ts +418 -416
  55. package/src/card_gen/generate_cards.ts +347 -345
  56. package/src/config.ts +11 -11
  57. package/src/constants/api_constants.ts +7 -7
  58. package/src/constants/prompts/card_gen_prompt.ts +164 -164
  59. package/src/constants/prompts/typology_prompt.ts +139 -139
  60. package/src/embedding_generation/consolidation/global_consolidation.ts +96 -96
  61. package/src/embedding_generation/consolidation/local_consolidation.ts +141 -141
  62. package/src/embedding_generation/consolidation/write_consolidated_data.ts +98 -98
  63. package/src/embedding_generation/generate_embeddings.ts +42 -42
  64. package/src/embedding_generation/parse_embedding_response.ts +31 -31
  65. package/src/enums/card_type_enum.ts +6 -6
  66. package/src/gap_fill/calculate_gap_fill.ts +50 -50
  67. package/src/helper/get_id_from_title.ts +33 -33
  68. package/src/helper/mongo_helper.ts +29 -29
  69. package/src/helper/openai_helper.ts +20 -20
  70. package/src/helper/qdrant_db_methods.ts +77 -77
  71. package/src/helper/schema_helper/build_card_schema.ts +74 -98
  72. package/src/helper/schema_helper/build_classify_summarize_schema.ts +43 -43
  73. package/src/helper/schema_helper/build_concept_facts_schema.ts +45 -31
  74. package/src/helper/schema_helper/build_summary_schema.ts +43 -32
  75. package/src/index.ts +71 -73
  76. package/src/logger.ts +65 -65
  77. package/src/parse/parse_card/parse_cloze_card.ts +146 -146
  78. package/src/parse/parse_card/parse_flash_cards.ts +42 -42
  79. package/src/parse/parse_card/parse_match_card.ts +104 -104
  80. package/src/parse/parse_card/parse_mcq_card.ts +114 -114
  81. package/src/parse/parse_card_response.ts +197 -197
  82. package/src/parse/parse_source_content.ts +212 -212
  83. package/src/services/get_prompts.ts +164 -112
  84. package/src/services/open_ai_service.ts +89 -89
  85. package/src/services/qdrant_service.ts +10 -10
  86. package/src/types/base_param_type.ts +13 -13
  87. package/src/types/mongo_concept_fact_type.ts +12 -12
  88. package/src/types/parsed_card_type.ts +39 -39
  89. package/src/types/raw_card_response_types/generated_card_response_type.ts +59 -59
  90. package/src/types/source_taxonomy_type.ts +24 -24
  91. package/src/typology-parsed-response.ts +1932 -1932
  92. package/src/typology_gen/generate_concept_facts.ts +180 -169
  93. package/src/typology_gen/generate_typology.ts +203 -189
  94. package/src/typology_gen/summarize.ts +176 -164
  95. package/src/utils/distributed_quote_restoration.ts +80 -80
  96. package/src/utils/generate_args.ts +29 -29
  97. package/src/utils/parse_openai_response.ts +19 -19
  98. package/src/utils/sanitize_strings.ts +65 -65
  99. package/tsconfig.json +16 -16
  100. package/dist/constants/default_generation_variables.d.ts +0 -3
  101. package/dist/constants/default_generation_variables.d.ts.map +0 -1
  102. package/dist/constants/default_generation_variables.js +0 -580
  103. package/dist/constants/default_generation_variables.js.map +0 -1
  104. package/dist/services/prompts_test.d.ts +0 -10
  105. package/dist/services/prompts_test.d.ts.map +0 -1
  106. package/dist/services/prompts_test.js +0 -227
  107. package/dist/services/prompts_test.js.map +0 -1
  108. package/dist/types/generation_variables_schema.d.ts +0 -14
  109. package/dist/types/generation_variables_schema.d.ts.map +0 -1
  110. package/dist/types/generation_variables_schema.js +0 -3
  111. package/dist/types/generation_variables_schema.js.map +0 -1
  112. package/dist/utils/test.d.ts +0 -2
  113. package/dist/utils/test.d.ts.map +0 -1
  114. package/dist/utils/test.js +0 -5
  115. package/dist/utils/test.js.map +0 -1
  116. package/src/constants/default_generation_variables.ts +0 -624
  117. package/src/types/generation_variables_schema.ts +0 -16
@@ -1,416 +1,418 @@
1
- import {
2
- GenerateCards,
3
- GenerateCardsResponseList,
4
- } from "../card_gen/generate_cards";
5
- import { ParseSourceContent } from "../parse/parse_source_content";
6
- import { OpenAiService } from "../services/open_ai_service";
7
- import { GenerateTypology } from "../typology_gen/generate_typology";
8
- import { GenerateArgs } from "../utils/generate_args";
9
- import { GenerateEmbeddings } from "../embedding_generation/generate_embeddings";
10
- import { LocalConsolidation } from "../embedding_generation/consolidation/local_consolidation";
11
- import { GlobalConsolidation } from "../embedding_generation/consolidation/global_consolidation";
12
- import { BaseParamType } from "../types/base_param_type";
13
- import { SourceTaxonomy } from "../types/source_taxonomy_type";
14
- import { MongoConceptFactSource } from "../types/mongo_concept_fact_type";
15
- import { GenerateConceptFacts } from "../typology_gen/generate_concept_facts";
16
- import { GenerateSummaryCards } from "../typology_gen/summarize";
17
- import { GenerationVariablesSchema } from "../types/generation_variables_schema";
18
-
19
- export class OnlyEverGenerator {
20
- public api_key: string = "";
21
- public openAiService: OpenAiService;
22
- parsedContent?: {
23
- title: string;
24
- headings: string[];
25
- content: any[];
26
- taxonomy: SourceTaxonomy;
27
- source_id: string;
28
- type: string;
29
- } = undefined;
30
- public generationCurriculum: boolean = false;
31
-
32
- //Reference the variable schema for the expected object for generation
33
- public generationVariablesSchema: GenerationVariablesSchema = {
34
- bloom_instructions: {},
35
- output_schema: {
36
- concepts_facts: {},
37
- summary: {},
38
- classification: {},
39
- },
40
- cards: {},
41
- };
42
- public n: number = 0;
43
-
44
- expectedFields: Array<string> = [];
45
- typologyResponse?: any = undefined;
46
- cardgenResponse: GenerateCardsResponseList = [];
47
-
48
- constructor(
49
- apiKey: string,
50
- model: string,
51
- generationContent: BaseParamType,
52
- generationVariablesSchema: GenerationVariablesSchema,
53
- generationCurriculum: boolean,
54
- n: number | undefined
55
- ) {
56
- this.generationVariablesSchema = generationVariablesSchema;
57
- this.api_key = apiKey;
58
- this.generationCurriculum = generationCurriculum;
59
- this.n = n ?? 1;
60
- this.openAiService = new OpenAiService(
61
- apiKey,
62
- model ?? "gpt-3.5-turbo-1106"
63
- );
64
-
65
- const parsedData = new ParseSourceContent(
66
- generationContent.content
67
- ).parseData();
68
- (this.parsedContent = {
69
- title: parsedData.title,
70
- headings: parsedData.headings,
71
- content: parsedData.content,
72
- taxonomy: parsedData.taxonomy,
73
- source_id: parsedData.source_id,
74
- type: parsedData.type,
75
- }),
76
- (this.typologyResponse = generationContent.content.taxonomy);
77
-
78
- this.expectedFields = generationContent.content.fields; //returnFields();
79
- this.generationVariablesSchema = generationVariablesSchema;
80
- }
81
-
82
- async generate(
83
- generate_typology: boolean = false,
84
- generate_card: boolean = false,
85
- card_generation_types: string[] = []
86
- ): Promise<Array<any>> {
87
- try {
88
- const args = new GenerateArgs(generate_card, generate_typology, false);
89
- const responseToReturn: Array<any> = [];
90
- const whatNeedsToBeGenerated = args.getWhatNeedsToBeGenerated();
91
-
92
- for (const elem of whatNeedsToBeGenerated) {
93
- if (elem === "generate_tyopology") {
94
- const typologyResults = await this.processTypologyGeneration();
95
- responseToReturn.push(...typologyResults);
96
- } else if (elem === "generate_card") {
97
- const cardResult = await this.processCardGeneration(
98
- card_generation_types
99
- );
100
- if (cardResult) {
101
- responseToReturn.push(cardResult);
102
- }
103
- }
104
- }
105
-
106
- return responseToReturn;
107
- } catch (error) {
108
- console.log(error);
109
- return [];
110
- }
111
- }
112
-
113
- private async processTypologyGeneration(): Promise<Array<any>> {
114
- this.typologyResponse = await this.generateTypology();
115
- console.log(this.typologyResponse?.generate_cards?.value);
116
-
117
- const results: Array<any> = [];
118
- const isSuccessful = this.typologyResponse?.status_code === 200;
119
- const learnValueThreshold =
120
- (this.typologyResponse?.generate_cards?.value ?? 30) > 30;
121
-
122
- if (!isSuccessful || !learnValueThreshold) {
123
- results.push({
124
- type: "typology",
125
- data: this.typologyResponse,
126
- });
127
- return results;
128
- }
129
-
130
- // Process summary cards and concept facts
131
- await this.processSummaryCardsAndConceptFacts();
132
-
133
- // Only continue if summary cards were generated
134
- if (this.typologyResponse.summary_cards.length === 0) {
135
- return results;
136
- }
137
-
138
- // Process embeddings and consolidation if concept facts exist
139
- const hasConceptFacts = this.typologyResponse.concepts_facts.length > 0;
140
- if (hasConceptFacts) {
141
- const qdrantOps = await this.processEmbeddingsAndConsolidation();
142
- results.push({
143
- type: "typology",
144
- data: this.typologyResponse,
145
- qdrantOps,
146
- });
147
- } else {
148
- results.push({
149
- type: "typology",
150
- data: this.typologyResponse,
151
- qdrantOps: { update: [], inserts: [] },
152
- });
153
- }
154
-
155
- // Add summary cards response if generated
156
- if (this.typologyResponse.summary_cards.length > 0) {
157
- results.push({
158
- type: "summary_cards",
159
- data: this.typologyResponse,
160
- });
161
- }
162
-
163
- return results;
164
- }
165
-
166
- private async processSummaryCardsAndConceptFacts(): Promise<void> {
167
- console.log("generating summary cards");
168
- const summaryCardsResponse = await this.generateSummaryCards();
169
-
170
- if (
171
- summaryCardsResponse &&
172
- summaryCardsResponse.summary_cards &&
173
- summaryCardsResponse.summary_cards.length > 0
174
- ) {
175
- this.typologyResponse.summary_cards = summaryCardsResponse.summary_cards;
176
- this.typologyResponse.metadata.push(summaryCardsResponse.metadata);
177
- } else {
178
- this.typologyResponse.summary_cards = [];
179
- }
180
-
181
- if (this.typologyResponse.summary_cards.length === 0) return;
182
-
183
- const conceptFactsResponse = await this.generateConceptFacts(
184
- this.typologyResponse
185
- );
186
-
187
- if (
188
- conceptFactsResponse &&
189
- conceptFactsResponse.concepts_facts &&
190
- conceptFactsResponse.concepts_facts.length > 0
191
- ) {
192
- this.typologyResponse.concepts_facts =
193
- conceptFactsResponse.concepts_facts;
194
- this.typologyResponse.metadata.push(conceptFactsResponse.metadata);
195
- } else {
196
- this.typologyResponse.concepts_facts = [];
197
- }
198
- }
199
-
200
- private async processEmbeddingsAndConsolidation(): Promise<{
201
- update: any[];
202
- inserts: any[];
203
- }> {
204
- console.log(this.typologyResponse);
205
- const embeddings = await this.generateEmbeddings(this.typologyResponse);
206
- console.log("Embedding generated");
207
-
208
- const localConsolidation = await this.localConsolidation(
209
- embeddings.concepts_facts,
210
- this.parsedContent!.title
211
- );
212
- console.log("Local consolidation done");
213
- this.typologyResponse!.concepts_facts =
214
- localConsolidation.sourceTaxonomyOps;
215
-
216
- const globalConsolidation = await this.globalConsolidation(
217
- localConsolidation.sourceTaxonomyOps,
218
- this.parsedContent!.source_id,
219
- 0.8
220
- );
221
- console.log("Global consolidation done");
222
-
223
- this.typologyResponse!.concepts_facts = globalConsolidation.source_taxonomy;
224
- this.typologyResponse!.metadata?.push(embeddings.metadata);
225
-
226
- return {
227
- update: globalConsolidation.global_updates,
228
- inserts: globalConsolidation.global_inserts,
229
- };
230
- }
231
-
232
- private async processCardGeneration(
233
- card_generation_types: string[]
234
- ): Promise<any | null> {
235
- if (!this.shouldTheCardBeGeneratedAfterTypologyResponse()) {
236
- return null;
237
- }
238
-
239
- console.log("Generating card");
240
- this.parsedContent!.taxonomy = {
241
- concepts_facts: this.typologyResponse?.concepts_facts ?? [],
242
- fields: this.expectedFields,
243
- summary_cards: this.typologyResponse?.summary_cards ?? [],
244
- learn_value: this.typologyResponse?.learn_value ?? {
245
- value: 0,
246
- reason: "",
247
- bloom_levels: [],
248
- bloom_levels_reason: "",
249
- },
250
- };
251
-
252
- this.cardgenResponse = await this.generateCard(
253
- this.n,
254
- card_generation_types
255
- );
256
-
257
- return {
258
- type: "card_gen",
259
- data: this.cardgenResponse,
260
- };
261
- }
262
-
263
- shouldTheCardBeGeneratedAfterTypologyResponse() {
264
- if (this.typologyResponse) {
265
- const hasConceptsFacts =
266
- this.typologyResponse?.concepts_facts &&
267
- Array.isArray(this.typologyResponse.concepts_facts) &&
268
- this.typologyResponse.concepts_facts.length > 0;
269
-
270
- const learnValueAboveThreshold =
271
- (this.typologyResponse?.generate_cards?.value ??
272
- this.typologyResponse?.learn_value?.value ??
273
- 30) > 30;
274
-
275
- return hasConceptsFacts && learnValueAboveThreshold;
276
- } else {
277
- return false;
278
- }
279
- }
280
-
281
- async generateCard(
282
- n: number,
283
- card_generation_types: string[]
284
- ): Promise<GenerateCardsResponseList> {
285
- const content = {
286
- title: this.parsedContent?.title,
287
- concepts_facts: this.typologyResponse?.concepts_facts,
288
- content: this.parsedContent?.content,
289
- };
290
- let generateCardsResp = await new GenerateCards(
291
- this.openAiService,
292
- this.parsedContent?.source_id ?? "",
293
- JSON.stringify(content),
294
- this.parsedContent!.taxonomy,
295
- this.generationCurriculum,
296
- this.parsedContent?.type ?? "text",
297
- this.generationVariablesSchema
298
- ).generateCards(n, card_generation_types);
299
- return generateCardsResp;
300
- }
301
-
302
- async generateTypology() {
303
- const type = this.parsedContent?.type ?? "text";
304
- const content = {
305
- title: this.parsedContent?.title ?? "",
306
- ...(type === "text"
307
- ? { h1_headings: this.parsedContent?.headings ?? [""] }
308
- : { timecodes: this.parsedContent?.headings ?? [""] }),
309
- content: this.parsedContent?.content ?? [],
310
- };
311
- try {
312
- let response = await new GenerateTypology(
313
- this.openAiService,
314
- type,
315
- this.parsedContent?.source_id ?? "",
316
- content,
317
- this.expectedFields,
318
- this.generationCurriculum
319
- ).generate();
320
- return response;
321
- } catch (error) {
322
- console.log(error);
323
- }
324
- }
325
-
326
- async generateConceptFacts(typologyResponse: any) {
327
- const type = this.parsedContent?.type ?? "text";
328
- const content = {
329
- title: this.parsedContent?.title ?? "",
330
- ...(type === "text"
331
- ? { h1_headings: this.parsedContent?.headings ?? [""] }
332
- : { timecodes: this.parsedContent?.headings ?? [""] }),
333
- key_takeaways: typologyResponse?.summary_cards ?? [],
334
- content: this.parsedContent?.content ?? [],
335
- ...(typologyResponse && typeof typologyResponse === "object"
336
- ? {
337
- fields: typologyResponse.field ?? [],
338
- }
339
- : {}),
340
- };
341
- let response = await new GenerateConceptFacts(
342
- this.openAiService,
343
- this.parsedContent?.source_id ?? "",
344
- content,
345
- type,
346
- this.generationCurriculum,
347
- this.generationVariablesSchema
348
- ).generate();
349
- return response;
350
- }
351
-
352
- async generateSummaryCards() {
353
- const type = this.parsedContent?.type ?? "text";
354
- const content = {
355
- title: this.parsedContent?.title ?? "",
356
- ...(type === "text"
357
- ? { h1_headings: this.parsedContent?.headings ?? [""] }
358
- : { timecodes: this.parsedContent?.headings ?? [""] }),
359
- content: this.parsedContent?.content ?? [],
360
- };
361
- let response = await new GenerateSummaryCards(
362
- this.openAiService,
363
- this.parsedContent?.source_id ?? "",
364
- content,
365
- type,
366
- this.generationCurriculum,
367
- this.generationVariablesSchema
368
- ).generate();
369
- return response;
370
- }
371
-
372
- async generateEmbeddings(typologyResponse: any) {
373
- const concepts_facts = typologyResponse.concepts_facts;
374
- const texts = concepts_facts.map((e: MongoConceptFactSource) => e.text);
375
- const embeddings = await new GenerateEmbeddings(
376
- this.openAiService
377
- ).generateEmbeddings(concepts_facts);
378
- return embeddings;
379
- }
380
-
381
- async localConsolidation(
382
- concepts_facts: {
383
- text: string;
384
- type: string;
385
- reference: string;
386
- embedding: number[];
387
- }[],
388
- sourceId: string
389
- ) {
390
- const embeddings = new LocalConsolidation().consolidate(
391
- concepts_facts,
392
- sourceId
393
- );
394
- return embeddings;
395
- }
396
-
397
- async globalConsolidation(
398
- concepts_facts: {
399
- id: string;
400
- text: string;
401
- type: string;
402
- reference: string;
403
- embedding: number[];
404
- }[],
405
- sourceId: string,
406
- threshold: number
407
- ) {
408
- const embeddings = await new GlobalConsolidation().consolidate(
409
- concepts_facts,
410
- sourceId,
411
- threshold ?? 0.8
412
- );
413
-
414
- return embeddings;
415
- }
416
- }
1
+ import {
2
+ GenerateCards,
3
+ GenerateCardsResponseList,
4
+ } from "../card_gen/generate_cards";
5
+ import { ParseSourceContent } from "../parse/parse_source_content";
6
+ import { OpenAiService } from "../services/open_ai_service";
7
+ import { GenerateTypology } from "../typology_gen/generate_typology";
8
+ import { GenerateArgs } from "../utils/generate_args";
9
+ import { GenerateEmbeddings } from "../embedding_generation/generate_embeddings";
10
+ import { LocalConsolidation } from "../embedding_generation/consolidation/local_consolidation";
11
+ import { GlobalConsolidation } from "../embedding_generation/consolidation/global_consolidation";
12
+ import { BaseParamType } from "../types/base_param_type";
13
+ import { SourceTaxonomy } from "../types/source_taxonomy_type";
14
+ import { MongoConceptFactSource } from "../types/mongo_concept_fact_type";
15
+ import { GenerateConceptFacts } from "../typology_gen/generate_concept_facts";
16
+ import { GenerateSummaryCards } from "../typology_gen/summarize";
17
+
18
+ export class OnlyEverGenerator {
19
+ public api_key: string = "";
20
+ public openAiService: OpenAiService;
21
+
22
+ /// these fields will be populated inside the constructor
23
+ parsedContent?: {
24
+ title: string;
25
+ headings: string[];
26
+ content: any[];
27
+ taxonomy: SourceTaxonomy;
28
+ source_id: string;
29
+ type: string;
30
+ } = undefined;
31
+ public generationCurriculum: boolean = false;
32
+ public promptIdForTypology: string;
33
+ public promptIdForConceptFacts: string;
34
+ public promptIdForCardsGeneration: string;
35
+ public promptIdForSummaryCards: string;
36
+ public n: number = 0;
37
+
38
+ expectedFields: Array<string> = [];
39
+ typologyResponse?: any = undefined;
40
+ cardgenResponse: GenerateCardsResponseList = [];
41
+ summarizeResponse = {};
42
+
43
+ constructor(
44
+ apiKey: string,
45
+ model: string,
46
+ generationContent: BaseParamType,
47
+ promptIdForTypology: string,
48
+ promptIdForConceptFacts: string,
49
+ promptIdForCardsGeneration: string,
50
+ promptIdForSummaryCards: string,
51
+
52
+ generationCurriculum: boolean,
53
+ n: number | undefined
54
+ ) {
55
+ this.promptIdForTypology = promptIdForTypology;
56
+ this.promptIdForConceptFacts = promptIdForConceptFacts;
57
+ this.promptIdForCardsGeneration = promptIdForCardsGeneration;
58
+ this.promptIdForSummaryCards = promptIdForSummaryCards;
59
+ this.api_key = apiKey;
60
+ this.generationCurriculum = generationCurriculum;
61
+ this.n = n ?? 1;
62
+ this.openAiService = new OpenAiService(
63
+ apiKey,
64
+ model ?? "gpt-3.5-turbo-1106"
65
+ );
66
+
67
+ const parsedData = new ParseSourceContent(
68
+ generationContent.content
69
+ ).parseData();
70
+ (this.parsedContent = {
71
+ title: parsedData.title,
72
+ headings: parsedData.headings,
73
+ content: parsedData.content,
74
+ taxonomy: parsedData.taxonomy,
75
+ source_id: parsedData.source_id,
76
+ type: parsedData.type,
77
+ }),
78
+ (this.typologyResponse = generationContent.content.taxonomy);
79
+
80
+ this.expectedFields = generationContent.content.fields; //returnFields();
81
+ }
82
+
83
+ async generate(
84
+ generate_typology: boolean = false,
85
+ generate_card: boolean = false,
86
+ card_generation_types: string[] = []
87
+ ): Promise<Array<any>> {
88
+ try {
89
+ const args = new GenerateArgs(generate_card, generate_typology, false);
90
+ const responseToReturn: Array<any> = [];
91
+ const whatNeedsToBeGenerated = args.getWhatNeedsToBeGenerated();
92
+
93
+ for (const elem of whatNeedsToBeGenerated) {
94
+ if (elem === "generate_tyopology") {
95
+ const typologyResults = await this.processTypologyGeneration();
96
+ responseToReturn.push(...typologyResults);
97
+ } else if (elem === "generate_card") {
98
+ const cardResult = await this.processCardGeneration(
99
+ card_generation_types
100
+ );
101
+ if (cardResult) {
102
+ responseToReturn.push(cardResult);
103
+ }
104
+ }
105
+ }
106
+
107
+ return responseToReturn;
108
+ } catch (error) {
109
+ console.log(error);
110
+ return [];
111
+ }
112
+ }
113
+
114
+ private async processTypologyGeneration(): Promise<Array<any>> {
115
+ this.typologyResponse = await this.generateTypology();
116
+ console.log(this.typologyResponse?.generate_cards?.value);
117
+
118
+ const results: Array<any> = [];
119
+ const isSuccessful = this.typologyResponse?.status_code === 200;
120
+ const learnValueThreshold =
121
+ (this.typologyResponse?.generate_cards?.value ?? 30) > 30;
122
+
123
+ if (!isSuccessful || !learnValueThreshold) {
124
+ results.push({
125
+ type: "typology",
126
+ data: this.typologyResponse,
127
+ });
128
+ return results;
129
+ }
130
+
131
+ // Process summary cards and concept facts
132
+ await this.processSummaryCardsAndConceptFacts();
133
+
134
+ // Only continue if summary cards were generated
135
+ if (this.typologyResponse.summary_cards.length === 0) {
136
+ return results;
137
+ }
138
+
139
+ // Process embeddings and consolidation if concept facts exist
140
+ const hasConceptFacts = this.typologyResponse.concepts_facts.length > 0;
141
+ if (hasConceptFacts) {
142
+ const qdrantOps = await this.processEmbeddingsAndConsolidation();
143
+ results.push({
144
+ type: "typology",
145
+ data: this.typologyResponse,
146
+ qdrantOps,
147
+ });
148
+ } else {
149
+ results.push({
150
+ type: "typology",
151
+ data: this.typologyResponse,
152
+ qdrantOps: { update: [], inserts: [] },
153
+ });
154
+ }
155
+
156
+ // Add summary cards response if generated
157
+ if (this.typologyResponse.summary_cards.length > 0) {
158
+ results.push({
159
+ type: "summary_cards",
160
+ data: this.typologyResponse,
161
+ });
162
+ }
163
+
164
+ return results;
165
+ }
166
+
167
+ private async processSummaryCardsAndConceptFacts(): Promise<void> {
168
+ console.log("generating summary cards");
169
+ const summaryCardsResponse = await this.generateSummaryCards();
170
+
171
+ if (
172
+ summaryCardsResponse &&
173
+ summaryCardsResponse.summary_cards &&
174
+ summaryCardsResponse.summary_cards.length > 0
175
+ ) {
176
+ this.typologyResponse.summary_cards = summaryCardsResponse.summary_cards;
177
+ this.typologyResponse.metadata.push(summaryCardsResponse.metadata);
178
+ } else {
179
+ this.typologyResponse.summary_cards = [];
180
+ }
181
+
182
+ if (this.typologyResponse.summary_cards.length === 0) return;
183
+
184
+ const conceptFactsResponse = await this.generateConceptFacts(
185
+ this.typologyResponse
186
+ );
187
+
188
+ if (
189
+ conceptFactsResponse &&
190
+ conceptFactsResponse.concepts_facts &&
191
+ conceptFactsResponse.concepts_facts.length > 0
192
+ ) {
193
+ this.typologyResponse.concepts_facts =
194
+ conceptFactsResponse.concepts_facts;
195
+ this.typologyResponse.metadata.push(conceptFactsResponse.metadata);
196
+ } else {
197
+ this.typologyResponse.concepts_facts = [];
198
+ }
199
+ }
200
+
201
+ private async processEmbeddingsAndConsolidation(): Promise<{
202
+ update: any[];
203
+ inserts: any[];
204
+ }> {
205
+ console.log(this.typologyResponse);
206
+ const embeddings = await this.generateEmbeddings(this.typologyResponse);
207
+ console.log("Embedding generated");
208
+
209
+ const localConsolidation = await this.localConsolidation(
210
+ embeddings.concepts_facts,
211
+ this.parsedContent!.title
212
+ );
213
+ console.log("Local consolidation done");
214
+ this.typologyResponse!.concepts_facts =
215
+ localConsolidation.sourceTaxonomyOps;
216
+
217
+ const globalConsolidation = await this.globalConsolidation(
218
+ localConsolidation.sourceTaxonomyOps,
219
+ this.parsedContent!.source_id,
220
+ 0.8
221
+ );
222
+ console.log("Global consolidation done");
223
+
224
+ this.typologyResponse!.concepts_facts = globalConsolidation.source_taxonomy;
225
+ this.typologyResponse!.metadata?.push(embeddings.metadata);
226
+
227
+ return {
228
+ update: globalConsolidation.global_updates,
229
+ inserts: globalConsolidation.global_inserts,
230
+ };
231
+ }
232
+
233
+ private async processCardGeneration(
234
+ card_generation_types: string[]
235
+ ): Promise<any | null> {
236
+ if (!this.shouldTheCardBeGeneratedAfterTypologyResponse()) {
237
+ return null;
238
+ }
239
+
240
+ console.log("Generating card");
241
+ this.parsedContent!.taxonomy = {
242
+ concepts_facts: this.typologyResponse?.concepts_facts ?? [],
243
+ fields: this.expectedFields,
244
+ summary_cards: this.typologyResponse?.summary_cards ?? [],
245
+ learn_value: this.typologyResponse?.learn_value ?? {
246
+ value: 0,
247
+ reason: "",
248
+ bloom_levels: [],
249
+ bloom_levels_reason: "",
250
+ },
251
+ };
252
+
253
+ this.cardgenResponse = await this.generateCard(
254
+ this.n,
255
+ card_generation_types
256
+ );
257
+
258
+ return {
259
+ type: "card_gen",
260
+ data: this.cardgenResponse,
261
+ };
262
+ }
263
+
264
+ shouldTheCardBeGeneratedAfterTypologyResponse() {
265
+ if (this.typologyResponse) {
266
+ const hasConceptsFacts =
267
+ this.typologyResponse?.concepts_facts &&
268
+ Array.isArray(this.typologyResponse.concepts_facts) &&
269
+ this.typologyResponse.concepts_facts.length > 0;
270
+
271
+ const learnValueAboveThreshold =
272
+ (this.typologyResponse?.generate_cards?.value ??
273
+ this.typologyResponse?.learn_value?.value ??
274
+ 30) > 30;
275
+
276
+ return hasConceptsFacts && learnValueAboveThreshold;
277
+ } else {
278
+ return false;
279
+ }
280
+ }
281
+
282
+ async generateCard(
283
+ n: number,
284
+ card_generation_types: string[]
285
+ ): Promise<GenerateCardsResponseList> {
286
+ const content = {
287
+ title: this.parsedContent?.title,
288
+ concepts_facts: this.typologyResponse?.concepts_facts,
289
+ content: this.parsedContent?.content,
290
+ };
291
+ let generateCardsResp = await new GenerateCards(
292
+ this.openAiService,
293
+ this.parsedContent?.source_id ?? "",
294
+ JSON.stringify(content),
295
+ this.parsedContent!.taxonomy,
296
+ this.promptIdForCardsGeneration,
297
+ this.generationCurriculum,
298
+ this.parsedContent?.type ?? "text"
299
+ ).generateCards(n, card_generation_types);
300
+ return generateCardsResp;
301
+ }
302
+
303
+ async generateTypology() {
304
+ const type = this.parsedContent?.type ?? "text";
305
+ const content = {
306
+ title: this.parsedContent?.title ?? "",
307
+ ...(type === "text"
308
+ ? { h1_headings: this.parsedContent?.headings ?? [""] }
309
+ : { timecodes: this.parsedContent?.headings ?? [""] }),
310
+ content: this.parsedContent?.content ?? [],
311
+ };
312
+ try {
313
+ let response = await new GenerateTypology(
314
+ this.openAiService,
315
+ type,
316
+ this.parsedContent?.source_id ?? "",
317
+ content,
318
+ this.expectedFields,
319
+ this.promptIdForTypology,
320
+ this.generationCurriculum
321
+ ).generate();
322
+ return response;
323
+ } catch (error) {
324
+ console.log(error);
325
+ }
326
+ }
327
+
328
+ async generateConceptFacts(typologyResponse: any) {
329
+ const type = this.parsedContent?.type ?? "text";
330
+ const content = {
331
+ title: this.parsedContent?.title ?? "",
332
+ ...(type === "text"
333
+ ? { h1_headings: this.parsedContent?.headings ?? [""] }
334
+ : { timecodes: this.parsedContent?.headings ?? [""] }),
335
+ key_takeaways: typologyResponse?.summary_cards ?? [],
336
+ content: this.parsedContent?.content ?? [],
337
+ ...(typologyResponse && typeof typologyResponse === "object"
338
+ ? {
339
+ fields: typologyResponse.field ?? [],
340
+ }
341
+ : {}),
342
+ };
343
+ let response = await new GenerateConceptFacts(
344
+ this.openAiService,
345
+ this.parsedContent?.source_id ?? "",
346
+ content,
347
+ type,
348
+ this.promptIdForConceptFacts,
349
+ this.generationCurriculum
350
+ ).generate();
351
+ return response;
352
+ }
353
+
354
+ async generateSummaryCards() {
355
+ const type = this.parsedContent?.type ?? "text";
356
+ const content = {
357
+ title: this.parsedContent?.title ?? "",
358
+ ...(type === "text"
359
+ ? { h1_headings: this.parsedContent?.headings ?? [""] }
360
+ : { timecodes: this.parsedContent?.headings ?? [""] }),
361
+ content: this.parsedContent?.content ?? [],
362
+ };
363
+ let response = await new GenerateSummaryCards(
364
+ this.openAiService,
365
+ this.parsedContent?.source_id ?? "",
366
+ content,
367
+ type,
368
+ this.promptIdForSummaryCards,
369
+ this.generationCurriculum
370
+ ).generate();
371
+ return response;
372
+ }
373
+
374
+ async generateEmbeddings(typologyResponse: any) {
375
+ const concepts_facts = typologyResponse.concepts_facts;
376
+ const texts = concepts_facts.map((e: MongoConceptFactSource) => e.text);
377
+ const embeddings = await new GenerateEmbeddings(
378
+ this.openAiService
379
+ ).generateEmbeddings(concepts_facts);
380
+ return embeddings;
381
+ }
382
+
383
+ async localConsolidation(
384
+ concepts_facts: {
385
+ text: string;
386
+ type: string;
387
+ reference: string;
388
+ embedding: number[];
389
+ }[],
390
+ sourceId: string
391
+ ) {
392
+ const embeddings = new LocalConsolidation().consolidate(
393
+ concepts_facts,
394
+ sourceId
395
+ );
396
+ return embeddings;
397
+ }
398
+
399
+ async globalConsolidation(
400
+ concepts_facts: {
401
+ id: string;
402
+ text: string;
403
+ type: string;
404
+ reference: string;
405
+ embedding: number[];
406
+ }[],
407
+ sourceId: string,
408
+ threshold: number
409
+ ) {
410
+ const embeddings = await new GlobalConsolidation().consolidate(
411
+ concepts_facts,
412
+ sourceId,
413
+ threshold ?? 0.8
414
+ );
415
+
416
+ return embeddings;
417
+ }
418
+ }