medpromptjs 0.4.4 → 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,177 +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
- function o(r, n) {
148
- _regeneratorDefine(e, r, function (e) {
149
- return this._invoke(r, n, e);
150
- });
151
- }
152
- r ? i ? i(e, r, {
153
- value: n,
154
- enumerable: !t,
155
- configurable: !t,
156
- writable: !t
157
- }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
158
- }, _regeneratorDefine(e, r, n, t);
159
- }
160
- function _setPrototypeOf(t, e) {
161
- return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
162
- return t.__proto__ = e, t;
163
- }, _setPrototypeOf(t, e);
164
- }
165
- function _toPrimitive(t, r) {
166
- if ("object" != typeof t || !t) return t;
167
- var e = t[Symbol.toPrimitive];
168
- if (void 0 !== e) {
169
- var i = e.call(t, r || "default");
170
- if ("object" != typeof i) return i;
171
- throw new TypeError("@@toPrimitive must return a primitive value.");
172
- }
173
- return ("string" === r ? String : Number)(t);
174
- }
175
- function _toPropertyKey(t) {
176
- var i = _toPrimitive(t, "string");
177
- return "symbol" == typeof i ? i : i + "";
178
- }
13
+ var llms = require('@langchain/core/language_models/llms');
14
+ var embeddings = require('@langchain/core/embeddings');
179
15
 
180
16
  /**
181
17
  * Copyright 2024 Bell Eapen
@@ -192,16 +28,36 @@ function _toPropertyKey(t) {
192
28
  * See the License for the specific language governing permissions and
193
29
  * limitations under the License.
194
30
  */
195
- var mydi = function mydi(c, m, b) {
31
+ const mydi = (c, m, b) => {
196
32
  try {
197
33
  return c.resolve(m + '_' + b);
198
- } catch (e) {
34
+ } catch (e) {}
35
+ try {
36
+ return c.resolve(m + '-' + b);
37
+ } catch (e) {}
38
+ try {
199
39
  return c.resolve(b);
200
- }
40
+ } catch (e) {}
41
+ return null;
201
42
  };
202
43
 
203
- var BaseChain = /*#__PURE__*/function () {
204
- 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) {
205
61
  this.container = void 0;
206
62
  this._name = '';
207
63
  this._description = '';
@@ -211,283 +67,165 @@ var BaseChain = /*#__PURE__*/function () {
211
67
  this.chat_model = void 0;
212
68
  this.runnable = void 0;
213
69
  this.container = container;
214
- this.llm = this.resolve('main-llm');
215
- this.chat_model = false;
216
- 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
+ }
217
80
  }
218
81
  // Getters and setters
219
- var _proto = BaseChain.prototype;
220
- _proto.initialize = function initialize() {
221
- if (this._name === '') {
222
- this._name = this.camelize(this.constructor.name);
223
- }
224
- if (this._description === '') {
225
- this._description = this.snake_case(this.constructor.name);
226
- }
227
- if (this._template === '') {
228
- this._template = "{{input}}";
229
- }
230
- 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;
231
99
  if (this.chat_model) {
232
100
  this.prompt = prompts.ChatPromptTemplate.fromTemplate(this._template);
233
101
  } else {
234
102
  this.prompt = prompts.PromptTemplate.fromTemplate(this._template);
235
103
  }
236
- };
237
- _proto.resolve = function resolve(name) {
238
- return mydi(this.container, this._name, name);
239
- };
240
- _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) {
241
109
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
242
110
  return index === 0 ? word.toLowerCase() : word.toUpperCase();
243
111
  }).replace(/\s+/g, '');
244
- };
245
- _proto.snake_case = function snake_case(str) {
112
+ }
113
+ snake_case(str) {
246
114
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
247
115
  return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();
248
116
  }).replace(/\s+/g, '');
249
117
  }
250
118
  // https://js.langchain.com/v0.1/docs/expression_language/how_to/routing/
251
119
  //! Override this method
