medpromptjs 0.4.4 → 0.5.1

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