abdibrahem commited on
Commit
4899b34
·
1 Parent(s): e7d03d1

Update prompt

Browse files
Files changed (1) hide show
  1. main.py +236 -539
main.py CHANGED
@@ -68,9 +68,9 @@ class HealthcareChatbot:
68
  self.endpoints_documentation = endpoints_documentation
69
  self.ollama_base_url = "http://localhost:11434"
70
  self.model_name = "gemma3"
71
- self.BASE_URL = 'https://4646-197-54-54-66.ngrok-free.app'
72
  self.headers = {'Content-type': 'application/json'}
73
- self.user_id = '19cc0380-57e8-45db-94e4-6ad6e6802084'
74
  self.max_retries = 3
75
  self.retry_delay = 2
76
 
@@ -155,559 +155,257 @@ class HealthcareChatbot:
155
  self.json_parser = JsonOutputParser(pydantic_object=RouterResponse)
156
 
157
  # UNIFIED ROUTER CHAIN - Handles both intent classification AND API routing
158
- self.router_prompt_template = PromptTemplate(
159
- template="""
160
- You are a routing system. Your job is simple:
161
- 1. Understand what the user wants
162
- 2. Handle any dates/times in their request with PRECISE calculations
163
- 3. Check if any endpoint can do what they want
164
- 4. If yes = API_ACTION, if no = CONVERSATION
165
-
166
- ## Available API Endpoints Documentation
167
- {endpoints_documentation}
168
-
169
- ## User Query to Analyze
170
- Query: "{user_query}"
171
- Language: {detected_language}
172
- Current Context:
173
- - DateTime: {current_datetime}
174
- - Timezone: {timezone}
175
- - Current Day of Week: {current_day_name}
176
-
177
- ## Step-by-Step Analysis
178
-
179
- **STEP 1: What does the user want?**
180
- - If query is in Arabic, translate it to English first
181
- - Identify the exact action or information the user is requesting
182
- - Focus on understanding their underlying need, not just the words
183
-
184
- **STEP 2: Handle Date/Time Processing with PRECISE Calculations**
185
- IMPORTANT: Use the current datetime ({current_datetime}) and timezone ({timezone}) for ALL calculations.
186
-
187
- ### Current Date Reference Points:
188
- - Today is: {current_datetime}
189
- - Current day of week: {current_day_name}
190
- - Current timezone: {timezone}
191
-
192
- ### Arabic Date/Time Expressions Processing:
193
- **Basic Relative Dates:**
194
- - "اليوم" (today) = {current_datetime} date portion
195
- - "غدا" (tomorrow) = current date + 1 day
196
- - "أمس" (yesterday) = current date - 1 day
197
- - "بعد غد" (day after tomorrow) = current date + 2 days
198
-
199
- **Weekly Expressions - CALCULATE PRECISELY:**
200
- - "الأسبوع القادم" (next week) = current date + 7 days
201
- - "الأسبوع الماضي" (last week) = current date - 7 days
202
-
203
- **Specific Weekday Calculations - MOST IMPORTANT:**
204
- For expressions like "يوم [weekday] القادم" (next [weekday]):
205
- 1. Identify the target weekday from Arabic names:
206
- - الأحد (Sunday) = 0
207
- - الاثنين (Monday) = 1
208
- - الثلاثاء (Tuesday) = 2
209
- - الأربعاء (Wednesday) = 3
210
- - الخميس (Thursday) = 4
211
- - الجمعة (Friday) = 5
212
- - السبت (Saturday) = 6
213
-
214
- 2. Calculate days to add:
215
- - Get current weekday number (0=Sunday, 1=Monday, etc.)
216
- - Target weekday number
217
- - If target > current: days_to_add = target - current
218
- - If target <= current: days_to_add = 7 - (current - target)
219
- - Final date = current_date + days_to_add
220
-
221
- **Example Calculation:**
222
- If today is Sunday (June 1, 2025) and user says "يوم الاربع القادم" (next Wednesday):
223
- - Current weekday: 0 (Sunday)
224
- - Target weekday: 3 (Wednesday)
225
- - Days to add: 3 - 0 = 3
226
- - Result: June 1 + 3 days = June 4, 2025
227
-
228
- **Monthly/Yearly Expressions:**
229
- - "الشهر القادم" (next month) = add 1 month to current date
230
- - "الشهر الماضي" (last month) = subtract 1 month from current date
231
- - "السنة القادمة" (next year) = add 1 year to current date
232
-
233
- **Time Expressions:**
234
- - "صباحًا" (morning/AM) = 09:00 if no specific time given
235
- - "مساءً" (evening/PM) = 18:00 if no specific time given
236
- - "ظهرًا" (noon) = 12:00
237
- - "منتصف الليل" (midnight) = 00:00
238
- - "بعد ساعتين" (in 2 hours) = current time + 2 hours
239
- - "قبل ساعة" (1 hour ago) = current time - 1 hour
240
-
241
- **Date Format Output:**
242
- - Always convert final calculated date to ISO 8601 format: YYYY-MM-DDTHH:MM:SS
243
- - Include timezone offset if available
244
- - For date-only expressions, use 00:00:00 as default time
245
-
246
- **STEP 3: Find matching endpoint**
247
- - Read each endpoint description in the documentation
248
- - Check if any endpoint's purpose can fulfill what the user wants
249
- - Match based on functionality, not keywords
250
-
251
- **STEP 4: Decision**
252
- - Found matching endpoint = "API_ACTION"
253
- - No matching endpoint = "CONVERSATION"
254
-
255
- **STEP 5: Parameter Extraction (only if API_ACTION)**
256
- - Extract parameter values from user query
257
- - Use the CALCULATED dates/times from Step 2
258
- - Convert all dates/times to ISO 8601 format (YYYY-MM-DDTHH:MM:SS)
259
- - List any missing required parameters
260
- - **CRITICAL: All parameters must be in English**
261
- - Translate any Arabic text to English
262
- - Convert names to English equivalents (e.g., "دكتور احمد" → "Dr. Ahmed")
263
- - Use standard English terms for all parameters
264
-
265
- ## Output Format
266
- {{
267
- "intent": "CONVERSATION|API_ACTION",
268
- "confidence": 0.8,
269
- "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",
270
- "endpoint": "/exact/endpoint/path",
271
- "method": "GET|POST|PUT|DELETE",
272
- "params": {{
273
- // ALL VALUES MUST BE IN ENGLISH
274
- // Arabic terms must be translated to English equivalents
275
- }},
276
- "missing_required": [],
277
- "calculated_datetime": "YYYY-MM-DDTHH:MM:SS (if date/time was processed)"
278
- }}
279
-
280
- ## CRITICAL REMINDERS:
281
- 1. ALWAYS use the provided current_datetime ({current_datetime}) as your base for calculations
282
- 2. For "next weekday" expressions, calculate the exact number of days to add
283
- 3. Show your calculation work in the reasoning field
284
- 4. Double-check weekday numbers: Sunday=0, Monday=1, Tuesday=2, Wednesday=3, Thursday=4, Friday=5, Saturday=6
285
- 5. **ALL PARAMETERS MUST BE IN ENGLISH** - translate any Arabic text before output
286
-
287
- **FINAL CHECK BEFORE OUTPUTTING:**
288
- 🔍 **MANDATORY LANGUAGE CHECK:**
289
- 1. Examine every value in the params object
290
- 2. If ANY value contains Arabic characters (ا-ي), you MUST:
291
- - Translate it to English
292
- - Convert names to English equivalents
293
- - Replace Arabic terms with English counterparts
294
- 3. Only output JSON when ALL parameters are in English
295
-
296
- Now analyze the user query step by step and give me the JSON response.
297
- """,
298
- input_variables=["user_query", "detected_language", "extracted_keywords",
299
- "sentiment_analysis", "endpoints_documentation", "current_datetime",
300
- "timezone", "current_day_name"]
301
- )
302
- ''' Third Approach '''
303
  # self.router_prompt_template = PromptTemplate(
