medpromptjs 0.5.0 → 0.5.2
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.
- package/dist/chain.d.ts +3 -0
- package/dist/medpromptjs.cjs.development.js +10 -7
- package/dist/medpromptjs.cjs.development.js.map +1 -1
- package/dist/medpromptjs.cjs.production.min.js +1 -1
- package/dist/medpromptjs.cjs.production.min.js.map +1 -1
- package/dist/medpromptjs.esm.js +10 -7
- package/dist/medpromptjs.esm.js.map +1 -1
- package/package.json +7 -10
package/dist/chain.d.ts
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
import { LLM } from '@langchain/core/language_models/llms';
|
|
17
|
+
import { FakeListChatModel } from '@langchain/core/utils/testing';
|
|
17
18
|
export declare class BaseChain {
|
|
18
19
|
container: any;
|
|
19
20
|
private _name;
|
|
@@ -23,7 +24,9 @@ export declare class BaseChain {
|
|
|
23
24
|
llm: LLM;
|
|
24
25
|
chat_model: boolean;
|
|
25
26
|
runnable: any;
|
|
27
|
+
fakeLLM: FakeListChatModel;
|
|
26
28
|
constructor(container: any);
|
|
29
|
+
initializePrompt(): void;
|
|
27
30
|
get name(): string;
|
|
28
31
|
set name(value: string);
|
|
29
32
|
get description(): string;
|
|
@@ -6,6 +6,7 @@ var prompts = require('@langchain/core/prompts');
|
|
|
6
6
|
var runnables = require('@langchain/core/runnables');
|
|
7
7
|
var messages = require('@langchain/core/messages');
|
|
8
8
|
var output_parsers = require('@langchain/core/output_parsers');
|
|
9
|
+
var testing = require('@langchain/core/utils/testing');
|
|
9
10
|
var agents = require('langchain/agents');
|
|
10
11
|
var tools = require('langchain/tools');
|
|
11
12
|
var textsplitters = require('@langchain/textsplitters');
|
|
@@ -66,12 +67,18 @@ class BaseChain {
|
|
|
66
67
|
this.llm = void 0;
|
|
67
68
|
this.chat_model = void 0;
|
|
68
69
|
this.runnable = void 0;
|
|
70
|
+
this.fakeLLM = new testing.FakeListChatModel({
|
|
71
|
+
responses: ['Hello, this is a fake response (There is no real LLM available)!', 'bootstrap main-llm with a real LLM instance', 'This is another fake response (There is no real LLM available)!']
|
|
72
|
+
});
|
|
69
73
|
this.container = container;
|
|
70
74
|
this._name = this.camelize(this.constructor.name);
|
|
71
75
|
this._description = this.snake_case(this.constructor.name);
|
|
72
|
-
this.llm = this.resolve('llm');
|
|
73
|
-
this._template = this.resolve('template');
|
|
76
|
+
this.llm = this.resolve('llm', this.fakeLLM);
|
|
77
|
+
this._template = this.resolve('template', '{input}');
|
|
74
78
|
this.chat_model = this.resolve('chat-model', false);
|
|
79
|
+
this.initializePrompt();
|
|
80
|
+
}
|
|
81
|
+
initializePrompt() {
|
|
75
82
|
if (this.chat_model) {
|
|
76
83
|
this.prompt = prompts.ChatPromptTemplate.fromTemplate(this._template);
|
|
77
84
|
} else {
|
|
@@ -96,11 +103,7 @@ class BaseChain {
|
|
|
96
103
|
}
|
|
97
104
|
set template(value) {
|
|
98
105
|
this._template = value;
|
|
99
|
-
|
|
100
|
-
this.prompt = prompts.ChatPromptTemplate.fromTemplate(this._template);
|
|
101
|
-
} else {
|
|
102
|
-
this.prompt = prompts.PromptTemplate.fromTemplate(this._template);
|
|
103
|
-
}
|
|
106
|
+
this.initializePrompt();
|
|
104
107
|
}
|
|
105
108
|
resolve(name, defaultValue = null) {
|
|
106
109
|
return mydi(this.container, this.camelize(this.constructor.name), name) || defaultValue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"medpromptjs.cjs.development.js","sources":["../src/mydi.ts","../src/chain.ts","../src/agent.ts","../src/tool.ts","../src/llm_loop.ts","../src/llm.ts","../src/embedding.ts"],"sourcesContent":["/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst mydi = (c: any, m: string, b: string) => {\n try {\n return c.resolve(m + '_' + b);\n } catch (e) { }\n try {\n return c.resolve(m + '-' + b);\n } catch (e) {}\n try {\n return c.resolve(b);\n } catch (e) {}\n return null;\n};\n\nexport default mydi;\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PromptTemplate, ChatPromptTemplate } from '@langchain/core/prompts';\nimport { LLM } from '@langchain/core/language_models/llms';\nimport mydi from './mydi';\nimport {\n RunnablePassthrough,\n RunnableSequence,\n} from '@langchain/core/runnables';\nimport { AIMessage } from '@langchain/core/messages';\nimport { StringOutputParser } from '@langchain/core/output_parsers';\n\nexport class BaseChain {\n container: any;\n private _name: string = '';\n private _description: string = '';\n private _template: string = '';\n prompt: any;\n llm: LLM;\n chat_model: boolean;\n runnable: any;\n\n constructor(container: any) {\n this.container = container;\n this._name = this.camelize(this.constructor.name);\n this._description = this.snake_case(this.constructor.name);\n this.llm = this.resolve('llm');\n this._template = this.resolve('template');\n this.chat_model = this.resolve('chat-model', false);\n if (this.chat_model) {\n this.prompt = ChatPromptTemplate.fromTemplate(this._template);\n } else {\n this.prompt = PromptTemplate.fromTemplate(this._template);\n }\n }\n\n // Getters and setters\n get name(): string {\n return this._name;\n }\n set name(value: string) {\n this._name = value === '' ? this.camelize(this.constructor.name) : value;\n }\n\n get description(): string {\n return this._description;\n }\n set description(value: string) {\n this._description =\n value === '' ? this.snake_case(this.constructor.name) : value;\n }\n\n get template(): string {\n return this._template;\n }\n set template(value: string) {\n this._template = value;\n if (this.chat_model) {\n this.prompt = ChatPromptTemplate.fromTemplate(this._template);\n } else {\n this.prompt = PromptTemplate.fromTemplate(this._template);\n }\n }\n\n resolve(name: string, defaultValue: any = null): any {\n return (\n mydi(this.container, this.camelize(this.constructor.name), name) ||\n defaultValue\n );\n }\n\n camelize(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n }\n\n snake_case(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();\n })\n .replace(/\\s+/g, '');\n }\n\n // https://js.langchain.com/v0.1/docs/expression_language/how_to/routing/\n //! Override this method\n async chain(input: any) {\n const outputParser = new StringOutputParser();\n this.runnable = RunnableSequence.from([\n {\n input: new RunnablePassthrough(),\n // context: async () => loadContextFromStore(),\n },\n this.prompt,\n this.llm,\n outputParser,\n ]);\n if (this.chat_model) {\n const response: string = await this.runnable.invoke(input);\n const aiMessage = new AIMessage(response);\n return aiMessage.content;\n }\n return await this.runnable.invoke(input);\n }\n\n async invoke(input: any) {\n return this.chain(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BaseChain } from './chain';\nimport type { ToolInterface } from '@langchain/core/tools';\nimport { createStructuredChatAgent, AgentExecutor } from 'langchain/agents';\n\nexport class BaseAgent extends BaseChain {\n private _tools: ToolInterface[] = [];\n\n\n get tools(): ToolInterface[] {\n return this._tools;\n }\n set tools(value: ToolInterface[]) {\n this._tools = value;\n }\n\n /**\n * Run the agent using the provided input.\n * This uses createStructuredChatAgent and AgentExecutor from langchain/agents.\n */\n async run(input: any) {\n const agent = await createStructuredChatAgent({\n llm: this.llm,\n tools: this._tools,\n prompt: this.prompt,\n });\n const agentExecutor = new AgentExecutor({\n agent: agent,\n tools: this.tools,\n // verbose: true,\n handleParsingErrors:\n 'Please try again, paying close attention to the final answer',\n });\n return await agentExecutor.invoke(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DynamicStructuredTool } from 'langchain/tools';\nimport mydi from './mydi';\n\nexport class BaseTool extends DynamicStructuredTool {\n /** @hidden */\n container: any;\n name: string;\n description: string;\n schema: any;\n constructor(\n container: any,\n name: string,\n description: string,\n schema: any,\n func: any = null\n ) {\n super({\n name: name,\n description: description,\n schema: schema,\n func: func,\n });\n this.container = container;\n this.name = name === '' ? this.camelize(this.constructor.name) : name;\n this.description =\n description === '' ? this.snake_case(this.constructor.name) : description;\n this.schema = schema;\n }\n\n func = async (args: any) => {\n return 'override this';\n };\n\n resolve(name: string) {\n return mydi(this.container, this.name, name);\n }\n\n camelize(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n }\n\n snake_case(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();\n })\n .replace(/\\s+/g, '');\n }\n\n /**\n * @param input - The input to process in batch.\n * @param config - The configuration for the batch.\n * @returns A promise resolving to an array of results.\n */\n async _batchWithConfig(input: any, config: any): Promise<any[]> {\n // Call the parent implementation or provide your own\n return super._batchWithConfig(input, config);\n }\n}\n","import { BaseChain } from './chain';\nimport { CharacterTextSplitter } from '@langchain/textsplitters';\nimport { Logger, ILogObj } from 'tslog';\n\nconst log: Logger<ILogObj> = new Logger();\nexport class LLMLoop extends BaseChain {\n // Implement the LLM loop logic here\n stringExpression: string = '';\n _mapQueryTemplate: string = `\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: `;\n\n _mapDocTemplate: string = `\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: `;\n\n _reduceChainTemplate: string = `\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: `;\n\n // Add getters and setters for the templates if needed\n get mapQueryTemplate(): string {\n return this._mapQueryTemplate;\n }\n set mapQueryTemplate(template: string) {\n this._mapQueryTemplate = template;\n }\n get mapDocTemplate(): string {\n return this._mapDocTemplate;\n }\n set mapDocTemplate(template: string) {\n this._mapDocTemplate = template;\n }\n get reduceChainTemplate(): string {\n return this._reduceChainTemplate;\n }\n set reduceChainTemplate(template: string) {\n this._reduceChainTemplate = template;\n }\n\n async checkAssertion(expression: string, context: any): Promise<boolean> {\n let _expression: string = '';\n try {\n // Check if expression is a valid JSON string\n _expression = this.printValues(JSON.parse(expression));\n } catch (error) {\n _expression = expression; // If not, use the expression as is\n }\n\n log.info(`Checking assertion with expression: ${_expression}`);\n // Initialize context and content\n let _context: any = undefined;\n let _content: string = '';\n try {\n _context = JSON.parse(context);\n } catch (error) {\n _context = context; // If not, use the context as is\n log.warn(`Context is not a valid JSON string: ${context}`);\n log.warn(`Using context as a string: ${_context}`);\n }\n try {\n // Check if context is a valid JSON string\n _context = JSON.parse(context);\n _context.forEach((element: any) => {\n element.content.forEach((contentItem: any) => {\n _content += atob(contentItem.attachment.data.value);\n });\n });\n } catch (error) {\n _content = context; // If not, use the context as is\n log.warn(`Context is not a valid JSON : ${context}`);\n log.warn(`Using context as a string: ${_content}`);\n }\n _content = this.findDatesAndConvertToTimeElapsed(\n _content.replace(/(\\r\\n|\\n|\\r)/gm, ' ')\n );\n log.info(`Checking assertion with context: ${_content}`);\n const _input = {\n input: {\n expression: _expression,\n context: _content,\n },\n };\n const result = await this.chain(_input);\n log.info(`Assertion check result: ${result}`);\n return result;\n }\n\n async checkMention(expression: string, context: any): Promise<boolean> {\n if (expression && context) return true; // Placeholder for assertion check logic\n return false;\n }\n\n async checkNegation(expression: string, context: any): Promise<boolean> {\n if (expression && context) return true; // Placeholder for assertion check logic\n return false;\n }\n\n findDatesAndConvertToTimeElapsed(text: string): string {\n // Regular expression to match dates in format of 'mm/dd/yyyy' or 'mm-dd-yyyy'\n const dateRegex = /(\\d{1,2}[-/]\\d{1,2}[-/]\\d{4})/g;\n let matches;\n let currentDate = new Date();\n\n while ((matches = dateRegex.exec(text)) !== null) {\n let date = new Date(matches[0]);\n let timeElapsed =\n (currentDate.getTime() - date.getTime()) / (1000 * 60 * 60 * 24);\n text = text.replace(\n matches[0],\n Math.floor(timeElapsed).toString() + ' days ago.'\n );\n }\n return text;\n }\n\n camelToString(camelCase: string): string {\n return camelCase.replace(/([A-Z])/g, ' $1').replace(/^./, function (str) {\n return str.toUpperCase();\n });\n }\n\n stringToBoolean(str: string): boolean {\n log.info(`Converting string to boolean: ${str}`);\n const positiveKeywords = [\n 'true',\n 'contains',\n 'confirms',\n 'yes',\n 'affirmative',\n 'matches',\n 'exists',\n 'present',\n 'absolutely',\n 'certainly',\n 'definitely',\n 'indeed',\n 'did have',\n 'showed',\n 'revealed',\n ];\n const lowerStr = str.toLowerCase();\n return positiveKeywords.some((keyword) => lowerStr.includes(keyword));\n }\n\n async textSplitter(\n text: string,\n chunkSize: number = 3900,\n chunkOverlap: number = 0\n ): Promise<string[]> {\n const textSplitter = new CharacterTextSplitter({\n chunkSize: chunkSize,\n chunkOverlap: chunkOverlap,\n });\n const texts = await textSplitter.splitText(text);\n // Log the number of chunks created\n if (texts.length === 0) {\n log.warn('No text chunks created. Please check the input text.');\n return [];\n }\n if (texts.length > 100) {\n log.warn(\n `Warning: More than 100 text chunks created (${texts.length}). This may affect performance.`\n );\n }\n if (chunkSize < 1000) {\n log.warn(\n `Warning: Chunk size is less than 1000 characters (${chunkSize}). This may lead to very small chunks.`\n );\n }\n log.info(\n `Text split into ${texts.length} chunks with size ${chunkSize} and overlap ${chunkOverlap}`\n );\n return texts;\n }\n\n printValues(obj: any) {\n log.info(`Processing Rule: ${obj.name} for ${obj.context}`);\n // For each obj.expression:arg:where\n if (obj.expression && obj.expression.arg && obj.expression.arg.where) {\n // for each args in obj.expression.arg.where, extract the nested key called \"value\"\n const statements = this.extractObjectsByKey(\n obj.expression.arg.where,\n 'value'\n );\n return statements.join(' ').replace(/,/g, ' ');\n }\n // return statements array as a string seperated by space\n return '';\n }\n\n extractObjectsByKey(obj: any, key: string): any[] {\n const results: any[] = [];\n\n function traverse(obj: any) {\n for (const currentKey in obj) {\n if (obj.hasOwnProperty(currentKey)) {\n if (currentKey === key) {\n results.push(obj[currentKey]);\n }\n if (typeof obj[currentKey] === 'object' && obj[currentKey] !== null) {\n traverse(obj[currentKey]);\n }\n }\n }\n }\n\n traverse(obj);\n return results;\n }\n\n _printValues(obj: any) {\n for (var key in obj) {\n if (typeof obj[key] === 'object') {\n this._printValues(obj[key]);\n } else {\n this.stringExpression += obj[key] + ' ';\n }\n }\n const _eliminate = [\n 'true',\n 'false',\n 'null',\n 'undefined',\n 'String',\n 'Number',\n 'Object',\n 'Array',\n 'Boolean',\n 'value',\n 'Type',\n 'Specifier',\n 'Named',\n ];\n _eliminate.forEach((element) => {\n const regex = new RegExp(element, 'g');\n this.stringExpression = this.stringExpression.replace(regex, '');\n });\n this.stringExpression = this.stringExpression.replace(\n /(?:https?|ftp):\\/\\/[\\n\\S]+/g,\n ''\n );\n return this.camelToString(this.stringExpression);\n }\n\n async chain(input: any) {\n // Create a chain using RunnableSequence, RunnablePassthrough and RunnableParallel\n // input has two properties: expression and context\n // expression goes through mapQuery and parallely\n // context goes through textSplitter and mapDoc\n // Finally reduceChain is called with the results of mapQuery and mapDoc\n // LCEL-based implementation using RunnableSequence, RunnableParallel, and RunnablePassthrough\n const { RunnableSequence, RunnableParallel, RunnablePassthrough } =\n await import('@langchain/core/runnables');\n\n const mapQuery: BaseChain = new BaseChain(this.container);\n const mapDoc: BaseChain = new BaseChain(this.container);\n const reduceChain: BaseChain = new BaseChain(this.container);\n mapQuery.name = 'MapQuery';\n mapQuery.description = 'Map the expression to a natural language query.';\n mapQuery.template = this.resolve('litl_mapquery_template', this._mapQueryTemplate);\n mapDoc.name = 'MapDoc';\n mapDoc.description = 'Map the document to a set of facts.';\n mapDoc.template = this.resolve('litl_mapdoc_template', this._mapDocTemplate);\n reduceChain.name = 'ReduceChain';\n reduceChain.description = 'Reduce a set of documents to binary answer.';\n reduceChain.template = this.resolve('litl_reduce_chain_template', this._reduceChainTemplate);\n const mapQueryChain = RunnablePassthrough.assign({\n query: async (input: any) =>\n mapQuery.chain({ expression: input.input.expression }),\n });\n\n const mapDocChain = RunnablePassthrough.assign({\n documents: async (input: any) => {\n const textChunks = await this.textSplitter(input.input.context);\n return Promise.all(\n textChunks.map((chunk) =>\n mapDoc.chain({\n document: chunk,\n statements: input.input.expression,\n })\n )\n );\n },\n });\n\n const parallelChain = RunnableParallel.from([mapQueryChain, mapDocChain]);\n\n const sequence = RunnableSequence.from([\n parallelChain,\n async (results: any) => {\n /* results is an array: [{ query: ... }, { documents: [...] }]\n{\n \"0\": {\n \"input\": {\n \"expression\": \"0 Visual foot exam showed active infection?\",\n \"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. \"\n },\n \"query\": \"The text indicates a question about whether a visual foot exam revealed an active infection.\\n\"\n },\n \"1\": {\n \"input\": {\n \"expression\": \"0 Visual foot exam showed active infection?\",\n \"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. \"\n },\n \"documents\": [\n \"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\"\n ]\n }\n}\n */\n log.info(`Results from parallel chain: ${JSON.stringify(results)}`);\n const expression = results[0].input.expression;\n const query = results[0].query;\n const documents = results[1].documents;\n return reduceChain.chain({\n facts: documents,\n query: query + ' ' + expression,\n });\n },\n (result: any) => this.stringToBoolean(result),\n ]);\n\n return sequence.invoke(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLM, type BaseLLMParams } from '@langchain/core/language_models/llms';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\n\n/**\n * Model parameters for BaseLLM\n */\nexport interface ModelParams {\n maxOutputTokens?: number;\n nPredict?: number;\n topK?: number;\n topP?: number;\n temperature?: number;\n nBatch?: number;\n repeatPenalty?: number;\n repeatLastN?: number;\n}\n\n/**\n * Parameters for configuring BaseLLM\n */\nexport interface BaseLLMInput extends BaseLLMParams {\n baseUrl: string;\n model: string;\n apiKey?: string;\n timeout?: number;\n backend?: string;\n temperature?: number;\n topP?: number;\n topK?: number;\n nBatch?: number;\n nThreads?: number;\n nPredict?: number;\n maxOutputTokens?: number;\n repeatLastN?: number;\n repeatPenalty?: number;\n}\n\n/**\n * BaseLLM is a base class for LLMs that communicate with a remote API.\n * It extends the LangChain LLM class and provides configurable parameters\n * for model inference.\n */\nexport class BaseLLM extends LLM {\n baseUrl: string;\n model: string;\n apiKey: string;\n timeout: number;\n backend: string;\n temperature: number;\n topP: number;\n topK: number;\n nBatch: number;\n nThreads: number;\n nPredict: number;\n maxOutputTokens: number;\n repeatLastN: number;\n repeatPenalty: number;\n\n constructor(fields: BaseLLMInput) {\n super(fields);\n this.baseUrl = fields.baseUrl;\n this.model = fields.model;\n this.apiKey = fields.apiKey ?? '';\n this.timeout = fields.timeout ?? 60000;\n this.backend = fields.backend ?? 'dhti';\n this.temperature = fields.temperature ?? 0.1;\n this.topP = fields.topP ?? 0.8;\n this.topK = fields.topK ?? 40;\n this.nBatch = fields.nBatch ?? 8;\n this.nThreads = fields.nThreads ?? 4;\n this.nPredict = fields.nPredict ?? 256;\n this.maxOutputTokens = fields.maxOutputTokens ?? 512;\n this.repeatLastN = fields.repeatLastN ?? 64;\n this.repeatPenalty = fields.repeatPenalty ?? 1.18;\n }\n\n /**\n * Get the model default parameters\n */\n get modelDefaultParameters(): ModelParams {\n return {\n maxOutputTokens: this.maxOutputTokens,\n nPredict: this.nPredict,\n topK: this.topK,\n topP: this.topP,\n temperature: this.temperature,\n nBatch: this.nBatch,\n repeatPenalty: this.repeatPenalty,\n repeatLastN: this.repeatLastN,\n };\n }\n\n /**\n * Get the identifying parameters\n */\n get identifyingParams(): Record<string, unknown> {\n return {\n model: this.model,\n baseUrl: this.baseUrl,\n modelParameters: this.modelDefaultParameters,\n };\n }\n\n /**\n * Get the LLM type identifier\n */\n _llmType(): string {\n return 'dhti';\n }\n\n /**\n * Prepare the request payload for the API\n */\n protected preparePayload(prompt: string): Record<string, unknown> {\n return {\n model: this.model,\n options: this.modelDefaultParameters,\n messages: [{ role: 'user', content: prompt }],\n };\n }\n\n /**\n * Make the API call to generate text\n */\n async _call(\n prompt: string,\n _options: this['ParsedCallOptions'],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<string> {\n const payload = this.preparePayload(prompt);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(this.baseUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(\n `API request failed: status=${response.status}; body=${body}`\n );\n }\n\n const data = await response.json();\n\n // Expecting structure like: { \"choices\": [ { \"message\": { \"role\":\"assistant\",\"content\":\"...\" } } ] }\n // Adapt this path if the API differs\n if (\n data.choices &&\n Array.isArray(data.choices) &&\n data.choices.length > 0\n ) {\n const choice = data.choices[0];\n // support both \"message\" and direct \"text\"\n if (\n typeof choice === 'object' &&\n choice !== null &&\n 'message' in choice &&\n typeof choice.message === 'object' &&\n choice.message !== null\n ) {\n const content = (choice.message as Record<string, unknown>).content;\n if (typeof content === 'string') {\n return content;\n }\n } else if ('text' in choice) {\n const text = choice.text;\n if (typeof text === 'string') {\n return text;\n }\n }\n }\n\n // Fallback: return raw JSON string for debugging\n return JSON.stringify(data);\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === 'AbortError') {\n throw new Error(`API request timed out after ${this.timeout}ms`);\n }\n throw error;\n }\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Embeddings, type EmbeddingsParams } from '@langchain/core/embeddings';\n\n/**\n * Parameters for configuring BaseEmbedding\n */\nexport interface BaseEmbeddingInput extends EmbeddingsParams {\n baseUrl: string;\n model: string;\n apiKey?: string;\n}\n\n/**\n * BaseEmbedding is a base class for embeddings that communicate with a remote API.\n * It extends the LangChain Embeddings class and provides methods for embedding\n * documents and queries.\n */\nexport class BaseEmbedding extends Embeddings {\n baseUrl: string;\n model: string;\n apiKey: string;\n\n constructor(fields: BaseEmbeddingInput) {\n super(fields);\n this.baseUrl = fields.baseUrl;\n this.model = fields.model;\n this.apiKey = fields.apiKey ?? '';\n }\n\n /**\n * Embed a list of documents\n * @param texts - Array of strings to embed\n * @returns Promise of array of embedding vectors\n */\n async embedDocuments(texts: string[]): Promise<number[][]> {\n return this.getEmbeddings(texts);\n }\n\n /**\n * Embed a single query\n * @param text - String to embed\n * @returns Promise of embedding vector\n */\n async embedQuery(text: string): Promise<number[]> {\n const embeddings = await this.getEmbeddings([text]);\n return embeddings[0];\n }\n\n /**\n * Helper method to get embeddings for a list of texts\n * @param texts - Array of strings to embed\n * @returns Promise of array of embedding vectors\n */\n protected async getEmbeddings(texts: string[]): Promise<number[][]> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n\n const payload = {\n model: this.model,\n input: texts,\n };\n\n const response = await fetch(this.baseUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(\n `API request failed: status=${response.status}; body=${body}`\n );\n }\n\n const respJson = await response.json();\n\n if (!('embeddings' in respJson)) {\n throw new Error(\n `API response missing 'embeddings' key. Received keys: ${Object.keys(\n respJson\n ).join(', ')}`\n );\n }\n\n return respJson.embeddings as number[][];\n }\n}\n"],"names":["mydi","c","m","b","resolve","e","BaseChain","constructor","container","_name","_description","_template","prompt","llm","chat_model","runnable","camelize","name","snake_case","ChatPromptTemplate","fromTemplate","PromptTemplate","value","description","template","defaultValue","str","replace","word","index","toLowerCase","toUpperCase","chain","input","outputParser","StringOutputParser","RunnableSequence","from","RunnablePassthrough","response","invoke","aiMessage","AIMessage","content","BaseAgent","args","_tools","tools","run","agent","createStructuredChatAgent","agentExecutor","AgentExecutor","handleParsingErrors","BaseTool","DynamicStructuredTool","schema","func","_batchWithConfig","config","log","Logger","LLMLoop","stringExpression","_mapQueryTemplate","_mapDocTemplate","_reduceChainTemplate","mapQueryTemplate","mapDocTemplate","reduceChainTemplate","checkAssertion","expression","context","_expression","printValues","JSON","parse","error","info","_context","undefined","_content","warn","forEach","element","contentItem","atob","attachment","data","findDatesAndConvertToTimeElapsed","_input","result","checkMention","checkNegation","text","dateRegex","matches","currentDate","Date","exec","date","timeElapsed","getTime","Math","floor","toString","camelToString","camelCase","stringToBoolean","positiveKeywords","lowerStr","some","keyword","includes","textSplitter","chunkSize","chunkOverlap","CharacterTextSplitter","texts","splitText","length","obj","arg","where","statements","extractObjectsByKey","join","key","results","traverse","currentKey","hasOwnProperty","push","_printValues","_eliminate","regex","RegExp","RunnableParallel","mapQuery","mapDoc","reduceChain","mapQueryChain","assign","query","mapDocChain","documents","textChunks","Promise","all","map","chunk","document","parallelChain","sequence","stringify","facts","BaseLLM","LLM","fields","_fields$apiKey","_fields$timeout","_fields$backend","_fields$temperature","_fields$topP","_fields$topK","_fields$nBatch","_fields$nThreads","_fields$nPredict","_fields$maxOutputToke","_fields$repeatLastN","_fields$repeatPenalty","baseUrl","model","apiKey","timeout","backend","temperature","topP","topK","nBatch","nThreads","nPredict","maxOutputTokens","repeatLastN","repeatPenalty","modelDefaultParameters","identifyingParams","modelParameters","_llmType","preparePayload","options","messages","role","_call","_options","_runManager","payload","headers","controller","AbortController","timeoutId","setTimeout","abort","fetch","method","body","signal","clearTimeout","ok","Error","status","json","choices","Array","isArray","choice","message","BaseEmbedding","Embeddings","embedDocuments","getEmbeddings","embedQuery","embeddings","respJson","Object","keys"],"mappings":";;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;AAcG;AAEH,MAAMA,IAAI,GAAGA,CAACC,CAAM,EAAEC,CAAS,EAAEC,CAAS,KAAI;EAC5C,IAAI;IACF,OAAOF,CAAC,CAACG,OAAO,CAACF,CAAC,GAAG,GAAG,GAAGC,CAAC,CAAC,CAAA;AAC/B,GAAC,CAAC,OAAOE,CAAC,EAAE,EAAE;EACd,IAAI;IACF,OAAOJ,CAAC,CAACG,OAAO,CAACF,CAAC,GAAG,GAAG,GAAGC,CAAC,CAAC,CAAA;AAC/B,GAAC,CAAC,OAAOE,CAAC,EAAE,EAAC;EACb,IAAI;AACF,IAAA,OAAOJ,CAAC,CAACG,OAAO,CAACD,CAAC,CAAC,CAAA;AACrB,GAAC,CAAC,OAAOE,CAAC,EAAE,EAAC;AACb,EAAA,OAAO,IAAI,CAAA;AACb,CAAC;;AC3BD;;;;;;;;;;;;;;AAcG;MAYUC,SAAS,CAAA;EAUpBC,WAAAA,CAAYC,SAAc,EAAA;AAAA,IAAA,IAAA,CAT1BA,SAAS,GAAA,KAAA,CAAA,CAAA;IAAA,IACDC,CAAAA,KAAK,GAAW,EAAE,CAAA;IAAA,IAClBC,CAAAA,YAAY,GAAW,EAAE,CAAA;IAAA,IACzBC,CAAAA,SAAS,GAAW,EAAE,CAAA;AAAA,IAAA,IAAA,CAC9BC,MAAM,GAAA,KAAA,CAAA,CAAA;AAAA,IAAA,IAAA,CACNC,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ACyK,EAAE,EAAE;AAChB,MAAA,MAAMH,IAAI,GAAG,MAAMtK,QAAQ,CAACuD,IAAI,EAAE,CAAA;MAClC,MAAM,IAAImH,KAAK,CACb,CAA8B1K,2BAAAA,EAAAA,QAAQ,CAAC2K,MAAM,CAAA,OAAA,EAAUL,IAAI,CAAA,CAAE,CAC9D,CAAA;AACH,KAAA;AAEA,IAAA,MAAMkB,QAAQ,GAAG,MAAMxL,QAAQ,CAAC4K,IAAI,EAAE,CAAA;AAEtC,IAAA,IAAI,EAAE,YAAY,IAAIY,QAAQ,CAAC,EAAE;AAC/B,MAAA,MAAM,IAAId,KAAK,CACb,CAAyDe,sDAAAA,EAAAA,MAAM,CAACC,IAAI,CAClEF,QAAQ,CACT,CAACjG,IAAI,CAAC,IAAI,CAAC,EAAE,CACf,CAAA;AACH,KAAA;IAEA,OAAOiG,QAAQ,CAACD,UAAwB,CAAA;AAC1C,GAAA;AACD;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"medpromptjs.cjs.development.js","sources":["../src/mydi.ts","../src/chain.ts","../src/agent.ts","../src/tool.ts","../src/llm_loop.ts","../src/llm.ts","../src/embedding.ts"],"sourcesContent":["/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst mydi = (c: any, m: string, b: string) => {\n try {\n return c.resolve(m + '_' + b);\n } catch (e) { }\n try {\n return c.resolve(m + '-' + b);\n } catch (e) {}\n try {\n return c.resolve(b);\n } catch (e) {}\n return null;\n};\n\nexport default mydi;\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PromptTemplate, ChatPromptTemplate } from '@langchain/core/prompts';\nimport { LLM } from '@langchain/core/language_models/llms';\nimport mydi from './mydi';\nimport {\n RunnablePassthrough,\n RunnableSequence,\n} from '@langchain/core/runnables';\nimport { AIMessage } from '@langchain/core/messages';\nimport { StringOutputParser } from '@langchain/core/output_parsers';\nimport { FakeListChatModel } from '@langchain/core/utils/testing';\n\nexport class BaseChain {\n container: any;\n private _name: string = '';\n private _description: string = '';\n private _template: string = '';\n prompt: any;\n llm: LLM;\n chat_model: boolean;\n runnable: any;\n fakeLLM: FakeListChatModel = new FakeListChatModel({\n responses: [\n 'Hello, this is a fake response (There is no real LLM available)!',\n 'bootstrap main-llm with a real LLM instance',\n 'This is another fake response (There is no real LLM available)!',\n ],\n });\n\n constructor(container: any) {\n this.container = container;\n this._name = this.camelize(this.constructor.name);\n this._description = this.snake_case(this.constructor.name);\n this.llm = this.resolve('llm', this.fakeLLM);\n this._template = this.resolve('template', '{input}');\n this.chat_model = this.resolve('chat-model', false);\n this.initializePrompt();\n }\n\n initializePrompt() {\n if (this.chat_model) {\n this.prompt = ChatPromptTemplate.fromTemplate(this._template);\n } else {\n this.prompt = PromptTemplate.fromTemplate(this._template);\n }\n }\n // Getters and setters\n get name(): string {\n return this._name;\n }\n set name(value: string) {\n this._name = value === '' ? this.camelize(this.constructor.name) : value;\n }\n\n get description(): string {\n return this._description;\n }\n set description(value: string) {\n this._description =\n value === '' ? this.snake_case(this.constructor.name) : value;\n }\n\n get template(): string {\n return this._template;\n }\n set template(value: string) {\n this._template = value;\n this.initializePrompt();\n }\n\n resolve(name: string, defaultValue: any = null): any {\n return (\n mydi(this.container, this.camelize(this.constructor.name), name) ||\n defaultValue\n );\n }\n\n camelize(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n }\n\n snake_case(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();\n })\n .replace(/\\s+/g, '');\n }\n\n // https://js.langchain.com/v0.1/docs/expression_language/how_to/routing/\n //! Override this method\n async chain(input: any) {\n const outputParser = new StringOutputParser();\n this.runnable = RunnableSequence.from([\n {\n input: new RunnablePassthrough(),\n // context: async () => loadContextFromStore(),\n },\n this.prompt,\n this.llm,\n outputParser,\n ]);\n if (this.chat_model) {\n const response: string = await this.runnable.invoke(input);\n const aiMessage = new AIMessage(response);\n return aiMessage.content;\n }\n return await this.runnable.invoke(input);\n }\n\n async invoke(input: any) {\n return this.chain(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BaseChain } from './chain';\nimport type { ToolInterface } from '@langchain/core/tools';\nimport { createStructuredChatAgent, AgentExecutor } from 'langchain/agents';\n\nexport class BaseAgent extends BaseChain {\n private _tools: ToolInterface[] = [];\n\n\n get tools(): ToolInterface[] {\n return this._tools;\n }\n set tools(value: ToolInterface[]) {\n this._tools = value;\n }\n\n /**\n * Run the agent using the provided input.\n * This uses createStructuredChatAgent and AgentExecutor from langchain/agents.\n */\n async run(input: any) {\n const agent = await createStructuredChatAgent({\n llm: this.llm,\n tools: this._tools,\n prompt: this.prompt,\n });\n const agentExecutor = new AgentExecutor({\n agent: agent,\n tools: this.tools,\n // verbose: true,\n handleParsingErrors:\n 'Please try again, paying close attention to the final answer',\n });\n return await agentExecutor.invoke(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DynamicStructuredTool } from 'langchain/tools';\nimport mydi from './mydi';\n\nexport class BaseTool extends DynamicStructuredTool {\n /** @hidden */\n container: any;\n name: string;\n description: string;\n schema: any;\n constructor(\n container: any,\n name: string,\n description: string,\n schema: any,\n func: any = null\n ) {\n super({\n name: name,\n description: description,\n schema: schema,\n func: func,\n });\n this.container = container;\n this.name = name === '' ? this.camelize(this.constructor.name) : name;\n this.description =\n description === '' ? this.snake_case(this.constructor.name) : description;\n this.schema = schema;\n }\n\n func = async (args: any) => {\n return 'override this';\n };\n\n resolve(name: string) {\n return mydi(this.container, this.name, name);\n }\n\n camelize(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n }\n\n snake_case(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();\n })\n .replace(/\\s+/g, '');\n }\n\n /**\n * @param input - The input to process in batch.\n * @param config - The configuration for the batch.\n * @returns A promise resolving to an array of results.\n */\n async _batchWithConfig(input: any, config: any): Promise<any[]> {\n // Call the parent implementation or provide your own\n return super._batchWithConfig(input, config);\n }\n}\n","import { BaseChain } from './chain';\nimport { CharacterTextSplitter } from '@langchain/textsplitters';\nimport { Logger, ILogObj } from 'tslog';\n\nconst log: Logger<ILogObj> = new Logger();\nexport class LLMLoop extends BaseChain {\n // Implement the LLM loop logic here\n stringExpression: string = '';\n _mapQueryTemplate: string = `\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: `;\n\n _mapDocTemplate: string = `\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: `;\n\n _reduceChainTemplate: string = `\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: `;\n\n // Add getters and setters for the templates if needed\n get mapQueryTemplate(): string {\n return this._mapQueryTemplate;\n }\n set mapQueryTemplate(template: string) {\n this._mapQueryTemplate = template;\n }\n get mapDocTemplate(): string {\n return this._mapDocTemplate;\n }\n set mapDocTemplate(template: string) {\n this._mapDocTemplate = template;\n }\n get reduceChainTemplate(): string {\n return this._reduceChainTemplate;\n }\n set reduceChainTemplate(template: string) {\n this._reduceChainTemplate = template;\n }\n\n async checkAssertion(expression: string, context: any): Promise<boolean> {\n let _expression: string = '';\n try {\n // Check if expression is a valid JSON string\n _expression = this.printValues(JSON.parse(expression));\n } catch (error) {\n _expression = expression; // If not, use the expression as is\n }\n\n log.info(`Checking assertion with expression: ${_expression}`);\n // Initialize context and content\n let _context: any = undefined;\n let _content: string = '';\n try {\n _context = JSON.parse(context);\n } catch (error) {\n _context = context; // If not, use the context as is\n log.warn(`Context is not a valid JSON string: ${context}`);\n log.warn(`Using context as a string: ${_context}`);\n }\n try {\n // Check if context is a valid JSON string\n _context = JSON.parse(context);\n _context.forEach((element: any) => {\n element.content.forEach((contentItem: any) => {\n _content += atob(contentItem.attachment.data.value);\n });\n });\n } catch (error) {\n _content = context; // If not, use the context as is\n log.warn(`Context is not a valid JSON : ${context}`);\n log.warn(`Using context as a string: ${_content}`);\n }\n _content = this.findDatesAndConvertToTimeElapsed(\n _content.replace(/(\\r\\n|\\n|\\r)/gm, ' ')\n );\n log.info(`Checking assertion with context: ${_content}`);\n const _input = {\n input: {\n expression: _expression,\n context: _content,\n },\n };\n const result = await this.chain(_input);\n log.info(`Assertion check result: ${result}`);\n return result;\n }\n\n async checkMention(expression: string, context: any): Promise<boolean> {\n if (expression && context) return true; // Placeholder for assertion check logic\n return false;\n }\n\n async checkNegation(expression: string, context: any): Promise<boolean> {\n if (expression && context) return true; // Placeholder for assertion check logic\n return false;\n }\n\n findDatesAndConvertToTimeElapsed(text: string): string {\n // Regular expression to match dates in format of 'mm/dd/yyyy' or 'mm-dd-yyyy'\n const dateRegex = /(\\d{1,2}[-/]\\d{1,2}[-/]\\d{4})/g;\n let matches;\n let currentDate = new Date();\n\n while ((matches = dateRegex.exec(text)) !== null) {\n let date = new Date(matches[0]);\n let timeElapsed =\n (currentDate.getTime() - date.getTime()) / (1000 * 60 * 60 * 24);\n text = text.replace(\n matches[0],\n Math.floor(timeElapsed).toString() + ' days ago.'\n );\n }\n return text;\n }\n\n camelToString(camelCase: string): string {\n return camelCase.replace(/([A-Z])/g, ' $1').replace(/^./, function (str) {\n return str.toUpperCase();\n });\n }\n\n stringToBoolean(str: string): boolean {\n log.info(`Converting string to boolean: ${str}`);\n const positiveKeywords = [\n 'true',\n 'contains',\n 'confirms',\n 'yes',\n 'affirmative',\n 'matches',\n 'exists',\n 'present',\n 'absolutely',\n 'certainly',\n 'definitely',\n 'indeed',\n 'did have',\n 'showed',\n 'revealed',\n ];\n const lowerStr = str.toLowerCase();\n return positiveKeywords.some((keyword) => lowerStr.includes(keyword));\n }\n\n async textSplitter(\n text: string,\n chunkSize: number = 3900,\n chunkOverlap: number = 0\n ): Promise<string[]> {\n const textSplitter = new CharacterTextSplitter({\n chunkSize: chunkSize,\n chunkOverlap: chunkOverlap,\n });\n const texts = await textSplitter.splitText(text);\n // Log the number of chunks created\n if (texts.length === 0) {\n log.warn('No text chunks created. Please check the input text.');\n return [];\n }\n if (texts.length > 100) {\n log.warn(\n `Warning: More than 100 text chunks created (${texts.length}). This may affect performance.`\n );\n }\n if (chunkSize < 1000) {\n log.warn(\n `Warning: Chunk size is less than 1000 characters (${chunkSize}). This may lead to very small chunks.`\n );\n }\n log.info(\n `Text split into ${texts.length} chunks with size ${chunkSize} and overlap ${chunkOverlap}`\n );\n return texts;\n }\n\n printValues(obj: any) {\n log.info(`Processing Rule: ${obj.name} for ${obj.context}`);\n // For each obj.expression:arg:where\n if (obj.expression && obj.expression.arg && obj.expression.arg.where) {\n // for each args in obj.expression.arg.where, extract the nested key called \"value\"\n const statements = this.extractObjectsByKey(\n obj.expression.arg.where,\n 'value'\n );\n return statements.join(' ').replace(/,/g, ' ');\n }\n // return statements array as a string seperated by space\n return '';\n }\n\n extractObjectsByKey(obj: any, key: string): any[] {\n const results: any[] = [];\n\n function traverse(obj: any) {\n for (const currentKey in obj) {\n if (obj.hasOwnProperty(currentKey)) {\n if (currentKey === key) {\n results.push(obj[currentKey]);\n }\n if (typeof obj[currentKey] === 'object' && obj[currentKey] !== null) {\n traverse(obj[currentKey]);\n }\n }\n }\n }\n\n traverse(obj);\n return results;\n }\n\n _printValues(obj: any) {\n for (var key in obj) {\n if (typeof obj[key] === 'object') {\n this._printValues(obj[key]);\n } else {\n this.stringExpression += obj[key] + ' ';\n }\n }\n const _eliminate = [\n 'true',\n 'false',\n 'null',\n 'undefined',\n 'String',\n 'Number',\n 'Object',\n 'Array',\n 'Boolean',\n 'value',\n 'Type',\n 'Specifier',\n 'Named',\n ];\n _eliminate.forEach((element) => {\n const regex = new RegExp(element, 'g');\n this.stringExpression = this.stringExpression.replace(regex, '');\n });\n this.stringExpression = this.stringExpression.replace(\n /(?:https?|ftp):\\/\\/[\\n\\S]+/g,\n ''\n );\n return this.camelToString(this.stringExpression);\n }\n\n async chain(input: any) {\n // Create a chain using RunnableSequence, RunnablePassthrough and RunnableParallel\n // input has two properties: expression and context\n // expression goes through mapQuery and parallely\n // context goes through textSplitter and mapDoc\n // Finally reduceChain is called with the results of mapQuery and mapDoc\n // LCEL-based implementation using RunnableSequence, RunnableParallel, and RunnablePassthrough\n const { RunnableSequence, RunnableParallel, RunnablePassthrough } =\n await import('@langchain/core/runnables');\n\n const mapQuery: BaseChain = new BaseChain(this.container);\n const mapDoc: BaseChain = new BaseChain(this.container);\n const reduceChain: BaseChain = new BaseChain(this.container);\n mapQuery.name = 'MapQuery';\n mapQuery.description = 'Map the expression to a natural language query.';\n mapQuery.template = this.resolve('litl_mapquery_template', this._mapQueryTemplate);\n mapDoc.name = 'MapDoc';\n mapDoc.description = 'Map the document to a set of facts.';\n mapDoc.template = this.resolve('litl_mapdoc_template', this._mapDocTemplate);\n reduceChain.name = 'ReduceChain';\n reduceChain.description = 'Reduce a set of documents to binary answer.';\n reduceChain.template = this.resolve('litl_reduce_chain_template', this._reduceChainTemplate);\n const mapQueryChain = RunnablePassthrough.assign({\n query: async (input: any) =>\n mapQuery.chain({ expression: input.input.expression }),\n });\n\n const mapDocChain = RunnablePassthrough.assign({\n documents: async (input: any) => {\n const textChunks = await this.textSplitter(input.input.context);\n return Promise.all(\n textChunks.map((chunk) =>\n mapDoc.chain({\n document: chunk,\n statements: input.input.expression,\n })\n )\n );\n },\n });\n\n const parallelChain = RunnableParallel.from([mapQueryChain, mapDocChain]);\n\n const sequence = RunnableSequence.from([\n parallelChain,\n async (results: any) => {\n /* results is an array: [{ query: ... }, { documents: [...] }]\n{\n \"0\": {\n \"input\": {\n \"expression\": \"0 Visual foot exam showed active infection?\",\n \"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. \"\n },\n \"query\": \"The text indicates a question about whether a visual foot exam revealed an active infection.\\n\"\n },\n \"1\": {\n \"input\": {\n \"expression\": \"0 Visual foot exam showed active infection?\",\n \"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. \"\n },\n \"documents\": [\n \"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\"\n ]\n }\n}\n */\n log.info(`Results from parallel chain: ${JSON.stringify(results)}`);\n const expression = results[0].input.expression;\n const query = results[0].query;\n const documents = results[1].documents;\n return reduceChain.chain({\n facts: documents,\n query: query + ' ' + expression,\n });\n },\n (result: any) => this.stringToBoolean(result),\n ]);\n\n return sequence.invoke(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLM, type BaseLLMParams } from '@langchain/core/language_models/llms';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\n\n/**\n * Model parameters for BaseLLM\n */\nexport interface ModelParams {\n maxOutputTokens?: number;\n nPredict?: number;\n topK?: number;\n topP?: number;\n temperature?: number;\n nBatch?: number;\n repeatPenalty?: number;\n repeatLastN?: number;\n}\n\n/**\n * Parameters for configuring BaseLLM\n */\nexport interface BaseLLMInput extends BaseLLMParams {\n baseUrl: string;\n model: string;\n apiKey?: string;\n timeout?: number;\n backend?: string;\n temperature?: number;\n topP?: number;\n topK?: number;\n nBatch?: number;\n nThreads?: number;\n nPredict?: number;\n maxOutputTokens?: number;\n repeatLastN?: number;\n repeatPenalty?: number;\n}\n\n/**\n * BaseLLM is a base class for LLMs that communicate with a remote API.\n * It extends the LangChain LLM class and provides configurable parameters\n * for model inference.\n */\nexport class BaseLLM extends LLM {\n baseUrl: string;\n model: string;\n apiKey: string;\n timeout: number;\n backend: string;\n temperature: number;\n topP: number;\n topK: number;\n nBatch: number;\n nThreads: number;\n nPredict: number;\n maxOutputTokens: number;\n repeatLastN: number;\n repeatPenalty: number;\n\n constructor(fields: BaseLLMInput) {\n super(fields);\n this.baseUrl = fields.baseUrl;\n this.model = fields.model;\n this.apiKey = fields.apiKey ?? '';\n this.timeout = fields.timeout ?? 60000;\n this.backend = fields.backend ?? 'dhti';\n this.temperature = fields.temperature ?? 0.1;\n this.topP = fields.topP ?? 0.8;\n this.topK = fields.topK ?? 40;\n this.nBatch = fields.nBatch ?? 8;\n this.nThreads = fields.nThreads ?? 4;\n this.nPredict = fields.nPredict ?? 256;\n this.maxOutputTokens = fields.maxOutputTokens ?? 512;\n this.repeatLastN = fields.repeatLastN ?? 64;\n this.repeatPenalty = fields.repeatPenalty ?? 1.18;\n }\n\n /**\n * Get the model default parameters\n */\n get modelDefaultParameters(): ModelParams {\n return {\n maxOutputTokens: this.maxOutputTokens,\n nPredict: this.nPredict,\n topK: this.topK,\n topP: this.topP,\n temperature: this.temperature,\n nBatch: this.nBatch,\n repeatPenalty: this.repeatPenalty,\n repeatLastN: this.repeatLastN,\n };\n }\n\n /**\n * Get the identifying parameters\n */\n get identifyingParams(): Record<string, unknown> {\n return {\n model: this.model,\n baseUrl: this.baseUrl,\n modelParameters: this.modelDefaultParameters,\n };\n }\n\n /**\n * Get the LLM type identifier\n */\n _llmType(): string {\n return 'dhti';\n }\n\n /**\n * Prepare the request payload for the API\n */\n protected preparePayload(prompt: string): Record<string, unknown> {\n return {\n model: this.model,\n options: this.modelDefaultParameters,\n messages: [{ role: 'user', content: prompt }],\n };\n }\n\n /**\n * Make the API call to generate text\n */\n async _call(\n prompt: string,\n _options: this['ParsedCallOptions'],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<string> {\n const payload = this.preparePayload(prompt);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(this.baseUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(\n `API request failed: status=${response.status}; body=${body}`\n );\n }\n\n const data = await response.json();\n\n // Expecting structure like: { \"choices\": [ { \"message\": { \"role\":\"assistant\",\"content\":\"...\" } } ] }\n // Adapt this path if the API differs\n if (\n data.choices &&\n Array.isArray(data.choices) &&\n data.choices.length > 0\n ) {\n const choice = data.choices[0];\n // support both \"message\" and direct \"text\"\n if (\n typeof choice === 'object' &&\n choice !== null &&\n 'message' in choice &&\n typeof choice.message === 'object' &&\n choice.message !== null\n ) {\n const content = (choice.message as Record<string, unknown>).content;\n if (typeof content === 'string') {\n return content;\n }\n } else if ('text' in choice) {\n const text = choice.text;\n if (typeof text === 'string') {\n return text;\n }\n }\n }\n\n // Fallback: return raw JSON string for debugging\n return JSON.stringify(data);\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === 'AbortError') {\n throw new Error(`API request timed out after ${this.timeout}ms`);\n }\n throw error;\n }\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Embeddings, type EmbeddingsParams } from '@langchain/core/embeddings';\n\n/**\n * Parameters for configuring BaseEmbedding\n */\nexport interface BaseEmbeddingInput extends EmbeddingsParams {\n baseUrl: string;\n model: string;\n apiKey?: string;\n}\n\n/**\n * BaseEmbedding is a base class for embeddings that communicate with a remote API.\n * It extends the LangChain Embeddings class and provides methods for embedding\n * documents and queries.\n */\nexport class BaseEmbedding extends Embeddings {\n baseUrl: string;\n model: string;\n apiKey: string;\n\n constructor(fields: BaseEmbeddingInput) {\n super(fields);\n this.baseUrl = fields.baseUrl;\n this.model = fields.model;\n this.apiKey = fields.apiKey ?? '';\n }\n\n /**\n * Embed a list of documents\n * @param texts - Array of strings to embed\n * @returns Promise of array of embedding vectors\n */\n async embedDocuments(texts: string[]): Promise<number[][]> {\n return this.getEmbeddings(texts);\n }\n\n /**\n * Embed a single query\n * @param text - String to embed\n * @returns Promise of embedding vector\n */\n async embedQuery(text: string): Promise<number[]> {\n const embeddings = await this.getEmbeddings([text]);\n return embeddings[0];\n }\n\n /**\n * Helper method to get embeddings for a list of texts\n * @param texts - Array of strings to embed\n * @returns Promise of array of embedding vectors\n */\n protected async getEmbeddings(texts: string[]): Promise<number[][]> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n\n const payload = {\n model: this.model,\n input: texts,\n };\n\n const response = await fetch(this.baseUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(\n `API request failed: status=${response.status}; body=${body}`\n );\n }\n\n const respJson = await response.json();\n\n if (!('embeddings' in respJson)) {\n throw new Error(\n `API response missing 'embeddings' key. Received keys: ${Object.keys(\n respJson\n ).join(', ')}`\n );\n }\n\n return respJson.embeddings as number[][];\n }\n}\n"],"names":["mydi","c","m","b","resolve","e","BaseChain","constructor","container","_name","_description","_template","prompt","llm","chat_model","runnable","fakeLLM","FakeListChatModel","responses","camelize","name","snake_case","initializePrompt","ChatPromptTemplate","fromTemplate","PromptTemplate","value","description","template","defaultValue","str","replace","word","index","toLowerCase","toUpperCase","chain","input","outputParser","StringOutputParser","RunnableSequence","from","RunnablePassthrough","response","invoke","aiMessage","AIMessage","content","BaseAgent","args","_tools","tools","run","agent","createStructuredChatAgent","agentExecutor","AgentExecutor","handleParsingErrors","BaseTool","DynamicStructuredTool","schema","func","_batchWithConfig","config","log","Logger","LLMLoop","stringExpression","_mapQueryTemplate","_mapDocTemplate","_reduceChainTemplate","mapQueryTemplate","mapDocTemplate","reduceChainTemplate","checkAssertion","expression","context","_expression","printValues","JSON","parse","error","info","_context","undefined","_content","warn","forEach","element","contentItem","atob","attachment","data","findDatesAndConvertToTimeElapsed","_input","result","checkMention","checkNegation","text","dateRegex","matches","currentDate","Date","exec","date","timeElapsed","getTime","Math","floor","toString","camelToString","camelCase","stringToBoolean","positiveKeywords","lowerStr","some","keyword","includes","textSplitter","chunkSize","chunkOverlap","CharacterTextSplitter","texts","splitText","length","obj","arg","where","statements","extractObjectsByKey","join","key","results","traverse","currentKey","hasOwnProperty","push","_printValues","_eliminate","regex","RegExp","RunnableParallel","mapQuery","mapDoc","reduceChain","mapQueryChain","assign","query","mapDocChain","documents","textChunks","Promise","all","map","chunk","document","parallelChain","sequence","stringify","facts","BaseLLM","LLM","fields","_fields$apiKey","_fields$timeout","_fields$backend","_fields$temperature","_fields$topP","_fields$topK","_fields$nBatch","_fields$nThreads","_fields$nPredict","_fields$maxOutputToke","_fields$repeatLastN","_fields$repeatPenalty","baseUrl","model","apiKey","timeout","backend","temperature","topP","topK","nBatch","nThreads","nPredict","maxOutputTokens","repeatLastN","repeatPenalty","modelDefaultParameters","identifyingParams","modelParameters","_llmType","preparePayload","options","messages","role","_call","_options","_runManager","payload","headers","controller","AbortController","timeoutId","setTimeout","abort","fetch","method","body","signal","clearTimeout","ok","Error","status","json","choices","Array","isArray","choice","message","BaseEmbedding","Embeddings","embedDocuments","getEmbeddings","embedQuery","embeddings","respJson","Object","keys"],"mappings":";;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;AAcG;AAEH,MAAMA,IAAI,GAAGA,CAACC,CAAM,EAAEC,CAAS,EAAEC,CAAS,KAAI;EAC5C,IAAI;IACF,OAAOF,CAAC,CAACG,OAAO,CAACF,CAAC,GAAG,GAAG,GAAGC,CAAC,CAAC,CAAA;AAC/B,GAAC,CAAC,OAAOE,CAAC,EAAE,EAAE;EACd,IAAI;IACF,OAAOJ,CAAC,CAACG,OAAO,CAACF,CAAC,GAAG,GAAG,GAAGC,CAAC,CAAC,CAAA;AAC/B,GAAC,CAAC,OAAOE,CAAC,EAAE,EAAC;EACb,IAAI;AACF,IAAA,OAAOJ,CAAC,CAACG,OAAO,CAACD,CAAC,CAAC,CAAA;AACrB,GAAC,CAAC,OAAOE,CAAC,EAAE,EAAC;AACb,EAAA,OAAO,IAAI,CAAA;AACb,CAAC;;AC3BD;;;;;;;;;;;;;;AAcG;MAaUC,SAAS,CAAA;EAiBpBC,WAAAA,CAAYC,SAAc,EAAA;AAAA,IAAA,IAAA,CAhB1BA,SAAS,GAAA,KAAA,CAAA,CAAA;IAAA,IACDC,CAAAA,KAAK,GAAW,EAAE,CAAA;IAAA,IAClBC,CAAAA,YAAY,GAAW,EAAE,CAAA;IAAA,IACzBC,CAAAA,SAAS,GAAW,EAAE,CAAA;AAAA,IAAA,IAAA,CAC9BC,MAAM,GAAA,KAAA,CAAA,CAAA;AAAA,IAAA,IAAA,CACNC,GAAG,GAAA,KAAA,CAAA,CAAA;AAAA,IAAA,IAAA,CACHC,UAAU,GAAA,KAAA,CAAA,CAAA;AAAA,IAAA,IAAA,CACVC,QAAQ,GAAA,KAAA,CAAA,CAAA;AAAA,IAAA,IAAA,CACRC,OAAO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AA;MAClC,MAAM,IAAImH,KAAK,CACb,CAA8B1K,2BAAAA,EAAAA,QAAQ,CAAC2K,MAAM,CAAA,OAAA,EAAUL,IAAI,CAAA,CAAE,CAC9D,CAAA;AACH,KAAA;AAEA,IAAA,MAAMkB,QAAQ,GAAG,MAAMxL,QAAQ,CAAC4K,IAAI,EAAE,CAAA;AAEtC,IAAA,IAAI,EAAE,YAAY,IAAIY,QAAQ,CAAC,EAAE;AAC/B,MAAA,MAAM,IAAId,KAAK,CACb,CAAyDe,sDAAAA,EAAAA,MAAM,CAACC,IAAI,CAClEF,QAAQ,CACT,CAACjG,IAAI,CAAC,IAAI,CAAC,EAAE,CACf,CAAA;AACH,KAAA;IAEA,OAAOiG,QAAQ,CAACD,UAAwB,CAAA;AAC1C,GAAA;AACD;;;;;;;;;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@langchain/core/prompts"),t=require("@langchain/core/runnables"),n=require("@langchain/core/messages"),a=require("@langchain/core/output_parsers"),s=require("langchain/agents"),i=require("langchain/tools"),r=require("@langchain/textsplitters"),o=require("tslog"),c=require("@langchain/core/language_models/llms"),l=require("@langchain/core/embeddings");const h=(e,t,n)=>{try{return e.resolve(t+"_"+n)}catch(e){}try{return e.resolve(t+"-"+n)}catch(e){}try{return e.resolve(n)}catch(e){}return null};class p{constructor(t){this.container=void 0,this._name="",this._description="",this._template="",this.prompt=void 0,this.llm=void 0,this.chat_model=void 0,this.runnable=void 0,this.container=t,this._name=this.camelize(this.constructor.name),this._description=this.snake_case(this.constructor.name),this.llm=this.resolve("llm"),this._template=this.resolve("template"),this.chat_model=this.resolve("chat-model",!1),this.prompt=this.chat_model?e.ChatPromptTemplate.fromTemplate(this._template):e.PromptTemplate.fromTemplate(this._template)}get name(){return this._name}set name(e){this._name=""===e?this.camelize(this.constructor.name):e}get description(){return this._description}set description(e){this._description=""===e?this.snake_case(this.constructor.name):e}get template(){return this._template}set template(t){this._template=t,this.prompt=this.chat_model?e.ChatPromptTemplate.fromTemplate(this._template):e.PromptTemplate.fromTemplate(this._template)}resolve(e,t=null){return h(this.container,this.camelize(this.constructor.name),e)||t}camelize(e){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,function(e,t){return 0===t?e.toLowerCase():e.toUpperCase()}).replace(/\s+/g,"")}snake_case(e){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,function(e,t){return 0===t?e.toLowerCase():"_"+e.toLowerCase()}).replace(/\s+/g,"")}async chain(e){const s=new a.StringOutputParser;if(this.runnable=t.RunnableSequence.from([{input:new t.RunnablePassthrough},this.prompt,this.llm,s]),this.chat_model){const t=await this.runnable.invoke(e);return new n.AIMessage(t).content}return await this.runnable.invoke(e)}async invoke(e){return this.chain(e)}}const u=new o.Logger;exports.BaseAgent=class extends p{constructor(...e){super(...e),this._tools=[]}get tools(){return this._tools}set tools(e){this._tools=e}async run(e){const t=await s.createStructuredChatAgent({llm:this.llm,tools:this._tools,prompt:this.prompt}),n=new s.AgentExecutor({agent:t,tools:this.tools,handleParsingErrors:"Please try again, paying close attention to the final answer"});return await n.invoke(e)}},exports.BaseChain=p,exports.BaseEmbedding=class extends l.Embeddings{constructor(e){var t;super(e),this.baseUrl=void 0,this.model=void 0,this.apiKey=void 0,this.baseUrl=e.baseUrl,this.model=e.model,this.apiKey=null!=(t=e.apiKey)?t:""}async embedDocuments(e){return this.getEmbeddings(e)}async embedQuery(e){return(await this.getEmbeddings([e]))[0]}async getEmbeddings(e){const t={"Content-Type":"application/json"};this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`);const n={model:this.model,input:e},a=await fetch(this.baseUrl,{method:"POST",headers:t,body:JSON.stringify(n)});if(!a.ok){const e=await a.text();throw new Error(`API request failed: status=${a.status}; body=${e}`)}const s=await a.json();if(!("embeddings"in s))throw new Error(`API response missing 'embeddings' key. Received keys: ${Object.keys(s).join(", ")}`);return s.embeddings}},exports.BaseLLM=class extends c.LLM{constructor(e){var t,n,a,s,i,r,o,c,l,h,p,u;super(e),this.baseUrl=void 0,this.model=void 0,this.apiKey=void 0,this.timeout=void 0,this.backend=void 0,this.temperature=void 0,this.topP=void 0,this.topK=void 0,this.nBatch=void 0,this.nThreads=void 0,this.nPredict=void 0,this.maxOutputTokens=void 0,this.repeatLastN=void 0,this.repeatPenalty=void 0,this.baseUrl=e.baseUrl,this.model=e.model,this.apiKey=null!=(t=e.apiKey)?t:"",this.timeout=null!=(n=e.timeout)?n:6e4,this.backend=null!=(a=e.backend)?a:"dhti",this.temperature=null!=(s=e.temperature)?s:.1,this.topP=null!=(i=e.topP)?i:.8,this.topK=null!=(r=e.topK)?r:40,this.nBatch=null!=(o=e.nBatch)?o:8,this.nThreads=null!=(c=e.nThreads)?c:4,this.nPredict=null!=(l=e.nPredict)?l:256,this.maxOutputTokens=null!=(h=e.maxOutputTokens)?h:512,this.repeatLastN=null!=(p=e.repeatLastN)?p:64,this.repeatPenalty=null!=(u=e.repeatPenalty)?u:1.18}get modelDefaultParameters(){return{maxOutputTokens:this.maxOutputTokens,nPredict:this.nPredict,topK:this.topK,topP:this.topP,temperature:this.temperature,nBatch:this.nBatch,repeatPenalty:this.repeatPenalty,repeatLastN:this.repeatLastN}}get identifyingParams(){return{model:this.model,baseUrl:this.baseUrl,modelParameters:this.modelDefaultParameters}}_llmType(){return"dhti"}preparePayload(e){return{model:this.model,options:this.modelDefaultParameters,messages:[{role:"user",content:e}]}}async _call(e,t,n){const a=this.preparePayload(e),s={"Content-Type":"application/json"};this.apiKey&&(s.Authorization=`Bearer ${this.apiKey}`);const i=new AbortController,r=setTimeout(()=>i.abort(),this.timeout);try{const e=await fetch(this.baseUrl,{method:"POST",headers:s,body:JSON.stringify(a),signal:i.signal});if(clearTimeout(r),!e.ok){const t=await e.text();throw new Error(`API request failed: status=${e.status}; body=${t}`)}const t=await e.json();if(t.choices&&Array.isArray(t.choices)&&t.choices.length>0){const e=t.choices[0];if("object"==typeof e&&null!==e&&"message"in e&&"object"==typeof e.message&&null!==e.message){const t=e.message.content;if("string"==typeof t)return t}else if("text"in e){const t=e.text;if("string"==typeof t)return t}}return JSON.stringify(t)}catch(e){if(clearTimeout(r),e instanceof Error&&"AbortError"===e.name)throw new Error(`API request timed out after ${this.timeout}ms`);throw e}}},exports.BaseTool=class extends i.DynamicStructuredTool{constructor(e,t,n,a,s=null){super({name:t,description:n,schema:a,func:s}),this.container=void 0,this.name=void 0,this.description=void 0,this.schema=void 0,this.func=async e=>"override this",this.container=e,this.name=""===t?this.camelize(this.constructor.name):t,this.description=""===n?this.snake_case(this.constructor.name):n,this.schema=a}resolve(e){return h(this.container,this.name,e)}camelize(e){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,function(e,t){return 0===t?e.toLowerCase():e.toUpperCase()}).replace(/\s+/g,"")}snake_case(e){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,function(e,t){return 0===t?e.toLowerCase():"_"+e.toLowerCase()}).replace(/\s+/g,"")}async _batchWithConfig(e,t){return super._batchWithConfig(e,t)}},exports.LLMLoop=class extends p{constructor(...e){super(...e),this.stringExpression="",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: ",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: ",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: "}get mapQueryTemplate(){return this._mapQueryTemplate}set mapQueryTemplate(e){this._mapQueryTemplate=e}get mapDocTemplate(){return this._mapDocTemplate}set mapDocTemplate(e){this._mapDocTemplate=e}get reduceChainTemplate(){return this._reduceChainTemplate}set reduceChainTemplate(e){this._reduceChainTemplate=e}async checkAssertion(e,t){let n,a="";try{a=this.printValues(JSON.parse(e))}catch(t){a=e}u.info(`Checking assertion with expression: ${a}`);let s="";try{n=JSON.parse(t)}catch(e){n=t,u.warn(`Context is not a valid JSON string: ${t}`),u.warn(`Using context as a string: ${n}`)}try{n=JSON.parse(t),n.forEach(e=>{e.content.forEach(e=>{s+=atob(e.attachment.data.value)})})}catch(e){s=t,u.warn(`Context is not a valid JSON : ${t}`),u.warn(`Using context as a string: ${s}`)}s=this.findDatesAndConvertToTimeElapsed(s.replace(/(\r\n|\n|\r)/gm," ")),u.info(`Checking assertion with context: ${s}`);const i={input:{expression:a,context:s}},r=await this.chain(i);return u.info(`Assertion check result: ${r}`),r}async checkMention(e,t){return!(!e||!t)}async checkNegation(e,t){return!(!e||!t)}findDatesAndConvertToTimeElapsed(e){const t=/(\d{1,2}[-/]\d{1,2}[-/]\d{4})/g;let n,a=new Date;for(;null!==(n=t.exec(e));){let t=new Date(n[0]),s=(a.getTime()-t.getTime())/864e5;e=e.replace(n[0],Math.floor(s).toString()+" days ago.")}return e}camelToString(e){return e.replace(/([A-Z])/g," $1").replace(/^./,function(e){return e.toUpperCase()})}stringToBoolean(e){u.info(`Converting string to boolean: ${e}`);const t=e.toLowerCase();return["true","contains","confirms","yes","affirmative","matches","exists","present","absolutely","certainly","definitely","indeed","did have","showed","revealed"].some(e=>t.includes(e))}async textSplitter(e,t=3900,n=0){const a=new r.CharacterTextSplitter({chunkSize:t,chunkOverlap:n}),s=await a.splitText(e);return 0===s.length?(u.warn("No text chunks created. Please check the input text."),[]):(s.length>100&&u.warn(`Warning: More than 100 text chunks created (${s.length}). This may affect performance.`),t<1e3&&u.warn(`Warning: Chunk size is less than 1000 characters (${t}). This may lead to very small chunks.`),u.info(`Text split into ${s.length} chunks with size ${t} and overlap ${n}`),s)}printValues(e){return u.info(`Processing Rule: ${e.name} for ${e.context}`),e.expression&&e.expression.arg&&e.expression.arg.where?this.extractObjectsByKey(e.expression.arg.where,"value").join(" ").replace(/,/g," "):""}extractObjectsByKey(e,t){const n=[];return function e(a){for(const s in a)a.hasOwnProperty(s)&&(s===t&&n.push(a[s]),"object"==typeof a[s]&&null!==a[s]&&e(a[s]))}(e),n}_printValues(e){for(var t in e)"object"==typeof e[t]?this._printValues(e[t]):this.stringExpression+=e[t]+" ";return["true","false","null","undefined","String","Number","Object","Array","Boolean","value","Type","Specifier","Named"].forEach(e=>{const t=new RegExp(e,"g");this.stringExpression=this.stringExpression.replace(t,"")}),this.stringExpression=this.stringExpression.replace(/(?:https?|ftp):\/\/[\n\S]+/g,""),this.camelToString(this.stringExpression)}async chain(e){const{RunnableSequence:t,RunnableParallel:n,RunnablePassthrough:a}=await import("@langchain/core/runnables"),s=new p(this.container),i=new p(this.container),r=new p(this.container);s.name="MapQuery",s.description="Map the expression to a natural language query.",s.template=this.resolve("litl_mapquery_template",this._mapQueryTemplate),i.name="MapDoc",i.description="Map the document to a set of facts.",i.template=this.resolve("litl_mapdoc_template",this._mapDocTemplate),r.name="ReduceChain",r.description="Reduce a set of documents to binary answer.",r.template=this.resolve("litl_reduce_chain_template",this._reduceChainTemplate);const o=a.assign({query:async e=>s.chain({expression:e.input.expression})}),c=a.assign({documents:async e=>{const t=await this.textSplitter(e.input.context);return Promise.all(t.map(t=>i.chain({document:t,statements:e.input.expression})))}}),l=n.from([o,c]);return t.from([l,async e=>(u.info(`Results from parallel chain: ${JSON.stringify(e)}`),r.chain({facts:e[1].documents,query:e[0].query+" "+e[0].input.expression})),e=>this.stringToBoolean(e)]).invoke(e)}};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@langchain/core/prompts"),t=require("@langchain/core/runnables"),n=require("@langchain/core/messages"),a=require("@langchain/core/output_parsers"),s=require("@langchain/core/utils/testing"),i=require("langchain/agents"),r=require("langchain/tools"),o=require("@langchain/textsplitters"),c=require("tslog"),l=require("@langchain/core/language_models/llms"),h=require("@langchain/core/embeddings");const u=(e,t,n)=>{try{return e.resolve(t+"_"+n)}catch(e){}try{return e.resolve(t+"-"+n)}catch(e){}try{return e.resolve(n)}catch(e){}return null};class p{constructor(e){this.container=void 0,this._name="",this._description="",this._template="",this.prompt=void 0,this.llm=void 0,this.chat_model=void 0,this.runnable=void 0,this.fakeLLM=new s.FakeListChatModel({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)!"]}),this.container=e,this._name=this.camelize(this.constructor.name),this._description=this.snake_case(this.constructor.name),this.llm=this.resolve("llm",this.fakeLLM),this._template=this.resolve("template","{input}"),this.chat_model=this.resolve("chat-model",!1),this.initializePrompt()}initializePrompt(){this.prompt=this.chat_model?e.ChatPromptTemplate.fromTemplate(this._template):e.PromptTemplate.fromTemplate(this._template)}get name(){return this._name}set name(e){this._name=""===e?this.camelize(this.constructor.name):e}get description(){return this._description}set description(e){this._description=""===e?this.snake_case(this.constructor.name):e}get template(){return this._template}set template(e){this._template=e,this.initializePrompt()}resolve(e,t=null){return u(this.container,this.camelize(this.constructor.name),e)||t}camelize(e){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,function(e,t){return 0===t?e.toLowerCase():e.toUpperCase()}).replace(/\s+/g,"")}snake_case(e){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,function(e,t){return 0===t?e.toLowerCase():"_"+e.toLowerCase()}).replace(/\s+/g,"")}async chain(e){const s=new a.StringOutputParser;if(this.runnable=t.RunnableSequence.from([{input:new t.RunnablePassthrough},this.prompt,this.llm,s]),this.chat_model){const t=await this.runnable.invoke(e);return new n.AIMessage(t).content}return await this.runnable.invoke(e)}async invoke(e){return this.chain(e)}}const m=new c.Logger;exports.BaseAgent=class extends p{constructor(...e){super(...e),this._tools=[]}get tools(){return this._tools}set tools(e){this._tools=e}async run(e){const t=await i.createStructuredChatAgent({llm:this.llm,tools:this._tools,prompt:this.prompt}),n=new i.AgentExecutor({agent:t,tools:this.tools,handleParsingErrors:"Please try again, paying close attention to the final answer"});return await n.invoke(e)}},exports.BaseChain=p,exports.BaseEmbedding=class extends h.Embeddings{constructor(e){var t;super(e),this.baseUrl=void 0,this.model=void 0,this.apiKey=void 0,this.baseUrl=e.baseUrl,this.model=e.model,this.apiKey=null!=(t=e.apiKey)?t:""}async embedDocuments(e){return this.getEmbeddings(e)}async embedQuery(e){return(await this.getEmbeddings([e]))[0]}async getEmbeddings(e){const t={"Content-Type":"application/json"};this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`);const n={model:this.model,input:e},a=await fetch(this.baseUrl,{method:"POST",headers:t,body:JSON.stringify(n)});if(!a.ok){const e=await a.text();throw new Error(`API request failed: status=${a.status}; body=${e}`)}const s=await a.json();if(!("embeddings"in s))throw new Error(`API response missing 'embeddings' key. Received keys: ${Object.keys(s).join(", ")}`);return s.embeddings}},exports.BaseLLM=class extends l.LLM{constructor(e){var t,n,a,s,i,r,o,c,l,h,u,p;super(e),this.baseUrl=void 0,this.model=void 0,this.apiKey=void 0,this.timeout=void 0,this.backend=void 0,this.temperature=void 0,this.topP=void 0,this.topK=void 0,this.nBatch=void 0,this.nThreads=void 0,this.nPredict=void 0,this.maxOutputTokens=void 0,this.repeatLastN=void 0,this.repeatPenalty=void 0,this.baseUrl=e.baseUrl,this.model=e.model,this.apiKey=null!=(t=e.apiKey)?t:"",this.timeout=null!=(n=e.timeout)?n:6e4,this.backend=null!=(a=e.backend)?a:"dhti",this.temperature=null!=(s=e.temperature)?s:.1,this.topP=null!=(i=e.topP)?i:.8,this.topK=null!=(r=e.topK)?r:40,this.nBatch=null!=(o=e.nBatch)?o:8,this.nThreads=null!=(c=e.nThreads)?c:4,this.nPredict=null!=(l=e.nPredict)?l:256,this.maxOutputTokens=null!=(h=e.maxOutputTokens)?h:512,this.repeatLastN=null!=(u=e.repeatLastN)?u:64,this.repeatPenalty=null!=(p=e.repeatPenalty)?p:1.18}get modelDefaultParameters(){return{maxOutputTokens:this.maxOutputTokens,nPredict:this.nPredict,topK:this.topK,topP:this.topP,temperature:this.temperature,nBatch:this.nBatch,repeatPenalty:this.repeatPenalty,repeatLastN:this.repeatLastN}}get identifyingParams(){return{model:this.model,baseUrl:this.baseUrl,modelParameters:this.modelDefaultParameters}}_llmType(){return"dhti"}preparePayload(e){return{model:this.model,options:this.modelDefaultParameters,messages:[{role:"user",content:e}]}}async _call(e,t,n){const a=this.preparePayload(e),s={"Content-Type":"application/json"};this.apiKey&&(s.Authorization=`Bearer ${this.apiKey}`);const i=new AbortController,r=setTimeout(()=>i.abort(),this.timeout);try{const e=await fetch(this.baseUrl,{method:"POST",headers:s,body:JSON.stringify(a),signal:i.signal});if(clearTimeout(r),!e.ok){const t=await e.text();throw new Error(`API request failed: status=${e.status}; body=${t}`)}const t=await e.json();if(t.choices&&Array.isArray(t.choices)&&t.choices.length>0){const e=t.choices[0];if("object"==typeof e&&null!==e&&"message"in e&&"object"==typeof e.message&&null!==e.message){const t=e.message.content;if("string"==typeof t)return t}else if("text"in e){const t=e.text;if("string"==typeof t)return t}}return JSON.stringify(t)}catch(e){if(clearTimeout(r),e instanceof Error&&"AbortError"===e.name)throw new Error(`API request timed out after ${this.timeout}ms`);throw e}}},exports.BaseTool=class extends r.DynamicStructuredTool{constructor(e,t,n,a,s=null){super({name:t,description:n,schema:a,func:s}),this.container=void 0,this.name=void 0,this.description=void 0,this.schema=void 0,this.func=async e=>"override this",this.container=e,this.name=""===t?this.camelize(this.constructor.name):t,this.description=""===n?this.snake_case(this.constructor.name):n,this.schema=a}resolve(e){return u(this.container,this.name,e)}camelize(e){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,function(e,t){return 0===t?e.toLowerCase():e.toUpperCase()}).replace(/\s+/g,"")}snake_case(e){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,function(e,t){return 0===t?e.toLowerCase():"_"+e.toLowerCase()}).replace(/\s+/g,"")}async _batchWithConfig(e,t){return super._batchWithConfig(e,t)}},exports.LLMLoop=class extends p{constructor(...e){super(...e),this.stringExpression="",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: ",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: ",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: "}get mapQueryTemplate(){return this._mapQueryTemplate}set mapQueryTemplate(e){this._mapQueryTemplate=e}get mapDocTemplate(){return this._mapDocTemplate}set mapDocTemplate(e){this._mapDocTemplate=e}get reduceChainTemplate(){return this._reduceChainTemplate}set reduceChainTemplate(e){this._reduceChainTemplate=e}async checkAssertion(e,t){let n,a="";try{a=this.printValues(JSON.parse(e))}catch(t){a=e}m.info(`Checking assertion with expression: ${a}`);let s="";try{n=JSON.parse(t)}catch(e){n=t,m.warn(`Context is not a valid JSON string: ${t}`),m.warn(`Using context as a string: ${n}`)}try{n=JSON.parse(t),n.forEach(e=>{e.content.forEach(e=>{s+=atob(e.attachment.data.value)})})}catch(e){s=t,m.warn(`Context is not a valid JSON : ${t}`),m.warn(`Using context as a string: ${s}`)}s=this.findDatesAndConvertToTimeElapsed(s.replace(/(\r\n|\n|\r)/gm," ")),m.info(`Checking assertion with context: ${s}`);const i={input:{expression:a,context:s}},r=await this.chain(i);return m.info(`Assertion check result: ${r}`),r}async checkMention(e,t){return!(!e||!t)}async checkNegation(e,t){return!(!e||!t)}findDatesAndConvertToTimeElapsed(e){const t=/(\d{1,2}[-/]\d{1,2}[-/]\d{4})/g;let n,a=new Date;for(;null!==(n=t.exec(e));){let t=new Date(n[0]),s=(a.getTime()-t.getTime())/864e5;e=e.replace(n[0],Math.floor(s).toString()+" days ago.")}return e}camelToString(e){return e.replace(/([A-Z])/g," $1").replace(/^./,function(e){return e.toUpperCase()})}stringToBoolean(e){m.info(`Converting string to boolean: ${e}`);const t=e.toLowerCase();return["true","contains","confirms","yes","affirmative","matches","exists","present","absolutely","certainly","definitely","indeed","did have","showed","revealed"].some(e=>t.includes(e))}async textSplitter(e,t=3900,n=0){const a=new o.CharacterTextSplitter({chunkSize:t,chunkOverlap:n}),s=await a.splitText(e);return 0===s.length?(m.warn("No text chunks created. Please check the input text."),[]):(s.length>100&&m.warn(`Warning: More than 100 text chunks created (${s.length}). This may affect performance.`),t<1e3&&m.warn(`Warning: Chunk size is less than 1000 characters (${t}). This may lead to very small chunks.`),m.info(`Text split into ${s.length} chunks with size ${t} and overlap ${n}`),s)}printValues(e){return m.info(`Processing Rule: ${e.name} for ${e.context}`),e.expression&&e.expression.arg&&e.expression.arg.where?this.extractObjectsByKey(e.expression.arg.where,"value").join(" ").replace(/,/g," "):""}extractObjectsByKey(e,t){const n=[];return function e(a){for(const s in a)a.hasOwnProperty(s)&&(s===t&&n.push(a[s]),"object"==typeof a[s]&&null!==a[s]&&e(a[s]))}(e),n}_printValues(e){for(var t in e)"object"==typeof e[t]?this._printValues(e[t]):this.stringExpression+=e[t]+" ";return["true","false","null","undefined","String","Number","Object","Array","Boolean","value","Type","Specifier","Named"].forEach(e=>{const t=new RegExp(e,"g");this.stringExpression=this.stringExpression.replace(t,"")}),this.stringExpression=this.stringExpression.replace(/(?:https?|ftp):\/\/[\n\S]+/g,""),this.camelToString(this.stringExpression)}async chain(e){const{RunnableSequence:t,RunnableParallel:n,RunnablePassthrough:a}=await import("@langchain/core/runnables"),s=new p(this.container),i=new p(this.container),r=new p(this.container);s.name="MapQuery",s.description="Map the expression to a natural language query.",s.template=this.resolve("litl_mapquery_template",this._mapQueryTemplate),i.name="MapDoc",i.description="Map the document to a set of facts.",i.template=this.resolve("litl_mapdoc_template",this._mapDocTemplate),r.name="ReduceChain",r.description="Reduce a set of documents to binary answer.",r.template=this.resolve("litl_reduce_chain_template",this._reduceChainTemplate);const o=a.assign({query:async e=>s.chain({expression:e.input.expression})}),c=a.assign({documents:async e=>{const t=await this.textSplitter(e.input.context);return Promise.all(t.map(t=>i.chain({document:t,statements:e.input.expression})))}}),l=n.from([o,c]);return t.from([l,async e=>(m.info(`Results from parallel chain: ${JSON.stringify(e)}`),r.chain({facts:e[1].documents,query:e[0].query+" "+e[0].input.expression})),e=>this.stringToBoolean(e)]).invoke(e)}};
|
|
2
2
|
//# sourceMappingURL=medpromptjs.cjs.production.min.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"medpromptjs.cjs.production.min.js","sources":["../src/mydi.ts","../src/chain.ts","../src/llm_loop.ts","../src/agent.ts","../src/embedding.ts","../src/llm.ts","../src/tool.ts"],"sourcesContent":["/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst mydi = (c: any, m: string, b: string) => {\n try {\n return c.resolve(m + '_' + b);\n } catch (e) { }\n try {\n return c.resolve(m + '-' + b);\n } catch (e) {}\n try {\n return c.resolve(b);\n } catch (e) {}\n return null;\n};\n\nexport default mydi;\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PromptTemplate, ChatPromptTemplate } from '@langchain/core/prompts';\nimport { LLM } from '@langchain/core/language_models/llms';\nimport mydi from './mydi';\nimport {\n RunnablePassthrough,\n RunnableSequence,\n} from '@langchain/core/runnables';\nimport { AIMessage } from '@langchain/core/messages';\nimport { StringOutputParser } from '@langchain/core/output_parsers';\n\nexport class BaseChain {\n container: any;\n private _name: string = '';\n private _description: string = '';\n private _template: string = '';\n prompt: any;\n llm: LLM;\n chat_model: boolean;\n runnable: any;\n\n constructor(container: any) {\n this.container = container;\n this._name = this.camelize(this.constructor.name);\n this._description = this.snake_case(this.constructor.name);\n this.llm = this.resolve('llm');\n this._template = this.resolve('template');\n this.chat_model = this.resolve('chat-model', false);\n if (this.chat_model) {\n this.prompt = ChatPromptTemplate.fromTemplate(this._template);\n } else {\n this.prompt = PromptTemplate.fromTemplate(this._template);\n }\n }\n\n // Getters and setters\n get name(): string {\n return this._name;\n }\n set name(value: string) {\n this._name = value === '' ? this.camelize(this.constructor.name) : value;\n }\n\n get description(): string {\n return this._description;\n }\n set description(value: string) {\n this._description =\n value === '' ? this.snake_case(this.constructor.name) : value;\n }\n\n get template(): string {\n return this._template;\n }\n set template(value: string) {\n this._template = value;\n if (this.chat_model) {\n this.prompt = ChatPromptTemplate.fromTemplate(this._template);\n } else {\n this.prompt = PromptTemplate.fromTemplate(this._template);\n }\n }\n\n resolve(name: string, defaultValue: any = null): any {\n return (\n mydi(this.container, this.camelize(this.constructor.name), name) ||\n defaultValue\n );\n }\n\n camelize(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n }\n\n snake_case(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();\n })\n .replace(/\\s+/g, '');\n }\n\n // https://js.langchain.com/v0.1/docs/expression_language/how_to/routing/\n //! Override this method\n async chain(input: any) {\n const outputParser = new StringOutputParser();\n this.runnable = RunnableSequence.from([\n {\n input: new RunnablePassthrough(),\n // context: async () => loadContextFromStore(),\n },\n this.prompt,\n this.llm,\n outputParser,\n ]);\n if (this.chat_model) {\n const response: string = await this.runnable.invoke(input);\n const aiMessage = new AIMessage(response);\n return aiMessage.content;\n }\n return await this.runnable.invoke(input);\n }\n\n async invoke(input: any) {\n return this.chain(input);\n }\n}\n","import { BaseChain } from './chain';\nimport { CharacterTextSplitter } from '@langchain/textsplitters';\nimport { Logger, ILogObj } from 'tslog';\n\nconst log: Logger<ILogObj> = new Logger();\nexport class LLMLoop extends BaseChain {\n // Implement the LLM loop logic here\n stringExpression: string = '';\n _mapQueryTemplate: string = `\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: `;\n\n _mapDocTemplate: string = `\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: `;\n\n _reduceChainTemplate: string = `\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: `;\n\n // Add getters and setters for the templates if needed\n get mapQueryTemplate(): string {\n return this._mapQueryTemplate;\n }\n set mapQueryTemplate(template: string) {\n this._mapQueryTemplate = template;\n }\n get mapDocTemplate(): string {\n return this._mapDocTemplate;\n }\n set mapDocTemplate(template: string) {\n this._mapDocTemplate = template;\n }\n get reduceChainTemplate(): string {\n return this._reduceChainTemplate;\n }\n set reduceChainTemplate(template: string) {\n this._reduceChainTemplate = template;\n }\n\n async checkAssertion(expression: string, context: any): Promise<boolean> {\n let _expression: string = '';\n try {\n // Check if expression is a valid JSON string\n _expression = this.printValues(JSON.parse(expression));\n } catch (error) {\n _expression = expression; // If not, use the expression as is\n }\n\n log.info(`Checking assertion with expression: ${_expression}`);\n // Initialize context and content\n let _context: any = undefined;\n let _content: string = '';\n try {\n _context = JSON.parse(context);\n } catch (error) {\n _context = context; // If not, use the context as is\n log.warn(`Context is not a valid JSON string: ${context}`);\n log.warn(`Using context as a string: ${_context}`);\n }\n try {\n // Check if context is a valid JSON string\n _context = JSON.parse(context);\n _context.forEach((element: any) => {\n element.content.forEach((contentItem: any) => {\n _content += atob(contentItem.attachment.data.value);\n });\n });\n } catch (error) {\n _content = context; // If not, use the context as is\n log.warn(`Context is not a valid JSON : ${context}`);\n log.warn(`Using context as a string: ${_content}`);\n }\n _content = this.findDatesAndConvertToTimeElapsed(\n _content.replace(/(\\r\\n|\\n|\\r)/gm, ' ')\n );\n log.info(`Checking assertion with context: ${_content}`);\n const _input = {\n input: {\n expression: _expression,\n context: _content,\n },\n };\n const result = await this.chain(_input);\n log.info(`Assertion check result: ${result}`);\n return result;\n }\n\n async checkMention(expression: string, context: any): Promise<boolean> {\n if (expression && context) return true; // Placeholder for assertion check logic\n return false;\n }\n\n async checkNegation(expression: string, context: any): Promise<boolean> {\n if (expression && context) return true; // Placeholder for assertion check logic\n return false;\n }\n\n findDatesAndConvertToTimeElapsed(text: string): string {\n // Regular expression to match dates in format of 'mm/dd/yyyy' or 'mm-dd-yyyy'\n const dateRegex = /(\\d{1,2}[-/]\\d{1,2}[-/]\\d{4})/g;\n let matches;\n let currentDate = new Date();\n\n while ((matches = dateRegex.exec(text)) !== null) {\n let date = new Date(matches[0]);\n let timeElapsed =\n (currentDate.getTime() - date.getTime()) / (1000 * 60 * 60 * 24);\n text = text.replace(\n matches[0],\n Math.floor(timeElapsed).toString() + ' days ago.'\n );\n }\n return text;\n }\n\n camelToString(camelCase: string): string {\n return camelCase.replace(/([A-Z])/g, ' $1').replace(/^./, function (str) {\n return str.toUpperCase();\n });\n }\n\n stringToBoolean(str: string): boolean {\n log.info(`Converting string to boolean: ${str}`);\n const positiveKeywords = [\n 'true',\n 'contains',\n 'confirms',\n 'yes',\n 'affirmative',\n 'matches',\n 'exists',\n 'present',\n 'absolutely',\n 'certainly',\n 'definitely',\n 'indeed',\n 'did have',\n 'showed',\n 'revealed',\n ];\n const lowerStr = str.toLowerCase();\n return positiveKeywords.some((keyword) => lowerStr.includes(keyword));\n }\n\n async textSplitter(\n text: string,\n chunkSize: number = 3900,\n chunkOverlap: number = 0\n ): Promise<string[]> {\n const textSplitter = new CharacterTextSplitter({\n chunkSize: chunkSize,\n chunkOverlap: chunkOverlap,\n });\n const texts = await textSplitter.splitText(text);\n // Log the number of chunks created\n if (texts.length === 0) {\n log.warn('No text chunks created. Please check the input text.');\n return [];\n }\n if (texts.length > 100) {\n log.warn(\n `Warning: More than 100 text chunks created (${texts.length}). This may affect performance.`\n );\n }\n if (chunkSize < 1000) {\n log.warn(\n `Warning: Chunk size is less than 1000 characters (${chunkSize}). This may lead to very small chunks.`\n );\n }\n log.info(\n `Text split into ${texts.length} chunks with size ${chunkSize} and overlap ${chunkOverlap}`\n );\n return texts;\n }\n\n printValues(obj: any) {\n log.info(`Processing Rule: ${obj.name} for ${obj.context}`);\n // For each obj.expression:arg:where\n if (obj.expression && obj.expression.arg && obj.expression.arg.where) {\n // for each args in obj.expression.arg.where, extract the nested key called \"value\"\n const statements = this.extractObjectsByKey(\n obj.expression.arg.where,\n 'value'\n );\n return statements.join(' ').replace(/,/g, ' ');\n }\n // return statements array as a string seperated by space\n return '';\n }\n\n extractObjectsByKey(obj: any, key: string): any[] {\n const results: any[] = [];\n\n function traverse(obj: any) {\n for (const currentKey in obj) {\n if (obj.hasOwnProperty(currentKey)) {\n if (currentKey === key) {\n results.push(obj[currentKey]);\n }\n if (typeof obj[currentKey] === 'object' && obj[currentKey] !== null) {\n traverse(obj[currentKey]);\n }\n }\n }\n }\n\n traverse(obj);\n return results;\n }\n\n _printValues(obj: any) {\n for (var key in obj) {\n if (typeof obj[key] === 'object') {\n this._printValues(obj[key]);\n } else {\n this.stringExpression += obj[key] + ' ';\n }\n }\n const _eliminate = [\n 'true',\n 'false',\n 'null',\n 'undefined',\n 'String',\n 'Number',\n 'Object',\n 'Array',\n 'Boolean',\n 'value',\n 'Type',\n 'Specifier',\n 'Named',\n ];\n _eliminate.forEach((element) => {\n const regex = new RegExp(element, 'g');\n this.stringExpression = this.stringExpression.replace(regex, '');\n });\n this.stringExpression = this.stringExpression.replace(\n /(?:https?|ftp):\\/\\/[\\n\\S]+/g,\n ''\n );\n return this.camelToString(this.stringExpression);\n }\n\n async chain(input: any) {\n // Create a chain using RunnableSequence, RunnablePassthrough and RunnableParallel\n // input has two properties: expression and context\n // expression goes through mapQuery and parallely\n // context goes through textSplitter and mapDoc\n // Finally reduceChain is called with the results of mapQuery and mapDoc\n // LCEL-based implementation using RunnableSequence, RunnableParallel, and RunnablePassthrough\n const { RunnableSequence, RunnableParallel, RunnablePassthrough } =\n await import('@langchain/core/runnables');\n\n const mapQuery: BaseChain = new BaseChain(this.container);\n const mapDoc: BaseChain = new BaseChain(this.container);\n const reduceChain: BaseChain = new BaseChain(this.container);\n mapQuery.name = 'MapQuery';\n mapQuery.description = 'Map the expression to a natural language query.';\n mapQuery.template = this.resolve('litl_mapquery_template', this._mapQueryTemplate);\n mapDoc.name = 'MapDoc';\n mapDoc.description = 'Map the document to a set of facts.';\n mapDoc.template = this.resolve('litl_mapdoc_template', this._mapDocTemplate);\n reduceChain.name = 'ReduceChain';\n reduceChain.description = 'Reduce a set of documents to binary answer.';\n reduceChain.template = this.resolve('litl_reduce_chain_template', this._reduceChainTemplate);\n const mapQueryChain = RunnablePassthrough.assign({\n query: async (input: any) =>\n mapQuery.chain({ expression: input.input.expression }),\n });\n\n const mapDocChain = RunnablePassthrough.assign({\n documents: async (input: any) => {\n const textChunks = await this.textSplitter(input.input.context);\n return Promise.all(\n textChunks.map((chunk) =>\n mapDoc.chain({\n document: chunk,\n statements: input.input.expression,\n })\n )\n );\n },\n });\n\n const parallelChain = RunnableParallel.from([mapQueryChain, mapDocChain]);\n\n const sequence = RunnableSequence.from([\n parallelChain,\n async (results: any) => {\n /* results is an array: [{ query: ... }, { documents: [...] }]\n{\n \"0\": {\n \"input\": {\n \"expression\": \"0 Visual foot exam showed active infection?\",\n \"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. \"\n },\n \"query\": \"The text indicates a question about whether a visual foot exam revealed an active infection.\\n\"\n },\n \"1\": {\n \"input\": {\n \"expression\": \"0 Visual foot exam showed active infection?\",\n \"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. \"\n },\n \"documents\": [\n \"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\"\n ]\n }\n}\n */\n log.info(`Results from parallel chain: ${JSON.stringify(results)}`);\n const expression = results[0].input.expression;\n const query = results[0].query;\n const documents = results[1].documents;\n return reduceChain.chain({\n facts: documents,\n query: query + ' ' + expression,\n });\n },\n (result: any) => this.stringToBoolean(result),\n ]);\n\n return sequence.invoke(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BaseChain } from './chain';\nimport type { ToolInterface } from '@langchain/core/tools';\nimport { createStructuredChatAgent, AgentExecutor } from 'langchain/agents';\n\nexport class BaseAgent extends BaseChain {\n private _tools: ToolInterface[] = [];\n\n\n get tools(): ToolInterface[] {\n return this._tools;\n }\n set tools(value: ToolInterface[]) {\n this._tools = value;\n }\n\n /**\n * Run the agent using the provided input.\n * This uses createStructuredChatAgent and AgentExecutor from langchain/agents.\n */\n async run(input: any) {\n const agent = await createStructuredChatAgent({\n llm: this.llm,\n tools: this._tools,\n prompt: this.prompt,\n });\n const agentExecutor = new AgentExecutor({\n agent: agent,\n tools: this.tools,\n // verbose: true,\n handleParsingErrors:\n 'Please try again, paying close attention to the final answer',\n });\n return await agentExecutor.invoke(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Embeddings, type EmbeddingsParams } from '@langchain/core/embeddings';\n\n/**\n * Parameters for configuring BaseEmbedding\n */\nexport interface BaseEmbeddingInput extends EmbeddingsParams {\n baseUrl: string;\n model: string;\n apiKey?: string;\n}\n\n/**\n * BaseEmbedding is a base class for embeddings that communicate with a remote API.\n * It extends the LangChain Embeddings class and provides methods for embedding\n * documents and queries.\n */\nexport class BaseEmbedding extends Embeddings {\n baseUrl: string;\n model: string;\n apiKey: string;\n\n constructor(fields: BaseEmbeddingInput) {\n super(fields);\n this.baseUrl = fields.baseUrl;\n this.model = fields.model;\n this.apiKey = fields.apiKey ?? '';\n }\n\n /**\n * Embed a list of documents\n * @param texts - Array of strings to embed\n * @returns Promise of array of embedding vectors\n */\n async embedDocuments(texts: string[]): Promise<number[][]> {\n return this.getEmbeddings(texts);\n }\n\n /**\n * Embed a single query\n * @param text - String to embed\n * @returns Promise of embedding vector\n */\n async embedQuery(text: string): Promise<number[]> {\n const embeddings = await this.getEmbeddings([text]);\n return embeddings[0];\n }\n\n /**\n * Helper method to get embeddings for a list of texts\n * @param texts - Array of strings to embed\n * @returns Promise of array of embedding vectors\n */\n protected async getEmbeddings(texts: string[]): Promise<number[][]> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n\n const payload = {\n model: this.model,\n input: texts,\n };\n\n const response = await fetch(this.baseUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(\n `API request failed: status=${response.status}; body=${body}`\n );\n }\n\n const respJson = await response.json();\n\n if (!('embeddings' in respJson)) {\n throw new Error(\n `API response missing 'embeddings' key. Received keys: ${Object.keys(\n respJson\n ).join(', ')}`\n );\n }\n\n return respJson.embeddings as number[][];\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLM, type BaseLLMParams } from '@langchain/core/language_models/llms';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\n\n/**\n * Model parameters for BaseLLM\n */\nexport interface ModelParams {\n maxOutputTokens?: number;\n nPredict?: number;\n topK?: number;\n topP?: number;\n temperature?: number;\n nBatch?: number;\n repeatPenalty?: number;\n repeatLastN?: number;\n}\n\n/**\n * Parameters for configuring BaseLLM\n */\nexport interface BaseLLMInput extends BaseLLMParams {\n baseUrl: string;\n model: string;\n apiKey?: string;\n timeout?: number;\n backend?: string;\n temperature?: number;\n topP?: number;\n topK?: number;\n nBatch?: number;\n nThreads?: number;\n nPredict?: number;\n maxOutputTokens?: number;\n repeatLastN?: number;\n repeatPenalty?: number;\n}\n\n/**\n * BaseLLM is a base class for LLMs that communicate with a remote API.\n * It extends the LangChain LLM class and provides configurable parameters\n * for model inference.\n */\nexport class BaseLLM extends LLM {\n baseUrl: string;\n model: string;\n apiKey: string;\n timeout: number;\n backend: string;\n temperature: number;\n topP: number;\n topK: number;\n nBatch: number;\n nThreads: number;\n nPredict: number;\n maxOutputTokens: number;\n repeatLastN: number;\n repeatPenalty: number;\n\n constructor(fields: BaseLLMInput) {\n super(fields);\n this.baseUrl = fields.baseUrl;\n this.model = fields.model;\n this.apiKey = fields.apiKey ?? '';\n this.timeout = fields.timeout ?? 60000;\n this.backend = fields.backend ?? 'dhti';\n this.temperature = fields.temperature ?? 0.1;\n this.topP = fields.topP ?? 0.8;\n this.topK = fields.topK ?? 40;\n this.nBatch = fields.nBatch ?? 8;\n this.nThreads = fields.nThreads ?? 4;\n this.nPredict = fields.nPredict ?? 256;\n this.maxOutputTokens = fields.maxOutputTokens ?? 512;\n this.repeatLastN = fields.repeatLastN ?? 64;\n this.repeatPenalty = fields.repeatPenalty ?? 1.18;\n }\n\n /**\n * Get the model default parameters\n */\n get modelDefaultParameters(): ModelParams {\n return {\n maxOutputTokens: this.maxOutputTokens,\n nPredict: this.nPredict,\n topK: this.topK,\n topP: this.topP,\n temperature: this.temperature,\n nBatch: this.nBatch,\n repeatPenalty: this.repeatPenalty,\n repeatLastN: this.repeatLastN,\n };\n }\n\n /**\n * Get the identifying parameters\n */\n get identifyingParams(): Record<string, unknown> {\n return {\n model: this.model,\n baseUrl: this.baseUrl,\n modelParameters: this.modelDefaultParameters,\n };\n }\n\n /**\n * Get the LLM type identifier\n */\n _llmType(): string {\n return 'dhti';\n }\n\n /**\n * Prepare the request payload for the API\n */\n protected preparePayload(prompt: string): Record<string, unknown> {\n return {\n model: this.model,\n options: this.modelDefaultParameters,\n messages: [{ role: 'user', content: prompt }],\n };\n }\n\n /**\n * Make the API call to generate text\n */\n async _call(\n prompt: string,\n _options: this['ParsedCallOptions'],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<string> {\n const payload = this.preparePayload(prompt);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(this.baseUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(\n `API request failed: status=${response.status}; body=${body}`\n );\n }\n\n const data = await response.json();\n\n // Expecting structure like: { \"choices\": [ { \"message\": { \"role\":\"assistant\",\"content\":\"...\" } } ] }\n // Adapt this path if the API differs\n if (\n data.choices &&\n Array.isArray(data.choices) &&\n data.choices.length > 0\n ) {\n const choice = data.choices[0];\n // support both \"message\" and direct \"text\"\n if (\n typeof choice === 'object' &&\n choice !== null &&\n 'message' in choice &&\n typeof choice.message === 'object' &&\n choice.message !== null\n ) {\n const content = (choice.message as Record<string, unknown>).content;\n if (typeof content === 'string') {\n return content;\n }\n } else if ('text' in choice) {\n const text = choice.text;\n if (typeof text === 'string') {\n return text;\n }\n }\n }\n\n // Fallback: return raw JSON string for debugging\n return JSON.stringify(data);\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === 'AbortError') {\n throw new Error(`API request timed out after ${this.timeout}ms`);\n }\n throw error;\n }\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DynamicStructuredTool } from 'langchain/tools';\nimport mydi from './mydi';\n\nexport class BaseTool extends DynamicStructuredTool {\n /** @hidden */\n container: any;\n name: string;\n description: string;\n schema: any;\n constructor(\n container: any,\n name: string,\n description: string,\n schema: any,\n func: any = null\n ) {\n super({\n name: name,\n description: description,\n schema: schema,\n func: func,\n });\n this.container = container;\n this.name = name === '' ? this.camelize(this.constructor.name) : name;\n this.description =\n description === '' ? this.snake_case(this.constructor.name) : description;\n this.schema = schema;\n }\n\n func = async (args: any) => {\n return 'override this';\n };\n\n resolve(name: string) {\n return mydi(this.container, this.name, name);\n }\n\n camelize(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n }\n\n snake_case(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();\n })\n .replace(/\\s+/g, '');\n }\n\n /**\n * @param input - The input to process in batch.\n * @param config - The configuration for the batch.\n * @returns A promise resolving to an array of results.\n */\n async _batchWithConfig(input: any, config: any): Promise<any[]> {\n // Call the parent implementation or provide your own\n return super._batchWithConfig(input, config);\n }\n}\n"],"names":["mydi","c","m","b","resolve","e","BaseChain","constructor","container","this","_name","_description","_template","prompt","llm","chat_model","runnable","camelize","name","snake_case","ChatPromptTemplate","fromTemplate","PromptTemplate","value","description","template","defaultValue","str","replace","word","index","toLowerCase","toUpperCase","chain","input","outputParser","StringOutputParser","RunnableSequence","from","RunnablePassthrough","response","invoke","AIMessage","content","log","Logger","args","super","_tools","tools","run","agent","createStructuredChatAgent","agentExecutor","AgentExecutor","handleParsingErrors","Embeddings","fields","_fields$apiKey","baseUrl","model","apiKey","embedDocuments","texts","getEmbeddings","embedQuery","text","headers","payload","fetch","method","body","JSON","stringify","ok","Error","status","respJson","json","Object","keys","join","embeddings","LLM","_fields$timeout","_fields$backend","_fields$temperature","_fields$topP","_fields$topK","_fields$nBatch","_fields$nThreads","_fields$nPredict","_fields$maxOutputToke","_fields$repeatLastN","_fields$repeatPenalty","timeout","backend","temperature","topP","topK","nBatch","nThreads","nPredict","maxOutputTokens","repeatLastN","repeatPenalty","modelDefaultParameters","identifyingParams","modelParameters","_llmType","preparePayload","options","messages","role","_call","_options","_runManager","controller","AbortController","timeoutId","setTimeout","abort","signal","clearTimeout","data","choices","Array","isArray","length","choice","message","error","DynamicStructuredTool","schema","func","async","_batchWithConfig","config","stringExpression","_mapQueryTemplate","_mapDocTemplate","_reduceChainTemplate","mapQueryTemplate","mapDocTemplate","reduceChainTemplate","checkAssertion","expression","context","_context","_expression","printValues","parse","info","_content","warn","forEach","element","contentItem","atob","attachment","findDatesAndConvertToTimeElapsed","_input","result","checkMention","checkNegation","dateRegex","matches","currentDate","Date","exec","date","timeElapsed","getTime","Math","floor","toString","camelToString","camelCase","stringToBoolean","lowerStr","some","keyword","includes","textSplitter","chunkSize","chunkOverlap","CharacterTextSplitter","splitText","obj","arg","where","extractObjectsByKey","key","results","traverse","currentKey","hasOwnProperty","push","_printValues","regex","RegExp","RunnableParallel","import","mapQuery","mapDoc","reduceChain","mapQueryChain","assign","query","mapDocChain","documents","textChunks","Promise","all","map","chunk","document","statements","parallelChain","facts"],"mappings":"obAgBA,MAAMA,EAAOA,CAACC,EAAQC,EAAWC,KAC/B,IACE,OA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c,8CAC1BqL,EAAYpL,SAAWhB,KAAKL,QAAQ,6BAA8BK,KAAKoI,sBACvE,MAAMiE,EAAgBvK,EAAoBwK,OAAO,CAC/CC,MAAOzE,SACLoE,EAAS1K,MAAM,CAAEiH,WAAYhH,EAAMA,MAAMgH,eAGvC+D,EAAc1K,EAAoBwK,OAAO,CAC7CG,UAAW3E,UACT,MAAM4E,QAAmB1M,KAAK8K,aAAarJ,EAAMA,MAAMiH,SACvD,OAAOiE,QAAQC,IACbF,EAAWG,IAAKC,GACdX,EAAO3K,MAAM,CACXuL,SAAUD,EACVE,WAAYvL,EAAMA,MAAMgH,kBAO5BwE,EAAgBjB,EAAiBnK,KAAK,CAACwK,EAAeG,IAqC5D,OAnCiB5K,EAAiBC,KAAK,CACrCoL,EACAnF,UAqBE3F,EAAI4G,KAAK,gCAAgChF,KAAKC,UAAUwH,MAIjDY,EAAY5K,MAAM,CACvB0L,MAFgB1B,EAAQ,GAAGiB,UAG3BF,MAJYf,EAAQ,GAAGe,MAIR,IALEf,EAAQ,GAAG/J,MAAMgH,cAQrCgB,GAAgBzJ,KAAKyK,gBAAgBhB,KAGxBzH,OAAOP,EACzB"}
|
|
1
|
+
{"version":3,"file":"medpromptjs.cjs.production.min.js","sources":["../src/mydi.ts","../src/chain.ts","../src/llm_loop.ts","../src/agent.ts","../src/embedding.ts","../src/llm.ts","../src/tool.ts"],"sourcesContent":["/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst mydi = (c: any, m: string, b: string) => {\n try {\n return c.resolve(m + '_' + b);\n } catch (e) { }\n try {\n return c.resolve(m + '-' + b);\n } catch (e) {}\n try {\n return c.resolve(b);\n } catch (e) {}\n return null;\n};\n\nexport default mydi;\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PromptTemplate, ChatPromptTemplate } from '@langchain/core/prompts';\nimport { LLM } from '@langchain/core/language_models/llms';\nimport mydi from './mydi';\nimport {\n RunnablePassthrough,\n RunnableSequence,\n} from '@langchain/core/runnables';\nimport { AIMessage } from '@langchain/core/messages';\nimport { StringOutputParser } from '@langchain/core/output_parsers';\nimport { FakeListChatModel } from '@langchain/core/utils/testing';\n\nexport class BaseChain {\n container: any;\n private _name: string = '';\n private _description: string = '';\n private _template: string = '';\n prompt: any;\n llm: LLM;\n chat_model: boolean;\n runnable: any;\n fakeLLM: FakeListChatModel = new FakeListChatModel({\n responses: [\n 'Hello, this is a fake response (There is no real LLM available)!',\n 'bootstrap main-llm with a real LLM instance',\n 'This is another fake response (There is no real LLM available)!',\n ],\n });\n\n constructor(container: any) {\n this.container = container;\n this._name = this.camelize(this.constructor.name);\n this._description = this.snake_case(this.constructor.name);\n this.llm = this.resolve('llm', this.fakeLLM);\n this._template = this.resolve('template', '{input}');\n this.chat_model = this.resolve('chat-model', false);\n this.initializePrompt();\n }\n\n initializePrompt() {\n if (this.chat_model) {\n this.prompt = ChatPromptTemplate.fromTemplate(this._template);\n } else {\n this.prompt = PromptTemplate.fromTemplate(this._template);\n }\n }\n // Getters and setters\n get name(): string {\n return this._name;\n }\n set name(value: string) {\n this._name = value === '' ? this.camelize(this.constructor.name) : value;\n }\n\n get description(): string {\n return this._description;\n }\n set description(value: string) {\n this._description =\n value === '' ? this.snake_case(this.constructor.name) : value;\n }\n\n get template(): string {\n return this._template;\n }\n set template(value: string) {\n this._template = value;\n this.initializePrompt();\n }\n\n resolve(name: string, defaultValue: any = null): any {\n return (\n mydi(this.container, this.camelize(this.constructor.name), name) ||\n defaultValue\n );\n }\n\n camelize(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n }\n\n snake_case(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();\n })\n .replace(/\\s+/g, '');\n }\n\n // https://js.langchain.com/v0.1/docs/expression_language/how_to/routing/\n //! Override this method\n async chain(input: any) {\n const outputParser = new StringOutputParser();\n this.runnable = RunnableSequence.from([\n {\n input: new RunnablePassthrough(),\n // context: async () => loadContextFromStore(),\n },\n this.prompt,\n this.llm,\n outputParser,\n ]);\n if (this.chat_model) {\n const response: string = await this.runnable.invoke(input);\n const aiMessage = new AIMessage(response);\n return aiMessage.content;\n }\n return await this.runnable.invoke(input);\n }\n\n async invoke(input: any) {\n return this.chain(input);\n }\n}\n","import { BaseChain } from './chain';\nimport { CharacterTextSplitter } from '@langchain/textsplitters';\nimport { Logger, ILogObj } from 'tslog';\n\nconst log: Logger<ILogObj> = new Logger();\nexport class LLMLoop extends BaseChain {\n // Implement the LLM loop logic here\n stringExpression: string = '';\n _mapQueryTemplate: string = `\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: `;\n\n _mapDocTemplate: string = `\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: `;\n\n _reduceChainTemplate: string = `\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: `;\n\n // Add getters and setters for the templates if needed\n get mapQueryTemplate(): string {\n return this._mapQueryTemplate;\n }\n set mapQueryTemplate(template: string) {\n this._mapQueryTemplate = template;\n }\n get mapDocTemplate(): string {\n return this._mapDocTemplate;\n }\n set mapDocTemplate(template: string) {\n this._mapDocTemplate = template;\n }\n get reduceChainTemplate(): string {\n return this._reduceChainTemplate;\n }\n set reduceChainTemplate(template: string) {\n this._reduceChainTemplate = template;\n }\n\n async checkAssertion(expression: string, context: any): Promise<boolean> {\n let _expression: string = '';\n try {\n // Check if expression is a valid JSON string\n _expression = this.printValues(JSON.parse(expression));\n } catch (error) {\n _expression = expression; // If not, use the expression as is\n }\n\n log.info(`Checking assertion with expression: ${_expression}`);\n // Initialize context and content\n let _context: any = undefined;\n let _content: string = '';\n try {\n _context = JSON.parse(context);\n } catch (error) {\n _context = context; // If not, use the context as is\n log.warn(`Context is not a valid JSON string: ${context}`);\n log.warn(`Using context as a string: ${_context}`);\n }\n try {\n // Check if context is a valid JSON string\n _context = JSON.parse(context);\n _context.forEach((element: any) => {\n element.content.forEach((contentItem: any) => {\n _content += atob(contentItem.attachment.data.value);\n });\n });\n } catch (error) {\n _content = context; // If not, use the context as is\n log.warn(`Context is not a valid JSON : ${context}`);\n log.warn(`Using context as a string: ${_content}`);\n }\n _content = this.findDatesAndConvertToTimeElapsed(\n _content.replace(/(\\r\\n|\\n|\\r)/gm, ' ')\n );\n log.info(`Checking assertion with context: ${_content}`);\n const _input = {\n input: {\n expression: _expression,\n context: _content,\n },\n };\n const result = await this.chain(_input);\n log.info(`Assertion check result: ${result}`);\n return result;\n }\n\n async checkMention(expression: string, context: any): Promise<boolean> {\n if (expression && context) return true; // Placeholder for assertion check logic\n return false;\n }\n\n async checkNegation(expression: string, context: any): Promise<boolean> {\n if (expression && context) return true; // Placeholder for assertion check logic\n return false;\n }\n\n findDatesAndConvertToTimeElapsed(text: string): string {\n // Regular expression to match dates in format of 'mm/dd/yyyy' or 'mm-dd-yyyy'\n const dateRegex = /(\\d{1,2}[-/]\\d{1,2}[-/]\\d{4})/g;\n let matches;\n let currentDate = new Date();\n\n while ((matches = dateRegex.exec(text)) !== null) {\n let date = new Date(matches[0]);\n let timeElapsed =\n (currentDate.getTime() - date.getTime()) / (1000 * 60 * 60 * 24);\n text = text.replace(\n matches[0],\n Math.floor(timeElapsed).toString() + ' days ago.'\n );\n }\n return text;\n }\n\n camelToString(camelCase: string): string {\n return camelCase.replace(/([A-Z])/g, ' $1').replace(/^./, function (str) {\n return str.toUpperCase();\n });\n }\n\n stringToBoolean(str: string): boolean {\n log.info(`Converting string to boolean: ${str}`);\n const positiveKeywords = [\n 'true',\n 'contains',\n 'confirms',\n 'yes',\n 'affirmative',\n 'matches',\n 'exists',\n 'present',\n 'absolutely',\n 'certainly',\n 'definitely',\n 'indeed',\n 'did have',\n 'showed',\n 'revealed',\n ];\n const lowerStr = str.toLowerCase();\n return positiveKeywords.some((keyword) => lowerStr.includes(keyword));\n }\n\n async textSplitter(\n text: string,\n chunkSize: number = 3900,\n chunkOverlap: number = 0\n ): Promise<string[]> {\n const textSplitter = new CharacterTextSplitter({\n chunkSize: chunkSize,\n chunkOverlap: chunkOverlap,\n });\n const texts = await textSplitter.splitText(text);\n // Log the number of chunks created\n if (texts.length === 0) {\n log.warn('No text chunks created. Please check the input text.');\n return [];\n }\n if (texts.length > 100) {\n log.warn(\n `Warning: More than 100 text chunks created (${texts.length}). This may affect performance.`\n );\n }\n if (chunkSize < 1000) {\n log.warn(\n `Warning: Chunk size is less than 1000 characters (${chunkSize}). This may lead to very small chunks.`\n );\n }\n log.info(\n `Text split into ${texts.length} chunks with size ${chunkSize} and overlap ${chunkOverlap}`\n );\n return texts;\n }\n\n printValues(obj: any) {\n log.info(`Processing Rule: ${obj.name} for ${obj.context}`);\n // For each obj.expression:arg:where\n if (obj.expression && obj.expression.arg && obj.expression.arg.where) {\n // for each args in obj.expression.arg.where, extract the nested key called \"value\"\n const statements = this.extractObjectsByKey(\n obj.expression.arg.where,\n 'value'\n );\n return statements.join(' ').replace(/,/g, ' ');\n }\n // return statements array as a string seperated by space\n return '';\n }\n\n extractObjectsByKey(obj: any, key: string): any[] {\n const results: any[] = [];\n\n function traverse(obj: any) {\n for (const currentKey in obj) {\n if (obj.hasOwnProperty(currentKey)) {\n if (currentKey === key) {\n results.push(obj[currentKey]);\n }\n if (typeof obj[currentKey] === 'object' && obj[currentKey] !== null) {\n traverse(obj[currentKey]);\n }\n }\n }\n }\n\n traverse(obj);\n return results;\n }\n\n _printValues(obj: any) {\n for (var key in obj) {\n if (typeof obj[key] === 'object') {\n this._printValues(obj[key]);\n } else {\n this.stringExpression += obj[key] + ' ';\n }\n }\n const _eliminate = [\n 'true',\n 'false',\n 'null',\n 'undefined',\n 'String',\n 'Number',\n 'Object',\n 'Array',\n 'Boolean',\n 'value',\n 'Type',\n 'Specifier',\n 'Named',\n ];\n _eliminate.forEach((element) => {\n const regex = new RegExp(element, 'g');\n this.stringExpression = this.stringExpression.replace(regex, '');\n });\n this.stringExpression = this.stringExpression.replace(\n /(?:https?|ftp):\\/\\/[\\n\\S]+/g,\n ''\n );\n return this.camelToString(this.stringExpression);\n }\n\n async chain(input: any) {\n // Create a chain using RunnableSequence, RunnablePassthrough and RunnableParallel\n // input has two properties: expression and context\n // expression goes through mapQuery and parallely\n // context goes through textSplitter and mapDoc\n // Finally reduceChain is called with the results of mapQuery and mapDoc\n // LCEL-based implementation using RunnableSequence, RunnableParallel, and RunnablePassthrough\n const { RunnableSequence, RunnableParallel, RunnablePassthrough } =\n await import('@langchain/core/runnables');\n\n const mapQuery: BaseChain = new BaseChain(this.container);\n const mapDoc: BaseChain = new BaseChain(this.container);\n const reduceChain: BaseChain = new BaseChain(this.container);\n mapQuery.name = 'MapQuery';\n mapQuery.description = 'Map the expression to a natural language query.';\n mapQuery.template = this.resolve('litl_mapquery_template', this._mapQueryTemplate);\n mapDoc.name = 'MapDoc';\n mapDoc.description = 'Map the document to a set of facts.';\n mapDoc.template = this.resolve('litl_mapdoc_template', this._mapDocTemplate);\n reduceChain.name = 'ReduceChain';\n reduceChain.description = 'Reduce a set of documents to binary answer.';\n reduceChain.template = this.resolve('litl_reduce_chain_template', this._reduceChainTemplate);\n const mapQueryChain = RunnablePassthrough.assign({\n query: async (input: any) =>\n mapQuery.chain({ expression: input.input.expression }),\n });\n\n const mapDocChain = RunnablePassthrough.assign({\n documents: async (input: any) => {\n const textChunks = await this.textSplitter(input.input.context);\n return Promise.all(\n textChunks.map((chunk) =>\n mapDoc.chain({\n document: chunk,\n statements: input.input.expression,\n })\n )\n );\n },\n });\n\n const parallelChain = RunnableParallel.from([mapQueryChain, mapDocChain]);\n\n const sequence = RunnableSequence.from([\n parallelChain,\n async (results: any) => {\n /* results is an array: [{ query: ... }, { documents: [...] }]\n{\n \"0\": {\n \"input\": {\n \"expression\": \"0 Visual foot exam showed active infection?\",\n \"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. \"\n },\n \"query\": \"The text indicates a question about whether a visual foot exam revealed an active infection.\\n\"\n },\n \"1\": {\n \"input\": {\n \"expression\": \"0 Visual foot exam showed active infection?\",\n \"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. \"\n },\n \"documents\": [\n \"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\"\n ]\n }\n}\n */\n log.info(`Results from parallel chain: ${JSON.stringify(results)}`);\n const expression = results[0].input.expression;\n const query = results[0].query;\n const documents = results[1].documents;\n return reduceChain.chain({\n facts: documents,\n query: query + ' ' + expression,\n });\n },\n (result: any) => this.stringToBoolean(result),\n ]);\n\n return sequence.invoke(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BaseChain } from './chain';\nimport type { ToolInterface } from '@langchain/core/tools';\nimport { createStructuredChatAgent, AgentExecutor } from 'langchain/agents';\n\nexport class BaseAgent extends BaseChain {\n private _tools: ToolInterface[] = [];\n\n\n get tools(): ToolInterface[] {\n return this._tools;\n }\n set tools(value: ToolInterface[]) {\n this._tools = value;\n }\n\n /**\n * Run the agent using the provided input.\n * This uses createStructuredChatAgent and AgentExecutor from langchain/agents.\n */\n async run(input: any) {\n const agent = await createStructuredChatAgent({\n llm: this.llm,\n tools: this._tools,\n prompt: this.prompt,\n });\n const agentExecutor = new AgentExecutor({\n agent: agent,\n tools: this.tools,\n // verbose: true,\n handleParsingErrors:\n 'Please try again, paying close attention to the final answer',\n });\n return await agentExecutor.invoke(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Embeddings, type EmbeddingsParams } from '@langchain/core/embeddings';\n\n/**\n * Parameters for configuring BaseEmbedding\n */\nexport interface BaseEmbeddingInput extends EmbeddingsParams {\n baseUrl: string;\n model: string;\n apiKey?: string;\n}\n\n/**\n * BaseEmbedding is a base class for embeddings that communicate with a remote API.\n * It extends the LangChain Embeddings class and provides methods for embedding\n * documents and queries.\n */\nexport class BaseEmbedding extends Embeddings {\n baseUrl: string;\n model: string;\n apiKey: string;\n\n constructor(fields: BaseEmbeddingInput) {\n super(fields);\n this.baseUrl = fields.baseUrl;\n this.model = fields.model;\n this.apiKey = fields.apiKey ?? '';\n }\n\n /**\n * Embed a list of documents\n * @param texts - Array of strings to embed\n * @returns Promise of array of embedding vectors\n */\n async embedDocuments(texts: string[]): Promise<number[][]> {\n return this.getEmbeddings(texts);\n }\n\n /**\n * Embed a single query\n * @param text - String to embed\n * @returns Promise of embedding vector\n */\n async embedQuery(text: string): Promise<number[]> {\n const embeddings = await this.getEmbeddings([text]);\n return embeddings[0];\n }\n\n /**\n * Helper method to get embeddings for a list of texts\n * @param texts - Array of strings to embed\n * @returns Promise of array of embedding vectors\n */\n protected async getEmbeddings(texts: string[]): Promise<number[][]> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n\n const payload = {\n model: this.model,\n input: texts,\n };\n\n const response = await fetch(this.baseUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(\n `API request failed: status=${response.status}; body=${body}`\n );\n }\n\n const respJson = await response.json();\n\n if (!('embeddings' in respJson)) {\n throw new Error(\n `API response missing 'embeddings' key. Received keys: ${Object.keys(\n respJson\n ).join(', ')}`\n );\n }\n\n return respJson.embeddings as number[][];\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLM, type BaseLLMParams } from '@langchain/core/language_models/llms';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\n\n/**\n * Model parameters for BaseLLM\n */\nexport interface ModelParams {\n maxOutputTokens?: number;\n nPredict?: number;\n topK?: number;\n topP?: number;\n temperature?: number;\n nBatch?: number;\n repeatPenalty?: number;\n repeatLastN?: number;\n}\n\n/**\n * Parameters for configuring BaseLLM\n */\nexport interface BaseLLMInput extends BaseLLMParams {\n baseUrl: string;\n model: string;\n apiKey?: string;\n timeout?: number;\n backend?: string;\n temperature?: number;\n topP?: number;\n topK?: number;\n nBatch?: number;\n nThreads?: number;\n nPredict?: number;\n maxOutputTokens?: number;\n repeatLastN?: number;\n repeatPenalty?: number;\n}\n\n/**\n * BaseLLM is a base class for LLMs that communicate with a remote API.\n * It extends the LangChain LLM class and provides configurable parameters\n * for model inference.\n */\nexport class BaseLLM extends LLM {\n baseUrl: string;\n model: string;\n apiKey: string;\n timeout: number;\n backend: string;\n temperature: number;\n topP: number;\n topK: number;\n nBatch: number;\n nThreads: number;\n nPredict: number;\n maxOutputTokens: number;\n repeatLastN: number;\n repeatPenalty: number;\n\n constructor(fields: BaseLLMInput) {\n super(fields);\n this.baseUrl = fields.baseUrl;\n this.model = fields.model;\n this.apiKey = fields.apiKey ?? '';\n this.timeout = fields.timeout ?? 60000;\n this.backend = fields.backend ?? 'dhti';\n this.temperature = fields.temperature ?? 0.1;\n this.topP = fields.topP ?? 0.8;\n this.topK = fields.topK ?? 40;\n this.nBatch = fields.nBatch ?? 8;\n this.nThreads = fields.nThreads ?? 4;\n this.nPredict = fields.nPredict ?? 256;\n this.maxOutputTokens = fields.maxOutputTokens ?? 512;\n this.repeatLastN = fields.repeatLastN ?? 64;\n this.repeatPenalty = fields.repeatPenalty ?? 1.18;\n }\n\n /**\n * Get the model default parameters\n */\n get modelDefaultParameters(): ModelParams {\n return {\n maxOutputTokens: this.maxOutputTokens,\n nPredict: this.nPredict,\n topK: this.topK,\n topP: this.topP,\n temperature: this.temperature,\n nBatch: this.nBatch,\n repeatPenalty: this.repeatPenalty,\n repeatLastN: this.repeatLastN,\n };\n }\n\n /**\n * Get the identifying parameters\n */\n get identifyingParams(): Record<string, unknown> {\n return {\n model: this.model,\n baseUrl: this.baseUrl,\n modelParameters: this.modelDefaultParameters,\n };\n }\n\n /**\n * Get the LLM type identifier\n */\n _llmType(): string {\n return 'dhti';\n }\n\n /**\n * Prepare the request payload for the API\n */\n protected preparePayload(prompt: string): Record<string, unknown> {\n return {\n model: this.model,\n options: this.modelDefaultParameters,\n messages: [{ role: 'user', content: prompt }],\n };\n }\n\n /**\n * Make the API call to generate text\n */\n async _call(\n prompt: string,\n _options: this['ParsedCallOptions'],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<string> {\n const payload = this.preparePayload(prompt);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(this.baseUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(\n `API request failed: status=${response.status}; body=${body}`\n );\n }\n\n const data = await response.json();\n\n // Expecting structure like: { \"choices\": [ { \"message\": { \"role\":\"assistant\",\"content\":\"...\" } } ] }\n // Adapt this path if the API differs\n if (\n data.choices &&\n Array.isArray(data.choices) &&\n data.choices.length > 0\n ) {\n const choice = data.choices[0];\n // support both \"message\" and direct \"text\"\n if (\n typeof choice === 'object' &&\n choice !== null &&\n 'message' in choice &&\n typeof choice.message === 'object' &&\n choice.message !== null\n ) {\n const content = (choice.message as Record<string, unknown>).content;\n if (typeof content === 'string') {\n return content;\n }\n } else if ('text' in choice) {\n const text = choice.text;\n if (typeof text === 'string') {\n return text;\n }\n }\n }\n\n // Fallback: return raw JSON string for debugging\n return JSON.stringify(data);\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === 'AbortError') {\n throw new Error(`API request timed out after ${this.timeout}ms`);\n }\n throw error;\n }\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DynamicStructuredTool } from 'langchain/tools';\nimport mydi from './mydi';\n\nexport class BaseTool extends DynamicStructuredTool {\n /** @hidden */\n container: any;\n name: string;\n description: string;\n schema: any;\n constructor(\n container: any,\n name: string,\n description: string,\n schema: any,\n func: any = null\n ) {\n super({\n name: name,\n description: description,\n schema: schema,\n func: func,\n });\n this.container = container;\n this.name = name === '' ? this.camelize(this.constructor.name) : name;\n this.description =\n description === '' ? this.snake_case(this.constructor.name) : description;\n this.schema = schema;\n }\n\n func = async (args: any) => {\n return 'override this';\n };\n\n resolve(name: string) {\n return mydi(this.container, this.name, name);\n }\n\n camelize(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n }\n\n snake_case(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();\n })\n .replace(/\\s+/g, '');\n }\n\n /**\n * @param input - The input to process in batch.\n * @param config - The configuration for the batch.\n * @returns A promise resolving to an array of results.\n */\n async _batchWithConfig(input: any, config: any): Promise<any[]> {\n // Call the parent implementation or provide your own\n return super._batchWithConfig(input, config);\n }\n}\n"],"names":["mydi","c","m","b","resolve","e","BaseChain","constructor","container","this","_name","_description","_template","prompt","llm","chat_model","runnable","fakeLLM","FakeListChatModel","responses","camelize","name","snake_case","initializePrompt","ChatPromptTemplate","fromTemplate","PromptTemplate","value","description","template","defaultValue","str","replace","word","index","toLowerCase","toUpperCase","chain","input","outputParser","StringOutputParser","RunnableSequence","from","RunnablePassthrough","response","invoke","AIMessage","content","log","Logger","args","super","_tools","tools","run","agent","createStructuredChatAgent","agentExecutor","AgentExecutor","handleParsingErrors","Embeddings","fields","_fields$apiKey","baseUrl","model","apiKey","embedDocuments","texts","getEmbeddings","embedQuery","text","headers","payload","fetch","method","body","JSON","stringify","ok","Error","status","respJson","json","Object","keys","join","embeddings","LLM","_fields$timeout","_fields$backend","_fields$temperature","_fields$topP","_fields$topK","_fields$nBatch","_fields$nThreads","_fields$nPredict","_fields$maxOutputToke","_fields$repeatLastN","_fields$repeatPenalty","timeout","backend","temperature","topP","topK","nBatch","nThreads","nPredict","maxOutputTokens","repeatLastN","repeatPenalty","modelDefaultParameters","identifyingParams","modelParameters","_llmType","preparePayload","options","messages","role","_call","_options","_runManager","controller","AbortController","timeoutId","setTimeout","abort","signal","clearTimeout","data","choices","Array","isArray","length","choice","message","error","DynamicStructuredTool","schema","func","async","_batchWithConfig","config","stringExpression","_mapQueryTemplate","_mapDocTemplate","_reduceChainTemplate","mapQueryTemplate","mapDocTemplate","reduceChainTemplate","checkAssertion","expression","context","_context","_expression","printValues","parse","info","_content","warn","forEach","element","contentItem","atob","attachment","findDatesAndConvertToTimeElapsed","_input","result","checkMention","checkNegation","dateRegex","matches","currentDate","Date","exec","date","timeElapsed","getTime","Math","floor","toString","camelToString","camelCase","stringToBoolean","lowerStr","some","keyword","includes","textSplitter","chunkSize","chunkOverlap","CharacterTextSplitter","splitText","obj","arg","where","extractObjectsByKey","key","results","traverse","currentKey","hasOwnProperty","push","_printValues","regex","RegExp","RunnableParallel","import","mapQuery","mapDoc","reduceChain","mapQueryChain","assign","query","mapDocChain","documents","textChunks","Promise","all","map","chunk","document","statements","parallelChain","facts"],"mappings":"+dAgBA,MAAMA,EAAOA,CAACC,EAAQC,EAAWC,KAC/B,IACE,OAAOF,EAAEG,QAAQF,EAAI,IAAMC,EAC7B,CAAE,MAAOE,GAAK,CACd,IACE,OAAOJ,EAAEG,QAAQF,EAAI,IAAMC,EAC7B,CAAE,MAAOE,GAAI,CACb,IACE,OAAOJ,EAAEG,QAAQD,EACnB,CAAE,MAAOE,GAAI,CACb,OAAO,YCCIC,EAiBXC,WAAAA,CAAYC,GAAcC,KAhB1BD,eAAS,EAAAC,KACDC,MAAgB,GAAED,KAClBE,aAAuB,GAAEF,KACzBG,UAAoB,GAAEH,KAC9BI,YAAM,EAAAJ,KACNK,SAAG,EAAAL,KACHM,gBAAU,EAAAN,KACVO,cAAQ,EAAAP,KACRQ,QAA8B,IAAIC,oBAAkB,CAClDC,UAAW,CACT,mEACA,8CACA,qEAKFV,KAAKD,UAAYA,EACjBC,KAAKC,MAAQD,KAAKW,SAASX,KAAKF,YAAYc,MAC5CZ,KAAKE,aAAeF,KAAKa,WAAWb,KAAKF,YAAYc,MACrDZ,KAAKK,IAAML,KAAKL,QAAQ,MAAOK,KAAKQ,SACpCR,KAAKG,UAAYH,KAAKL,QAAQ,WAAY,WAC1CK,KAAKM,WAAaN,KAAKL,QAAQ,cAAc,GAC7CK,KAAKc,kBACP,CAEAA,gBAAAA,GAEId,KAAKI,OADHJ,KAAKM,WACOS,EAAkBA,mBAACC,aAAahB,KAAKG,WAErCc,EAAcA,eAACD,aAAahB,KAAKG,UAEnD,CAEA,QAAIS,GACF,OAAOZ,KAAKC,KACd,CACA,QAAIW,CAAKM,GACPlB,KAAKC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AIzM,EAAUG,KAAKD,WACzCwM,EAAoB,IAAI1M,EAAUG,KAAKD,WACvCyM,EAAyB,IAAI3M,EAAUG,KAAKD,WAClDuM,EAAS1L,KAAO,WAChB0L,EAASnL,YAAc,kDACvBmL,EAASlL,SAAWpB,KAAKL,QAAQ,yBAA0BK,KAAKsI,mBAChEiE,EAAO3L,KAAO,SACd2L,EAAOpL,YAAc,sCACrBoL,EAAOnL,SAAWpB,KAAKL,QAAQ,uBAAwBK,KAAKuI,iBAC5DiE,EAAY5L,KAAO,cACnB4L,EAAYrL,YAAc,8CAC1BqL,EAAYpL,SAAWpB,KAAKL,QAAQ,6BAA8BK,KAAKwI,sBACvE,MAAMiE,EAAgBvK,EAAoBwK,OAAO,CAC/CC,MAAOzE,SACLoE,EAAS1K,MAAM,CAAEiH,WAAYhH,EAAMA,MAAMgH,eAGvC+D,EAAc1K,EAAoBwK,OAAO,CAC7CG,UAAW3E,UACT,MAAM4E,QAAmB9M,KAAKkL,aAAarJ,EAAMA,MAAMiH,SACvD,OAAOiE,QAAQC,IACbF,EAAWG,IAAKC,GACdX,EAAO3K,MAAM,CACXuL,SAAUD,EACVE,WAAYvL,EAAMA,MAAMgH,kBAO5BwE,EAAgBjB,EAAiBnK,KAAK,CAACwK,EAAeG,IAqC5D,OAnCiB5K,EAAiBC,KAAK,CACrCoL,EACAnF,UAqBE3F,EAAI4G,KAAK,gCAAgChF,KAAKC,UAAUwH,MAIjDY,EAAY5K,MAAM,CACvB0L,MAFgB1B,EAAQ,GAAGiB,UAG3BF,MAJYf,EAAQ,GAAGe,MAIR,IALEf,EAAQ,GAAG/J,MAAMgH,cAQrCgB,GAAgB7J,KAAK6K,gBAAgBhB,KAGxBzH,OAAOP,EACzB"}
|
package/dist/medpromptjs.esm.js
CHANGED
|
@@ -2,6 +2,7 @@ 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
4
|
import { StringOutputParser } from '@langchain/core/output_parsers';
|
|
5
|
+
import { FakeListChatModel } from '@langchain/core/utils/testing';
|
|
5
6
|
import { createStructuredChatAgent, AgentExecutor } from 'langchain/agents';
|
|
6
7
|
import { DynamicStructuredTool } from 'langchain/tools';
|
|
7
8
|
import { CharacterTextSplitter } from '@langchain/textsplitters';
|
|
@@ -62,12 +63,18 @@ class BaseChain {
|
|
|
62
63
|
this.llm = void 0;
|
|
63
64
|
this.chat_model = void 0;
|
|
64
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
|
+
});
|
|
65
69
|
this.container = container;
|
|
66
70
|
this._name = this.camelize(this.constructor.name);
|
|
67
71
|
this._description = this.snake_case(this.constructor.name);
|
|
68
|
-
this.llm = this.resolve('llm');
|
|
69
|
-
this._template = this.resolve('template');
|
|
72
|
+
this.llm = this.resolve('llm', this.fakeLLM);
|
|
73
|
+
this._template = this.resolve('template', '{input}');
|
|
70
74
|
this.chat_model = this.resolve('chat-model', false);
|
|
75
|
+
this.initializePrompt();
|
|
76
|
+
}
|
|
77
|
+
initializePrompt() {
|
|
71
78
|
if (this.chat_model) {
|
|
72
79
|
this.prompt = ChatPromptTemplate.fromTemplate(this._template);
|
|
73
80
|
} else {
|
|
@@ -92,11 +99,7 @@ class BaseChain {
|
|
|
92
99
|
}
|
|
93
100
|
set template(value) {
|
|
94
101
|
this._template = value;
|
|
95
|
-
|
|
96
|
-
this.prompt = ChatPromptTemplate.fromTemplate(this._template);
|
|
97
|
-
} else {
|
|
98
|
-
this.prompt = PromptTemplate.fromTemplate(this._template);
|
|
99
|
-
}
|
|
102
|
+
this.initializePrompt();
|
|
100
103
|
}
|
|
101
104
|
resolve(name, defaultValue = null) {
|
|
102
105
|
return mydi(this.container, this.camelize(this.constructor.name), name) || defaultValue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"medpromptjs.esm.js","sources":["../src/mydi.ts","../src/chain.ts","../src/agent.ts","../src/tool.ts","../src/llm_loop.ts","../src/llm.ts","../src/embedding.ts"],"sourcesContent":["/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst mydi = (c: any, m: string, b: string) => {\n try {\n return c.resolve(m + '_' + b);\n } catch (e) { }\n try {\n return c.resolve(m + '-' + b);\n } catch (e) {}\n try {\n return c.resolve(b);\n } catch (e) {}\n return null;\n};\n\nexport default mydi;\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PromptTemplate, ChatPromptTemplate } from '@langchain/core/prompts';\nimport { LLM } from '@langchain/core/language_models/llms';\nimport mydi from './mydi';\nimport {\n RunnablePassthrough,\n RunnableSequence,\n} from '@langchain/core/runnables';\nimport { AIMessage } from '@langchain/core/messages';\nimport { StringOutputParser } from '@langchain/core/output_parsers';\n\nexport class BaseChain {\n container: any;\n private _name: string = '';\n private _description: string = '';\n private _template: string = '';\n prompt: any;\n llm: LLM;\n chat_model: boolean;\n runnable: any;\n\n constructor(container: any) {\n this.container = container;\n this._name = this.camelize(this.constructor.name);\n this._description = this.snake_case(this.constructor.name);\n this.llm = this.resolve('llm');\n this._template = this.resolve('template');\n this.chat_model = this.resolve('chat-model', false);\n if (this.chat_model) {\n this.prompt = ChatPromptTemplate.fromTemplate(this._template);\n } else {\n this.prompt = PromptTemplate.fromTemplate(this._template);\n }\n }\n\n // Getters and setters\n get name(): string {\n return this._name;\n }\n set name(value: string) {\n this._name = value === '' ? this.camelize(this.constructor.name) : value;\n }\n\n get description(): string {\n return this._description;\n }\n set description(value: string) {\n this._description =\n value === '' ? this.snake_case(this.constructor.name) : value;\n }\n\n get template(): string {\n return this._template;\n }\n set template(value: string) {\n this._template = value;\n if (this.chat_model) {\n this.prompt = ChatPromptTemplate.fromTemplate(this._template);\n } else {\n this.prompt = PromptTemplate.fromTemplate(this._template);\n }\n }\n\n resolve(name: string, defaultValue: any = null): any {\n return (\n mydi(this.container, this.camelize(this.constructor.name), name) ||\n defaultValue\n );\n }\n\n camelize(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n }\n\n snake_case(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();\n })\n .replace(/\\s+/g, '');\n }\n\n // https://js.langchain.com/v0.1/docs/expression_language/how_to/routing/\n //! Override this method\n async chain(input: any) {\n const outputParser = new StringOutputParser();\n this.runnable = RunnableSequence.from([\n {\n input: new RunnablePassthrough(),\n // context: async () => loadContextFromStore(),\n },\n this.prompt,\n this.llm,\n outputParser,\n ]);\n if (this.chat_model) {\n const response: string = await this.runnable.invoke(input);\n const aiMessage = new AIMessage(response);\n return aiMessage.content;\n }\n return await this.runnable.invoke(input);\n }\n\n async invoke(input: any) {\n return this.chain(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BaseChain } from './chain';\nimport type { ToolInterface } from '@langchain/core/tools';\nimport { createStructuredChatAgent, AgentExecutor } from 'langchain/agents';\n\nexport class BaseAgent extends BaseChain {\n private _tools: ToolInterface[] = [];\n\n\n get tools(): ToolInterface[] {\n return this._tools;\n }\n set tools(value: ToolInterface[]) {\n this._tools = value;\n }\n\n /**\n * Run the agent using the provided input.\n * This uses createStructuredChatAgent and AgentExecutor from langchain/agents.\n */\n async run(input: any) {\n const agent = await createStructuredChatAgent({\n llm: this.llm,\n tools: this._tools,\n prompt: this.prompt,\n });\n const agentExecutor = new AgentExecutor({\n agent: agent,\n tools: this.tools,\n // verbose: true,\n handleParsingErrors:\n 'Please try again, paying close attention to the final answer',\n });\n return await agentExecutor.invoke(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DynamicStructuredTool } from 'langchain/tools';\nimport mydi from './mydi';\n\nexport class BaseTool extends DynamicStructuredTool {\n /** @hidden */\n container: any;\n name: string;\n description: string;\n schema: any;\n constructor(\n container: any,\n name: string,\n description: string,\n schema: any,\n func: any = null\n ) {\n super({\n name: name,\n description: description,\n schema: schema,\n func: func,\n });\n this.container = container;\n this.name = name === '' ? this.camelize(this.constructor.name) : name;\n this.description =\n description === '' ? this.snake_case(this.constructor.name) : description;\n this.schema = schema;\n }\n\n func = async (args: any) => {\n return 'override this';\n };\n\n resolve(name: string) {\n return mydi(this.container, this.name, name);\n }\n\n camelize(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n }\n\n snake_case(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();\n })\n .replace(/\\s+/g, '');\n }\n\n /**\n * @param input - The input to process in batch.\n * @param config - The configuration for the batch.\n * @returns A promise resolving to an array of results.\n */\n async _batchWithConfig(input: any, config: any): Promise<any[]> {\n // Call the parent implementation or provide your own\n return super._batchWithConfig(input, config);\n }\n}\n","import { BaseChain } from './chain';\nimport { CharacterTextSplitter } from '@langchain/textsplitters';\nimport { Logger, ILogObj } from 'tslog';\n\nconst log: Logger<ILogObj> = new Logger();\nexport class LLMLoop extends BaseChain {\n // Implement the LLM loop logic here\n stringExpression: string = '';\n _mapQueryTemplate: string = `\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: `;\n\n _mapDocTemplate: string = `\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: `;\n\n _reduceChainTemplate: string = `\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: `;\n\n // Add getters and setters for the templates if needed\n get mapQueryTemplate(): string {\n return this._mapQueryTemplate;\n }\n set mapQueryTemplate(template: string) {\n this._mapQueryTemplate = template;\n }\n get mapDocTemplate(): string {\n return this._mapDocTemplate;\n }\n set mapDocTemplate(template: string) {\n this._mapDocTemplate = template;\n }\n get reduceChainTemplate(): string {\n return this._reduceChainTemplate;\n }\n set reduceChainTemplate(template: string) {\n this._reduceChainTemplate = template;\n }\n\n async checkAssertion(expression: string, context: any): Promise<boolean> {\n let _expression: string = '';\n try {\n // Check if expression is a valid JSON string\n _expression = this.printValues(JSON.parse(expression));\n } catch (error) {\n _expression = expression; // If not, use the expression as is\n }\n\n log.info(`Checking assertion with expression: ${_expression}`);\n // Initialize context and content\n let _context: any = undefined;\n let _content: string = '';\n try {\n _context = JSON.parse(context);\n } catch (error) {\n _context = context; // If not, use the context as is\n log.warn(`Context is not a valid JSON string: ${context}`);\n log.warn(`Using context as a string: ${_context}`);\n }\n try {\n // Check if context is a valid JSON string\n _context = JSON.parse(context);\n _context.forEach((element: any) => {\n element.content.forEach((contentItem: any) => {\n _content += atob(contentItem.attachment.data.value);\n });\n });\n } catch (error) {\n _content = context; // If not, use the context as is\n log.warn(`Context is not a valid JSON : ${context}`);\n log.warn(`Using context as a string: ${_content}`);\n }\n _content = this.findDatesAndConvertToTimeElapsed(\n _content.replace(/(\\r\\n|\\n|\\r)/gm, ' ')\n );\n log.info(`Checking assertion with context: ${_content}`);\n const _input = {\n input: {\n expression: _expression,\n context: _content,\n },\n };\n const result = await this.chain(_input);\n log.info(`Assertion check result: ${result}`);\n return result;\n }\n\n async checkMention(expression: string, context: any): Promise<boolean> {\n if (expression && context) return true; // Placeholder for assertion check logic\n return false;\n }\n\n async checkNegation(expression: string, context: any): Promise<boolean> {\n if (expression && context) return true; // Placeholder for assertion check logic\n return false;\n }\n\n findDatesAndConvertToTimeElapsed(text: string): string {\n // Regular expression to match dates in format of 'mm/dd/yyyy' or 'mm-dd-yyyy'\n const dateRegex = /(\\d{1,2}[-/]\\d{1,2}[-/]\\d{4})/g;\n let matches;\n let currentDate = new Date();\n\n while ((matches = dateRegex.exec(text)) !== null) {\n let date = new Date(matches[0]);\n let timeElapsed =\n (currentDate.getTime() - date.getTime()) / (1000 * 60 * 60 * 24);\n text = text.replace(\n matches[0],\n Math.floor(timeElapsed).toString() + ' days ago.'\n );\n }\n return text;\n }\n\n camelToString(camelCase: string): string {\n return camelCase.replace(/([A-Z])/g, ' $1').replace(/^./, function (str) {\n return str.toUpperCase();\n });\n }\n\n stringToBoolean(str: string): boolean {\n log.info(`Converting string to boolean: ${str}`);\n const positiveKeywords = [\n 'true',\n 'contains',\n 'confirms',\n 'yes',\n 'affirmative',\n 'matches',\n 'exists',\n 'present',\n 'absolutely',\n 'certainly',\n 'definitely',\n 'indeed',\n 'did have',\n 'showed',\n 'revealed',\n ];\n const lowerStr = str.toLowerCase();\n return positiveKeywords.some((keyword) => lowerStr.includes(keyword));\n }\n\n async textSplitter(\n text: string,\n chunkSize: number = 3900,\n chunkOverlap: number = 0\n ): Promise<string[]> {\n const textSplitter = new CharacterTextSplitter({\n chunkSize: chunkSize,\n chunkOverlap: chunkOverlap,\n });\n const texts = await textSplitter.splitText(text);\n // Log the number of chunks created\n if (texts.length === 0) {\n log.warn('No text chunks created. Please check the input text.');\n return [];\n }\n if (texts.length > 100) {\n log.warn(\n `Warning: More than 100 text chunks created (${texts.length}). This may affect performance.`\n );\n }\n if (chunkSize < 1000) {\n log.warn(\n `Warning: Chunk size is less than 1000 characters (${chunkSize}). This may lead to very small chunks.`\n );\n }\n log.info(\n `Text split into ${texts.length} chunks with size ${chunkSize} and overlap ${chunkOverlap}`\n );\n return texts;\n }\n\n printValues(obj: any) {\n log.info(`Processing Rule: ${obj.name} for ${obj.context}`);\n // For each obj.expression:arg:where\n if (obj.expression && obj.expression.arg && obj.expression.arg.where) {\n // for each args in obj.expression.arg.where, extract the nested key called \"value\"\n const statements = this.extractObjectsByKey(\n obj.expression.arg.where,\n 'value'\n );\n return statements.join(' ').replace(/,/g, ' ');\n }\n // return statements array as a string seperated by space\n return '';\n }\n\n extractObjectsByKey(obj: any, key: string): any[] {\n const results: any[] = [];\n\n function traverse(obj: any) {\n for (const currentKey in obj) {\n if (obj.hasOwnProperty(currentKey)) {\n if (currentKey === key) {\n results.push(obj[currentKey]);\n }\n if (typeof obj[currentKey] === 'object' && obj[currentKey] !== null) {\n traverse(obj[currentKey]);\n }\n }\n }\n }\n\n traverse(obj);\n return results;\n }\n\n _printValues(obj: any) {\n for (var key in obj) {\n if (typeof obj[key] === 'object') {\n this._printValues(obj[key]);\n } else {\n this.stringExpression += obj[key] + ' ';\n }\n }\n const _eliminate = [\n 'true',\n 'false',\n 'null',\n 'undefined',\n 'String',\n 'Number',\n 'Object',\n 'Array',\n 'Boolean',\n 'value',\n 'Type',\n 'Specifier',\n 'Named',\n ];\n _eliminate.forEach((element) => {\n const regex = new RegExp(element, 'g');\n this.stringExpression = this.stringExpression.replace(regex, '');\n });\n this.stringExpression = this.stringExpression.replace(\n /(?:https?|ftp):\\/\\/[\\n\\S]+/g,\n ''\n );\n return this.camelToString(this.stringExpression);\n }\n\n async chain(input: any) {\n // Create a chain using RunnableSequence, RunnablePassthrough and RunnableParallel\n // input has two properties: expression and context\n // expression goes through mapQuery and parallely\n // context goes through textSplitter and mapDoc\n // Finally reduceChain is called with the results of mapQuery and mapDoc\n // LCEL-based implementation using RunnableSequence, RunnableParallel, and RunnablePassthrough\n const { RunnableSequence, RunnableParallel, RunnablePassthrough } =\n await import('@langchain/core/runnables');\n\n const mapQuery: BaseChain = new BaseChain(this.container);\n const mapDoc: BaseChain = new BaseChain(this.container);\n const reduceChain: BaseChain = new BaseChain(this.container);\n mapQuery.name = 'MapQuery';\n mapQuery.description = 'Map the expression to a natural language query.';\n mapQuery.template = this.resolve('litl_mapquery_template', this._mapQueryTemplate);\n mapDoc.name = 'MapDoc';\n mapDoc.description = 'Map the document to a set of facts.';\n mapDoc.template = this.resolve('litl_mapdoc_template', this._mapDocTemplate);\n reduceChain.name = 'ReduceChain';\n reduceChain.description = 'Reduce a set of documents to binary answer.';\n reduceChain.template = this.resolve('litl_reduce_chain_template', this._reduceChainTemplate);\n const mapQueryChain = RunnablePassthrough.assign({\n query: async (input: any) =>\n mapQuery.chain({ expression: input.input.expression }),\n });\n\n const mapDocChain = RunnablePassthrough.assign({\n documents: async (input: any) => {\n const textChunks = await this.textSplitter(input.input.context);\n return Promise.all(\n textChunks.map((chunk) =>\n mapDoc.chain({\n document: chunk,\n statements: input.input.expression,\n })\n )\n );\n },\n });\n\n const parallelChain = RunnableParallel.from([mapQueryChain, mapDocChain]);\n\n const sequence = RunnableSequence.from([\n parallelChain,\n async (results: any) => {\n /* results is an array: [{ query: ... }, { documents: [...] }]\n{\n \"0\": {\n \"input\": {\n \"expression\": \"0 Visual foot exam showed active infection?\",\n \"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. \"\n },\n \"query\": \"The text indicates a question about whether a visual foot exam revealed an active infection.\\n\"\n },\n \"1\": {\n \"input\": {\n \"expression\": \"0 Visual foot exam showed active infection?\",\n \"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. \"\n },\n \"documents\": [\n \"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\"\n ]\n }\n}\n */\n log.info(`Results from parallel chain: ${JSON.stringify(results)}`);\n const expression = results[0].input.expression;\n const query = results[0].query;\n const documents = results[1].documents;\n return reduceChain.chain({\n facts: documents,\n query: query + ' ' + expression,\n });\n },\n (result: any) => this.stringToBoolean(result),\n ]);\n\n return sequence.invoke(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLM, type BaseLLMParams } from '@langchain/core/language_models/llms';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\n\n/**\n * Model parameters for BaseLLM\n */\nexport interface ModelParams {\n maxOutputTokens?: number;\n nPredict?: number;\n topK?: number;\n topP?: number;\n temperature?: number;\n nBatch?: number;\n repeatPenalty?: number;\n repeatLastN?: number;\n}\n\n/**\n * Parameters for configuring BaseLLM\n */\nexport interface BaseLLMInput extends BaseLLMParams {\n baseUrl: string;\n model: string;\n apiKey?: string;\n timeout?: number;\n backend?: string;\n temperature?: number;\n topP?: number;\n topK?: number;\n nBatch?: number;\n nThreads?: number;\n nPredict?: number;\n maxOutputTokens?: number;\n repeatLastN?: number;\n repeatPenalty?: number;\n}\n\n/**\n * BaseLLM is a base class for LLMs that communicate with a remote API.\n * It extends the LangChain LLM class and provides configurable parameters\n * for model inference.\n */\nexport class BaseLLM extends LLM {\n baseUrl: string;\n model: string;\n apiKey: string;\n timeout: number;\n backend: string;\n temperature: number;\n topP: number;\n topK: number;\n nBatch: number;\n nThreads: number;\n nPredict: number;\n maxOutputTokens: number;\n repeatLastN: number;\n repeatPenalty: number;\n\n constructor(fields: BaseLLMInput) {\n super(fields);\n this.baseUrl = fields.baseUrl;\n this.model = fields.model;\n this.apiKey = fields.apiKey ?? '';\n this.timeout = fields.timeout ?? 60000;\n this.backend = fields.backend ?? 'dhti';\n this.temperature = fields.temperature ?? 0.1;\n this.topP = fields.topP ?? 0.8;\n this.topK = fields.topK ?? 40;\n this.nBatch = fields.nBatch ?? 8;\n this.nThreads = fields.nThreads ?? 4;\n this.nPredict = fields.nPredict ?? 256;\n this.maxOutputTokens = fields.maxOutputTokens ?? 512;\n this.repeatLastN = fields.repeatLastN ?? 64;\n this.repeatPenalty = fields.repeatPenalty ?? 1.18;\n }\n\n /**\n * Get the model default parameters\n */\n get modelDefaultParameters(): ModelParams {\n return {\n maxOutputTokens: this.maxOutputTokens,\n nPredict: this.nPredict,\n topK: this.topK,\n topP: this.topP,\n temperature: this.temperature,\n nBatch: this.nBatch,\n repeatPenalty: this.repeatPenalty,\n repeatLastN: this.repeatLastN,\n };\n }\n\n /**\n * Get the identifying parameters\n */\n get identifyingParams(): Record<string, unknown> {\n return {\n model: this.model,\n baseUrl: this.baseUrl,\n modelParameters: this.modelDefaultParameters,\n };\n }\n\n /**\n * Get the LLM type identifier\n */\n _llmType(): string {\n return 'dhti';\n }\n\n /**\n * Prepare the request payload for the API\n */\n protected preparePayload(prompt: string): Record<string, unknown> {\n return {\n model: this.model,\n options: this.modelDefaultParameters,\n messages: [{ role: 'user', content: prompt }],\n };\n }\n\n /**\n * Make the API call to generate text\n */\n async _call(\n prompt: string,\n _options: this['ParsedCallOptions'],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<string> {\n const payload = this.preparePayload(prompt);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(this.baseUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(\n `API request failed: status=${response.status}; body=${body}`\n );\n }\n\n const data = await response.json();\n\n // Expecting structure like: { \"choices\": [ { \"message\": { \"role\":\"assistant\",\"content\":\"...\" } } ] }\n // Adapt this path if the API differs\n if (\n data.choices &&\n Array.isArray(data.choices) &&\n data.choices.length > 0\n ) {\n const choice = data.choices[0];\n // support both \"message\" and direct \"text\"\n if (\n typeof choice === 'object' &&\n choice !== null &&\n 'message' in choice &&\n typeof choice.message === 'object' &&\n choice.message !== null\n ) {\n const content = (choice.message as Record<string, unknown>).content;\n if (typeof content === 'string') {\n return content;\n }\n } else if ('text' in choice) {\n const text = choice.text;\n if (typeof text === 'string') {\n return text;\n }\n }\n }\n\n // Fallback: return raw JSON string for debugging\n return JSON.stringify(data);\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === 'AbortError') {\n throw new Error(`API request timed out after ${this.timeout}ms`);\n }\n throw error;\n }\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Embeddings, type EmbeddingsParams } from '@langchain/core/embeddings';\n\n/**\n * Parameters for configuring BaseEmbedding\n */\nexport interface BaseEmbeddingInput extends EmbeddingsParams {\n baseUrl: string;\n model: string;\n apiKey?: string;\n}\n\n/**\n * BaseEmbedding is a base class for embeddings that communicate with a remote API.\n * It extends the LangChain Embeddings class and provides methods for embedding\n * documents and queries.\n */\nexport class BaseEmbedding extends Embeddings {\n baseUrl: string;\n model: string;\n apiKey: string;\n\n constructor(fields: BaseEmbeddingInput) {\n super(fields);\n this.baseUrl = fields.baseUrl;\n this.model = fields.model;\n this.apiKey = fields.apiKey ?? '';\n }\n\n /**\n * Embed a list of documents\n * @param texts - Array of strings to embed\n * @returns Promise of array of embedding vectors\n */\n async embedDocuments(texts: string[]): Promise<number[][]> {\n return this.getEmbeddings(texts);\n }\n\n /**\n * Embed a single query\n * @param text - String to embed\n * @returns Promise of embedding vector\n */\n async embedQuery(text: string): Promise<number[]> {\n const embeddings = await this.getEmbeddings([text]);\n return embeddings[0];\n }\n\n /**\n * Helper method to get embeddings for a list of texts\n * @param texts - Array of strings to embed\n * @returns Promise of array of embedding vectors\n */\n protected async getEmbeddings(texts: string[]): Promise<number[][]> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n\n const payload = {\n model: this.model,\n input: texts,\n };\n\n const response = await fetch(this.baseUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(\n `API request failed: status=${response.status}; body=${body}`\n );\n }\n\n const respJson = await response.json();\n\n if (!('embeddings' in respJson)) {\n throw new Error(\n `API response missing 'embeddings' key. Received keys: ${Object.keys(\n respJson\n ).join(', ')}`\n );\n }\n\n return respJson.embeddings as number[][];\n }\n}\n"],"names":["mydi","c","m","b","resolve","e","BaseChain","constructor","container","_name","_description","_template","prompt","llm","chat_model","runnable","camelize","name","snake_case","ChatPromptTemplate","fromTemplate","PromptTemplate","value","description","template","defaultValue","str","replace","word","index","toLowerCase","toUpperCase","chain","input","outputParser","StringOutputParser","RunnableSequence","from","RunnablePassthrough","response","invoke","aiMessage","AIMessage","content","BaseAgent","args","_tools","tools","run","agent","createStructuredChatAgent","agentExecutor","AgentExecutor","handleParsingErrors","BaseTool","DynamicStructuredTool","schema","func","_batchWithConfig","config","log","Logger","LLMLoop","stringExpression","_mapQueryTemplate","_mapDocTemplate","_reduceChainTemplate","mapQueryTemplate","mapDocTemplate","reduceChainTemplate","checkAssertion","expression","context","_expression","printValues","JSON","parse","error","info","_context","undefined","_content","warn","forEach","element","contentItem","atob","attachment","data","findDatesAndConvertToTimeElapsed","_input","result","checkMention","checkNegation","text","dateRegex","matches","currentDate","Date","exec","date","timeElapsed","getTime","Math","floor","toString","camelToString","camelCase","stringToBoolean","positiveKeywords","lowerStr","some","keyword","includes","textSplitter","chunkSize","chunkOverlap","CharacterTextSplitter","texts","splitText","length","obj","arg","where","statements","extractObjectsByKey","join","key","results","traverse","currentKey","hasOwnProperty","push","_printValues","_eliminate","regex","RegExp","RunnableParallel","mapQuery","mapDoc","reduceChain","mapQueryChain","assign","query","mapDocChain","documents","textChunks","Promise","all","map","chunk","document","parallelChain","sequence","stringify","facts","BaseLLM","LLM","fields","_fields$apiKey","_fields$timeout","_fields$backend","_fields$temperature","_fields$topP","_fields$topK","_fields$nBatch","_fields$nThreads","_fields$nPredict","_fields$maxOutputToke","_fields$repeatLastN","_fields$repeatPenalty","baseUrl","model","apiKey","timeout","backend","temperature","topP","topK","nBatch","nThreads","nPredict","maxOutputTokens","repeatLastN","repeatPenalty","modelDefaultParameters","identifyingParams","modelParameters","_llmType","preparePayload","options","messages","role","_call","_options","_runManager","payload","headers","controller","AbortController","timeoutId","setTimeout","abort","fetch","method","body","signal","clearTimeout","ok","Error","status","json","choices","Array","isArray","choice","message","BaseEmbedding","Embeddings","embedDocuments","getEmbeddings","embedQuery","embeddings","respJson","Object","keys"],"mappings":";;;;;;;;;;;AAAA;;;;;;;;;;;;;;AAcG;AAEH,MAAMA,IAAI,GAAGA,CAACC,CAAM,EAAEC,CAAS,EAAEC,CAAS,KAAI;EAC5C,IAAI;IACF,OAAOF,CAAC,CAACG,OAAO,CAACF,CAAC,GAAG,GAAG,GAAGC,CAAC,CAAC,CAAA;AAC/B,GAAC,CAAC,OAAOE,CAAC,EAAE,EAAE;EACd,IAAI;IACF,OAAOJ,CAAC,CAACG,OAAO,CAACF,CAAC,GAAG,GAAG,GAAGC,CAAC,CAAC,CAAA;AAC/B,GAAC,CAAC,OAAOE,CAAC,EAAE,EAAC;EACb,IAAI;AACF,IAAA,OAAOJ,CAAC,CAACG,OAAO,CAACD,CAAC,CAAC,CAAA;AACrB,GAAC,CAAC,OAAOE,CAAC,EAAE,EAAC;AACb,EAAA,OAAO,IAAI,CAAA;AACb,CAAC;;A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OAAO,GAAG;MACdxB,KAAK,EAAE,IAAI,CAACA,KAAK;AACjB3I,MAAAA,KAAK,EAAEqF,KAAAA;KACR,CAAA;IAED,MAAM/E,QAAQ,GAAG,MAAMoK,KAAK,CAAC,IAAI,CAAChC,OAAO,EAAE;AACzCiC,MAAAA,MAAM,EAAE,MAAM;MACdP,OAAO;AACPQ,MAAAA,IAAI,EAAElI,IAAI,CAAC+E,SAAS,CAAC0C,OAAO,CAAA;AAC7B,KAAA,CAAC,CAAA;AAEF,IAAA,IAAI,CAAC7J,QAAQ,CAACyK,EAAE,EAAE;AAChB,MAAA,MAAMH,IAAI,GAAG,MAAMtK,QAAQ,CAACuD,IAAI,EAAE,CAAA;MAClC,MAAM,IAAImH,KAAK,CACb,CAA8B1K,2BAAAA,EAAAA,QAAQ,CAAC2K,MAAM,CAAA,OAAA,EAAUL,IAAI,CAAA,CAAE,CAC9D,CAAA;AACH,KAAA;AAEA,IAAA,MAAMkB,QAAQ,GAAG,MAAMxL,QAAQ,CAAC4K,IAAI,EAAE,CAAA;AAEtC,IAAA,IAAI,EAAE,YAAY,IAAIY,QAAQ,CAAC,EAAE;AAC/B,MAAA,MAAM,IAAId,KAAK,CACb,CAAyDe,sDAAAA,EAAAA,MAAM,CAACC,IAAI,CAClEF,QAAQ,CACT,CAACjG,IAAI,CAAC,IAAI,CAAC,EAAE,CACf,CAAA;AACH,KAAA;IAEA,OAAOiG,QAAQ,CAACD,UAAwB,CAAA;AAC1C,GAAA;AACD;;;;"}
|
|
1
|
+
{"version":3,"file":"medpromptjs.esm.js","sources":["../src/mydi.ts","../src/chain.ts","../src/agent.ts","../src/tool.ts","../src/llm_loop.ts","../src/llm.ts","../src/embedding.ts"],"sourcesContent":["/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst mydi = (c: any, m: string, b: string) => {\n try {\n return c.resolve(m + '_' + b);\n } catch (e) { }\n try {\n return c.resolve(m + '-' + b);\n } catch (e) {}\n try {\n return c.resolve(b);\n } catch (e) {}\n return null;\n};\n\nexport default mydi;\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PromptTemplate, ChatPromptTemplate } from '@langchain/core/prompts';\nimport { LLM } from '@langchain/core/language_models/llms';\nimport mydi from './mydi';\nimport {\n RunnablePassthrough,\n RunnableSequence,\n} from '@langchain/core/runnables';\nimport { AIMessage } from '@langchain/core/messages';\nimport { StringOutputParser } from '@langchain/core/output_parsers';\nimport { FakeListChatModel } from '@langchain/core/utils/testing';\n\nexport class BaseChain {\n container: any;\n private _name: string = '';\n private _description: string = '';\n private _template: string = '';\n prompt: any;\n llm: LLM;\n chat_model: boolean;\n runnable: any;\n fakeLLM: FakeListChatModel = new FakeListChatModel({\n responses: [\n 'Hello, this is a fake response (There is no real LLM available)!',\n 'bootstrap main-llm with a real LLM instance',\n 'This is another fake response (There is no real LLM available)!',\n ],\n });\n\n constructor(container: any) {\n this.container = container;\n this._name = this.camelize(this.constructor.name);\n this._description = this.snake_case(this.constructor.name);\n this.llm = this.resolve('llm', this.fakeLLM);\n this._template = this.resolve('template', '{input}');\n this.chat_model = this.resolve('chat-model', false);\n this.initializePrompt();\n }\n\n initializePrompt() {\n if (this.chat_model) {\n this.prompt = ChatPromptTemplate.fromTemplate(this._template);\n } else {\n this.prompt = PromptTemplate.fromTemplate(this._template);\n }\n }\n // Getters and setters\n get name(): string {\n return this._name;\n }\n set name(value: string) {\n this._name = value === '' ? this.camelize(this.constructor.name) : value;\n }\n\n get description(): string {\n return this._description;\n }\n set description(value: string) {\n this._description =\n value === '' ? this.snake_case(this.constructor.name) : value;\n }\n\n get template(): string {\n return this._template;\n }\n set template(value: string) {\n this._template = value;\n this.initializePrompt();\n }\n\n resolve(name: string, defaultValue: any = null): any {\n return (\n mydi(this.container, this.camelize(this.constructor.name), name) ||\n defaultValue\n );\n }\n\n camelize(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n }\n\n snake_case(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();\n })\n .replace(/\\s+/g, '');\n }\n\n // https://js.langchain.com/v0.1/docs/expression_language/how_to/routing/\n //! Override this method\n async chain(input: any) {\n const outputParser = new StringOutputParser();\n this.runnable = RunnableSequence.from([\n {\n input: new RunnablePassthrough(),\n // context: async () => loadContextFromStore(),\n },\n this.prompt,\n this.llm,\n outputParser,\n ]);\n if (this.chat_model) {\n const response: string = await this.runnable.invoke(input);\n const aiMessage = new AIMessage(response);\n return aiMessage.content;\n }\n return await this.runnable.invoke(input);\n }\n\n async invoke(input: any) {\n return this.chain(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BaseChain } from './chain';\nimport type { ToolInterface } from '@langchain/core/tools';\nimport { createStructuredChatAgent, AgentExecutor } from 'langchain/agents';\n\nexport class BaseAgent extends BaseChain {\n private _tools: ToolInterface[] = [];\n\n\n get tools(): ToolInterface[] {\n return this._tools;\n }\n set tools(value: ToolInterface[]) {\n this._tools = value;\n }\n\n /**\n * Run the agent using the provided input.\n * This uses createStructuredChatAgent and AgentExecutor from langchain/agents.\n */\n async run(input: any) {\n const agent = await createStructuredChatAgent({\n llm: this.llm,\n tools: this._tools,\n prompt: this.prompt,\n });\n const agentExecutor = new AgentExecutor({\n agent: agent,\n tools: this.tools,\n // verbose: true,\n handleParsingErrors:\n 'Please try again, paying close attention to the final answer',\n });\n return await agentExecutor.invoke(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DynamicStructuredTool } from 'langchain/tools';\nimport mydi from './mydi';\n\nexport class BaseTool extends DynamicStructuredTool {\n /** @hidden */\n container: any;\n name: string;\n description: string;\n schema: any;\n constructor(\n container: any,\n name: string,\n description: string,\n schema: any,\n func: any = null\n ) {\n super({\n name: name,\n description: description,\n schema: schema,\n func: func,\n });\n this.container = container;\n this.name = name === '' ? this.camelize(this.constructor.name) : name;\n this.description =\n description === '' ? this.snake_case(this.constructor.name) : description;\n this.schema = schema;\n }\n\n func = async (args: any) => {\n return 'override this';\n };\n\n resolve(name: string) {\n return mydi(this.container, this.name, name);\n }\n\n camelize(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : word.toUpperCase();\n })\n .replace(/\\s+/g, '');\n }\n\n snake_case(str: string) {\n return str\n .replace(/(?:^\\w|[A-Z]|\\b\\w)/g, function (word, index) {\n return index === 0 ? word.toLowerCase() : '_' + word.toLowerCase();\n })\n .replace(/\\s+/g, '');\n }\n\n /**\n * @param input - The input to process in batch.\n * @param config - The configuration for the batch.\n * @returns A promise resolving to an array of results.\n */\n async _batchWithConfig(input: any, config: any): Promise<any[]> {\n // Call the parent implementation or provide your own\n return super._batchWithConfig(input, config);\n }\n}\n","import { BaseChain } from './chain';\nimport { CharacterTextSplitter } from '@langchain/textsplitters';\nimport { Logger, ILogObj } from 'tslog';\n\nconst log: Logger<ILogObj> = new Logger();\nexport class LLMLoop extends BaseChain {\n // Implement the LLM loop logic here\n stringExpression: string = '';\n _mapQueryTemplate: string = `\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: `;\n\n _mapDocTemplate: string = `\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: `;\n\n _reduceChainTemplate: string = `\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: `;\n\n // Add getters and setters for the templates if needed\n get mapQueryTemplate(): string {\n return this._mapQueryTemplate;\n }\n set mapQueryTemplate(template: string) {\n this._mapQueryTemplate = template;\n }\n get mapDocTemplate(): string {\n return this._mapDocTemplate;\n }\n set mapDocTemplate(template: string) {\n this._mapDocTemplate = template;\n }\n get reduceChainTemplate(): string {\n return this._reduceChainTemplate;\n }\n set reduceChainTemplate(template: string) {\n this._reduceChainTemplate = template;\n }\n\n async checkAssertion(expression: string, context: any): Promise<boolean> {\n let _expression: string = '';\n try {\n // Check if expression is a valid JSON string\n _expression = this.printValues(JSON.parse(expression));\n } catch (error) {\n _expression = expression; // If not, use the expression as is\n }\n\n log.info(`Checking assertion with expression: ${_expression}`);\n // Initialize context and content\n let _context: any = undefined;\n let _content: string = '';\n try {\n _context = JSON.parse(context);\n } catch (error) {\n _context = context; // If not, use the context as is\n log.warn(`Context is not a valid JSON string: ${context}`);\n log.warn(`Using context as a string: ${_context}`);\n }\n try {\n // Check if context is a valid JSON string\n _context = JSON.parse(context);\n _context.forEach((element: any) => {\n element.content.forEach((contentItem: any) => {\n _content += atob(contentItem.attachment.data.value);\n });\n });\n } catch (error) {\n _content = context; // If not, use the context as is\n log.warn(`Context is not a valid JSON : ${context}`);\n log.warn(`Using context as a string: ${_content}`);\n }\n _content = this.findDatesAndConvertToTimeElapsed(\n _content.replace(/(\\r\\n|\\n|\\r)/gm, ' ')\n );\n log.info(`Checking assertion with context: ${_content}`);\n const _input = {\n input: {\n expression: _expression,\n context: _content,\n },\n };\n const result = await this.chain(_input);\n log.info(`Assertion check result: ${result}`);\n return result;\n }\n\n async checkMention(expression: string, context: any): Promise<boolean> {\n if (expression && context) return true; // Placeholder for assertion check logic\n return false;\n }\n\n async checkNegation(expression: string, context: any): Promise<boolean> {\n if (expression && context) return true; // Placeholder for assertion check logic\n return false;\n }\n\n findDatesAndConvertToTimeElapsed(text: string): string {\n // Regular expression to match dates in format of 'mm/dd/yyyy' or 'mm-dd-yyyy'\n const dateRegex = /(\\d{1,2}[-/]\\d{1,2}[-/]\\d{4})/g;\n let matches;\n let currentDate = new Date();\n\n while ((matches = dateRegex.exec(text)) !== null) {\n let date = new Date(matches[0]);\n let timeElapsed =\n (currentDate.getTime() - date.getTime()) / (1000 * 60 * 60 * 24);\n text = text.replace(\n matches[0],\n Math.floor(timeElapsed).toString() + ' days ago.'\n );\n }\n return text;\n }\n\n camelToString(camelCase: string): string {\n return camelCase.replace(/([A-Z])/g, ' $1').replace(/^./, function (str) {\n return str.toUpperCase();\n });\n }\n\n stringToBoolean(str: string): boolean {\n log.info(`Converting string to boolean: ${str}`);\n const positiveKeywords = [\n 'true',\n 'contains',\n 'confirms',\n 'yes',\n 'affirmative',\n 'matches',\n 'exists',\n 'present',\n 'absolutely',\n 'certainly',\n 'definitely',\n 'indeed',\n 'did have',\n 'showed',\n 'revealed',\n ];\n const lowerStr = str.toLowerCase();\n return positiveKeywords.some((keyword) => lowerStr.includes(keyword));\n }\n\n async textSplitter(\n text: string,\n chunkSize: number = 3900,\n chunkOverlap: number = 0\n ): Promise<string[]> {\n const textSplitter = new CharacterTextSplitter({\n chunkSize: chunkSize,\n chunkOverlap: chunkOverlap,\n });\n const texts = await textSplitter.splitText(text);\n // Log the number of chunks created\n if (texts.length === 0) {\n log.warn('No text chunks created. Please check the input text.');\n return [];\n }\n if (texts.length > 100) {\n log.warn(\n `Warning: More than 100 text chunks created (${texts.length}). This may affect performance.`\n );\n }\n if (chunkSize < 1000) {\n log.warn(\n `Warning: Chunk size is less than 1000 characters (${chunkSize}). This may lead to very small chunks.`\n );\n }\n log.info(\n `Text split into ${texts.length} chunks with size ${chunkSize} and overlap ${chunkOverlap}`\n );\n return texts;\n }\n\n printValues(obj: any) {\n log.info(`Processing Rule: ${obj.name} for ${obj.context}`);\n // For each obj.expression:arg:where\n if (obj.expression && obj.expression.arg && obj.expression.arg.where) {\n // for each args in obj.expression.arg.where, extract the nested key called \"value\"\n const statements = this.extractObjectsByKey(\n obj.expression.arg.where,\n 'value'\n );\n return statements.join(' ').replace(/,/g, ' ');\n }\n // return statements array as a string seperated by space\n return '';\n }\n\n extractObjectsByKey(obj: any, key: string): any[] {\n const results: any[] = [];\n\n function traverse(obj: any) {\n for (const currentKey in obj) {\n if (obj.hasOwnProperty(currentKey)) {\n if (currentKey === key) {\n results.push(obj[currentKey]);\n }\n if (typeof obj[currentKey] === 'object' && obj[currentKey] !== null) {\n traverse(obj[currentKey]);\n }\n }\n }\n }\n\n traverse(obj);\n return results;\n }\n\n _printValues(obj: any) {\n for (var key in obj) {\n if (typeof obj[key] === 'object') {\n this._printValues(obj[key]);\n } else {\n this.stringExpression += obj[key] + ' ';\n }\n }\n const _eliminate = [\n 'true',\n 'false',\n 'null',\n 'undefined',\n 'String',\n 'Number',\n 'Object',\n 'Array',\n 'Boolean',\n 'value',\n 'Type',\n 'Specifier',\n 'Named',\n ];\n _eliminate.forEach((element) => {\n const regex = new RegExp(element, 'g');\n this.stringExpression = this.stringExpression.replace(regex, '');\n });\n this.stringExpression = this.stringExpression.replace(\n /(?:https?|ftp):\\/\\/[\\n\\S]+/g,\n ''\n );\n return this.camelToString(this.stringExpression);\n }\n\n async chain(input: any) {\n // Create a chain using RunnableSequence, RunnablePassthrough and RunnableParallel\n // input has two properties: expression and context\n // expression goes through mapQuery and parallely\n // context goes through textSplitter and mapDoc\n // Finally reduceChain is called with the results of mapQuery and mapDoc\n // LCEL-based implementation using RunnableSequence, RunnableParallel, and RunnablePassthrough\n const { RunnableSequence, RunnableParallel, RunnablePassthrough } =\n await import('@langchain/core/runnables');\n\n const mapQuery: BaseChain = new BaseChain(this.container);\n const mapDoc: BaseChain = new BaseChain(this.container);\n const reduceChain: BaseChain = new BaseChain(this.container);\n mapQuery.name = 'MapQuery';\n mapQuery.description = 'Map the expression to a natural language query.';\n mapQuery.template = this.resolve('litl_mapquery_template', this._mapQueryTemplate);\n mapDoc.name = 'MapDoc';\n mapDoc.description = 'Map the document to a set of facts.';\n mapDoc.template = this.resolve('litl_mapdoc_template', this._mapDocTemplate);\n reduceChain.name = 'ReduceChain';\n reduceChain.description = 'Reduce a set of documents to binary answer.';\n reduceChain.template = this.resolve('litl_reduce_chain_template', this._reduceChainTemplate);\n const mapQueryChain = RunnablePassthrough.assign({\n query: async (input: any) =>\n mapQuery.chain({ expression: input.input.expression }),\n });\n\n const mapDocChain = RunnablePassthrough.assign({\n documents: async (input: any) => {\n const textChunks = await this.textSplitter(input.input.context);\n return Promise.all(\n textChunks.map((chunk) =>\n mapDoc.chain({\n document: chunk,\n statements: input.input.expression,\n })\n )\n );\n },\n });\n\n const parallelChain = RunnableParallel.from([mapQueryChain, mapDocChain]);\n\n const sequence = RunnableSequence.from([\n parallelChain,\n async (results: any) => {\n /* results is an array: [{ query: ... }, { documents: [...] }]\n{\n \"0\": {\n \"input\": {\n \"expression\": \"0 Visual foot exam showed active infection?\",\n \"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. \"\n },\n \"query\": \"The text indicates a question about whether a visual foot exam revealed an active infection.\\n\"\n },\n \"1\": {\n \"input\": {\n \"expression\": \"0 Visual foot exam showed active infection?\",\n \"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. \"\n },\n \"documents\": [\n \"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\"\n ]\n }\n}\n */\n log.info(`Results from parallel chain: ${JSON.stringify(results)}`);\n const expression = results[0].input.expression;\n const query = results[0].query;\n const documents = results[1].documents;\n return reduceChain.chain({\n facts: documents,\n query: query + ' ' + expression,\n });\n },\n (result: any) => this.stringToBoolean(result),\n ]);\n\n return sequence.invoke(input);\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LLM, type BaseLLMParams } from '@langchain/core/language_models/llms';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\n\n/**\n * Model parameters for BaseLLM\n */\nexport interface ModelParams {\n maxOutputTokens?: number;\n nPredict?: number;\n topK?: number;\n topP?: number;\n temperature?: number;\n nBatch?: number;\n repeatPenalty?: number;\n repeatLastN?: number;\n}\n\n/**\n * Parameters for configuring BaseLLM\n */\nexport interface BaseLLMInput extends BaseLLMParams {\n baseUrl: string;\n model: string;\n apiKey?: string;\n timeout?: number;\n backend?: string;\n temperature?: number;\n topP?: number;\n topK?: number;\n nBatch?: number;\n nThreads?: number;\n nPredict?: number;\n maxOutputTokens?: number;\n repeatLastN?: number;\n repeatPenalty?: number;\n}\n\n/**\n * BaseLLM is a base class for LLMs that communicate with a remote API.\n * It extends the LangChain LLM class and provides configurable parameters\n * for model inference.\n */\nexport class BaseLLM extends LLM {\n baseUrl: string;\n model: string;\n apiKey: string;\n timeout: number;\n backend: string;\n temperature: number;\n topP: number;\n topK: number;\n nBatch: number;\n nThreads: number;\n nPredict: number;\n maxOutputTokens: number;\n repeatLastN: number;\n repeatPenalty: number;\n\n constructor(fields: BaseLLMInput) {\n super(fields);\n this.baseUrl = fields.baseUrl;\n this.model = fields.model;\n this.apiKey = fields.apiKey ?? '';\n this.timeout = fields.timeout ?? 60000;\n this.backend = fields.backend ?? 'dhti';\n this.temperature = fields.temperature ?? 0.1;\n this.topP = fields.topP ?? 0.8;\n this.topK = fields.topK ?? 40;\n this.nBatch = fields.nBatch ?? 8;\n this.nThreads = fields.nThreads ?? 4;\n this.nPredict = fields.nPredict ?? 256;\n this.maxOutputTokens = fields.maxOutputTokens ?? 512;\n this.repeatLastN = fields.repeatLastN ?? 64;\n this.repeatPenalty = fields.repeatPenalty ?? 1.18;\n }\n\n /**\n * Get the model default parameters\n */\n get modelDefaultParameters(): ModelParams {\n return {\n maxOutputTokens: this.maxOutputTokens,\n nPredict: this.nPredict,\n topK: this.topK,\n topP: this.topP,\n temperature: this.temperature,\n nBatch: this.nBatch,\n repeatPenalty: this.repeatPenalty,\n repeatLastN: this.repeatLastN,\n };\n }\n\n /**\n * Get the identifying parameters\n */\n get identifyingParams(): Record<string, unknown> {\n return {\n model: this.model,\n baseUrl: this.baseUrl,\n modelParameters: this.modelDefaultParameters,\n };\n }\n\n /**\n * Get the LLM type identifier\n */\n _llmType(): string {\n return 'dhti';\n }\n\n /**\n * Prepare the request payload for the API\n */\n protected preparePayload(prompt: string): Record<string, unknown> {\n return {\n model: this.model,\n options: this.modelDefaultParameters,\n messages: [{ role: 'user', content: prompt }],\n };\n }\n\n /**\n * Make the API call to generate text\n */\n async _call(\n prompt: string,\n _options: this['ParsedCallOptions'],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<string> {\n const payload = this.preparePayload(prompt);\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(this.baseUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(\n `API request failed: status=${response.status}; body=${body}`\n );\n }\n\n const data = await response.json();\n\n // Expecting structure like: { \"choices\": [ { \"message\": { \"role\":\"assistant\",\"content\":\"...\" } } ] }\n // Adapt this path if the API differs\n if (\n data.choices &&\n Array.isArray(data.choices) &&\n data.choices.length > 0\n ) {\n const choice = data.choices[0];\n // support both \"message\" and direct \"text\"\n if (\n typeof choice === 'object' &&\n choice !== null &&\n 'message' in choice &&\n typeof choice.message === 'object' &&\n choice.message !== null\n ) {\n const content = (choice.message as Record<string, unknown>).content;\n if (typeof content === 'string') {\n return content;\n }\n } else if ('text' in choice) {\n const text = choice.text;\n if (typeof text === 'string') {\n return text;\n }\n }\n }\n\n // Fallback: return raw JSON string for debugging\n return JSON.stringify(data);\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === 'AbortError') {\n throw new Error(`API request timed out after ${this.timeout}ms`);\n }\n throw error;\n }\n }\n}\n","/**\n * Copyright 2024 Bell Eapen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Embeddings, type EmbeddingsParams } from '@langchain/core/embeddings';\n\n/**\n * Parameters for configuring BaseEmbedding\n */\nexport interface BaseEmbeddingInput extends EmbeddingsParams {\n baseUrl: string;\n model: string;\n apiKey?: string;\n}\n\n/**\n * BaseEmbedding is a base class for embeddings that communicate with a remote API.\n * It extends the LangChain Embeddings class and provides methods for embedding\n * documents and queries.\n */\nexport class BaseEmbedding extends Embeddings {\n baseUrl: string;\n model: string;\n apiKey: string;\n\n constructor(fields: BaseEmbeddingInput) {\n super(fields);\n this.baseUrl = fields.baseUrl;\n this.model = fields.model;\n this.apiKey = fields.apiKey ?? '';\n }\n\n /**\n * Embed a list of documents\n * @param texts - Array of strings to embed\n * @returns Promise of array of embedding vectors\n */\n async embedDocuments(texts: string[]): Promise<number[][]> {\n return this.getEmbeddings(texts);\n }\n\n /**\n * Embed a single query\n * @param text - String to embed\n * @returns Promise of embedding vector\n */\n async embedQuery(text: string): Promise<number[]> {\n const embeddings = await this.getEmbeddings([text]);\n return embeddings[0];\n }\n\n /**\n * Helper method to get embeddings for a list of texts\n * @param texts - Array of strings to embed\n * @returns Promise of array of embedding vectors\n */\n protected async getEmbeddings(texts: string[]): Promise<number[][]> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n\n const payload = {\n model: this.model,\n input: texts,\n };\n\n const response = await fetch(this.baseUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new Error(\n `API request failed: status=${response.status}; body=${body}`\n );\n }\n\n const respJson = await response.json();\n\n if (!('embeddings' in respJson)) {\n throw new Error(\n `API response missing 'embeddings' key. Received keys: ${Object.keys(\n respJson\n ).join(', ')}`\n );\n }\n\n return respJson.embeddings as number[][];\n }\n}\n"],"names":["mydi","c","m","b","resolve","e","BaseChain","constructor","container","_name","_description","_template","prompt","llm","chat_model","runnable","fakeLLM","FakeListChatModel","responses","camelize","name","snake_case","initializePrompt","ChatPromptTemplate","fromTemplate","PromptTemplate","value","description","template","defaultValue","str","replace","word","index","toLowerCase","toUpperCase","chain","input","outputParser","StringOutputParser","RunnableSequence","from","RunnablePassthrough","response","invoke","aiMessage","AIMessage","content","BaseAgent","args","_tools","tools","run","agent","createStructuredChatAgent","agentExecutor","AgentExecutor","handleParsingErrors","BaseTool","DynamicStructuredTool","schema","func","_batchWithConfig","config","log","Logger","LLMLoop","stringExpression","_mapQueryTemplate","_mapDocTemplate","_reduceChainTemplate","mapQueryTemplate","mapDocTemplate","reduceChainTemplate","checkAssertion","expression","context","_expression","printValues","JSON","parse","error","info","_context","undefined","_content","warn","forEach","element","contentItem","atob","attachment","data","findDatesAndConvertToTimeElapsed","_input","result","checkMention","checkNegation","text","dateRegex","matches","currentDate","Date","exec","date","timeElapsed","getTime","Math","floor","toString","camelToString","camelCase","stringToBoolean","positiveKeywords","lowerStr","some","keyword","includes","textSplitter","chunkSize","chunkOverlap","CharacterTextSplitter","texts","splitText","length","obj","arg","where","statements","extractObjectsByKey","join","key","results","traverse","currentKey","hasOwnProperty","push","_printValues","_eliminate","regex","RegExp","RunnableParallel","mapQuery","mapDoc","reduceChain","mapQueryChain","assign","query","mapDocChain","documents","textChunks","Promise","all","map","chunk","document","parallelChain","sequence","stringify","facts","BaseLLM","LLM","fields","_fields$apiKey","_fields$timeout","_fields$backend","_fields$temperature","_fields$topP","_fields$topK","_fields$nBatch","_fields$nThreads","_fields$nPredict","_fields$maxOutputToke","_fields$repeatLastN","_fields$repeatPenalty","baseUrl","model","apiKey","timeout","backend","temperature","topP","topK","nBatch","nThreads","nPredict","maxOutputTokens","repeatLastN","repeatPenalty","modelDefaultParameters","identifyingParams","modelParameters","_llmType","preparePayload","options","messages","role","_call","_options","_runManager","payload","headers","controller","AbortController","timeoutId","setTimeout","abort","fetch","method","body","signal","clearTimeout","ok","Error","status","json","choices","Array","isArray","choice","message","BaseEmbedding","Embeddings","embedDocuments","getEmbeddings","embedQuery","embeddings","respJson","Object","keys"],"mappings":";;;;;;;;;;;;AAAA;;;;;;;;;;;;;;AAcG;AAEH,MAAMA,IAAI,GAAGA,CAACC,CAAM,EAAEC,CAAS,EAAEC,CAAS,KAAI;EAC5C,IAAI;IACF,OAAOF,CAAC,CAACG,OAAO,CAACF,CAAC,GAAG,GAAG,GAAGC,CAAC,CAAC,CAAA;AAC/B,GAAC,CAAC,OAAOE,CAAC,EAAE,EAAE;EACd,IAAI;IACF,OAAOJ,CAAC,CAACG,OAAO,CAACF,CAAC,GAAG,GAAG,GAAGC,CAAC,CAAC,CAAA;AAC/B,GAAC,CAAC,OAAOE,CAAC,EAAE,EAAC;EACb,IAAI;AACF,IAAA,OAAOJ,CAAC,CAACG,OAAO,CAACD,CAAC,CAAC,CAAA;AACrB,GAAC,CAAC,OAAOE,CAAC,EAAE,EAAC;AACb,EAAA,OAAO,IAAI,CAAA;AACb,CAAC;;AC3BD;;;;;;;;;;;;;;AAcG;MAaUC,SAAS,CAAA;EAiBpBC,WAAAA,CAAYC,SAAc,EAAA;AAAA,IAAA,IAAA,CAhB1BA,SAAS,GAAA,KAAA,CAAA,CAAA;IAAA,IACDC,CAAAA,KAAK,GAAW,EAAE,CAAA;IAAA,I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AM/E,QAAQ,GAAG,MAAMoK,KAAK,CAAC,IAAI,CAAChC,OAAO,EAAE;AACzCiC,MAAAA,MAAM,EAAE,MAAM;MACdP,OAAO;AACPQ,MAAAA,IAAI,EAAElI,IAAI,CAAC+E,SAAS,CAAC0C,OAAO,CAAA;AAC7B,KAAA,CAAC,CAAA;AAEF,IAAA,IAAI,CAAC7J,QAAQ,CAACyK,EAAE,EAAE;AAChB,MAAA,MAAMH,IAAI,GAAG,MAAMtK,QAAQ,CAACuD,IAAI,EAAE,CAAA;MAClC,MAAM,IAAImH,KAAK,CACb,CAA8B1K,2BAAAA,EAAAA,QAAQ,CAAC2K,MAAM,CAAA,OAAA,EAAUL,IAAI,CAAA,CAAE,CAC9D,CAAA;AACH,KAAA;AAEA,IAAA,MAAMkB,QAAQ,GAAG,MAAMxL,QAAQ,CAAC4K,IAAI,EAAE,CAAA;AAEtC,IAAA,IAAI,EAAE,YAAY,IAAIY,QAAQ,CAAC,EAAE;AAC/B,MAAA,MAAM,IAAId,KAAK,CACb,CAAyDe,sDAAAA,EAAAA,MAAM,CAACC,IAAI,CAClEF,QAAQ,CACT,CAACjG,IAAI,CAAC,IAAI,CAAC,EAAE,CACf,CAAA;AACH,KAAA;IAEA,OAAOiG,QAAQ,CAACD,UAAwB,CAAA;AAC1C,GAAA;AACD;;;;"}
|
package/package.json
CHANGED
|
@@ -1,22 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "medpromptjs",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.2",
|
|
4
4
|
"description": "A library of langchain base classes for building medical applications.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Bell Eapen",
|
|
7
7
|
"main": "dist/index.js",
|
|
8
|
-
"module": "dist/medpromptjs.
|
|
8
|
+
"module": "dist/medpromptjs.mjs",
|
|
9
9
|
"typings": "dist/index.d.ts",
|
|
10
10
|
"exports": {
|
|
11
11
|
".": {
|
|
12
|
-
"
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/medpromptjs.mjs",
|
|
13
14
|
"require": "./dist/index.js",
|
|
14
|
-
"
|
|
15
|
-
},
|
|
16
|
-
"./dist/medpromptjs.esm.js": {
|
|
17
|
-
"import": "./dist/medpromptjs.esm.js",
|
|
18
|
-
"require": "./dist/index.js",
|
|
19
|
-
"types": "./dist/index.d.ts"
|
|
15
|
+
"default": "./dist/index.js"
|
|
20
16
|
}
|
|
21
17
|
},
|
|
22
18
|
"files": [
|
|
@@ -25,6 +21,7 @@
|
|
|
25
21
|
"scripts": {
|
|
26
22
|
"analyze": "size-limit --why",
|
|
27
23
|
"build": "dts build --target node",
|
|
24
|
+
"postbuild": "mv dist/medpromptjs.esm.js dist/medpromptjs.mjs && mv dist/medpromptjs.esm.js.map dist/medpromptjs.mjs.map && sed -i 's/medpromptjs.esm.js.map/medpromptjs.mjs.map/g' dist/medpromptjs.mjs",
|
|
28
25
|
"lint": "dts lint --fix",
|
|
29
26
|
"prepare": "dts build --target node",
|
|
30
27
|
"size": "size-limit",
|
|
@@ -69,7 +66,7 @@
|
|
|
69
66
|
"dts-cli": "^2.0.5",
|
|
70
67
|
"google-auth-library": "^10.1.0",
|
|
71
68
|
"husky": "^9.1.7",
|
|
72
|
-
"size-limit": "^
|
|
69
|
+
"size-limit": "^12.0.0",
|
|
73
70
|
"supertest": "^7.1.1",
|
|
74
71
|
"ts-mockito": "^2.6.1",
|
|
75
72
|
"tslib": "^2.6.2",
|