Kennedy Johnson Cursor commited on
Commit
838be72
·
1 Parent(s): 03622b8

Fix advisor panel to use conversation context for follow-up answers.

Browse files

Skip orchestrator clarification for continuing threads and weight replies after protein questions; hydrate sessions from MongoDB on cold starts; instruct personas to calculate protein targets from chat history.

Co-authored-by: Cursor <cursoragent@cursor.com>

multi_llm_chatbot_backend/app/api/routes/chat.py CHANGED
@@ -10,7 +10,7 @@ from fastapi.responses import StreamingResponse
10
  from pydantic import BaseModel, Field
11
 
12
  from app.api.routes.chat_sessions import persist_message
13
- from app.api.utils import get_or_create_session_for_request_async
14
  from app.core.auth import get_current_active_user
15
  from app.core.bootstrap import chat_orchestrator
16
  from app.core.database import get_database
@@ -107,6 +107,14 @@ async def chat_stream(
107
  chat_session_id=message.chat_session_id,
108
  user_id=str(current_user.id),
109
  )
 
 
 
 
 
 
 
 
110
  else:
111
  sid = await get_or_create_session_for_request_async(request)
112
 
 
10
  from pydantic import BaseModel, Field
11
 
12
  from app.api.routes.chat_sessions import persist_message
13
+ from app.api.utils import get_or_create_session_for_request_async, load_chat_session_into_context
14
  from app.core.auth import get_current_active_user
15
  from app.core.bootstrap import chat_orchestrator
16
  from app.core.database import get_database
 
107
  chat_session_id=message.chat_session_id,
108
  user_id=str(current_user.id),
109
  )
110
+ elif len(session_manager.get_session(sid).messages) == 0:
111
+ # Cold start / new worker: hydrate from MongoDB before routing
112
+ loaded = await load_chat_session_into_context(
113
+ message.chat_session_id,
114
+ str(current_user.id),
115
+ )
116
+ if loaded:
117
+ sid = loaded
118
  else:
119
  sid = await get_or_create_session_for_request_async(request)
120
 
multi_llm_chatbot_backend/app/api/utils.py CHANGED
@@ -72,9 +72,16 @@ async def load_chat_session_into_context(chat_session_id: str, user_id: str) ->
72
  messages = chat_session.get('messages', [])
73
  for msg_data in messages:
74
  try:
 
 
 
 
 
 
 
75
  message = {
76
  'id': msg_data.get('id', 'unknown'),
77
- 'role': 'user' if msg_data.get('type') == 'user' else 'assistant',
78
  'content': msg_data.get('content', ''),
79
  'timestamp': msg_data.get('timestamp', '')
80
  }