304
- # template="""
305
- # You are a routing system. Your job is simple:
306
- # 1. Understand what the user wants
307
- # 2. Handle any dates/times in their request with PRECISE calculations
308
- # 3. Check if any endpoint can do what they want
309
- # 4. If yes = API_ACTION, if no = CONVERSATION
310
-
311
- # ## Available API Endpoints Documentation
312
- # {endpoints_documentation}
313
 
314
- # ## User Query to Analyze
315
  # Query: "{user_query}"
316
  # Language: {detected_language}
317
- # Current Context:
318
- # - DateTime: {current_datetime}
319
- # - Timezone: {timezone}
320
- # - Current Day of Week: {current_day_name}
321
-
322
- # ## Step-by-Step Analysis
323
-
324
- # **STEP 1: What does the user want?**
325
- # - If query is in Arabic, translate it to English first
326
- # - Identify the exact action or information the user is requesting
327
- # - Focus on understanding their underlying need, not just the words
328
-
329
- # **STEP 2: Handle Date/Time Processing with PRECISE Calculations**
330
- # IMPORTANT: Use the current datetime ({current_datetime}) and timezone ({timezone}) for ALL calculations.
331
-
332
- # ### Current Date Reference Points:
333
- # - Today is: {current_datetime}
334
- # - Current day of week: {current_day_name}
335
- # - Current timezone: {timezone}
336
-
337
- # ### Arabic Date/Time Expressions Processing:
338
- # **Basic Relative Dates:**
339
- # - "اليوم" (today) = {current_datetime} date portion
340
- # - "غدا" (tomorrow) = current date + 1 day
341
- # - "أمس" (yesterday) = current date - 1 day
342
- # - "بعد غد" (day after tomorrow) = current date + 2 days
343
-
344
- # **Weekly Expressions - CALCULATE PRECISELY:**
345
- # - "الأسبوع القادم" (next week) = current date + 7 days
346
- # - "الأسبوع الماضي" (last week) = current date - 7 days
347
-
348
- # **Specific Weekday Calculations - MOST IMPORTANT:**
349
- # For expressions like "يوم [weekday] القادم" (next [weekday]):
350
- # 1. Identify the target weekday from Arabic names:
351
- # - الأحد (Sunday) = 0
352
- # - الاثنين (Monday) = 1
353
- # - الثلاثاء (Tuesday) = 2
354
- # - الأربعاء (Wednesday) = 3
355
- # - الخميس (Thursday) = 4
356
- # - الجمعة (Friday) = 5
357
- # - السبت (Saturday) = 6
358
-
359
- # 2. Calculate days to add:
360
- # - Get current weekday number (0=Sunday, 1=Monday, etc.)
361
- # - Target weekday number
362
- # - If target > current: days_to_add = target - current
363
- # - If target <= current: days_to_add = 7 - (current - target)
364
- # - Final date = current_date + days_to_add
365
-
366
- # **Example Calculation:**
367
- # If today is Sunday (June 1, 2025) and user says "يوم الاربع القادم" (next Wednesday):
368
- # - Current weekday: 0 (Sunday)
369
- # - Target weekday: 3 (Wednesday)
370
- # - Days to add: 3 - 0 = 3
371
- # - Result: June 1 + 3 days = June 4, 2025
372
-
373
- # **Monthly/Yearly Expressions:**
374
- # - "الشهر القادم" (next month) = add 1 month to current date
375
- # - "الشهر الماضي" (last month) = subtract 1 month from current date
376
- # - "السنة القادمة" (next year) = add 1 year to current date
377
-
378
- # **Time Expressions:**
379
- # - "صباحًا" (morning/AM) = 09:00 if no specific time given
380
- # - "مساءً" (evening/PM) = 18:00 if no specific time given
381
- # - "ظهرًا" (noon) = 12:00
382
- # - "منتصف الليل" (midnight) = 00:00
383
- # - "بعد ساعتين" (in 2 hours) = current time + 2 hours
384
- # - "قبل ساعة" (1 hour ago) = current time - 1 hour
385
-
386
- # **Date Format Output:**
387
- # - Always convert final calculated date to ISO 8601 format: YYYY-MM-DDTHH:MM:SS
388
- # - Include timezone offset if available
389
- # - For date-only expressions, use 00:00:00 as default time
390
-
391
- # **STEP 3: Find matching endpoint**
392
- # - Read each endpoint description in the documentation
393
- # - Check if any endpoint's purpose can fulfill what the user wants
394
- # - Match based on functionality, not keywords
395
-
396
- # **STEP 4: Decision**
397
- # - Found matching endpoint = "API_ACTION"
398
- # - No matching endpoint = "CONVERSATION"
399
-
400
- # **STEP 5: Parameter Extraction (only if API_ACTION)**
401
- # - Extract parameter values from the user's query and translate the parameters value to English.
402
- # - Use the CALCULATED dates/times from Step 2
403
- # - Convert all dates/times to ISO 8601 format (YYYY-MM-DDTHH:MM:SS)
404
- # - List any missing required parameters
405
-
406
- # ## Output Format
407
- # {{
408
- # "intent": "CONVERSATION|API_ACTION",
409
- # "confidence": 0.8,
410
- # "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",
411
- # "endpoint": "/exact/endpoint/path",
412
- # "method": "GET|POST|PUT|DELETE",
413
- # "params": {{}},
414
- # "missing_required": [],
415
- # "calculated_datetime": "YYYY-MM-DDTHH:MM:SS (if date/time was processed)"
416
- # }}
417
 
418
- # ## CRITICAL REMINDERS:
419
- # 1. ALWAYS use the provided current_datetime ({current_datetime}) as your base for calculations
420
- # 2. For "next weekday" expressions, calculate the exact number of days to add
421
- # 3. Show your calculation work in the reasoning field
422
- # 4. Double-check weekday numbers: Sunday=0, Monday=1, Tuesday=2, Wednesday=3, Thursday=4, Friday=5, Saturday=6
423
-
424
- # Now analyze the user query step by step and give me the JSON response.
425
- # """,
426
- # input_variables=["user_query", "detected_language", "extracted_keywords",
427
- # "sentiment_analysis", "endpoints_documentation", "current_datetime",
428
- # "timezone", "current_day_name"]
429
- # )
430
- ''' Second Approach '''
431
- # self.router_prompt_template = PromptTemplate(
432
- # template="""
433
- # You are a routing system. Your job is simple:
434
- # 1. Understand what the user wants
435
- # 2. Handle any dates/times in their request
436
- # 3. Check if any endpoint can do what they want
437
- # 4. If yes = API_ACTION, if no = CONVERSATION
438
-
439
- # ## Available API Endpoints Documentation
440
  # {endpoints_documentation}
441
 
442
- # ## User Query to Analyze
443
- # Query: "{user_query}"
444
- # Language: {detected_language}
445
- # Current Context:
446
- # - DateTime: {current_datetime}
447
- # - Timezone: {timezone}
448
-
449
- # ## Step-by-Step Analysis
450
-
451
- # **STEP 1: What does the user want?**
452
- # - If query is in Arabic, translate it to English first
453
- # - Identify the exact action or information the user is requesting
454
- # - Focus on understanding their underlying need, not just the words
455
-
456
- # **STEP 2: Handle Date/Time Processing**
457
- # - Identify any temporal expressions in the user query
458
- # - Convert relative dates/times using the current context:
459
- # * "اليوم" (today) = current date
460
- # * "غدا" (tomorrow) = current date + 1 day
461
- # * "أمس" (yesterday) = current date - 1 day
462
- # * "الأسبوع القادم" (next week) = current date + 7 days
463
- # * "بعد ساعتين" (in 2 hours) = current time + 2 hours
464
- # * "صباحًا" (morning/AM), "مساءً" (evening/PM)
465
- # * "الشهر القادم" (next month) = current date + 1 month
466
- # * "الأسبوع الماضي" (last week) = current date - 7 days
467
- # - Handle different date formats and languages
468
- # - Account for timezone differences
469
- # - Convert to ISO 8601 format: YYYY-MM-DDTHH:MM:SS
470
-
471
- # **STEP 3: Find matching endpoint**
472
- # - Read each endpoint description in the documentation
473
- # - Check if any endpoint's purpose can fulfill what the user wants
474
- # - Match based on functionality, not keywords
475
-
476
- # **STEP 3: Decision**
477
- # - Found matching endpoint = "API_ACTION"
478
- # - No matching endpoint = "CONVERSATION"
479
-
480
- # **STEP 4: Parameter Extraction (only if API_ACTION)**
481
- # - Extract parameter values from user query
482
- # - Convert dates/times to ISO 8601 format (YYYY-MM-DDTHH:MM:SS) using the context above
483
- # - List any missing required parameters
484
-
485
- # ## Output Format
486
  # {{
487
  # "intent": "CONVERSATION|API_ACTION",
488
  # "confidence": 0.8,
489
- # "reasoning": "User wants: [what user actually needs]. Date/time processing: [any date conversions made]. Found endpoint: [endpoint path and why it matches] OR No endpoint matches this need",
490
- # "endpoint": "/exact/endpoint/path",
491
- # "method": "GET|POST|PUT|DELETE",
492
- # "params": {{}},
493
- # "missing_required": []
 
 
 
494
  # }}
495
 
496
- # Now analyze the user query step by step and give me the JSON response.
497
- # """,
498
- # input_variables=["user_query", "detected_language", "extracted_keywords",
499
- # "sentiment_analysis", "endpoints_documentation", "current_datetime", "timezone"]
500
- # )
501
-
502
- ''' First Approach '''
503
- # self.router_prompt_template = PromptTemplate(
504
- # template="""
505
- # You are a routing system. Your job is simple:
506
- # 1. Understand what the user wants
507
- # 2. Check if any endpoint can do what they want
508
- # 3. If yes = API_ACTION, if no = CONVERSATION
509
-
510
- # ## Available API Endpoints Documentation
511
- # {endpoints_documentation}
512
 
513
- # ## User Query to Analyze
514
- # Query: "{user_query}"
515
- # Language: {detected_language}
516
-
517
- # ## Step-by-Step Analysis
518
-
519
- # **STEP 1: What does the user want?**
520
- # - If query is in Arabic, translate it to English first
521
- # - Identify the exact action or information the user is requesting
522
- # - Focus on understanding their underlying need, not just the words
523
-
524
- # **STEP 2: Find matching endpoint**
525
- # - Read each endpoint description in the documentation
526
- # - Check if any endpoint's purpose can fulfill what the user wants
527
- # - Match based on functionality, not keywords
528
-
529
- # **STEP 3: Decision**
530
- # - Found matching endpoint = "API_ACTION"
531
- # - No matching endpoint = "CONVERSATION"
532
-
533
- # ## Output Format
534
- # {{
535
- # "intent": "CONVERSATION|API_ACTION",
536
- # "confidence": 0.8,
537
- # "reasoning": "User wants: [what user actually needs]. Found endpoint: [endpoint path and why it matches] OR No endpoint matches this need",
538
- # "endpoint": "/exact/endpoint/path",
539
- # "method": "GET|POST|PUT|DELETE",
540
- # "params": {{}},
541
- # "missing_required": []
542
- # }}
543
-
544
- # Now analyze the user query step by step and give me the JSON response.
545
- # """,
546
- # input_variables=["user_query", "detected_language", "extracted_keywords",
547
- # "sentiment_analysis", "endpoints_documentation"]
548
- # )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
549
  # CONVERSATION CHAIN - Handles conversational responses
550
  self.conversation_template = PromptTemplate(
551
  template="""
552
- You are a friendly and professional healthcare chatbot assistant.
553
 
554
- === RESPONSE GUIDELINES ===
555
- - Respond ONLY in {detected_language}
556
- - Be helpful, empathetic, and professional
557
- - Keep responses concise but informative
558
- - Use appropriate medical terminology when needed
559
- - Maintain a caring and supportive tone
560
-
561
- === CONTEXT ===
562
- User Message: {user_query}
563
  Language: {detected_language}
564
  Sentiment: {sentiment_analysis}
565
- Conversation History: {conversation_history}
566
-
567
- === LANGUAGE-SPECIFIC INSTRUCTIONS ===
568
 
569
- FOR ARABIC RESPONSES:
570
- - Use Modern Standard Arabic (الفصحى)
571
- - Be respectful and formal as appropriate in Arabic culture
572
- - Use proper Arabic medical terminology
573
- - Keep sentences clear and grammatically correct
574
 
575
- FOR ENGLISH RESPONSES:
576
- - Use clear, professional English
577
- - Be warm and approachable
578
- - Use appropriate medical terminology
579
 
580
- === RESPONSE RULES ===
581
- 1. Address the user's question or comment directly
582
  2. Provide helpful information when possible
583
- 3. If you cannot help with something specific, explain what you CAN help with
584
- 4. Never provide specific medical advice - always recommend consulting healthcare professionals
585
- 5. Be encouraging and supportive
586
- 6. Do NOT mix languages in your response
587
- 7. End responses naturally without asking multiple questions
588
 
589
- Generate a helpful conversational response:""",
590
  input_variables=["user_query", "detected_language", "sentiment_analysis", "conversation_history"]
591
  )
592
 
