medpromptjs 0.4.3 → 0.5.0

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.
@@ -5,179 +5,13 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var prompts = require('@langchain/core/prompts');
6
6
  var runnables = require('@langchain/core/runnables');
7
7
  var messages = require('@langchain/core/messages');
8
+ var output_parsers = require('@langchain/core/output_parsers');
8
9
  var agents = require('langchain/agents');
9
10
  var tools = require('langchain/tools');
10
11
  var textsplitters = require('@langchain/textsplitters');
11
12
  var tslog = require('tslog');
12
-
13
- function asyncGeneratorStep(n, t, e, r, o, a, c) {
14
- try {
15
- var i = n[a](c),
16
- u = i.value;
17
- } catch (n) {
18
- return void e(n);
19
- }
20
- i.done ? t(u) : Promise.resolve(u).then(r, o);
21
- }
22
- function _asyncToGenerator(n) {
23
- return function () {
24
- var t = this,
25
- e = arguments;
26
- return new Promise(function (r, o) {
27
- var a = n.apply(t, e);
28
- function _next(n) {
29
- asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
30
- }
31
- function _throw(n) {
32
- asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
33
- }
34
- _next(void 0);
35
- });
36
- };
37
- }
38
- function _defineProperties(e, r) {
39
- for (var t = 0; t < r.length; t++) {
40
- var o = r[t];
41
- o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
42
- }
43
- }
44
- function _createClass(e, r, t) {
45
- return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
46
- writable: !1
47
- }), e;
48
- }
49
- function _inheritsLoose(t, o) {
50
- t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
51
- }
52
- function _regenerator() {
53
- /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
54
- var e,
55
- t,
56
- r = "function" == typeof Symbol ? Symbol : {},
57
- n = r.iterator || "@@iterator",
58
- o = r.toStringTag || "@@toStringTag";
59
- function i(r, n, o, i) {
60
- var c = n && n.prototype instanceof Generator ? n : Generator,
61
- u = Object.create(c.prototype);
62
- return _regeneratorDefine(u, "_invoke", function (r, n, o) {
63
- var i,
64
- c,
65
- u,
66
- f = 0,
67
- p = o || [],
68
- y = !1,
69
- G = {
70
- p: 0,
71
- n: 0,
72
- v: e,
73
- a: d,
74
- f: d.bind(e, 4),
75
- d: function (t, r) {
76
- return i = t, c = 0, u = e, G.n = r, a;
77
- }
78
- };
79
- function d(r, n) {
80
- for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
81
- var o,
82
- i = p[t],
83
- d = G.p,
84
- l = i[2];
85
- r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
86
- }
87
- if (o || r > 1) return a;
88
- throw y = !0, n;
89
- }
90
- return function (o, p, l) {
91
- if (f > 1) throw TypeError("Generator is already running");
92
- for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
93
- i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
94
- try {
95
- if (f = 2, i) {
96
- if (c || (o = "next"), t = i[o]) {
97
- if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
98
- if (!t.done) return t;
99
- u = t.value, c < 2 && (c = 0);
100
- } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
101
- i = e;
102
- } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
103
- } catch (t) {
104
- i = e, c = 1, u = t;
105
- } finally {
106
- f = 1;
107
- }
108
- }
109
- return {
110
- value: t,
111
- done: y
112
- };
113
- };
114
- }(r, o, i), !0), u;
115
- }
116
- var a = {};
117
- function Generator() {}
118
- function GeneratorFunction() {}
119
- function GeneratorFunctionPrototype() {}
120
- t = Object.getPrototypeOf;
121
- var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
122
- return this;
123
- }), t),
124
- u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
125
- function f(e) {
126
- return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
127
- }
128
- return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
129
- return this;
130
- }), _regeneratorDefine(u, "toString", function () {
131
- return "[object Generator]";
132
- }), (_regenerator = function () {
133
- return {
134
- w: i,
135
- m: f
136
- };
137
- })();
138
- }
139
- function _regeneratorDefine(e, r, n, t) {
140
- var i = Object.defineProperty;
141
- try {
142
- i({}, "", {});
143
- } catch (e) {
144
- i = 0;
145
- }
146
- _regeneratorDefine = function (e, r, n, t) {
147
- if (r) i ? i(e, r, {
148
- value: n,
149
- enumerable: !t,
150
- configurable: !t,
151
- writable: !t
152
- }) : e[r] = n;else {
153
- function o(r, n) {
154
- _regeneratorDefine(e, r, function (e) {
155
- return this._invoke(r, n, e);
156
- });
157
- }
158
- o("next", 0), o("throw", 1), o("return", 2);
159
- }
160
- }, _regeneratorDefine(e, r, n, t);
161
- }
162
- function _setPrototypeOf(t, e) {
163
- return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
164
- return t.__proto__ = e, t;
165
- }, _setPrototypeOf(t, e);
166
- }
167
- function _toPrimitive(t, r) {
168
- if ("object" != typeof t || !t) return t;
169
- var e = t[Symbol.toPrimitive];
170
- if (void 0 !== e) {
171
- var i = e.call(t, r || "default");
172
- if ("object" != typeof i) return i;
173
- throw new TypeError("@@toPrimitive must return a primitive value.");
174
- }
175
- return ("string" === r ? String : Number)(t);
176
- }
177
- function _toPropertyKey(t) {
178
- var i = _toPrimitive(t, "string");
179
- return "symbol" == typeof i ? i : i + "";
180
- }
13
+ var llms = require('@langchain/core/language_models/llms');
14
+ var embeddings = require('@langchain/core/embeddings');
181
15
 
182
16
  /**
183
17
  * Copyright 2024 Bell Eapen
@@ -194,16 +28,36 @@ function _toPropertyKey(t) {
194
28
  * See the License for the specific language governing permissions and
195
29
  * limitations under the License.
196
30
  */
197
- var mydi = function mydi(c, m, b) {
31
+ const mydi = (c, m, b) => {
198
32
  try {
199
33
  return c.resolve(m + '_' + b);
200
- } catch (e) {
34
+ } catch (e) {}
35
+ try {
36
+ return c.resolve(m + '-' + b);
37
+ } catch (e) {}
38
+ try {
201
39
  return c.resolve(b);
202
- }
40
+ } catch (e) {}
41
+ return null;
203
42
  };
204
43
 
