File size: 11,655 Bytes
de60742
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea74ed3
de60742
 
ea74ed3
 
 
de60742
 
ea74ed3
eb0a98a
de60742
ea74ed3
6bc6a63
ea74ed3
 
eb0a98a
 
 
 
 
de60742
 
 
6bc6a63
 
 
de60742
 
eb0a98a
 
 
ea74ed3
6bc6a63
de60742
 
 
 
eb0a98a
 
 
 
6bc6a63
ea74ed3
 
 
de60742
6bc6a63
eb0a98a
6bc6a63
 
 
 
 
 
 
eb0a98a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bc6a63
 
eb0a98a
 
6bc6a63
 
eb0a98a
6bc6a63
eb0a98a
 
de60742
eb0a98a
de60742
6bc6a63
eb0a98a
6bc6a63
eb0a98a
de60742
eb0a98a
 
6bc6a63
de60742
 
 
6bc6a63
eb0a98a
 
 
 
6bc6a63
eb0a98a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bc6a63
 
 
 
 
 
eb0a98a
de60742
 
eb0a98a
 
 
6bc6a63
eb0a98a
 
 
 
 
 
 
 
 
 
de60742
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import os
import re
from dotenv import load_dotenv
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def load_api_key(key_name="OPENROUTER_API_KEY"):
    """
    Loads the specified API key from environment variables.
    Loads .env file first if it exists.

    Args:
        key_name (str): The name of the environment variable holding the API key.

    Returns:
        str: The API key.

    Raises:
        ValueError: If the API key environment variable is not set.
    """
    load_dotenv() # Load environment variables from .env file if it exists
    api_key = os.getenv(key_name)
    if not api_key:
        raise ValueError(
            f"'{key_name}' environment variable not set. Please create a .env file or set the variable."
        )
    return api_key


def parse_llm_answer(response_text: str, question_type: str = "MCQ_SINGLE_CORRECT") -> list[str] | str | None:
    """
    Parses the LLM response text to extract answers within <answer> tags.
    The parsing logic adapts based on the question_type.

    Handles:
    - MCQ_SINGLE_CORRECT: Single option identifier (integer like "1", "2" or letter like "A", "B").
    - INTEGER: Single numerical value, which can be an integer or a decimal (e.g., "5", "12.75", "0.5").
    - MCQ_MULTIPLE_CORRECT: Multiple option identifiers (integers or letters), comma-separated.
    - The specific string "SKIP" for skipped questions (case-insensitive content within tags).
    - Potential newlines and varied spacing within the tags.

    Args:
        response_text (str): The raw text response from the LLM.
        question_type (str): The type of question, e.g., "MCQ_SINGLE_CORRECT",
                             "MCQ_MULTIPLE_CORRECT", "INTEGER".
                             Defaults to "MCQ_SINGLE_CORRECT".

    Returns:
        list[str] | str | None:
            - A list containing string answer(s) if found and valid.
              (e.g., ["1"], ["A"], ["12.75"], ["A", "C"])
            - The string "SKIP" if the response indicates a skip.
            - None if parsing fails (no tag, invalid content, type mismatch, etc.).
    """
    if not response_text:
        return None

    # Check for exact SKIP response first (case-insensitive for the tag and content)
    # Using regex to be more flexible with whitespace around SKIP
    skip_match = re.search(r"<answer>\s*SKIP\s*</answer>", response_text, re.IGNORECASE)
    if skip_match:
        logging.info(f"Parsed answer as SKIP for question_type: {question_type}.")
        return "SKIP"

    match = re.search(r"<answer>(.*?)</answer>", response_text, re.DOTALL | re.IGNORECASE)

    if not match:
        logging.warning(f"Could not find <answer> tag in response for question_type: {question_type} in response: '{response_text[:200]}...'")
        return None

    extracted_content = match.group(1).strip()
    if not extracted_content:
        logging.warning(f"Found <answer> tag but content is empty for question_type: {question_type}.")
        return None

    potential_answers_str_list = [item.strip() for item in extracted_content.split(',')]
    parsed_answers_final = []

    for ans_str_raw in potential_answers_str_list:
        ans_str = ans_str_raw.strip()
        if not ans_str: # Skip empty strings that might result from "1, ,2" or trailing commas
            continue

        if question_type == "INTEGER":
            try:
                # Try to parse as float to validate it's a number (integer or decimal).
                # The value is kept as a string to preserve original formatting (e.g., "0.50", "5.0")
                # for exact string comparison with ground truth if needed, and for consistent type handling.
                float(ans_str) 
                parsed_answers_final.append(ans_str)
            except ValueError:
                logging.warning(f"Could not parse '{ans_str}' as a valid number (integer or decimal) for INTEGER type. Full content: '{extracted_content}'")
                return None # If any part is not a valid number for INTEGER type, fail parsing.
        
        elif question_type in ["MCQ_SINGLE_CORRECT", "MCQ_MULTIPLE_CORRECT"]:
            # For MCQs, the answer can be an integer (option number like 1, 2, 3, 4)
            # or a letter (option identifier like A, B, C, D).
            # The parser accepts these and returns them as strings.
            # Numerical options are typically single digits 1-4.
            # Letter options are single letters A-D (case-insensitive, converted to uppercase).
            if re.fullmatch(r"[1-4]", ans_str): # Typical integer options
                parsed_answers_final.append(ans_str)
            elif re.fullmatch(r"[a-dA-D]", ans_str): # Typical letter options (A,B,C,D or a,b,c,d)
                parsed_answers_final.append(ans_str.upper()) # Standardize to uppercase
            elif re.fullmatch(r"[1-9]\d*", ans_str): # Accept other integers if questions use them as options
                logging.debug(f"Accepting non-standard integer option '{ans_str}' for MCQ. Full content: '{extracted_content}'")
                parsed_answers_final.append(ans_str)
            elif re.fullmatch(r"[a-zA-Z]", ans_str): # Accept other single letters if questions use them
                logging.debug(f"Accepting non-standard letter option '{ans_str}' for MCQ. Full content: '{extracted_content}'")
                parsed_answers_final.append(ans_str.upper())
            else:
                logging.warning(f"Could not parse '{ans_str}' as a valid MCQ option (expected 1-4, A-D, or other single int/letter). Full content: '{extracted_content}'")
                return None # If any part is not a valid MCQ option, fail parsing.
        else: # Should not happen if question_type is validated before calling
            logging.error(f"Unknown question_type '{question_type}' encountered in parse_llm_answer logic.")
            return None


    if not parsed_answers_final: # If list is empty after processing (e.g. content was just commas)
        logging.warning(f"No valid answer items found after parsing content: '{extracted_content}' for question_type: {question_type}.")
        return None

    # Apply rules based on question_type for number of answers
    if question_type in ["MCQ_SINGLE_CORRECT", "INTEGER"]:
        if len(parsed_answers_final) == 1:
            return parsed_answers_final # Returns list[str] with one element
        else:
            logging.warning(f"Expected single answer for {question_type}, but found {len(parsed_answers_final)} items: {parsed_answers_final}. Content: '{extracted_content}'")
            return None
    elif question_type == "MCQ_MULTIPLE_CORRECT":
        # For multiple correct, any number of valid items is acceptable.
        # Return them sorted and unique.
        return sorted(list(set(parsed_answers_final)))
    else:
        # This case should ideally be caught by earlier checks or input validation.
        logging.error(f"Unknown question_type '{question_type}' provided to parse_llm_answer at final stage.")
        return None