@@ -110,10 +117,13 @@ async def get_or_create_session_for_request_async(
110
 
111
  # Case 1: Loading an existing chat session
112
  if chat_session_id and user_id:
113
- memory_session_id = await load_chat_session_into_context(chat_session_id, user_id)
114
- if memory_session_id:
115
- return memory_session_id
116
- # If loading failed, create new session
 
 
 
117
 
118
  # Case 2: Explicit session ID provided
119
  if session_id_override:
 
72
  messages = chat_session.get('messages', [])
73
  for msg_data in messages:
74
  try:
75
+ msg_type = msg_data.get('type', '')
76
+ if msg_type == 'user':
77
+ role = 'user'
78
+ elif msg_type == 'advisor':
79
+ role = msg_data.get('persona_id') or 'assistant'
80
+ else:
81
+ role = 'assistant'
82
  message = {
83
  'id': msg_data.get('id', 'unknown'),
84
+ 'role': role,
85
  'content': msg_data.get('content', ''),
86
  'timestamp': msg_data.get('timestamp', '')
87
  }
 
117
 
118
  # Case 1: Loading an existing chat session
119
  if chat_session_id and user_id:
120
+ memory_session_id = f"chat_{chat_session_id}"
121
+ loaded = await load_chat_session_into_context(chat_session_id, user_id)
122
+ if loaded:
123
+ return loaded
124
+ # Keep a stable session id even when MongoDB load fails (e.g. race on first message)
125
+ session_manager.get_session(memory_session_id)
126
+ return memory_session_id
127
 
128
  # Case 2: Explicit session ID provided
129
  if session_id_override:
multi_llm_chatbot_backend/app/core/improved_orchestrator.py CHANGED
@@ -14,6 +14,25 @@ import re
14
 
15
  logger = logging.getLogger(__name__)
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  class ImprovedChatOrchestrator:
18
  """
19
  Enhanced orchestrator with document awareness and improved context handling
@@ -182,7 +201,57 @@ class ImprovedChatOrchestrator:
182
  references.extend(matches)
183
 
184
  return references[:3] # Limit to first 3 references
185
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  def needs_clarification(self, session: ConversationContext, user_input: str) -> bool:
187
  """
188
  Determine if the user input needs clarification.
@@ -191,10 +260,14 @@ class ImprovedChatOrchestrator:
191
  # TODO: This method should be refactored to be more generic instead of
192
  # relying on hard-coded regex and keywords.
193
 
194
- # If this is not the first message, probably don't need clarification
195
- user_messages = [msg for msg in session.messages if msg.get('role') == 'user']
196
- if len(user_messages) > 1:
197
- logger.info(f"Skipping clarification: session already has {len(user_messages)} user message(s)")
 
 
 
 
198
  return False
199
 
200
  # Check for vague patterns - FIXED to handle "I am" vs "I'm"
@@ -243,9 +316,14 @@ class ImprovedChatOrchestrator:
243
  to route to the advisor panel. Falls back to the legacy rule-based
244
  method if the LLM call fails.
245
  """
246
- user_messages = [msg for msg in session.messages if msg.get('role') == 'user']
247
- if len(user_messages) > 1:
248
- logger.info("Skipping clarification: session already has %d user message(s)", len(user_messages))
 
 
 
 
 
249
  return False
250
 
251
  app_cfg = get_settings().app
@@ -254,31 +332,47 @@ class ImprovedChatOrchestrator:
254
  f"{p.name} ({p.id})" for p in self.personas.values()
255
  )
256
  domain_keywords = ", ".join(orch_cfg.specific_keywords)
 
 
 
257
 
258
  system_prompt = (
259
  "You are a routing classifier for an AI advisory application.\n\n"
260
  f"Application: {app_cfg.title} — {app_cfg.subtitle}\n"
261
  f"Available advisors: {advisor_descriptions}\n"
262
  f"Domain-relevant topics: {domain_keywords}\n\n"
263
- "Your task: decide whether the user's FIRST message contains enough "
264
  "substance to send to the advisors, or whether it is too vague and "
265
  "requires a clarifying follow-up before the advisors can help.\n\n"
 
 
 
 
 
266
  "A message NEEDS CLARIFICATION when it:\n"
267
  "- Expresses confusion or uncertainty without a concrete topic\n"
268
  "- Is a single generic request like 'help' or 'advice'\n"
269
- "- Contains no identifiable subject the advisors could address\n\n"
 
270
  "A message is CLEAR ENOUGH when it:\n"
271
  "- Mentions a specific topic, question, or problem area\n"
272
  "- Provides enough context for at least one advisor to respond usefully\n"
273
  "- Even a short message is fine if the intent is unambiguous "
274
  "(e.g. 'explain transformers' is clear)\n"
275
  "- Messages mentioning domain-relevant topics are likely clear enough "
276
- "to route directly, even if brief\n\n"
 
277
  "Respond ONLY with valid JSON:\n"
278
  '{"needs_clarification": true or false, "reason": "one sentence explanation"}'
279
  )
280
 
281
- user_prompt = f'User message: "{user_input}"'
 
 
 
 
 
 
282
 
283
  raw = None
284
 
 
14
 
15
  logger = logging.getLogger(__name__)
16
 
17
+ # Short replies that supply data (weight, height, age) in response to a prior question.
18
+ _FOLLOW_UP_DATA_PATTERNS = [
19
+ r"^\s*i['']?m\s+\d",
20
+ r"^\s*i am\s+\d",
21
+ r"\d+\s*(?:lbs?|pounds?|kg|kilos?|kgs)\b",
22
+ r"^\s*\d{2,3}\s*(?:lbs?|pounds?|kg|kilos?|kgs)?\s*$",
23
+ r"^\s*\d+\s*(?:years?\s*old|yo)\b",
24
+ r"^\s*(?:about|around|roughly)\s+\d",
25
+ ]
26
+
27
+ # Prior-turn topics that make a short data reply actionable (e.g. protein + weight).
28
+ _FOLLOW_UP_TOPIC_KEYWORDS = [
29
+ "protein", "macro", "calorie", "weight", "body weight", "bulk", "cut",
30
+ "recomp", "hypertrophy", "muscle", "nutrition", "meal", "diet",
31
+ "how much", "how many", "grams", "g/day", "schedule", "days per week",
32
+ "equipment", "experience", "goal",
33
+ ]
34
+
35
+
36
  class ImprovedChatOrchestrator:
37
  """
38
  Enhanced orchestrator with document awareness and improved context handling
 
201
  references.extend(matches)
202
 
203
  return references[:3] # Limit to first 3 references
204
+
205
+ def _get_user_messages(self, session: ConversationContext) -> List[Dict[str, str]]:
206
+ return [msg for msg in session.messages if msg.get("role") == "user"]
207
+
208
+ def _has_continuing_conversation(self, session: ConversationContext) -> bool:
209
+ """True when the user is past the first turn or advisors have already replied."""
210
+ user_messages = self._get_user_messages(session)
211
+ if len(user_messages) > 1:
212
+ return True
213
+ advisor_roles = set(self.personas.keys()) | {"assistant", "orchestrator"}
214
+ return any(msg.get("role") in advisor_roles for msg in session.messages)
215
+
216
+ def _prior_conversation_text(
217
+ self, session: ConversationContext, exclude_latest_user: bool = False
218
+ ) -> str:
219
+ """Concatenate prior messages for clarification and routing context."""
220
+ messages = session.messages
221
+ if exclude_latest_user and messages and messages[-1].get("role") == "user":
222
+ messages = messages[:-1]
223
+ return "\n".join(
224
+ f"{msg.get('role', 'unknown')}: {msg.get('content', '')}"
225
+ for msg in messages
226
+ if msg.get("role") != "system"
227
+ )
228
+
229
+ def _is_follow_up_data_reply(
230
+ self, session: ConversationContext, user_input: str
231
+ ) -> bool:
232
+ """
233
+ Detect short replies that answer a prior question (e.g. weight after
234
+ a protein question) even when session history failed to hydrate.
235
+ """
236
+ user_lower = user_input.lower().strip()
237
+ if len(user_input.split()) > 10:
238
+ return False
239
+
240
+ looks_like_data = any(
241
+ re.search(pattern, user_lower, re.IGNORECASE)
242
+ for pattern in _FOLLOW_UP_DATA_PATTERNS
243
+ )
244
+ if not looks_like_data:
245
+ return False
246
+
247
+ prior_text = self._prior_conversation_text(
248
+ session, exclude_latest_user=True
249
+ ).lower()
250
+ if not prior_text:
251
+ return False
252
+
253
+ return any(keyword in prior_text for keyword in _FOLLOW_UP_TOPIC_KEYWORDS)
254
+
255
  def needs_clarification(self, session: ConversationContext, user_input: str) -> bool:
256
  """
257
  Determine if the user input needs clarification.
 
260
  # TODO: This method should be refactored to be more generic instead of
261
  # relying on hard-coded regex and keywords.
262
 
263
+ if self._has_continuing_conversation(session):
264
+ logger.info("Skipping clarification: continuing conversation")
265
+ return False
266
+
267
+ if self._is_follow_up_data_reply(session, user_input):
268
+ logger.info(
269
+ "NO CLARIFICATION: follow-up data reply with prior topic context"
270
+ )
271
  return False
272
 
273
  # Check for vague patterns - FIXED to handle "I am" vs "I'm"
 
316
  to route to the advisor panel. Falls back to the legacy rule-based
317
  method if the LLM call fails.
318
  """
319
+ if self._has_continuing_conversation(session):
320
+ logger.info("Skipping clarification: continuing conversation")
321
+ return False
322
+
323
+ if self._is_follow_up_data_reply(session, user_input):
324
+ logger.info(
325
+ "Skipping clarification: follow-up data reply with prior topic context"
326
+ )
327
  return False
328
 
329
  app_cfg = get_settings().app
 
332
  f"{p.name} ({p.id})" for p in self.personas.values()
333
  )