593
- # API RESPONSE CHAIN - Formats API responses for users
594
- # self.api_response_template = PromptTemplate(
595
- # template="""
596
- # You are a professional healthcare assistant. Answer the user's question using the provided API data.
597
-
598
- # User Query: {user_query}
599
- # User Sentiment: {sentiment_analysis}
600
- # Response Language: {detected_language}
601
-
602
- # API Response Data:
603
- # {api_response}
604
-
605
- # === INSTRUCTIONS ===
606
-
607
- # 1. Read and understand the API response data above
608
- # 2. Use ONLY the actual data from the API response - never make up information
609
- # 3. Respond in {detected_language} language only
610
- # 4. Write like you're talking to a friend or family member - warm, friendly, and caring
611
- # 5. Make it sound natural and conversational, not like a system message
612
- # 6. Convert technical data to simple, everyday language
613
-
614
- # === DATE AND TIME FORMATTING ===
615
-
616
- # When you see date_time fields like '2025-05-30T10:28:10':
617
- # - For English: Convert to "May 30, 2025 at 10:28 AM"
618
- # - For Arabic: Convert to "٣٠ مايو ٢٠٢٥ في الساعة ١٠:٢٨ صباحاً"
619
-
620
- # === RESPONSE EXAMPLES ===
621
-
622
- # For appointment confirmations:
623
- # - English: "Great! I've got your appointment set up for May 30, 2025 at 10:28 AM. Everything looks good!"
624
- # - Arabic: "ممتاز! موعدك محجوز يوم ٣٠ مايو ٢٠٢٥ الساعة ١٠:٢٨ صباحاً. كل شيء جاهز!"
625
-
626
- # For appointment info:
627
- # - English: "Your next appointment is on May 30, 2025 at 10:28 AM. See you then!"
628
- # - Arabic: "موعدك القادم يوم ٣٠ مايو ٢٠٢٥ الساعة ١٠:٢٨ صباحاً. نراك قريباً!"
629
 
630
- # === TONE GUIDELINES ===
631
- # - Use friendly words like: "Great!", "Perfect!", "All set!", "ممتاز!", "رائع!", "تمام!"
632
- # - Add reassuring phrases: "Everything looks good", "You're all set", "كل شيء جاهز", "تم بنجاح"
633
- # - Sound helpful and caring, not robotic or formal
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
634
 
635
- # === LANGUAGE FORMATTING ===
636
-
637
- # For Arabic responses:
638
- # - Use Arabic numerals: ٠١٢٣٤٥٦٧٨٩
639
- # - Use Arabic month names: يناير، فبراير، مارس، أبريل، مايو، يونيو، يوليو، أغسطس، سبتمبر، أكتوبر، نوفمبر، ديسمبر
640
- # - Friendly, warm Arabic tone
641
-
642
- # For English responses:
643
- # - Use standard English numerals
644
- # - 12-hour time format with AM/PM
645
- # - Friendly, conversational English tone
646
-
647
- # === CRITICAL RULES ===
648
- # - Extract dates and times exactly as they appear in the API response
649
- # - Never use example dates or placeholder information
650
- # - Respond only in the specified language
651
- # - Make your response sound like a helpful friend, not a computer
652
- # - Focus on answering the user's specific question with warmth and care
653
-
654
- # Generate a friendly, helpful response using the API data provided above.
655
- # """,
656
- # input_variables=["user_query", "api_response", "detected_language", "sentiment_analysis"]
657
- # )
658
- self.api_response_template = PromptTemplate(
659
- template="""
660
- You are a professional healthcare assistant. Generate a natural language response to the user's query using ONLY the provided API data.
661
-
662
- User Query: {user_query}
663
- User Sentiment: {sentiment_analysis}
664
- Response Language: {detected_language}
665
-
666
- API Response Data:
667
- {api_response}
668
-
669
- === CORE INSTRUCTIONS ===
670
-
671
- 1. Analyze the API response structure and extract relevant data points
672
- 2. Cross-reference with the user's query to determine what information to include
673
- 3. Respond in {detected_language} using a warm, conversational tone
674
- 4. Convert technical data into natural language appropriate for healthcare communication
675
-
676
- === DATE/TIME HANDLING ===
677
-
678
- 1. Identify all date/time fields in the API response (look for ISO 8601 format: YYYY-MM-DDTHH:MM:SS)
679
- 2. For English responses:
680
- - Format dates as "Month Day, Year at HH:MM AM/PM"
681
- - Convert times to 12-hour format with proper AM/PM
682
- 3. For Arabic responses:
683
- - Format dates as "Day Month Year الساعة HH:MM صباحاً/مساءً"
684
- - Use Arabic numerals (٠١٢٣٤٥٦٧٨٩)
685
- - Use Arabic month names
686
- 4. Preserve all original date/time values - only change the formatting
687
-
688
- === RESPONSE GUIDELINES ===
689
-
690
- 1. Use ONLY data present in the API response
691
- 2. Maintain a professional yet friendly healthcare tone
692
- 3. Adapt to the user's sentiment:
693
- - Positive: reinforce with encouraging language
694
- - Neutral: provide clear, factual information
695
- - Negative: show empathy and offer assistance
696
- 4. Structure the response to directly answer the user's query
697
- 5. Include relevant details from the API response that address the user's needs
698
-
699
- === CRITICAL RULES ===
700
-
701
- 1. Never invent or hallucinate information not present in the API response
702
- 2. If the API response doesn't contain requested information, say so politely
703
- 3. All dates/times must exactly match the API data
704
- 4. Maintain strict language consistency (respond only in {detected_language})
705
- 5. Format all technical data (IDs, codes, etc.) for easy understanding
706
-
707
- Generate a helpful response that addresses the user's query using the API data.
708
- """,
709
- input_variables=["user_query", "api_response", "detected_language", "sentiment_analysis"]
710
- )
711
 
