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