abdibrahem commited on
Commit
845e045
ยท
1 Parent(s): f66a3b2
Files changed (1) hide show
  1. main.py +92 -112
main.py CHANGED
@@ -194,138 +194,118 @@ class HealthcareChatbot:
194
  # API routing prompt (reuse existing router_prompt_template)
195
  self.router_prompt_template = PromptTemplate(
196
  template="""
197
- You are a STRICT API routing assistant that MUST analyze every single endpoint description thoroughly before making any routing decision. You are FORBIDDEN from selecting any endpoint without explicit justification from its documented description.
198
 
199
  === CURRENT CONTEXT ===
200
  Current Date/Time: {current_datetime}
201
  Current Timezone: {timezone}
202
  User Location/Locale: {user_locale}
203
 
204
- === AVAILABLE ENDPOINTS ===
205
  {endpoints_documentation}
206
 
207
- === USER REQUEST DETAILS ===
208
  User Query: {user_query}
209
- Detected Language: {detected_language}
210
- Extracted Keywords: {extracted_keywords}
211
- Sentiment Analysis: {sentiment_analysis}
212
  Conversation History: {conversation_history}
213
 
214
- === MANDATORY STEP-BY-STEP ANALYSIS PROTOCOL ===
215
-
216
- STEP 1: PRECISE USER INTENT EXTRACTION
217
- Analyze the user query word by word:
218
- - CORE ACTION: What is the user trying to DO? (Examples: create appointment, cancel booking, get patient info, update schedule, list available slots)
219
- - TARGET RESOURCE: What specific thing are they acting on? (appointment, patient, doctor, schedule, availability)
220
- - SPECIFIC DETAILS: What exact information or conditions did they mention?
221
- - CONTEXT CLUES: What can be inferred from conversation history?
222
- - EXPECTED OUTCOME: What result does the user expect to receive?
223
-
224
- STEP 2: EXHAUSTIVE ENDPOINT DESCRIPTION ANALYSIS
225
- For EVERY SINGLE endpoint in the documentation, you MUST:
226
-
227
- A) READ THE DESCRIPTION COMPLETELY
228
- - Quote the exact description text from documentation
229
- - Identify what business function this endpoint serves
230
- - Understand what problem it solves for users
231
-
232
- B) ANALYZE USAGE SCENARIOS
233
- - When would someone use this endpoint?
234
- - What user intentions does this endpoint address?
235
- - What are the typical use cases mentioned in description?
236
-
237
- C) MATCH AGAINST USER QUERY
238
- - Does the endpoint description match user's intent? (EXACT MATCH/PARTIAL MATCH/NO MATCH)
239
- - Quote specific words from description that relate to user query
240
- - Identify any gaps between user intent and endpoint purpose
241
-
242
- D) PARAMETER RELEVANCE CHECK
243
- - Do the required parameters make sense for user's request?
244
- - Are the parameters mentioned in user query or conversation history?
245
- - Can all required parameters be satisfied from available information?
246
-
247
- STEP 3: ENDPOINT ELIMINATION PROCESS
248
- Go through each endpoint and explicitly state:
249
- - ENDPOINT NAME: [exact path from documentation]
250
- - DESCRIPTION QUOTE: "[exact description text from documentation]"
251
- - INTENT MATCH ANALYSIS: Does this solve user's problem? Why or why not?
252
- - DECISION: KEEP or ELIMINATE (with detailed reasoning)
253
-
254
- Continue until only compatible endpoints remain.
255
-
256
- STEP 4: FINAL SELECTION WITH PROOF
257
- From remaining endpoints, select the BEST match by:
258
- - DESCRIPTION ALIGNMENT: Which description most closely matches user intent?
259
- - PARAMETER COMPLETENESS: Which endpoint has the most satisfiable parameters?
260
- - USE CASE FIT: Which endpoint's documented use cases best match the user's scenario?
261
-
262
- You MUST provide direct quotes from the selected endpoint's description that justify your choice.
263
-
264
- STEP 5: PARAMETER EXTRACTION WITH VALIDATION
265
- For the selected endpoint:
266
- - Extract ONLY parameters that are explicitly documented
267
- - Convert dates to YYYY-MM-DDTHH:mm:ss format:
268
- * "today" โ†’ {current_datetime}T08:00:00 (or specified time)
269
- * "tomorrow" โ†’ current date + 1 day + time
270
- * "3 PM" โ†’ 15:00:00
271
- * "morning" โ†’ 08:00:00, "afternoon" โ†’ 14:00:00, "evening" โ†’ 18:00:00
272
- - Validate each parameter against documented constraints
273
- - Mark any required parameters that cannot be extracted from user query or context
274
-
275
- === STRICT VALIDATION RULES ===
276
- Before making ANY routing decision:
277
-
278
- โœ“ DESCRIPTION MATCH: The selected endpoint's description MUST clearly relate to user's intent
279
- โœ“ USE CASE ALIGNMENT: The endpoint's documented use cases MUST include user's scenario
280
- โœ“ PARAMETER COMPATIBILITY: All required parameters MUST be extractable or identifiable as missing
281
- โœ“ NO FABRICATION: Never assume endpoint capabilities not mentioned in description
282
- โœ“ NO GUESSING: Never select endpoints based on path names alone - ONLY use descriptions
283
- โœ“ QUOTE REQUIREMENT: You MUST quote relevant parts of endpoint description in your reasoning
284
-
285
- === RESPONSE FORMAT (MAINTAIN EXACTLY) ===
286
  {{
287
  "reasoning": {{
288
- "user_intent": "Precise description of what user wants to accomplish",
289
- "selected_endpoint": "Why this endpoint was chosen - MUST include direct quotes from endpoint description that match user intent",
290
- "parameter_mapping": "How each parameter maps to user query with validation against documentation"
291
  }},
292
  "endpoint": "/exact_endpoint_path_from_documentation",
293
- "method": "HTTP_METHOD_FROM_DOCUMENTATION",
294
  "params": {{
295
- "required_param_1": "extracted_value_in_correct_format",
296
- "required_param_2": "extracted_value_in_correct_format",
297
- "optional_param": "value_if_available"
298
  }},
299
- "missing_required": ["list_of_required_parameters_not_extractable_from_query"],
300
  "confidence": 0.95
301
  }}
302
 
303
- === CRITICAL ANALYSIS REQUIREMENTS ===
304
-
305
- 1. **DESCRIPTION-DRIVEN SELECTION**: Your choice MUST be based on endpoint descriptions, not endpoint names or assumptions
306
-
307
- 2. **EXPLICIT REASONING**: Quote exact text from endpoint description that supports your selection
308
-
309
- 3. **COMPREHENSIVE COMPARISON**: Analyze ALL endpoints before selecting - show your elimination process
310
-
311
- 4. **NO SHORTCUTS**: Never select based on partial information or assumptions
312
-
313
- 5. **PARAMETER PRECISION**: Only use parameters explicitly documented for the selected endpoint
314
-
315
- 6. **DATE FORMAT COMPLIANCE**: All dates MUST be in YYYY-MM-DDTHH:mm:ss format
316
-
317
- 7. **CONFIDENCE HONESTY**: Base confidence on how well endpoint description matches user intent
318
-
319
- === EXAMPLE ANALYSIS STRUCTURE ===
320
- "I analyzed all endpoints in the documentation:
321
-
322
- - /endpoint1: Description states '[quote description]' - This does NOT match user intent because [specific reason]
323
- - /endpoint2: Description states '[quote description]' - This PARTIALLY matches because [specific reason]
324
- - /endpoint3: Description states '[quote description]' - This EXACTLY matches because [specific reason]
325
-
326
- Selected /endpoint3 because its description '[relevant quote]' directly addresses the user's need to [user intent]."
327
-
328
- Now analyze the user query against EVERY endpoint description in the documentation. Show your complete analysis process and select the endpoint whose description best matches the user's intent.
 
329
  """,
330
  input_variables=[
331
  "endpoints_documentation", "user_query", "detected_language",
 
194
  # API routing prompt (reuse existing router_prompt_template)
195
  self.router_prompt_template = PromptTemplate(
196
  template="""
197
+ You are a precise API routing assistant. Your job is to analyze user queries and select the correct API endpoint with proper parameters.
198
 
199
  === CURRENT CONTEXT ===
200
  Current Date/Time: {current_datetime}
201
  Current Timezone: {timezone}
202
  User Location/Locale: {user_locale}
203
 
204
+ === ENDPOINT DOCUMENTATION ===
205
  {endpoints_documentation}
206
 
207
+ === USER REQUEST ANALYSIS ===
208
  User Query: {user_query}
209
+ Language: {detected_language}
210
+ Keywords: {extracted_keywords}
211
+ Sentiment: {sentiment_analysis}
212
  Conversation History: {conversation_history}
213
 
214
+ === ROUTING PROCESS ===
215
+ Follow these steps in order:
216
+
217
+ STEP 1: INTENT ANALYSIS
218
+ - What is the user trying to accomplish?
219
+ - What type of operation are they requesting? (create, read, update, delete, search, etc.)
220
+ - What entity/resource are they working with?
221
+
222
+ STEP 2: ENDPOINT MATCHING
223
+ - Review each endpoint in the documentation
224
+ - Match the user's intent to the endpoint's PURPOSE/DESCRIPTION
225
+ - Consider the HTTP method (GET for retrieval, POST for creation, etc.)
226
+ - Verify the endpoint can handle the user's specific request
227
+
228
+ STEP 3: PARAMETER EXTRACTION WITH DATE HANDLING
229
+ - Identify ALL required parameters from the endpoint documentation
230
+ - Extract parameter values from the user query and conversation history
231
+ - Handle date/time expressions with precision:
232
+ * RELATIVE TIME CONVERSION:
233
+ - "today" โ†’ current date (from current_datetime) + specified time or T08:00:00
234
+ - "tomorrow" โ†’ current date + 1 day + specified time or T08:00:00
235
+ - "yesterday" โ†’ current date - 1 day + specified time or T08:00:00
236
+ - "next week" โ†’ current date + 7 days + specified time or T08:00:00
237
+ - "in 2 hours" โ†’ current datetime + 2 hours
238
+ - "next Monday/Tuesday/etc." โ†’ calculate exact date + specified time or T08:00:00
239
+ * TIME EXPRESSIONS:
240
+ - "morning" โ†’ 08:00:00
241
+ - "afternoon" โ†’ 14:00:00
242
+ - "evening" โ†’ 18:00:00
243
+ - "3 PM" โ†’ 15:00:00
244
+ - "10:30 AM" โ†’ 10:30:00
245
+ * ARABIC TIME EXPRESSIONS:
246
+ - "ุงู„ูŠูˆู…" (today) โ†’ current date + time
247
+ - "ุบุฏุง" (tomorrow) โ†’ current date + 1 day + time
248
+ - "ุฃู…ุณ" (yesterday) โ†’ current date - 1 day + time
249
+ - "ุงู„ุตุจุงุญ" (morning) โ†’ 08:00:00
250
+ - "ุจุนุฏ ุงู„ุธู‡ุฑ" (afternoon) โ†’ 14:00:00
251
+ - "ุงู„ู…ุณุงุก" (evening) โ†’ 18:00:00
252
+ - Convert ALL dates to ISO 8601 format: YYYY-MM-DDTHH:mm:ss
253
+ - Convert data types as needed (numbers to integers, booleans, etc.)
254
+ - Set appropriate defaults for optional parameters if beneficial
255
+
256
+ STEP 4: VALIDATION
257
+ - Ensure ALL required parameters are provided or identified as missing
258
+ - Verify parameter formats match documentation requirements
259
+ - Check that the selected endpoint actually solves the user's problem
260
+ - Validate date formats are exactly YYYY-MM-DDTHH:mm:ss
261
+
262
+ === RESPONSE FORMAT ===
263
+ Provide your analysis and decision in this exact JSON structure:
264
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  {{
266
  "reasoning": {{
267
+ "user_intent": "Brief description of what the user wants to accomplish",
268
+ "selected_endpoint": "Why this endpoint was chosen over others",
269
+ "parameter_mapping": "How user query maps to endpoint parameters"
270
  }},
271
  "endpoint": "/exact_endpoint_path_from_documentation",
272
+ "method": "HTTP_METHOD",
273
  "params": {{
274
+ "required_param_1": "extracted_or_converted_value",
275
+ "required_param_2": "extracted_or_converted_value",
276
+ "optional_param": "value_if_applicable"
277
  }},
278
+ "missing_required": ["list", "of", "missing", "required", "parameters"],
279
  "confidence": 0.95
280
  }}
281
 
282
+ === CRITICAL RULES ===
283
+ 1. ONLY select endpoints that exist in the provided documentation
284
+ 2. NEVER fabricate or assume endpoint parameters not in documentation
285
+ 3. ALL required parameters MUST be included or listed as missing
286
+ 4. Convert dates/times to ISO 8601 format (YYYY-MM-DDTHH:mm:ss) - this is MANDATORY
287
+ 5. If patient_id is required and not provided, add it to missing_required
288
+ 6. Match endpoints by PURPOSE/DESCRIPTION, not just keywords in the path
289
+ 7. If multiple endpoints could work, choose the most specific one
290
+ 8. If no endpoint matches, set endpoint to null and explain in reasoning
291
+ 9. Use conversation history to extract missing context (patient IDs, previous dates, etc.)
292
+ 10. Handle timezone considerations using the provided timezone context
293
+
294
+ === DATE FORMATTING EXAMPLES ===
295
+ - Current datetime: 2025-05-31T10:30:00
296
+ - "today at 3 PM" โ†’ 2025-05-31T15:00:00
297
+ - "tomorrow morning" โ†’ 2025-06-01T08:00:00
298
+ - "next Tuesday at 2:30 PM" โ†’ calculate exact date + T14:30:00
299
+ - "in 3 hours" โ†’ 2025-05-31T13:30:00
300
+
301
+ === EXAMPLES OF GOOD MATCHING ===
302
+ - User wants "patient records" โ†’ Use patient retrieval endpoint, not general search
303
+ - User wants to "schedule appointment" โ†’ Use appointment creation endpoint
304
+ - User asks "what appointments today" โ†’ Use appointment listing with date filter (today's date in YYYY-MM-DDTHH:mm:ss format)
305
+ - User wants to "update medication" โ†’ Use medication update endpoint with patient_id
306
+ - User says "cancel my appointment tomorrow" โ†’ Use appointment cancellation endpoint with tomorrow's date
307
+
308
+ Think step by step and be precise with your endpoint selection and parameter extraction. Pay special attention to date/time handling and ensure all dates are in the exact format YYYY-MM-DDTHH:mm:ss.
309
  """,
310
  input_variables=[
311
  "endpoints_documentation", "user_query", "detected_language",