-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
455 lines (374 loc) · 14.1 KB
/
main.py
File metadata and controls
455 lines (374 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
import json
import os
import re
import numpy as np
import yaml
from dotenv import load_dotenv
from jsonschema import validate
from jsonschema.exceptions import SchemaError, ValidationError
from openai import OpenAI
from termcolor import colored
load_dotenv()
client = OpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
)
DEBUG = False
PATIENT = "patient_0"
def cosine_similarity(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
def get_embedding(text, model="text-embedding-ada-002"):
return client.embeddings.create(input=[text], model=model).data[0].embedding
def input_multi(msg: str):
print(msg, end="")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
return "\n".join(contents)
def pretty_print_conversation(messages):
role_to_color = {
"system": "red",
"user": "green",
"assistant": "blue",
"function": "magenta",
}
for message in messages:
try:
role = message["role"]
except:
role = message.role
if role == "system":
print(colored(f"system: {message['content']}\n", role_to_color[role]))
elif role == "user":
print(colored(f"user: {message['content']}\n", role_to_color[role]))
elif role == "assistant" and message.function_call:
print(colored(f"assistant: {message.function_call}\n", role_to_color[role]))
elif role == "assistant" and not message.function_call:
print(colored(f"assistant: {message.content}\n", role_to_color[role]))
elif role == "function":
print(
colored(
f"function ({message['name']}): {message['content']}\n",
role_to_color[role],
)
)
with open("data/system_prompt.md", "r") as file:
system_prompt = file.read()
with open("data/system_functions.json", "r") as file:
system_functions = json.load(file)
with open("data/care_pathways.yaml", "r") as file:
care_pathways = yaml.safe_load(file)
with open("data/med_models.json", "r") as file:
med_models = json.load(file)
with open("data/diagnostic_tests.json", "r") as file:
diagnostic_tests = json.load(file)
with open("data/clinics.json", "r") as file:
clinics = json.load(file)
with open(f"data/{PATIENT}/ehr.json", "r") as file:
ehr = json.load(file)
for i in range(len(med_models)):
if med_models[i].get("embedding") is None:
med_models[i]["embedding"] = get_embedding(
med_models[i]["name"] + "\n" + med_models[i]["description"]
)
for i in range(len(diagnostic_tests)):
if diagnostic_tests[i].get("embedding") is None:
diagnostic_tests[i]["embedding"] = get_embedding(
diagnostic_tests[i]["name"] + "\n" + diagnostic_tests[i]["description"]
)
for i in range(len(care_pathways)):
if care_pathways[i].get("embedding") is None:
care_pathways[i]["embedding"] = get_embedding(
care_pathways[i]["name"] + "\n" + care_pathways[i]["content"]
)
for i in range(len(ehr)):
if ehr[i].get("embedding") is None:
ehr[i]["embedding"] = get_embedding(ehr[i]["name"] + "\n" + ehr[i]["content"])
for i in range(len(clinics)):
if clinics[i].get("embedding") is None:
clinics[i]["embedding"] = get_embedding(
clinics[i]["name"] + "\n" + clinics[i]["description"]
)
def list_to_obj(obj):
return {func["name"]: func["parameters"]["properties"] for func in obj}
def merge_function_lists(funclists):
res = {}
for funclist in funclists:
res.update(list_to_obj(funclist))
return res
functions = merge_function_lists([med_models, diagnostic_tests, system_functions])
def search(arr, query, n=3):
embedding = get_embedding(query)
ranked_models = sorted(
arr, key=lambda x: cosine_similarity(x["embedding"], embedding), reverse=True
)
return [
{k: v for k, v in model.items() if k != "embedding"}
for model in ranked_models[:n]
]
with open(f"data/{PATIENT}/primary_care.md", "r") as file:
patient_case = file.read()
user_prompt = input("What do you want to ask?\n")
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": patient_case},
{"role": "user", "content": user_prompt},
]
def call_llm(messages, functions, model="gpt-4-1106-preview"):
return client.chat.completions.create(
model=model,
# model="gpt-3.5-turbo-0125",
messages=messages,
functions=functions,
function_call="auto",
temperature=0.4,
max_tokens=1024,
# top_p=1,
# frequency_penalty=0,
# presence_penalty=0,
seed=2024,
)
while True:
pretty_print_conversation(messages)
response = call_llm(messages, system_functions)
if DEBUG:
print(response)
else:
os.system("clear")
response_message = response.choices[0].message
messages.append(response_message)
pretty_print_conversation(messages)
if not response_message.function_call:
user_prompt = input("What do you want to ask?\n")
match = re.search(r"INSERT (\w+)", user_prompt)
print(match)
if match:
file = match.group(1)
print(file)
with open(f"data/{PATIENT}/{file}.md", "r") as file:
text = file.read()
messages.append({"role": "user", "content": text})
else:
messages.append({"role": "user", "content": user_prompt})
else:
function_name = response_message.function_call.name
function_args = json.loads(response_message.function_call.arguments)
if functions.get(function_name) is None:
messages.append(
{
"role": "function",
"name": function_name,
"content": json.dumps(
{
"error": "No such function",
"details": "The function requested does not exist. Try using the applicable serach function to find a suitable function.",
},
indent=4,
),
}
)
continue
try:
validate(instance=function_args, schema=functions[function_name])
except ValidationError as e:
messages.append(
{
"role": "function",
"name": function_name,
"content": json.dumps(
{"error": "Validation Failed", "details": e.message}, indent=4
),
}
)
continue
except SchemaError as e:
messages.append(
{
"role": "function",
"name": function_name,
"content": json.dumps(
{"error": "Validation Failed", "details": e.message}, indent=4
),
}
)
continue
if function_name == "request_diagnostic_test" or function_name == "run_model":
subfunction_name = function_args["name"]
subfunction_args = function_args.get("arguments")
if functions.get(subfunction_name) is None:
messages.append(
{
"role": "function",
"name": function_name,
"content": json.dumps(
{
"error": "No such function",
"details": f"The requested function ({subfunction_name}) to use does not exist",
},
indent=4,
),
}
)
continue
if subfunction_args is None:
subfunction_args = {}
if functions[subfunction_name] != {} and subfunction_args == {}:
messages.append(
{
"role": "function",
"name": subfunction_name,
"content": json.dumps(
{
"error": "Validation Failed",
"details": f'Function call requries arguments in the "arguments" key: {json.dumps(functions[subfunction_name])}',
},
indent=4,
),
}
)
continue
try:
validate(instance=subfunction_args, schema=functions[subfunction_name])
except ValidationError as e:
messages.append(
{
"role": "function",
"name": subfunction_name,
"content": json.dumps(
{"error": "Validation Failed", "details": e.message},
indent=4,
),
}
)
continue
except SchemaError as e:
messages.append(
{
"role": "function",
"name": subfunction_name,
"content": json.dumps(
{"error": "Validation Failed", "details": e.message},
indent=4,
),
}
)
continue
if function_name == "search_care_pathways":
queried_pathways = search(care_pathways, function_args.get("search_query"))
queried_pathways = [{"name": d["name"]} for d in queried_pathways]
messages.append(
{
"role": "function",
"name": "search_care_pathways",
"content": json.dumps(queried_pathways, indent=4),
}
)
elif function_name == "get_care_pathway":
value = [d for d in care_pathways if d["name"] == function_args.get("name")]
if len(value) == 0:
value = "NO VALUE WITH THAT NAME FOUND"
else:
value = value[0]["content"]
messages.append(
{
"role": "function",
"name": "get_care_pathway",
"content": json.dumps({"value": value}, indent=4),
}
)
elif function_name == "search_models":
queried_functions = search(med_models, function_args.get("search_query"))
messages.append(
{
"role": "function",
"name": "search_models",
"content": json.dumps(queried_functions, indent=4),
}
)
elif function_name == "search_diagnostic_tests":
queried_functions = search(
diagnostic_tests, function_args.get("search_query")
)
messages.append(
{
"role": "function",
"name": "search_diagnostic_tests",
"content": json.dumps(queried_functions, indent=4),
}
)
elif function_name == "list_ehr":
only_updates = [
{k: v for k, v in d.items() if k != "embedding"}
for d in ehr
if d.get("created")
]
messages.append(
{
"role": "function",
"name": "list_ehr",
"content": json.dumps(only_updates, indent=4),
}
)
elif function_name == "search_values_in_ehr":
queried_values = search(ehr, function_args.get("search_query"))
messages.append(
{
"role": "function",
"name": "search_values_in_ehr",
"content": json.dumps(queried_values, indent=4),
}
)
elif function_name == "get_value_from_ehr":
value = [d for d in ehr if d["name"] == function_args.get("name")]
if len(value) == 0:
value = "NO VALUE WITH THAT NAME FOUND"
else:
value = value[0]["content"]
messages.append(
{
"role": "function",
"name": "get_value_from_ehr",
"content": json.dumps({"value": value}, indent=4),
}
)
elif function_name == "search_referral_clinics":
queried_clinics = search(clinics, function_args.get("search_query"))
messages.append(
{
"role": "function",
"name": "search_referral_clinics",
"content": json.dumps(queried_clinics, indent=4),
}
)
else:
function_name = response_message.function_call.name
function_args = json.loads(response_message.function_call.arguments)
print(
f"ChatGPT wants to use the function/model: {function_name} with arguments: {function_args}"
)
user_prompt = input("What should be returned?\n")
match = re.search(r"INSERT (\w+)", user_prompt)
print(match)
if match:
file = match.group(1)
print(file)
with open(f"data/{PATIENT}/{file}.md", "r") as file:
text = file.read()
messages.append(
{
"role": "function",
"name": function_name,
"content": text,
}
)
else:
messages.append(
{
"role": "function",
"name": function_name,
"content": user_prompt,
}
)