252
- ;
253
- _proto.chain =
254
- /*#__PURE__*/
255
- function () {
256
- var _chain = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(input) {
257
- var response, aiMessage;
258
- return _regenerator().w(function (_context) {
259
- while (1) switch (_context.n) {
260
- case 0:
261
- this.runnable = runnables.RunnableSequence.from([new runnables.RunnablePassthrough(), this.prompt, this.llm]);
262
- if (!this.chat_model) {
263
- _context.n = 2;
264
- break;
265
- }
266
- _context.n = 1;
267
- return this.runnable.invoke(input);
268
- case 1:
269
- response = _context.v;
270
- aiMessage = new messages.AIMessage(response);
271
- return _context.a(2, aiMessage.content);
272
- case 2:
273
- _context.n = 3;
274
- return this.runnable.invoke(input);
275
- case 3:
276
- return _context.a(2, _context.v);
277
- }
278
- }, _callee, this);
279
- }));
280
- function chain(_x) {
281
- return _chain.apply(this, arguments);
282
- }
283
- return chain;
284
- }();
285
- return _createClass(BaseChain, [{
286
- key: "name",
287
- get: function get() {
288
- return this._name;
289
- },
290
- set: function set(value) {
291
- this._name = value === '' ? this.camelize(this.constructor.name) : value;
292
- }
293
- }, {
294
- key: "description",
295
- get: function get() {
296
- return this._description;
297
- },
298
- set: function set(value) {
299
- this._description = value === '' ? this.snake_case(this.constructor.name) : value;
300
- }
301
- }, {
302
- key: "template",
303
- get: function get() {
304
- return this._template;
305
- },
306
- set: function set(value) {
307
- this._template = value;
308
- try {
309
- this.chat_model = this.resolve('chat_model');
310
- } catch (e) {}
311
- if (this.chat_model) {
312
- this.prompt = prompts.ChatPromptTemplate.fromTemplate(this._template);
313
- } else {
314
- this.prompt = prompts.PromptTemplate.fromTemplate(this._template);
315
- }
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;
316
130
  }
317
- }]);
318
- }();
131
+ return await this.runnable.invoke(input);
132
+ }
133
+ async invoke(input) {
134
+ return this.chain(input);
135
+ }
136
+ }
319
137
 
320
- var BaseAgent = /*#__PURE__*/function () {
321
- function BaseAgent(container) {
322
- this.container = void 0;
323
- this._name = '';
324
- this._description = '';
325
- 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);
326
156
  this._tools = [];
327
- this.prompt = void 0;
328
- this.llm = void 0;
329
- this.chat_model = void 0;
330
- this.runnable = void 0;
331
- this.container = container;
332
- this.llm = this.resolve('main-llm');
333
- this.chat_model = false;
334
- this.initialize();
335
157
  }