334
  domain_keywords = ", ".join(orch_cfg.specific_keywords)
335
+ conversation_context = self._prior_conversation_text(
336
+ session, exclude_latest_user=True
337
+ )
338
 
339
  system_prompt = (
340
  "You are a routing classifier for an AI advisory application.\n\n"
341
  f"Application: {app_cfg.title} — {app_cfg.subtitle}\n"
342
  f"Available advisors: {advisor_descriptions}\n"
343
  f"Domain-relevant topics: {domain_keywords}\n\n"
344
+ "Your task: decide whether the user's latest message contains enough "
345
  "substance to send to the advisors, or whether it is too vague and "
346
  "requires a clarifying follow-up before the advisors can help.\n\n"
347
+ "Use the full conversation history when provided. Short follow-up "
348
+ "replies that supply requested data (body weight, schedule, equipment, "
349
+ "experience level) are CLEAR ENOUGH when prior messages asked for that "
350
+ "information or discussed a related topic (e.g. protein question then "
351
+ "'230 lbs').\n\n"
352
  "A message NEEDS CLARIFICATION when it:\n"
353
  "- Expresses confusion or uncertainty without a concrete topic\n"
354
  "- Is a single generic request like 'help' or 'advice'\n"
355
+ "- Contains no identifiable subject the advisors could address\n"
356
+ "- Is a standalone data point with NO prior conversation context\n\n"
357
  "A message is CLEAR ENOUGH when it:\n"
358
  "- Mentions a specific topic, question, or problem area\n"
359
  "- Provides enough context for at least one advisor to respond usefully\n"
360
  "- Even a short message is fine if the intent is unambiguous "
361
  "(e.g. 'explain transformers' is clear)\n"
362
  "- Messages mentioning domain-relevant topics are likely clear enough "
363
+ "to route directly, even if brief\n"
364
+ "- Is a follow-up answer that completes information from earlier turns\n\n"
365
  "Respond ONLY with valid JSON:\n"
366
  '{"needs_clarification": true or false, "reason": "one sentence explanation"}'
367
  )
