File size: 7,829 Bytes
c8b1c88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generator Agent.

- Takes (grade, topic) and optional reviewer feedback.
- Produces STRICT JSON in the required schema.

This agent does not print or format output; it only returns Python dicts.
"""

from __future__ import annotations

import json
import re
from typing import Any, Dict, List, Optional

from config import get_groq_client
from utils.prompts import generator_system_prompt, generator_user_prompt


MODEL_NAME = "llama-3.3-70b-versatile"  # Strong general model; change if needed.


def _parse_strict_json(text: str) -> Dict[str, Any]:
    """Parse JSON from model output.

    We expect JSON-only responses. If the model still wraps text,
    we attempt a minimal extraction as a last resort.
    """

    try:
        return json.loads(text)
    except json.JSONDecodeError:
        # Minimal fallback: try extracting the first JSON object.
        start = text.find("{")
        end = text.rfind("}")
        if start == -1 or end == -1 or end <= start:
            raise
        return json.loads(text[start : end + 1])


def _validate_generator_output(payload: Dict[str, Any]) -> None:
    if not isinstance(payload, dict):
        raise ValueError("Generator output must be a JSON object.")

    if set(payload.keys()) != {"explanation", "mcqs"}:
        raise ValueError("Generator output must contain exactly: explanation, mcqs")

    if not isinstance(payload["explanation"], str) or not payload["explanation"].strip():
        raise ValueError("'explanation' must be a non-empty string")

    mcqs = payload["mcqs"]
    if not isinstance(mcqs, list) or len(mcqs) == 0:
        raise ValueError("'mcqs' must be a non-empty list")

    for idx, item in enumerate(mcqs, start=1):
        if not isinstance(item, dict):
            raise ValueError(f"MCQ {idx} must be an object")

        expected_keys = {"question", "options", "answer"}
        if set(item.keys()) != expected_keys:
            raise ValueError(f"MCQ {idx} must contain exactly: question, options, answer")

        if not isinstance(item["question"], str) or not item["question"].strip():
            raise ValueError(f"MCQ {idx} question must be a non-empty string")

        options = item["options"]
        if not isinstance(options, list) or len(options) != 4 or not all(
            isinstance(o, str) and o.strip() for o in options
        ):
            raise ValueError(f"MCQ {idx} options must be a list of 4 non-empty strings")

        # Coerce common LLM answer formats to an exact option string.
        # Examples handled:
        # - answer: "B"  -> options[1]
        # - answer: "Option B" / "B) ..." / "B. ..." -> options[1]
        # - answer differs only by whitespace/case/prefix labels.
        answer_raw = item["answer"]
        if not isinstance(answer_raw, str) or not answer_raw.strip():
            raise ValueError(f"MCQ {idx} answer must be a non-empty string")

        if answer_raw in options:
            continue

        def _norm(s: str) -> str:
            # Normalize whitespace and quotes for comparison.
            s = s.strip()
            s = s.replace("\u2018", "'").replace("\u2019", "'")
            s = s.replace("\u201c", '"').replace("\u201d", '"')
            s = re.sub(r"\s+", " ", s)
            return s

        normalized_answer = _norm(answer_raw)
        normalized_options = [_norm(o) for o in options]

        # 1) Exact match after normalization.
        for opt, opt_norm in zip(options, normalized_options):
            if normalized_answer == opt_norm:
                item["answer"] = opt
                break
        else:
            # 2) Case-insensitive match after normalization.
            lowered_answer = normalized_answer.casefold()
            ci_matches = [i for i, opt_norm in enumerate(normalized_options) if opt_norm.casefold() == lowered_answer]
            if len(ci_matches) == 1:
                item["answer"] = options[ci_matches[0]]
            else:
                # 3) Letter/index selection -> option mapping.
                # Accept: "A"/"B"/"C"/"D", "Option A", "(B)", "B)" etc.
                m = re.fullmatch(r"\(?\s*(?:option\s+)?([A-D])\s*\)?(?:\s*[:\).\-])?\s*(.*)", normalized_answer, flags=re.IGNORECASE)
                chosen_index: Optional[int] = None
                trailing_text = ""
                if m:
                    chosen_index = ord(m.group(1).upper()) - ord("A")
                    trailing_text = _norm(m.group(2) or "")

                if chosen_index is not None and 0 <= chosen_index < 4:
                    # If the model also repeated some option text, validate it matches the chosen option.
                    if trailing_text:
                        chosen_opt_norm = normalized_options[chosen_index]
                        # Strip leading label from the option itself, if present.
                        chosen_opt_stripped = re.sub(
                            r"^\s*(?:\(?\s*)?[A-D](?:\s*\)?\s*)?(?:[:\).\-])\s*",
                            "",
                            chosen_opt_norm,
                            flags=re.IGNORECASE,
                        )
                        if trailing_text.casefold() not in {
                            chosen_opt_norm.casefold(),
                            chosen_opt_stripped.casefold(),
                        }:
                            raise ValueError(
                                f"MCQ {idx} answer must exactly match one of the options (letter points to a different option text)"
                            )

                    item["answer"] = options[chosen_index]
                else:
                    # 4) Options may be prefixed like "A) ..."; compare after stripping such prefixes.
                    def _strip_label_prefix(s: str) -> str:
                        return re.sub(
                            r"^\s*(?:\(?\s*)?[A-D](?:\s*\)?\s*)?(?:[:\).\-])\s*",
                            "",
                            _norm(s),
                            flags=re.IGNORECASE,
                        )

                    stripped_answer = _strip_label_prefix(answer_raw)
                    stripped_option_norms = [_strip_label_prefix(o) for o in options]
                    stripped_matches = [
                        i
                        for i, opt_stripped in enumerate(stripped_option_norms)
                        if _norm(opt_stripped).casefold() == _norm(stripped_answer).casefold()
                    ]
                    if len(stripped_matches) == 1:
                        item["answer"] = options[stripped_matches[0]]
                    else:
                        raise ValueError(f"MCQ {idx} answer must exactly match one of the options")


def generate_content(*, grade: int, topic: str, feedback: Optional[List[str]] = None) -> Dict[str, Any]:
    """Call Groq LLM to generate content with strict JSON output."""

    client = get_groq_client()

    messages = [
        {"role": "system", "content": generator_system_prompt()},
        {"role": "user", "content": generator_user_prompt(grade=grade, topic=topic, feedback=feedback)},
    ]

    # Deterministic settings.
    try:
        response = client.chat.completions.create(
            model=MODEL_NAME,
            messages=messages,
            temperature=0,
            top_p=1,
            # If supported by the SDK/model, JSON mode improves compliance.
            response_format={"type": "json_object"},
        )
    except TypeError:
        # Older SDKs may not accept `response_format`.
        response = client.chat.completions.create(
            model=MODEL_NAME,
            messages=messages,
            temperature=0,
            top_p=1,
        )

    text = response.choices[0].message.content
    parsed = _parse_strict_json(text)
    _validate_generator_output(parsed)
    return parsed