|
| 1 | +import re |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +from graphgen.bases import BaseGenerator |
| 5 | +from graphgen.templates import TF_GENERATION_PROMPT |
| 6 | +from graphgen.utils import compute_content_hash, detect_main_language, logger |
| 7 | + |
| 8 | + |
| 9 | +class TrueFalseGenerator(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 true/false QA pairs from the LLM response. |
| 18 | + Each QA pair contains a statement question and True/False 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", and "answer" keys |
| 23 | + """ |
| 24 | + qa_pairs: dict[str, dict[str, Any]] = {} |
| 25 | + |
| 26 | + # Extract all QA pair blocks |
| 27 | + qa_blocks = re.findall(r"<qa_pair>(.*?)</qa_pair>", response, re.DOTALL) |
| 28 | + |
| 29 | + if not qa_blocks: |
| 30 | + logger.warning("No QA pairs found in response: %s", response) |
| 31 | + return {} |
| 32 | + |
| 33 | + for block in qa_blocks: |
| 34 | + # Extract and clean question text |
| 35 | + q_match = re.search(r"<question>(.*?)</question>", block, re.DOTALL) |
| 36 | + if not q_match: |
| 37 | + logger.warning("Failed to parse question from block: %s", block) |
| 38 | + continue |
| 39 | + question = q_match.group(1).strip().strip('"').strip("'") |
| 40 | + |
| 41 | + # Extract and validate answer |
| 42 | + ans_match = re.search(r"<answer>(.*?)</answer>", block, re.DOTALL) |
| 43 | + if not ans_match: |
| 44 | + logger.warning("Failed to parse answer from block: %s", block) |
| 45 | + continue |
| 46 | + answer = ans_match.group(1).strip().strip('"').strip("'") |
| 47 | + |
| 48 | + # Ensure answer exists in options |
| 49 | + if answer.lower() not in ["true", "false"]: |
| 50 | + logger.warning("Invalid answer '%s' in block: %s", answer, block) |
| 51 | + continue |
| 52 | + |
| 53 | + # Build result entry with question hash as key |
| 54 | + question_hash = compute_content_hash(question) |
| 55 | + qa_pairs[question_hash] = { |
| 56 | + "question": question, |
| 57 | + "answer": answer, # "True" or "False" |
| 58 | + } |
| 59 | + |
| 60 | + logger.debug("Successfully parsed TF question: %s", question[:50]) |
| 61 | + |
| 62 | + if not qa_pairs: |
| 63 | + logger.error("Failed to parse any valid true/false pairs from response") |
| 64 | + |
| 65 | + return qa_pairs |
| 66 | + |
| 67 | + # pylint: disable=W0221 |
| 68 | + def build_prompt( |
| 69 | + self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]] |
| 70 | + ) -> str: |
| 71 | + nodes, edges = batch |
| 72 | + entities_str = "\n".join( |
| 73 | + [ |
| 74 | + f"{index + 1}. {node[0]}: {node[1]['description']}" |
| 75 | + for index, node in enumerate(nodes) |
| 76 | + ] |
| 77 | + ) |
| 78 | + |
| 79 | + relationships_str = "\n".join( |
| 80 | + [ |
| 81 | + f"{index + 1}. {edge[0]} -- {edge[1]}: {edge[2]['description']}" |
| 82 | + for index, edge in enumerate(edges) |
| 83 | + ] |
| 84 | + ) |
| 85 | + context = entities_str + "\n" + relationships_str |
| 86 | + language = detect_main_language(entities_str + relationships_str) |
| 87 | + prompt = TF_GENERATION_PROMPT[language].format( |
| 88 | + context=context, |
| 89 | + num_of_questions=self.num_of_questions, |
| 90 | + ) |
| 91 | + return prompt |
0 commit comments