# Example Usage (for testing)
if __name__ == '__main__':
    test_cases = [
        # MCQ_SINGLE_CORRECT (can be number or letter)
        {"resp": "<answer>2</answer>", "type": "MCQ_SINGLE_CORRECT", "expected": ["2"]},
        {"resp": "<answer>B</answer>", "type": "MCQ_SINGLE_CORRECT", "expected": ["B"]},
        {"resp": "<answer> c </answer>", "type": "MCQ_SINGLE_CORRECT", "expected": ["C"]},
        {"resp": "<answer>1,3</answer>", "type": "MCQ_SINGLE_CORRECT", "expected": None}, # Fail: multiple for single
        {"resp": "<answer>A,C</answer>", "type": "MCQ_SINGLE_CORRECT", "expected": None}, # Fail: multiple for single
        {"resp": "<answer>X</answer>", "type": "MCQ_SINGLE_CORRECT", "expected": None}, # Fail: invalid letter
        {"resp": "<answer>5</answer>", "type": "MCQ_SINGLE_CORRECT", "expected": ["5"]}, # Allow other numbers for now

        # INTEGER (can be int or decimal string)
        {"resp": "<answer>42</answer>", "type": "INTEGER", "expected": ["42"]},
        {"resp": "<answer>0</answer>", "type": "INTEGER", "expected": ["0"]},
        {"resp": "<answer>12.75</answer>", "type": "INTEGER", "expected": ["12.75"]},
        {"resp": "<answer>0.5</answer>", "type": "INTEGER", "expected": ["0.5"]},
        {"resp": "<answer>-5</answer>", "type": "INTEGER", "expected": ["-5"]}, # Assuming negative integers are valid if problem allows
        {"resp": "<answer>5.00</answer>", "type": "INTEGER", "expected": ["5.00"]},
        {"resp": "<answer>abc</answer>", "type": "INTEGER", "expected": None}, # Fail: not a number
        {"resp": "<answer>1,2</answer>", "type": "INTEGER", "expected": None}, # Fail: multiple for single int

        # MCQ_MULTIPLE_CORRECT (can be numbers or letters, mixed is not typical but parser allows if items are valid individually)
        {"resp": "<answer>1,3</answer>", "type": "MCQ_MULTIPLE_CORRECT", "expected": ["1", "3"]},
        {"resp": "<answer>A,C</answer>", "type": "MCQ_MULTIPLE_CORRECT", "expected": ["A", "C"]},
        {"resp": "<answer> b , d </answer>", "type": "MCQ_MULTIPLE_CORRECT", "expected": ["B", "D"]},
        {"resp": "<answer>2</answer>", "type": "MCQ_MULTIPLE_CORRECT", "expected": ["2"]}, # Single is valid
        {"resp": "<answer>D</answer>", "type": "MCQ_MULTIPLE_CORRECT", "expected": ["D"]}, # Single is valid
        {"resp": "<answer>1,C,3</answer>", "type": "MCQ_MULTIPLE_CORRECT", "expected": ["1", "3", "C"]}, # Mixed, sorted
        {"resp": "<answer>C,1,A,1</answer>", "type": "MCQ_MULTIPLE_CORRECT", "expected": ["1", "A", "C"]}, # Unique and sorted
        {"resp": "<answer>1,X,3</answer>", "type": "MCQ_MULTIPLE_CORRECT", "expected": None}, # Invalid item "X"

        # SKIP and general failures
        {"resp": "<ANSWER>SKIP</ANSWER>", "type": "MCQ_SINGLE_CORRECT", "expected": "SKIP"},
        {"resp": "  <answer>  SKIP  </answer>  ", "type": "INTEGER", "expected": "SKIP"},
        {"resp": "No answer tag here.", "type": "MCQ_SINGLE_CORRECT", "expected": None},
        {"resp": "<answer></answer>", "type": "MCQ_SINGLE_CORRECT", "expected": None},
        {"resp": "<answer>  </answer>", "type": "MCQ_SINGLE_CORRECT", "expected": None},
        {"resp": None, "type": "MCQ_SINGLE_CORRECT", "expected": None},
        {"resp": "", "type": "MCQ_SINGLE_CORRECT", "expected": None},
        {"resp": "<answer>5</answer>", "type": "UNKNOWN_TYPE", "expected": None}, # Unknown type
        {"resp": "<answer>1,,2</answer>", "type": "MCQ_MULTIPLE_CORRECT", "expected": ["1", "2"]}, # Handles empty item from double comma
    ]

    print("\n--- Testing parse_llm_answer (revised) ---")
    all_passed = True
    for i, case in enumerate(test_cases):
        parsed = parse_llm_answer(case["resp"], case["type"])
        if parsed == case["expected"]:
            print(f"Test {i+1} PASSED: Response: '{str(case['resp'])[:50]}...', Type: {case['type']} -> Parsed: {parsed}")
        else:
            print(f"Test {i+1} FAILED: Response: '{str(case['resp'])[:50]}...', Type: {case['type']} -> Parsed: {parsed} (Expected: {case['expected']})")
            all_passed = False
    
    if all_passed:
        print("\nAll revised parse_llm_answer tests passed!")
    else:
        print("\nSome revised parse_llm_answer tests FAILED.")

    # Test API key loading (will raise error if .env or env var not set)
    # try:
    #     key = load_api_key()
    #     print(f"\nAPI Key loaded successfully (partially hidden): {key[:4]}...{key[-4:]}")
    # except ValueError as e:
    #     print(f"\nError loading API key: {e}")