336
- // Getters and setters
337
- var _proto = BaseAgent.prototype;
338
- _proto.initialize = function initialize() {
339
- if (this._name === '') {
340
- this._name = this.camelize(this.constructor.name);
341
- }
342
- if (this._description === '') {
343
- this._description = this.snake_case(this.constructor.name);
344
- }
345
- if (this._template === '') {
346
- this._template = "{{input}}";
347
- }
348
- this.prompt = this.prompt || prompts.PromptTemplate.fromTemplate(this._template);
349
- if (this.chat_model) {
350
- this.prompt = prompts.ChatPromptTemplate.fromTemplate(this._template);
351
- } else {
352
- this.prompt = prompts.PromptTemplate.fromTemplate(this._template);
353
- }
354
- };
355
- _proto.resolve = function resolve(name) {
356
- return mydi(this.container, this._name, name);
357
- };
358
- _proto.camelize = function camelize(str) {
359
- return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
360
- return index === 0 ? word.toLowerCase() : word.toUpperCase();
361
- }).replace(/\s+/g, '');
362
- };
363
- _proto.snake_case = function snake_case(str) {
364
- return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
365
- return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();
366
- }).replace(/\s+/g, '');
367
- };
368
- _proto.run = /*#__PURE__*/function () {
369
- var _run = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(input) {
370
- var agent, agentExecutor;
371
- return _regenerator().w(function (_context) {
372
- while (1) switch (_context.n) {
373
- case 0:
374
- _context.n = 1;
375
- return agents.createStructuredChatAgent({
376
- llm: this.llm,
377
- tools: this._tools,
378
- prompt: this.prompt
379
- });
380
- case 1:
381
- agent = _context.v;
382
- agentExecutor = new agents.AgentExecutor({
383
- agent: agent,
384
- tools: this.tools,
385
- // verbose: true,
386
- handleParsingErrors: 'Please try again, paying close attention to the final answer'
387
- });
388
- _context.n = 2;
389
- return agentExecutor.invoke(input);
390
- case 2:
391
- return _context.a(2, _context.v);
392
- }
393
- }, _callee, this);
394
- }));
395
- function run(_x) {
396
- return _run.apply(this, arguments);
397
- }
398
- return run;
399
- }();
400
- return _createClass(BaseAgent, [{
401
- key: "name",
402
- get: function get() {
403
- return this._name;
404
- },
405
- set: function set(value) {
406
- this._name = value === '' ? this.camelize(this.constructor.name) : value;
407
- }
408
- }, {
409
- key: "description",
410
- get: function get() {
411
- return this._description;
412
- },
413
- set: function set(value) {
414
- this._description = value === '' ? this.snake_case(this.constructor.name) : value;
415
- }
416
- }, {
417
- key: "template",
418
- get: function get() {
419
- return this._template;
420
- },
421
- set: function set(value) {
422
- this._template = value;
423
- try {
424
- this.chat_model = this.resolve('chat_model');
425
- } catch (e) {}
426
- if (this.chat_model) {
427
- this.prompt = prompts.ChatPromptTemplate.fromTemplate(this._template);
428
- } else {
429
- this.prompt = prompts.PromptTemplate.fromTemplate(this._template);
430
- }
431
- }
432
- // Getters and setters for tools
433
- }, {
434
- key: "tools",
435
- get: function get() {
436
- return this._tools;
437
- },
438
- set: function set(value) {
439
- this._tools = value;
440
- }
441
- }]);
442
- }();
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
+ }
443
183
 
444
- var BaseTool = /*#__PURE__*/function (_DynamicStructuredToo) {
445
- function BaseTool(container, name, description, schema, func) {
446
- var _this;
447
- if (func === void 0) {
448
- func = null;
449
- }
450
- _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({
451
202
  name: name,
452
203
  description: description,
453
204
  schema: schema,
454
205
  func: func
455
- }) || this;
206
+ });
456
207
  /** @hidden */
457
- _this.container = void 0;
458
- _this.name = void 0;
459
- _this.description = void 0;
460
- _this.schema = void 0;
461
- _this.func = /*#__PURE__*/function () {
462
- var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(args) {
463
- return _regenerator().w(function (_context) {
464
- while (1) switch (_context.n) {
465
- case 0:
466
- return _context.a(2, 'override this');
467
- }
468
- }, _callee);
469
- }));
470
- return function (_x) {
471
- return _ref.apply(this, arguments);
472
- };
473
- }();
474
- _this.container = container;
475
- _this.name = name === '' ? _this.camelize(_this.constructor.name) : name;
476
- _this.description = description === '' ? _this.snake_case(_this.constructor.name) : description;
477
- _this.schema = schema;
478
- return _this;
479
- }
480
- _inheritsLoose(BaseTool, _DynamicStructuredToo);
481
- var _proto = BaseTool.prototype;
482
- _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) {
483
221
  return mydi(this.container, this.name, name);
484
- };
485
- _proto.camelize = function camelize(str) {
222
+ }
223
+ camelize(str) {
486
224
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
487
225
  return index === 0 ? word.toLowerCase() : word.toUpperCase();
488
226
  }).replace(/\s+/g, '');
489
- };
490
- _proto.snake_case = function snake_case(str) {
227
+ }
228
+ snake_case(str) {
491
229
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (word, index) {
492
230
  return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();
493
231
  }).replace(/\s+/g, '');