712
  # Create the 3 chains
713
  self.router_chain = LLMChain(llm=self.llm, prompt=self.router_prompt_template)
@@ -1094,7 +792,7 @@ class HealthcareChatbot:
1094
  api_data=None
1095
  )
1096
 
1097
- elif router_data["intent"] == "API_ACTION":
1098
  print(f"\n🔗 Handling as API_ACTION")
1099
 
1100
  # Check for missing required parameters
@@ -1131,18 +829,18 @@ class HealthcareChatbot:
1131
  language=detected_language
1132
  )
1133
 
1134
- else:
1135
- # Fallback for unknown intent
1136
- print(f"⚠️ Unknown intent: {router_data['intent']}")
1137
- fallback_response = self.handle_conversation(user_message, detected_language, sentiment_result)
1138
 
1139
- return ChatResponse(
1140
- response_id=str(time.time()),
1141
- response_type="conversation",
1142
- message=fallback_response,
1143
- api_call_made=False,
1144
- language=detected_language
1145
- )
1146
 
1147
  except Exception as e:
1148
  print(f"❌ Error in chat method: {str(e)}")
@@ -1223,7 +921,6 @@ class HealthcareChatbot:
1223
  # if __name__ == "__main__":
1224
  # main()
1225
 
1226
-
1227
  from fastapi import FastAPI, HTTPException
1228
  from pydantic import BaseModel
1229
  from typing import Dict, Any, Optional
 
68
  self.endpoints_documentation = endpoints_documentation
69
  self.ollama_base_url = "http://localhost:11434"
70
  self.model_name = "gemma3"
71
+ self.BASE_URL = 'https://2ab0-197-54-60-164.ngrok-free.app'
72
  self.headers = {'Content-type': 'application/json'}
73
+ self.user_id = '98d485d1-2691-4aee-ad60-977825c1f794'
74
  self.max_retries = 3
75
  self.retry_delay = 2
76
 
 
155
  self.json_parser = JsonOutputParser(pydantic_object=RouterResponse)
156
 
157
  # UNIFIED ROUTER CHAIN - Handles both intent classification AND API routing
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  # self.router_prompt_template = PromptTemplate(
159
+ # template="""
160
+ # You are a routing system. Analyze user intent and handle dates precisely.
 
 
 
 
 
 
 
161
 
162
+ # CONTEXT:
163
  # Query: "{user_query}"
164
  # Language: {detected_language}
165
+ # Current: {current_datetime} ({current_day_name})
166
+ # Timezone: {timezone}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
+ # ENDPOINTS:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  # {endpoints_documentation}
170
 
171
+ # ANALYSIS STEPS:
172
+ # 1. **Intent**: What does the user want? (translate Arabic to English first)
173
+ # 2. **Date/Time**: Calculate precisely using current datetime as base
174
+ # 3. **Match**: Find endpoint that can fulfill the request
175
+ # 4. **Decision**: Matching endpoint = API_ACTION, else CONVERSATION
176
+
177
+ # DATE CALCULATIONS (use {current_datetime} as base):
178
+ # Today/اليوم = current date
179
+ # • Tomorrow/غدا = +1 day
180
+ # Next week/الأسبوع القادم = +7 days
181
+ # Next [weekday]/يوم [weekday] القادم: Calculate days to target weekday
182
+ # - Weekdays: الأحد=0, الاثنين=1, الثلاثاء=2, الأربعاء=3, الخميس=4, الجمعة=5, السبت=6
183
+ # - Formula: If target > current: target-current, else: 7-(current-target)
184
+ # • Times: صباحًا=09:00, مساءً=18:00, ظهرًا=12:00
185
+ # Format: YYYY-MM-DDTHH:MM:SS
186
+
187
+ # OUTPUT FORMAT:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  # {{
189
  # "intent": "CONVERSATION|API_ACTION",
190
  # "confidence": 0.8,
191
+ # "reasoning": "User wants: [need]. Date calc: [show work]. Endpoint: [path/reason]",
192
+ # "endpoint": "/exact/path" or null,
193
+ # "method": "GET|POST|PUT|DELETE" or null,
194
+ # "params": {{
195
+ # // ALL VALUES IN ENGLISH - translate Arabic names/terms
196
+ # }},
197
+ # "missing_required": [],
198
+ # "calculated_datetime": "YYYY-MM-DDTHH:MM:SS" or null
199
  # }}
200
 
201
+ # CRITICAL RULES:
202
+ # • Use {current_datetime} for ALL date calculations
203
+ # Show calculation work in reasoning
204
+ # Translate ALL Arabic parameters to English
205
+ # • Match endpoints by functionality, not keywords
 
 
 
 
 
 
 
 
 
 
 
206
 
