@proteinjs/conversation 1.0.5 → 1.0.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 (152) hide show
  1. package/.eslintrc.js +20 -0
  2. package/.prettierrc +8 -0
  3. package/CHANGELOG.md +7 -4
  4. package/LICENSE +21 -0
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +40 -28
  7. package/dist/src/CodegenConversation.d.ts +11 -11
  8. package/dist/src/CodegenConversation.d.ts.map +1 -1
  9. package/dist/src/CodegenConversation.js +294 -180
  10. package/dist/src/CodegenConversation.js.map +1 -1
  11. package/dist/src/Conversation.d.ts +52 -49
  12. package/dist/src/Conversation.d.ts.map +1 -1
  13. package/dist/src/Conversation.js +480 -274
  14. package/dist/src/Conversation.js.map +1 -1
  15. package/dist/src/ConversationModule.d.ts +6 -6
  16. package/dist/src/ConversationModule.js +3 -3
  17. package/dist/src/Function.d.ts +4 -4
  18. package/dist/src/Function.d.ts.map +1 -1
  19. package/dist/src/Function.js +3 -3
  20. package/dist/src/OpenAi.d.ts +42 -10
  21. package/dist/src/OpenAi.d.ts.map +1 -1
  22. package/dist/src/OpenAi.js +496 -289
  23. package/dist/src/OpenAi.js.map +1 -1
  24. package/dist/src/Paragraph.d.ts +4 -4
  25. package/dist/src/Paragraph.d.ts.map +1 -1
  26. package/dist/src/Paragraph.js +17 -16
  27. package/dist/src/Paragraph.js.map +1 -1
  28. package/dist/src/Sentence.d.ts +4 -4
  29. package/dist/src/Sentence.d.ts.map +1 -1
  30. package/dist/src/Sentence.js +21 -19
  31. package/dist/src/Sentence.js.map +1 -1
  32. package/dist/src/code_template/Code.d.ts +15 -15
  33. package/dist/src/code_template/Code.d.ts.map +1 -1
  34. package/dist/src/code_template/Code.js +167 -69
  35. package/dist/src/code_template/Code.js.map +1 -1
  36. package/dist/src/code_template/CodeTemplate.d.ts +11 -11
  37. package/dist/src/code_template/CodeTemplate.d.ts.map +1 -1
  38. package/dist/src/code_template/CodeTemplate.js +169 -79
  39. package/dist/src/code_template/CodeTemplate.js.map +1 -1
  40. package/dist/src/code_template/CodeTemplateModule.d.ts +6 -6
  41. package/dist/src/code_template/CodeTemplateModule.js +28 -26
  42. package/dist/src/code_template/Repo.d.ts +34 -38
  43. package/dist/src/code_template/Repo.d.ts.map +1 -1
  44. package/dist/src/code_template/Repo.js +291 -191
  45. package/dist/src/code_template/Repo.js.map +1 -1
  46. package/dist/src/fs/conversation_fs/ConversationFsModerator.d.ts +12 -12
  47. package/dist/src/fs/conversation_fs/ConversationFsModerator.d.ts.map +1 -1
  48. package/dist/src/fs/conversation_fs/ConversationFsModerator.js +111 -98
  49. package/dist/src/fs/conversation_fs/ConversationFsModerator.js.map +1 -1
  50. package/dist/src/fs/conversation_fs/ConversationFsModule.d.ts +11 -11
  51. package/dist/src/fs/conversation_fs/ConversationFsModule.d.ts.map +1 -1
  52. package/dist/src/fs/conversation_fs/ConversationFsModule.js +204 -99
  53. package/dist/src/fs/conversation_fs/ConversationFsModule.js.map +1 -1
  54. package/dist/src/fs/conversation_fs/FsFunctions.d.ts +58 -62
  55. package/dist/src/fs/conversation_fs/FsFunctions.d.ts.map +1 -1
  56. package/dist/src/fs/conversation_fs/FsFunctions.js +414 -266
  57. package/dist/src/fs/conversation_fs/FsFunctions.js.map +1 -1
  58. package/dist/src/fs/git/GitModule.d.ts +8 -8
  59. package/dist/src/fs/git/GitModule.d.ts.map +1 -1
  60. package/dist/src/fs/git/GitModule.js +163 -74
  61. package/dist/src/fs/git/GitModule.js.map +1 -1
  62. package/dist/src/fs/keyword_to_files_index/KeywordToFilesIndexFunctions.d.ts +16 -18
  63. package/dist/src/fs/keyword_to_files_index/KeywordToFilesIndexFunctions.d.ts.map +1 -1
  64. package/dist/src/fs/keyword_to_files_index/KeywordToFilesIndexFunctions.js +158 -58
  65. package/dist/src/fs/keyword_to_files_index/KeywordToFilesIndexFunctions.js.map +1 -1
  66. package/dist/src/fs/keyword_to_files_index/KeywordToFilesIndexModule.d.ts +27 -26
  67. package/dist/src/fs/keyword_to_files_index/KeywordToFilesIndexModule.d.ts.map +1 -1
  68. package/dist/src/fs/keyword_to_files_index/KeywordToFilesIndexModule.js +234 -133
  69. package/dist/src/fs/keyword_to_files_index/KeywordToFilesIndexModule.js.map +1 -1
  70. package/dist/src/fs/package/PackageFunctions.d.ts +54 -60
  71. package/dist/src/fs/package/PackageFunctions.d.ts.map +1 -1
  72. package/dist/src/fs/package/PackageFunctions.js +366 -223
  73. package/dist/src/fs/package/PackageFunctions.js.map +1 -1
  74. package/dist/src/fs/package/PackageModule.d.ts +24 -24
  75. package/dist/src/fs/package/PackageModule.d.ts.map +1 -1
  76. package/dist/src/fs/package/PackageModule.js +292 -163
  77. package/dist/src/fs/package/PackageModule.js.map +1 -1
  78. package/dist/src/history/MessageHistory.d.ts +12 -12
  79. package/dist/src/history/MessageHistory.d.ts.map +1 -1
  80. package/dist/src/history/MessageHistory.js +52 -43
  81. package/dist/src/history/MessageHistory.js.map +1 -1
  82. package/dist/src/history/MessageModerator.d.ts +2 -2
  83. package/dist/src/history/MessageModerator.js +3 -3
  84. package/dist/src/template/ConversationTemplate.d.ts +8 -8
  85. package/dist/src/template/ConversationTemplate.d.ts.map +1 -1
  86. package/dist/src/template/ConversationTemplate.js +3 -3
  87. package/dist/src/template/ConversationTemplateFunctions.d.ts +33 -35
  88. package/dist/src/template/ConversationTemplateFunctions.d.ts.map +1 -1
  89. package/dist/src/template/ConversationTemplateFunctions.js +176 -75
  90. package/dist/src/template/ConversationTemplateFunctions.js.map +1 -1
  91. package/dist/src/template/ConversationTemplateModule.d.ts +51 -48
  92. package/dist/src/template/ConversationTemplateModule.d.ts.map +1 -1
  93. package/dist/src/template/ConversationTemplateModule.js +211 -114
  94. package/dist/src/template/ConversationTemplateModule.js.map +1 -1
  95. package/dist/src/template/createApp/CreateAppTemplate.d.ts +1 -1
  96. package/dist/src/template/createApp/CreateAppTemplate.js +151 -59
  97. package/dist/src/template/createCode/CreateCodeConversationTemplate.d.ts +1 -1
  98. package/dist/src/template/createCode/CreateCodeConversationTemplate.d.ts.map +1 -1
  99. package/dist/src/template/createCode/CreateCodeConversationTemplate.js +183 -74
  100. package/dist/src/template/createCode/CreateCodeConversationTemplate.js.map +1 -1
  101. package/dist/src/template/createPackage/CreatePackageConversationTemplate.d.ts +1 -1
  102. package/dist/src/template/createPackage/CreatePackageConversationTemplate.d.ts.map +1 -1
  103. package/dist/src/template/createPackage/CreatePackageConversationTemplate.js +174 -84
  104. package/dist/src/template/createPackage/CreatePackageConversationTemplate.js.map +1 -1
  105. package/dist/src/template/createPackage/tsconfig.json +11 -11
  106. package/dist/test/createKeywordFilesIndex.test.d.ts +1 -1
  107. package/dist/test/createKeywordFilesIndex.test.js +132 -41
  108. package/dist/test/createKeywordFilesIndex.test.js.map +1 -1
  109. package/dist/test/openai/openai.generateList.test.d.ts +1 -1
  110. package/dist/test/openai/openai.generateList.test.js +136 -47
  111. package/dist/test/openai/openai.generateList.test.js.map +1 -1
  112. package/dist/test/openai/openai.parseCodeFromMarkdown.test.d.ts +1 -1
  113. package/dist/test/openai/openai.parseCodeFromMarkdown.test.js +15 -10
  114. package/dist/test/openai/openai.parseCodeFromMarkdown.test.js.map +1 -1
  115. package/dist/test/repo/repo.test.d.ts +1 -1
  116. package/dist/test/repo/repo.test.js +127 -38
  117. package/dist/test/repo/repo.test.js.map +1 -1
  118. package/jest.config.js +2 -2
  119. package/package.json +11 -5
  120. package/src/CodegenConversation.ts +6 -4
  121. package/src/Conversation.ts +102 -33
  122. package/src/ConversationModule.ts +2 -2
  123. package/src/Function.ts +0 -1
  124. package/src/OpenAi.ts +128 -63
  125. package/src/Paragraph.ts +3 -2
  126. package/src/Sentence.ts +5 -3
  127. package/src/code_template/Code.ts +25 -19
  128. package/src/code_template/CodeTemplate.ts +8 -7
  129. package/src/code_template/CodeTemplateModule.ts +2 -2
  130. package/src/code_template/Repo.ts +25 -19
  131. package/src/fs/conversation_fs/ConversationFsModerator.ts +34 -20
  132. package/src/fs/conversation_fs/ConversationFsModule.ts +13 -7
  133. package/src/fs/conversation_fs/FsFunctions.ts +33 -44
  134. package/src/fs/git/GitModule.ts +2 -4
  135. package/src/fs/keyword_to_files_index/KeywordToFilesIndexFunctions.ts +31 -31
  136. package/src/fs/keyword_to_files_index/KeywordToFilesIndexModule.ts +19 -18
  137. package/src/fs/package/PackageFunctions.ts +34 -41
  138. package/src/fs/package/PackageModule.ts +33 -21
  139. package/src/history/MessageHistory.ts +7 -4
  140. package/src/history/MessageModerator.ts +1 -1
  141. package/src/template/ConversationTemplate.ts +9 -9
  142. package/src/template/ConversationTemplateFunctions.ts +8 -7
  143. package/src/template/ConversationTemplateModule.ts +24 -15
  144. package/src/template/createApp/CreateAppTemplate.ts +1 -1
  145. package/src/template/createCode/CreateCodeConversationTemplate.ts +9 -11
  146. package/src/template/createPackage/CreatePackageConversationTemplate.ts +2 -9
  147. package/src/template/createPackage/jest.config.js +2 -2
  148. package/test/createKeywordFilesIndex.test.ts +3 -3
  149. package/test/openai/openai.generateList.test.ts +5 -3
  150. package/test/openai/openai.parseCodeFromMarkdown.test.ts +10 -5
  151. package/test/repo/repo.test.ts +3 -4
  152. package/tsconfig.json +16 -20