@@ -496,225 +234,189 @@ var BaseTool = /*#__PURE__*/function (_DynamicStructuredToo) {
496
234
  * @param input - The input to process in batch.
497
235
  * @param config - The configuration for the batch.
498
236
  * @returns A promise resolving to an array of results.
499
- */;
500
- _proto._batchWithConfig =
501
- /*#__PURE__*/
502
- function () {
503
- var _batchWithConfig2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(input, config) {
504
- return _regenerator().w(function (_context2) {
505
- while (1) switch (_context2.n) {
506
- case 0:
507
- return _context2.a(2, _DynamicStructuredToo.prototype._batchWithConfig.call(this, input, config));
508
- }
509
- }, _callee2, this);
510
- }));
511
- function _batchWithConfig(_x2, _x3) {
512
- return _batchWithConfig2.apply(this, arguments);
513
- }
514
- return _batchWithConfig;
515
- }();
516
- return BaseTool;
517
- }(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
+ }
518
243
 
519
- var log = /*#__PURE__*/new tslog.Logger();
520
- var LLMLoop = /*#__PURE__*/function (_BaseChain) {
521
- function LLMLoop() {
522
- var _this;
523
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
524
- args[_key] = arguments[_key];
525
- }
526
- _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);
527
248
  // Implement the LLM loop logic here
528
- _this.stringExpression = '';
529
- _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: ";
530
- _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: ";
531
- _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: ";
532
- return _this;
533
- }
534
- _inheritsLoose(LLMLoop, _BaseChain);
535
- var _proto = LLMLoop.prototype;
536
- _proto.checkAssertion = /*#__PURE__*/function () {
537
- var _checkAssertion = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(expression, context) {
538
- var _expression, _context, _content, _input, result;
539
- return _regenerator().w(function (_context2) {
540
- while (1) switch (_context2.n) {
541
- case 0:
542
- _expression = '';
543
- try {
544
- // Check if expression is a valid JSON string
545
- _expression = this.printValues(JSON.parse(expression));
546
- } catch (error) {
547
- _expression = expression; // If not, use the expression as is
548
- }
549
- log.info("Checking assertion with expression: " + _expression);
550
- // Initialize context and content
551
- _context = undefined;
552
- _content = '';
553
- try {
554
- _context = JSON.parse(context);
555
- } catch (error) {
556
- _context = context; // If not, use the context as is
557
- log.warn("Context is not a valid JSON string: " + context);
558
- log.warn("Using context as a string: " + _context);
559
- }
560
- try {
561
- // Check if context is a valid JSON string
562
- _context = JSON.parse(context);
563
- _context.forEach(function (element) {
564
- element.content.forEach(function (contentItem) {
565
- _content += atob(contentItem.attachment.data.value);
566
- });
567
- });
568
- } catch (error) {
569
- _content = context; // If not, use the context as is
570
- log.warn("Context is not a valid JSON : " + context);
571
- log.warn("Using context as a string: " + _content);
572
- }
573
- _content = this.findDatesAndConvertToTimeElapsed(_content.replace(/(\r\n|\n|\r)/gm, ' '));
574
- log.info("Checking assertion with context: " + _content);
575
- _input = {
576
- input: {
577
- expression: _expression,
578
- context: _content
579
- }
580
- };
581
- _context2.n = 1;
582
- return this.chain(_input);
583
- case 1:
584
- result = _context2.v;
585
- log.info("Assertion check result: " + result);
586
- return _context2.a(2, result);
587
- }
588
- }, _callee, this);
589
- }));
590
- function checkAssertion(_x, _x2) {
591
- return _checkAssertion.apply(this, arguments);
592
- }
593
- return checkAssertion;
594
- }();
595
- _proto.checkMention = /*#__PURE__*/function () {
596
- var _checkMention = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(expression, context) {
597
- return _regenerator().w(function (_context3) {
598
- while (1) switch (_context3.n) {
599
- case 0:
600
- if (!(expression && context)) {
601
- _context3.n = 1;
602
- break;
603
- }
604
- return _context3.a(2, true);
605
- case 1:
606
- return _context3.a(2, false);
607
- }
608
- }, _callee2);
609
- }));
610
- function checkMention(_x3, _x4) {
611
- return _checkMention.apply(this, arguments);
612
- }
613
- return checkMention;
614
- }();
615
- _proto.checkNegation = /*#__PURE__*/function () {
616
- var _checkNegation = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(expression, context) {
617
- return _regenerator().w(function (_context4) {
618
- while (1) switch (_context4.n) {
619
- case 0:
620
- if (!(expression && context)) {
621
- _context4.n = 1;
622
- break;
623
- }
624
- return _context4.a(2, true);
625
- case 1:
626
- return _context4.a(2, false);
627
- }
628
- }, _callee3);
629
- }));
630
- function checkNegation(_x5, _x6) {
631
- return _checkNegation.apply(this, arguments);
632
- }
633
- return checkNegation;
634
- }();
635
- _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) {
636
363
  // Regular expression to match dates in format of 'mm/dd/yyyy' or 'mm-dd-yyyy'
637
- var dateRegex = /(\d{1,2}[-/]\d{1,2}[-/]\d{4})/g;
638
- var matches;
639
- var currentDate = new Date();
364
+ const dateRegex = /(\d{1,2}[-/]\d{1,2}[-/]\d{4})/g;
365
+ let matches;
366
+ let currentDate = new Date();
640
367
  while ((matches = dateRegex.exec(text)) !== null) {
641
- var date = new Date(matches[0]);
642
- 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);
643
370
  text = text.replace(matches[0], Math.floor(timeElapsed).toString() + ' days ago.');
644
371
  }
