EduGenerator / agents /generator.py
dwaynefernandes05's picture
First commit
c8b1c88
Raw History Blame Contribute Delete
7.83 kB
"""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