Datasets:
File size: 17,706 Bytes
10bf19f |
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 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 |
""" Evaluate Medical Tests Classification in LLMS """
## Setup
#### Load the API key and libaries.
import os
import re
import json
import pandas as pd
import argparse
import subprocess
import time
# Create a class to handle the GPT API
class GPT:
# build the constructor
def __init__(self, model='gpt-3.5-turbo', temperature=0.0, n_repetitions=1, reasoning=False, languages=['english', 'portuguese'], path='data/Portuguese.csv', max_tokens=500):
import openai
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key = os.environ['OPENAI_API_KEY']
self.path = path
self.model = model
self.temperature = temperature
self.n_repetitions = n_repetitions if n_repetitions > 0 else 1
self.reasoning = reasoning
self.languages = languages
self.max_tokens = max_tokens
self.delimiter = "####"
self.responses = ['A', 'B', 'C', 'D']
self.extra_message = ""
if self.reasoning:
self.output_keys = ['response', 'reasoning']
else:
self.output_keys = ['response']
self.update_system_message()
def update_system_message(self):
"""
Update the system message based on the current configuration.
"""
if self.reasoning:
self.system_message = f"""
You will be provided with medical queries in this languages: {", ".join(self.languages)}. \
The medical query will be delimited with {self.delimiter} characters.
Each question will have {len(self.responses)} possible answer options.\
provide the letter with the answer and a short sentence answering why the answer was selected. \
{self.extra_message}
Provide your output in json format with the \
keys: {", ".join(self.output_keys)}.
Responses: {", ".join(self.responses)}.
"""
else:
self.system_message = f"""
You will be provided with medical queries in this languages: {", ".join(self.languages)}. \
The medical query will be delimited with {self.delimiter} characters.
Each question will have {len(self.responses)} possible answer options.\
provide only the letter with the response.
{self.extra_message}
Provide your output in json format with:
the keys: {", ".join(self.output_keys)}.
Responses: {", ".join(self.responses)}.
E.g. if response is 'a', the output should be: {{"response" : "a"}}
"""
# function to change the delimiter
def change_delimiter(self, delimiter):
""" Change the delimiter """
self.delimiter = delimiter
self.update_system_message()
# function to change the responses
def change_responses(self, responses):
self.responses = responses
self.update_system_message()
def change_output_keys(self, output_keys):
self.output_keys = output_keys
self.update_system_message()
def add_output_key(self, output_key):
self.output_keys.append(output_key)
self.update_system_message()
def change_languages(self, languages):
self.languages = languages
self.update_system_message()
def add_extra_message(self, extra_message):
self.extra_message = extra_message
self.update_system_message()
def change_system_message(self, system_message):
self.system_message = system_message
def change_reasoning(self, reasoning=None):
if type(reasoning) == bool:
self.reasoning = reasoning
else:
if reasoning:
print(f'Reasoning should be boolean. Changing reasoning from {self.reasoning} to {not(self.reasoning)}.')
self.reasoning = False if self.reasoning else True
if self.reasoning:
self.output_keys.append('reasoning')
# remove duplicates
self.output_keys = list(set(self.output_keys))
else:
try:
self.output_keys.remove('reasoning')
except:
pass
self.update_system_message()
#### Template for the Questions
def generate_question(self, question):
user_message = f"""/
{question}"""
messages = [
{'role':'system',
'content': self.system_message},
{'role':'user',
'content': f"{self.delimiter}{user_message}{self.delimiter}"},
]
return messages
#### Get the completion from the messages
def get_completion_from_messages(self, prompt):
messages = self.generate_question(prompt)
try:
response = openai.ChatCompletion.create(
model=self.model,
messages=messages,
temperature=self.temperature,
max_tokens=self.max_tokens,
request_timeout=10
)
except:
# Could be due to TPM or RPM, so sleep one minute
time.sleep(61)
response = self.get_completion_from_messages(prompt)
return response
response = response.choices[0].message["content"]
# Convert the string into a JSON object
response = json.loads(response)
return response
### Questions from a csv file:
df = pd.read_csv(self.path)
### Evaluate the model in question answering per language:
responses = {}
for key in self.output_keys:
responses[key] = {}
for language in self.languages:
responses[key][language] = [[] for n in range(self.n_repetitions)]
for row in range(df.shape[0]):
print('*'*50)
print(f'Question {row+1}: ')
for language in self.languages:
print(f'Language: {language}')
question = df[language][row]
print('Question: ')
print(question)
for n in range(self.n_repetitions):
print(f'Test #{n}: ')
response = self.get_completion_from_messages(question)
print(response)
for key in self.output_keys:
# Append to the list:
responses[key][language][n].append(response[key])
print('*'*50)
### Save the results in a csv file:
for language in self.languages:
if self.n_repetitions == 1:
for key in self.output_keys:
df[f'{key}_{language}'] = responses[key][language][0]
else:
for n in range(self.n_repetitions):
for key in self.output_keys:
df[f'{key}_{language}_{n}'] = responses[key][language][n]
if save:
if not os.path.exists('responses'):
os.makedirs('responses')
if self.n_repetitions == 1:
df.to_csv(f"responses/{self.model}_Temperature{str(self.temperature).replace('.', '_')}.csv", index=False)
else:
df.to_csv(f"responses/{self.model}_Temperature{str(self.temperature).replace('.', '_')}_{self.n_repetitions}Repetitions.csv", index=False)
return df
# Create a class to handle the LLAMA 2
class LLAMA:
# build the constructor
def __init__(self, model='Llama-2-7b', temperature=0.0, n_repetitions=1, reasoning=False, languages=['english', 'portuguese'], path='data/Portuguese.csv', max_tokens=500, verbose=False):
self.model = model
model_path = self.download_hugging_face_model(model)
from llama_cpp import Llama
self.llm = Llama(model_path=model_path, verbose=verbose)
self.path = path
self.temperature = temperature
self.n_repetitions = n_repetitions if n_repetitions > 0 else 1
self.reasoning = reasoning
self.languages = languages
self.max_tokens = max_tokens
self.delimiter = "####"
self.responses = ['A', 'B', 'C', 'D']
self.extra_message = ""
if self.reasoning:
self.output_keys = ['response', 'reasoning']
else:
self.output_keys = ['response']
self.update_system_message()
def update_system_message(self):
"""
Update the system message based on the current configuration.
"""
if self.reasoning:
self.system_message = f"""
You will be provided with medical queries in this languages: {", ".join(self.languages)}. \
The medical query will be delimited with \
{self.delimiter} characters.
Each question will have {len(self.responses)} possible answer options.\
provide the letter with the answer and a short sentence answering why the answer was selected. \
{self.extra_message}
Provide your output in json format with the \
keys: {", ".join(self.output_keys)}. Make sure to always use the those keys, do not modify the keys.
Be very careful with the resulting JSON file, make sure to add curly braces, quotes to define the strings, and commas to separate the items within the JSON.
Responses: {", ".join(self.responses)}.
"""
else:
self.system_message = f"""
You will be provided with medical queries in this languages: {", ".join(self.languages)}. \
The medical query will be delimited with \
{self.delimiter} characters.
Each question will have {len(self.responses)} possible answer options.\
{self.extra_message}
Provide your output in json format with the \
keys: {", ".join(self.output_keys)}. Make sure to always use the those keys, do not modify the keys.
Be very careful with the resulting JSON file, make sure to add curly braces, quotes to define the strings, and commas to separate the items within the JSON.
Responses: {", ".join(self.responses)}.
"""
def download_and_rename(self, url, filename):
"""Downloads a file from the given URL and renames it to the given new file name.
Args:
url: The URL of the file to download.
new_file_name: The new file name for the downloaded file.
"""
os.makedirs(os.path.dirname(filename), exist_ok=True)
print(f'Downloading the weights of the model: {url} ...')
subprocess.run(["wget", "-q", "-O", filename, url])
print(f'Done!')
def download_hugging_face_model(self, model_version='Llama-2-7b'):
if model_version not in ['Llama-2-7b', 'Llama-2-13b', 'Llama-2-70b']:
raise ValueError("Options for Llama model should be 7b, 13b or 70b")
MODEL_URL = {
'Llama-2-7b': 'https://huggingface.co/TheBloke/Llama-2-7b-Chat-GGUF/resolve/main/llama-2-7b-chat.Q8_0.gguf',
'Llama-2-13b': 'https://huggingface.co/TheBloke/Llama-2-13B-chat-GGUF/resolve/main/llama-2-13b-chat.Q8_0.gguf',
'Llama-2-70b': 'https://huggingface.co/TheBloke/Llama-2-70B-chat-GGUF/resolve/main/llama-2-70b-chat.Q5_0.gguf'
}
MODEL_URL = MODEL_URL[model_version]
model_path = f'Models/{model_version}.gguf'
if os.path.exists(model_path):
confirmation = input(f"The model file '{model_path}' already exists. Do you want to overwrite it? (yes/no): ").strip().lower()
if confirmation != 'yes':
print("Model installation aborted.")
return model_path
self.download_and_rename(MODEL_URL, model_path)
return model_path
# function to change the delimiter
def change_delimiter(self, delimiter):
""" Change the delimiter """
self.delimiter = delimiter
self.update_system_message()
# function to change the responses
def change_responses(self, responses):
self.responses = responses
self.update_system_message()
def change_output_keys(self, output_keys):
self.output_keys = output_keys
self.update_system_message()
def add_output_key(self, output_key):
self.output_keys.append(output_key)
self.update_system_message()
def change_languages(self, languages):
self.languages = languages
self.update_system_message()
def add_extra_message(self, extra_message):
self.extra_message = extra_message
self.update_system_message()
def change_system_message(self, system_message):
self.system_message = system_message
def change_reasoning(self, reasoning=None):
if type(reasoning) == bool:
self.reasoning = reasoning
else:
if reasoning:
print(f'Reasoning should be boolean. Changing reasoning from {self.reasoning} to {not(self.reasoning)}.')
self.reasoning = False if self.reasoning else True
if self.reasoning:
self.output_keys.append('reasoning')
# remove duplicates
self.output_keys = list(set(self.output_keys))
else:
try:
self.output_keys.remove('reasoning')
except:
pass
self.update_system_message()
#### Template for the Questions
def generate_question(self, question):
user_message = f"""/
{question}"""
messages = [
{'role':'system',
'content': self.system_message},
{'role':'user',
'content': f"{self.delimiter}{user_message}{self.delimiter}"},
]
return messages
#### Get the completion from the messages
def get_completion_from_messages(self, prompt):
messages = self.generate_question(prompt)
response = self.llm.create_chat_completion(
messages,
temperature=self.temperature,
max_tokens=self.max_tokens)
self.llm.set_cache(None)
response = response['choices'][0]['message']["content"]
# Convert the string into a JSON object
try:
# Use regular expressions to extract JSON
json_pattern = r'\{.*\}' # Match everything between '{' and '}'
match = re.search(json_pattern, response, re.DOTALL)
response = match.group()
# Define a regex pattern to identify unquoted string values
pattern = r'("[^"]*":\s*)([A-Za-z_][A-Za-z0-9_]*)'
# Use a lambda function to add quotes to unquoted string values
response = re.sub(pattern, lambda m: f'{m.group(1)}"{m.group(2)}"', response)
# Convert
response = json.loads(response)
except:
print(f'Error converting respose to json: {response}')
print('Generating new response...')
response = self.get_completion_from_messages(prompt)
return response
if self.reasoning:
# Iterate through the keys of the dictionary
for key in list(response.keys()):
if 'reas' in key.lower():
# Update the dictionary with the new key and its corresponding value
response['reasoning'] = response.pop(key)
return response
def llm_language_evaluation(self, save=True):
### Questions from a csv file:
df = pd.read_csv(self.path)
### Evaluate the model in question answering per language:
responses = {}
for key in self.output_keys:
responses[key] = {}
for language in self.languages:
responses[key][language] = [[] for n in range(self.n_repetitions)]
for row in range(df.shape[0]):
print('*'*50)
print(f'Question {row+1}: ')
for language in self.languages:
print(f'Language: {language}')
question = df[language][row]
print('Question: ')
print(question)
for n in range(self.n_repetitions):
print(f'Test #{n}: ')
response = self.get_completion_from_messages(question)
print(response)
for key in self.output_keys:
# Append to the list:
responses[key][language][n].append(response[key])
print('*'*50)
### Save the results in a csv file:
for language in self.languages:
if self.n_repetitions == 1:
for key in self.output_keys:
df[f'{key}_{language}'] = responses[key][language][0]
else:
for n in range(self.n_repetitions):
for key in self.output_keys:
df[f'{key}_{language}_{n}'] = responses[key][language][n]
if save:
if not os.path.exists('responses'):
os.makedirs('responses')
if self.n_repetitions == 1:
df.to_csv(f"responses/{self.model}_Temperature{str(self.temperature).replace('.', '_')}.csv", index=False)
else:
df.to_csv(f"responses/{self.model}_Temperature{str(self.temperature).replace('.', '_')}_{self.n_repetitions}Repetitions.csv", index=False)
return df |