medpromptjs 0.4.3 → 0.5.0

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