abdibrahem commited on
Commit
6b4a7d2
Β·
1 Parent(s): 5bc59c9

Fix api prompt

Browse files
Files changed (1) hide show
  1. main.py +126 -117
main.py CHANGED
@@ -193,132 +193,141 @@ class HealthcareChatbot:
193
 
194
  # API routing prompt (reuse existing router_prompt_template)
195
  self.router_prompt_template = PromptTemplate(
196
- template="""
197
- You are an expert API routing assistant with deep analytical capabilities. Your role is to thoroughly understand user intentions and precisely match them with the most appropriate API endpoint after comprehensive analysis.
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
- === COMPREHENSIVE ANALYSIS PROCESS ===
215
-
216
- PHASE 1: DEEP QUERY UNDERSTANDING
217
- Thoroughly analyze the user's request by examining:
218
- - PRIMARY INTENT: What is the core action the user wants to perform?
219
- - SECONDARY INTENTS: Are there multiple actions or follow-up implications?
220
- - ENTITY IDENTIFICATION: What specific resources/objects are mentioned?
221
- - OPERATION TYPE: Create, Read, Update, Delete, Search, List, Filter, Aggregate?
222
- - IMPLICIT CONTEXT: What assumptions or unstated requirements exist?
223
- - URGENCY/PRIORITY: Is this time-sensitive or routine?
224
- - SCOPE: Single item, multiple items, or system-wide operation?
225
-
226
- PHASE 2: ENDPOINTS DOCUMENTATION COMPREHENSION
227
- For EACH endpoint in the documentation, analyze:
228
- - PURPOSE AND FUNCTIONALITY: What business problem does this endpoint solve?
229
- - REQUIRED VS OPTIONAL PARAMETERS: What data is absolutely necessary?
230
- - INPUT DATA TYPES AND FORMATS: How should data be structured?
231
- - EXPECTED OUTPUT: What will this endpoint return?
232
- - USE CASES: When would this endpoint be the best choice?
233
- - CONSTRAINTS AND LIMITATIONS: What are the boundaries of this endpoint?
234
- - RELATIONSHIP TO OTHER ENDPOINTS: How does it fit in the overall API ecosystem?
235
-
236
- PHASE 3: SEMANTIC MATCHING AND SCORING
237
- For each potential endpoint match:
238
- - INTENT ALIGNMENT SCORE (0-100): How well does the endpoint's purpose match user intent?
239
- - PARAMETER AVAILABILITY SCORE (0-100): How much required data can be extracted/inferred?
240
- - CONTEXT RELEVANCE SCORE (0-100): How well does this fit the conversation context?
241
- - OPERATIONAL COMPLEXITY SCORE (0-100): How straightforward is this operation?
242
- - TOTAL MATCH SCORE: Weighted average of above scores
243
-
244
- PHASE 4: TEMPORAL AND CONTEXTUAL PROCESSING
245
- Handle time-related expressions with precision:
246
- - RELATIVE TIME CONVERSION:
247
- * Arabic: Ψ§Ω„ΩŠΩˆΩ…/today, ΨΊΨ―Ψ§/tomorrow, Ψ£Ω…Ψ³/yesterday, Ψ¨ΨΉΨ―/after, Ω‚Ψ¨Ω„/before
248
- * English: today, tomorrow, yesterday, next week, in 2 hours, etc.
249
- * Context-aware: "next appointment", "usual time", "same day"
250
- - ABSOLUTE TIME PARSING:
251
- * Date formats: DD/MM/YYYY, MM-DD-YYYY, YYYY-MM-DD
252
- * Time formats: 12-hour (AM/PM), 24-hour, relative (morning/afternoon)
253
- - TIMEZONE CONSIDERATIONS:
254
- * Convert all times to user's timezone
255
- * Account for daylight saving time if applicable
256
- * Provide ISO 8601 formatted output
257
-
258
- PHASE 5: PARAMETER EXTRACTION AND VALIDATION
259
- Extract and validate ALL parameters:
260
- - DIRECT EXTRACTION: Explicitly mentioned values in user query
261
- - CONTEXTUAL INFERENCE: Values derivable from conversation history
262
- - TYPE CONVERSION: Ensure proper data types (string, int, float, datetime, boolean)
263
- - FORMAT VALIDATION: Check against endpoint requirements
264
- - DEFAULT VALUES: Apply sensible defaults for optional parameters
265
- - MISSING PARAMETER IDENTIFICATION: Clearly identify what's missing and why it's needed
266
-
267
- PHASE 6: DECISION VALIDATION AND CONFIDENCE ASSESSMENT
268
- Before finalizing the decision:
269
- - SANITY CHECK: Does this endpoint actually solve the user's problem?
270
- - ALTERNATIVE CONSIDERATION: Are there better endpoint options?
271
- - COMPLETENESS VERIFICATION: Are all required parameters available or obtainable?
272
- - EDGE CASE EVALUATION: What could go wrong with this choice?
273
- - CONFIDENCE CALCULATION: How certain are you about this routing decision?
274
-
275
- === RESPONSE FORMAT ===
276
- Provide your comprehensive analysis and decision in this exact JSON structure:
277
 
278
- {{
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
  "reasoning": {{
280
- "user_intent": "Brief description of what the user wants to accomplish",
281
- "selected_endpoint": "Why this endpoint was chosen over others",
282
- "parameter_mapping": "How user query maps to endpoint parameters"
283
  }},
284
  "endpoint": "/exact_endpoint_path_from_documentation",
285
- "method": "HTTP_METHOD",
286
  "params": {{
287
- "required_param_1": "extracted_or_converted_value",
288
- "required_param_2": "extracted_or_converted_value",
289
- "optional_param": "value_if_applicable"
290
  }},
291
- "missing_required": ["list", "of", "missing", "required", "parameters"],
292
  "confidence": 0.95
293
  }}
294
 
295
- === CRITICAL EXCELLENCE STANDARDS ===
296
- 1. **ACCURACY FIRST**: Only route to endpoints that exist in the documentation
297
- 2. **NO FABRICATION**: Never assume parameters or capabilities not explicitly documented
298
- 3. **COMPLETE UNDERSTANDING**: Demonstrate deep comprehension of both query and endpoints
299
- 4. **TEMPORAL PRECISION**: Handle all time expressions with mathematical accuracy
300
- 5. **CONTEXT MASTERY**: Leverage conversation history intelligently and completely
301
- 6. **MULTILINGUAL COMPETENCY**: Handle Arabic, English, and mixed-language queries flawlessly
302
- 7. **PARAMETER COMPLETENESS**: Account for every required parameter or clearly identify gaps
303
- 8. **CONFIDENCE HONESTY**: Provide realistic confidence scores with clear reasoning
304
- 9. **EDGE CASE AWARENESS**: Consider what could go wrong and prepare for it
305
- 10. **DECISION TRANSPARENCY**: Make your reasoning process completely clear and auditable
306
-
307
- === ADVANCED CONTEXT HANDLING ===
308
- - **Pronoun Resolution**: "Cancel it" β†’ identify what "it" refers to from history
309
- - **Implicit References**: "Same time tomorrow" β†’ extract time from previous context
310
- - **Entity Persistence**: Remember patient IDs, appointment IDs across conversation turns
311
- - **Intent Continuation**: Understand when user is continuing a previous request
312
- - **Correction Handling**: Detect when user is correcting previous information
313
-
314
- Think methodically through each phase. Demonstrate deep understanding before making decisions. Be thorough in your analysis and transparent in your reasoning.
315
- """,
316
- input_variables=[
317
- "endpoints_documentation", "user_query", "detected_language",
318
- "extracted_keywords", "sentiment_analysis", "conversation_history",
319
- "current_datetime", "timezone", "user_locale"
320
- ]
321
- )
 
 
322
  # self.router_prompt_template = PromptTemplate(
