dwaynefernandes05 commited on
Commit
c8b1c88
·
1 Parent(s): f3da6b9

First commit

Browse files
Files changed (10) hide show
  1. .devcontainer/devcontainer.json +33 -0
  2. .gitignore +20 -0
  3. README.md +2 -3
  4. agents/generator.py +190 -0
  5. agents/reviewer.py +75 -0
  6. app.py +55 -0
  7. config.py +35 -0
  8. graph.py +143 -0
  9. requirements.txt +4 -0
  10. utils/prompts.py +102 -0
.devcontainer/devcontainer.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "Python 3",
3
+ // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
4
+ "image": "mcr.microsoft.com/devcontainers/python:1-3.11-bookworm",
5
+ "customizations": {
6
+ "codespaces": {
7
+ "openFiles": [
8
+ "README.md",
9
+ "app.py"
10
+ ]
11
+ },
12
+ "vscode": {
13
+ "settings": {},
14
+ "extensions": [
15
+ "ms-python.python",
16
+ "ms-python.vscode-pylance"
17
+ ]
18
+ }
19
+ },
20
+ "updateContentCommand": "[ -f packages.txt ] && sudo apt update && sudo apt upgrade -y && sudo xargs apt install -y <packages.txt; [ -f requirements.txt ] && pip3 install --user -r requirements.txt; pip3 install --user streamlit; echo '✅ Packages installed and Requirements met'",
21
+ "postAttachCommand": {
22
+ "server": "streamlit run app.py --server.enableCORS false --server.enableXsrfProtection false"
23
+ },
24
+ "portsAttributes": {
25
+ "8501": {
26
+ "label": "Application",
27
+ "onAutoForward": "openPreview"
28
+ }
29
+ },
30
+ "forwardPorts": [
31
+ 8501
32
+ ]
33
+ }
.gitignore ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.pyo
5
+ *.pyd
6
+
7
+ # Virtual environments
8
+ .venv/
9
+ venv/
10
+ ENV/
11
+
12
+ # Env files
13
+ .env
14
+
15
+ # Streamlit
16
+ .streamlit/
17
+
18
+ # OS
19
+ .DS_Store
20
+ Thumbs.db
README.md CHANGED
@@ -3,11 +3,10 @@ title: EduGenerator
3
  emoji: 🌍
4
  colorFrom: indigo
5
  colorTo: green
6
- sdk: gradio
7
- sdk_version: 6.9.0
8
  app_file: app.py
9
  pinned: false
10
- short_description: 'Langgraph based agents create MCQ questions for students '
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
3
  emoji: 🌍
4
  colorFrom: indigo
5
  colorTo: green
6
+ sdk: streamlit
 
7
  app_file: app.py
8
  pinned: false
