|
| 1 | +import re |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +from graphgen.bases import BaseGenerator |
| 5 | +from graphgen.templates import MCQ_GENERATION_PROMPT |
| 6 | +from graphgen.utils import compute_content_hash, detect_main_language, logger |
| 7 | + |
| 8 | + |
| 9 | +class MultiChoiceGenerator(BaseGenerator): |
| 10 | + def __init__(self, llm_client, num_of_questions) -> None: |
| 11 | + super().__init__(llm_client) |
| 12 | + self.num_of_questions = num_of_questions |
| 13 | + |
| 14 | + @staticmethod |
| 15 | + def parse_response(response: str) -> Any: |
| 16 | + """ |
| 17 | + Parse multiple choice QA pairs from the LLM response. |
| 18 | + Each QA pair contains question text, four options, and the correct answer. |
| 19 | +
|
| 20 | + :param response: The LLM response containing XML-formatted QA pairs |
| 21 | + :return: Dictionary mapping question hash to question data, where each |
| 22 | + value is a dict with "question", "options", "answer", and |
| 23 | + "correct_answer_text" keys |
| 24 | + """ |
| 25 | + qa_pairs = {} |
| 26 | + |
| 27 | + # Extract all QA pair blocks |
| 28 | + qa_blocks = re.findall(r"<qa_pair>(.*?)</qa_pair>", response, re.DOTALL) |
| 29 | + |
| 30 | + if not qa_blocks: |
| 31 | + logger.warning("No QA pairs found in response: %s", response) |
| 32 | + return {} |
| 33 | + |
| 34 | + for block in qa_blocks: |
| 35 | + # Extract and clean question text |
| 36 | + q_match = re.search(r"<question>(.*?)</question>", block, re.DOTALL) |
| 37 | + if not q_match: |
| 38 | + logger.warning("Failed to parse question from block: %s", block) |
| 39 | + continue |
| 40 | + question = q_match.group(1).strip().strip('"').strip("'") |
| 41 | + |
| 42 | + # Extract and parse options (A, B, C, D) |
| 43 | + opt_match = re.search(r"<options>(.*?)</options>", block, re.DOTALL) |
| 44 | + if not opt_match: |
| 45 | + logger.warning("Failed to parse options from block: %s", block) |
| 46 | + continue |
| 47 | + |
| 48 | + options = {} |
| 49 | + options_text = opt_match.group(1).strip() |
| 50 | + for line in options_text.split("\n"): |
| 51 | + line = line.strip() |
| 52 | + if not line: |
| 53 | + continue |
| 54 | + # Match patterns like "A. text" or "B. text" |
| 55 | + if m := re.match(r"^([A-D])[.\s]\s*(.*)$", line): |
| 56 | + letter, text = m.groups() |
| 57 | + options[letter] = text.strip() |
| 58 | + |
| 59 | + # Validate options count |
| 60 | + if len(options) != 4: |
| 61 | + logger.warning( |
| 62 | + "Expected 4 options, found %d: %s", len(options), options_text |
| 63 | + ) |
| 64 | + continue |
| 65 | + |
| 66 | + # Extract and validate answer |
| 67 | + ans_match = re.search(r"<answer>(.*?)</answer>", block, re.DOTALL) |
| 68 | + if not ans_match: |
| 69 | + logger.warning("Failed to parse answer from block: %s", block) |
| 70 | + continue |
| 71 | + answer = ans_match.group(1).strip().strip('"').strip("'") |
| 72 | + |
| 73 | + # Ensure answer exists in options |
| 74 | + if answer not in options: |
| 75 | + logger.warning( |
| 76 | + "Answer '%s' not found in options: %s", answer, list(options.keys()) |
| 77 | + ) |
| 78 | + continue |
| 79 | + |
| 80 | + # Build result entry with question hash as key |
| 81 | + question_hash = compute_content_hash(question) |
| 82 | + qa_pairs[question_hash] = { |
| 83 | + "question": question, |
| 84 | + "options": options, # Dict like {"A": "text", "B": "text", ...} |
| 85 | + "answer": answer, # Single letter: "A", "B", "C", or "D" |
| 86 | + "correct_answer_text": options[ |
| 87 | + answer |
| 88 | + ], # The actual text of correct answer |
| 89 | + } |
| 90 | + |
| 91 | + logger.debug("Successfully parsed MCQ: %s", question[:50]) |
| 92 | + |
| 93 | + if not qa_pairs: |
| 94 | + logger.error("Failed to parse any valid MCQ pairs from response") |
| 95 | + |
| 96 | + return qa_pairs |
| 97 | + |
| 98 | + # pylint: disable=W0221 |
| 99 | + def build_prompt( |
| 100 | + self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]] |
| 101 | + ) -> str: |
| 102 | + nodes, edges = batch |
| 103 | + entities_str = "\n".join( |
| 104 | + [ |
| 105 | + f"{index + 1}. {node[0]}: {node[1]['description']}" |
| 106 | + for index, node in enumerate(nodes) |
| 107 | + ] |
| 108 | + ) |
| 109 | + |
| 110 | + relationships_str = "\n".join( |
| 111 | + [ |
| 112 | + f"{index + 1}. {edge[0]} -- {edge[1]}: {edge[2]['description']}" |
| 113 | + for index, edge in enumerate(edges) |
| 114 | + ] |
| 115 | + ) |
| 116 | + context = entities_str + "\n" + relationships_str |
| 117 | + language = detect_main_language(entities_str + relationships_str) |
| 118 | + prompt = MCQ_GENERATION_PROMPT[language].format( |
| 119 | + context=context, |
| 120 | + num_of_questions=self.num_of_questions, |
| 121 | + ) |
| 122 | + return prompt |
0 commit comments