323
  # template="""
324
  # You are a precise API routing assistant. Your job is to analyze user queries and select the correct API endpoint with proper parameters.
 
193
 
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 that MUST strictly adhere to provided endpoint documentation. Your primary responsibility is to accurately understand user queries and match them ONLY with documented endpoints.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ANALYSIS PROTOCOL ===
215
+
216
+ STEP 1: EXHAUSTIVE QUERY DECOMPOSITION
217
+ Break down the user query into atomic components:
218
+ - EXACT WORDS USED: List every significant word/phrase
219
+ - PRIMARY ACTION VERB: What specific action is requested? (create, get, update, delete, list, search, cancel, reschedule, etc.)
220
+ - TARGET ENTITY: What object/resource is being acted upon? (appointment, patient, doctor, schedule, etc.)
221
+ - QUALIFIERS: What conditions, filters, or specifications are mentioned?
222
+ - TIME EXPRESSIONS: Any date/time references (today, tomorrow, specific dates/times)
223
+ - IDENTIFIERS: Any IDs, names, or unique references mentioned
224
+ - IMPLICIT REQUIREMENTS: What unstated needs can be inferred?
225
+
226
+ STEP 2: ENDPOINTS DOCUMENTATION VERIFICATION
227
+ For EVERY endpoint in the documentation, perform this exact analysis:
228
+ - ENDPOINT PATH: Record the exact path as written in documentation
229
+ - HTTP METHOD: Note the exact method (GET, POST, PUT, DELETE, PATCH)
230
+ - PURPOSE STATEMENT: What does this endpoint actually do according to docs?
231
+ - REQUIRED PARAMETERS: List every mandatory parameter with exact names and types
232
+ - OPTIONAL PARAMETERS: List every optional parameter with exact names and types
233
+ - PARAMETER CONSTRAINTS: Any validation rules, formats, or restrictions
234
+ - RESPONSE STRUCTURE: What data does this endpoint return?
235
+ - USAGE SCENARIOS: When should this endpoint be used vs others?
236
+
237
+ STEP 3: STRICT COMPATIBILITY MATCHING
238
+ For each endpoint, calculate exact compatibility:
239
+ - ACTION MATCH: Does the endpoint's action exactly match user's intent? (YES/NO/PARTIAL)
240
+ - ENTITY MATCH: Does the endpoint work with the requested resource type? (YES/NO)
241
+ - PARAMETER AVAILABILITY: Can ALL required parameters be satisfied? (YES/NO + list gaps)
242
+ - CONSTRAINT COMPLIANCE: Do extracted values meet all documented constraints? (YES/NO + violations)
243
+ - DOCUMENTATION PROOF: Quote exact documentation text that supports this match
244
+
245
+ STEP 4: RIGOROUS PARAMETER EXTRACTION
246
+ Extract parameters with extreme precision:
247
+ - DIRECT EXTRACTION: Values explicitly stated in user query
248
+ - CONTEXTUAL EXTRACTION: Values from conversation history (with specific references)
249
+ - TYPE CONVERSION: Convert to exact types specified in documentation
250
+ - DATE/TIME FORMATTING: Convert ALL dates to ISO 8601 format (YYYY-MM-DDTHH:mm:ss)
251
+ * "today" β†’ {current_datetime}T08:00:00 (or specified time)
252
+ * "tomorrow" β†’ add 1 day to current date
253
+ * "next week" β†’ add 7 days to current date
254
+ * Specific times: "3 PM" β†’ 15:00:00, "morning" β†’ 08:00:00
255
+ - VALIDATION: Verify each parameter against documentation constraints
256
+ - MISSING IDENTIFICATION: Clearly identify any required parameters that cannot be extracted
257
+
258
+ STEP 5: DOCUMENTATION COMPLIANCE CHECK
259
+ Before finalizing ANY decision:
260
+ - ENDPOINT EXISTS: Confirm the endpoint path exists exactly as documented
261
+ - METHOD CORRECT: Verify the HTTP method matches documentation
262
+ - PARAMETERS COMPLETE: Ensure all required parameters are available
263
+ - PARAMETER TYPES VALID: Confirm all parameter types match documentation
264
+ - NO ASSUMPTIONS: Never assume functionality not explicitly documented
265
+ - NO FABRICATION: Never create parameter names or values not mentioned in docs
266
+
267
+ STEP 6: CONFIDENCE CALCULATION
268
+ Calculate confidence based on:
269
+ - Intent clarity: How clear is the user's request? (0-30 points)
270
+ - Documentation match: How well does selected endpoint fit? (0-40 points)
271
+ - Parameter completeness: How many required params are available? (0-30 points)
272
+ - Total confidence = (points/100)
273
+
274
+ === CRITICAL ERROR PREVENTION ===
275
+ NEVER do any of the following:
276
+ - Route to endpoints not found in the provided documentation
277
+ - Assume parameter names that aren't documented
278
+ - Guess at endpoint capabilities
279
+ - Ignore required parameters
280
+ - Use incorrect HTTP methods
281
+ - Provide dates in wrong format (must be YYYY-MM-DDTHH:mm:ss)
282
+ - Make assumptions about API behavior not explicitly documented
283
+
284
+ === RESPONSE FORMAT (MAINTAIN EXACTLY) ===
285
+ {{
286
  "reasoning": {{
287
+ "user_intent": "Detailed explanation of user's exact request",
288
+ "selected_endpoint": "Why this specific documented endpoint was chosen with documentation reference",
289
+ "parameter_mapping": "How each parameter was extracted and validated against documentation"
290
  }},
291
  "endpoint": "/exact_endpoint_path_from_documentation",
292
+ "method": "HTTP_METHOD_FROM_DOCUMENTATION",
293
  "params": {{
294
+ "required_param_1": "extracted_value_in_correct_type",
295
+ "required_param_2": "extracted_value_in_correct_type",
296
+ "optional_param": "value_if_available_and_valid"
297
  }},
298
+ "missing_required": ["list_of_required_parameters_that_could_not_be_extracted"],
299
  "confidence": 0.95
300
  }}
