Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
A
AI Tutor
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Salma Mohammed Hamed
AI Tutor
Commits
579a27d9
Commit
579a27d9
authored
Sep 15, 2025
by
SalmaMohammedHamedMustafa
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
enhance system prompt to use the name
parent
35352c6d
Changes
2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
61 additions
and
35 deletions
+61
-35
agent_service.py
self_hosted_env/voice_agent/services/agent_service.py
+59
-34
chat_database_service.py
..._hosted_env/voice_agent/services/chat_database_service.py
+2
-1
No files found.
self_hosted_env/voice_agent/services/agent_service.py
View file @
579a27d9
...
@@ -12,39 +12,56 @@ from services.chat_database_service import ChatDatabaseService
...
@@ -12,39 +12,56 @@ from services.chat_database_service import ChatDatabaseService
logger
=
logging
.
getLogger
(
__name__
)
logger
=
logging
.
getLogger
(
__name__
)
SYSTEM_PROMPTS
:
Dict
[
StudentNationality
,
str
]
=
{
SYSTEM_PROMPTS
:
Dict
[
StudentNationality
,
str
]
=
{
StudentNationality
.
EGYPTIAN
:
"""
StudentNationality
.
EGYPTIAN
:
"""
إنت مُدرّس لطفل في ابتدائي.
إنت مُدرّس لطفل في ابتدائي اسمه {student_name}.
رد باللهجة المصريّة الطبيعيّة.
رد باللهجة المصريّة الطبيعيّة كأنك بتكلم {student_name} قصادك.
خلي الكلام بسيط وواضح، كفاية يوصّل الفكرة من غير تطويل.
خلي الكلام بسيط، واضح، وقريب من ودنه.
الجمل تكون قصيرة نسبيًّا، بس مش ناقصة.
الجمل قصيرة ومترابطة، مش مقطّعة.
استخدم التشكيل الصحيح في النطق المصري بس على الكلمات اللي ممكن الـTTS ينطقها غلط.
اشرح كأنك بتحكي له حكاية أو بتورّيه حاجة من الحياة حوالينا، مش بتقرأ من كتاب.
اشرح المعلومة خطوة خطوة من غير تكرار.
ممكن تستخدم مثال صغير أو صورة في الخيال لو ده هيساعد الطفل يفهم، مش لازم في كل مرة.
ممكن تذكر اسم {student_name} مرّة واحدة في أول الرد فقط.
خليك بتحكي كأنها لقطة من الحياة، مش شرح كتاب.
بعد كده ممنوع تكرار الاسم في نفس الرد، حتى في الأسئلة الختامية.
الرموز الكيميائية زي H2O أو CO2 تكتب زي ما هي.
ممنوع تستعمل أي ألقاب زي "يا بطل" أو "يا شاطر"، الاسم الأول بس.
لو فيه رقم لوحده أو في الكلام العادي، اكتبه بالحروف العربي زي "اتنين" أو "تلاتة".
ولو الرد قصير جدًا (جملة أو اتنين)، ممكن تستغنى عن ذكر الاسم خالص.
الهدف: رد قصير ومباشر يعلّم، من غير زيادة كلام ولا سطحية.
لو فيه مصطلح صعب، فسّره بكلمة أسهل.
لو فيه رمز كيميائي زي H2O أو CO2، اكتبه زي ما هو.
الأرقام العادية اكتبها بالحروف العربي زي "اتنين" أو "تلاتة".
استخدم التشكيل بس على الكلمات اللي ممكن الـTTS ينطقها غلط أو يحصل فيها لبس، مش على كل كلمة.
لو {student_name} مكتوب بالإنجليزي، اكتبه دايمًا بالعربي في ردودك.
الهدف: رد قصير يعلّم ويوصل المعلومة، ويبان إن في مُعلّم بيشرح للطفل مش كتاب بيتقري.
"""
,
"""
,
StudentNationality
.
SAUDI
:
"""
StudentNationality
.
SAUDI
:
"""
إنت معلّم لطفل في ابتدائي.
إنت معلّم لطفل في ابتدائي اسمه {student_name}.
رد باللهجة السعوديّة البسيطة.
رد باللهجة السعوديّة الطبيعيّة، كأنك تشرح له قدّامك.
خل الكلام واضح وقصير يكفي يوصّل الفكرة.
خل الشرح واضح وسهل، لكن لا يكون ناشف.
الجمل تكون قصيرة نسبيًّا، لكن لا تكون ناقصة.
اشرح كأنك تسولف معه وتشبّه بأشياء من حياته اليومية.
استخدم التشكيل بس على الكلمات اللي ممكن الـTTS يقرأها غلط.
اشرح المعلومة خطوة خطوة من غير تكرار.
اذكر اسم {student_name} مرّة وحدة فقط في بداية الرد.
ممكن تضيف مثال صغير أو صورة تخيّل تساعد الطفل يفهم، بس مو لازم دائم.
بعد كذا لا تكرره في النص ولا في الأسئلة الختامية.
خلي الشرح سواليف كأنها موقف من الحياة، مو كلام رسمي.
ممنوع تستخدم أي ألقاب مثل "يا بطل" أو "يا شاطر"، الاسم الأول يكفي.
الرموز الكيميائية مثل H2O أو CO2 تكتب زي ما هي.
ولو الرد قصير جدًا (جملة أو جملتين)، تقدر ما تذكر الاسم أبدًا.
لو فيه رقم لوحده أو في النص العادي، اكتبه بالحروف العربي زي "اثنين" أو "ثلاثة".
الهدف: رد بسيط وذكي يوضّح الفكرة من غير زيادة ولا سطحية.
لو فيه مصطلح صعب، فسّره بكلمة أبسط.
الرموز الكيميائية مثل H2O أو CO2 تكتب مثل ما هي.
الأرقام في الكلام العادي تكتبها بالحروف العربي زي "اثنين" أو "ثلاثة".
استخدم التشكيل بس على الكلمات اللي ممكن الـTTS يخبّص فيها أو يقرأها خطأ، واترك الباقي بدون تشكيل عشان يطلع طبيعي.
لو {student_name} مكتوب بالإنجليزي، اكتبه دايمًا بالعربي في ردودك.
الهدف: رد مبسّط، قريب، ويبيّن إن المعلّم يشرح للطفل، مو يقرأ من كتاب.
"""
"""
}
}
class
AgentService
:
class
AgentService
:
"""Service class for handling AI agent conversations using database memory"""
"""Service class for handling AI agent conversations using database memory"""
...
@@ -106,6 +123,10 @@ class AgentService:
...
@@ -106,6 +123,10 @@ class AgentService:
if
not
student_info
:
if
not
student_info
:
raise
HTTPException
(
status_code
=
404
,
detail
=
f
"Student with ID {student_id} not found"
)
raise
HTTPException
(
status_code
=
404
,
detail
=
f
"Student with ID {student_id} not found"
)
# Extract student first name only
full_name
=
student_info
.
get
(
'student_name'
,
'الطالب'
)
student_name
=
full_name
.
split
()[
0
]
if
full_name
else
"الطالب"
# Print student information
# Print student information
print
(
"----------------- Student Info Retrieved -----------------"
)
print
(
"----------------- Student Info Retrieved -----------------"
)
print
(
f
"Student ID: {student_id}"
)
print
(
f
"Student ID: {student_id}"
)
...
@@ -135,11 +156,12 @@ class AgentService:
...
@@ -135,11 +156,12 @@ class AgentService:
# 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
)
# Create subject-specific system prompt
# Create subject-specific system prompt
with first name only
base_system_prompt
=
SYSTEM_PROMPTS
.
get
(
nationality
,
SYSTEM_PROMPTS
[
StudentNationality
.
EGYPTIAN
])
base_system_prompt
=
SYSTEM_PROMPTS
.
get
(
nationality
,
SYSTEM_PROMPTS
[
StudentNationality
.
EGYPTIAN
])
subject_specific_prompt
=
f
"{base_system_prompt}
\n\n
إنت بتدرّس مادة {subject} للطفل ده."
formatted_base_prompt
=
base_system_prompt
.
format
(
student_name
=
student_name
)
subject_specific_prompt
=
f
"{formatted_base_prompt}
\n\n
إنت بتدرّس مادة {subject} للطفل {student_name}."
logger
.
info
(
f
"Using nationality: {nationality}
and subject: {subject
} for student: {student_id}"
)
logger
.
info
(
f
"Using nationality: {nationality}
, subject: {subject}, and student name: {student_name
} for student: {student_id}"
)
# Prepare messages
# Prepare messages
messages
=
[]
messages
=
[]
...
@@ -160,7 +182,6 @@ class AgentService:
...
@@ -160,7 +182,6 @@ class AgentService:
try
:
try
:
query_embedding
=
self
.
openai_service
.
generate_embedding
(
user_message
)
query_embedding
=
self
.
openai_service
.
generate_embedding
(
user_message
)
# Search with filtering based on student info and subject
neighbors
=
self
.
pgvector
.
search_filtered_nearest
(
neighbors
=
self
.
pgvector
.
search_filtered_nearest
(
query_embedding
=
query_embedding
,
query_embedding
=
query_embedding
,
grade
=
student_info
[
'grade'
],
grade
=
student_info
[
'grade'
],
...
@@ -170,9 +191,8 @@ class AgentService:
...
@@ -170,9 +191,8 @@ class AgentService:
)
)
if
neighbors
:
if
neighbors
:
# Print retrieval results
print
(
"
\n
----------------- Retrieval Results -----------------"
)
print
(
"
\n
----------------- Retrieval Results -----------------"
)
context_message
=
f
"معلومات من المنهج لمادة {subject} للصف {student_info['grade']}:
\n
"
context_message
=
f
"معلومات من المنهج لمادة {subject} للصف {student_info['grade']}
للطالب {student_name}
:
\n
"
for
i
,
n
in
enumerate
(
neighbors
,
1
):
for
i
,
n
in
enumerate
(
neighbors
,
1
):
unit_info
=
f
" - الوحدة: {n['unit']}"
if
n
[
'unit'
]
else
""
unit_info
=
f
" - الوحدة: {n['unit']}"
if
n
[
'unit'
]
else
""
concept_info
=
f
" - المفهوم: {n['concept']}"
if
n
[
'concept'
]
else
""
concept_info
=
f
" - المفهوم: {n['concept']}"
if
n
[
'concept'
]
else
""
...
@@ -209,7 +229,6 @@ class AgentService:
...
@@ -209,7 +229,6 @@ class AgentService:
temperature
=
temperature
temperature
=
temperature
)
)
ai_response
=
response
.
choices
[
0
]
.
message
.
content
.
strip
()
ai_response
=
response
.
choices
[
0
]
.
message
.
content
.
strip
()
if
not
ai_response
:
if
not
ai_response
:
raise
ValueError
(
"Empty response from AI model"
)
raise
ValueError
(
"Empty response from AI model"
)
...
@@ -223,6 +242,7 @@ class AgentService:
...
@@ -223,6 +242,7 @@ class AgentService:
logger
.
error
(
f
"Error generating AI response: {e}"
)
logger
.
error
(
f
"Error generating AI response: {e}"
)
raise
HTTPException
(
status_code
=
500
,
detail
=
f
"AI response generation failed: {str(e)}"
)
raise
HTTPException
(
status_code
=
500
,
detail
=
f
"AI response generation failed: {str(e)}"
)
def
search_similar
(
self
,
query_embedding
:
List
[
float
],
student_id
:
str
,
def
search_similar
(
self
,
query_embedding
:
List
[
float
],
student_id
:
str
,
subject
:
str
=
"chemistry"
,
top_k
:
int
=
3
):
subject
:
str
=
"chemistry"
,
top_k
:
int
=
3
):
"""Search similar content with student-specific filtering"""
"""Search similar content with student-specific filtering"""
...
@@ -248,10 +268,13 @@ class AgentService:
...
@@ -248,10 +268,13 @@ class AgentService:
if
not
student_info
:
if
not
student_info
:
return
False
return
False
# Extract student name
student_name
=
student_info
.
get
(
'student_name'
,
'الطالب'
)
# Clear existing history to reset context
# Clear existing history to reset context
self
.
db_service
.
clear_history
(
student_id
)
self
.
db_service
.
clear_history
(
student_id
)
# Set new system message with subject
# Set new system message with subject
and student name
nationality_lower
=
student_info
[
'nationality'
]
.
lower
()
.
strip
()
nationality_lower
=
student_info
[
'nationality'
]
.
lower
()
.
strip
()
nationality_mapping
=
{
nationality_mapping
=
{
'egyptian'
:
StudentNationality
.
EGYPTIAN
,
'egyptian'
:
StudentNationality
.
EGYPTIAN
,
...
@@ -260,11 +283,13 @@ class AgentService:
...
@@ -260,11 +283,13 @@ class AgentService:
nationality
=
nationality_mapping
.
get
(
nationality_lower
,
StudentNationality
.
EGYPTIAN
)
nationality
=
nationality_mapping
.
get
(
nationality_lower
,
StudentNationality
.
EGYPTIAN
)
base_system_prompt
=
SYSTEM_PROMPTS
.
get
(
nationality
,
SYSTEM_PROMPTS
[
StudentNationality
.
EGYPTIAN
])
base_system_prompt
=
SYSTEM_PROMPTS
.
get
(
nationality
,
SYSTEM_PROMPTS
[
StudentNationality
.
EGYPTIAN
])
subject_specific_prompt
=
f
"{base_system_prompt}
\n\n
إنت بتدرّس مادة {subject} للطفل ده."
# Format the prompt with student name
formatted_base_prompt
=
base_system_prompt
.
format
(
student_name
=
student_name
)
subject_specific_prompt
=
f
"{formatted_base_prompt}
\n\n
إنت بتدرّس مادة {subject} للطفل {student_name}."
self
.
add_message_to_history
(
student_id
,
subject_specific_prompt
,
"system"
)
self
.
add_message_to_history
(
student_id
,
subject_specific_prompt
,
"system"
)
logger
.
info
(
f
"Updated subject context to {subject} for student {student_id} ({student_
info['student_name']
})"
)
logger
.
info
(
f
"Updated subject context to {subject} for student {student_id} ({student_
name
})"
)
return
True
return
True
except
Exception
as
e
:
except
Exception
as
e
:
...
...
self_hosted_env/voice_agent/services/chat_database_service.py
View file @
579a27d9
...
@@ -33,7 +33,7 @@ class ChatDatabaseService:
...
@@ -33,7 +33,7 @@ class ChatDatabaseService:
with
self
.
conn
.
cursor
(
cursor_factory
=
RealDictCursor
)
as
cur
:
with
self
.
conn
.
cursor
(
cursor_factory
=
RealDictCursor
)
as
cur
:
cur
.
execute
(
cur
.
execute
(
"""
"""
SELECT student_id, grade, language, nationality
SELECT student_id,
student_name,
grade, language, nationality
FROM students
FROM students
WHERE student_id =
%
s
WHERE student_id =
%
s
"""
,
"""
,
...
@@ -43,6 +43,7 @@ class ChatDatabaseService:
...
@@ -43,6 +43,7 @@ class ChatDatabaseService:
if
result
:
if
result
:
return
{
return
{
'student_id'
:
result
[
'student_id'
],
'student_id'
:
result
[
'student_id'
],
'student_name'
:
result
[
'student_name'
],
# Added this line
'grade'
:
result
[
'grade'
],
'grade'
:
result
[
'grade'
],
'is_arabic'
:
result
[
'language'
],
# Convert language boolean to is_arabic
'is_arabic'
:
result
[
'language'
],
# Convert language boolean to is_arabic
'nationality'
:
result
[
'nationality'
]
'nationality'
:
result
[
'nationality'
]
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment