Benny-Tang commited on
Commit
b3687e7
·
verified ·
1 Parent(s): e14bed5

Update agents.py

Browse files
Files changed (1) hide show
  1. agents.py +26 -126
agents.py CHANGED
@@ -1,139 +1,39 @@
1
- # agents.py
2
  import os
3
  import random
4
- from collections import Counter
5
- from typing import List, Dict, Any
6
-
7
- # Accept either env var name
8
- GLM_API_KEY = os.getenv("ZHIPUAI_API_KEY") or os.getenv("zhipuai_api_key")
9
 
 
 
10
 
11
  class AnalyzerAgent:
12
- def analyze(self, per_question: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
13
- topic_stats = {}
14
- for qid, info in per_question.items():
15
- topics = info.get("topics") or []
16
- user = info.get("user")
17
- correct = info.get("correct")
18
- is_correct = (correct is not None and user is not None and str(user).strip() == str(correct).strip())
19
- for t in topics:
20
- if t not in topic_stats:
21
- topic_stats[t] = {"correct": 0, "total": 0}
22
- topic_stats[t]["total"] += 1
23
- if is_correct:
24
- topic_stats[t]["correct"] += 1
25
-
26
- topic_accuracy = {}
27
- weak_topics = []
28
- for t, stats in topic_stats.items():
29
- total = stats["total"]
30
- acc = round((stats["correct"] / total) * 100, 2) if total > 0 else 0.0
31
- topic_accuracy[t] = {"accuracy_percent": acc, "total": total}
32
- if total >= 3 and acc < 65.0:
33
- weak_topics.append(t)
34
-
35
- recommendation = "Focus on: " + ", ".join(weak_topics) if weak_topics else "No major weak topics detected."
36
-
37
- return {"topic_accuracy": topic_accuracy, "weak_topics": weak_topics, "recommendation": recommendation}
38
-
39
 
40
  class CoachAgent:
41
- def coach(self, analysis: Dict[str, Any], level: str, subject: str) -> Dict[str, Any]:
42
- weak = analysis.get("weak_topics", [])
43
- if not weak:
44
- tips = [
45
- "Revise key topics and practice mixed mock papers.",
46
- "Time yourself when attempting past papers.",
47
- "Review incorrect answers and understand mistakes."
48
- ]
49
- else:
50
- tips = [
51
- f"Focus 20–30 minutes daily on {weak[0]}. Break it to small tasks.",
52
- "Practice targeted short questions and review solutions.",
53
- "Explain topics to a peer to strengthen memory."
54
- ]
55
-
56
- practice = []
57
- for t in weak[:3]:
58
- practice.append({"text": f"Practice task on {t}", "topic": t})
59
-
60
- return {"tips": tips, "study_plan": "20 min/day weak topics + weekly full mock", "practice": practice}
61
-
62
 
63
  class PredictiveAgent:
64
- def __init__(self):
65
- self.api_key = GLM_API_KEY
66
-
67
- def _top_topics(self, question_bank: List[Dict], subject: str, k=6):
68
- subj_key = f"Form5_{subject}"
69
- counter = Counter()
70
- for q in question_bank:
71
- if q.get("subject") != subj_key:
72
- continue
73
- for t in q.get("topics", []):
74
- counter[t] += 1
75
- return [t for t, _ in counter.most_common(k)]
76
-
77
- def generate_predictions(self, level: str, subject: str, n: int = 5, question_bank: List[Dict] = None) -> List[Dict]:
78
- preds = []
79
- base = 900000
80
- topics = self._top_topics(question_bank or [], subject) if question_bank else []
81
- if not topics:
82
- fallback = {
83
- "BM": ["perbendaharaan_kata", "tatabahasa"],
84
- "English": ["vocabulary", "grammar"],
85
- "Math": ["algebra", "geometry"],
86
- "History": ["events", "dates"],
87
- "Science": ["physics", "chemistry"],
88
- "MoralStudies": ["ethics", "values"]
89
- }
90
- topics = fallback.get(subject, ["general"])
91
-
92
- # Not calling GLM here by default; heuristics used. If you want GLM, we can wire it (needs API + endpoint)
93
- for i in range(n):
94
- topic = topics[i % len(topics)]
95
- q = self._heuristic(subject, topic, i + 1)
96
- q["id"] = base + i
97
- q["source"] = "predicted"
98
- q["confidence"] = round(random.uniform(0.35, 0.75), 2)
99
- preds.append(q)
100
- return preds
101
-
102
- def _heuristic(self, subject: str, topic: str, idx: int) -> Dict:
103
- if subject == "BM":
104
- text = "Pilih sinonim bagi perkataan 'gembira'."
105
- choices = ["Sedih", "Gembira", "Marah", "Letih"]
106
- correct = "Gembira"
107
- elif subject == "English":
108
- text = "Choose the correct synonym for 'happy'."
109
- choices = ["Sad", "Joyful", "Angry", "Tired"]
110
- correct = "Joyful"
111
- elif subject == "Math":
112
- text = "If 2x + 3 = 11, what is x?"
113
- choices = ["2", "3", "4", "5"]
114
- correct = "4"
115
- elif subject == "Science":
116
- text = "What is the SI unit of force?"
117
- choices = ["Joule", "Newton", "Pascal", "Watt"]
118
- correct = "Newton"
119
- elif subject == "History":
120
- text = "Which year is associated with Malayan independence?"
121
- choices = ["1945", "1957", "1963", "1975"]
122
- correct = "1957"
123
- elif subject == "MoralStudies":
124
- text = "Which value best represents mutual respect?"
125
- choices = ["Greed", "Respect", "Laziness", "Selfishness"]
126
- correct = "Respect"
127
- else:
128
- text = f"Practice question on {topic}."
129
- choices = ["A", "B", "C", "D"]
130
- correct = "A"
131
-
132
- return {"text": text, "choices": choices, "correct_answer": correct, "topics": [topic], "difficulty": 3}
133
 
134
- def summary(self, level: str, subject: str, question_bank: List[Dict] = None) -> Dict:
135
- topics = self._top_topics(question_bank or [], subject) if question_bank else []
136
- return {"level": level, "subject": subject, "top_topics": topics, "note": "Heuristic predictions — for practice only."}
137
 
138
 
139
 
 
 
1
  import os
2
  import random
3
+ from zhipuai import ZhipuAI
 
 
 
 
4
 
5
+ API_KEY = os.getenv("zhipuai_api_key")
6
+ client = ZhipuAI(api_key=API_KEY)
7
 
8
  class AnalyzerAgent:
9
+ def analyze(self, answers, correct_answers):
10
+ score = 0
11
+ feedback = []
12
+ for qid, user_ans in answers.items():
13
+ if user_ans == correct_answers.get(qid):
14
+ score += 1
15
+ else:
16
+ feedback.append(f"Q{qid}: Correct was {correct_answers.get(qid)}")
17
+ return score, feedback
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  class CoachAgent:
20
+ def give_feedback(self, feedback):
21
+ if not feedback:
22
+ return "Excellent! You answered all correctly."
23
+ return "Review these: " + "; ".join(feedback)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  class PredictiveAgent:
26
+ def predict_questions(self, past_questions, subject):
27
+ """
28
+ Use GLM4.5 to predict potential questions based on past trends.
29
+ """
30
+ prompt = f"Analyze these past SPM {subject} questions and predict possible future ones:\n{past_questions[:1000]}"
31
+ resp = client.chat.completions.create(
32
+ model="glm-4-5",
33
+ messages=[{"role": "user", "content": prompt}]
34
+ )
35
+ return resp.choices[0].message["content"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
 
 
 
37
 
38
 
39