301
 
302
+ === DATE/TIME PROCESSING RULES ===
303
+ - ALL date parameters MUST be in format: YYYY-MM-DDTHH:mm:ss
304
+ - Time expressions conversion:
305
+ * "today" β†’ current date + specified time or 08:00:00
306
+ * "tomorrow" β†’ current date + 1 day + specified time or 08:00:00
307
+ * "next Monday" β†’ calculate exact date + specified time or 08:00:00
308
+ * "in 2 hours" β†’ current datetime + 2 hours
309
+ - Always use 24-hour format
310
+ - If no time specified, default to 08:00:00
311
+
312
+ === QUALITY ASSURANCE CHECKLIST ===
313
+ Before providing response, verify:
314
+ βœ“ Endpoint exists exactly as documented
315
+ βœ“ HTTP method matches documentation
316
+ βœ“ All required parameters identified and extracted (or marked missing)
317
+ βœ“ Parameter types match documentation requirements
318
+ βœ“ Date formats are YYYY-MM-DDTHH:mm:ss
319
+ βœ“ No fabricated or assumed functionality
320
+ βœ“ Confidence score reflects actual certainty
321
+ βœ“ Reasoning clearly explains documentation basis for decision
322
+
323
+ Analyze the user query against the endpoints documentation with absolute precision. Only route to documented endpoints with documented parameters. Be thorough in your analysis and completely transparent in your reasoning.
324
+ """,
325
+ input_variables=[
326
+ "endpoints_documentation", "user_query", "detected_language",
327
+ "extracted_keywords", "sentiment_analysis", "conversation_history",
328
+ "current_datetime", "timezone", "user_locale"
329
+ ]
330
+ )
331
  # self.router_prompt_template = PromptTemplate(
332
  # template="""
333
  # You are a precise API routing assistant. Your job is to analyze user queries and select the correct API endpoint with proper parameters.