645
372
  return text;
646
- };
647
- _proto.camelToString = function camelToString(camelCase) {
373
+ }
374
+ camelToString(camelCase) {
648
375
  return camelCase.replace(/([A-Z])/g, ' $1').replace(/^./, function (str) {
649
376
  return str.toUpperCase();
650
377
  });
651
- };
652
- _proto.stringToBoolean = function stringToBoolean(str) {
653
- log.info("Converting string to boolean: " + str);
654
- var positiveKeywords = ['true', 'contains', 'confirms', 'yes', 'affirmative', 'matches', 'exists', 'present', 'absolutely', 'certainly', 'definitely', 'indeed', 'did have', 'showed', 'revealed'];
655
- var lowerStr = str.toLowerCase();
656
- return positiveKeywords.some(function (keyword) {
657
- 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
658
389
  });
659
- };
660
- _proto.textSplitter = /*#__PURE__*/function () {
661
- var _textSplitter = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(text, chunkSize, chunkOverlap) {
662
- var textSplitter, texts;
663
- return _regenerator().w(function (_context5) {
664
- while (1) switch (_context5.n) {
665
- case 0:
666
- if (chunkSize === void 0) {
667
- chunkSize = 3900;
668
- }
669
- if (chunkOverlap === void 0) {
670
- chunkOverlap = 0;
671
- }
672
- textSplitter = new textsplitters.CharacterTextSplitter({
673
- chunkSize: chunkSize,
674
- chunkOverlap: chunkOverlap
675
- });
676
- _context5.n = 1;
677
- return textSplitter.splitText(text);
678
- case 1:
679
- texts = _context5.v;
680
- if (!(texts.length === 0)) {
681
- _context5.n = 2;
682
- break;
683
- }
684
- log.warn('No text chunks created. Please check the input text.');
685
- return _context5.a(2, []);
686
- case 2:
687
- if (texts.length > 100) {
688
- log.warn("Warning: More than 100 text chunks created (" + texts.length + "). This may affect performance.");
689
- }
690
- if (chunkSize < 1000) {
691
- log.warn("Warning: Chunk size is less than 1000 characters (" + chunkSize + "). This may lead to very small chunks.");
692
- }
693
- log.info("Text split into " + texts.length + " chunks with size " + chunkSize + " and overlap " + chunkOverlap);
694
- return _context5.a(2, texts);
695
- }
696
- }, _callee4);
697
- }));
698
- function textSplitter(_x7, _x8, _x9) {
699
- 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 [];
700
395
  }