9
+ short_description: Langgraph based agents create MCQ questions for students
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
agents/generator.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generator Agent.
2
+
3
+ - Takes (grade, topic) and optional reviewer feedback.
4
+ - Produces STRICT JSON in the required schema.
5
+
6
+ This agent does not print or format output; it only returns Python dicts.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ from typing import Any, Dict, List, Optional
14
+
15
+ from config import get_groq_client
16
+ from utils.prompts import generator_system_prompt, generator_user_prompt
17
+
18
+
19
+ MODEL_NAME = "llama-3.3-70b-versatile" # Strong general model; change if needed.
20
+
21
+
22
+ def _parse_strict_json(text: str) -> Dict[str, Any]:
23
+ """Parse JSON from model output.
24
+
25
+ We expect JSON-only responses. If the model still wraps text,
26
+ we attempt a minimal extraction as a last resort.
27
+ """
28
+
29
+ try:
30
+ return json.loads(text)
31
+ except json.JSONDecodeError:
32
+ # Minimal fallback: try extracting the first JSON object.
33
+ start = text.find("{")
34
+ end = text.rfind("}")
35
+ if start == -1 or end == -1 or end <= start:
36
+ raise
37
+ return json.loads(text[start : end + 1])
38
+
39
+
40
+ def _validate_generator_output(payload: Dict[str, Any]) -> None:
41
+ if not isinstance(payload, dict):
42
+ raise ValueError("Generator output must be a JSON object.")
43
+
44
+ if set(payload.keys()) != {"explanation", "mcqs"}:
45
+ raise ValueError("Generator output must contain exactly: explanation, mcqs")
46
+
47
+ if not isinstance(payload["explanation"], str) or not payload["explanation"].strip():
48
+ raise ValueError("'explanation' must be a non-empty string")
49
+
50
+ mcqs = payload["mcqs"]
51
+ if not isinstance(mcqs, list) or len(mcqs) == 0:
52
+ raise ValueError("'mcqs' must be a non-empty list")
53
+
54
+ for idx, item in enumerate(mcqs, start=1):
55
+ if not isinstance(item, dict):
56
+ raise ValueError(f"MCQ {idx} must be an object")
57
+
58
+ expected_keys = {"question", "options", "answer"}
59
+ if set(item.keys()) != expected_keys:
60
+ raise ValueError(f"MCQ {idx} must contain exactly: question, options, answer")
61
+
62
+ if not isinstance(item["question"], str) or not item["question"].strip():
63
+ raise ValueError(f"MCQ {idx} question must be a non-empty string")
64
+
65
+ options = item["options"]
66
+ if not isinstance(options, list) or len(options) != 4 or not all(
67
+ isinstance(o, str) and o.strip() for o in options
68
+ ):
69
+ raise ValueError(f"MCQ {idx} options must be a list of 4 non-empty strings")
70
+
71
+ # Coerce common LLM answer formats to an exact option string.
72
+ # Examples handled:
73
+ # - answer: "B" -> options[1]
74
+ # - answer: "Option B" / "B) ..." / "B. ..." -> options[1]
75
+ # - answer differs only by whitespace/case/prefix labels.
76
+ answer_raw = item["answer"]
77
+ if not isinstance(answer_raw, str) or not answer_raw.strip():
78
+ raise ValueError(f"MCQ {idx} answer must be a non-empty string")
79
+
80
+ if answer_raw in options:
81
+ continue
82
+
83
+ def _norm(s: str) -> str:
84
+ # Normalize whitespace and quotes for comparison.
85
+ s = s.strip()
86
+ s = s.replace("\u2018", "'").replace("\u2019", "'")
87
+ s = s.replace("\u201c", '"').replace("\u201d", '"')
88
+ s = re.sub(r"\s+", " ", s)
89
+ return s
90
+
91
+ normalized_answer = _norm(answer_raw)
92
+ normalized_options = [_norm(o) for o in options]
93
+
94
+ # 1) Exact match after normalization.
95
+ for opt, opt_norm in zip(options, normalized_options):
96
+ if normalized_answer == opt_norm:
97
+ item["answer"] = opt
98
+ break
99
+ else:
100
+ # 2) Case-insensitive match after normalization.
101
+ lowered_answer = normalized_answer.casefold()
102
+ ci_matches = [i for i, opt_norm in enumerate(normalized_options) if opt_norm.casefold() == lowered_answer]
103
+ if len(ci_matches) == 1:
104
+ item["answer"] = options[ci_matches[0]]
105
+ else:
106
+ # 3) Letter/index selection -> option mapping.
107
+ # Accept: "A"/"B"/"C"/"D", "Option A", "(B)", "B)" etc.
108
+ m = re.fullmatch(r"\(?\s*(?:option\s+)?([A-D])\s*\)?(?:\s*[:\).\-])?\s*(.*)", normalized_answer, flags=re.IGNORECASE)
109
+ chosen_index: Optional[int] = None
110
+ trailing_text = ""
111
+ if m:
112
+ chosen_index = ord(m.group(1).upper()) - ord("A")
113
+ trailing_text = _norm(m.group(2) or "")
114
+
115
+ if chosen_index is not None and 0 <= chosen_index < 4:
116
+ # If the model also repeated some option text, validate it matches the chosen option.
117
+ if trailing_text:
118
+ chosen_opt_norm = normalized_options[chosen_index]
119
+ # Strip leading label from the option itself, if present.
120
+ chosen_opt_stripped = re.sub(
121
+ r"^\s*(?:\(?\s*)?[A-D](?:\s*\)?\s*)?(?:[:\).\-])\s*",
122
+ "",
123
+ chosen_opt_norm,
124
+ flags=re.IGNORECASE,
125
+ )
126
+ if trailing_text.casefold() not in {
127
+ chosen_opt_norm.casefold(),
128
+ chosen_opt_stripped.casefold(),
129
+ }:
130
+ raise ValueError(
131
+ f"MCQ {idx} answer must exactly match one of the options (letter points to a different option text)"
132
+ )
133
+
134
+ item["answer"] = options[chosen_index]
135
+ else:
136
+ # 4) Options may be prefixed like "A) ..."; compare after stripping such prefixes.
137
+ def _strip_label_prefix(s: str) -> str:
138
+ return re.sub(
139
+ r"^\s*(?:\(?\s*)?[A-D](?:\s*\)?\s*)?(?:[:\).\-])\s*",
140
+ "",
141
+ _norm(s),
142
+ flags=re.IGNORECASE,
143
+ )
144
+
145
+ stripped_answer = _strip_label_prefix(answer_raw)
146
+ stripped_option_norms = [_strip_label_prefix(o) for o in options]
147
+ stripped_matches = [
148
+ i
149
+ for i, opt_stripped in enumerate(stripped_option_norms)
150
+ if _norm(opt_stripped).casefold() == _norm(stripped_answer).casefold()
151
+ ]
152
+ if len(stripped_matches) == 1:
153
+ item["answer"] = options[stripped_matches[0]]
154
+ else:
155
+ raise ValueError(f"MCQ {idx} answer must exactly match one of the options")
156
+
157
+
158
+ def generate_content(*, grade: int, topic: str, feedback: Optional[List[str]] = None) -> Dict[str, Any]:
159
+ """Call Groq LLM to generate content with strict JSON output."""
160
+
161
+ client = get_groq_client()
162
+
163
+ messages = [
164
+ {"role": "system", "content": generator_system_prompt()},
165
+ {"role": "user", "content": generator_user_prompt(grade=grade, topic=topic, feedback=feedback)},
166
+ ]
167
+
168
+ # Deterministic settings.
169
+ try:
170
+ response = client.chat.completions.create(
171
+ model=MODEL_NAME,
172
+ messages=messages,
173
+ temperature=0,
174
+ top_p=1,
175
+ # If supported by the SDK/model, JSON mode improves compliance.
176
+ response_format={"type": "json_object"},
177
+ )
178
+ except TypeError:
179
+ # Older SDKs may not accept `response_format`.
180
+ response = client.chat.completions.create(
181
+ model=MODEL_NAME,
182
+ messages=messages,
183
+ temperature=0,
184
+ top_p=1,
185
+ )
186
+
187
+ text = response.choices[0].message.content
188
+ parsed = _parse_strict_json(text)
189
+ _validate_generator_output(parsed)
190
+ return parsed
agents/reviewer.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reviewer Agent.
2
+
3
+ - Takes the generator JSON output.
4
+ - Returns STRICT JSON with pass/fail and feedback list.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from typing import Any, Dict
11
+
12
+ from config import get_groq_client
13
+ from utils.prompts import reviewer_system_prompt, reviewer_user_prompt
14
+
15
+
16
+ MODEL_NAME = "llama-3.3-70b-versatile"
17
+
18
+
19
+ def _parse_strict_json(text: str) -> Dict[str, Any]:
20
+ try:
21
+ return json.loads(text)
22
+ except json.JSONDecodeError:
23
+ start = text.find("{")
24
+ end = text.rfind("}")
25
+ if start == -1 or end == -1 or end <= start:
26
+ raise
27
+ return json.loads(text[start : end + 1])
28
+
29
+
30
+ def _validate_reviewer_output(payload: Dict[str, Any]) -> None:
31
+ if not isinstance(payload, dict):
32
+ raise ValueError("Reviewer output must be a JSON object")
33
+
34
+ if set(payload.keys()) != {"status", "feedback"}:
35
+ raise ValueError("Reviewer output must contain exactly: status, feedback")
36
+
37
+ if payload["status"] not in {"pass", "fail"}:
38
+ raise ValueError("Reviewer status must be 'pass' or 'fail'")
39
+
40
+ feedback = payload["feedback"]
41
+ if not isinstance(feedback, list) or not all(isinstance(x, str) for x in feedback):
42
+ raise ValueError("Reviewer feedback must be a list of strings")
43
+
44
+ if payload["status"] == "pass" and len(feedback) != 0:
45
+ raise ValueError("When status is 'pass', feedback must be an empty list")
46
+
47
+
48
+ def review_content(*, grade: int, topic: str, generator_output: Dict[str, Any]) -> Dict[str, Any]:
49
+ client = get_groq_client()
50
+
51
+ messages = [
52
+ {"role": "system", "content": reviewer_system_prompt()},
53
+ {"role": "user", "content": reviewer_user_prompt(grade=grade, topic=topic, generator_output=generator_output)},
54
+ ]
55
+
56
+ try:
57
+ response = client.chat.completions.create(
58
+ model=MODEL_NAME,
59
+ messages=messages,
60
+ temperature=0,
61
+ top_p=1,
62
+ response_format={"type": "json_object"},
63
+ )
64
+ except TypeError:
65
+ response = client.chat.completions.create(
66
+ model=MODEL_NAME,
67
+ messages=messages,
68
+ temperature=0,
69
+ top_p=1,
70
+ )
71
+
72
+ text = response.choices[0].message.content
73
+ parsed = _parse_strict_json(text)
74
+ _validate_reviewer_output(parsed)
75
+ return parsed
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Streamlit UI for the Agentic Educational Content Generator."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import streamlit as st
6
+
7
+ from graph import run_flow
8
+
9
+
10
+ st.set_page_config(page_title="Agentic Edu Generator", layout="centered")
11
+
12
+ st.title("Agent-Based Educational Content Generator")
13
+ st.caption("Generator Agent → Reviewer Agent → (optional one-time refinement)")
14
+
15
+ with st.form("input_form"):
16
+ grade = st.number_input("Grade", min_value=1, max_value=12, value=4, step=1)
17
+ topic = st.text_input("Topic", value="Types of angles")
18
+ submitted = st.form_submit_button("Generate Content")
19
+
20
+ if submitted:
21
+ if not str(topic).strip():
22
+ st.error("Please enter a topic.")
23
+ st.stop()
24
+
25
+ with st.spinner("Running agents..."):
26
+ state = run_flow(grade=int(grade), topic=str(topic).strip())
27
+
28
+ refinement_used = bool(state.get("refinement_used"))
29
+
30
+ st.subheader("1) Generator Output")
31
+ st.json(state.get("generator_output", {}))
32
+
33
+ st.subheader("2) Reviewer Feedback")
34
+ reviewer_output = state.get("reviewer_output", {})
35
+ st.json(reviewer_output)
36
+ feedback = reviewer_output.get("feedback") if isinstance(reviewer_output, dict) else None
37
+ if isinstance(feedback, list) and feedback:
38
+ st.markdown("**Issues found**")
39
+ for item in feedback:
40
+ st.write(f"- {item}")
41
+
42
+ if refinement_used:
43
+ st.subheader("3) Refined Output (after one refinement)")
44
+ refined = state.get("refined_generator_output")
45
+ refined_review = state.get("refined_reviewer_output")
46
+
47
+ if refined is not None:
48
+ st.markdown("**Refined Generator Output**")
49
+ st.json(refined)
50
+
51
+ if refined_review is not None:
52
+ st.markdown("**Refined Reviewer Output**")
53
+ st.json(refined_review)
54
+
55
+ st.divider()
config.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration and Groq client initialization.
2
+
3
+ - Loads environment variables via python-dotenv.
4
+ - Exposes a single `get_groq_client()` helper.
5
+
6
+ Never hardcode secrets. Put `GROQ_API_KEY` in `.env`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from functools import lru_cache
13
+
14
+ from dotenv import load_dotenv
15
+ from groq import Groq
16
+
17
+
18
+ @lru_cache(maxsize=1)
19
+ def get_groq_client() -> Groq:
20
+ """Create and cache a Groq client.
21
+
22
+ Raises:
23
+ RuntimeError: if GROQ_API_KEY is missing.
24
+ """
25
+
26
+ # Load .env (if present) once per process.
27
+ load_dotenv()
28
+
29
+ api_key = os.getenv("GROQ_API_KEY")
30
+ if not api_key:
31
+ raise RuntimeError(
32
+ "Missing GROQ_API_KEY. Create a .env file (see .env.example) and set GROQ_API_KEY."
33
+ )
34
+
35
+ return Groq(api_key=api_key)
graph.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LangGraph workflow.
2
+
3
+ Flow:
4
+ 1) generator
5
+ 2) reviewer
6
+ 3) if pass -> end
7
+ if fail -> generator (with feedback) -> reviewer -> end
8
+
9
+ Max one refinement pass.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any, Dict, List, TypedDict
15
+
16
+ from langgraph.graph import END, StateGraph
17
+
18
+ from agents.generator import generate_content
19
+ from agents.reviewer import review_content
20
+
21
+
22
+ class GraphState(TypedDict, total=False):
23
+ grade: int
24
+ topic: str
25
+
26
+ # initial agent outputs (first pass)
27
+ generator_output: Dict[str, Any]
28
+ reviewer_output: Dict[str, Any]
29
+
30
+ # refined outputs (only if refinement occurs)
31
+ refined_generator_output: Dict[str, Any]
32
+ refined_reviewer_output: Dict[str, Any]
33
+
34
+ # internal working values
35
+ current_generator_output: Dict[str, Any]
36
+ last_reviewer_output: Dict[str, Any]
37
+
38
+ # refinement control
39
+ refinement_used: bool
40
+ reviewer_feedback: List[str]
41
+
42
+
43
+ def generator_node(state: GraphState) -> GraphState:
44
+ grade = state["grade"]
45
+ topic = state["topic"]
46
+ feedback = state.get("reviewer_feedback") if state.get("refinement_used") else None
47
+
48
+ output = generate_content(grade=grade, topic=topic, feedback=feedback)
49
+
50
+ # Preserve the original output for the UI. Store refined output separately.
51
+ if state.get("refinement_used"):
52
+ return {
53
+ "refined_generator_output": output,
54
+ "current_generator_output": output,
55
+ }
56
+
57
+ return {
58
+ "generator_output": output,
59
+ "current_generator_output": output,
60
+ }
61
+
62
+
63
+ def reviewer_node(state: GraphState) -> GraphState:
64
+ grade = state["grade"]
65
+ topic = state["topic"]
66
+
67
+ gen_out = state["current_generator_output"]
68
+ review = review_content(grade=grade, topic=topic, generator_output=gen_out)
69
+
70
+ if state.get("refinement_used"):
71
+ return {
72
+ "refined_reviewer_output": review,
73
+ "last_reviewer_output": review,
74
+ }
75
+
76
+ return {
77
+ "reviewer_output": review,
78
+ "last_reviewer_output": review,
79
+ }
80
+
81
+
82
+ def should_refine(state: GraphState) -> str:
83
+ """Conditional edge after the first review."""
84
+
85
+ review = state["last_reviewer_output"]
86
+ status = review["status"]
87
+
88
+ if status == "pass":
89
+ return "end"
90
+
91
+ # fail
92
+ if state.get("refinement_used"):
93
+ return "end"
94
+
95
+ return "refine"
96
+
97
+
98
+ def set_refinement_context(state: GraphState) -> GraphState:
99
+ """Capture feedback and mark that we used our single refinement pass."""
100
+
101
+ feedback = state["last_reviewer_output"]["feedback"]
102
+ return {
103
+ "refinement_used": True,
104
+ "reviewer_feedback": feedback,
105
+ }
106
+
107
+
108
+ def build_graph():
109
+ graph = StateGraph(GraphState)
110
+
111
+ graph.add_node("generator", generator_node)
112
+ graph.add_node("reviewer", reviewer_node)
113
+ graph.add_node("set_refinement", set_refinement_context)
114
+
115
+ graph.set_entry_point("generator")
116
+ graph.add_edge("generator", "reviewer")
117
+
118
+ graph.add_conditional_edges(
119
+ "reviewer",
120
+ should_refine,
121
+ {
122
+ "end": END,
123
+ "refine": "set_refinement",
124
+ },
125
+ )
126
+
127
+ graph.add_edge("set_refinement", "generator")
128
+
129
+ return graph.compile()
130
+
131
+
132
+ def run_flow(*, grade: int, topic: str) -> GraphState:
133
+ """Run the full flow and return the final state for the UI."""
134
+
135
+ app = build_graph()
136
+ initial: GraphState = {
137
+ "grade": int(grade),
138
+ "topic": str(topic).strip(),
139
+ "refinement_used": False,
140
+ }
141
+
142
+ final_state = app.invoke(initial)
143
+ return final_state
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ streamlit>=1.32
2
+ python-dotenv>=1.0
3
+ langgraph>=0.2.0
4
+ groq>=0.9.0
utils/prompts.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Centralized prompts for the Generator and Reviewer agents.
2
+
3
+ All prompts live here to keep the rest of the code clean and deterministic.
4
+
5
+ We are very strict about JSON-only outputs.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from typing import Any, Dict, List, Optional
12
+
13
+
14
+ JSON_ONLY_RULES = (
15
+ "You MUST respond with valid JSON only. "
16
+ "Do NOT include markdown. Do NOT include any extra keys. "
17
+ "Do NOT add commentary outside the JSON."
18
+ )
19
+
20
+
21
+ def generator_system_prompt() -> str:
22
+ schema_example = {
23
+ "explanation": "string",
24
+ "mcqs": [
25
+ {
26
+ "question": "string",
27
+ "options": [
28
+ "Option 1 text",
29
+ "Option 2 text",
30
+ "Option 3 text",
31
+ "Option 4 text",
32
+ ],
33
+ "answer": "Option 2 text",
34
+ }
35
+ ],
36
+ }
37
+
38
+ return (
39
+ "You are the Generator Agent. Your job is to create accurate, age-appropriate educational content. "
40
+ + JSON_ONLY_RULES
41
+ + "\n\n"
42
+ + "Output schema (MUST match exactly):\n"
43
+ + json.dumps(schema_example, ensure_ascii=False)
44
+ + "\n\n"
45
+ + "Hard rules:\n"
46
+ + "- Keep language appropriate for the given grade.\n"
47
+ + "- Explanation must only cover concepts you will test in MCQs.\n"
48
+ + "- MCQs must have exactly 4 options (strings).\n"
49
+ + "- `answer` MUST be EXACTLY one of the strings in `options` (copy/paste match).\n"
50
+ + "- Do NOT return A/B/C/D as the answer unless the option text is literally 'A', 'B', 'C', or 'D'.\n"
51
+ + "- Do not vary the structure.\n"
52
+ )
53
+
54
+
55
+ def generator_user_prompt(grade: int, topic: str, feedback: Optional[List[str]] = None) -> str:
56
+ payload: Dict[str, Any] = {"grade": grade, "topic": topic}
57
+
58
+ if feedback:
59
+ payload["reviewer_feedback"] = feedback
60
+
61
+ return (
62
+ "Generate educational content for the following input (JSON):\n"
63
+ + json.dumps(payload, ensure_ascii=False)
64
+ + "\n\n"
65
+ + "If reviewer_feedback is provided, fix those issues while keeping the SAME output schema."
66
+ )
67
+
68
+
69
+ def reviewer_system_prompt() -> str:
70
+ schema_example = {
71
+ "status": "pass",
72
+ "feedback": ["Sentence 2 is too complex for Grade 4"],
73
+ }
74
+
75
+ return (
76
+ "You are the Reviewer Agent. You evaluate the Generator's JSON output. "
77
+ + JSON_ONLY_RULES
78
+ + "\n\n"
79
+ + "Output schema (MUST match exactly):\n"
80
+ + json.dumps(schema_example, ensure_ascii=False)
81
+ + "\n\n"
82
+ + "Evaluation criteria:\n"
83
+ + "- Age appropriateness for the given grade\n"
84
+ + "- Conceptual correctness\n"
85
+ + "- Clarity\n"
86
+ + "- Alignment between explanation and MCQs (MCQs must only test introduced concepts)\n"
87
+ + "\n"
88
+ + "If anything is wrong, set status='fail' and list concrete issues in feedback. "
89
+ + "If everything is good, status='pass' and feedback should be an empty list."
90
+ )
91
+
92
+
93
+ def reviewer_user_prompt(grade: int, topic: str, generator_output: Dict[str, Any]) -> str:
94
+ """Provide review context, including grade/topic, so the reviewer can judge appropriateness."""
95
+
96
+ payload = {
97
+ "grade": grade,
98
+ "topic": topic,
99
+ "generator_output": generator_output,
100
+ }
101
+
102
+ return "Review the following (JSON):\n" + json.dumps(payload, ensure_ascii=False)