Girish Jeswani commited on
Commit
7ed6712
·
1 Parent(s): e97bd0e

update chat endpoint with persona ordering

Browse files
multi_llm_chatbot_backend/app/api/routes.py CHANGED
@@ -186,65 +186,88 @@ async def switch_provider(provider_data: ProviderSwitch):
186
  detail=f"Failed to switch to {provider_data.provider}: {str(e)}"
187
  )
188
 
189
- # Main chat endpoint (SAME INTERFACE, improved backend)
190
  @router.post("/chat-sequential")
191
  async def chat_sequential_enhanced(message: ChatMessage, request: Request):
192
  """
193
- Enhanced sequential chat with improved document awareness and response quality
 
194
  """
195
  try:
196
  # Get or create session
197
  session_id = get_or_create_session_for_request(request, message.session_id)
198
 
199
- # Process message with enhanced orchestrator
200
- orchestrator_result = await chat_orchestrator.process_message_with_enhanced_context(
201
- user_input=message.user_input,
202
- session_id=session_id,
203
- response_length=message.response_length or "medium"
 
 
 
204
  )
205
-
206
- if orchestrator_result["status"] == "success":
207
- responses = orchestrator_result["responses"]
208
-
209
- # Enhanced RAG information for debugging and user feedback
210
- rag_info = {
211
- "total_personas": len(responses),
212
- "personas_using_documents": sum(1 for r in responses if r.get("used_documents", False)),
213
- "total_document_chunks_used": sum(r.get("document_chunks_used", 0) for r in responses),
214
- "document_aware_query": orchestrator_result.get("document_references_detected", False),
215
- "available_documents": orchestrator_result.get("available_documents", [])
216
- }
217
-
218
- return {
219
- "type": "persona_responses",
220
- "responses": responses,
221
- "rag_info": rag_info,
222
- "session_id": session_id,
223
- "query_analysis": {
224
- "document_references_found": orchestrator_result.get("document_references_detected", False),
225
- "personas_with_high_quality_context": [
226
- r["persona_id"] for r in responses
227
- if r.get("context_quality") == "high"
228
- ]
229
- }
230
- }
231
- else:
232
- # Fallback response with helpful guidance
233
- return {
234
- "type": "clarification_needed",
235
- "message": orchestrator_result.get("message", "I need more information to help you effectively."),
236
- "suggestions": orchestrator_result.get("suggestions", [
237
- "Could you provide more details about your specific question?",
238
- "Consider uploading relevant documents to get more targeted advice.",
239
- "Try asking about a specific aspect of your research."
240
- ]),
241
- "session_id": session_id,
242
- "rag_info": {"total_personas": 0, "personas_using_documents": 0}
243
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
244
 
245
  except Exception as e:
246
  logger.error(f"Error in enhanced sequential chat: {str(e)}")
247
- raise HTTPException(status_code=500, detail=f"Error processing request: {str(e)}")
 
 
 
 
 
 
248
 
249
  @router.post("/chat/{persona_id}")
250
  async def chat_with_specific_advisor(persona_id: str, input: UserInput, request: Request):
 
186
  detail=f"Failed to switch to {provider_data.provider}: {str(e)}"
187
  )
188
 
189
+ # Main chat endpoint
190
  @router.post("/chat-sequential")
191
  async def chat_sequential_enhanced(message: ChatMessage, request: Request):
192
  """
193
+ Enhanced sequential chat with intelligent persona ordering.
194
+ Returns responses in the order determined by LLM-based relevance ranking.
195
  """
196
  try:
197
  # Get or create session
198
  session_id = get_or_create_session_for_request(request, message.session_id)
199
 
200
+ # Add user message to session first (needed for persona ranking)
201
+ session = session_manager.get_session(session_id)
202
+ session.append_message("user", message.user_input)
203
+
204
+ # Get intelligently ordered personas based on context
205
+ top_personas = await chat_orchestrator.get_top_personas(
206
+ session_id=session_id,
207
+ k=3 # Get top 3 most relevant personas
208
  )
209
+
210
+ logger.info(f"Intelligent persona order for session {session_id}: {top_personas}")
211
+
212
+ # Generate responses from personas in the intelligent order
213
+ responses = []
214
+
215
+ for persona_id in top_personas:
216
+ try:
217
+ # Generate response from this persona
218
+ persona_result = await chat_orchestrator.chat_with_persona(
219
+ user_input=message.user_input,
220
+ persona_id=persona_id,
221
+ session_id=session_id,
222
+ response_length=message.response_length or "medium"
223
+ )
224
+
225
+
226
+ if "persona_name" in persona_result and "response" in persona_result:
227
+ responses.append({
228
+ "persona": persona_result["persona_name"],
229
+ "persona_id": persona_result["persona_id"],
230
+ "response": persona_result["response"]
231
+ })
232
+ elif persona_result.get("type") == "single_persona_response" and "persona" in persona_result:
233
+ persona_data = persona_result["persona"]
234
+ responses.append({
235
+ "persona": persona_data["persona_name"],
236
+ "persona_id": persona_data["persona_id"],
237
+ "response": persona_data["response"]
238
+ })
239
+ else:
240
+ # Fallback response
241
+ responses.append({
242
+ "persona": chat_orchestrator.personas[persona_id].name,
243
+ "persona_id": persona_id,
244
+ "response": "I'm having trouble processing your question right now. Please try again."
245
+ })
246
+
247
+ except Exception as e:
248
+ logger.error(f"Error generating response for persona {persona_id}: {str(e)}")
249
+ # Error fallback
250
+ responses.append({
251
+ "persona": chat_orchestrator.personas[persona_id].name,
252
+ "persona_id": persona_id,
253
+ "response": "I encountered an error while processing your question. Please try again."
254
+ })
255
+
256
+ # response format
257
+ return {
258
+ "type": "sequential_responses",
259
+ "responses": responses
260
+ }
261
 
262
  except Exception as e:
263
  logger.error(f"Error in enhanced sequential chat: {str(e)}")
264
+ return {
265
+ "type": "error",
266
+ "responses": [{
267
+ "persona": "System",
268
+ "response": "I'm having trouble processing your request. Could you please try again?"
269
+ }]
270
+ }
271
 
272
  @router.post("/chat/{persona_id}")
273
  async def chat_with_specific_advisor(persona_id: str, input: UserInput, request: Request):