368
 
369
+ if conversation_context.strip():
370
+ user_prompt = (
371
+ f"Conversation so far:\n{conversation_context}\n\n"
372
+ f'Latest user message: "{user_input}"'
373
+ )
374
+ else:
375
+ user_prompt = f'User message: "{user_input}"'
376
 
377
  raw = None
378
 
multi_llm_chatbot_backend/app/tests/unit/test_clarification.py CHANGED
@@ -6,13 +6,19 @@ from unittest.mock import AsyncMock, MagicMock, patch
6
  from app.core.improved_orchestrator import ImprovedChatOrchestrator
7
 
8
 
9
- def _make_session(user_message_count=1):
10
  """Build a mock ConversationContext with N user messages."""
11
  session = MagicMock()
12
- session.messages = [
13
  {"role": "user", "content": f"message {i}"}
14
  for i in range(user_message_count)
15
  ]
 
 
 
 
 
 
16
  return session
17
 
18
 
@@ -334,3 +340,54 @@ class TestNeedsClarificationImproved(unittest.TestCase):
334
  self.assertEqual(len(context), 1)
335
  self.assertEqual(context[0]["role"], "user")
336
  self.assertIn("How do I structure my lit review?", context[0]["content"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  from app.core.improved_orchestrator import ImprovedChatOrchestrator
7
 
8
 
9
+ def _make_session(user_message_count=1, prior_advisor=False):
10
  """Build a mock ConversationContext with N user messages."""
11
  session = MagicMock()
12
+ messages = [
13
  {"role": "user", "content": f"message {i}"}
14
  for i in range(user_message_count)
15
  ]
16
+ if prior_advisor:
17
+ messages = [
18
+ {"role": "user", "content": "how much protein should I consume?"},
19
+ {"role": "nutrition_strategist", "content": "Aim for 1.6-2.2 g/kg. What is your body weight?"},
20
+ ]
21
+ session.messages = messages
22
  return session
23
 
24
 
 
340
  self.assertEqual(len(context), 1)
341
  self.assertEqual(context[0]["role"], "user")
342
  self.assertIn("How do I structure my lit review?", context[0]["content"])
343
+
344
+
345
+ @patch("app.core.improved_orchestrator.get_settings")
346
+ class TestFollowUpClarificationSkip(unittest.TestCase):
347
+
348
+ def _run(self, coro):
349
+ return asyncio.run(coro)
350
+
351
+ def test_skips_clarification_for_weight_follow_up_after_protein_question(self, mock_settings):
352
+ mock_settings.return_value = _make_mock_settings()
353
+ llm = MagicMock()
354
+ llm.generate = AsyncMock()
355
+ orch = _make_orchestrator(persona_llm=llm)
356
+ session = _make_session(prior_advisor=True)
357
+ session.messages.append({"role": "user", "content": "im 230 lbs"})
358
+
359
+ result = self._run(
360
+ orch.needs_clarification_improved(session, "im 230 lbs")
361
+ )
362
+
363
+ self.assertFalse(result)
364
+ llm.generate.assert_not_called()
365
+
366
+ def test_rule_based_skips_weight_follow_up_with_prior_topic(self, mock_settings):
367
+ mock_settings.return_value = _make_mock_settings()
368
+ orch = _make_orchestrator()
369
+ session = _make_session(prior_advisor=True)
370
+ session.messages.append({"role": "user", "content": "230 lbs"})
371
+
372
+ result = orch.needs_clarification(session, "230 lbs")
373
+
374
+ self.assertFalse(result)
375
+
376
+ def test_skips_when_advisors_already_replied(self, mock_settings):
377
+ mock_settings.return_value = _make_mock_settings()
378
+ llm = MagicMock()
379
+ llm.generate = AsyncMock()
380
+ orch = _make_orchestrator(persona_llm=llm)
381
+ session = MagicMock()
382
+ session.messages = [
383
+ {"role": "user", "content": "how much protein?"},
384
+ {"role": "nutrition_strategist", "content": "Tell me your weight"},
385
+ {"role": "user", "content": "230 lbs"},
386
+ ]
387
+
388
+ result = self._run(
389
+ orch.needs_clarification_improved(session, "230 lbs")
390
+ )
391
+
392
+ self.assertFalse(result)
393
+ llm.generate.assert_not_called()
muscle_growth_config.yaml CHANGED
@@ -118,6 +118,13 @@ personas:
118
  - Insert one blank line between sections.
119
  - Keep each section unique and non-repetitive.
120
  - Prioritize safety: recommend consulting a physician for pain, injury, or medical conditions.
 
 
 
 
 
 
 
121
  personas_dir: "personas/fitness_advisors"
122
 
123
  orchestrator:
@@ -150,6 +157,12 @@ orchestrator:
150
  - "physique"
151
  - "progress"
152
  - "deload"
 
 
 
 
 
 
153
  clarification_questions:
154
  - "What is your primary goal — muscle gain, strength, recomposition, or general fitness?"
155
  - "Which muscle group or training split are you asking about?"
 
118
  - Insert one blank line between sections.
119
  - Keep each section unique and non-repetitive.
120
  - Prioritize safety: recommend consulting a physician for pain, injury, or medical conditions.
121
+
122
+ **Conversation memory:**
123
+ - Read the full chat history before responding.
124
+ - Never re-ask for information the user already provided in earlier messages.
125
+ - When the user supplies follow-up data (body weight, schedule, equipment, experience), apply it immediately to the question they asked earlier in the thread.
126
+ - Perform unit conversions and arithmetic when you have enough inputs (e.g. lbs→kg, protein g/day at 1.6–2.2 g/kg).
127
+ - Default training and nutrition goal to muscle gain / hypertrophy unless the user specifies otherwise.
128
  personas_dir: "personas/fitness_advisors"
129
 
130
  orchestrator:
 
157
  - "physique"
158
  - "progress"
159
  - "deload"
160
+ - "lbs"
161
+ - "lb"
162
+ - "pounds"
163
+ - "kg"
164
+ - "kilos"
165
+ - "weight"
166
  clarification_questions:
167
  - "What is your primary goal — muscle gain, strength, recomposition, or general fitness?"
168
  - "Which muscle group or training split are you asking about?"
personas/fitness_advisors/hypertrophy_coach.yaml CHANGED
@@ -16,4 +16,9 @@ persona_prompt: |
16
  **YOUR RESPONSE STYLE:**
17
  - Be specific with exercises, sets, reps, and weekly structure
18
  - Explain why each recommendation supports hypertrophy
19
- - Ask about schedule, equipment, and experience when details are missing
 
 
 
 
 
 
16
  **YOUR RESPONSE STYLE:**
17
  - Be specific with exercises, sets, reps, and weekly structure
18
  - Explain why each recommendation supports hypertrophy
19
+ - Ask about schedule, equipment, and experience only when still missing from the conversation
20
+
21
+ **CONVERSATION CONTEXT:**
22
+ - Use the full chat history; combine follow-up answers with the original question
23
+ - When nutrition topics arise and the user gives body weight, support protein targets using 1.6–2.2 g/kg (show math when helpful)
24
+ - Default goal to muscle gain / hypertrophy when not specified
personas/fitness_advisors/nutrition_strategist.yaml CHANGED
@@ -17,3 +17,12 @@ persona_prompt: |
17
  - Give concrete gram ranges and simple meal examples when possible
18
  - Tie nutrition advice to the user's training goals and schedule
19
  - Note when medical or dietary conditions require professional guidance
 
 
 
 
 
 
 
 
 
 
17
  - Give concrete gram ranges and simple meal examples when possible
18
  - Tie nutrition advice to the user's training goals and schedule
19
  - Note when medical or dietary conditions require professional guidance
20
+
21
+ **CONVERSATION CONTEXT & CALCULATIONS:**
22
+ - Use the full chat history; do not ask again for details already given
23
+ - If the user asked about protein and then provides body weight (e.g. "230 lbs", "I'm 180"), calculate immediately:
24
+ - Convert lbs to kg: divide by 2.205 (230 lbs ≈ 104.3 kg)
25
+ - Hypertrophy protein target: 1.6–2.2 g/kg/day
26
+ - Show the math briefly and give a rounded daily gram target (e.g. 167–230 g/day)
27
+ - Default goal to muscle gain / hypertrophy when not specified
28
+ - Only ask for missing inputs that are still unknown after reading the thread
personas/fitness_advisors/program_planner.yaml CHANGED
@@ -17,3 +17,9 @@ persona_prompt: |
17
  - Turn goals into a clear weekly plan with measurable checkpoints
18
  - Be encouraging but realistic about time commitments
19
  - Suggest simple tracking templates the user can reuse each week
 
 
 
 
 
 
 
17
  - Turn goals into a clear weekly plan with measurable checkpoints
18
  - Be encouraging but realistic about time commitments
19
  - Suggest simple tracking templates the user can reuse each week
20
+
21
+ **CONVERSATION CONTEXT:**
22
+ - Read the full chat history before responding
23
+ - Apply follow-up details (body weight, days per week, equipment) to the user's earlier question
24
+ - Do not re-ask for information already provided in the thread
25
+ - Default goal to muscle gain / hypertrophy when not specified