@@ -1,305 +1,512 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1
+ 'use strict';
2
+ var __awaiter =
3
+ (this && this.__awaiter) ||
4
+ function (thisArg, _arguments, P, generator) {
5
+ function adopt(value) {
6
+ return value instanceof P
7
+ ? value
8
+ : new P(function (resolve) {
9
+ resolve(value);
10
+ });
11
+ }
4
12
  return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ function fulfilled(value) {
14
+ try {
15
+ step(generator.next(value));
16
+ } catch (e) {
17
+ reject(e);
18
+ }
19
+ }
20
+ function rejected(value) {
21
+ try {
22
+ step(generator['throw'](value));
23
+ } catch (e) {
24
+ reject(e);
25
+ }
26
+ }
27
+ function step(result) {
28
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
29
+ }
30
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
31
  });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
32
+ };
33
+ var __generator =
34
+ (this && this.__generator) ||
35
+ function (thisArg, body) {
36
+ var _ = {
37
+ label: 0,
38
+ sent: function () {
39
+ if (t[0] & 1) throw t[1];
40
+ return t[1];
41
+ },
42
+ trys: [],
43
+ ops: [],
44
+ },
45
+ f,
46
+ y,
47
+ t,
48
+ g;
49
+ return (
50
+ (g = { next: verb(0), throw: verb(1), return: verb(2) }),
51
+ typeof Symbol === 'function' &&
52
+ (g[Symbol.iterator] = function () {
53
+ return this;
54
+ }),
55
+ g
56
+ );
57
+ function verb(n) {
58
+ return function (v) {
59
+ return step([n, v]);
60
+ };
61
+ }
15
62
  function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
63
+ if (f) throw new TypeError('Generator is already executing.');
64
+ while ((g && ((g = 0), op[0] && (_ = 0)), _))
65
+ try {
66
+ if (
67
+ ((f = 1),
68
+ y &&
69
+ (t = op[0] & 2 ? y['return'] : op[0] ? y['throw'] || ((t = y['return']) && t.call(y), 0) : y.next) &&
70
+ !(t = t.call(y, op[1])).done)
71
+ )
72
+ return t;
73
+ if (((y = 0), t)) op = [op[0] & 2, t.value];
74
+ switch (op[0]) {
75
+ case 0:
76
+ case 1:
77
+ t = op;
78
+ break;
79
+ case 4:
80
+ _.label++;
81
+ return { value: op[1], done: false };
82
+ case 5:
83
+ _.label++;
84
+ y = op[1];
85
+ op = [0];
86
+ continue;
87
+ case 7:
88
+ op = _.ops.pop();
89
+ _.trys.pop();
90
+ continue;
91
+ default:
92
+ if (!((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && (op[0] === 6 || op[0] === 2)) {
93
+ _ = 0;
94
+ continue;
95
+ }
96
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
97
+ _.label = op[1];
98
+ break;
99
+ }
100
+ if (op[0] === 6 && _.label < t[1]) {
101
+ _.label = t[1];
102
+ t = op;
103
+ break;
104
+ }
105
+ if (t && _.label < t[2]) {
106
+ _.label = t[2];
107
+ _.ops.push(op);
108
+ break;
109
+ }
110
+ if (t[2]) _.ops.pop();
111
+ _.trys.pop();
112
+ continue;
113
+ }
114
+ op = body.call(thisArg, _);
115
+ } catch (e) {
116
+ op = [6, e];
117
+ y = 0;
118
+ } finally {
119
+ f = t = 0;
120
+ }
121
+ if (op[0] & 5) throw op[1];
122
+ return { value: op[0] ? op[1] : void 0, done: true };
36
123
  }
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
124
+ };
125
+ Object.defineProperty(exports, '__esModule', { value: true });
39
126
  exports.OpenAi = exports.DEFAULT_MODEL = void 0;
40
- var openai_1 = require("openai");
41
- var util_1 = require("@proteinjs/util");
42
- var MessageHistory_1 = require("./history/MessageHistory");
127
+ var openai_1 = require('openai');
128
+ var util_1 = require('@proteinjs/util');
129
+ var MessageHistory_1 = require('./history/MessageHistory');
43
130
  function delay(ms) {
44
- return new Promise(function (resolve) { return setTimeout(resolve, ms); });
131
+ return new Promise(function (resolve) {
132
+ return setTimeout(resolve, ms);
133
+ });
45
134
  }
46
135
  exports.DEFAULT_MODEL = 'gpt-3.5-turbo';
47
136
  var OpenAi = /** @class */ (function () {
48
- function OpenAi() {
137
+ function OpenAi() {}
138
+ OpenAi.generateResponse = function (messages, model, history, functions, messageModerators, logLevel) {
139
+ if (logLevel === void 0) {
140
+ logLevel = 'info';
49
141
  }
50
- OpenAi.generateResponse = function (messages, model, history, functions, messageModerators, logLevel) {
51
- if (logLevel === void 0) { logLevel = 'info'; }
52
- return __awaiter(this, void 0, void 0, function () {
53
- var logger, messageParams, messageParamsWithHistory, response, responseMessage, functionReturnMessage, responseText;
54
- return __generator(this, function (_a) {
55
- switch (_a.label) {
56
- case 0:
57
- logger = new util_1.Logger('OpenAi.generateResponse', logLevel);
58
- messageParams = messages.map(function (message) { return { role: 'user', content: message }; });
59
- if (history)
60
- history.push(messageParams);
61
- messageParamsWithHistory = history ? history : new MessageHistory_1.MessageHistory().push(messageParams);
62
- if (messageModerators)
63
- messageParamsWithHistory = OpenAi.moderateHistory(messageParamsWithHistory, messageModerators);
64
- return [4 /*yield*/, OpenAi.executeRequest(messageParamsWithHistory, logLevel, functions, model)];
65
- case 1:
66
- response = _a.sent();
67
- responseMessage = response.choices[0].message;
68
- if (!responseMessage.function_call) return [3 /*break*/, 4];
69
- messageParamsWithHistory.push([responseMessage]);
70
- return [4 /*yield*/, this.callFunction(logLevel, responseMessage.function_call, functions)];
71
- case 2:
72
- functionReturnMessage = _a.sent();
73
- if (functionReturnMessage)
74
- messageParamsWithHistory.push([functionReturnMessage]);
75
- return [4 /*yield*/, this.generateResponse([], model, messageParamsWithHistory, functions, messageModerators, logLevel)];
76
- case 3: return [2 /*return*/, _a.sent()];
77
- case 4:
78
- responseText = responseMessage.content;
79
- if (!responseText) {
80
- logger.error("Received response: ".concat(JSON.stringify(response)));
81
- throw new Error("Response was empty for messages: ".concat(messages.join('\n')));
82
- }
83
- messageParamsWithHistory.push([responseMessage]);
84
- return [2 /*return*/, responseText];
85
- }
142
+ return __awaiter(this, void 0, void 0, function () {
143
+ var logger,
144
+ messageParams,
145
+ messageParamsWithHistory,
146
+ response,
147
+ responseMessage,
148
+ functionReturnMessage,
149
+ responseText;
150
+ return __generator(this, function (_a) {
151
+ switch (_a.label) {
152
+ case 0:
153
+ logger = new util_1.Logger('OpenAi.generateResponse', logLevel);
154
+ messageParams = messages.map(function (message) {
155
+ return { role: 'user', content: message };
86
156
  });
87
- });
88
- };
89
- OpenAi.moderateHistory = function (history, messageModerators) {
90
- for (var _i = 0, messageModerators_1 = messageModerators; _i < messageModerators_1.length; _i++) {
91
- var messageModerator = messageModerators_1[_i];
92
- history.setMessages(messageModerator.observe(history.getMessages()));
157
+ if (history) {
158
+ history.push(messageParams);
159
+ }
160
+ messageParamsWithHistory = history ? history : new MessageHistory_1.MessageHistory().push(messageParams);
161
+ if (messageModerators) {
162
+ messageParamsWithHistory = OpenAi.moderateHistory(messageParamsWithHistory, messageModerators);
163
+ }
164
+ return [4 /*yield*/, OpenAi.executeRequest(messageParamsWithHistory, logLevel, functions, model)];
165
+ case 1:
166
+ response = _a.sent();
167
+ responseMessage = response.choices[0].message;
168
+ if (!responseMessage.function_call) return [3 /*break*/, 4];
169
+ messageParamsWithHistory.push([responseMessage]);
170
+ return [4 /*yield*/, this.callFunction(logLevel, responseMessage.function_call, functions)];
171
+ case 2:
172
+ functionReturnMessage = _a.sent();
173
+ if (functionReturnMessage) {
174
+ messageParamsWithHistory.push([functionReturnMessage]);
175
+ }
176
+ return [
177
+ 4 /*yield*/,
178
+ this.generateResponse([], model, messageParamsWithHistory, functions, messageModerators, logLevel),
179
+ ];
180
+ case 3:
181
+ return [2 /*return*/, _a.sent()];
182
+ case 4:
183
+ responseText = responseMessage.content;
184
+ if (!responseText) {
185
+ logger.error('Received response: '.concat(JSON.stringify(response)));
186
+ throw new Error('Response was empty for messages: '.concat(messages.join('\n')));
187
+ }
188
+ messageParamsWithHistory.push([responseMessage]);
189
+ return [2 /*return*/, responseText];
93
190
  }
94
- return history;
95
- };
96
- OpenAi.executeRequest = function (messageParamsWithHistory, logLevel, functions, model) {
97
- return __awaiter(this, void 0, void 0, function () {
98
- var logger, openaiApi, response, latestMessage, responseMessage, error_1, waitTime, remainingTokens, delayMs;
99
- return __generator(this, function (_a) {
100
- switch (_a.label) {
101
- case 0:
102
- logger = new util_1.Logger('OpenAi.executeRequest', logLevel);
103
- openaiApi = new openai_1.OpenAI();
104
- _a.label = 1;
105
- case 1:
106
- _a.trys.push([1, 3, , 7]);
107
- latestMessage = messageParamsWithHistory.getMessages()[messageParamsWithHistory.getMessages().length - 1];
108
- if (latestMessage.content)
109
- logger.info("Sending request: ".concat(latestMessage.content));
110
- else if (latestMessage.role == 'function')
111
- logger.info("Sending request: returning output of ".concat(latestMessage.name, " function"));
112
- else
113
- logger.info("Sending request");
114
- logger.debug("Sending messages: ".concat(JSON.stringify(messageParamsWithHistory.getMessages(), null, 2)), true);
115
- return [4 /*yield*/, openaiApi.chat.completions.create({
116
- model: model ? model : exports.DEFAULT_MODEL,
117
- temperature: 0,
118
- messages: messageParamsWithHistory.getMessages(),
119
- functions: functions === null || functions === void 0 ? void 0 : functions.map(function (f) { return f.definition; }),
120
- })];
121
- case 2:
122
- response = _a.sent();
123
- responseMessage = response.choices[0].message;
124
- if (responseMessage.content)
125
- logger.info("Received response: ".concat(responseMessage.content));
126
- else if (responseMessage.function_call)
127
- logger.info("Received response: call ".concat(responseMessage.function_call.name, " function"));
128
- else
129
- logger.info("Received response");
130
- if (response.usage)
131
- logger.info(JSON.stringify(response.usage));
132
- else
133
- logger.info(JSON.stringify("Usage data missing"));
134
- return [3 /*break*/, 7];
135
- case 3:
136
- error_1 = _a.sent();
137
- logger.info("Received error response, error type: ".concat(error_1.type));
138
- if (!(typeof error_1.status !== 'undefined' && error_1.status == 429)) return [3 /*break*/, 6];
139
- if (!(error_1.type == 'tokens' && typeof error_1.headers['x-ratelimit-reset-tokens'] === 'string')) return [3 /*break*/, 6];
140
- waitTime = parseInt(error_1.headers['x-ratelimit-reset-tokens']);
141
- remainingTokens = error_1.headers['x-ratelimit-remaining-tokens'];
142
- delayMs = 15000;
143
- logger.warn("Waiting to retry in ".concat(delayMs / 1000, "s, token reset in: ").concat(waitTime, "s, remaining tokens: ").concat(remainingTokens));
144
- return [4 /*yield*/, delay(delayMs)];
145
- case 4:
146
- _a.sent();
147
- return [4 /*yield*/, OpenAi.executeRequest(messageParamsWithHistory, logLevel, functions, model)];
148
- case 5: return [2 /*return*/, _a.sent()];
149
- case 6: throw error_1;
150
- case 7: return [2 /*return*/, response];
151
- }
152
- });
153
- });
154
- };
155
- OpenAi.callFunction = function (logLevel, functionCall, functions) {
156
- return __awaiter(this, void 0, void 0, function () {
157
- var logger, warning, message, f, warning, message, returnObject, _a, _b, error_2;
158
- return __generator(this, function (_c) {
159
- switch (_c.label) {
160
- case 0:
161
- logger = new util_1.Logger('OpenAi.callFunction', logLevel);
162
- if (!functions) {
163
- warning = "Assistant attempted to call a function when no functions were provided";
164
- logger.warn(warning);
165
- message = { role: 'user', content: warning };
166
- return [2 /*return*/, message];
167
- }
168
- functionCall.name = functionCall.name.split('.').pop();
169
- f = functions.find(function (f) { return f.definition.name === functionCall.name; });
170
- if (!f) {
171
- warning = "Assistant attempted to call nonexistent function: ".concat(functionCall.name);
172
- logger.warn(warning);
173
- message = { role: 'user', content: warning };
174
- return [2 /*return*/, message];
175
- }
176
- returnObject = null;
177
- _c.label = 1;
178
- case 1:
179
- _c.trys.push([1, 3, , 4]);
180
- logger.info("Assistant calling function: ".concat(f.definition.name, "(").concat(functionCall.arguments, ")"));
181
- _b = (_a = JSON).stringify;
182
- return [4 /*yield*/, f.call(JSON.parse(functionCall.arguments))];
183
- case 2:
184
- returnObject = _b.apply(_a, [_c.sent()]);
185
- logger.info("Assistant called function: ".concat(f.definition.name, "(").concat(functionCall.arguments, ") => ").concat(returnObject), 1000);
186
- return [3 /*break*/, 4];
187
- case 3:
188
- error_2 = _c.sent();
189
- logger.error(error_2.message);
190
- return [3 /*break*/, 4];
191
- case 4:
192
- if (!returnObject)
193
- return [2 /*return*/];
194
- return [2 /*return*/, {
195
- role: 'function',
196
- name: f.definition.name,
197
- content: returnObject,
198
- }];
199
- }
200
- });
201
- });
202
- };
203
- OpenAi.generateCode = function (messages, model, history, functions, messageModerators, includeSystemMessages, logLevel) {
204
- if (includeSystemMessages === void 0) { includeSystemMessages = true; }
205
- if (logLevel === void 0) { logLevel = 'info'; }
206
- return __awaiter(this, void 0, void 0, function () {
207
- var systemMessages, resolvedHistory, code;
208
- return __generator(this, function (_a) {
209
- switch (_a.label) {
210
- case 0:
211
- systemMessages = [
212
- { role: 'system', content: 'Return only the code and exclude example usage, markdown, explanations, comments and notes.' },
213
- { role: 'system', content: "Write code in typescript." },
214
- { role: 'system', content: "Declare explicit types for all function parameters." },
215
- { role: 'system', content: 'Export all functions and objects generated.' },
216
- { role: 'system', content: 'Do not omit function implementations.' },
217
- ];
218
- resolvedHistory = history ?
219
- includeSystemMessages ?
220
- history.push(systemMessages)
221
- :
222
- history
223
- :
224
- includeSystemMessages ?
225
- new MessageHistory_1.MessageHistory().push(systemMessages)
226
- :
227
- undefined;
228
- return [4 /*yield*/, this.generateResponse(messages, model, resolvedHistory, functions, messageModerators, logLevel)];
229
- case 1:
230
- code = _a.sent();
231
- return [2 /*return*/, this.parseCodeFromMarkdown(code)];
232
- }
233
- });
234
- });
235
- };
236
- OpenAi.updateCode = function (code, description, model, history, functions, messageModerators, includeSystemMessages, logLevel) {
237
- if (includeSystemMessages === void 0) { includeSystemMessages = true; }
238
- if (logLevel === void 0) { logLevel = 'info'; }
239
- return __awaiter(this, void 0, void 0, function () {
240
- return __generator(this, function (_a) {
241
- switch (_a.label) {
242
- case 0: return [4 /*yield*/, this.generateCode([this.updateCodeDescription(code, description)], model, history, functions, messageModerators, includeSystemMessages, logLevel)];
243
- case 1: return [2 /*return*/, _a.sent()];
244
- }
245
- });
246
- });
247
- };
248
- OpenAi.updateCodeDescription = function (code, description) {
249
- return "Update this code:\n\n".concat(code, "\n\n").concat(description);
250
- };
251
- OpenAi.parseCodeFromMarkdown = function (code) {
252
- if (!code.match(/```([\s\S]+?)```/g))
253
- return code;
254
- var filteredLines = [];
255
- var inCodeBlock = false;
256
- for (var _i = 0, _a = code.split('\n'); _i < _a.length; _i++) {
257
- var line = _a[_i];
258
- if (line.startsWith('```')) {
259
- inCodeBlock = !inCodeBlock;
260
- if (!inCodeBlock)
261
- filteredLines.push('');
262
- continue;
191
+ });
192
+ });
193
+ };
194
+ OpenAi.moderateHistory = function (history, messageModerators) {
195
+ for (var _i = 0, messageModerators_1 = messageModerators; _i < messageModerators_1.length; _i++) {
196
+ var messageModerator = messageModerators_1[_i];
197
+ history.setMessages(messageModerator.observe(history.getMessages()));
198
+ }
199
+ return history;
200
+ };
201
+ OpenAi.executeRequest = function (messageParamsWithHistory, logLevel, functions, model) {
202
+ return __awaiter(this, void 0, void 0, function () {
203
+ var logger, openaiApi, response, latestMessage, responseMessage, error_1, waitTime, remainingTokens, delayMs;
204
+ return __generator(this, function (_a) {
205
+ switch (_a.label) {
206
+ case 0:
207
+ logger = new util_1.Logger('OpenAi.executeRequest', logLevel);
208
+ openaiApi = new openai_1.OpenAI();
209
+ _a.label = 1;
210
+ case 1:
211
+ _a.trys.push([1, 3, , 7]);
212
+ latestMessage = messageParamsWithHistory.getMessages()[messageParamsWithHistory.getMessages().length - 1];
213
+ if (latestMessage.content) {
214
+ logger.info('Sending request: '.concat(latestMessage.content));
215
+ } else if (latestMessage.role == 'function') {
216
+ logger.info('Sending request: returning output of '.concat(latestMessage.name, ' function'));
217
+ } else {
218
+ logger.info('Sending request');
219
+ }
220
+ logger.debug(
221
+ 'Sending messages: '.concat(JSON.stringify(messageParamsWithHistory.getMessages(), null, 2)),
222
+ true
223
+ );
224
+ return [
225
+ 4 /*yield*/,
226
+ openaiApi.chat.completions.create({
227
+ model: model ? model : exports.DEFAULT_MODEL,
228
+ temperature: 0,
229
+ messages: messageParamsWithHistory.getMessages(),
230
+ functions:
231
+ functions === null || functions === void 0
232
+ ? void 0
233
+ : functions.map(function (f) {
234
+ return f.definition;
235
+ }),
236
+ }),
237
+ ];
238
+ case 2:
239
+ response = _a.sent();
240
+ responseMessage = response.choices[0].message;
241
+ if (responseMessage.content) {
242
+ logger.info('Received response: '.concat(responseMessage.content));
243
+ } else if (responseMessage.function_call) {
244
+ logger.info('Received response: call '.concat(responseMessage.function_call.name, ' function'));
245
+ } else {
246
+ logger.info('Received response');
263
247
  }
264
- if (inCodeBlock)
265
- filteredLines.push(line);
248
+ if (response.usage) {
249
+ logger.info(JSON.stringify(response.usage));
250
+ } else {
251
+ logger.info(JSON.stringify('Usage data missing'));
252
+ }
253
+ return [3 /*break*/, 7];
254
+ case 3:
255
+ error_1 = _a.sent();
256
+ logger.info('Received error response, error type: '.concat(error_1.type));
257
+ if (!(typeof error_1.status !== 'undefined' && error_1.status == 429)) return [3 /*break*/, 6];
258
+ if (!(error_1.type == 'tokens' && typeof error_1.headers['x-ratelimit-reset-tokens'] === 'string'))
259
+ return [3 /*break*/, 6];
260
+ waitTime = parseInt(error_1.headers['x-ratelimit-reset-tokens']);
261
+ remainingTokens = error_1.headers['x-ratelimit-remaining-tokens'];
262
+ delayMs = 15000;
263
+ logger.warn(
264
+ 'Waiting to retry in '
265
+ .concat(delayMs / 1000, 's, token reset in: ')
266
+ .concat(waitTime, 's, remaining tokens: ')
267
+ .concat(remainingTokens)
268
+ );
269
+ return [4 /*yield*/, delay(delayMs)];
270
+ case 4:
271
+ _a.sent();
272
+ return [4 /*yield*/, OpenAi.executeRequest(messageParamsWithHistory, logLevel, functions, model)];
273
+ case 5:
274
+ return [2 /*return*/, _a.sent()];
275
+ case 6:
276
+ throw error_1;
277
+ case 7:
278
+ return [2 /*return*/, response];
266
279
  }
267
- // remove the last '' that will become a \n
268
- // we only want spaces between code blocks
269
- filteredLines.pop();
270
- return filteredLines.join('\n');
271
- };
272
- OpenAi.generateList = function (messages, model, history, functions, messageModerators, includeSystemMessages, logLevel) {
273
- if (includeSystemMessages === void 0) { includeSystemMessages = true; }
274
- if (logLevel === void 0) { logLevel = 'info'; }
275
- return __awaiter(this, void 0, void 0, function () {
276
- var systemMessages, resolvedHistory, list;
277
- return __generator(this, function (_a) {
278
- switch (_a.label) {
279
- case 0:
280
- systemMessages = [
281
- { role: 'system', content: 'Return only the list and exclude example usage, markdown and all explanations, comments and notes.' },
282
- { role: 'system', content: 'Separate each item in the list by a ;' },
283
- ];
284
- resolvedHistory = history ?
285
- includeSystemMessages ?
286
- history.push(systemMessages)
287
- :
288
- history
289
- :
290
- includeSystemMessages ?
291
- new MessageHistory_1.MessageHistory().push(systemMessages)
292
- :
293
- undefined;
294
- return [4 /*yield*/, this.generateResponse(messages, model, resolvedHistory, functions, messageModerators, logLevel)];
295
- case 1:
296
- list = _a.sent();
297
- return [2 /*return*/, list.split(';').map(function (item) { return item.trim(); })];
298
- }
280
+ });
281
+ });
282
+ };
283
+ OpenAi.callFunction = function (logLevel, functionCall, functions) {
284
+ return __awaiter(this, void 0, void 0, function () {
285
+ var logger, warning, message, f, warning, message, returnObject, _a, _b, error_2;
286
+ return __generator(this, function (_c) {
287
+ switch (_c.label) {
288
+ case 0:
289
+ logger = new util_1.Logger('OpenAi.callFunction', logLevel);
290
+ if (!functions) {
291
+ warning = 'Assistant attempted to call a function when no functions were provided';
292
+ logger.warn(warning);
293
+ message = { role: 'user', content: warning };
294
+ return [2 /*return*/, message];
295
+ }
296
+ functionCall.name = functionCall.name.split('.').pop();
297
+ f = functions.find(function (f) {
298
+ return f.definition.name === functionCall.name;
299
299
  });
300
- });
301
- };
302
- return OpenAi;
303
- }());
300
+ if (!f) {
301
+ warning = 'Assistant attempted to call nonexistent function: '.concat(functionCall.name);
302
+ logger.warn(warning);
303
+ message = { role: 'user', content: warning };
304
+ return [2 /*return*/, message];
305
+ }
306
+ returnObject = null;
307
+ _c.label = 1;
308
+ case 1:
309
+ _c.trys.push([1, 3, , 4]);
310
+ logger.info(
311
+ 'Assistant calling function: '.concat(f.definition.name, '(').concat(functionCall.arguments, ')')
312
+ );
313
+ _b = (_a = JSON).stringify;
314
+ return [4 /*yield*/, f.call(JSON.parse(functionCall.arguments))];
315
+ case 2:
316
+ returnObject = _b.apply(_a, [_c.sent()]);
317
+ logger.info(
318
+ 'Assistant called function: '
319
+ .concat(f.definition.name, '(')
320
+ .concat(functionCall.arguments, ') => ')
321
+ .concat(returnObject),
322
+ 1000
323
+ );
324
+ return [3 /*break*/, 4];
325
+ case 3:
326
+ error_2 = _c.sent();
327
+ logger.error(error_2.message);
328
+ return [3 /*break*/, 4];
329
+ case 4:
330
+ if (!returnObject) {
331
+ return [2 /*return*/];
332
+ }
333
+ return [
334
+ 2 /*return*/,
335
+ {
336
+ role: 'function',
337
+ name: f.definition.name,
338
+ content: returnObject,
339
+ },
340
+ ];
341
+ }
342
+ });
343
+ });
344
+ };
345
+ OpenAi.generateCode = function (
346
+ messages,
347
+ model,
348
+ history,
349
+ functions,
350
+ messageModerators,
351
+ includeSystemMessages,
352
+ logLevel
353
+ ) {
354
+ if (includeSystemMessages === void 0) {
355
+ includeSystemMessages = true;
356
+ }
357
+ if (logLevel === void 0) {
358
+ logLevel = 'info';
359
+ }
360
+ return __awaiter(this, void 0, void 0, function () {
361
+ var systemMessages, resolvedHistory, code;
362
+ return __generator(this, function (_a) {
363
+ switch (_a.label) {
364
+ case 0:
365
+ systemMessages = [
366
+ {
367
+ role: 'system',
368
+ content: 'Return only the code and exclude example usage, markdown, explanations, comments and notes.',
369
+ },
370
+ { role: 'system', content: 'Write code in typescript.' },
371
+ { role: 'system', content: 'Declare explicit types for all function parameters.' },
372
+ { role: 'system', content: 'Export all functions and objects generated.' },
373
+ { role: 'system', content: 'Do not omit function implementations.' },
374
+ ];
375
+ resolvedHistory = history
376
+ ? includeSystemMessages
377
+ ? history.push(systemMessages)
378
+ : history
379
+ : includeSystemMessages
380
+ ? new MessageHistory_1.MessageHistory().push(systemMessages)
381
+ : undefined;
382
+ return [
383
+ 4 /*yield*/,
384
+ this.generateResponse(messages, model, resolvedHistory, functions, messageModerators, logLevel),
385
+ ];
386
+ case 1:
387
+ code = _a.sent();
388
+ return [2 /*return*/, this.parseCodeFromMarkdown(code)];
389
+ }
390
+ });
391
+ });
392
+ };
393
+ OpenAi.updateCode = function (
394
+ code,
395
+ description,
396
+ model,
397
+ history,
398
+ functions,
399
+ messageModerators,
400
+ includeSystemMessages,
401
+ logLevel
402
+ ) {
403
+ if (includeSystemMessages === void 0) {
404
+ includeSystemMessages = true;
405
+ }
406
+ if (logLevel === void 0) {
407
+ logLevel = 'info';
408
+ }
409
+ return __awaiter(this, void 0, void 0, function () {
410
+ return __generator(this, function (_a) {
411
+ switch (_a.label) {
412
+ case 0:
413
+ return [
414
+ 4 /*yield*/,
415
+ this.generateCode(
416
+ [this.updateCodeDescription(code, description)],
417
+ model,
418
+ history,
419
+ functions,
420
+ messageModerators,
421
+ includeSystemMessages,
422
+ logLevel
423
+ ),
424
+ ];
425
+ case 1:
426
+ return [2 /*return*/, _a.sent()];
427
+ }
428
+ });
429
+ });
430
+ };
431
+ OpenAi.updateCodeDescription = function (code, description) {
432
+ return 'Update this code:\n\n'.concat(code, '\n\n').concat(description);
433
+ };
434
+ OpenAi.parseCodeFromMarkdown = function (code) {
435
+ if (!code.match(/```([\s\S]+?)```/g)) {
436
+ return code;
437
+ }
438
+ var filteredLines = [];
439
+ var inCodeBlock = false;
440
+ for (var _i = 0, _a = code.split('\n'); _i < _a.length; _i++) {
441
+ var line = _a[_i];
442
+ if (line.startsWith('```')) {
443
+ inCodeBlock = !inCodeBlock;
444
+ if (!inCodeBlock) {
445
+ filteredLines.push('');
446
+ }
447
+ continue;
448
+ }
449
+ if (inCodeBlock) {
450
+ filteredLines.push(line);
451
+ }
452
+ }
453
+ // remove the last '' that will become a \n
454
+ // we only want spaces between code blocks
455
+ filteredLines.pop();
456
+ return filteredLines.join('\n');
457
+ };
458
+ OpenAi.generateList = function (
459
+ messages,
460
+ model,
461
+ history,
462
+ functions,
463
+ messageModerators,
464
+ includeSystemMessages,
465
+ logLevel
466
+ ) {
467
+ if (includeSystemMessages === void 0) {
468
+ includeSystemMessages = true;
469
+ }
470
+ if (logLevel === void 0) {
471
+ logLevel = 'info';
472
+ }
473
+ return __awaiter(this, void 0, void 0, function () {
474
+ var systemMessages, resolvedHistory, list;
475
+ return __generator(this, function (_a) {
476
+ switch (_a.label) {
477
+ case 0:
478
+ systemMessages = [
479
+ {
480
+ role: 'system',
481
+ content:
482
+ 'Return only the list and exclude example usage, markdown and all explanations, comments and notes.',
483
+ },
484
+ { role: 'system', content: 'Separate each item in the list by a ;' },
485
+ ];
486
+ resolvedHistory = history
487
+ ? includeSystemMessages
488
+ ? history.push(systemMessages)
489
+ : history
490
+ : includeSystemMessages
491
+ ? new MessageHistory_1.MessageHistory().push(systemMessages)
492
+ : undefined;
493
+ return [
494
+ 4 /*yield*/,
495
+ this.generateResponse(messages, model, resolvedHistory, functions, messageModerators, logLevel),
496
+ ];
497
+ case 1:
498
+ list = _a.sent();
499
+ return [
500
+ 2 /*return*/,
501
+ list.split(';').map(function (item) {
502
+ return item.trim();
503
+ }),
504
+ ];
505
+ }
506
+ });
507
+ });
508
+ };
509
+ return OpenAi;
510
+ })();
304
511
  exports.OpenAi = OpenAi;
305
- //# sourceMappingURL=OpenAi.js.map
512
+ //# sourceMappingURL=OpenAi.js.map