205
- var BaseChain = /*#__PURE__*/function () {
206
- function BaseChain(container) {
44
+ /**
45
+ * Copyright 2024 Bell Eapen
46
+ *
47
+ * Licensed under the Apache License, Version 2.0 (the "License");
48
+ * you may not use this file except in compliance with the License.
49
+ * You may obtain a copy of the License at
50
+ *
51
+ * https://www.apache.org/licenses/LICENSE-2.0
52
+ *
53
+ * Unless required by applicable law or agreed to in writing, software
54
+ * distributed under the License is distributed on an "AS IS" BASIS,
55
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
56
+ * See the License for the specific language governing permissions and
57
+ * limitations under the License.
58
+ */
59
+ class BaseChain {
60
+ constructor(container) {
207
61
  this.container = void 0;
208
62
  this._name = '';
209
63
  this._description = '';
@@ -213,283 +67,165 @@ var BaseChain = /*#__PURE__*/function () {
213
67
  this.chat_model = void 0;
214
68
  this.runnable = void 0;
215
69
  this.container = container;
216
- this.llm = this.resolve('main-llm');
217
- this.chat_model = false;
218
- this.initialize();
70
+ this._name = this.camelize(this.constructor.name);
71
+ this._description = this.snake_case(this.constructor.name);
72
+ this.llm = this.resolve('llm');
73
+ this._template = this.resolve('template');
74
+ this.chat_model = this.resolve('chat-model', false);
75
+ if (this.chat_model) {
76
+ this.prompt = prompts.ChatPromptTemplate.fromTemplate(this._template);
77
+ } else {
78
+ this.prompt = prompts.PromptTemplate.fromTemplate(this._template);
79
+ }
219
80
  }
220
81
  // Getters and setters
221
- var _proto = BaseChain.prototype;
222
- _proto.initialize = function initialize() {
223
- if (this._name === '') {
224
- this._name = this.camelize(this.constructor.name);
225
- }
226
- if (this._description === '') {
227
- this._description = this.snake_case(this.constructor.name);
228
- }
229
- if (this._template === '') {
230
- this._template = "{{input}}";
231
- }
232
- this.prompt = this.prompt || prompts.PromptTemplate.fromTemplate(this._template);
82
+ get name() {
83
+ return this._name;
84
+ }
85
+ set name(value) {
86
+ this._name = value === '' ? this.camelize(this.constructor.name) : value;
87
+ }
88
+ get description() {
89
+ return this._description;
90
+ }
91
+ set description(value) {
92
+ this._description = value === '' ? this.snake_case(this.constructor.name) : value;
93
+ }
94
+ get template() {
95
+ return this._template;
96
+ }
97
+ set template(value) {
98
+ this._template = value;
233
99
  if (this.chat_model) {
234
100
  this.prompt = prompts.ChatPromptTemplate.fromTemplate(this._template);
235
101
  } else {
236
102
  this.prompt = prompts.PromptTemplate.fromTemplate(this._template);
237
103
  }
238
- };
239
- _proto.resolve = function resolve(name) {
240
- return mydi(this.container, this._name, name);
241
- };
242
- _proto.camelize = function camelize(str) {
104
+ }
105
+ resolve(name, defaultValue = null) {
106
+ return mydi(this.container, this.camelize(this.constructor.name), name) || defaultValue;
107
+ }
108
+ camelize(str) {
243
109
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
244
110
  return index === 0 ? word.toLowerCase() : word.toUpperCase();
245
111
  }).replace(/\s+/g, '');
246
- };
247
- _proto.snake_case = function snake_case(str) {
112
+ }
113
+ snake_case(str) {
248
114
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
249
115
  return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();
250
116
  }).replace(/\s+/g, '');
251
117
  }
252
118
  // https://js.langchain.com/v0.1/docs/expression_language/how_to/routing/
253
119
  //! Override this method
254
- ;
255
- _proto.chain =
256
- /*#__PURE__*/
257
- function () {
258
- var _chain = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(input) {
259
- var response, aiMessage;
260
- return _regenerator().w(function (_context) {
261
- while (1) switch (_context.n) {
262
- case 0:
263
- this.runnable = runnables.RunnableSequence.from([new runnables.RunnablePassthrough(), this.prompt, this.llm]);
264
- if (!this.chat_model) {
265
- _context.n = 2;
266
- break;
267
- }
268
- _context.n = 1;
269
- return this.runnable.invoke(input);
270
- case 1:
271
- response = _context.v;
272
- aiMessage = new messages.AIMessage(response);
273
- return _context.a(2, aiMessage.content);
274
- case 2:
275
- _context.n = 3;
276
- return this.runnable.invoke(input);
277
- case 3:
278
- return _context.a(2, _context.v);
279
- }
280
- }, _callee, this);
281
- }));
282
- function chain(_x) {
283
- return _chain.apply(this, arguments);
284
- }
285
- return chain;
286
- }();
287
- return _createClass(BaseChain, [{
288
- key: "name",
289
- get: function get() {
290
- return this._name;
291
- },
292
- set: function set(value) {
293
- this._name = value === '' ? this.camelize(this.constructor.name) : value;
294
- }
295
- }, {
296
- key: "description",
297
- get: function get() {
298
- return this._description;
299
- },
300
- set: function set(value) {
301
- this._description = value === '' ? this.snake_case(this.constructor.name) : value;
302
- }
303
- }, {
304
- key: "template",
305
- get: function get() {
306
- return this._template;
307
- },
308
- set: function set(value) {
309
- this._template = value;
310
- try {
311
- this.chat_model = this.resolve('chat_model');
312
- } catch (e) {}
313
- if (this.chat_model) {
314
- this.prompt = prompts.ChatPromptTemplate.fromTemplate(this._template);
315
- } else {
316
- this.prompt = prompts.PromptTemplate.fromTemplate(this._template);
317
- }
120
+ async chain(input) {
121
+ const outputParser = new output_parsers.StringOutputParser();
122
+ this.runnable = runnables.RunnableSequence.from([{
123
+ input: new runnables.RunnablePassthrough()
124
+ // context: async () => loadContextFromStore(),
125
+ }, this.prompt, this.llm, outputParser]);
126
+ if (this.chat_model) {
127
+ const response = await this.runnable.invoke(input);
128
+ const aiMessage = new messages.AIMessage(response);
129
+ return aiMessage.content;
318
130
  }
319
- }]);
320
- }();
131
+ return await this.runnable.invoke(input);
132
+ }
133
+ async invoke(input) {
134
+ return this.chain(input);
135
+ }
136
+ }
321
137
 
322
- var BaseAgent = /*#__PURE__*/function () {
323
- function BaseAgent(container) {
324
- this.container = void 0;
325
- this._name = '';
326
- this._description = '';
327
- this._template = "\n ## Question: {question}\n ## Answer: {answer}\n Given the above question and answer, generate a chain of thought explanation for the answer.\n First, start with the model generated chain of thought explanation.\n End the chain of though explanation with:\n Therefore, the answer is {answer}.\n ";
138
+ /**
139
+ * Copyright 2024 Bell Eapen
140
+ *
141
+ * Licensed under the Apache License, Version 2.0 (the "License");
142
+ * you may not use this file except in compliance with the License.
143
+ * You may obtain a copy of the License at
144
+ *
145
+ * https://www.apache.org/licenses/LICENSE-2.0
146
+ *
147
+ * Unless required by applicable law or agreed to in writing, software
148
+ * distributed under the License is distributed on an "AS IS" BASIS,
149
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
150
+ * See the License for the specific language governing permissions and
151
+ * limitations under the License.
152
+ */
153
+ class BaseAgent extends BaseChain {
154
+ constructor(...args) {
155
+ super(...args);
328
156
  this._tools = [];
329
- this.prompt = void 0;
330
- this.llm = void 0;
331
- this.chat_model = void 0;
332
- this.runnable = void 0;
333
- this.container = container;
334
- this.llm = this.resolve('main-llm');
335
- this.chat_model = false;
336
- this.initialize();
337
157
  }
338
- // Getters and setters
339
- var _proto = BaseAgent.prototype;
340
- _proto.initialize = function initialize() {
341
- if (this._name === '') {
342
- this._name = this.camelize(this.constructor.name);
343
- }
344
- if (this._description === '') {
345
- this._description = this.snake_case(this.constructor.name);
346
- }
347
- if (this._template === '') {
348
- this._template = "{{input}}";
349
- }
350
- this.prompt = this.prompt || prompts.PromptTemplate.fromTemplate(this._template);
351
- if (this.chat_model) {
352
- this.prompt = prompts.ChatPromptTemplate.fromTemplate(this._template);
353
- } else {
354
- this.prompt = prompts.PromptTemplate.fromTemplate(this._template);
355
- }
356
- };
357
- _proto.resolve = function resolve(name) {
358
- return mydi(this.container, this._name, name);
359
- };
360
- _proto.camelize = function camelize(str) {
361
- return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
362
- return index === 0 ? word.toLowerCase() : word.toUpperCase();
363
- }).replace(/\s+/g, '');
364
- };
365
- _proto.snake_case = function snake_case(str) {
366
- return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
367
- return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();
368
- }).replace(/\s+/g, '');
369
- };
370
- _proto.run = /*#__PURE__*/function () {
371
- var _run = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(input) {
372
- var agent, agentExecutor;
373
- return _regenerator().w(function (_context) {
374
- while (1) switch (_context.n) {
375
- case 0:
376
- _context.n = 1;
377
- return agents.createStructuredChatAgent({
378
- llm: this.llm,
379
- tools: this._tools,
380
- prompt: this.prompt
381
- });
382
- case 1:
383
- agent = _context.v;
384
- agentExecutor = new agents.AgentExecutor({
385
- agent: agent,
386
- tools: this.tools,
387
- // verbose: true,
388
- handleParsingErrors: 'Please try again, paying close attention to the final answer'
389
- });
390
- _context.n = 2;
391
- return agentExecutor.invoke(input);
392
- case 2:
393
- return _context.a(2, _context.v);
394
- }
395
- }, _callee, this);
396
- }));
397
- function run(_x) {
398
- return _run.apply(this, arguments);
399
- }
400
- return run;
401
- }();
402
- return _createClass(BaseAgent, [{
403
- key: "name",
404
- get: function get() {
405
- return this._name;
406
- },
407
- set: function set(value) {
408
- this._name = value === '' ? this.camelize(this.constructor.name) : value;
409
- }
410
- }, {
411
- key: "description",
412
- get: function get() {
413
- return this._description;
414
- },
415
- set: function set(value) {
416
- this._description = value === '' ? this.snake_case(this.constructor.name) : value;
417
- }
418
- }, {
419
- key: "template",
420
- get: function get() {
421
- return this._template;
422
- },
423
- set: function set(value) {
424
- this._template = value;
425
- try {
426
- this.chat_model = this.resolve('chat_model');
427
- } catch (e) {}
428
- if (this.chat_model) {
429
- this.prompt = prompts.ChatPromptTemplate.fromTemplate(this._template);
430
- } else {
431
- this.prompt = prompts.PromptTemplate.fromTemplate(this._template);
432
- }
433
- }
434
- // Getters and setters for tools
435
- }, {
436
- key: "tools",
437
- get: function get() {
438
- return this._tools;
439
- },
440
- set: function set(value) {
441
- this._tools = value;
442
- }
443
- }]);
444
- }();
158
+ get tools() {
159
+ return this._tools;
160
+ }
161
+ set tools(value) {
162
+ this._tools = value;
163
+ }
164
+ /**
165
+ * Run the agent using the provided input.
166
+ * This uses createStructuredChatAgent and AgentExecutor from langchain/agents.
167
+ */
168
+ async run(input) {
169
+ const agent = await agents.createStructuredChatAgent({
170
+ llm: this.llm,
171
+ tools: this._tools,
172
+ prompt: this.prompt
173
+ });
174
+ const agentExecutor = new agents.AgentExecutor({
175
+ agent: agent,
176
+ tools: this.tools,
177
+ // verbose: true,
178
+ handleParsingErrors: 'Please try again, paying close attention to the final answer'
179
+ });
180
+ return await agentExecutor.invoke(input);
181
+ }
182
+ }
445
183
 