701
- return textSplitter;
702
- }();
703
- _proto.printValues = function printValues(obj) {
704
- log.info("Processing Rule: " + obj.name + " for " + obj.context);
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.`);
401
+ }
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}`);
705
407
  // For each obj.expression:arg:where
706
408
  if (obj.expression && obj.expression.arg && obj.expression.arg.where) {
707
409
  // for each args in obj.expression.arg.where, extract the nested key called "value"
708
- var statements = this.extractObjectsByKey(obj.expression.arg.where, 'value');
410
+ const statements = this.extractObjectsByKey(obj.expression.arg.where, 'value');
709
411
  return statements.join(' ').replace(/,/g, ' ');
710
412
  }
711
413
  // return statements array as a string seperated by space
712
414
  return '';
713
- };
714
- _proto.extractObjectsByKey = function extractObjectsByKey(obj, key) {
715
- var results = [];
415
+ }
416
+ extractObjectsByKey(obj, key) {
417
+ const results = [];
716
418
  function traverse(obj) {
717
- for (var currentKey in obj) {
419
+ for (const currentKey in obj) {
718
420
  if (obj.hasOwnProperty(currentKey)) {
719
421
  if (currentKey === key) {
720
422
  results.push(obj[currentKey]);
@@ -727,9 +429,8 @@ var LLMLoop = /*#__PURE__*/function (_BaseChain) {
727
429
  }
728
430
  traverse(obj);
729
431
  return results;
730
- };
731
- _proto._printValues = function _printValues(obj) {
732
- var _this2 = this;
432
+ }
433
+ _printValues(obj) {
733
434
  for (var key in obj) {
734
435
  if (typeof obj[key] === 'object') {
735
436
  this._printValues(obj[key]);
@@ -737,168 +438,324 @@ var LLMLoop = /*#__PURE__*/function (_BaseChain) {
737
438
  this.stringExpression += obj[key] + ' ';
738
439
  }
739
440
  }
740
- var _eliminate = ['true', 'false', 'null', 'undefined', 'String', 'Number', 'Object', 'Array', 'Boolean', 'value', 'Type', 'Specifier', 'Named'];
741
- _eliminate.forEach(function (element) {
742
- var regex = new RegExp(element, 'g');
743
- _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, '');
744
445
  });
745
446
  this.stringExpression = this.stringExpression.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '');
746
447
  return this.camelToString(this.stringExpression);
747
- };
748
- _proto.chain = /*#__PURE__*/function () {
749
- var _chain = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8(input) {
750
- var _this3 = this;
751
- var _yield$import, RunnableSequence, RunnableParallel, RunnablePassthrough, mapQuery, mapDoc, reduceChain, mapQueryChain, mapDocChain, parallelChain, sequence;
752
- return _regenerator().w(function (_context9) {
753
- while (1) switch (_context9.n) {
754
- case 0:
755
- _context9.n = 1;
756
- return import('@langchain/core/runnables');
757
- case 1:
758
- _yield$import = _context9.v;
759
- RunnableSequence = _yield$import.RunnableSequence;
760
- RunnableParallel = _yield$import.RunnableParallel;
761
- RunnablePassthrough = _yield$import.RunnablePassthrough;
762
- mapQuery = new BaseChain(this.container);
763
- mapDoc = new BaseChain(this.container);
764
- reduceChain = new BaseChain(this.container);
765
- mapQuery.name = 'MapQuery';
766
- mapQuery.description = 'Map the expression to a natural language query.';
767
- mapQuery.template = this._mapQueryTemplate;
768
- mapDoc.name = 'MapDoc';
769
- mapDoc.description = 'Map the document to a set of facts.';
770
- mapDoc.template = this._mapDocTemplate;
771
- reduceChain.name = 'ReduceChain';
772
- reduceChain.description = 'Reduce a set of documents to binary answer.';
773
- reduceChain.template = this._reduceChainTemplate;
774
- mapQueryChain = RunnablePassthrough.assign({
775
- query: function () {
776
- var _query = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(input) {
777
- return _regenerator().w(function (_context6) {
778
- while (1) switch (_context6.n) {
779
- case 0:
780
- return _context6.a(2, mapQuery.chain({
781
- expression: input.input.expression
782
- }));
783
- }
784
- }, _callee5);
785
- }));
786
- function query(_x1) {
787
- return _query.apply(this, arguments);
788
- }
789
- return query;
790
- }()
791
- });
792
- mapDocChain = RunnablePassthrough.assign({
793
- documents: function () {
794
- var _documents = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(input) {
795
- var textChunks;
796
- return _regenerator().w(function (_context7) {
797
- while (1) switch (_context7.n) {
798
- case 0:
799
- _context7.n = 1;
800
- return _this3.textSplitter(input.input.context);
801
- case 1:
802
- textChunks = _context7.v;
803
- return _context7.a(2, Promise.all(textChunks.map(function (chunk) {
804
- return mapDoc.chain({
805
- document: chunk,
806
- statements: input.input.expression
807
- });
808
- })));
809
- }
810
- }, _callee6);
811
- }));
812
- function documents(_x10) {
813
- return _documents.apply(this, arguments);
814
- }
815
- return documents;
816
- }()
817
- });
818
- parallelChain = RunnableParallel.from([mapQueryChain, mapDocChain]);
819
- sequence = RunnableSequence.from([parallelChain, (/*#__PURE__*/function () {
820
- var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(results) {
821
- var expression, query, documents;
822
- return _regenerator().w(function (_context8) {
823
- while (1) switch (_context8.n) {
824
- case 0:
825
- /* results is an array: [{ query: ... }, { documents: [...] }]
826
- {
827
- "0": {
828
- "input": {
829
- "expression": "0 Visual foot exam showed active infection?",
830
- "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. "
831
- },
832
- "query": "The text indicates a question about whether a visual foot exam revealed an active infection.\n"
833
- },
834
- "1": {
835
- "input": {
836
- "expression": "0 Visual foot exam showed active infection?",
837
- "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. "
838
- },
839
- "documents": [
840
- "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"
841
- ]
842
- }
843
- }
844
- */
845
- log.info("Results from parallel chain: " + JSON.stringify(results));
846
- expression = results[0].input.expression;
847
- query = results[0].query;
848
- documents = results[1].documents;
849
- return _context8.a(2, reduceChain.chain({
850
- facts: documents,
851
- query: query + ' ' + expression
852
- }));
853
- }
854
- }, _callee7);
855
- }));
856
- return function (_x11) {
857
- return _ref.apply(this, arguments);
858
- };
859
- }()), function (result) {
860
- return _this3.stringToBoolean(result);
861
- }]);
862
- 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
+ }
863
660
  }
864
- }, _callee8, this);
865
- }));
866
- function chain(_x0) {
867
- 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;
868
670
  }