207
+ # Analyze and respond with JSON:""",
208
+ # input_variables=["user_query", "detected_language", "extracted_keywords",
209
+ # "sentiment_analysis", "endpoints_documentation", "current_datetime",
210
+ # "timezone", "current_day_name"]
211
+ # )
212
+ self.router_prompt_template = PromptTemplate(
213
+ template="""
214
+ You are a routing system. Analyze user intent and handle dates precisely.
215
+
216
+ CONTEXT:
217
+ Query: "{user_query}"
218
+ Language: {detected_language}
219
+ Current: {current_datetime} ({current_day_name})
220
+ Timezone: {timezone}
221
+
222
+ ENDPOINTS:
223
+ {endpoints_documentation}
224
+
225
+ ANALYSIS STEPS:
226
+ 1. **Intent**: What does the user want? (translate Arabic to English first)
227
+ 2. **Translation**: Convert ALL Arabic text to English equivalents
228
+ 3. **Date/Time**: Calculate precisely using current datetime as base
229
+ 4. **Match**: Find endpoint that can fulfill the request
230
+ 5. **Decision**: Matching endpoint = API_ACTION, else CONVERSATION
231
+
232
+ TRANSLATION REQUIREMENTS:
233
+ ALL parameter values MUST be in English
234
+ • Arabic names: محمد→Mohammed, أحمد→Ahmed, فاطمة→Fatima, علي→Ali, etc.
235
+ • Arabic terms: طبيب→doctor, مريض→patient, حجز→booking, موعد→appointment
236
+ • Arabic reasons: صداع→headache, حمى→fever, فحص→checkup, استشارة→consultation
237
+ • NO Arabic characters allowed in final params
238
+
239
+ DATE CALCULATIONS (use {current_datetime} as base):
240
+ • Today/اليوم = current date
241
+ Tomorrow/غدا = +1 day
242
+ • Next week/الأسبوع القادم = +7 days
243
+ • Next [weekday]/يوم [weekday] القادم: Calculate days to target weekday
244
+ - Weekdays: الأحد=0, الاثنين=1, الثلاثاء=2, الأربعاء=3, الخميس=4, الجمعة=5, السبت=6
245
+ - Formula: If target > current: target-current, else: 7-(current-target)
246
+ • Times: صباحًا=09:00, مساءً=18:00, ظهرًا=12:00
247
+ • Format: YYYY-MM-DDTHH:MM:SS
248
+
249
+ PARAMETER VALIDATION:
250
+ Before outputting, verify each param value:
251
+ - Is it in English? ✓/✗
252
+ - Contains Arabic characters? ✗ (reject if yes)
253
+ - Properly translated? ✓/✗
254
+
255
+ OUTPUT FORMAT:
256
+ {{
257
+ "intent": "CONVERSATION|API_ACTION",
258
+ "confidence": 0.8,
259
+ "reasoning": "User wants: [need in English]. Translation applied: [Arabic→English]. Date calc: [show work]. Endpoint: [path/reason]",
260
+ "endpoint": "/exact/path" or null,
261
+ "method": "GET|POST|PUT|DELETE" or null,
262
+ "params": {{
263
+ // MANDATORY: ALL VALUES MUST BE IN ENGLISH
264
+ // Example: "doctor_name": "Mohammed" NOT "محمد"
265
+ }},
266
+ "missing_required": [],
267
+ "calculated_datetime": "YYYY-MM-DDTHH:MM:SS" or null
268
+ }}
269
+
270
+ CRITICAL RULES:
271
+ • Use {current_datetime} for ALL date calculations
272
+ • MANDATORY: Translate ALL Arabic text to English in params
273
+ • Show translation work: "محمد→Mohammed" in reasoning
274
+ • Reject output if ANY param contains Arabic characters
275
+ • Match endpoints by functionality, not keywords
276
+
277
+ VALIDATION CHECK:
278
+ Before final output, ask: "Are ALL param values in English?" If NO, translate them.
279
+
280
+ Analyze and respond with JSON:""",
281
+ input_variables=["user_query", "detected_language", "extracted_keywords",
282
+ "sentiment_analysis", "endpoints_documentation", "current_datetime",
283
+ "timezone", "current_day_name"]
284
+ )
285
+
286
  # CONVERSATION CHAIN - Handles conversational responses
287
  self.conversation_template = PromptTemplate(
288
  template="""
289
+ You are a friendly healthcare chatbot assistant.
290
 
291
+ CONTEXT:
292
+ Message: {user_query}
 
 
 
 
 
 
 
293
  Language: {detected_language}
294
  Sentiment: {sentiment_analysis}
 
 
 
295
 
296
+ RESPONSE GUIDELINES:
297
+ Respond ONLY in {detected_language}
298
+ Be helpful, empathetic, and professional
299
+ Keep responses concise but informative
300
+ Use caring and supportive tone
301
 
302
+ LANGUAGE SPECIFICS:
303
+ Arabic: Use Modern Standard Arabic (الفصحى), formal tone, proper medical terms
304
+ English: Clear professional language, warm and approachable
 
305
 
306
+ RULES:
307
+ 1. Address user's question directly
308
  2. Provide helpful information when possible
309
+ 3. Never give specific medical advice - recommend healthcare professionals
310
+ 4. Be encouraging and supportive
311
+ 5. Don't mix languages
312
+ 6. End naturally without multiple questions
 
313
 
314
+ Generate a helpful response:""",
315
  input_variables=["user_query", "detected_language", "sentiment_analysis", "conversation_history"]
316
  )
317
 
