agent service gets the nationality from the db

parent 6bd8732f
......@@ -8,7 +8,7 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY . .
#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
CMD ["python", "main.py"]
#CMD ["python", "main.py"]
......@@ -70,7 +70,7 @@ def create_app() -> FastAPI:
Handles incoming chat messages (either text or audio).
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")
async def get_audio_response():
......
......@@ -19,7 +19,7 @@ StudentNationality.EGYPTIAN: """
إنت مُدرّس كيميا لطفل في ابتدائي.
رد باللهجة المصريّة الطبيعيّة.
خلي الكلام بسيط وواضح، كفاية يوصّل الفكرة من غير تطويل.
الجمل تكون قصيرة نسبيًّا، بس مش ناقصة.
الجمل تكون قصيرة نسبيًّا، بس مش ناقصة.
استخدم التشكيل بس على الكلمات اللي ممكن الـTTS ينطقها غلط.
اشرح المعلومة خطوة خطوة من غير تكرار.
ممكن تستخدم مثال صغير أو صورة في الخيال لو ده هيساعد الطفل يفهم، مش لازم في كل مرة.
......@@ -35,7 +35,7 @@ StudentNationality.EGYPTIAN: """
إنت معلّم كيميا لطفل في ابتدائي.
رد باللهجة السعوديّة البسيطة.
خل الكلام واضح وقصير يكفي يوصّل الفكرة.
الجمل تكون قصيرة نسبيًّا، لكن لا تكون ناقصة.
الجمل تكون قصيرة نسبيًّا، لكن لا تكون ناقصة.
استخدم التشكيل بس على الكلمات اللي ممكن الـTTS يقرأها غلط.
اشرح المعلومة خطوة خطوة من غير تكرار.
ممكن تضيف مثال صغير أو صورة تخيّل تساعد الطفل يفهم، بس مو لازم دائم.
......@@ -80,7 +80,6 @@ class AgentService:
self,
user_message: str,
student_id: str,
nationality: StudentNationality = StudentNationality.EGYPTIAN,
model: str = Models.chat,
temperature: float = 1.0,
top_k: int = 3
......@@ -90,13 +89,29 @@ class AgentService:
raise HTTPException(status_code=500, detail="Agent service not available")
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
self.add_message_to_history(student_id, user_message, "user")
# Get conversation history from database
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])
# Prepare messages
......@@ -169,8 +184,7 @@ if __name__ == "__main__":
try:
reply = agent.generate_response(
"هو يعني إيه ذَرّة؟",
student_id="student_001",
nationality=StudentNationality.EGYPTIAN
student_id="student_001"
)
print("AI:", reply)
except Exception as e:
......
import os
import psycopg2
from psycopg2.extras import RealDictCursor
from typing import List, Dict
from typing import List, Dict, Optional
import logging
logger = logging.getLogger(__name__)
......@@ -18,6 +18,16 @@ class ChatDatabaseService:
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]]:
"""Get chat history for a student, returns in chronological order"""
with self.conn.cursor(cursor_factory=RealDictCursor) as cur:
......
......@@ -34,8 +34,7 @@ class ChatService:
def process_message(self,
student_id: str,
file: Optional[UploadFile] = None,
text: Optional[str] = None,
nationality: StudentNationality = StudentNationality.EGYPTIAN) -> dict:
text: Optional[str] = None):
"""Process message for student using database memory"""
self.response_manager.clear_response()
......@@ -62,7 +61,6 @@ class ChatService:
agent_response = self.agent_service.generate_response(
user_message=user_message,
student_id=student_id,
nationality=nationality
)
# 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