Skip to content

Commit 45fca49

Browse files
committed
fix promttecher
1 parent 64ad434 commit 45fca49

2 files changed

Lines changed: 107 additions & 2 deletions

File tree

courseservice/routes/learning_path_routes.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,8 +226,8 @@ def generate_teacher_recommendations(course_id):
226226
# Tạo prompt cho teacher recommendations
227227
prompt = create_teacher_recommendations_prompt(explanations, course_id)
228228

229-
# Gọi Gemini AI
230-
recommendations = gemini_service.generate_explanation(prompt)
229+
# Gọi Gemini AI cho teacher recommendations
230+
recommendations = gemini_service.generate_teacher_recommendations(prompt)
231231

232232
if recommendations:
233233
# Lưu teacher recommendations

courseservice/services/gemini_service.py

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,94 @@ def generate_explanation(self, prompt: str) -> dict:
124124
except Exception as e:
125125
logger.error(f"Error calling Gemini API: {e}")
126126
return self._get_fallback_explanation()
127+
128+
def generate_teacher_recommendations(self, prompt: str) -> dict:
129+
"""Generate teacher recommendations using Gemini AI - separate method for teachers"""
130+
try:
131+
if not self.api_key:
132+
logger.warning("Gemini API key not found")
133+
return self._get_teacher_fallback()
134+
135+
headers = {
136+
'x-goog-api-key': self.api_key,
137+
'Content-Type': 'application/json'
138+
}
139+
140+
# Use original prompt without modification for teachers
141+
payload = {
142+
"contents": [
143+
{
144+
"role": "user",
145+
"parts": [
146+
{"text": prompt}
147+
]
148+
}
149+
],
150+
"generationConfig": {
151+
"temperature": 0.7,
152+
"topK": 40,
153+
"topP": 0.95,
154+
"maxOutputTokens": 2048,
155+
"candidateCount": 1
156+
}
157+
}
158+
159+
response = requests.post(
160+
self.api_url,
161+
headers=headers,
162+
json=payload,
163+
timeout=25
164+
)
165+
166+
if response.status_code == 200:
167+
result = response.json()
168+
169+
if 'candidates' in result and len(result['candidates']) > 0:
170+
candidate = result['candidates'][0]
171+
172+
# Check finish reason
173+
finish_reason = candidate.get('finishReason', '')
174+
if finish_reason == 'MAX_TOKENS':
175+
logger.warning("Teacher recommendations response was truncated due to MAX_TOKENS")
176+
177+
# Extract text with better error handling
178+
generated_text = None
179+
if 'content' in candidate:
180+
content = candidate['content']
181+
if 'parts' in content and len(content['parts']) > 0:
182+
generated_text = content['parts'][0].get('text', '')
183+
184+
if not generated_text:
185+
logger.error("No text found in teacher recommendations response")
186+
return self._get_teacher_fallback()
187+
188+
# Extract JSON from response
189+
try:
190+
json_start = generated_text.find('{')
191+
json_end = generated_text.rfind('}') + 1
192+
193+
if json_start >= 0 and json_end > json_start:
194+
json_str = generated_text[json_start:json_end]
195+
teacher_data = json.loads(json_str)
196+
return teacher_data
197+
else:
198+
# If no JSON found, return fallback
199+
logger.warning("No JSON found in teacher recommendations response")
200+
return self._get_teacher_fallback()
201+
202+
except json.JSONDecodeError as e:
203+
logger.error(f"Failed to parse JSON from teacher recommendations: {e}")
204+
return self._get_teacher_fallback()
205+
else:
206+
logger.error("No candidates in teacher recommendations response")
207+
return self._get_teacher_fallback()
208+
else:
209+
logger.error(f"Teacher recommendations API error: {response.status_code} - {response.text}")
210+
return self._get_teacher_fallback()
211+
212+
except Exception as e:
213+
logger.error(f"Error calling Gemini API for teacher recommendations: {e}")
214+
return self._get_teacher_fallback()
127215

128216
def _get_fallback_explanation(self) -> dict:
129217
"""Fallback explanation when AI is not available"""
@@ -139,5 +227,22 @@ def _get_fallback_explanation(self) -> dict:
139227
]
140228
}
141229

230+
def _get_teacher_fallback(self) -> dict:
231+
"""Fallback teacher recommendations when AI is not available"""
232+
return {
233+
"class_overview": "Lớp học có tình hình đa dạng, cần điều chỉnh phương pháp giảng dạy phù hợp.",
234+
"main_challenges": "Học sinh có trình độ không đồng đều, cần hỗ trợ cá nhân hóa.",
235+
"teaching_suggestions": [
236+
"Tạo nhóm học tập theo trình độ",
237+
"Cung cấp bài tập bổ sung cho học sinh yếu",
238+
"Thiết kế thử thách cho học sinh giỏi"
239+
],
240+
"priority_actions": [
241+
"Xác định học sinh cần hỗ trợ thêm",
242+
"Tăng cường feedback trong quá trình học"
243+
],
244+
"motivation": "Hãy kiên nhẫn! Mỗi học sinh đều có tiềm năng phát triển."
245+
}
246+
142247
# Singleton instance
143248
gemini_service = GeminiService()

0 commit comments

Comments
 (0)