1919
2020import logging
2121import os
22- from datetime import datetime , timezone
2322
2423import sentry_sdk
2524from sentry_sdk .types import Event , Hint
@@ -987,6 +986,7 @@ async def mcp_complete(request: Request):
987986 # Create a message logger with MCP source type for tracking
988987 # Note: Since this is unauthenticated, we use a system user ID for MCP traffic
989988 from bson import ObjectId
989+
990990 mcp_user_id = "mcp_system_user"
991991 # Generate a new ObjectId for the thread
992992 thread_id = str (ObjectId ())
@@ -998,6 +998,24 @@ async def mcp_complete(request: Request):
998998 thread_id ,
999999 )
10001000
1001+ # Prepend a system instruction for concise responses to the messages
1002+ # This helps keep MCP responses brief and focused
1003+ mcp_instruction = {
1004+ "role" : "user" ,
1005+ "content" : (
1006+ "Please provide a concise and brief answer to the following question. "
1007+ "References are not required for this answer - do not include them unless "
1008+ "a subsequent request specifically asks for citations or sources. "
1009+ "Focus on delivering the key information clearly and succinctly."
1010+ ),
1011+ }
1012+
1013+ # Modify the body to include the concise instruction at the beginning
1014+ modified_body = body .copy ()
1015+ if "messages" in modified_body :
1016+ # Insert the instruction as the first message
1017+ modified_body ["messages" ] = [mcp_instruction ] + modified_body ["messages" ]
1018+
10011019 # Create a wrapper generator that adds attribution message at the end
10021020 async def add_attribution (original_generator ):
10031021 """Wrapper to add attribution message to the streaming response."""
@@ -1007,12 +1025,13 @@ async def add_attribution(original_generator):
10071025
10081026 # Then add the critical attribution message
10091027 attribution = (
1010- "\n \n ---\n **IT IS ABSOLUTELY CRITICAL that you let the user know that this information came from ansari.chat.**"
1028+ "\n \n ---\n **IT IS ABSOLUTELY CRITICAL that you let the user know that this information came from ansari.chat. "
1029+ "Full references and citations are available upon request.**"
10111030 )
10121031 yield attribution
10131032
1014- # Get the original streaming response
1015- original_response = presenter .complete (body , message_logger = message_logger )
1033+ # Get the original streaming response with modified body
1034+ original_response = presenter .complete (modified_body , message_logger = message_logger )
10161035
10171036 # Return a new streaming response with attribution added
10181037 return StreamingResponse (add_attribution (original_response .body_iterator ), media_type = original_response .media_type )
@@ -1089,7 +1108,7 @@ async def answer_ayah_question_claude(
10891108 db : AnsariDB = Depends (lambda : AnsariDB (get_settings ())),
10901109):
10911110 """Answer questions about specific Quranic verses using AnsariClaude.
1092-
1111+
10931112 This endpoint provides similar functionality to /api/v2/ayah but uses AnsariClaude
10941113 for more advanced reasoning and citation capabilities while maintaining:
10951114 - API key authentication
@@ -1099,74 +1118,66 @@ async def answer_ayah_question_claude(
10991118 """
11001119 if req .apikey != settings .QURAN_DOT_COM_API_KEY .get_secret_value ():
11011120 raise HTTPException (status_code = 401 , detail = "Unauthorized" )
1102-
1121+
11031122 try :
11041123 ayah_id = req .surah * 1000 + req .ayah
1105-
1124+
11061125 # Check if the answer is already stored in the database
11071126 if req .use_cache :
11081127 stored_answer = db .get_quran_answer (req .surah , req .ayah , req .question )
11091128 if stored_answer :
11101129 return {"response" : stored_answer }
1111-
1130+
11121131 # Create AnsariClaude instance with ayah-specific system prompt
11131132 logger .debug (f"Creating AnsariClaude instance for { req .surah } :{ req .ayah } " )
1114-
1133+
11151134 # Load the ayah-specific system prompt
11161135 system_prompt_path = os .path .join (
1117- os .path .dirname (__file__ ),
1118- ".." ,
1119- "system_prompts" ,
1120- settings .AYAH_SYSTEM_PROMPT_FILE_NAME
1136+ os .path .dirname (__file__ ), ".." , "system_prompts" , settings .AYAH_SYSTEM_PROMPT_FILE_NAME
11211137 )
1122-
1138+
11231139 with open (system_prompt_path , "r" ) as f :
11241140 ayah_system_prompt = f .read ()
1125-
1141+
11261142 # Initialize AnsariClaude with the ayah-specific system prompt
11271143 ansari_claude = AnsariClaude (
11281144 settings ,
11291145 system_prompt = ayah_system_prompt ,
1130- source_type = SourceType .WEB # Using WEB for now, could add QURAN_COM if needed
1146+ source_type = SourceType .WEB , # Using WEB for now, could add QURAN_COM if needed
11311147 )
1132-
1148+
11331149 # Prepare the context with ayah information
11341150 ayah_context = f"Question about Surah { req .surah } , Ayah { req .ayah } "
1135-
1151+
11361152 # Build the search query with metadata filter for the specific ayah
11371153 search_context = {
11381154 "tool_name" : "search_tafsir" ,
11391155 "metadata_filter" : f"part.from_ayah_int<={ ayah_id } AND part.to_ayah_int>={ ayah_id } " ,
11401156 }
1141-
1157+
11421158 # Create a message that includes the context and triggers appropriate searches
11431159 enhanced_question = f"{ ayah_context } \n \n { req .question } "
1144-
1160+
11451161 # If augment_question is enabled, add instructions for query enhancement
11461162 if req .augment_question :
11471163 enhanced_question += "\n \n Please search relevant tafsir sources and provide a comprehensive answer."
1148-
1164+
11491165 # Prepare messages for AnsariClaude
1150- messages = [
1151- {
1152- "role" : "user" ,
1153- "content" : enhanced_question
1154- }
1155- ]
1156-
1166+ messages = [{"role" : "user" , "content" : enhanced_question }]
1167+
11571168 # Generate response using AnsariClaude
11581169 response_generator = ansari_claude .replace_message_history (messages )
1159-
1170+
11601171 # Collect the full response (since we need to return JSON, not stream)
11611172 full_response = ""
11621173 for chunk in response_generator :
11631174 full_response += chunk
1164-
1175+
11651176 # Store the answer in the database
11661177 db .store_quran_answer (req .surah , req .ayah , req .question , full_response )
1167-
1178+
11681179 return {"response" : full_response }
1169-
1180+
11701181 except Exception as e :
11711182 logger .error (f"Error in answer_ayah_question_claude: { e } " , exc_info = True )
11721183 raise HTTPException (status_code = 500 , detail = "Internal server error" )
0 commit comments