446
- var BaseTool = /*#__PURE__*/function (_DynamicStructuredToo) {
447
- function BaseTool(container, name, description, schema, func) {
448
- var _this;
449
- if (func === void 0) {
450
- func = null;
451
- }
452
- _this = _DynamicStructuredToo.call(this, {
184
+ /**
185
+ * Copyright 2024 Bell Eapen
186
+ *
187
+ * Licensed under the Apache License, Version 2.0 (the "License");
188
+ * you may not use this file except in compliance with the License.
189
+ * You may obtain a copy of the License at
190
+ *
191
+ * https://www.apache.org/licenses/LICENSE-2.0
192
+ *
193
+ * Unless required by applicable law or agreed to in writing, software
194
+ * distributed under the License is distributed on an "AS IS" BASIS,
195
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
196
+ * See the License for the specific language governing permissions and
197
+ * limitations under the License.
198
+ */
199
+ class BaseTool extends tools.DynamicStructuredTool {
200
+ constructor(container, name, description, schema, func = null) {
201
+ super({
453
202
  name: name,
454
203
  description: description,
455
204
  schema: schema,
456
205
  func: func
457
- }) || this;
206
+ });
458
207
  /** @hidden */
459
- _this.container = void 0;
460
- _this.name = void 0;
461
- _this.description = void 0;
462
- _this.schema = void 0;
463
- _this.func = /*#__PURE__*/function () {
464
- var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(args) {
465
- return _regenerator().w(function (_context) {
466
- while (1) switch (_context.n) {
467
- case 0:
468
- return _context.a(2, 'override this');
469
- }
470
- }, _callee);
471
- }));
472
- return function (_x) {
473
- return _ref.apply(this, arguments);
474
- };
475
- }();
476
- _this.container = container;
477
- _this.name = name === '' ? _this.camelize(_this.constructor.name) : name;
478
- _this.description = description === '' ? _this.snake_case(_this.constructor.name) : description;
479
- _this.schema = schema;
480
- return _this;
481
- }
482
- _inheritsLoose(BaseTool, _DynamicStructuredToo);
483
- var _proto = BaseTool.prototype;
484
- _proto.resolve = function resolve(name) {
208
+ this.container = void 0;
209
+ this.name = void 0;
210
+ this.description = void 0;
211
+ this.schema = void 0;
212
+ this.func = async args => {
213
+ return 'override this';
214
+ };
215
+ this.container = container;
216
+ this.name = name === '' ? this.camelize(this.constructor.name) : name;
217
+ this.description = description === '' ? this.snake_case(this.constructor.name) : description;
218
+ this.schema = schema;
219
+ }
220
+ resolve(name) {
485
221
  return mydi(this.container, this.name, name);
486
- };
487
- _proto.camelize = function camelize(str) {
222
+ }
223
+ camelize(str) {
488
224
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
489
225
  return index === 0 ? word.toLowerCase() : word.toUpperCase();
490
226
  }).replace(/\s+/g, '');
491
- };
492
- _proto.snake_case = function snake_case(str) {
227
+ }
228
+ snake_case(str) {
493
229
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
494
230
  return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();
495
231
  }).replace(/\s+/g, '');
@@ -498,225 +234,189 @@ var BaseTool = /*#__PURE__*/function (_DynamicStructuredToo) {
498
234
  * @param input - The input to process in batch.
499
235
  * @param config - The configuration for the batch.
500
236
  * @returns A promise resolving to an array of results.
501
- */;
502
- _proto._batchWithConfig =
503
- /*#__PURE__*/
504
- function () {
505
- var _batchWithConfig2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(input, config) {
506
- return _regenerator().w(function (_context2) {
507
- while (1) switch (_context2.n) {
508
- case 0:
509
- return _context2.a(2, _DynamicStructuredToo.prototype._batchWithConfig.call(this, input, config));
510
- }
511
- }, _callee2, this);
512
- }));
513
- function _batchWithConfig(_x2, _x3) {
514
- return _batchWithConfig2.apply(this, arguments);
515
- }
516
- return _batchWithConfig;
517
- }();
518
- return BaseTool;
519
- }(tools.DynamicStructuredTool);
237
+ */
238
+ async _batchWithConfig(input, config) {
239
+ // Call the parent implementation or provide your own
240
+ return super._batchWithConfig(input, config);
241
+ }
242
+ }
520
243
 
521
- var log = /*#__PURE__*/new tslog.Logger();
522
- var LLMLoop = /*#__PURE__*/function (_BaseChain) {
523
- function LLMLoop() {
524
- var _this;
525
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
526
- args[_key] = arguments[_key];
527
- }
528
- _this = _BaseChain.call.apply(_BaseChain, [this].concat(args)) || this;
244
+ const log = /*#__PURE__*/new tslog.Logger();
245
+ class LLMLoop extends BaseChain {
246
+ constructor(...args) {
247
+ super(...args);
529
248
  // Implement the LLM loop logic here
530
- _this.stringExpression = '';
531
- _this._mapQueryTemplate = "\n You are an assistant that can convert statements to a natural language query as in the example below.\n\n\n\n Statements: Visual foot exam in the last month. Visual foot exam showed active infection.\n query: Did the patient have a visual foot exam in the last month? Is there any evidence of active infection?\n Statements: {expression}\n query: ";
532
- _this._mapDocTemplate = "\n You will be given a document and few statements.\n\n Extract facts from the document that are relevant to the statements.\n\n Do not include any irrelevant information or context.\n\n\n\n Example:\n\n document: The patient is a 45-year-old male with a history of hypertension. He presented with chest pain and was diagnosed with myocardial infarction. He was treated with aspirin and beta-blockers.\n\n statements: diagnosis of myocardial infarction. currently on beta-blockers.\n\n facts: The patient was diagnosed with myocardial infarction and is currently on beta-blockers.\n\n document: {document} \n\n statements: {statements}\n\n facts: ";
533
- _this._reduceChainTemplate = "\n Say yes if the facts mentions all aspects of the query, else say no.\n\n\n Example:\n facts: Patient had a laproscopy 27 days back. The findings were normal. \n\n query: Did the patient have a laproscopy this month?\n\n answer: YES. The patient had a laproscopy 27 days back.\n\n facts: The patient is a diabetic and hypertensive. He is on metformin and amlodipine. \n\n query: Is the patient on heparin and metformin?\n\n answer: NO. The patient is on heparin but not on metformin.\n\n facts: A visual foot examination was performed 26 days ago to assess skin integrity, circulation, and structural abnormalities. The exam revealed normal skin condition, nail health, circulation, and absence of edema and deformities. However, there were signs of an active infection with erythema and swelling. \n\n query: Did the patient have a visual foot exam in the last month? Is there any evidence of active infection?\n\n answer: YES. The patient had a visual foot exam in the last month and there is evidence of active infection.\n\n facts: A visual foot examination was performed 126 days ago to assess skin integrity, circulation, and structural abnormalities. The exam revealed normal skin condition, nail health, circulation, and absence of edema and deformities. However, there were signs of an active infection with erythema and swelling. \n\n query: Did the patient have a visual foot exam in the last month? Is there any evidence of active infection?\n\n answer: NO. The patient did not have a visual foot exam in the last month but there is evidence of active infection.\n\n facts: {facts} \n\n query: {query}\n\n answer: ";
534
- return _this;
535
- }
536
- _inheritsLoose(LLMLoop, _BaseChain);
537
- var _proto = LLMLoop.prototype;
538
- _proto.checkAssertion = /*#__PURE__*/function () {
539
- var _checkAssertion = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(expression, context) {
540
- var _expression, _context, _content, _input, result;
541
- return _regenerator().w(function (_context2) {
542
- while (1) switch (_context2.n) {
543
- case 0:
544
- _expression = '';
545
- try {
546
- // Check if expression is a valid JSON string
547
- _expression = this.printValues(JSON.parse(expression));
548
- } catch (error) {
549
- _expression = expression; // If not, use the expression as is
550
- }
551
- log.info("Checking assertion with expression: " + _expression);
552
- // Initialize context and content
553
- _context = undefined;
554
- _content = '';
555
- try {
556
- _context = JSON.parse(context);
557
- } catch (error) {
558
- _context = context; // If not, use the context as is
559
- log.warn("Context is not a valid JSON string: " + context);
560
- log.warn("Using context as a string: " + _context);
561
- }
562
- try {
563
- // Check if context is a valid JSON string
564
- _context = JSON.parse(context);
565
- _context.forEach(function (element) {
566
- element.content.forEach(function (contentItem) {
567
- _content += atob(contentItem.attachment.data.value);
568
- });
569
- });
570
- } catch (error) {
571
- _content = context; // If not, use the context as is
572
- log.warn("Context is not a valid JSON : " + context);
573
- log.warn("Using context as a string: " + _content);
574
- }
575
- _content = this.findDatesAndConvertToTimeElapsed(_content.replace(/(\r\n|\n|\r)/gm, ' '));
576
- log.info("Checking assertion with context: " + _content);
577
- _input = {
578
- input: {
579
- expression: _expression,
580
- context: _content
581
- }
582
- };
583
- _context2.n = 1;
584
- return this.chain(_input);
585
- case 1:
586
- result = _context2.v;
587
- log.info("Assertion check result: " + result);
588
- return _context2.a(2, result);
589
- }
590
- }, _callee, this);
591
- }));
592
- function checkAssertion(_x, _x2) {
593
- return _checkAssertion.apply(this, arguments);
594
- }
595
- return checkAssertion;
596
- }();
597
- _proto.checkMention = /*#__PURE__*/function () {
598
- var _checkMention = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(expression, context) {
599
- return _regenerator().w(function (_context3) {
600
- while (1) switch (_context3.n) {
601
- case 0:
602
- if (!(expression && context)) {
603
- _context3.n = 1;
604
- break;
605
- }
606
- return _context3.a(2, true);
607
- case 1:
608
- return _context3.a(2, false);
609
- }
610
- }, _callee2);
611
- }));
612
- function checkMention(_x3, _x4) {
613
- return _checkMention.apply(this, arguments);
614
- }
615
- return checkMention;
616
- }();
617
- _proto.checkNegation = /*#__PURE__*/function () {
618
- var _checkNegation = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(expression, context) {
619
- return _regenerator().w(function (_context4) {
620
- while (1) switch (_context4.n) {
621
- case 0:
622
- if (!(expression && context)) {
623
- _context4.n = 1;
624
- break;
625
- }
626
- return _context4.a(2, true);
627
- case 1:
628
- return _context4.a(2, false);
629
- }
630
- }, _callee3);
631
- }));
632
- function checkNegation(_x5, _x6) {
633
- return _checkNegation.apply(this, arguments);
634
- }
635
- return checkNegation;
636
- }();
637
- _proto.findDatesAndConvertToTimeElapsed = function findDatesAndConvertToTimeElapsed(text) {
249
+ this.stringExpression = '';
250
+ this._mapQueryTemplate = `
251
+ You are an assistant that can convert statements to a natural language query as in the example below.\n
252
+
253
+
254
+ Statements: Visual foot exam in the last month. Visual foot exam showed active infection.
255
+ query: Did the patient have a visual foot exam in the last month? Is there any evidence of active infection?
256
+ Statements: {expression}
257
+ query: `;
258
+ this._mapDocTemplate = `
259
+ You will be given a document and few statements.\n
260
+ Extract facts from the document that are relevant to the statements.\n
261
+ Do not include any irrelevant information or context.\n
262
+
263
+
264
+ Example:\n
265
+ document: The patient is a 45-year-old male with a history of hypertension. He presented with chest pain and was diagnosed with myocardial infarction. He was treated with aspirin and beta-blockers.\n
266
+ statements: diagnosis of myocardial infarction. currently on beta-blockers.\n
267
+ facts: The patient was diagnosed with myocardial infarction and is currently on beta-blockers.\n
268
+ document: {document} \n
269
+ statements: {statements}\n
270
+ facts: `;
271
+ this._reduceChainTemplate = `
272
+ Say yes if the facts mentions all aspects of the query, else say no.\n
273
+
274
+ Example:
275
+ facts: Patient had a laproscopy 27 days back. The findings were normal. \n
276
+ query: Did the patient have a laproscopy this month?\n
277
+ answer: YES. The patient had a laproscopy 27 days back.\n
278
+ facts: The patient is a diabetic and hypertensive. He is on metformin and amlodipine. \n
279
+ query: Is the patient on heparin and metformin?\n
280
+ answer: NO. The patient is on heparin but not on metformin.\n
281
+ facts: A visual foot examination was performed 26 days ago to assess skin integrity, circulation, and structural abnormalities. The exam revealed normal skin condition, nail health, circulation, and absence of edema and deformities. However, there were signs of an active infection with erythema and swelling. \n
282
+ query: Did the patient have a visual foot exam in the last month? Is there any evidence of active infection?\n
283
+ answer: YES. The patient had a visual foot exam in the last month and there is evidence of active infection.\n
284
+ facts: A visual foot examination was performed 126 days ago to assess skin integrity, circulation, and structural abnormalities. The exam revealed normal skin condition, nail health, circulation, and absence of edema and deformities. However, there were signs of an active infection with erythema and swelling. \n
285
+ query: Did the patient have a visual foot exam in the last month? Is there any evidence of active infection?\n
286
+ answer: NO. The patient did not have a visual foot exam in the last month but there is evidence of active infection.\n
287
+ facts: {facts} \n
288
+ query: {query}\n
289
+ answer: `;
290
+ }
291
+ // Add getters and setters for the templates if needed
292
+ get mapQueryTemplate() {
293
+ return this._mapQueryTemplate;
294
+ }
295
+ set mapQueryTemplate(template) {
296
+ this._mapQueryTemplate = template;
297
+ }
298
+ get mapDocTemplate() {
299
+ return this._mapDocTemplate;
300
+ }
301
+ set mapDocTemplate(template) {
302
+ this._mapDocTemplate = template;
303
+ }
304
+ get reduceChainTemplate() {
305
+ return this._reduceChainTemplate;
306
+ }
307
+ set reduceChainTemplate(template) {
308
+ this._reduceChainTemplate = template;
309
+ }
310
+ async checkAssertion(expression, context) {
311
+ let _expression = '';
312
+ try {
313
+ // Check if expression is a valid JSON string
314
+ _expression = this.printValues(JSON.parse(expression));
315
+ } catch (error) {
316
+ _expression = expression; // If not, use the expression as is
317
+ }
318
+ log.info(`Checking assertion with expression: ${_expression}`);
319
+ // Initialize context and content
320
+ let _context = undefined;
321
+ let _content = '';
322
+ try {
323
+ _context = JSON.parse(context);
324
+ } catch (error) {
325
+ _context = context; // If not, use the context as is
326
+ log.warn(`Context is not a valid JSON string: ${context}`);
327
+ log.warn(`Using context as a string: ${_context}`);
328
+ }
329
+ try {
330
+ // Check if context is a valid JSON string
331
+ _context = JSON.parse(context);
332
+ _context.forEach(element => {
333
+ element.content.forEach(contentItem => {
334
+ _content += atob(contentItem.attachment.data.value);
335
+ });
336
+ });
337
+ } catch (error) {
338
+ _content = context; // If not, use the context as is
339
+ log.warn(`Context is not a valid JSON : ${context}`);
340
+ log.warn(`Using context as a string: ${_content}`);
341
+ }
342
+ _content = this.findDatesAndConvertToTimeElapsed(_content.replace(/(\r\n|\n|\r)/gm, ' '));
343
+ log.info(`Checking assertion with context: ${_content}`);
344
+ const _input = {
345
+ input: {
346
+ expression: _expression,
347
+ context: _content
348
+ }
349
+ };
350
+ const result = await this.chain(_input);
351
+ log.info(`Assertion check result: ${result}`);
352
+ return result;
353
+ }
354
+ async checkMention(expression, context) {
355
+ if (expression && context) return true; // Placeholder for assertion check logic
356
+ return false;
357
+ }
358
+ async checkNegation(expression, context) {
359
+ if (expression && context) return true; // Placeholder for assertion check logic
360
+ return false;
361
+ }
362
+ findDatesAndConvertToTimeElapsed(text) {
638
363
  // Regular expression to match dates in format of 'mm/dd/yyyy' or 'mm-dd-yyyy'
639
- var dateRegex = /(\d{1,2}[-/]\d{1,2}[-/]\d{4})/g;
640
- var matches;
641
- var currentDate = new Date();
364
+ const dateRegex = /(\d{1,2}[-/]\d{1,2}[-/]\d{4})/g;
365
+ let matches;
366
+ let currentDate = new Date();
642
367
  while ((matches = dateRegex.exec(text)) !== null) {
643
- var date = new Date(matches[0]);
644
- var timeElapsed = (currentDate.getTime() - date.getTime()) / (1000 * 60 * 60 * 24);
368
+ let date = new Date(matches[0]);
369
+ let timeElapsed = (currentDate.getTime() - date.getTime()) / (1000 * 60 * 60 * 24);
645
370
  text = text.replace(matches[0], Math.floor(timeElapsed).toString() + ' days ago.');
646
371
  }
647
372
  return text;
648
- };
649
- _proto.camelToString = function camelToString(camelCase) {
373
+ }
374
+ camelToString(camelCase) {
650
375
  return camelCase.replace(/([A-Z])/g, ' $1').replace(/^./, function (str) {
651
376
  return str.toUpperCase();
652
377
  });
653
- };
654
- _proto.stringToBoolean = function stringToBoolean(str) {
655
- log.info("Converting string to boolean: " + str);
656
- var positiveKeywords = ['true', 'contains', 'confirms', 'yes', 'affirmative', 'matches', 'exists', 'present', 'absolutely', 'certainly', 'definitely', 'indeed', 'did have', 'showed', 'revealed'];
657
- var lowerStr = str.toLowerCase();
658
- return positiveKeywords.some(function (keyword) {
659
- return lowerStr.includes(keyword);
378
+ }
379
+ stringToBoolean(str) {
380
+ log.info(`Converting string to boolean: ${str}`);
381
+ const positiveKeywords = ['true', 'contains', 'confirms', 'yes', 'affirmative', 'matches', 'exists', 'present', 'absolutely', 'certainly', 'definitely', 'indeed', 'did have', 'showed', 'revealed'];
382
+ const lowerStr = str.toLowerCase();
383
+ return positiveKeywords.some(keyword => lowerStr.includes(keyword));
384
+ }
385
+ async textSplitter(text, chunkSize = 3900, chunkOverlap = 0) {
386
+ const textSplitter = new textsplitters.CharacterTextSplitter({
387
+ chunkSize: chunkSize,
388
+ chunkOverlap: chunkOverlap
660
389
  });
661
- };
662
- _proto.textSplitter = /*#__PURE__*/function () {
663
- var _textSplitter = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(text, chunkSize, chunkOverlap) {
664
- var textSplitter, texts;
665
- return _regenerator().w(function (_context5) {
666
- while (1) switch (_context5.n) {
667
- case 0:
668
- if (chunkSize === void 0) {
669
- chunkSize = 3900;
670
- }
671
- if (chunkOverlap === void 0) {
672
- chunkOverlap = 0;
673
- }
674
- textSplitter = new textsplitters.CharacterTextSplitter({
675
- chunkSize: chunkSize,
676
- chunkOverlap: chunkOverlap
677
- });
678
- _context5.n = 1;
679
- return textSplitter.splitText(text);
680
- case 1:
681
- texts = _context5.v;
682
- if (!(texts.length === 0)) {
683
- _context5.n = 2;
684
- break;
685
- }
686
- log.warn('No text chunks created. Please check the input text.');
687
- return _context5.a(2, []);
688
- case 2:
689
- if (texts.length > 100) {
690
- log.warn("Warning: More than 100 text chunks created (" + texts.length + "). This may affect performance.");
691
- }
692
- if (chunkSize < 1000) {
693
- log.warn("Warning: Chunk size is less than 1000 characters (" + chunkSize + "). This may lead to very small chunks.");
694
- }
695
- log.info("Text split into " + texts.length + " chunks with size " + chunkSize + " and overlap " + chunkOverlap);
696
- return _context5.a(2, texts);
697
- }
698
- }, _callee4);
699
- }));
700
- function textSplitter(_x7, _x8, _x9) {
701
- return _textSplitter.apply(this, arguments);
390
+ const texts = await textSplitter.splitText(text);
391
+ // Log the number of chunks created
392
+ if (texts.length === 0) {
393
+ log.warn('No text chunks created. Please check the input text.');
394
+ return [];
395
+ }
396
+ if (texts.length > 100) {
397
+ log.warn(`Warning: More than 100 text chunks created (${texts.length}). This may affect performance.`);
398
+ }
399
+ if (chunkSize < 1000) {
400
+ log.warn(`Warning: Chunk size is less than 1000 characters (${chunkSize}). This may lead to very small chunks.`);
702
401
  }
703
- return textSplitter;
704
- }();
705
- _proto.printValues = function printValues(obj) {
706
- log.info("Processing Rule: " + obj.name + " for " + obj.context);
402
+ log.info(`Text split into ${texts.length} chunks with size ${chunkSize} and overlap ${chunkOverlap}`);
403
+ return texts;
404
+ }
405
+ printValues(obj) {
406
+ log.info(`Processing Rule: ${obj.name} for ${obj.context}`);
707
407
  // For each obj.expression:arg:where
708
408
  if (obj.expression && obj.expression.arg && obj.expression.arg.where) {
709
409
  // for each args in obj.expression.arg.where, extract the nested key called "value"
710
- var statements = this.extractObjectsByKey(obj.expression.arg.where, 'value');
410
+ const statements = this.extractObjectsByKey(obj.expression.arg.where, 'value');
711
411
  return statements.join(' ').replace(/,/g, ' ');
712
412
  }
713
413
  // return statements array as a string seperated by space
714
414
  return '';
715
- };
716
- _proto.extractObjectsByKey = function extractObjectsByKey(obj, key) {
717
- var results = [];
415
+ }
416
+ extractObjectsByKey(obj, key) {
417
+ const results = [];
718
418
  function traverse(obj) {
719
- for (var currentKey in obj) {
419
+ for (const currentKey in obj) {
720
420
  if (obj.hasOwnProperty(currentKey)) {
721
421
  if (currentKey === key) {
722
422
  results.push(obj[currentKey]);
@@ -729,9 +429,8 @@ var LLMLoop = /*#__PURE__*/function (_BaseChain) {
729
429
  }
730
430
  traverse(obj);
731
431
  return results;
732
- };
733
- _proto._printValues = function _printValues(obj) {
734
- var _this2 = this;
432
+ }
433
+ _printValues(obj) {
735
434
  for (var key in obj) {
736
435
  if (typeof obj[key] === 'object') {
737
436
  this._printValues(obj[key]);
@@ -739,168 +438,324 @@ var LLMLoop = /*#__PURE__*/function (_BaseChain) {
739
438
  this.stringExpression += obj[key] + ' ';
740
439
  }
741
440
  }
742
- var _eliminate = ['true', 'false', 'null', 'undefined', 'String', 'Number', 'Object', 'Array', 'Boolean', 'value', 'Type', 'Specifier', 'Named'];
743
- _eliminate.forEach(function (element) {
744
- var regex = new RegExp(element, 'g');
745
- _this2.stringExpression = _this2.stringExpression.replace(regex, '');
441
+ const _eliminate = ['true', 'false', 'null', 'undefined', 'String', 'Number', 'Object', 'Array', 'Boolean', 'value', 'Type', 'Specifier', 'Named'];
442
+ _eliminate.forEach(element => {
443
+ const regex = new RegExp(element, 'g');
444
+ this.stringExpression = this.stringExpression.replace(regex, '');
746
445
  });
747
446
  this.stringExpression = this.stringExpression.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '');
748
447
  return this.camelToString(this.stringExpression);
749
- };
750
- _proto.chain = /*#__PURE__*/function () {
751
- var _chain = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8(input) {
752
- var _this3 = this;
753
- var _yield$import, RunnableSequence, RunnableParallel, RunnablePassthrough, mapQuery, mapDoc, reduceChain, mapQueryChain, mapDocChain, parallelChain, sequence;
754
- return _regenerator().w(function (_context9) {
755
- while (1) switch (_context9.n) {
756
- case 0:
757
- _context9.n = 1;
758
- return import('@langchain/core/runnables');
759
- case 1:
760
- _yield$import = _context9.v;
761
- RunnableSequence = _yield$import.RunnableSequence;
762
- RunnableParallel = _yield$import.RunnableParallel;
763
- RunnablePassthrough = _yield$import.RunnablePassthrough;
764
- mapQuery = new BaseChain(this.container);
765
- mapDoc = new BaseChain(this.container);
766
- reduceChain = new BaseChain(this.container);
767
- mapQuery.name = 'MapQuery';
768
- mapQuery.description = 'Map the expression to a natural language query.';
769
- mapQuery.template = this._mapQueryTemplate;
770
- mapDoc.name = 'MapDoc';
771
- mapDoc.description = 'Map the document to a set of facts.';
772
- mapDoc.template = this._mapDocTemplate;
773
- reduceChain.name = 'ReduceChain';
774
- reduceChain.description = 'Reduce a set of documents to binary answer.';
775
- reduceChain.template = this._reduceChainTemplate;
776
- mapQueryChain = RunnablePassthrough.assign({
777
- query: function () {
778
- var _query = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(input) {
779
- return _regenerator().w(function (_context6) {
780
- while (1) switch (_context6.n) {
781
- case 0:
782
- return _context6.a(2, mapQuery.chain({
783
- expression: input.input.expression
784
- }));
785
- }
786
- }, _callee5);
787
- }));
788
- function query(_x1) {
789
- return _query.apply(this, arguments);
790
- }
791
- return query;
792
- }()
793
- });
794
- mapDocChain = RunnablePassthrough.assign({
795
- documents: function () {
796
- var _documents = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(input) {
797
- var textChunks;
798
- return _regenerator().w(function (_context7) {
799
- while (1) switch (_context7.n) {
800
- case 0:
801
- _context7.n = 1;
802
- return _this3.textSplitter(input.input.context);
803
- case 1:
804
- textChunks = _context7.v;
805
- return _context7.a(2, Promise.all(textChunks.map(function (chunk) {
806
- return mapDoc.chain({
807
- document: chunk,
808
- statements: input.input.expression
809
- });
810
- })));
811
- }
812
- }, _callee6);
813
- }));
814
- function documents(_x10) {
815
- return _documents.apply(this, arguments);
816
- }
817
- return documents;
818
- }()
819
- });
820
- parallelChain = RunnableParallel.from([mapQueryChain, mapDocChain]);
821
- sequence = RunnableSequence.from([parallelChain, (/*#__PURE__*/function () {
822
- var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(results) {
823
- var expression, query, documents;
824
- return _regenerator().w(function (_context8) {
825
- while (1) switch (_context8.n) {
826
- case 0:
827
- /* results is an array: [{ query: ... }, { documents: [...] }]
828
- {
829
- "0": {
830
- "input": {
831
- "expression": "0 Visual foot exam showed active infection?",
832
- "context": "Procedure: The patient underwent a visual foot examination on 26 days ago. to assess skin integrity, circulation, and structural abnormalities. Findings: - Skin Condition: No signs of dryness, cracking, or ulceration were observed. No abnormal lesions or discoloration present. - Nail Health: Toenails appeared intact with no evidence of fungal infection or ingrown nails. - Circulation: Normal coloration, with no signs of cyanosis or pallor. Capillary refill time within normal limits. - Edema: No visible swelling in the feet or ankles. - Deformities: No structural abnormalities such as bunions, hammertoes, or Charcot foot deformities noted. - Infections: Showed signs of active infection with erythema and swelling. - Sensation: No visible signs of neuropathy, though further testing may be required to assess sensory deficits. "
833
- },
834
- "query": "The text indicates a question about whether a visual foot exam revealed an active infection.\n"
835
- },
836
- "1": {
837
- "input": {
838
- "expression": "0 Visual foot exam showed active infection?",
839
- "context": "Procedure: The patient underwent a visual foot examination on 26 days ago. to assess skin integrity, circulation, and structural abnormalities. Findings: - Skin Condition: No signs of dryness, cracking, or ulceration were observed. No abnormal lesions or discoloration present. - Nail Health: Toenails appeared intact with no evidence of fungal infection or ingrown nails. - Circulation: Normal coloration, with no signs of cyanosis or pallor. Capillary refill time within normal limits. - Edema: No visible swelling in the feet or ankles. - Deformities: No structural abnormalities such as bunions, hammertoes, or Charcot foot deformities noted. - Infections: Showed signs of active infection with erythema and swelling. - Sensation: No visible signs of neuropathy, though further testing may be required to assess sensory deficits. "
840
- },
841
- "documents": [
842
- "26 days ago, a visual foot examination revealed no dryness, cracking, ulceration, lesions, discoloration, fungal infection, ingrown nails, cyanosis, pallor, edema, bunions, hammertoes, or Charcot foot deformities. Circulation and capillary refill were normal. However, the exam showed signs"
843
- ]
844
- }
845
- }
846
- */
847
- log.info("Results from parallel chain: " + JSON.stringify(results));
848
- expression = results[0].input.expression;
849
- query = results[0].query;
850
- documents = results[1].documents;
851
- return _context8.a(2, reduceChain.chain({
852
- facts: documents,
853
- query: query + ' ' + expression
854
- }));
855
- }
856
- }, _callee7);
857
- }));
858
- return function (_x11) {
859
- return _ref.apply(this, arguments);
860
- };
861
- }()), function (result) {
862
- return _this3.stringToBoolean(result);
863
- }]);
864
- return _context9.a(2, sequence.invoke(input));
448
+ }
449
+ async chain(input) {
450
+ // Create a chain using RunnableSequence, RunnablePassthrough and RunnableParallel
451
+ // input has two properties: expression and context
452
+ // expression goes through mapQuery and parallely
453
+ // context goes through textSplitter and mapDoc
454
+ // Finally reduceChain is called with the results of mapQuery and mapDoc
455
+ // LCEL-based implementation using RunnableSequence, RunnableParallel, and RunnablePassthrough
456
+ const {
457
+ RunnableSequence,
458
+ RunnableParallel,
459
+ RunnablePassthrough
460
+ } = await import('@langchain/core/runnables');
461
+ const mapQuery = new BaseChain(this.container);
462
+ const mapDoc = new BaseChain(this.container);
463
+ const reduceChain = new BaseChain(this.container);
464
+ mapQuery.name = 'MapQuery';
465
+ mapQuery.description = 'Map the expression to a natural language query.';
466
+ mapQuery.template = this.resolve('litl_mapquery_template', this._mapQueryTemplate);
467
+ mapDoc.name = 'MapDoc';
468
+ mapDoc.description = 'Map the document to a set of facts.';
469
+ mapDoc.template = this.resolve('litl_mapdoc_template', this._mapDocTemplate);
470
+ reduceChain.name = 'ReduceChain';
471
+ reduceChain.description = 'Reduce a set of documents to binary answer.';
472
+ reduceChain.template = this.resolve('litl_reduce_chain_template', this._reduceChainTemplate);
473
+ const mapQueryChain = RunnablePassthrough.assign({
474
+ query: async input => mapQuery.chain({
475
+ expression: input.input.expression
476
+ })
477
+ });
478
+ const mapDocChain = RunnablePassthrough.assign({
479
+ documents: async input => {
480
+ const textChunks = await this.textSplitter(input.input.context);
481
+ return Promise.all(textChunks.map(chunk => mapDoc.chain({
482
+ document: chunk,
483
+ statements: input.input.expression
484
+ })));
485
+ }
486
+ });
487
+ const parallelChain = RunnableParallel.from([mapQueryChain, mapDocChain]);
488
+ const sequence = RunnableSequence.from([parallelChain, async results => {
489
+ /* results is an array: [{ query: ... }, { documents: [...] }]
490
+ {
491
+ "0": {
492
+ "input": {
493
+ "expression": "0 Visual foot exam showed active infection?",
494
+ "context": "Procedure: The patient underwent a visual foot examination on 26 days ago. to assess skin integrity, circulation, and structural abnormalities. Findings: - Skin Condition: No signs of dryness, cracking, or ulceration were observed. No abnormal lesions or discoloration present. - Nail Health: Toenails appeared intact with no evidence of fungal infection or ingrown nails. - Circulation: Normal coloration, with no signs of cyanosis or pallor. Capillary refill time within normal limits. - Edema: No visible swelling in the feet or ankles. - Deformities: No structural abnormalities such as bunions, hammertoes, or Charcot foot deformities noted. - Infections: Showed signs of active infection with erythema and swelling. - Sensation: No visible signs of neuropathy, though further testing may be required to assess sensory deficits. "
495
+ },
496
+ "query": "The text indicates a question about whether a visual foot exam revealed an active infection.\n"
497
+ },
498
+ "1": {
499
+ "input": {
500
+ "expression": "0 Visual foot exam showed active infection?",
501
+ "context": "Procedure: The patient underwent a visual foot examination on 26 days ago. to assess skin integrity, circulation, and structural abnormalities. Findings: - Skin Condition: No signs of dryness, cracking, or ulceration were observed. No abnormal lesions or discoloration present. - Nail Health: Toenails appeared intact with no evidence of fungal infection or ingrown nails. - Circulation: Normal coloration, with no signs of cyanosis or pallor. Capillary refill time within normal limits. - Edema: No visible swelling in the feet or ankles. - Deformities: No structural abnormalities such as bunions, hammertoes, or Charcot foot deformities noted. - Infections: Showed signs of active infection with erythema and swelling. - Sensation: No visible signs of neuropathy, though further testing may be required to assess sensory deficits. "
502
+ },
503
+ "documents": [
504
+ "26 days ago, a visual foot examination revealed no dryness, cracking, ulceration, lesions, discoloration, fungal infection, ingrown nails, cyanosis, pallor, edema, bunions, hammertoes, or Charcot foot deformities. Circulation and capillary refill were normal. However, the exam showed signs"
505
+ ]
506
+ }
507
+ }
508
+ */
509
+ log.info(`Results from parallel chain: ${JSON.stringify(results)}`);
510
+ const expression = results[0].input.expression;
511
+ const query = results[0].query;
512
+ const documents = results[1].documents;
513
+ return reduceChain.chain({
514
+ facts: documents,
515
+ query: query + ' ' + expression
516
+ });
517
+ }, result => this.stringToBoolean(result)]);
518
+ return sequence.invoke(input);
519
+ }
520
+ }
521
+
522
+ /**
523
+ * Copyright 2024 Bell Eapen
524
+ *
525
+ * Licensed under the Apache License, Version 2.0 (the "License");
526
+ * you may not use this file except in compliance with the License.
527
+ * You may obtain a copy of the License at
528
+ *
529
+ * https://www.apache.org/licenses/LICENSE-2.0
530
+ *
531
+ * Unless required by applicable law or agreed to in writing, software
532
+ * distributed under the License is distributed on an "AS IS" BASIS,
533
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
534
+ * See the License for the specific language governing permissions and
535
+ * limitations under the License.
536
+ */
537
+ /**
538
+ * BaseLLM is a base class for LLMs that communicate with a remote API.
539
+ * It extends the LangChain LLM class and provides configurable parameters
540
+ * for model inference.
541
+ */
542
+ class BaseLLM extends llms.LLM {
543
+ constructor(fields) {
544
+ var _fields$apiKey, _fields$timeout, _fields$backend, _fields$temperature, _fields$topP, _fields$topK, _fields$nBatch, _fields$nThreads, _fields$nPredict, _fields$maxOutputToke, _fields$repeatLastN, _fields$repeatPenalty;
545
+ super(fields);
546
+ this.baseUrl = void 0;
547
+ this.model = void 0;
548
+ this.apiKey = void 0;
549
+ this.timeout = void 0;
550
+ this.backend = void 0;
551
+ this.temperature = void 0;
552
+ this.topP = void 0;
553
+ this.topK = void 0;
554
+ this.nBatch = void 0;
555
+ this.nThreads = void 0;
556
+ this.nPredict = void 0;
557
+ this.maxOutputTokens = void 0;
558
+ this.repeatLastN = void 0;
559
+ this.repeatPenalty = void 0;
560
+ this.baseUrl = fields.baseUrl;
561
+ this.model = fields.model;
562
+ this.apiKey = (_fields$apiKey = fields.apiKey) != null ? _fields$apiKey : '';
563
+ this.timeout = (_fields$timeout = fields.timeout) != null ? _fields$timeout : 60000;
564
+ this.backend = (_fields$backend = fields.backend) != null ? _fields$backend : 'dhti';
565
+ this.temperature = (_fields$temperature = fields.temperature) != null ? _fields$temperature : 0.1;
566
+ this.topP = (_fields$topP = fields.topP) != null ? _fields$topP : 0.8;
567
+ this.topK = (_fields$topK = fields.topK) != null ? _fields$topK : 40;
568
+ this.nBatch = (_fields$nBatch = fields.nBatch) != null ? _fields$nBatch : 8;
569
+ this.nThreads = (_fields$nThreads = fields.nThreads) != null ? _fields$nThreads : 4;
570
+ this.nPredict = (_fields$nPredict = fields.nPredict) != null ? _fields$nPredict : 256;
571
+ this.maxOutputTokens = (_fields$maxOutputToke = fields.maxOutputTokens) != null ? _fields$maxOutputToke : 512;
572
+ this.repeatLastN = (_fields$repeatLastN = fields.repeatLastN) != null ? _fields$repeatLastN : 64;
573
+ this.repeatPenalty = (_fields$repeatPenalty = fields.repeatPenalty) != null ? _fields$repeatPenalty : 1.18;
574
+ }
575
+ /**
576
+ * Get the model default parameters
577
+ */
578
+ get modelDefaultParameters() {
579
+ return {
580
+ maxOutputTokens: this.maxOutputTokens,
581
+ nPredict: this.nPredict,
582
+ topK: this.topK,
583
+ topP: this.topP,
584
+ temperature: this.temperature,
585
+ nBatch: this.nBatch,
586
+ repeatPenalty: this.repeatPenalty,
587
+ repeatLastN: this.repeatLastN
588
+ };
589
+ }
590
+ /**
591
+ * Get the identifying parameters
592
+ */
593
+ get identifyingParams() {
594
+ return {
595
+ model: this.model,
596
+ baseUrl: this.baseUrl,
597
+ modelParameters: this.modelDefaultParameters
598
+ };
599
+ }
600
+ /**
601
+ * Get the LLM type identifier
602
+ */
603
+ _llmType() {
604
+ return 'dhti';
605
+ }
606
+ /**
607
+ * Prepare the request payload for the API
608
+ */
609
+ preparePayload(prompt) {
610
+ return {
611
+ model: this.model,
612
+ options: this.modelDefaultParameters,
613
+ messages: [{
614
+ role: 'user',
615
+ content: prompt
616
+ }]
617
+ };
618
+ }
619
+ /**
620
+ * Make the API call to generate text
621
+ */
622
+ async _call(prompt, _options, _runManager) {
623
+ const payload = this.preparePayload(prompt);
624
+ const headers = {
625
+ 'Content-Type': 'application/json'
626
+ };
627
+ if (this.apiKey) {
628
+ headers['Authorization'] = `Bearer ${this.apiKey}`;
629
+ }
630
+ const controller = new AbortController();
631
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
632
+ try {
633
+ const response = await fetch(this.baseUrl, {
634
+ method: 'POST',
635
+ headers,
636
+ body: JSON.stringify(payload),
637
+ signal: controller.signal
638
+ });
639
+ clearTimeout(timeoutId);
640
+ if (!response.ok) {
641
+ const body = await response.text();
642
+ throw new Error(`API request failed: status=${response.status}; body=${body}`);
643
+ }
644
+ const data = await response.json();
645
+ // Expecting structure like: { "choices": [ { "message": { "role":"assistant","content":"..." } } ] }
646
+ // Adapt this path if the API differs
647
+ if (data.choices && Array.isArray(data.choices) && data.choices.length > 0) {
648
+ const choice = data.choices[0];
649
+ // support both "message" and direct "text"
650
+ if (typeof choice === 'object' && choice !== null && 'message' in choice && typeof choice.message === 'object' && choice.message !== null) {
651
+ const content = choice.message.content;
652
+ if (typeof content === 'string') {
653
+ return content;
654
+ }
655
+ } else if ('text' in choice) {
656
+ const text = choice.text;
657
+ if (typeof text === 'string') {
658
+ return text;
659
+ }
865
660
  }
866
- }, _callee8, this);
867
- }));
868
- function chain(_x0) {
869
- return _chain.apply(this, arguments);
661
+ }
662
+ // Fallback: return raw JSON string for debugging
663
+ return JSON.stringify(data);
664
+ } catch (error) {
665
+ clearTimeout(timeoutId);
666
+ if (error instanceof Error && error.name === 'AbortError') {
667
+ throw new Error(`API request timed out after ${this.timeout}ms`);
668
+ }
669
+ throw error;
870
670
  }
871
- return chain;
872
- }();
873
- return _createClass(LLMLoop, [{
874
- key: "mapQueryTemplate",
875
- get:
876
- // Add getters and setters for the templates if needed
877
- function get() {
878
- return this._mapQueryTemplate;
879
- },
880
- set: function set(template) {
881
- this._mapQueryTemplate = template;
671
+ }
672
+ }
673
+
674
+ /**
675
+ * Copyright 2024 Bell Eapen
676
+ *
677
+ * Licensed under the Apache License, Version 2.0 (the "License");
678
+ * you may not use this file except in compliance with the License.
679
+ * You may obtain a copy of the License at
680
+ *
681
+ * https://www.apache.org/licenses/LICENSE-2.0
682
+ *
683
+ * Unless required by applicable law or agreed to in writing, software
684
+ * distributed under the License is distributed on an "AS IS" BASIS,
685
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
686
+ * See the License for the specific language governing permissions and
687
+ * limitations under the License.
688
+ */
689
+ /**
690
+ * BaseEmbedding is a base class for embeddings that communicate with a remote API.
691
+ * It extends the LangChain Embeddings class and provides methods for embedding
692
+ * documents and queries.
693
+ */
694
+ class BaseEmbedding extends embeddings.Embeddings {
695
+ constructor(fields) {
696
+ var _fields$apiKey;
697
+ super(fields);
698
+ this.baseUrl = void 0;
699
+ this.model = void 0;
700
+ this.apiKey = void 0;
701
+ this.baseUrl = fields.baseUrl;
702
+ this.model = fields.model;
703
+ this.apiKey = (_fields$apiKey = fields.apiKey) != null ? _fields$apiKey : '';
704
+ }
705
+ /**
706
+ * Embed a list of documents
707
+ * @param texts - Array of strings to embed
708
+ * @returns Promise of array of embedding vectors
709
+ */
710
+ async embedDocuments(texts) {
711
+ return this.getEmbeddings(texts);
712
+ }
713
+ /**
714
+ * Embed a single query
715
+ * @param text - String to embed
716
+ * @returns Promise of embedding vector
717
+ */
718
+ async embedQuery(text) {
719
+ const embeddings = await this.getEmbeddings([text]);
720
+ return embeddings[0];
721
+ }
722
+ /**
723
+ * Helper method to get embeddings for a list of texts
724
+ * @param texts - Array of strings to embed
725
+ * @returns Promise of array of embedding vectors
726
+ */
727
+ async getEmbeddings(texts) {
728
+ const headers = {
729
+ 'Content-Type': 'application/json'
730
+ };
731
+ if (this.apiKey) {
732
+ headers['Authorization'] = `Bearer ${this.apiKey}`;
882
733
  }
883
- }, {
884
- key: "mapDocTemplate",
885
- get: function get() {
886
- return this._mapDocTemplate;
887
- },
888
- set: function set(template) {
889
- this._mapDocTemplate = template;
734
+ const payload = {
735
+ model: this.model,
736
+ input: texts
737
+ };
738
+ const response = await fetch(this.baseUrl, {
739
+ method: 'POST',
740
+ headers,
741
+ body: JSON.stringify(payload)
742
+ });
743
+ if (!response.ok) {
744
+ const body = await response.text();
745
+ throw new Error(`API request failed: status=${response.status}; body=${body}`);
890
746
  }
891
- }, {
892
- key: "reduceChainTemplate",
893
- get: function get() {
894
- return this._reduceChainTemplate;
895
- },
896
- set: function set(template) {
897
- this._reduceChainTemplate = template;
747
+ const respJson = await response.json();
748
+ if (!('embeddings' in respJson)) {
749
+ throw new Error(`API response missing 'embeddings' key. Received keys: ${Object.keys(respJson).join(', ')}`);
898
750
  }
899
- }]);
900
- }(BaseChain);
751
+ return respJson.embeddings;
752
+ }
753
+ }
901
754
 
902
755
  exports.BaseAgent = BaseAgent;
903
756
  exports.BaseChain = BaseChain;
757
+ exports.BaseEmbedding = BaseEmbedding;
758
+ exports.BaseLLM = BaseLLM;
904
759
  exports.BaseTool = BaseTool;
905
760
  exports.LLMLoop = LLMLoop;
906
761
  //# sourceMappingURL=medpromptjs.cjs.development.js.map