|
| 1 | +import re |
| 2 | +from enum import Enum |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +from datasets import load_dataset |
| 6 | +from openai import AsyncOpenAI |
| 7 | +import verifiers as vf |
| 8 | +from medarc_verifiers.rewards.multiple_choice_accuracy import multiple_choice_accuracy |
| 9 | +from medarc_verifiers.utils.randomize_multiple_choice import randomize_multiple_choice |
| 10 | +from medarc_verifiers.parsers.xml_parser import XMLParser |
| 11 | +from verifiers.types import Info, State |
| 12 | +from verifiers.utils.data_utils import extract_boxed_answer, BOXED_SYSTEM_PROMPT |
| 13 | + |
| 14 | + |
| 15 | +class CareQASplit(Enum): |
| 16 | + """Mode selector for CareQA environment.""" |
| 17 | + |
| 18 | + EN = "en" |
| 19 | + OPEN = "open" |
| 20 | + |
| 21 | + |
| 22 | +# --- MCQ Helpers --- |
| 23 | + |
| 24 | + |
| 25 | +def _build_mcq_prompt(question: str, options: dict[str, str]) -> str: |
| 26 | + """Create an MCQ prompt.""" |
| 27 | + formatted_opts = "\n".join(f"{k}. {v}" for k, v in options.items()) |
| 28 | + return f"Question: {question}\nChoices:\n{formatted_opts}\nAnswer:" |
| 29 | + |
| 30 | + |
| 31 | +def accuracy(completion, answer: str, parser: vf.Parser, info: dict | None = None, **kwargs) -> float: |
| 32 | + """Reward based on shared multiple-choice accuracy grading.""" |
| 33 | + parsed = parser.parse_answer(completion) or "" |
| 34 | + answer_text = info.get("answer_text", None) if info else None |
| 35 | + is_correct = multiple_choice_accuracy(llm_answer=parsed, answer_letter=answer, answer_text=answer_text) |
| 36 | + return 1.0 if is_correct else 0.0 |
| 37 | + |
| 38 | + |
| 39 | +# --- Open-Ended Helpers --- |
| 40 | + |
| 41 | + |
| 42 | +JUDGE_TEMPLATE = """You are grading an AI assistant's answer to a medical/science exam questions. |
| 43 | +
|
| 44 | +Input: |
| 45 | +- <question>: The exam question. |
| 46 | +- <reference_answer>: The correct answer. |
| 47 | +- <assistant_answer>: The AI's response to grade. |
| 48 | +
|
| 49 | +Task: Determine if the assistant's answer is correct or incorrect by comparing it to the reference answer and output your grade in <grade>...</grade> tags. |
| 50 | +
|
| 51 | +Grading Rules: |
| 52 | +- Assume the reference answer is correct and reflects the expected exam solution. |
| 53 | +- Focus on factual content and meaning, not style, length, or confidence. |
| 54 | +
|
| 55 | +Correct if the assistant's answer conveys the same essential fact(s) as the reference, including: |
| 56 | +- Synonyms, acronyms (expanded or abbreviated), or rephrasing with equivalent meaning |
| 57 | +- Slightly more general/specific phrasing that captures the key concept |
| 58 | +- Shorter or longer answers that express the tested fact without contradictions |
| 59 | +- Additional supporting details that don't contradict the reference |
| 60 | +
|
| 61 | +Incorrect if any of these apply: |
| 62 | +- Different main concept, mechanism, structure, or relationship |
| 63 | +- Contradicts the reference on key points (wrong organ, drug, effect, process, etc.) |
| 64 | +- Contains clearly incorrect information |
| 65 | +- Too vague/incomplete to match the reference |
| 66 | +- Merely repeats question words without the core information from the reference |
| 67 | +
|
| 68 | +Be strict: clear mismatches on main concepts or incorrect claims = Incorrect. |
| 69 | +
|
| 70 | +<question>{question}</question> |
| 71 | +<reference_answer>{answer}</reference_answer> |
| 72 | +<assistant_answer>{response}</assistant_answer> |
| 73 | +
|
| 74 | +Briefly explain whether the assistant's answer matches or conflicts with the reference. Then output your grade as: |
| 75 | +
|
| 76 | +<grade>[Correct or Incorrect]</grade> |
| 77 | +""".strip() |
| 78 | + |
| 79 | + |
| 80 | +def extract_answer_section(completion_text: str) -> str: |
| 81 | + """Extract final answer after think tags.""" |
| 82 | + if not completion_text: |
| 83 | + return "" |
| 84 | + if "<think>" in completion_text and "</think>" in completion_text: |
| 85 | + return re.sub(r".*?</think>", "", completion_text, flags=re.DOTALL).strip() |
| 86 | + return completion_text.strip() |
| 87 | + |
| 88 | + |
| 89 | +def load_environment( |
| 90 | + split: str | CareQASplit, |
| 91 | + system_prompt: Optional[str] = None, |
| 92 | + # MCQ-specific options |
| 93 | + shuffle_answers: bool = False, |
| 94 | + shuffle_seed: int | None = 1618, |
| 95 | + # Open-ended specific options |
| 96 | + judge_model: str = "gpt-4o-mini", |
| 97 | + judge_base_url: str | None = None, |
| 98 | + judge_api_key: str | None = None, |
| 99 | + **kwargs, |
| 100 | +) -> vf.Environment: |
| 101 | + """ |
| 102 | + CareQA evaluation environment supporting both MCQ and Open-Ended modes. |
| 103 | +
|
| 104 | + Args: |
| 105 | + split: CareQASplit.EN for multiple-choice or CareQASplit.OPEN for open-ended QA. |
| 106 | + system_prompt: Custom system prompt (uses mode-appropriate default if None). |
| 107 | + shuffle_answers: Shuffle MCQ answer options (MCQ mode only). |
| 108 | + shuffle_seed: Seed for answer shuffling (MCQ mode only). |
| 109 | + judge_model: Model to use for LLM-as-judge evaluation (Open-ended mode only). |
| 110 | + judge_base_url: Base URL for judge API (Open-ended mode only). |
| 111 | + judge_api_key: API key for judge (Open-ended mode only). |
| 112 | +
|
| 113 | + Returns: |
| 114 | + A vf.Environment configured for the selected mode. |
| 115 | + """ |
| 116 | + split = CareQASplit(split) if isinstance(split, str) else split |
| 117 | + if split == CareQASplit.EN: |
| 118 | + return _load_mcq_environment( |
| 119 | + system_prompt=system_prompt, |
| 120 | + shuffle_answers=shuffle_answers, |
| 121 | + shuffle_seed=shuffle_seed, |
| 122 | + ) |
| 123 | + elif split == CareQASplit.OPEN: |
| 124 | + return _load_open_ended_environment( |
| 125 | + system_prompt=system_prompt, |
| 126 | + judge_model=judge_model, |
| 127 | + judge_base_url=judge_base_url, |
| 128 | + judge_api_key=judge_api_key, |
| 129 | + ) |
| 130 | + else: |
| 131 | + raise ValueError(f"Invalid mode: {split}") |
| 132 | + |
| 133 | + |
| 134 | +def _load_mcq_environment( |
| 135 | + system_prompt: Optional[str], |
| 136 | + shuffle_answers: bool, |
| 137 | + shuffle_seed: int | None, |
| 138 | +) -> vf.Environment: |
| 139 | + """Load CareQA multiple-choice environment.""" |
| 140 | + eval_dataset = load_dataset("HPAI-BSC/CareQA", "CareQA_en", split="test") |
| 141 | + |
| 142 | + def _map(ex, idx=None): |
| 143 | + options = {"A": ex["op1"], "B": ex["op2"], "C": ex["op3"], "D": ex["op4"]} |
| 144 | + gold_letter = ["A", "B", "C", "D"][ex["cop"] - 1] |
| 145 | + |
| 146 | + if shuffle_answers and gold_letter in options: |
| 147 | + options, gold_letter, _ = randomize_multiple_choice( |
| 148 | + options=options, |
| 149 | + answer_choice=gold_letter, |
| 150 | + seed=shuffle_seed, |
| 151 | + row_id=ex.get("id", idx), |
| 152 | + ) |
| 153 | + |
| 154 | + return { |
| 155 | + "question": _build_mcq_prompt(ex["question"], options), |
| 156 | + "answer": gold_letter, |
| 157 | + "info": { |
| 158 | + "answer_text": options.get(gold_letter, None), |
| 159 | + **({"options": options} if shuffle_answers else {}), |
| 160 | + }, |
| 161 | + } |
| 162 | + |
| 163 | + load_from_cache_file = not shuffle_answers |
| 164 | + eval_dataset = eval_dataset.map( |
| 165 | + _map, |
| 166 | + with_indices=True, |
| 167 | + remove_columns=eval_dataset.column_names, |
| 168 | + load_from_cache_file=load_from_cache_file, |
| 169 | + ) |
| 170 | + |
| 171 | + parser = vf.Parser(extract_boxed_answer) |
| 172 | + final_system_prompt = BOXED_SYSTEM_PROMPT or system_prompt |
| 173 | + |
| 174 | + rubric = vf.Rubric(funcs=[accuracy], weights=[1.0], parser=parser) |
| 175 | + |
| 176 | + return vf.SingleTurnEnv( |
| 177 | + eval_dataset=eval_dataset, |
| 178 | + rubric=rubric, |
| 179 | + parser=parser, |
| 180 | + system_prompt=final_system_prompt, |
| 181 | + ) |
| 182 | + |
| 183 | + |
| 184 | +def _load_open_ended_environment( |
| 185 | + system_prompt: Optional[str], |
| 186 | + judge_model: str, |
| 187 | + judge_base_url: str | None, |
| 188 | + judge_api_key: str | None, |
| 189 | +) -> vf.Environment: |
| 190 | + """Load CareQA open-ended environment with LLM-as-judge evaluation.""" |
| 191 | + eval_dataset = load_dataset("HPAI-BSC/CareQA", "CareQA_en_open", split="test") |
| 192 | + |
| 193 | + def _map(ex): |
| 194 | + info = {} |
| 195 | + info["question"] = ex["question"].strip() |
| 196 | + return { |
| 197 | + "question": ex["question"].strip(), |
| 198 | + "answer": ex.get("answer_explanation", ex.get("answer", "")), |
| 199 | + "task": "careqa_open", |
| 200 | + "info": info, |
| 201 | + } |
| 202 | + |
| 203 | + eval_dataset = eval_dataset.map(_map, remove_columns=eval_dataset.column_names) |
| 204 | + |
| 205 | + final_system_prompt = system_prompt or ( |
| 206 | + "Instructions: The following text is a medical question. Answer it in the most factual, concise, and informative way possible." |
| 207 | + ) |
| 208 | + |
| 209 | + # Judge client setup |
| 210 | + judge_client = AsyncOpenAI(base_url=judge_base_url, api_key=judge_api_key) |
| 211 | + judge_parser = XMLParser(fields=["grade"], answer_field="grade") |
| 212 | + |
| 213 | + judge_rubric = vf.JudgeRubric( |
| 214 | + parser=judge_parser, |
| 215 | + judge_client=judge_client, |
| 216 | + judge_model=judge_model, |
| 217 | + judge_prompt="{question}", |
| 218 | + ) |
| 219 | + |
| 220 | + async def accuracy(judge, prompt, completion, answer, state: State, info: Info) -> float: |
| 221 | + """Evaluate medical equivalence using LLM-as-judge.""" |
| 222 | + completion_text = completion if isinstance(completion, str) else str(completion) |
| 223 | + response = extract_answer_section(completion_text) |
| 224 | + |
| 225 | + try: |
| 226 | + judge_prompt = JUDGE_TEMPLATE.format(question=info.get("question", ""), answer=answer, response=response) |
| 227 | + judge_response = await judge_rubric.judge(judge_prompt, "", "", state) |
| 228 | + grade = judge_parser.parse_answer(judge_response).strip().lower() |
| 229 | + except AttributeError: |
| 230 | + judge_response = await judge_rubric.judge(judge_prompt, "", "", state) |
| 231 | + grade = judge_parser.parse_answer(judge_response).strip().lower() |
| 232 | + |
| 233 | + info.setdefault("judge_feedback", []).append( |
| 234 | + { |
| 235 | + "grade": grade, |
| 236 | + "raw_judge": str(judge_response), |
| 237 | + } |
| 238 | + ) |
| 239 | + |
| 240 | + if "correct" in grade and "incorrect" not in grade: |
| 241 | + return 1.0 |
| 242 | + else: |
| 243 | + return 0.0 |
| 244 | + |
| 245 | + judge_rubric.add_reward_func(accuracy, weight=1.0) |
| 246 | + |
| 247 | + return vf.SingleTurnEnv( |
| 248 | + eval_dataset=eval_dataset, |
| 249 | + system_prompt=final_system_prompt, |
| 250 | + rubric=judge_rubric, |
| 251 | + ) |
0 commit comments