RichardZhu52 commited on
Commit
c2f38bc
·
1 Parent(s): b21f84c

adding python files

Browse files
Files changed (2) hide show
  1. app.py +1185 -0
  2. utils.py +239 -0
app.py ADDED
@@ -0,0 +1,1185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from gradio_modal import Modal
3
+ from huggingface_hub import hf_hub_download, list_repo_files
4
+ import os, csv, datetime, sys
5
+ import json
6
+ from utils import format_chat, append_to_sheet, read_sheet_to_df
7
+ import random
8
+ import base64
9
+ import re
10
+
11
+ def encode_image_to_base64(image_path):
12
+ """Encodes an image file to a base64 string."""
13
+ try:
14
+ with open(image_path, "rb") as image_file:
15
+ encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
16
+ return encoded_string
17
+ except FileNotFoundError:
18
+ print(f"Error: Image file not found at {image_path}")
19
+ return None
20
+
21
+ # HTML file for first page
22
+ html_file_path = "index.html"
23
+ try:
24
+ with open(html_file_path, 'r', encoding='utf-8') as f:
25
+ TxAgent_Project_Page_HTML_raw = f.read()
26
+ TxAgent_Project_Page_HTML = TxAgent_Project_Page_HTML_raw
27
+
28
+ # Find all image paths matching the pattern
29
+ image_path_pattern = r'static/images/([^"]*\.jpg)'
30
+ image_paths = re.findall(image_path_pattern, TxAgent_Project_Page_HTML_raw)
31
+ unique_image_paths = set(image_paths)
32
+
33
+ # Encode each unique image and replace the paths
34
+ for img_file in unique_image_paths:
35
+ full_image_path = os.path.join("static/images", img_file)
36
+ encoded_image = encode_image_to_base64(full_image_path)
37
+ if encoded_image:
38
+ original_path = f"static/images/{img_file}"
39
+ base64_url = f'data:image/jpeg;base64,{encoded_image}' # Assuming JPEG, adjust if needed
40
+ TxAgent_Project_Page_HTML = TxAgent_Project_Page_HTML.replace(original_path, base64_url)
41
+
42
+ except Exception as e:
43
+ print(f"Error reading HTML file: {e}")
44
+ TxAgent_Project_Page_HTML = "<p>Error: Project page content could not be loaded.</p>"
45
+
46
+ # # Assume 'your_image.png' is in the same directory
47
+ # with open("txagent.jpg", "rb") as image_file:
48
+ # encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
49
+
50
+ # image_html = f'<img src="data:image/png;base64,{encoded_string}" alt="Your Image">'
51
+
52
+ # TxAgent_Project_Page_HTML = f"""
53
+ # <div>
54
+ # <h2>Project Information</h2>
55
+ # <p>Here's some information about the TxAgent project.</p>
56
+ # {image_html}
57
+ # </div>
58
+ # """
59
+
60
+ # Load tool lists
61
+ fda_drug_labeling_tools_path = "fda_drug_labeling_tools.json"
62
+ monarch_tools_path = "monarch_tools.json"
63
+ opentarget_tools_path = "opentarget_tools.json"
64
+
65
+ try:
66
+ with open(fda_drug_labeling_tools_path, 'r') as f:
67
+ fda_data = json.load(f)
68
+ fda_drug_labeling_tools_list = [item['name'] for item in fda_data if 'name' in item]
69
+ except Exception as e:
70
+ print(f"Error processing {fda_drug_labeling_tools_path}: {e}")
71
+ fda_drug_labeling_tools_list = ["Error loading FDA tools"]
72
+
73
+ try:
74
+ with open(monarch_tools_path, 'r') as f:
75
+ monarch_data = json.load(f)
76
+ monarch_tools_list = [item['name'] for item in monarch_data if 'name' in item]
77
+ except Exception as e:
78
+ print(f"Error processing {monarch_tools_path}: {e}")
79
+ monarch_tools_list = ["Error loading Monarch tools"]
80
+
81
+ try:
82
+ with open(opentarget_tools_path, 'r') as f:
83
+ opentarget_data = json.load(f)
84
+ opentarget_tools_list = [item['name'] for item in opentarget_data if 'name' in item]
85
+ except Exception as e:
86
+ print(f"Error processing {opentarget_tools_path}: {e}")
87
+ opentarget_tools_list = ["Error loading OpenTarget tools"]
88
+
89
+ #for labeling the different tool calls in format_chat
90
+ tool_database_labels = {
91
+ "**from approved FDA drug labels**": fda_drug_labeling_tools_list,
92
+ "**from the Monarch Initiative databases**": monarch_tools_list,
93
+ "**from the Open Targets database**": opentarget_tools_list,
94
+ }
95
+
96
+ # Define the six evaluation criteria as a list of dictionaries.
97
+ criteria = [
98
+ {
99
+ "label": "Problem Resolution",
100
+ "text": (
101
+ "Problem Resolution: Did the model effectively solve the problem?",
102
+ "1️⃣ Did Not Solve the Problem at All. 2️⃣ Attempted to Solve but Largely Incorrect or Incomplete. 3️⃣ Partially Solved the Problem, but with Limitations. 4️⃣ Mostly Solved the Problem, with Minor Issues. 5️⃣ Completely and Effectively Solved the Problem."
103
+ )
104
+ },
105
+ {
106
+ "label": "Helpfulness",
107
+ "text": (
108
+ "Helpfulness: Was the answer and reasoning provided helpful in addressing the question?",
109
+ "1️⃣ Not Helpful at All. 2️⃣ Slightly Helpful, but Largely Insufficient. 3️⃣ Moderately Helpful, but Needs Improvement. 4️⃣ Helpful and Mostly Clear, with Minor Issues. 5️⃣ Extremely Helpful and Comprehensive."
110
+ )
111
+ },
112
+ {
113
+ "label": "Scientific Consensus",
114
+ "text": (
115
+ "Clinical Consensus: Does the answer align with established scientific and clinical consensus?",
116
+ "1️⃣ Completely Misaligned with Clinical Consensus. 2️⃣ Partially Aligned but Contains Significant Inaccuracies or Misinterpretations. 3️⃣ Generally Aligned but Lacks Rigor or Clarity. 4️⃣ Mostly Aligned with Clinical Consensus, with Minor Omissions or Uncertainties. 5️⃣ Fully Aligned with Established Clinical Consensus."
117
+ )
118
+ },
119
+ {
120
+ "label": "Accuracy",
121
+ "text": (
122
+ "Accuracy of Content: Is there any incorrect or irrelevant content in the answer and the reasoning content?",
123
+ "1️⃣ Completely Inaccurate or Irrelevant. 2️⃣ Mostly Inaccurate, with Some Relevant Elements. 3️⃣ Partially Accurate, but Includes Some Errors or Omissions. 4️⃣ Mostly Accurate, with Minor Issues or Unverified Claims. 5️⃣ Completely Accurate and Relevant."
124
+ )
125
+ },
126
+ {
127
+ "label": "Completeness",
128
+ "text": (
129
+ "Completeness: Did the answer omit any essential content necessary for a comprehensive response?",
130
+ "1️⃣ Severely Incomplete – Major Content Omissions. 2️⃣ Largely Incomplete – Missing Key Elements. 3️⃣ Somewhat Complete – Covers Basics but Lacks Depth. 4️⃣ Mostly Complete – Minor Omissions or Gaps. 5️⃣ Fully Complete – No Important Omissions."
131
+ )
132
+ },
133
+ ]
134
+
135
+ criteria_for_comparison = [
136
+ {
137
+ "label": "Problem Resolution",
138
+ "text": (
139
+ "Problem Resolution: Did the model effectively solve the problem?<br>"
140
+ )
141
+ },
142
+ {
143
+ "label": "Helpfulness",
144
+ "text": (
145
+ "Helpfulness: Was the answer and reasoning provided helpful in addressing the question?<br>"
146
+ )
147
+ },
148
+ {
149
+ "label": "Scientific Consensus",
150
+ "text": (
151
+ "Scientific and Clinical Consensus: Does the answer align with established scientific and clinical consensus?<br>"
152
+ )
153
+ },
154
+ {
155
+ "label": "Accuracy",
156
+ "text": (
157
+ "Accuracy of Content: Is there any incorrect or irrelevant content in the answer and the reasoning content?<br>"
158
+ )
159
+ },
160
+ {
161
+ "label": "Completeness",
162
+ "text": (
163
+ "Completeness: Did the answer omit any essential content necessary for a comprehensive response?<br>"
164
+ )
165
+ },
166
+ ]
167
+
168
+ mapping = { #for pairwise mapping between model comparison selections
169
+ "👈 Model A": "A",
170
+ "👉 Model B": "B",
171
+ "🤝 Tie": "tie",
172
+ "👎 Neither model did well": "neither"
173
+ }
174
+
175
+ #Prepare data
176
+ REPO_ID = "RichardZhu52/TxAgent_human_eval"
177
+ CROWDSOURCING_DATA_DIRECTORY = "crowdsourcing_eval_data_0430"
178
+ TXAGENT_RESULTS_SHEET_BASE_NAME = "TxAgent_Human_Eval_Results_CROWDSOURCED"
179
+ DISEASE_SPECIALTY_MAP_FILENAME = "disease_specialty_map.json"
180
+
181
+ def get_evaluator_questions(email, disease_map_data, user_all_specs, all_files, evaluator_directory):
182
+ relevant_diseases = []
183
+ for disease, specs in disease_map_data.items():
184
+ disease_specs = set(specs.get('specialties', []))
185
+ disease_subspecs = set(specs.get('subspecialties', []))
186
+
187
+ # Check for intersection
188
+ if user_all_specs.intersection(disease_specs) or user_all_specs.intersection(disease_subspecs):
189
+ relevant_diseases.append(disease)
190
+
191
+ # Filter to only the files in that directory
192
+ evaluator_files = [f for f in all_files if f.startswith(f"{evaluator_directory}/")]
193
+ data_by_filename = {}
194
+ for remote_path in evaluator_files:
195
+ local_path = hf_hub_download(
196
+ repo_id=REPO_ID,
197
+ repo_type="dataset",
198
+ revision="main", #fetches the most recent version of the dataset each time this command is called
199
+ filename=remote_path,
200
+ # force_download=True,
201
+ )
202
+ with open(local_path, "r") as f:
203
+ model_name_key = os.path.basename(remote_path).replace('.json', '')
204
+ data_by_filename[model_name_key] = json.load(f)
205
+
206
+ # Filter questions based on relevant diseases derived from user specialties
207
+ evaluator_question_ids = []
208
+ relevant_diseases_lower = {disease.lower() for disease in relevant_diseases} # Convert relevant diseases to lowercase set for efficient lookup
209
+
210
+ # Assuming 'txagent' data is representative for question IDs and associated diseases
211
+ if 'txagent' in data_by_filename:
212
+ for entry in data_by_filename['txagent']:
213
+ question_id = entry.get("question_ID")
214
+ question_diseases = entry.get("disease", []) # Get diseases list, default to empty if missing
215
+ if question_id is not None and question_diseases:
216
+ # Convert question diseases to lowercase and check for intersection
217
+ question_diseases_lower = {disease.lower() for disease in question_diseases if isinstance(disease, str)}
218
+ if question_diseases_lower.intersection(relevant_diseases_lower):
219
+ evaluator_question_ids.append(question_id)
220
+
221
+ # Handle case where no relevant questions are found based on specialty
222
+ if not evaluator_question_ids:
223
+ return [], data_by_filename
224
+
225
+ #FINALLY, MAKE SURE THEY DIDNT ALREADY FILL IT OUT. Must go through every tuple of (question_ID, TxAgent, other model) where other model could be any of the other files in data_by_filename
226
+ model_names = [key for key in data_by_filename.keys() if key != 'txagent']
227
+ # evaluator_question_ids = question_map.get(email).get('question_ids')
228
+ full_question_ids_list = []
229
+ for other_model_name in model_names:
230
+ for q_id in evaluator_question_ids:
231
+ full_question_ids_list.append((q_id, other_model_name))
232
+
233
+ results_df = read_sheet_to_df(custom_sheet_name=str(TXAGENT_RESULTS_SHEET_BASE_NAME))
234
+ if (results_df is not None) and (not results_df.empty):
235
+ # collect all (question_ID, other_model) pairs already seen
236
+ matched_pairs = set()
237
+ for _, row in results_df.iterrows():
238
+ if row["Email"] == email:
239
+ q = row["Question ID"]
240
+ # pick whichever response isn’t 'txagent'
241
+ a, b = row["ResponseA_Model"], row["ResponseB_Model"]
242
+ if a == "txagent" and b != "txagent":
243
+ matched_pairs.add((q, b))
244
+ elif b == "txagent" and a != "txagent":
245
+ matched_pairs.add((q, a))
246
+
247
+ # filter out any tuple whose (q_id, other_model) was already matched
248
+ full_question_ids_list = [
249
+ (q_id, other_model)
250
+ for (q_id, other_model) in full_question_ids_list
251
+ if (q_id, other_model) not in matched_pairs
252
+ ]
253
+ print(f"Filtered question IDs: {full_question_ids_list}")
254
+ print(f"Length of filtered question IDs: {len(full_question_ids_list)}")
255
+
256
+
257
+ return full_question_ids_list, data_by_filename
258
+
259
+ def go_to_page0_from_minus1():
260
+ return gr.update(visible=False), gr.update(visible=True)
261
+
262
+ def go_to_eval_progress_modal(name, email, specialty_dd, subspecialty_dd, years_exp_radio, exp_explanation_tb, npi_id):
263
+
264
+ # ADDED: Validate that name and email are non-empty before proceeding
265
+ if not name or not email or not specialty_dd or not years_exp_radio:
266
+ return gr.update(visible=True), gr.update(visible=False), None, "Please fill out all the required fields (name, email, specialty, years of experience). If you are not a licensed physician with a specific specialty, please choose the specialty that most closely aligns with your biomedical expertise.", gr.Chatbot(), gr.Chatbot(), gr.HTML(),gr.State(),gr.update(visible=False), ""
267
+
268
+ # Combine user's selected specialties and subspecialties into a set for efficient lookup
269
+ # Ensure inputs are lists, even if None or single strings are passed (though Dropdown with multiselect=True should return lists)
270
+ user_specialties = set(specialty_dd if isinstance(specialty_dd, list) else ([specialty_dd] if specialty_dd else []))
271
+ user_subspecialties = set(subspecialty_dd if isinstance(subspecialty_dd, list) else ([subspecialty_dd] if subspecialty_dd else []))
272
+ user_all_specs = user_specialties.union(user_subspecialties)
273
+
274
+ #retrieve data from HF
275
+ evaluator_directory = CROWDSOURCING_DATA_DIRECTORY
276
+ if evaluator_directory is None:
277
+ return gr.update(visible=True), gr.update(visible=False), None, "Invalid Evaluator ID, please try again.", gr.Chatbot(), gr.Chatbot(), gr.HTML(),gr.State(),gr.update(visible=False),""
278
+ all_files = list_repo_files(
279
+ repo_id=REPO_ID,
280
+ repo_type="dataset",
281
+ revision="main",
282
+ )
283
+
284
+ disease_specialty_map = hf_hub_download(
285
+ repo_id=REPO_ID,
286
+ filename=DISEASE_SPECIALTY_MAP_FILENAME,
287
+ repo_type="dataset",
288
+ revision="main",
289
+ )
290
+
291
+ with open(disease_specialty_map, 'r') as f:
292
+ disease_map_data = json.load(f)
293
+
294
+ full_question_ids_list, data_by_filename = get_evaluator_questions(email, disease_map_data, user_all_specs, all_files, evaluator_directory)
295
+
296
+ if len(full_question_ids_list) == 0:
297
+ return gr.update(visible=True), gr.update(visible=False), None, "Based on your submitted data, you have no more questions to evaluate. You may exit the page; we will follow-up if we require anything else from you. Thank you!", gr.Chatbot(), gr.Chatbot(), gr.HTML(),gr.State(),gr.update(visible=False),""
298
+
299
+ full_question_ids_list = sorted(full_question_ids_list, key=lambda x: str(x[0])+str(x[1]))
300
+ #selected question is the first element
301
+ q_id, other_model_name = full_question_ids_list[0]
302
+
303
+ #Constructing question_for_eval, the question to evaluate this round
304
+ txagent_matched_entry = next(
305
+ (entry for entry in data_by_filename['txagent'] if entry.get("question_ID") == q_id),
306
+ None
307
+ )
308
+ other_model_matched_entry = next(
309
+ (entry for entry in data_by_filename[other_model_name] if entry.get("question_ID") == q_id),
310
+ None
311
+ )
312
+
313
+ models_list = [
314
+ {
315
+ "model": "txagent",
316
+ "reasoning_trace": txagent_matched_entry.get("solution")
317
+ },
318
+ {
319
+ "model": other_model_name,
320
+ "reasoning_trace": other_model_matched_entry.get("solution")
321
+ }
322
+ ]
323
+ random.shuffle(models_list)
324
+
325
+ question_for_eval = {
326
+ "question": txagent_matched_entry.get("question"),
327
+ "question_ID": q_id,
328
+ "models": models_list,
329
+ }
330
+
331
+ #update user_info
332
+ user_info = (name, email, specialty_dd, subspecialty_dd, years_exp_radio, exp_explanation_tb, npi_id, q_id)
333
+ chat_A_value = format_chat(question_for_eval['models'][0]['reasoning_trace'], tool_database_labels)
334
+ chat_B_value = format_chat(question_for_eval['models'][1]['reasoning_trace'], tool_database_labels)
335
+ prompt_text = question_for_eval['question']
336
+
337
+ # Construct the question-specific elements of the pairwise rating page (page 1)
338
+ page1_prompt = gr.HTML(f'<div style="background-color: #FFEFD5; border: 2px solid #FF8C00; padding: 10px; border-radius: 5px; color: black;"><strong style="color: black;">Prompt:</strong> {prompt_text}</div>')
339
+ chat_a = gr.Chatbot(
340
+ value=chat_A_value,
341
+ type="messages",
342
+ height=400,
343
+ label="Model A Response",
344
+ show_copy_button=False,
345
+ show_label=True,
346
+ render_markdown=True, # Required for markdown/HTML support in messages
347
+ avatar_images=None, # Optional: omit user/assistant icons
348
+ rtl=False
349
+ )
350
+ chat_b = gr.Chatbot(
351
+ value=chat_B_value,
352
+ type="messages",
353
+ height=400,
354
+ label="Model B Response",
355
+ show_copy_button=False,
356
+ show_label=True,
357
+ render_markdown=True, # Required for markdown/HTML support in messages
358
+ avatar_images=None, # Optional: omit user/assistant icons
359
+ rtl=False
360
+ )
361
+ return gr.update(visible=True), gr.update(visible=False), user_info,"", chat_a, chat_b, page1_prompt, question_for_eval, gr.update(visible=True), f"You are about to evaluate the next question."#f"You have {len(full_question_ids_list)} question(s) remaining to evaluate."
362
+
363
+ #goes to page 1 from confirmation modal that tells users how many questions they have left to evaluate
364
+ def go_to_page1():
365
+ """
366
+ Shows page 1
367
+ """
368
+
369
+ # Return updates to hide modal, hide page 0, show page 1, populate page 1, and set final state
370
+ updates = [
371
+ gr.update(visible=False),
372
+ gr.update(visible=False),
373
+ gr.update(visible=True),
374
+ ]
375
+ return updates
376
+
377
+
378
+ # Callback to transition from Page 1 to Page 2.
379
+ def go_to_page2(data_subset_state,*pairwise_values):
380
+ # pairwise_values is a tuple of values from each radio input.
381
+ criteria_count = len(criteria_for_comparison)
382
+ pairwise_list = list(pairwise_values[:criteria_count])
383
+ comparison_reasons_list = list(pairwise_values[criteria_count:])
384
+
385
+ #gradio components to display previous page results on next page
386
+ pairwise_results_for_display = [gr.Markdown(f"***As a reminder, your pairwise comparison answer for this criterion was: {pairwise_list[i]}. Your answer choices will be restricted based on your comparison answer, but you may go back and change the comparison answer if you wish.***") for i in range(len(criteria))]
387
+
388
+ if any(answer is None for answer in pairwise_list):
389
+ return gr.update(visible=True), gr.update(visible=False), None, None, "Error: Please select an option for every pairwise comparison.", gr.Chatbot(), gr.Chatbot(), gr.HTML(), *pairwise_results_for_display
390
+
391
+ chat_A_value = format_chat(data_subset_state['models'][0]['reasoning_trace'], tool_database_labels)
392
+ chat_B_value = format_chat(data_subset_state['models'][1]['reasoning_trace'], tool_database_labels)
393
+ prompt_text = data_subset_state['question']
394
+
395
+ # Construct the question-specific elements of the rating page (page 2)
396
+ chat_A_rating = gr.Chatbot(
397
+ value=chat_A_value,
398
+ type="messages",
399
+ height=400,
400
+ label="Model A Response",
401
+ show_copy_button=False,
402
+ render_markdown=True
403
+ )
404
+
405
+ chat_B_rating = gr.Chatbot(
406
+ value=chat_B_value,
407
+ type="messages",
408
+ height=400,
409
+ label="Model B Response",
410
+ show_copy_button=False,
411
+ render_markdown=True
412
+ )
413
+
414
+ page2_prompt = gr.HTML(f'<div style="background-color: #FFEFD5; border: 2px solid #FF8C00; padding: 10px; border-radius: 5px; color: black;"><strong style="color: black;">Prompt:</strong> {prompt_text}</div>')
415
+
416
+ return gr.update(visible=False), gr.update(visible=True), pairwise_list, comparison_reasons_list, "", chat_A_rating, chat_B_rating, page2_prompt, *pairwise_results_for_display
417
+
418
+
419
+ # Callback to store scores for Response A.
420
+ def store_A_scores(*args):
421
+ # Unpack the arguments: first half are scores, second half are checkboxes.
422
+ num = len(args) // 2
423
+ scores = list(args[:num])
424
+ unquals = list(args[num:])
425
+ return scores, unquals
426
+
427
+ # Callback to transition from Page 2 to Page 3.
428
+ def go_to_page3():
429
+ return gr.update(visible=False), gr.update(visible=True)
430
+
431
+ # Updated validation callback that ignores criteria with 'Unable to Judge'
432
+ def validate_ratings(pairwise_choices, *args):
433
+ num_criteria = len(criteria)
434
+ ratings_A_list = list(args[:num_criteria])
435
+ ratings_B_list = list(args[num_criteria:])
436
+ if any(r is None for r in ratings_A_list) or any(r is None for r in ratings_B_list):
437
+ return "Error: Please provide ratings for both responses for every criterion.", "Error: Please provide ratings for both responses for every criterion."
438
+ error_msgs = []
439
+ for i, choice in enumerate(pairwise_choices):
440
+ score_a = ratings_A_list[i]
441
+ score_b = ratings_B_list[i]
442
+ # Skip criteria if either rating is "Unable to Judge"
443
+ if score_a == "Unable to Judge" or score_b == "Unable to Judge":
444
+ continue
445
+ # Convert string scores to integers for comparison.
446
+ score_a = int(score_a)
447
+ score_b = int(score_b)
448
+ if choice == "👈 Model A" and score_a < score_b:
449
+ error_msgs.append(f"Criterion {i+1} ({criteria[i]['label']}): You selected A as better but scored A lower than B.")
450
+ elif choice == "👉 Model B" and score_b < score_a:
451
+ error_msgs.append(f"Criterion {i+1} ({criteria[i]['label']}): You selected B as better but scored B lower than A.")
452
+ elif choice == "🤝 Tie" and score_a != score_b:
453
+ error_msgs.append(f"Criterion {i+1} ({criteria[i]['label']}): You selected Tie but scored A and B differently.")
454
+
455
+ if error_msgs:
456
+ err_str = "\n".join(error_msgs)
457
+ return err_str, err_str
458
+ else:
459
+ return "No errors in responses; feel free to submit!", "No errors in responses; feel free to submit!"
460
+
461
+ # # Additional callback to handle submission results.
462
+ def toggle_slider(is_unqualified):
463
+ # When the checkbox is checked (True), set interactive to False to disable the slider.
464
+ return gr.update(interactive=not is_unqualified)
465
+
466
+ centered_col_css = """
467
+ #centered-column {
468
+ margin-left: auto;
469
+ margin-right: auto;
470
+ max-width: 800px; /* Adjust this width as desired */
471
+ width: 100%;
472
+ }
473
+ """
474
+ with gr.Blocks(css=centered_col_css) as demo:
475
+ # States to save information between pages.
476
+ user_info_state = gr.State()
477
+ pairwise_state = gr.State()
478
+ scores_A_state = gr.State()
479
+ comparison_reasons = gr.State()
480
+ unqualified_A_state = gr.State()
481
+ data_subset_state = gr.State()
482
+
483
+ # Load specialty data
484
+ specialties_path = "specialties.json"
485
+ subspecialties_path = "subspecialties.json"
486
+
487
+ try:
488
+ with open(specialties_path, 'r') as f:
489
+ specialties_list = json.load(f)
490
+ with open(subspecialties_path, 'r') as f:
491
+ subspecialties_list = json.load(f)
492
+ except FileNotFoundError:
493
+ print(f"Error: Could not find specialty files at {specialties_path} or {subspecialties_path}. Please ensure these files exist.")
494
+ # Provide default empty lists or handle the error as appropriate
495
+ specialties_list = ["Error loading specialties"]
496
+ subspecialties_list = ["Error loading subspecialties"]
497
+ except json.JSONDecodeError:
498
+ print(f"Error: Could not parse JSON from specialty files.")
499
+ specialties_list = ["Error parsing specialties"]
500
+ subspecialties_list = ["Error parsing subspecialties"]
501
+
502
+ # Page -1: Page to link them to question submission form or evaluation portal
503
+ with gr.Column(visible=True, elem_id="page-1") as page_minus1:
504
+ gr.HTML("""
505
+ <div>
506
+ <h1>TxAgent Evaluation Portal</h1>
507
+ <p>Welcome to the TxAgent Evaluation Portal.</p>
508
+ </div>
509
+ """)
510
+ with gr.Row():
511
+ submit_questions_btn = gr.Button("Submit Questions for TxAgent Evaluation")
512
+ participate_eval_btn = gr.Button("Participate in TxAgent Evaluation")
513
+ gr.HTML(TxAgent_Project_Page_HTML)
514
+
515
+ # Define actions for the new buttons
516
+ # For the Google Form button, we'll use JavaScript to open a new tab.
517
+ # The URL for the Google Form should be replaced with the actual link.
518
+ google_form_url = "https://forms.gle/pYvyvEQQwS5gdupQA" # Replace with your actual Google Form link
519
+ submit_questions_btn.click(
520
+ fn=None,
521
+ inputs=None,
522
+ outputs=None,
523
+ js=f"() => {{ window.open('{google_form_url}', '_blank'); }}"
524
+ )
525
+
526
+ # Page 0: Welcome / Informational page.
527
+ with gr.Column(visible=False, elem_id="page0") as page0:
528
+ gr.Markdown("## Welcome to the TxAgent Evalution Study!")
529
+ gr.Markdown("Please read the following instructions and then enter your information to begin:")
530
+ # Existing informational markdown...
531
+ gr.Markdown("""
532
+ - Each session requires a minimum commitment of 5-10 minutes to complete one question.
533
+ - If you wish to evaluate multiple questions, you may do so; you will never be asked to re-evaluate questions you have already seen.
534
+ - When evaluating a question, you will be asked to compare the responses of two different models to the question and then rate each model's response on a scale of 1-5.
535
+ - You may use the Back and Next buttons at the bottom of each page to edit any of your responses before submitting.
536
+ - You may use the Instruction Page and Home Page buttons at the bottom of each page to return to this page or the home page. Your progress will be saved but not submitted.
537
+ - You must submit your answers to the current question before moving on to evaluate the next question.
538
+ - You may stop in between questions and return at a later time; however, you must submit your answers to the current question if you would like them saved.
539
+
540
+ By clicking 'Next' below, you will start the study, with your progress saved after submitting each question. If you have any other questions or concerns, please contact us directly. Thank you for your participation!
541
+ """)
542
+ gr.Markdown("## Please enter your information to get a question to evaluate. Please use the same email every time you log onto this evaluation portal, as we use your email to prevent showing repeat questions.")
543
+ name = gr.Textbox(label="Name (required)")
544
+ email = gr.Textbox(label="Email (required). Please use the same email every time you log onto this evaluation portal, as we use your email to prevent showing repeat questions.")
545
+ specialty_dd = gr.Dropdown(choices=specialties_list, label="Primary Medical Specialty (required). Go to https://www.abms.org/member-boards/specialty-subspecialty-certificates/ for categorization)", multiselect=True)
546
+ subspecialty_dd = gr.Dropdown(choices=subspecialties_list, label="Subspecialty (if applicable). Go to https://www.abms.org/member-boards/specialty-subspecialty-certificates/ for categorization)", multiselect=True)
547
+ npi_id = gr.Textbox(label="National Provider Identifier ID (optional). Got to https://npiregistry.cms.hhs.gov/search to search for your NPI ID. If you do not have an NPI ID, please leave this blank.")
548
+ years_exp_radio = gr.Radio(
549
+ choices=["0-2 years", "3-5 years", "6-10 years", "11-20 years", "20+ years", "Not Applicable"],
550
+ label="How many years have you been involved in clinical and/or research activities related to your biomedical area of expertise? (required)"
551
+ )
552
+ exp_explanation_tb = gr.Textbox(label="Please briefly explain your expertise/experience relevant to evaluating AI for clinical decision support (optional)")
553
+
554
+ page0_error_box = gr.Markdown("")
555
+ with gr.Row():
556
+ next_btn_0 = gr.Button("Next")
557
+ with gr.Row():
558
+ home_btn_0 = gr.Button("Home (your registration info will be saved)")
559
+
560
+
561
+ with Modal(visible=False) as eval_progress_modal:
562
+ eval_progress_text = gr.Markdown("You have X questions remaining.")
563
+ eval_progress_proceed_btn = gr.Button("OK, proceed to question evaluation")
564
+
565
+ # Page 1: Pairwise Comparison.
566
+ with gr.Column(visible=False) as page1:
567
+ gr.Markdown("## Part 1/2: Pairwise Comparison") #Make the number controlled by question indexing!
568
+ page1_prompt = gr.HTML()
569
+ with gr.Row():
570
+ # ADDED: Use gr.Chatbot to display the scrollable chat window for Response A.
571
+ with gr.Column():
572
+ gr.Markdown("**Model A Response:**") # Already bold label.
573
+ chat_a = gr.Chatbot(
574
+ value=[], # Placeholder for chat history
575
+ type="messages",
576
+ height=400,
577
+ label="Model A Response",
578
+ show_copy_button=False,
579
+ show_label=True,
580
+ render_markdown=True, # Required for markdown/HTML support in messages
581
+ avatar_images=None, # Optional: omit user/assistant icons
582
+ rtl=False
583
+ )
584
+ # ADDED: Use gr.Chatbot to display the scrollable chat window for Response B.
585
+ with gr.Column():
586
+ gr.Markdown("**Model B Response:**")
587
+ chat_b = gr.Chatbot(
588
+ value=[],
589
+ type="messages",
590
+ height=400,
591
+ label="Model B Response",
592
+ show_copy_button=False,
593
+ show_label=True,
594
+ render_markdown=True, # Required for markdown/HTML support in messages
595
+ avatar_images=None, # Optional: omit user/assistant icons
596
+ rtl=False
597
+ )
598
+ gr.Markdown("<br><br>")
599
+ gr.Markdown("### For each criterion, select which response did better:")
600
+ comparison_reasons_inputs = [] # ADDED: list to store the free-text inputs
601
+ pairwise_inputs = []
602
+ for crit in criteria_for_comparison:
603
+ with gr.Row():
604
+ gr.Markdown(crit['text'])
605
+ radio = gr.Radio(
606
+ choices=[
607
+ "👈 Model A", # A
608
+ "👉 Model B", # B
609
+ "🤝 Tie", # tie
610
+ "👎 Neither model did well" # neither
611
+ ],
612
+ label="Which is better?"
613
+ )
614
+ pairwise_inputs.append(radio)
615
+ # ADDED: free text under each comparison
616
+ text_input = gr.Textbox(label=f"Reasons for your selection (optional)")
617
+ comparison_reasons_inputs.append(text_input)
618
+
619
+ page1_error_box = gr.Markdown("") # ADDED: display validation errors
620
+ with gr.Row():
621
+ back_btn_0 = gr.Button("Back")
622
+ next_btn_1 = gr.Button("Next: Rate Responses")
623
+
624
+ with gr.Row():
625
+ home_btn_1 = gr.Button("Home Page (your progress on this question will be saved but not submitted)") # ADDED: Home button on page11
626
+
627
+ # Page 2: Combined Rating Page for both responses.
628
+ with gr.Column(visible=False) as page2:
629
+ gr.Markdown("## Part 2/2: Rate Model Responses")
630
+ # ### EDIT: Show a highlighted prompt as on previous pages.
631
+ page2_prompt = gr.HTML()
632
+ # ### EDIT: Display both responses side-by-side using Chatbot windows.
633
+ with gr.Row():
634
+ with gr.Column():
635
+ gr.Markdown("**Model A Response:**")
636
+ chat_a_rating = gr.Chatbot(
637
+ value=[],
638
+ type="messages",
639
+ height=400,
640
+ label="Model A Response",
641
+ show_copy_button=False,
642
+ render_markdown=True
643
+ )
644
+ with gr.Column():
645
+ gr.Markdown("**Model B Response:**")
646
+ chat_b_rating = gr.Chatbot(
647
+ value=[],
648
+ type="messages",
649
+ height=400,
650
+ label="Model B Response",
651
+ show_copy_button=False,
652
+ render_markdown=True
653
+ )
654
+ gr.Markdown("<br><br>")
655
+ gr.Markdown("### For each criterion, select your ratings for each model response:")
656
+ # ### EDIT: For each criterion, create a row with two multiple-choice sets (left: Response A, right: Response B) separated by a border.
657
+ ratings_A = [] # to store the radio components for response A
658
+ ratings_B = [] # to store the radio components for response B
659
+
660
+ def restrict_choices(pairwise_list, index, score_a, score_b):
661
+ """
662
+ Returns (update_for_A, update_for_B).
663
+ Enforces rating constraints based on the pairwise choice for the given criterion index.
664
+ """
665
+ # Get the specific pairwise choice for this criterion using the index
666
+ # Add error handling in case the state/list is not ready or index is wrong
667
+ if not pairwise_list or index >= len(pairwise_list):
668
+ pairwise_choice = None
669
+ else:
670
+ pairwise_choice = pairwise_list[index]
671
+
672
+ base = ["1","2","3","4","5","Unable to Judge"]
673
+ # Default: no restrictions unless explicitly set
674
+ upd_A = gr.update(choices=base)
675
+ upd_B = gr.update(choices=base)
676
+
677
+ # Skip if no meaningful pairwise choice or either score is "Unable to Judge"
678
+ if pairwise_choice is None or pairwise_choice == "👎 Neither model did well" or (score_a is None and score_b is None):
679
+ # If one score is UJ but the other isn't, AND it's a Tie, we might still want to restrict the non-UJ one later?
680
+ # For now, keep it simple: if either is UJ or choice is Neither/None, don't restrict.
681
+ return upd_A, upd_B
682
+
683
+ # Helper to parse int safely
684
+ def to_int(x):
685
+ try: return int(x)
686
+ except (ValueError, TypeError): return None
687
+
688
+ a_int = to_int(score_a)
689
+ b_int = to_int(score_b)
690
+
691
+ # --- Apply Restrictions ---
692
+ if pairwise_choice == "👈 Model A":
693
+ # B must be ≤ A (if A is numeric)
694
+ if a_int is not None: #it is None if unable to judge
695
+ allowed_b_choices = [str(i) for i in range(1, a_int + 1)] + ["Unable to Judge"]
696
+ current_b = score_b if score_b in allowed_b_choices else None # Keep current valid choice
697
+ upd_B = gr.update(choices=allowed_b_choices, value=current_b)
698
+ # If A is UJ or non-numeric, B is unrestricted by this rule
699
+ # else: upd_B remains gr.update(choices=base)
700
+ if b_int is not None:
701
+ # A must be >= B (if B is numeric)
702
+ allowed_a_choices = [str(i) for i in range(b_int, 6)] + ["Unable to Judge"]
703
+ current_a = score_a if score_a in allowed_a_choices else None # Keep current valid choice
704
+ upd_A = gr.update(choices=allowed_a_choices, value=current_a)
705
+ # If B is UJ or non-numeric, A is unrestricted by this rule
706
+ # else: upd_A remains gr.update(choices=base)
707
+
708
+ elif pairwise_choice == "👉 Model B":
709
+ # A must be ≤ B (if B is numeric)
710
+ if b_int is not None:
711
+ allowed_a_choices = [str(i) for i in range(1, b_int + 1)] + ["Unable to Judge"]
712
+ current_a = score_a if score_a in allowed_a_choices else None # Keep current valid choice
713
+ upd_A = gr.update(choices=allowed_a_choices, value=current_a)
714
+ # If B is UJ or non-numeric, A is unrestricted by this rule
715
+ # else: upd_A remains gr.update(choices=base)
716
+ if a_int is not None:
717
+ # B must be >= A (if A is numeric)
718
+ allowed_b_choices = [str(i) for i in range(a_int, 6)] + ["Unable to Judge"]
719
+ current_b = score_b if score_b in allowed_b_choices else None # Keep current valid choice
720
+ upd_B = gr.update(choices=allowed_b_choices, value=current_b)
721
+ # If A is UJ or non-numeric, B is unrestricted by this rule
722
+ # else: upd_B remains gr.update(choices=base)
723
+
724
+ elif pairwise_choice == "🤝 Tie":
725
+ # If both are numeric, they must match. Enforce based on the one that *just changed*.
726
+ # If one changes to numeric, force the other (if also numeric) to match.
727
+ # If one changes to UJ, the other is unrestricted.
728
+ if a_int is not None:
729
+ upd_B = gr.update(choices=[score_a])
730
+ elif score_a == "Unable to Judge":
731
+ upd_B = gr.update(choices=["Unable to Judge"])
732
+ if b_int is not None:
733
+ upd_A = gr.update(choices=[score_b])
734
+ elif score_b == "Unable to Judge":
735
+ upd_A = gr.update(choices=["Unable to Judge"])
736
+
737
+ return upd_A, upd_B
738
+
739
+ def clear_selection():
740
+ return None, None
741
+
742
+ pairwise_results_for_display = [gr.Markdown(render=False) for _ in range(len(criteria))]
743
+ indices_for_change = []
744
+ for i, crit in enumerate(criteria):
745
+ index_component = gr.Number(value=i, visible=False, interactive=False)
746
+ indices_for_change.append(index_component)
747
+
748
+ with gr.Column(elem_id="centered-column"):
749
+ gr.Markdown(f'<div style="text-align: left;">{crit["text"][0]}</div>')
750
+ gr.Markdown(f'<div style="text-align: left;">{crit["text"][1]}</div>')
751
+ pairwise_results_for_display[i].render()
752
+ with gr.Row():
753
+ with gr.Column(scale=1):
754
+ rating_a = gr.Radio(choices=["1", "2", "3", "4", "5", "Unable to Judge"],
755
+ label=f"Score for Response A - {crit['label']}",
756
+ interactive=True)
757
+ with gr.Column(scale=1):
758
+ rating_b = gr.Radio(choices=["1", "2", "3", "4", "5", "Unable to Judge"],
759
+ label=f"Score for Response B - {crit['label']}",
760
+ interactive=True)
761
+ with gr.Row():
762
+ clear_btn = gr.Button("Clear Selection", size="sm")
763
+ clear_btn.click(fn=clear_selection, outputs=[rating_a,rating_b])
764
+
765
+ # wire each to re‐restrict the other on change
766
+ rating_a.change(
767
+ fn=restrict_choices,
768
+ inputs=[ pairwise_state, index_component, rating_a, rating_b ],
769
+ outputs=[ rating_a, rating_b ]
770
+ )
771
+ rating_b.change(
772
+ fn=restrict_choices,
773
+ inputs=[ pairwise_state, index_component, rating_a, rating_b ],
774
+ outputs=[ rating_a, rating_b ]
775
+ )
776
+ ratings_A.append(rating_a)
777
+ ratings_B.append(rating_b)
778
+ with gr.Row():
779
+ back_btn_2 = gr.Button("Back")
780
+ submit_btn = gr.Button("Submit (Note: Once submitted, you cannot edit your responses)", elem_id="submit_btn")
781
+
782
+ with gr.Row():
783
+ home_btn_2 = gr.Button("Home Page (your progress on this question will be saved but not submitted)")
784
+
785
+ result_text = gr.Textbox(label="Validation Result")
786
+
787
+ # Final Page: Thank you message.
788
+ with gr.Column(visible=False, elem_id="final_page") as final_page:
789
+ gr.Markdown("## You have no questions left to evaluate. Thank you for your participation!")
790
+ eval_again_btn = gr.Button("Evaluate Another Question")
791
+
792
+ # Error Modal: For displaying validation errors.
793
+ with Modal("Error", visible=False, elem_id="error_modal") as error_modal:
794
+ error_message_box = gr.Markdown()
795
+ ok_btn = gr.Button("OK")
796
+ # Clicking OK hides the modal.
797
+ ok_btn.click(lambda: gr.update(visible=False), None, error_modal)
798
+
799
+ # Confirmation Modal: Ask for final submission confirmation.
800
+ with Modal("Confirm Submission", visible=False, elem_id="confirm_modal") as confirm_modal:
801
+ gr.Markdown("Are you sure you want to submit? Once submitted, you cannot edit your responses.")
802
+ with gr.Row():
803
+ yes_btn = gr.Button("Yes, please submit")
804
+ cancel_btn = gr.Button("Cancel")
805
+
806
+ # --- Define Callback Functions for Confirmation Flow ---
807
+ def build_row_dict(data_subset_state, user_info, pairwise, comparisons_reasons, *args):
808
+ num_criteria = len(criteria)
809
+ ratings_A_vals = list(args[:num_criteria])
810
+ ratings_B_vals = list(args[num_criteria:])
811
+
812
+ prompt_text = data_subset_state['question']
813
+ response_A_model = data_subset_state['models'][0]['model']
814
+ response_B_model = data_subset_state['models'][1]['model']
815
+
816
+ timestamp = datetime.datetime.now().isoformat()
817
+ row = {
818
+ "Timestamp": timestamp,
819
+ "Name": user_info[0],
820
+ "Email": user_info[1],
821
+ "Specialty": str(user_info[2]),
822
+ "Subspecialty": str(user_info[3]),
823
+ "Years of Experience": user_info[4],
824
+ "Experience Explanation": user_info[5],
825
+ "NPI ID": user_info[6],
826
+ "Question ID": user_info[7],
827
+ "Prompt": prompt_text,
828
+ "ResponseA_Model": response_A_model,
829
+ "ResponseB_Model": response_B_model,
830
+ }
831
+
832
+ pairwise = [mapping.get(val, val) for val in pairwise]
833
+ for i, crit in enumerate(criteria):
834
+ label = crit['label']
835
+ row[f"Criterion_{label} Comparison: Which is Better?"] = pairwise[i]
836
+ row[f"Criterion_{label} Comments"] = comparisons_reasons[i]
837
+ row[f"ScoreA_{label}"] = ratings_A_vals[i]
838
+ row[f"ScoreB_{label}"] = ratings_B_vals[i]
839
+
840
+ return row
841
+
842
+ # def final_submit(data_subset_state, user_info, pairwise, comparisons_reasons, *args):
843
+
844
+ # row_dict = build_row_dict(data_subset_state, user_info, pairwise, comparisons_reasons, *args)
845
+ # append_to_sheet(user_data=None, custom_row_dict=row_dict, custom_sheet_name=str(TXAGENT_RESULTS_SHEET_BASE_NAME), add_header_when_create_sheet=True)
846
+
847
+ # return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
848
+
849
+ def final_submit(data_subset_state, user_info, pairwise, comparisons_reasons, *args):
850
+ # --- Part 1: Submit the current results (Existing Logic) ---
851
+ row_dict = build_row_dict(data_subset_state, user_info, pairwise, comparisons_reasons, *args)
852
+ append_to_sheet(user_data=None, custom_row_dict=row_dict, custom_sheet_name=str(TXAGENT_RESULTS_SHEET_BASE_NAME), add_header_when_create_sheet=True)
853
+
854
+ # --- Part 2: Recalculate remaining questions (Existing Logic + Modified Error Handling) ---
855
+ # try:
856
+
857
+ # --- Re-fetch data and filter questions (Same logic as before) ---
858
+ evaluator_directory = CROWDSOURCING_DATA_DIRECTORY
859
+ all_files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", revision="main")
860
+ disease_specialty_map = hf_hub_download(repo_id=REPO_ID, filename=DISEASE_SPECIALTY_MAP_FILENAME, repo_type="dataset", revision="main")
861
+ with open(disease_specialty_map, 'r') as f: disease_map_data = json.load(f)
862
+
863
+ _, email, specialty, subspecialty, _, _, _, _ = user_info
864
+ user_specialties = set(specialty if isinstance(specialty, list) else ([specialty] if specialty else []))
865
+ user_subspecialties = set(subspecialty if isinstance(subspecialty, list) else ([subspecialty] if subspecialty else []))
866
+ user_all_specs = user_specialties.union(user_subspecialties)
867
+
868
+ full_question_ids_list, data_by_filename = get_evaluator_questions(email, disease_map_data, user_all_specs, all_files, evaluator_directory)
869
+ remaining_count = len(full_question_ids_list)
870
+
871
+ # --- Part 3: Determine UI updates based on remaining count ---
872
+ if remaining_count == 0:
873
+ # Success with NO remaining questions
874
+ return (
875
+ gr.update(visible=False), # page0 (Hide)
876
+ gr.update(visible=False), # page2 (Hide)
877
+ gr.update(visible=False), # confirm_modal
878
+ gr.update(visible=False),
879
+ "",
880
+ gr.update(visible=True), # final_page (Show)
881
+ "",
882
+ None,
883
+ None,
884
+ None,
885
+ None
886
+ )
887
+
888
+ full_question_ids_list = sorted(full_question_ids_list, key=lambda x: str(x[0])+str(x[1]))
889
+ #selected question is the first element
890
+ q_id, other_model_name = full_question_ids_list[0]
891
+
892
+ #Constructing question_for_eval, the question to evaluate this round
893
+ txagent_matched_entry = next(
894
+ (entry for entry in data_by_filename['txagent'] if entry.get("question_ID") == q_id),
895
+ None
896
+ )
897
+ other_model_matched_entry = next(
898
+ (entry for entry in data_by_filename[other_model_name] if entry.get("question_ID") == q_id),
899
+ None
900
+ )
901
+
902
+ models_list = [
903
+ {
904
+ "model": "txagent",
905
+ "reasoning_trace": txagent_matched_entry.get("solution")
906
+ },
907
+ {
908
+ "model": other_model_name,
909
+ "reasoning_trace": other_model_matched_entry.get("solution")
910
+ }
911
+ ]
912
+ random.shuffle(models_list)
913
+
914
+ question_for_eval = {
915
+ "question": txagent_matched_entry.get("question"),
916
+ "question_ID": q_id,
917
+ "models": models_list,
918
+ }
919
+
920
+ chat_A_value = format_chat(question_for_eval['models'][0]['reasoning_trace'], tool_database_labels)
921
+ chat_B_value = format_chat(question_for_eval['models'][1]['reasoning_trace'], tool_database_labels)
922
+ prompt_text = question_for_eval['question']
923
+
924
+ # Construct the question-specific elements of the pairwise rating page (page 1)
925
+ page1_prompt = gr.HTML(f'<div style="background-color: #FFEFD5; border: 2px solid #FF8C00; padding: 10px; border-radius: 5px; color: black;"><strong style="color: black;">Prompt:</strong> {prompt_text}</div>')
926
+ chat_a = gr.Chatbot(
927
+ value=chat_A_value,
928
+ type="messages",
929
+ height=400,
930
+ label="Model A Response",
931
+ show_copy_button=False,
932
+ show_label=True,
933
+ render_markdown=True, # Required for markdown/HTML support in messages
934
+ avatar_images=None, # Optional: omit user/assistant icons
935
+ rtl=False
936
+ )
937
+ chat_b = gr.Chatbot(
938
+ value=chat_B_value,
939
+ type="messages",
940
+ height=400,
941
+ label="Model B Response",
942
+ show_copy_button=False,
943
+ show_label=True,
944
+ render_markdown=True, # Required for markdown/HTML support in messages
945
+ avatar_images=None, # Optional: omit user/assistant icons
946
+ rtl=False
947
+ )
948
+
949
+ # Success with remaining questions
950
+ return (
951
+ gr.update(visible=False), # page0 (Hide)
952
+ gr.update(visible=False), # page2 (Hide)
953
+ gr.update(visible=False), # confirm_modal (Hide)
954
+ gr.update(visible=True), # eval_progress_modal (Show)
955
+ f"Submission successful! There are more questions to evaluate. You may exit the page and return later if you wish.",#f"Submission successful! You have {remaining_count} question(s) remaining to evaluate. You may exit the page and return later if you wish.", # eval_progress_text
956
+ gr.update(visible=False), # final_page (Hide)
957
+ "",
958
+ chat_a,
959
+ chat_b,
960
+ page1_prompt,
961
+ question_for_eval)
962
+
963
+ # except Exception as e:
964
+ # error_message = f"Your submission was saved, but an error occurred while checking for remaining questions: {e}. Please try starting the process again by entering your details. If the problem persists, contact the administrator."
965
+ # print(f"Error during recalculation in final_submit: {e}") # Keep logging for debugging
966
+ # # *** MODIFIED RETURN ***: Error during recalculation
967
+ # return (
968
+ # gr.update(visible=True), # page0 (Show) - Send user back to start
969
+ # gr.update(visible=False), # page2 (Hide)
970
+ # gr.update(visible=False), # confirm_modal (Hide)
971
+ # gr.update(visible=False), # eval_progress_modal (Hide)
972
+ # "", # eval_progress_text (Clear)
973
+ # gr.update(visible=False), # final_page (Hide)
974
+ # error_message # page0_error_box (Update with error)
975
+ # )
976
+
977
+ def cancel_submission():
978
+ # Cancel final submission: just hide the confirmation modal.
979
+ return gr.update(visible=False)
980
+
981
+ def reset_everything_except_user_info():
982
+
983
+ # 3) Reset all pairwise radios & textboxes
984
+ reset_pairwise_radios = [gr.update(value=None) for i in range(len(criteria))]
985
+ reset_pairwise_reasoning_texts = [gr.update(value=None) for i in range(len(criteria))]
986
+
987
+ # 4) Reset all rating radios
988
+ reset_ratings_A = [gr.update(value=None) for i in range(len(criteria))]
989
+ reset_ratings_B = [gr.update(value=None) for i in range(len(criteria))]
990
+
991
+ return (
992
+ # pages
993
+ gr.update(visible=True), # page0
994
+ gr.update(visible=False), # final_page
995
+
996
+ # states
997
+ # gr.update(value=None), # user_info_state
998
+ gr.update(value=None), # pairwise_state
999
+ gr.update(value=None), # scores_A_state
1000
+ gr.update(value=None), # comparison_reasons
1001
+ gr.update(value=None), # unqualified_A_state
1002
+ # gr.update(value=None), # data_subset_state
1003
+
1004
+ #page0 elements that need to be reset
1005
+ gr.update(value=""), #page0_error_box
1006
+
1007
+ # page1 elements that need to be reset
1008
+ # gr.update(value=""), #page1_prompt
1009
+ # gr.update(value=[]), #chat_a
1010
+ # gr.update(value=[]), #chat_b
1011
+ gr.update(value=""), #page1_error_box
1012
+
1013
+ # page2 elements that need to be reset
1014
+ gr.update(value=""), #page2_prompt
1015
+ gr.update(value=[]), #chat_a_rating
1016
+ gr.update(value=[]), #chat_b_rating
1017
+ gr.update(value=""), #result_text
1018
+
1019
+ #lists of gradio elements that need to be unrolled
1020
+ *reset_pairwise_radios,
1021
+ *reset_pairwise_reasoning_texts,
1022
+ *reset_ratings_A,
1023
+ *reset_ratings_B
1024
+ )
1025
+
1026
+ # --- Define Transitions Between Pages ---
1027
+
1028
+
1029
+ # For the "Participate in Evaluation" button, transition to page0
1030
+ participate_eval_btn.click(
1031
+ fn=go_to_page0_from_minus1,
1032
+ inputs=None,
1033
+ outputs=[page_minus1, page0]
1034
+ )
1035
+
1036
+
1037
+ # Transition from Page 0 (Welcome) to Page 1.
1038
+ next_btn_0.click(
1039
+ fn=go_to_eval_progress_modal,
1040
+ inputs=[name, email, specialty_dd, subspecialty_dd, years_exp_radio, exp_explanation_tb, npi_id],
1041
+ outputs=[page0, page1, user_info_state, page0_error_box, chat_a, chat_b, page1_prompt, data_subset_state,eval_progress_modal,eval_progress_text],
1042
+ scroll_to_output=True
1043
+ )
1044
+
1045
+ eval_progress_proceed_btn.click(
1046
+ fn=go_to_page1,
1047
+ inputs=None,
1048
+ outputs=[eval_progress_modal, page0, page1],
1049
+ scroll_to_output=True
1050
+ )
1051
+
1052
+ #Home page buttons to simply shown page-1
1053
+ home_btn_0.click(lambda: (gr.update(visible=True), gr.update(visible=False)), None, [page_minus1, page0])
1054
+ home_btn_1.click(lambda: (gr.update(visible=True), gr.update(visible=False)), None, [page_minus1, page1])
1055
+ home_btn_2.click(lambda: (gr.update(visible=True), gr.update(visible=False)), None, [page_minus1, page2])
1056
+
1057
+ # Transition from Page 1 to Page 0 (Back button).
1058
+ back_btn_0.click(
1059
+ fn=lambda: (gr.update(visible=True), gr.update(visible=False)),
1060
+ inputs=None,
1061
+ outputs=[page0, page1]
1062
+ )
1063
+
1064
+ # Transition from Page 1 (Pairwise) to the combined Rating Page (Page 2).
1065
+ next_btn_1.click(
1066
+ fn=go_to_page2, # ### EDIT: Rename or update the function to simply pass the pairwise inputs if needed.
1067
+ inputs=[data_subset_state,*pairwise_inputs,*comparison_reasons_inputs],
1068
+ outputs=[page1, page2, pairwise_state, comparison_reasons, page1_error_box, chat_a_rating, chat_b_rating, page2_prompt, *pairwise_results_for_display],
1069
+ scroll_to_output=True
1070
+ )
1071
+
1072
+ # Transition from Rating Page (Page 2) back to Pairwise page.
1073
+ back_btn_2.click(
1074
+ fn=lambda: (gr.update(visible=True), gr.update(visible=False)),
1075
+ inputs=None,
1076
+ outputs=[page1, page2],
1077
+ scroll_to_output=True
1078
+ )
1079
+
1080
+ # --- Submission: Validate the Ratings and then Process the Result ---
1081
+ def process_result(result):
1082
+ # If validation passed, show the confirmation modal and proceed.
1083
+ if result == "No errors in responses; feel free to submit!":
1084
+ return (
1085
+ gr.update(), # Show page 3
1086
+ gr.update(), # Hide final page
1087
+ gr.update(visible=True), # Show confirmation modal
1088
+ gr.update(visible=False), # Hide error modal
1089
+ gr.update(value="") # EDIT: Clear the error_message_box
1090
+ )
1091
+ else:
1092
+ # If validation fails, show the error modal and display the error in error_message_box.
1093
+ return (
1094
+ gr.update(), # Keep page3 as is
1095
+ gr.update(), # Keep final page unchanged
1096
+ gr.update(visible=False), # Hide confirmation modal
1097
+ gr.update(visible=True), # Show error modal
1098
+ gr.update(value=result) # EDIT: Update error_message_box with the validation error
1099
+ )
1100
+
1101
+ # ### EDIT: Update the submission callback to use the new radio inputs.
1102
+ submit_btn.click(
1103
+ fn=validate_ratings,
1104
+ inputs=[pairwise_state, *ratings_A, *ratings_B],
1105
+ outputs=[error_message_box, result_text]
1106
+ ).then(
1107
+ fn=process_result,
1108
+ inputs=error_message_box,
1109
+ outputs=[page2, final_page, confirm_modal, error_modal, error_message_box],
1110
+ scroll_to_output=True
1111
+ )
1112
+
1113
+ # Finalize submission if user confirms.
1114
+ # yes_btn.click(
1115
+ # fn=final_submit,
1116
+ # inputs=[data_subset_state, user_info_state, pairwise_state, comparison_reasons, *ratings_A, *ratings_B],
1117
+ # outputs=[page2, final_page, confirm_modal]
1118
+ # )
1119
+ question_submission_event = yes_btn.click(
1120
+ fn=final_submit,
1121
+ inputs=[data_subset_state, user_info_state, pairwise_state, comparison_reasons, *ratings_A, *ratings_B],
1122
+ outputs=[
1123
+ page0, # Controlled by final_submit return value 1
1124
+ page2, # Controlled by final_submit return value 2
1125
+ confirm_modal, # Controlled by final_submit return value 3
1126
+ eval_progress_modal, # Controlled by final_submit return value 4
1127
+ eval_progress_text, # Controlled by final_submit return value 5
1128
+ final_page, # Controlled by final_submit return value 6
1129
+ page0_error_box,
1130
+ chat_a,
1131
+ chat_b,
1132
+ page1_prompt,
1133
+ data_subset_state
1134
+ ],
1135
+ scroll_to_output=True
1136
+ )
1137
+
1138
+ # Cancel final submission.
1139
+ cancel_btn.click(
1140
+ fn=cancel_submission,
1141
+ inputs=None,
1142
+ outputs=confirm_modal
1143
+ )
1144
+
1145
+ # Reset everything and evaluate another question button
1146
+ question_submission_event.then(
1147
+ fn=reset_everything_except_user_info,
1148
+ inputs=[],
1149
+ outputs=[
1150
+ # pages
1151
+ page0,
1152
+ final_page,
1153
+
1154
+ # states
1155
+ # user_info_state,
1156
+ pairwise_state,
1157
+ scores_A_state,
1158
+ comparison_reasons,
1159
+ unqualified_A_state,
1160
+ # data_subset_state,
1161
+
1162
+ #page0 elements that need to be reset
1163
+ page0_error_box,
1164
+
1165
+ # # page1 elements that need to be reset
1166
+ # page1_prompt,
1167
+ # chat_a,
1168
+ # chat_b,
1169
+ page1_error_box,
1170
+
1171
+ # page2 elements that need to be reset
1172
+ page2_prompt,
1173
+ chat_a_rating,
1174
+ chat_b_rating,
1175
+ result_text,
1176
+
1177
+ #lists of gradio elements that need to be unrolled
1178
+ *pairwise_inputs,
1179
+ *comparison_reasons_inputs,
1180
+ *ratings_A,
1181
+ *ratings_B
1182
+ ]
1183
+ )
1184
+
1185
+ demo.launch(share=True, allowed_paths = ["."])
utils.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ # Imports required for Google Sheets integration
3
+ import gspread
4
+ import random
5
+ import time
6
+ import functools
7
+ from gspread.exceptions import SpreadsheetNotFound, APIError
8
+ from oauth2client.service_account import ServiceAccountCredentials
9
+ import pandas as pd
10
+ import json
11
+ import gradio as gr
12
+ import os
13
+
14
+ GSERVICE_ACCOUNT_INFO = {
15
+ "type": "service_account",
16
+ "project_id": "txagent",
17
+ "private_key_id": "cc1a12e427917244a93faf6f19e72b589a685e65",
18
+ "private_key": None,
19
+ "client_email": "shanghua@txagent.iam.gserviceaccount.com",
20
+ "client_id": "108950722202634464257",
21
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
22
+ "token_uri": "https://oauth2.googleapis.com/token",
23
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
24
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/shanghua%40txagent.iam.gserviceaccount.com",
25
+ "universe_domain": "googleapis.com"
26
+ }
27
+ GSHEET_NAME = "TxAgent_data_collection"
28
+
29
+ GSheet_API_KEY = os.environ.get("GSheets_Shanghua_PrivateKey")
30
+ if GSheet_API_KEY is None:
31
+ print("GSheet_API_KEY not found in environment variables. Please set it.")
32
+ else:
33
+ GSheet_API_KEY = GSheet_API_KEY.replace("\\n", "\n")
34
+ GSERVICE_ACCOUNT_INFO["private_key"] = GSheet_API_KEY
35
+
36
+ #Exponential backoff retry decorator
37
+ def exponential_backoff_gspread(max_retries=30, max_backoff_sec=64, base_delay_sec=1, target_exception=APIError):
38
+ """
39
+ Decorator to implement exponential backoff for gspread API calls.
40
+
41
+ Retries a function call if it raises a specific exception (defaults to APIError)
42
+ that matches the Google Sheets API rate limit error (HTTP 429).
43
+
44
+ Args:
45
+ max_retries (int): Maximum number of retry attempts.
46
+ max_backoff_sec (int): Maximum delay between retries in seconds.
47
+ base_delay_sec (int): Initial delay in seconds for the first retry.
48
+ target_exception (Exception): The specific exception type to catch.
49
+ """
50
+ def decorator(func):
51
+ @functools.wraps(func)
52
+ def wrapper(*args, **kwargs):
53
+ retries = 0
54
+ while True: # Loop indefinitely until success or max retries exceeded
55
+ try:
56
+ # Attempt to execute the wrapped function
57
+ return func(*args, **kwargs)
58
+ except target_exception as e:
59
+ # Check if the error is the specific 429 Quota Exceeded error
60
+ # We parse the string representation as gspread's APIError includes the status code there.
61
+ error_message = str(e)
62
+ is_rate_limit_error = "[429]" in error_message and (
63
+ "Quota exceeded" in error_message or "Too Many Requests" in error_message
64
+ )
65
+
66
+ if is_rate_limit_error:
67
+ retries += 1
68
+ if retries > max_retries:
69
+ print(f"Max retries ({max_retries}) exceeded for {func.__name__}. Last error: {e}")
70
+ raise e # Re-raise the last exception after exhausting retries
71
+
72
+ # Calculate exponential backoff delay with random jitter (0-1 second)
73
+ backoff_delay = min(max_backoff_sec, base_delay_sec * (2 ** (retries - 1)) + random.uniform(0, 1))
74
+
75
+ print(
76
+ f"Rate limit hit for {func.__name__} (Attempt {retries}/{max_retries}). "
77
+ f"Retrying in {backoff_delay:.2f} seconds. Error: {e}"
78
+ )
79
+ time.sleep(backoff_delay)
80
+ else:
81
+ # If it's a different kind of APIError (e.g., 403 Forbidden, 404 Not Found), re-raise immediately.
82
+ print(f"Non-rate-limit APIError encountered in {func.__name__}: {e}")
83
+ raise e
84
+ except Exception as e:
85
+ # Catch any other unexpected exceptions during the function execution
86
+ print(f"An unexpected error occurred in {func.__name__}: {e}")
87
+ raise e # Re-raise unexpected errors
88
+ return wrapper
89
+ return decorator
90
+
91
+ #2) Initialize Google Sheets client
92
+ # Define the scopes
93
+ scope = [
94
+ "https://spreadsheets.google.com/feeds",
95
+ "https://www.googleapis.com/auth/drive",
96
+ ]
97
+
98
+ # Authenticate immediately on import
99
+ creds = ServiceAccountCredentials.from_json_keyfile_dict(GSERVICE_ACCOUNT_INFO, scope)
100
+ client = gspread.authorize(creds)
101
+
102
+ @exponential_backoff_gspread(max_retries=30, max_backoff_sec=64)
103
+ def read_sheet_to_df(custom_sheet_name=None, sheet_index=0):
104
+ """
105
+ Read all data from a Google Sheet into a pandas DataFrame.
106
+
107
+ Parameters:
108
+ custom_sheet_name (str): The name of the Google Sheet to open. If None, uses GSHEET_NAME.
109
+ sheet_index (int): Index of the worksheet within the spreadsheet (default is 0, the first sheet).
110
+
111
+ Returns:
112
+ pandas.DataFrame: DataFrame containing the sheet data, with the first row used as headers.
113
+ """
114
+
115
+ # Determine which sheet name to use
116
+ if custom_sheet_name is None:
117
+ custom_sheet_name = GSHEET_NAME
118
+
119
+ # Open the spreadsheet
120
+ try:
121
+ spreadsheet = client.open(custom_sheet_name)
122
+ except gspread.SpreadsheetNotFound:
123
+ return None
124
+
125
+ # Select the desired worksheet
126
+ try:
127
+ worksheet = spreadsheet.get_worksheet(sheet_index)
128
+ except IndexError:
129
+ return None
130
+
131
+ # Fetch all data: first row as header, remaining as records
132
+ data = worksheet.get_all_records()
133
+
134
+ # Convert to DataFrame
135
+ df = pd.DataFrame(data)
136
+
137
+ return df
138
+
139
+ @exponential_backoff_gspread(max_retries=30, max_backoff_sec=64)
140
+ def append_to_sheet(user_data=None, custom_row_dict=None, custom_sheet_name=None, add_header_when_create_sheet=False):
141
+ """
142
+ Append a new row to a Google Sheet. If 'custom_row' is provided, append that row.
143
+ Otherwise, append a default row constructed from the provided user_data.
144
+ """
145
+ if custom_sheet_name is None:
146
+ custom_sheet_name = GSHEET_NAME
147
+
148
+ try:
149
+ # Try to open the spreadsheet by name
150
+ spreadsheet = client.open(custom_sheet_name)
151
+ is_new = False
152
+ except SpreadsheetNotFound:
153
+ # If it doesn't exist, create it
154
+ spreadsheet = client.create(custom_sheet_name)
155
+ # Optionally, share the new spreadsheet with designated emails
156
+ spreadsheet.share('shanghuagao@gmail.com', perm_type='user', role='writer')
157
+ spreadsheet.share('rzhu@college.harvard.edu', perm_type='user', role='writer')
158
+ is_new = True
159
+
160
+ print("Spreadsheet ID:", spreadsheet.id)
161
+ # Access the first worksheet
162
+ sheet = spreadsheet.sheet1
163
+
164
+ if is_new and add_header_when_create_sheet:
165
+ # headers come from the keys of our row dict
166
+ if custom_row_dict is not None:
167
+ headers = list(custom_row_dict.keys())
168
+ else:
169
+ headers = list(user_data.keys())
170
+ sheet.append_row(headers)
171
+
172
+ if custom_row_dict is not None:
173
+ custom_row = [custom_row_dict.get(header) for header in list(custom_row_dict.keys())]
174
+ else:
175
+ # Construct the default row with a timestamp and user_data fields
176
+ custom_row = [str(datetime.datetime.now()), user_data["question"], user_data["final_answer"], user_data["trace"]]
177
+
178
+ # Append the custom or default row to the sheet
179
+ sheet.append_row(custom_row)
180
+
181
+ def format_chat(response, tool_database_labels):
182
+ chat_history = []
183
+ # Keep track of the last assistant message's tool_calls
184
+ last_tool_calls = []
185
+
186
+ for msg in response:
187
+ if msg["role"] == "assistant":
188
+ content = msg.get("content", "")
189
+ # Extract tool_calls from this assistant message (if any)
190
+ last_tool_calls = json.loads(msg.get("tool_calls", "[]"))
191
+ # Emit the assistant's main message
192
+ chat_history.append(
193
+ gr.ChatMessage(role="assistant", content=content)
194
+ )
195
+
196
+ elif msg["role"] == "tool":
197
+ # For each tool response, we pair it with the corresponding call
198
+ for i, tool_call in enumerate(last_tool_calls):
199
+ name = tool_call.get("name", "")
200
+ args = tool_call.get("arguments", {})
201
+
202
+ # Determine icon + title
203
+ database_label = ""
204
+ if name == "Tool_RAG":
205
+ title = "🧰 Tool RAG"
206
+ else:
207
+ title = f"🛠️ {name}"
208
+ for db_label, tool_list in tool_database_labels.items():
209
+ if name in tool_list:
210
+ title = f"🛠️ {name} (**retrieves** {db_label})"
211
+ database_label = " (" + db_label + ")"
212
+ break
213
+
214
+ # Parse and pretty-print the tool response content
215
+ raw = msg.get("content", "")
216
+ try:
217
+ parsed = json.loads(raw)
218
+ pretty = json.dumps(parsed)
219
+ except json.JSONDecodeError:
220
+ pretty = raw
221
+
222
+ # Add as a single ChatMessage with metadata.title and metadata.log.
223
+ # Display the arguments as the first part of the content, clearly separated from the response,
224
+ # and display the tool response content as contiguous text.
225
+ chat_history.append(
226
+ gr.ChatMessage(
227
+ role="assistant",
228
+ content=f"Input: {json.dumps(args)}\n\nResponse{database_label}:\n{pretty}",
229
+ metadata={
230
+ "title": title
231
+ }
232
+ )
233
+ )
234
+
235
+ # Clear after rendering
236
+ last_tool_calls = []
237
+
238
+ return chat_history
239
+