869
- return chain;
870
- }();
871
- return _createClass(LLMLoop, [{
872
- key: "mapQueryTemplate",
873
- get:
874
- // Add getters and setters for the templates if needed
875
- function get() {
876
- return this._mapQueryTemplate;
877
- },
878
- set: function set(template) {
879
- 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}`;
880
733
  }
881
- }, {
882
- key: "mapDocTemplate",
883
- get: function get() {
884
- return this._mapDocTemplate;
885
- },
886
- set: function set(template) {
887
- 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}`);
888
746
  }
889
- }, {
890
- key: "reduceChainTemplate",
891
- get: function get() {
892
- return this._reduceChainTemplate;
893
- },
894
- set: function set(template) {
895
- 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(', ')}`);
896
750
  }
897
- }]);
898
- }(BaseChain);
751
+ return respJson.embeddings;
752
+ }
753
+ }
899
754
 
900
755
  exports.BaseAgent = BaseAgent;
901
756
  exports.BaseChain = BaseChain;
757
+ exports.BaseEmbedding = BaseEmbedding;
758
+ exports.BaseLLM = BaseLLM;
902
759
  exports.BaseTool = BaseTool;
903
760
  exports.LLMLoop = LLMLoop;
904
761
  //# sourceMappingURL=medpromptjs.cjs.development.js.map