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