sp103107 commited on
Commit
3208104
·
verified ·
1 Parent(s): 0f7c973

Upload folder using huggingface_hub

Browse files
__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Package initializer."""
__pycache__/__init__.cpython-311.pyc ADDED
Binary file (210 Bytes). View file
 
__pycache__/admissions_agent.cpython-311.pyc ADDED
Binary file (5.94 kB). View file
 
__pycache__/prompts.cpython-311.pyc ADDED
Binary file (3.45 kB). View file
 
__pycache__/utils.cpython-311.pyc ADDED
Binary file (3.72 kB). View file
 
admissions_agent.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ admissions_agent.py
3
+ -------------------
4
+ AdmissionsAgent class for the NORA project, configured to use Google Gemini as the LLM backend.
5
+
6
+ Responsibilities:
7
+ - Review applicants using a prompt-engineered query
8
+ - Score applicants across weighted criteria
9
+ - Store reviews in memory for ranking
10
+ - Provide explanations for applicant scores
11
+ """
12
+
13
+ import os
14
+ import json
15
+ from dotenv import load_dotenv
16
+ import google.generativeai as genai
17
+ from agent.prompts import build_prompt
18
+ from agent.utils import parse_response, rank_applicants
19
+
20
+ # Load environment variables from .env file
21
+ load_dotenv()
22
+
23
+
24
+ class AdmissionsAgent:
25
+ """
26
+ AdmissionsAgent using Google Gemini for application evaluation.
27
+
28
+ Attributes
29
+ ----------
30
+ model : str
31
+ The Gemini model used for evaluation (default: "gemini-pro").
32
+ client : GenerativeModel
33
+ Gemini model client instance used to generate responses.
34
+ reviews : list
35
+ Memory of all reviewed applicants for ranking and explanations.
36
+ """
37
+
38
+ def __init__(self, model: str = "gemini-1.5-flash"):
39
+ """
40
+ Initialize the AdmissionsAgent with Gemini model.
41
+
42
+ Parameters
43
+ ----------
44
+ model : str, optional
45
+ The Gemini model name to use (default is "gemini-pro").
46
+
47
+ Raises
48
+ ------
49
+ ValueError
50
+ If GOOGLE_API_KEY is not set in environment variables.
51
+ """
52
+ if not os.getenv("GOOGLE_API_KEY"):
53
+ raise ValueError("❌ GOOGLE_API_KEY is not set. Please set it as an environment variable.")
54
+
55
+ self.model = model
56
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
57
+ self.client = genai.GenerativeModel(self.model)
58
+ self.reviews = []
59
+
60
+ def review_applicant(self, applicant: dict) -> dict:
61
+ """
62
+ Review a single applicant using Gemini and return structured results.
63
+
64
+ Parameters
65
+ ----------
66
+ applicant : dict
67
+ Dictionary containing applicant data (name, gpa, sat, activities, essay, recommendation).
68
+
69
+ Returns
70
+ -------
71
+ dict
72
+ Structured review containing:
73
+ - Scores for each category
74
+ - Total score
75
+ - Summary explanation
76
+ """
77
+ # 1️⃣ Build the master prompt with applicant data
78
+ prompt = build_prompt(applicant)
79
+
80
+ # 2️⃣ Call Gemini API with a controlled temperature
81
+ response = self.client.generate_content(
82
+ prompt,
83
+ generation_config={"temperature": 0.3}
84
+ )
85
+
86
+ # 3️⃣ Extract text safely (Gemini sometimes uses candidates array)
87
+ response_text = getattr(response, "text", None)
88
+ if not response_text and hasattr(response, "candidates") and response.candidates:
89
+ try:
90
+ response_text = response.candidates[0].content.parts[0].text
91
+ except (AttributeError, IndexError):
92
+ response_text = None
93
+
94
+ # 4️⃣ Parse JSON output from Gemini response
95
+ review = parse_response(response_text)
96
+
97
+ # 5️⃣ Store review in memory for later ranking/explanation
98
+ self.add_applicant_memory({"name": applicant.get("name", "Unknown"), **review})
99
+
100
+ return review
101
+
102
+ def rank_all(self) -> list:
103
+ """
104
+ Rank all reviewed applicants by total_score (descending).
105
+
106
+ Returns
107
+ -------
108
+ list
109
+ A sorted list of reviewed applicants, highest to lowest score.
110
+ """
111
+ return rank_applicants(self.reviews)
112
+
113
+ def explain_scoring(self, applicant_name: str) -> str:
114
+ """
115
+ Provide a plain-English explanation of why an applicant scored the way they did.
116
+
117
+ Parameters
118
+ ----------
119
+ applicant_name : str
120
+ The name of the applicant to explain.
121
+
122
+ Returns
123
+ -------
124
+ str
125
+ A short explanation summary of the applicant’s review, or an error if not found.
126
+ """
127
+ for review in self.reviews:
128
+ if review.get("name") == applicant_name:
129
+ return review.get("summary", "No summary available.")
130
+ return f"No applicant found with the name {applicant_name}."
131
+
132
+ def add_applicant_memory(self, review: dict):
133
+ """
134
+ Store an applicant review in memory.
135
+
136
+ Parameters
137
+ ----------
138
+ review : dict
139
+ Parsed JSON review dictionary to store.
140
+ """
141
+ self.reviews.append(review)
prompts.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ prompts.py
3
+ ----------
4
+ Holds the MASTER_PROMPT and prompt builder function for the NORA project.
5
+
6
+ Responsibilities:
7
+ - Define MASTER_PROMPT (Gemini instructions)
8
+ - Provide a build_prompt() function to dynamically inject applicant data
9
+ """
10
+
11
+ # =========================
12
+ # MASTER_PROMPT Definition
13
+ # =========================
14
+
15
+ MASTER_PROMPT = """You are NORA, Northeastern University’s Admissions Assistant AI.
16
+ Your job is to evaluate student applications for the admissions team.
17
+ You score applicants holistically, considering academics, activities, essays, and recommendations.
18
+ You are professional, impartial, and provide transparent reasoning for every score.
19
+
20
+ For each applicant, evaluate the following categories on a scale of 1–10:
21
+ - Academics (40%)
22
+ - Activities & Leadership (25%)
23
+ - Essay/Personal Statement (20%)
24
+ - Recommendations (15%)
25
+
26
+ Give:
27
+ 1. A score from 1–10 for each category.
28
+ 2. A one-sentence justification for each score.
29
+ 3. A weighted total score (1–10).
30
+ 4. A 2–3 sentence summary of why the applicant received that score.
31
+
32
+ Return ONLY valid JSON.
33
+ Do NOT include any extra text, explanations, or markdown formatting.
34
+ Use this exact structure:
35
+ {
36
+ "name": "<applicant name>",
37
+ "scores": {
38
+ "academics": {"score": X, "justification": "<reason>"},
39
+ "activities": {"score": X, "justification": "<reason>"},
40
+ "essay": {"score": X, "justification": "<reason>"},
41
+ "recommendations": {"score": X, "justification": "<reason>"}
42
+ },
43
+ "total_score": X.X,
44
+ "summary": "<2–3 sentence overall summary>"
45
+ }
46
+
47
+ Use the following guidelines for scoring each category:
48
+ - 10 = Exceptional (e.g., 4.0 GPA, national awards, essay is inspiring and original)
49
+ - 8–9 = Very strong (e.g., excellent academics and leadership)
50
+ - 5–7 = Average to solid (meets standard expectations, room for growth)
51
+ - 3–4 = Weak (limited engagement, mediocre writing)
52
+ - 1–2 = Poor (lacking evidence of effort, very low academics)"""
53
+
54
+ # =========================
55
+ # Helper Function
56
+ # =========================
57
+
58
+ def build_prompt(applicant: dict) -> str:
59
+ """
60
+ Build the final prompt for Gemini by merging the MASTER_PROMPT
61
+ with the applicant’s details.
62
+
63
+ Parameters
64
+ ----------
65
+ applicant : dict
66
+ Dictionary with keys like 'name', 'gpa', 'sat', 'activities', 'essay', and 'recommendation'.
67
+
68
+ Returns
69
+ -------
70
+ str
71
+ A formatted prompt string for Gemini.
72
+ """
73
+ applicant_text = f"Applicant Name: {applicant.get('name', 'Unknown')}\n"
74
+ applicant_text += f"GPA: {applicant.get('gpa', 'N/A')}\n"
75
+ applicant_text += f"SAT/ACT: {applicant.get('sat', 'N/A')}\n"
76
+ applicant_text += f"Activities: {applicant.get('activities', 'None listed')}\n"
77
+ applicant_text += f"Essay: {applicant.get('essay', 'No essay provided')}\n"
78
+ applicant_text += f"Recommendation: {applicant.get('recommendation', 'No recommendation provided')}\n"
79
+
80
+ return MASTER_PROMPT + "\n\nHere is the applicant data to review:\n" + applicant_text
utils.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ utils.py
3
+ --------
4
+ Utility functions for the NORA Admissions Agent project.
5
+
6
+ Responsibilities:
7
+ - parse_response: Safely parse JSON from Gemini’s response
8
+ - rank_applicants: Sort applicants by total score
9
+ - clean_json_text: Sanitize malformed JSON text (e.g., remove code fences)
10
+ """
11
+
12
+ import json
13
+ from typing import List, Dict
14
+
15
+ def parse_response(response_text: str) -> Dict:
16
+ """
17
+ Safely parse the JSON output from Gemini.
18
+
19
+ The LLM is instructed to return strict JSON, but in case of formatting
20
+ issues (extra text, markdown, etc.), this function attempts to handle errors
21
+ gracefully.
22
+
23
+ Parameters
24
+ ----------
25
+ response_text : str
26
+ The raw response text from Gemini.
27
+
28
+ Returns
29
+ -------
30
+ dict
31
+ A parsed JSON dictionary, or an error dictionary if parsing fails.
32
+
33
+ Example
34
+ -------
35
+ >>> parse_response('{"name": "Anna", "total_score": 9.2}')
36
+ {'name': 'Anna', 'total_score': 9.2}
37
+ """
38
+ # Handle None or empty input
39
+ if response_text is None:
40
+ return {"error": "Could not parse JSON", "raw_response": None}
41
+
42
+ if not response_text.strip():
43
+ return {"error": "Could not parse JSON", "raw_response": ""}
44
+
45
+ try:
46
+ return json.loads(response_text)
47
+ except json.JSONDecodeError:
48
+ cleaned = clean_json_text(response_text)
49
+ try:
50
+ return json.loads(cleaned)
51
+ except json.JSONDecodeError:
52
+ return {"error": "Could not parse JSON", "raw_response": response_text}
53
+
54
+ def rank_applicants(reviews: List[Dict]) -> List[Dict]:
55
+ """
56
+ Rank all applicants based on their total_score from highest to lowest.
57
+
58
+ Parameters
59
+ ----------
60
+ reviews : list of dict
61
+ List of applicant review dictionaries with 'total_score' key.
62
+
63
+ Returns
64
+ -------
65
+ list of dict
66
+ Sorted list of applicants.
67
+
68
+ Example
69
+ -------
70
+ >>> rank_applicants([{"name": "A", "total_score": 8.5}, {"name": "B", "total_score": 9.0}])
71
+ [{'name': 'B', 'total_score': 9.0}, {'name': 'A', 'total_score': 8.5}]
72
+ """
73
+ return sorted(reviews, key=lambda x: x.get("total_score", 0), reverse=True)
74
+
75
+ def clean_json_text(text: str) -> str:
76
+ """
77
+ Attempt to clean up malformed JSON text by:
78
+ - Removing markdown code fences
79
+ - Stripping extraneous whitespace
80
+
81
+ Parameters
82
+ ----------
83
+ text : str
84
+ The raw text from Gemini.
85
+
86
+ Returns
87
+ -------
88
+ str
89
+ A cleaned string that is more likely to parse as JSON.
90
+ """
91
+ cleaned = text.strip()
92
+ # Remove triple backticks and 'json' code block indicators if present
93
+ if cleaned.startswith("```"):
94
+ cleaned = cleaned.replace("```json", "").replace("```", "")
95
+ return cleaned.strip()