medpromptjs 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +55 -0
  3. package/dist/agents/explain_agent.d.ts +6 -0
  4. package/dist/agents/index.d.ts +2 -0
  5. package/dist/bootstrap.d.ts +1 -0
  6. package/dist/chains/index.d.ts +2 -0
  7. package/dist/chains/self_gen_cot_chain.d.ts +26 -0
  8. package/dist/index.d.ts +3 -0
  9. package/dist/index.js +8 -0
  10. package/dist/medpromptjs.cjs.development.js +576 -0
  11. package/dist/medpromptjs.cjs.development.js.map +1 -0
  12. package/dist/medpromptjs.cjs.production.min.js +2 -0
  13. package/dist/medpromptjs.cjs.production.min.js.map +1 -0
  14. package/dist/medpromptjs.esm.js +571 -0
  15. package/dist/medpromptjs.esm.js.map +1 -0
  16. package/dist/server/index.d.ts +3 -0
  17. package/dist/server/sample_app.d.ts +3 -0
  18. package/dist/tools/find_patient.d.ts +19 -0
  19. package/dist/tools/index.d.ts +2 -0
  20. package/dist/utils/fhir_server.d.ts +4 -0
  21. package/dist/utils/get_medical_record.d.ts +8 -0
  22. package/dist/utils/hapi_server.d.ts +5 -0
  23. package/dist/utils/index.d.ts +4 -0
  24. package/package.json +76 -0
  25. package/src/agents/explain_agent.ts +37 -0
  26. package/src/agents/index.ts +4 -0
  27. package/src/bootstrap.ts +17 -0
  28. package/src/chains/index.ts +2 -0
  29. package/src/chains/self_gen_cot_chain.ts +82 -0
  30. package/src/index.ts +5 -0
  31. package/src/server/index.ts +5 -0
  32. package/src/server/sample_app.js +47 -0
  33. package/src/server/sample_app.ts +51 -0
  34. package/src/tools/find_patient.ts +51 -0
  35. package/src/tools/index.ts +4 -0
  36. package/src/utils/fhir_server.ts +11 -0
  37. package/src/utils/get_medical_record.ts +44 -0
  38. package/src/utils/hapi_server.ts +19 -0
  39. package/src/utils/index.ts +6 -0
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "medpromptjs",
3
+ "version": "0.1.1",
4
+ "license": "Apache-2.0",
5
+ "author": "Bell Eapen",
6
+ "main": "dist/index.js",
7
+ "module": "dist/medpromptjs.esm.js",
8
+ "typings": "dist/index.d.ts",
9
+ "type": "module",
10
+ "files": [
11
+ "dist",
12
+ "src"
13
+ ],
14
+ "scripts": {
15
+ "analyze": "size-limit --why",
16
+ "build": "dts build",
17
+ "lint": "dts lint",
18
+ "prepare": "dts build",
19
+ "size": "size-limit",
20
+ "start": "dts watch",
21
+ "test": "dts test",
22
+ "docs": "typedoc --out docs src"
23
+ },
24
+ "husky": {
25
+ "hooks": {
26
+ "pre-commit": "dts lint"
27
+ }
28
+ },
29
+ "prettier": {
30
+ "printWidth": 80,
31
+ "semi": true,
32
+ "singleQuote": true,
33
+ "trailingComma": "es5"
34
+ },
35
+ "jest": {
36
+ "testEnvironment": "node"
37
+ },
38
+ "engines": {
39
+ "node": ">=12"
40
+ },
41
+ "size-limit": [
42
+ {
43
+ "path": "dist/medpromptjs.cjs.production.min.js",
44
+ "limit": "10 KB"
45
+ },
46
+ {
47
+ "path": "dist/medpromptjs.esm.js",
48
+ "limit": "10 KB"
49
+ }
50
+ ],
51
+ "devDependencies": {
52
+ "@size-limit/preset-small-lib": "^11.0.1",
53
+ "@tsconfig/recommended": "^1.0.3",
54
+ "@types/cors": "^2.8.17",
55
+ "@types/express": "^4.17.21",
56
+ "@types/supertest": "^6.0.2",
57
+ "dts-cli": "^2.0.3",
58
+ "google-auth-library": "^8.9.0",
59
+ "husky": "^8.0.3",
60
+ "size-limit": "^11.0.1",
61
+ "supertest": "^6.3.3",
62
+ "ts-mockito": "^2.6.1",
63
+ "tslib": "^2.6.2",
64
+ "typedoc": "^0.25.4",
65
+ "typescript": "^5.3.3"
66
+ },
67
+ "dependencies": {
68
+ "cors": "^2.8.5",
69
+ "dotenv": "^16.3.1",
70
+ "express": "^4.18.2",
71
+ "langchain": "^0.0.213",
72
+ "reflect-metadata": "^0.2.1",
73
+ "tslog": "^4.9.2",
74
+ "tsyringe": "^4.8.0"
75
+ }
76
+ }
@@ -0,0 +1,37 @@
1
+ import "../bootstrap";
2
+ import { SelfGenCotChain } from "../chains/self_gen_cot_chain";
3
+ import { pull } from "langchain/hub";
4
+ import type { PromptTemplate } from "@langchain/core/prompts";
5
+ import { SequentialChain, LLMChain } from "langchain/chains";
6
+ import { container } from "tsyringe";
7
+ import { LLM } from "langchain/llms/base";
8
+ import { AgentExecutor, createReactAgent } from "langchain/agents";
9
+ import { Tool } from "langchain/tools";
10
+ import type { ToolInterface } from "@langchain/core/tools";
11
+
12
+ export class ExplainAgent {
13
+
14
+ tools: any[];
15
+
16
+ constructor(tools: any[] = [new SelfGenCotChain()]) {
17
+ this.tools = tools;
18
+ }
19
+
20
+
21
+ async run(input: any){
22
+ const promptWithChat = await pull<PromptTemplate>("hwchase17/react-chat");
23
+ const llm: LLM = container.resolve("main-llm");
24
+ const tools: ToolInterface[] = this.tools;
25
+ const agentWithChat = await createReactAgent({
26
+ llm,
27
+ tools,
28
+ prompt: promptWithChat,
29
+ });
30
+ const agentExecutorWithChat = new AgentExecutor({
31
+ agent: agentWithChat,
32
+ tools,
33
+ });
34
+ const result2 = await agentExecutorWithChat.invoke(input);
35
+ return result2;
36
+ }
37
+ }
@@ -0,0 +1,4 @@
1
+ import "./bootstrap";
2
+
3
+ export { ExplainAgent } from "./explain_agent";
4
+
@@ -0,0 +1,17 @@
1
+ import "reflect-metadata";
2
+ import { HapiFhirServer } from "./utils/hapi_server";
3
+ import { container } from "tsyringe";
4
+ import { GoogleVertexAI } from "langchain/llms/googlevertexai";
5
+
6
+ const google_vertex_ai = new GoogleVertexAI({
7
+ model: "text-bison",
8
+ temperature: 0.2,
9
+ });
10
+
11
+ container.register("main-llm", {
12
+ useValue: google_vertex_ai,
13
+ });
14
+
15
+ container.register("FhirServer", {
16
+ useClass: HapiFhirServer,
17
+ });
@@ -0,0 +1,2 @@
1
+ import "./bootstrap";
2
+ export { SelfGenCotChain } from "./self_gen_cot_chain";
@@ -0,0 +1,82 @@
1
+ import "../bootstrap";
2
+ import { SequentialChain, LLMChain, BaseChain } from "langchain/chains";
3
+ import { container } from "tsyringe";
4
+ import { PromptTemplate } from "langchain/prompts";
5
+ import { LLM } from "langchain/llms/base";
6
+ import { BaseCache, ChainValues } from "langchain/dist/schema";
7
+ import { CallbackManagerForChainRun } from "langchain/dist/callbacks";
8
+
9
+
10
+ export class SelfGenCotChain {
11
+
12
+ private llm: LLM = container.resolve("main-llm");
13
+ name: string = "self generated explanation";
14
+ description: string = "Generate a chain of thought explanation for the answer to a question.";
15
+ private template: string = `
16
+ ## Question: {question}
17
+ ## Answer: {answer}
18
+ Given the above question and answer, generate a chain of thought explanation for the answer.
19
+ First, start with the model generated chain of thought explanation.
20
+ End the chain of though explanation with:
21
+ Therefore, the answer is {answer}.
22
+ `;
23
+
24
+ constructor(
25
+ llm?: LLM,
26
+ name?: string,
27
+ template?: string,
28
+ description?: string,
29
+ ) {
30
+ if (llm)
31
+ this.llm = llm;
32
+ if (name)
33
+ this.name = name;
34
+ if (template)
35
+ this.template = template;
36
+ if (description)
37
+ this.description = description;
38
+ }
39
+
40
+ promptTemplate: PromptTemplate = new PromptTemplate({
41
+ template: this.template,
42
+ inputVariables: ["question", "answer"],
43
+ });
44
+
45
+ chain: LLMChain = new LLMChain({
46
+ llm: this.llm,
47
+ prompt: this.promptTemplate,
48
+ outputKey: "explanation",
49
+ });
50
+
51
+ async call(args: { question: string, answer: string }) {
52
+ const chainExecutionResult = await this.chain.call(args);
53
+ return chainExecutionResult;
54
+ }
55
+
56
+ _call(values: ChainValues, runManager?: CallbackManagerForChainRun | undefined): Promise<ChainValues> {
57
+ throw new Error("Method not implemented.");
58
+ }
59
+ _chainType(): string {
60
+ return "self_gen_cot_chain";
61
+ }
62
+ get inputKeys(): string[] {
63
+ return ["question", "answer"];
64
+ }
65
+ get outputKeys(): string[] {
66
+ return ["explanation"];
67
+ }
68
+
69
+ public getName() {
70
+ return this.name;
71
+ }
72
+
73
+ public getTemplate() {
74
+ return this.template;
75
+ }
76
+
77
+ public getDescription() {
78
+ return this.description;
79
+ }
80
+
81
+ }
82
+
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ import "./bootstrap";
2
+
3
+ export { SelfGenCotChain } from "./chains/self_gen_cot_chain";
4
+ export { ExplainAgent } from './agents/explain_agent';
5
+
@@ -0,0 +1,5 @@
1
+ import "./bootstrap";
2
+
3
+ import app from '../../src/server/sample_app';
4
+
5
+ export default app;
@@ -0,0 +1,47 @@
1
+ import { SelfGenCotChain, ExplainAgent } from "../../dist/medpromptjs.esm.js"
2
+ import dotenv from "dotenv";
3
+ import express from "express";
4
+ import cors from "cors";
5
+ dotenv.config();
6
+
7
+
8
+ const app = express();
9
+ app.use(cors({ origin: "*" }));
10
+
11
+
12
+ const chain = new SelfGenCotChain();
13
+ const agent = new ExplainAgent();
14
+
15
+ app.get("/explain", async (req, res) => {
16
+ const input = req.query.input;
17
+ const chat_history = req.query.chat_history;
18
+ const input2 = {
19
+ input: input,
20
+ chat_history: chat_history,
21
+ }
22
+ if (input && typeof input === "string" && chat_history && typeof chat_history === "string") {
23
+ const response = await agent.run(input2);
24
+ res.json(response);
25
+ } else {
26
+ res.json({ error: "No message provided" });
27
+ }
28
+ });
29
+
30
+ app.get("/chain", async (req, res) => {
31
+ const question = req.query.question;
32
+ const answer = req.query.answer;
33
+ const input = {
34
+ question: question,
35
+ answer: answer,
36
+ }
37
+ if (question && typeof question === "string" && answer && typeof answer === "string") {
38
+ const response = await chain.call(input);
39
+ res.json(response);
40
+ } else {
41
+ res.json({ error: "No message provided" });
42
+ }
43
+ });
44
+
45
+ app.listen(5000, () => {
46
+ console.log("Server running on http://localhost:5000");
47
+ });
@@ -0,0 +1,51 @@
1
+ import "../bootstrap";
2
+ import { SelfGenCotChain } from "../chains/self_gen_cot_chain";
3
+ import { ExplainAgent } from '../../src/agents/explain_agent';
4
+ import * as dotenv from "dotenv";
5
+ import express from "express";
6
+ import cors from "cors";
7
+ dotenv.config();
8
+
9
+ const app = express();
10
+ app.use(cors({ origin: "*" }));
11
+
12
+ const chain = new SelfGenCotChain();
13
+ const agent = new ExplainAgent();
14
+
15
+ app.get("/explain", async (req: any, res: any) => {
16
+ const input = req.query.input;
17
+ const chat_history = req.query.chat_history;
18
+ const input2 = {
19
+ input: input,
20
+ chat_history: chat_history,
21
+ }
22
+ if (input && typeof input === "string" && chat_history && typeof chat_history === "string") {
23
+ const response = await agent.run(input2);
24
+ res.json(response);
25
+ } else {
26
+ res.json({ error: "No message provided" });
27
+ }
28
+ });
29
+
30
+
31
+ app.get("/chain", async (req: any, res: any) => {
32
+ const question = req.query.question;
33
+ const answer = req.query.answer;
34
+ const input = {
35
+ question: question,
36
+ answer: answer,
37
+ }
38
+ if (question && typeof question === "string" && answer && typeof answer === "string") {
39
+ const response = await chain.call(input);
40
+ res.json(response);
41
+ } else {
42
+ res.json({ error: "No message provided" });
43
+ }
44
+ });
45
+
46
+
47
+ app.listen(5000, () => {
48
+ console.log("Server running on http://localhost:5000");
49
+ });
50
+
51
+ export default app;
@@ -0,0 +1,51 @@
1
+ import "../bootstrap";
2
+ import { DynamicTool, DynamicStructuredTool } from "langchain/tools";
3
+ import { z } from "zod";
4
+ import { GetMedicalRecord } from "../utils/get_medical_record";
5
+ import { container } from "tsyringe";
6
+ import { get } from "langchain/util/convex";
7
+ import { FhirServer } from "../utils/fhir_server";
8
+
9
+
10
+ export const FhirPatientSearchTool = new DynamicStructuredTool({
11
+ name: "patient search",
12
+ description: `
13
+ Searches FHIR server for a patient with available data.
14
+ given: Given name of the patient.
15
+ family: Family name of the patient.
16
+ birth_date: Date of birth of the patient.
17
+ patient_id: ID of the patient.
18
+ All parameters are optional.
19
+ Returns a list of all matching patient names if multiple patients are found.
20
+ If no patient is found, returns the string "No patient found".
21
+ If only one patient is found, returns the patient ID as a string.
22
+ `,
23
+ schema: z.object({
24
+ given: z.string(),
25
+ family: z.string(),
26
+ birth_date: z.string(),
27
+ patient_id: z.string(),
28
+ }),
29
+ func: async (args) => {
30
+ const fhir_server: FhirServer = container.resolve("FhirServer");
31
+ const { given, family, birth_date, patient_id } = args;
32
+ let query = "Patient?"
33
+ if (patient_id) {
34
+ query += `_id=${patient_id}`
35
+ }
36
+ if (given) {
37
+ query += `&given=${given}`
38
+ }
39
+ if (family) {
40
+ query += `&family=${family}`
41
+ }
42
+ if (birth_date) {
43
+ query += `&birthdate=${birth_date}`
44
+ }
45
+ const data = await fhir_server.call_fhir_server(
46
+ "",
47
+ query,
48
+ );
49
+ return data;
50
+ },
51
+ });
@@ -0,0 +1,4 @@
1
+ import "./bootstrap";
2
+
3
+ export { FhirPatientSearchTool } from "./find_patient";
4
+
@@ -0,0 +1,11 @@
1
+
2
+ export abstract class FhirServer {
3
+
4
+ baseUrl: string | undefined;
5
+
6
+ abstract call_fhir_server(
7
+ url: string,
8
+ params: string,
9
+ ): Promise<any>;
10
+ }
11
+
@@ -0,0 +1,44 @@
1
+ import "../bootstrap";
2
+ import { autoInjectable, inject, injectable } from "tsyringe";
3
+ import { FhirServer } from "./fhir_server";
4
+ import { Logger } from "tslog";
5
+
6
+ const logger = new Logger({ name: "MedpromptLogger" });
7
+
8
+ @autoInjectable()
9
+ export class GetMedicalRecord {
10
+
11
+ constructor(
12
+ @inject("FhirServer")
13
+ private fhir_server: FhirServer,
14
+ ) {}
15
+
16
+ async get(
17
+ patient_id: string,
18
+ ): Promise<any> {
19
+ const query = this.format_query(patient_id)
20
+ logger.info(`query: ${query}`)
21
+ logger.info(`fhir_server: ${this.fhir_server.baseUrl}`)
22
+ const response = await this.fhir_server.call_fhir_server(
23
+ "",
24
+ query,
25
+ );
26
+ if (response.total != 0) {
27
+ return response;
28
+ } else {
29
+ return "No data found";
30
+ }
31
+ }
32
+
33
+ format_query(patient_id: string): string {
34
+ let query = "Patient?"
35
+ if (patient_id) {
36
+ query += `_id=${patient_id}`
37
+ query += "&_revinclude=Observation:subject"
38
+ query += "&_revinclude=Condition:subject"
39
+ query += "&_revinclude=Procedure:subject"
40
+ query += "&_revinclude=MedicationRequest:subject"
41
+ }
42
+ return query
43
+ }
44
+ }
@@ -0,0 +1,19 @@
1
+ import { FhirServer } from "./fhir_server";
2
+ import { Logger } from "tslog";
3
+
4
+ const logger = new Logger({ name: "MedpromptLogger" });
5
+
6
+ export class HapiFhirServer extends FhirServer {
7
+
8
+ baseUrl: string = 'http://hapi.fhir.org/baseR4/';
9
+
10
+ async call_fhir_server(url: string, params: string) {
11
+ const _url_with_params = `${this.baseUrl}${url}${params}`
12
+ logger.info(`url_with_params: ${_url_with_params}`)
13
+ const response = await fetch(
14
+ _url_with_params,
15
+ );
16
+ const data = await response.json();
17
+ return data;
18
+ }
19
+ }
@@ -0,0 +1,6 @@
1
+
2
+ import "./bootstrap";
3
+ export { FhirServer } from "./fhir_server";
4
+ export { GetMedicalRecord } from "./get_medical_record";
5
+ export { HapiFhirServer } from "./hapi_server";
6
+