Spaces:
Running
Running
Commit
·
8b0f083
1
Parent(s):
0e89d34
Update prompts
Browse files
main.py
CHANGED
@@ -67,9 +67,9 @@ class HealthcareChatbot:
|
|
67 |
self.endpoints_documentation = endpoints_documentation
|
68 |
self.ollama_base_url = "http://localhost:11434"
|
69 |
self.model_name = "gemma3"
|
70 |
-
self.BASE_URL = 'https://
|
71 |
self.headers = {'Content-type': 'application/json'}
|
72 |
-
self.user_id = '
|
73 |
self.max_retries = 3
|
74 |
self.retry_delay = 2
|
75 |
|
@@ -155,141 +155,149 @@ class HealthcareChatbot:
|
|
155 |
|
156 |
# UNIFIED ROUTER CHAIN - Handles both intent classification AND API routing
|
157 |
self.router_prompt_template = PromptTemplate(
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
293 |
''' Third Approach '''
|
294 |
# self.router_prompt_template = PromptTemplate(
|
295 |
# template="""
|
@@ -582,70 +590,123 @@ class HealthcareChatbot:
|
|
582 |
)
|
583 |
|
584 |
# API RESPONSE CHAIN - Formats API responses for users
|
585 |
-
self.api_response_template = PromptTemplate(
|
586 |
-
|
587 |
-
|
588 |
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
|
593 |
-
|
594 |
-
|
595 |
|
596 |
-
|
597 |
|
598 |
-
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
|
607 |
-
|
608 |
-
|
609 |
-
|
610 |
|
611 |
-
|
612 |
|
613 |
-
|
614 |
-
|
615 |
-
|
616 |
|
617 |
-
|
618 |
-
|
619 |
-
|
620 |
|
621 |
-
|
622 |
-
|
623 |
-
|
624 |
-
|
625 |
|
626 |
-
|
627 |
|
628 |
-
|
629 |
-
|
630 |
-
|
631 |
-
|
632 |
-
|
633 |
-
|
634 |
-
|
635 |
-
|
636 |
-
|
637 |
-
|
638 |
-
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
|
646 |
-
|
647 |
-
|
648 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
649 |
|
650 |
# Create the 3 chains
|
651 |
self.router_chain = LLMChain(llm=self.llm, prompt=self.router_prompt_template)
|
@@ -1144,7 +1205,6 @@ class HealthcareChatbot:
|
|
1144 |
print("🗑️ Conversation history cleared.")
|
1145 |
|
1146 |
|
1147 |
-
|
1148 |
# def main():
|
1149 |
# """Main function to run the healthcare chatbot"""
|
1150 |
# try:
|
|
|
67 |
self.endpoints_documentation = endpoints_documentation
|
68 |
self.ollama_base_url = "http://localhost:11434"
|
69 |
self.model_name = "gemma3"
|
70 |
+
self.BASE_URL = 'https://8ac0-197-54-54-66.ngrok-free.app'
|
71 |
self.headers = {'Content-type': 'application/json'}
|
72 |
+
self.user_id = '9e889485-3db4-4f70-a7a2-e219beae6578'
|
73 |
self.max_retries = 3
|
74 |
self.retry_delay = 2
|
75 |
|
|
|
155 |
|
156 |
# UNIFIED ROUTER CHAIN - Handles both intent classification AND API routing
|
157 |
self.router_prompt_template = PromptTemplate(
|
158 |
+
template="""
|
159 |
+
You are a routing system. Your job is simple:
|
160 |
+
1. Understand what the user wants
|
161 |
+
2. Handle any dates/times in their request with PRECISE calculations
|
162 |
+
3. Check if any endpoint can do what they want
|
163 |
+
4. If yes = API_ACTION, if no = CONVERSATION
|
164 |
+
|
165 |
+
## Available API Endpoints Documentation
|
166 |
+
{endpoints_documentation}
|
167 |
+
|
168 |
+
## User Query to Analyze
|
169 |
+
Query: "{user_query}"
|
170 |
+
Language: {detected_language}
|
171 |
+
Current Context:
|
172 |
+
- DateTime: {current_datetime}
|
173 |
+
- Timezone: {timezone}
|
174 |
+
- Current Day of Week: {current_day_name}
|
175 |
+
|
176 |
+
## Step-by-Step Analysis
|
177 |
+
|
178 |
+
**STEP 1: What does the user want?**
|
179 |
+
- If query is in Arabic, translate it to English first
|
180 |
+
- Identify the exact action or information the user is requesting
|
181 |
+
- Focus on understanding their underlying need, not just the words
|
182 |
+
|
183 |
+
**STEP 2: Handle Date/Time Processing with PRECISE Calculations**
|
184 |
+
IMPORTANT: Use the current datetime ({current_datetime}) and timezone ({timezone}) for ALL calculations.
|
185 |
+
|
186 |
+
### Current Date Reference Points:
|
187 |
+
- Today is: {current_datetime}
|
188 |
+
- Current day of week: {current_day_name}
|
189 |
+
- Current timezone: {timezone}
|
190 |
+
|
191 |
+
### Arabic Date/Time Expressions Processing:
|
192 |
+
**Basic Relative Dates:**
|
193 |
+
- "اليوم" (today) = {current_datetime} date portion
|
194 |
+
- "غدا" (tomorrow) = current date + 1 day
|
195 |
+
- "أمس" (yesterday) = current date - 1 day
|
196 |
+
- "بعد غد" (day after tomorrow) = current date + 2 days
|
197 |
+
|
198 |
+
**Weekly Expressions - CALCULATE PRECISELY:**
|
199 |
+
- "الأسبوع القادم" (next week) = current date + 7 days
|
200 |
+
- "الأسبوع الماضي" (last week) = current date - 7 days
|
201 |
+
|
202 |
+
**Specific Weekday Calculations - MOST IMPORTANT:**
|
203 |
+
For expressions like "يوم [weekday] القادم" (next [weekday]):
|
204 |
+
1. Identify the target weekday from Arabic names:
|
205 |
+
- الأحد (Sunday) = 0
|
206 |
+
- الاثنين (Monday) = 1
|
207 |
+
- الثلاثاء (Tuesday) = 2
|
208 |
+
- الأربعاء (Wednesday) = 3
|
209 |
+
- الخميس (Thursday) = 4
|
210 |
+
- الجمعة (Friday) = 5
|
211 |
+
- السبت (Saturday) = 6
|
212 |
+
|
213 |
+
2. Calculate days to add:
|
214 |
+
- Get current weekday number (0=Sunday, 1=Monday, etc.)
|
215 |
+
- Target weekday number
|
216 |
+
- If target > current: days_to_add = target - current
|
217 |
+
- If target <= current: days_to_add = 7 - (current - target)
|
218 |
+
- Final date = current_date + days_to_add
|
219 |
+
|
220 |
+
**Example Calculation:**
|
221 |
+
If today is Sunday (June 1, 2025) and user says "يوم الاربع القادم" (next Wednesday):
|
222 |
+
- Current weekday: 0 (Sunday)
|
223 |
+
- Target weekday: 3 (Wednesday)
|
224 |
+
- Days to add: 3 - 0 = 3
|
225 |
+
- Result: June 1 + 3 days = June 4, 2025
|
226 |
+
|
227 |
+
**Monthly/Yearly Expressions:**
|
228 |
+
- "الشهر القادم" (next month) = add 1 month to current date
|
229 |
+
- "الشهر الماضي" (last month) = subtract 1 month from current date
|
230 |
+
- "السنة القادمة" (next year) = add 1 year to current date
|
231 |
+
|
232 |
+
**Time Expressions:**
|
233 |
+
- "صباحًا" (morning/AM) = 09:00 if no specific time given
|
234 |
+
- "مساءً" (evening/PM) = 18:00 if no specific time given
|
235 |
+
- "ظهرًا" (noon) = 12:00
|
236 |
+
- "منتصف الليل" (midnight) = 00:00
|
237 |
+
- "بعد ساعتين" (in 2 hours) = current time + 2 hours
|
238 |
+
- "قبل ساعة" (1 hour ago) = current time - 1 hour
|
239 |
+
|
240 |
+
**Date Format Output:**
|
241 |
+
- Always convert final calculated date to ISO 8601 format: YYYY-MM-DDTHH:MM:SS
|
242 |
+
- Include timezone offset if available
|
243 |
+
- For date-only expressions, use 00:00:00 as default time
|
244 |
+
|
245 |
+
**STEP 3: Find matching endpoint**
|
246 |
+
- Read each endpoint description in the documentation
|
247 |
+
- Check if any endpoint's purpose can fulfill what the user wants
|
248 |
+
- Match based on functionality, not keywords
|
249 |
+
|
250 |
+
**STEP 4: Decision**
|
251 |
+
- Found matching endpoint = "API_ACTION"
|
252 |
+
- No matching endpoint = "CONVERSATION"
|
253 |
+
|
254 |
+
**STEP 5: Parameter Extraction (only if API_ACTION)**
|
255 |
+
- Extract parameter values from user query
|
256 |
+
- Use the CALCULATED dates/times from Step 2
|
257 |
+
- Convert all dates/times to ISO 8601 format (YYYY-MM-DDTHH:MM:SS)
|
258 |
+
- List any missing required parameters
|
259 |
+
- **CRITICAL: All parameters must be in English**
|
260 |
+
- Translate any Arabic text to English
|
261 |
+
- Convert names to English equivalents (e.g., "دكتور احمد" → "Dr. Ahmed")
|
262 |
+
- Use standard English terms for all parameters
|
263 |
+
|
264 |
+
## Output Format
|
265 |
+
{{
|
266 |
+
"intent": "CONVERSATION|API_ACTION",
|
267 |
+
"confidence": 0.8,
|
268 |
+
"reasoning": "User wants: [what user actually needs]. Date/time processing: [show exact calculation: current date + X days = final date]. Found endpoint: [endpoint path and why it matches] OR No endpoint matches this need",
|
269 |
+
"endpoint": "/exact/endpoint/path",
|
270 |
+
"method": "GET|POST|PUT|DELETE",
|
271 |
+
"params": {{
|
272 |
+
// ALL VALUES MUST BE IN ENGLISH
|
273 |
+
// Arabic terms must be translated to English equivalents
|
274 |
+
}},
|
275 |
+
"missing_required": [],
|
276 |
+
"calculated_datetime": "YYYY-MM-DDTHH:MM:SS (if date/time was processed)"
|
277 |
+
}}
|
278 |
+
|
279 |
+
## CRITICAL REMINDERS:
|
280 |
+
1. ALWAYS use the provided current_datetime ({current_datetime}) as your base for calculations
|
281 |
+
2. For "next weekday" expressions, calculate the exact number of days to add
|
282 |
+
3. Show your calculation work in the reasoning field
|
283 |
+
4. Double-check weekday numbers: Sunday=0, Monday=1, Tuesday=2, Wednesday=3, Thursday=4, Friday=5, Saturday=6
|
284 |
+
5. **ALL PARAMETERS MUST BE IN ENGLISH** - translate any Arabic text before output
|
285 |
+
|
286 |
+
**FINAL CHECK BEFORE OUTPUTTING:**
|
287 |
+
🔍 **MANDATORY LANGUAGE CHECK:**
|
288 |
+
1. Examine every value in the params object
|
289 |
+
2. If ANY value contains Arabic characters (ا-ي), you MUST:
|
290 |
+
- Translate it to English
|
291 |
+
- Convert names to English equivalents
|
292 |
+
- Replace Arabic terms with English counterparts
|
293 |
+
3. Only output JSON when ALL parameters are in English
|
294 |
+
|
295 |
+
Now analyze the user query step by step and give me the JSON response.
|
296 |
+
""",
|
297 |
+
input_variables=["user_query", "detected_language", "extracted_keywords",
|
298 |
+
"sentiment_analysis", "endpoints_documentation", "current_datetime",
|
299 |
+
"timezone", "current_day_name"]
|
300 |
+
)
|
301 |
''' Third Approach '''
|
302 |
# self.router_prompt_template = PromptTemplate(
|
303 |
# template="""
|
|
|
590 |
)
|
591 |
|
592 |
# API RESPONSE CHAIN - Formats API responses for users
|
593 |
+
# self.api_response_template = PromptTemplate(
|
594 |
+
# template="""
|
595 |
+
# You are a professional healthcare assistant. Answer the user's question using the provided API data.
|
596 |
|
597 |
+
# User Query: {user_query}
|
598 |
+
# User Sentiment: {sentiment_analysis}
|
599 |
+
# Response Language: {detected_language}
|
600 |
|
601 |
+
# API Response Data:
|
602 |
+
# {api_response}
|
603 |
|
604 |
+
# === INSTRUCTIONS ===
|
605 |
|
606 |
+
# 1. Read and understand the API response data above
|
607 |
+
# 2. Use ONLY the actual data from the API response - never make up information
|
608 |
+
# 3. Respond in {detected_language} language only
|
609 |
+
# 4. Write like you're talking to a friend or family member - warm, friendly, and caring
|
610 |
+
# 5. Make it sound natural and conversational, not like a system message
|
611 |
+
# 6. Convert technical data to simple, everyday language
|
612 |
+
|
613 |
+
# === DATE AND TIME FORMATTING ===
|
614 |
|
615 |
+
# When you see date_time fields like '2025-05-30T10:28:10':
|
616 |
+
# - For English: Convert to "May 30, 2025 at 10:28 AM"
|
617 |
+
# - For Arabic: Convert to "٣٠ مايو ٢٠٢٥ في الساعة ١٠:٢٨ صباحاً"
|
618 |
|
619 |
+
# === RESPONSE EXAMPLES ===
|
620 |
|
621 |
+
# For appointment confirmations:
|
622 |
+
# - English: "Great! I've got your appointment set up for May 30, 2025 at 10:28 AM. Everything looks good!"
|
623 |
+
# - Arabic: "ممتاز! موعدك محجوز يوم ٣٠ مايو ٢٠٢٥ الساعة ١٠:٢٨ صباحاً. كل شيء جاهز!"
|
624 |
|
625 |
+
# For appointment info:
|
626 |
+
# - English: "Your next appointment is on May 30, 2025 at 10:28 AM. See you then!"
|
627 |
+
# - Arabic: "موعدك القادم يوم ٣٠ مايو ٢٠٢٥ الساعة ١٠:٢٨ صباحاً. نراك قريباً!"
|
628 |
|
629 |
+
# === TONE GUIDELINES ===
|
630 |
+
# - Use friendly words like: "Great!", "Perfect!", "All set!", "ممتاز!", "رائع!", "تمام!"
|
631 |
+
# - Add reassuring phrases: "Everything looks good", "You're all set", "كل شيء جاهز", "تم بنجاح"
|
632 |
+
# - Sound helpful and caring, not robotic or formal
|
633 |
|
634 |
+
# === LANGUAGE FORMATTING ===
|
635 |
|
636 |
+
# For Arabic responses:
|
637 |
+
# - Use Arabic numerals: ٠١٢٣٤٥٦٧٨٩
|
638 |
+
# - Use Arabic month names: يناير، فبراير، مارس، أبريل، مايو، يونيو، يوليو، أغسطس، سبتمبر، أكتوبر، نوفمبر، ديسمبر
|
639 |
+
# - Friendly, warm Arabic tone
|
640 |
+
|
641 |
+
# For English responses:
|
642 |
+
# - Use standard English numerals
|
643 |
+
# - 12-hour time format with AM/PM
|
644 |
+
# - Friendly, conversational English tone
|
645 |
+
|
646 |
+
# === CRITICAL RULES ===
|
647 |
+
# - Extract dates and times exactly as they appear in the API response
|
648 |
+
# - Never use example dates or placeholder information
|
649 |
+
# - Respond only in the specified language
|
650 |
+
# - Make your response sound like a helpful friend, not a computer
|
651 |
+
# - Focus on answering the user's specific question with warmth and care
|
652 |
+
|
653 |
+
# Generate a friendly, helpful response using the API data provided above.
|
654 |
+
# """,
|
655 |
+
# input_variables=["user_query", "api_response", "detected_language", "sentiment_analysis"]
|
656 |
+
# )
|
657 |
+
self.api_response_template = PromptTemplate(
|
658 |
+
template="""
|
659 |
+
You are a professional healthcare assistant. Generate a natural language response to the user's query using ONLY the provided API data.
|
660 |
+
|
661 |
+
User Query: {user_query}
|
662 |
+
User Sentiment: {sentiment_analysis}
|
663 |
+
Response Language: {detected_language}
|
664 |
+
|
665 |
+
API Response Data:
|
666 |
+
{api_response}
|
667 |
+
|
668 |
+
=== CORE INSTRUCTIONS ===
|
669 |
+
|
670 |
+
1. Analyze the API response structure and extract relevant data points
|
671 |
+
2. Cross-reference with the user's query to determine what information to include
|
672 |
+
3. Respond in {detected_language} using a warm, conversational tone
|
673 |
+
4. Convert technical data into natural language appropriate for healthcare communication
|
674 |
+
|
675 |
+
=== DATE/TIME HANDLING ===
|
676 |
+
|
677 |
+
1. Identify all date/time fields in the API response (look for ISO 8601 format: YYYY-MM-DDTHH:MM:SS)
|
678 |
+
2. For English responses:
|
679 |
+
- Format dates as "Month Day, Year at HH:MM AM/PM"
|
680 |
+
- Convert times to 12-hour format with proper AM/PM
|
681 |
+
3. For Arabic responses:
|
682 |
+
- Format dates as "Day Month Year الساعة HH:MM صباحاً/مساءً"
|
683 |
+
- Use Arabic numerals (٠١٢٣٤٥٦٧٨٩)
|
684 |
+
- Use Arabic month names
|
685 |
+
4. Preserve all original date/time values - only change the formatting
|
686 |
+
|
687 |
+
=== RESPONSE GUIDELINES ===
|
688 |
+
|
689 |
+
1. Use ONLY data present in the API response
|
690 |
+
2. Maintain a professional yet friendly healthcare tone
|
691 |
+
3. Adapt to the user's sentiment:
|
692 |
+
- Positive: reinforce with encouraging language
|
693 |
+
- Neutral: provide clear, factual information
|
694 |
+
- Negative: show empathy and offer assistance
|
695 |
+
4. Structure the response to directly answer the user's query
|
696 |
+
5. Include relevant details from the API response that address the user's needs
|
697 |
+
|
698 |
+
=== CRITICAL RULES ===
|
699 |
+
|
700 |
+
1. Never invent or hallucinate information not present in the API response
|
701 |
+
2. If the API response doesn't contain requested information, say so politely
|
702 |
+
3. All dates/times must exactly match the API data
|
703 |
+
4. Maintain strict language consistency (respond only in {detected_language})
|
704 |
+
5. Format all technical data (IDs, codes, etc.) for easy understanding
|
705 |
+
|
706 |
+
Generate a helpful response that addresses the user's query using the API data.
|
707 |
+
""",
|
708 |
+
input_variables=["user_query", "api_response", "detected_language", "sentiment_analysis"]
|
709 |
+
)
|
710 |
|
711 |
# Create the 3 chains
|
712 |
self.router_chain = LLMChain(llm=self.llm, prompt=self.router_prompt_template)
|
|
|
1205 |
print("🗑️ Conversation history cleared.")
|
1206 |
|
1207 |
|
|
|
1208 |
# def main():
|
1209 |
# """Main function to run the healthcare chatbot"""
|
1210 |
# try:
|