318
+ self.api_response_template = PromptTemplate(
319
+ template="""
320
+ You are a friendly healthcare assistant. Answer using the API data provided.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
 
322
+ CONTEXT:
323
+ Query: {user_query}
324
+ Language: {detected_language}
325
+ API Data: {api_response}
326
+
327
+ INSTRUCTIONS:
328
+ • Use ONLY actual API data - never make up information
329
+ • Respond in {detected_language} only
330
+ • Sound warm and conversational, like talking to a friend
331
+ • Convert technical data to simple language
332
+
333
+ DATE/TIME FORMAT:
334
+ '2025-05-30T10:28:10' →
335
+ • English: "May 30, 2025 at 10:28 AM"
336
+ • Arabic: "٣٠ مايو ٢٠٢٥ في الساعة ١٠:٢٨ صباحاً"
337
+
338
+ TONE:
339
+ • Friendly starters: "Great!", "Perfect!", "ممتاز!", "رائع!"
340
+ • Reassuring: "Everything looks good", "كل شيء جاهز"
341
+ • Natural conversation, not robotic
342
+
343
+ LANGUAGE SPECIFICS:
344
+ Arabic: Use Arabic numerals (٠١٢٣٤٥٦٧٨٩) and month names
345
+ English: 12-hour format with AM/PM
346
+
347
+ EXAMPLES:
348
+ Appointment confirmed:
349
+ • English: "Great! Your appointment is set for May 30, 2025 at 10:28 AM!"
350
+ • Arabic: "ممتاز! موعدك محجوز يوم ٣٠ مايو ٢٠٢٥ الساعة ١٠:٢٨ صباحاً!"
351
+
352
+ Generate a friendly response using the API data:""",
353
+ input_variables=["user_query", "api_response", "detected_language", "sentiment_analysis"]
354
+ )
355
 
356
+ # self.api_response_template = PromptTemplate(
357
+ # template="""
358
+ # You are a professional healthcare assistant. Generate a natural language response to the user's query using ONLY the provided API data.
359
+
360
+ # User Query: {user_query}
361
+ # User Sentiment: {sentiment_analysis}
362
+ # Response Language: {detected_language}
363
+
364
+ # API Response Data:
365
+ # {api_response}
366
+
367
+ # === CORE INSTRUCTIONS ===
368
+
369
+ # 1. Analyze the API response structure and extract relevant data points
370
+ # 2. Cross-reference with the user's query to determine what information to include
371
+ # 3. Respond in {detected_language} using a warm, conversational tone
372
+ # 4. Convert technical data into natural language appropriate for healthcare communication
373
+
374
+ # === DATE/TIME HANDLING ===
375
+
376
+ # 1. Identify all date/time fields in the API response (look for ISO 8601 format: YYYY-MM-DDTHH:MM:SS)
377
+ # 2. For English responses:
378
+ # - Format dates as "Month Day, Year at HH:MM AM/PM"
379
+ # - Convert times to 12-hour format with proper AM/PM
380
+ # 3. For Arabic responses:
381
+ # - Format dates as "Day Month Year الساعة HH:MM صباحاً/مساءً"
382
+ # - Use Arabic numerals (٠١٢٣٤٥٦٧٨٩)
383
+ # - Use Arabic month names
384
+ # 4. Preserve all original date/time values - only change the formatting
385
+
386
+ # === RESPONSE GUIDELINES ===
387
+
388
+ # 1. Use ONLY data present in the API response
389
+ # 2. Maintain a professional yet friendly healthcare tone
390
+ # 3. Adapt to the user's sentiment:
391
+ # - Positive: reinforce with encouraging language
392
+ # - Neutral: provide clear, factual information
393
+ # - Negative: show empathy and offer assistance
394
+ # 4. Structure the response to directly answer the user's query
395
+ # 5. Include relevant details from the API response that address the user's needs
396
+
397
+ # === CRITICAL RULES ===
398
+
399
+ # 1. Never invent or hallucinate information not present in the API response
400
+ # 2. If the API response doesn't contain requested information, say so politely
401
+ # 3. All dates/times must exactly match the API data
402
+ # 4. Maintain strict language consistency (respond only in {detected_language})
403
+ # 5. Format all technical data (IDs, codes, etc.) for easy understanding
404
+
405
+ # Generate a helpful response that addresses the user's query using the API data.
406
+ # """,
407
+ # input_variables=["user_query", "api_response", "detected_language", "sentiment_analysis"]
408
+ # )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
409
 
410
  # Create the 3 chains
411
  self.router_chain = LLMChain(llm=self.llm, prompt=self.router_prompt_template)
 
792
  api_data=None
793
  )
794
 
795
+ else:
796
  print(f"\n🔗 Handling as API_ACTION")
797
 
798
  # Check for missing required parameters
 
829
  language=detected_language
830
  )
831
 
832
+ # else:
833
+ # # Fallback for unknown intent
834
+ # print(f"⚠️ Unknown intent: {router_data['intent']}")
835
+ # fallback_response = self.handle_conversation(user_message, detected_language, sentiment_result)
836
 
837
+ # return ChatResponse(
838
+ # response_id=str(time.time()),
839
+ # response_type="conversation",
840
+ # message=fallback_response,
841
+ # api_call_made=False,
842
+ # language=detected_language
843
+ # )
844
 
845
  except Exception as e:
846
  print(f"❌ Error in chat method: {str(e)}")
 
921
  # if __name__ == "__main__":
922
  # main()
923
 
 
924
  from fastapi import FastAPI, HTTPException
925
  from pydantic import BaseModel
926
  from typing import Dict, Any, Optional