agent service gets the nationality from the db

parent 6bd8732f
...@@ -8,7 +8,7 @@ RUN pip install --no-cache-dir -r requirements.txt ...@@ -8,7 +8,7 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY . . COPY . .
#just keep the container running without doing anything #just keep the container running without doing anything
#CMD ["sh", "-c", "while :; do sleep 10; done"] CMD ["sh", "-c", "while :; do sleep 10; done"]
#run the app automatically when the container starts #run the app automatically when the container starts
CMD ["python", "main.py"] #CMD ["python", "main.py"]
...@@ -70,7 +70,7 @@ def create_app() -> FastAPI: ...@@ -70,7 +70,7 @@ def create_app() -> FastAPI:
Handles incoming chat messages (either text or audio). Handles incoming chat messages (either text or audio).
Generates responses locally using the agent service. Generates responses locally using the agent service.
""" """
return container.chat_service.process_message(student_id="student_002", file=file, text=text, nationality=StudentNationality.SAUDI) return container.chat_service.process_message(student_id="student_002", file=file, text=text)
@app.get("/get-audio-response") @app.get("/get-audio-response")
async def get_audio_response(): async def get_audio_response():
......
...@@ -19,7 +19,7 @@ StudentNationality.EGYPTIAN: """ ...@@ -19,7 +19,7 @@ StudentNationality.EGYPTIAN: """
إنت مُدرّس كيميا لطفل في ابتدائي. إنت مُدرّس كيميا لطفل في ابتدائي.
رد باللهجة المصريّة الطبيعيّة. رد باللهجة المصريّة الطبيعيّة.
خلي الكلام بسيط وواضح، كفاية يوصّل الفكرة من غير تطويل. خلي الكلام بسيط وواضح، كفاية يوصّل الفكرة من غير تطويل.
الجمل تكون قصيرة نسبيًّا، بس مش ناقصة. الجمل تكون قصيرة نسبيًّا، بس مش ناقصة.
استخدم التشكيل بس على الكلمات اللي ممكن الـTTS ينطقها غلط. استخدم التشكيل بس على الكلمات اللي ممكن الـTTS ينطقها غلط.
اشرح المعلومة خطوة خطوة من غير تكرار. اشرح المعلومة خطوة خطوة من غير تكرار.
ممكن تستخدم مثال صغير أو صورة في الخيال لو ده هيساعد الطفل يفهم، مش لازم في كل مرة. ممكن تستخدم مثال صغير أو صورة في الخيال لو ده هيساعد الطفل يفهم، مش لازم في كل مرة.
...@@ -35,7 +35,7 @@ StudentNationality.EGYPTIAN: """ ...@@ -35,7 +35,7 @@ StudentNationality.EGYPTIAN: """
إنت معلّم كيميا لطفل في ابتدائي. إنت معلّم كيميا لطفل في ابتدائي.
رد باللهجة السعوديّة البسيطة. رد باللهجة السعوديّة البسيطة.
خل الكلام واضح وقصير يكفي يوصّل الفكرة. خل الكلام واضح وقصير يكفي يوصّل الفكرة.
الجمل تكون قصيرة نسبيًّا، لكن لا تكون ناقصة. الجمل تكون قصيرة نسبيًّا، لكن لا تكون ناقصة.
استخدم التشكيل بس على الكلمات اللي ممكن الـTTS يقرأها غلط. استخدم التشكيل بس على الكلمات اللي ممكن الـTTS يقرأها غلط.
اشرح المعلومة خطوة خطوة من غير تكرار. اشرح المعلومة خطوة خطوة من غير تكرار.
ممكن تضيف مثال صغير أو صورة تخيّل تساعد الطفل يفهم، بس مو لازم دائم. ممكن تضيف مثال صغير أو صورة تخيّل تساعد الطفل يفهم، بس مو لازم دائم.
...@@ -80,7 +80,6 @@ class AgentService: ...@@ -80,7 +80,6 @@ class AgentService:
self, self,
user_message: str, user_message: str,
student_id: str, student_id: str,
nationality: StudentNationality = StudentNationality.EGYPTIAN,
model: str = Models.chat, model: str = Models.chat,
temperature: float = 1.0, temperature: float = 1.0,
top_k: int = 3 top_k: int = 3
...@@ -90,13 +89,29 @@ class AgentService: ...@@ -90,13 +89,29 @@ class AgentService:
raise HTTPException(status_code=500, detail="Agent service not available") raise HTTPException(status_code=500, detail="Agent service not available")
try: try:
# Get student nationality from database
nationality_str = self.db_service.get_student_nationality(student_id)
if not nationality_str:
raise HTTPException(status_code=404, detail=f"Student with ID {student_id} not found")
# Convert database nationality to enum (handle case-insensitive conversion)
nationality_lower = nationality_str.lower().strip()
nationality_mapping = {
'egyptian': StudentNationality.EGYPTIAN,
'saudi': StudentNationality.SAUDI
}
nationality = nationality_mapping.get(nationality_lower, StudentNationality.EGYPTIAN)
if nationality_lower not in nationality_mapping:
logger.warning(f"Unknown nationality '{nationality_str}' for student {student_id}, defaulting to EGYPTIAN")
# Add user message to database # Add user message to database
self.add_message_to_history(student_id, user_message, "user") self.add_message_to_history(student_id, user_message, "user")
# Get conversation history from database # Get conversation history from database
conversation_history = self.get_conversation_history(student_id) conversation_history = self.get_conversation_history(student_id)
# Pick system prompt # Pick system prompt using the enum value
system_prompt = SYSTEM_PROMPTS.get(nationality, SYSTEM_PROMPTS[StudentNationality.EGYPTIAN]) system_prompt = SYSTEM_PROMPTS.get(nationality, SYSTEM_PROMPTS[StudentNationality.EGYPTIAN])
# Prepare messages # Prepare messages
...@@ -169,8 +184,7 @@ if __name__ == "__main__": ...@@ -169,8 +184,7 @@ if __name__ == "__main__":
try: try:
reply = agent.generate_response( reply = agent.generate_response(
"هو يعني إيه ذَرّة؟", "هو يعني إيه ذَرّة؟",
student_id="student_001", student_id="student_001"
nationality=StudentNationality.EGYPTIAN
) )
print("AI:", reply) print("AI:", reply)
except Exception as e: except Exception as e:
......
import os import os
import psycopg2 import psycopg2
from psycopg2.extras import RealDictCursor from psycopg2.extras import RealDictCursor
from typing import List, Dict from typing import List, Dict, Optional
import logging import logging
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -18,6 +18,16 @@ class ChatDatabaseService: ...@@ -18,6 +18,16 @@ class ChatDatabaseService:
dbname=os.getenv("POSTGRES_DB"), dbname=os.getenv("POSTGRES_DB"),
) )
def get_student_nationality(self, student_id: str) -> Optional[str]:
"""Get student nationality from database"""
with self.conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(
"SELECT nationality FROM students WHERE student_id = %s",
(student_id,)
)
result = cur.fetchone()
return result["nationality"] if result else None
def get_chat_history(self, student_id: str, limit: int = 20) -> List[Dict[str, str]]: def get_chat_history(self, student_id: str, limit: int = 20) -> List[Dict[str, str]]:
"""Get chat history for a student, returns in chronological order""" """Get chat history for a student, returns in chronological order"""
with self.conn.cursor(cursor_factory=RealDictCursor) as cur: with self.conn.cursor(cursor_factory=RealDictCursor) as cur:
......
...@@ -34,8 +34,7 @@ class ChatService: ...@@ -34,8 +34,7 @@ class ChatService:
def process_message(self, def process_message(self,
student_id: str, student_id: str,
file: Optional[UploadFile] = None, file: Optional[UploadFile] = None,
text: Optional[str] = None, text: Optional[str] = None):
nationality: StudentNationality = StudentNationality.EGYPTIAN) -> dict:
"""Process message for student using database memory""" """Process message for student using database memory"""
self.response_manager.clear_response() self.response_manager.clear_response()
...@@ -62,7 +61,6 @@ class ChatService: ...@@ -62,7 +61,6 @@ class ChatService:
agent_response = self.agent_service.generate_response( agent_response = self.agent_service.generate_response(
user_message=user_message, user_message=user_message,
student_id=student_id, student_id=student_id,
nationality=nationality
) )
# Generate TTS audio # Generate TTS audio
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment