chenemii commited on
Commit
e034895
·
1 Parent(s): 4773d5a

fix RAG system issues

Browse files

Signed-off-by: Emily Chen <emilyaychen@gmail.com>

Files changed (2) hide show
  1. app/models/llm_analyzer.py +2 -9
  2. app/streamlit_app.py +31 -32
app/models/llm_analyzer.py CHANGED
@@ -660,15 +660,8 @@ def parse_and_format_analysis(raw_analysis):
660
  cleaned_strengths = []
661
  for topic, desc in strength_items:
662
  topic_clean = topic.strip()
663
- # Take first full sentence from desc
664
- desc_text = desc.strip().replace('\n', ' ')
665
- # Ensure we end at the first period or em dash break
666
- sentence_match = re.match(r'(.+?\.)', desc_text)
667
- if sentence_match:
668
- desc_clean = sentence_match.group(1).strip()
669
- else:
670
- # Fallback: up to 180 chars
671
- desc_clean = desc_text[:180].strip()
672
  if topic_clean and desc_clean:
673
  cleaned_strengths.append(f"{topic_clean}: {desc_clean}")
674
  # Ensure exactly three strengths
 
660
  cleaned_strengths = []
661
  for topic, desc in strength_items:
662
  topic_clean = topic.strip()
663
+ # Clean and preserve the full description
664
+ desc_clean = desc.strip().replace('\n', ' ')
 
 
 
 
 
 
 
665
  if topic_clean and desc_clean:
666
  cleaned_strengths.append(f"{topic_clean}: {desc_clean}")
667
  # Ensure exactly three strengths
app/streamlit_app.py CHANGED
@@ -373,21 +373,12 @@ def generate_enhanced_response(rag_system, query, context_chunks, user_swing_con
373
 
374
  You are a golf swing technique expert assistant analyzing this specific player's swing.
375
 
376
- IMPORTANT: Only reference the player's swing analysis data above if the question is directly related to swing motion biomechanics (like hip rotation, shoulder turn, weight transfer, timing, etc.).
377
-
378
- Do NOT reference swing analysis for questions about:
379
- - Grip (how to hold the club)
380
- - Setup/stance (static positioning before the swing)
381
- - Equipment (clubs, balls, etc.)
382
- - Course management
383
- - Mental game
384
- - Basic fundamentals that aren't measured during swing motion
385
-
386
- Follow this response structure:
387
-
388
- 1. Synthesize information from the reference materials below to answer the user's question. Keep this to 2-4 sentences maximum. Start with "Based on [source name]," and provide clear, actionable advice about the technique.
389
-
390
- 2. If the question relates to swing motion biomechanics AND you found relevant measurements in the analysis above, provide specific improvement advice comparing current state to recommendations. Otherwise, provide general advice without forcing connections to unrelated swing metrics.
391
 
392
  Reference Materials from Golf Instruction Database:
393
  {knowledge_context}"""
@@ -396,10 +387,7 @@ Reference Materials from Golf Instruction Database:
396
 
397
  {query}
398
 
399
- Remember to:
400
- 1. Only reference my swing analysis if the question is about swing motion biomechanics
401
- 2. Synthesize expert advice concisely (2-4 sentences max)
402
- 3. Don't force connections between unrelated topics (e.g., don't mention wrist hinge when asking about grip)"""
403
 
404
  else:
405
  # Fallback to general system prompt if no swing analysis available
@@ -411,7 +399,7 @@ Instructions:
411
  - Reference relevant technical concepts when appropriate
412
  - Be encouraging and supportive
413
  - Synthesize information from multiple sources rather than just quoting them
414
- - Give clear, comprehensive explanations that golfers can understand and apply
415
 
416
  Reference Materials from Golf Instruction Database:
417
  {knowledge_context}"""
@@ -420,7 +408,7 @@ Reference Materials from Golf Instruction Database:
420
 
421
  {query}
422
 
423
- Please provide a helpful, detailed response that synthesizes the relevant information into clear, actionable guidance."""
424
 
425
  print(f"System prompt: {system_prompt}")
426
  print(f"User prompt: {user_prompt}")
@@ -431,7 +419,7 @@ Please provide a helpful, detailed response that synthesizes the relevant inform
431
  {"role": "system", "content": system_prompt},
432
  {"role": "user", "content": user_prompt}
433
  ],
434
- max_tokens=800,
435
  temperature=0.7
436
  )
437
  return response.choices[0].message.content
@@ -485,6 +473,21 @@ def generate_enhanced_fallback_response(query, context_chunks, user_swing_contex
485
  found_relevant_measurement = True
486
  break
487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
488
  elif "hip" in question_lower and ("rotation" in question_lower or "turn" in question_lower):
489
  # Look for hip rotation measurements (only if asking about hip rotation/turn)
490
  lines = analysis_content.split('\n')
@@ -521,9 +524,9 @@ def generate_enhanced_fallback_response(query, context_chunks, user_swing_contex
521
  found_relevant_measurement = True
522
  break
523
 
524
- # Part 2: Expert recommendation (synthesized from source)
525
  sentences = chunk_content.split('. ')
526
- meaningful_sentences = [s.strip() for s in sentences if len(s.strip()) > 20][:3]
527
  expert_advice = '. '.join(meaningful_sentences[:2]) + '.'
528
 
529
  response_parts.append(f"Based on {source_title}, {expert_advice}")
@@ -531,17 +534,13 @@ def generate_enhanced_fallback_response(query, context_chunks, user_swing_contex
531
  # Part 3: Improvement recommendation (only connect to swing analysis if relevant)
532
  if user_swing_context and found_relevant_measurement and not is_non_biomechanics:
533
  # Only provide swing-analysis-specific advice if we found relevant measurements
534
- analysis_content = user_swing_context.replace("USER'S SWING ANALYSIS:\n", "").strip()
535
- response_parts.append("Based on your current measurements compared to professional standards, focus on implementing the expert advice above to address your specific swing characteristics.")
536
  else:
537
  # For non-biomechanics questions or when no relevant measurements found
538
- response_parts.append("Focus on implementing this expert advice to improve your technique.")
539
-
540
- # Combine all parts
541
- final_response = "\n\n".join(response_parts)
542
 
543
- # Add source reference
544
- final_response += f"\n\n📚 **Source**: {source_title}"
545
 
546
  return final_response
547
 
 
373
 
374
  You are a golf swing technique expert assistant analyzing this specific player's swing.
375
 
376
+ INSTRUCTIONS:
377
+ 1. Always answer golf technique questions using the reference materials below
378
+ 2. For swing motion biomechanics questions (head movement, hip rotation, weight transfer, etc.), also reference specific measurements from the player's swing analysis above when relevant
379
+ 3. For setup/stance questions, answer from the reference materials without needing to reference swing motion data
380
+ 4. Provide clear, actionable advice based on proven golf instruction
381
+ 5. IMPORTANT: Keep responses to 4 sentences or less - be concise and focused
 
 
 
 
 
 
 
 
 
382
 
383
  Reference Materials from Golf Instruction Database:
384
  {knowledge_context}"""
 
387
 
388
  {query}
389
 
390
+ Please provide a helpful, concise response (4 sentences or less) that addresses the specific question while drawing from the relevant information in the context. If the question relates to swing motion biomechanics and you have specific measurements from my swing analysis above, include those details for personalized advice."""
 
 
 
391
 
392
  else:
393
  # Fallback to general system prompt if no swing analysis available
 
399
  - Reference relevant technical concepts when appropriate
400
  - Be encouraging and supportive
401
  - Synthesize information from multiple sources rather than just quoting them
402
+ - IMPORTANT: Keep responses to 4 sentences or less - be concise and focused
403
 
404
  Reference Materials from Golf Instruction Database:
405
  {knowledge_context}"""
 
408
 
409
  {query}
410
 
411
+ Please provide a helpful, concise response (4 sentences or less) that synthesizes the relevant information into clear, actionable guidance."""
412
 
413
  print(f"System prompt: {system_prompt}")
414
  print(f"User prompt: {user_prompt}")
 
419
  {"role": "system", "content": system_prompt},
420
  {"role": "user", "content": user_prompt}
421
  ],
422
+ max_tokens=400,
423
  temperature=0.7
424
  )
425
  return response.choices[0].message.content
 
473
  found_relevant_measurement = True
474
  break
475
 
476
+ elif "head" in question_lower and ("movement" in question_lower or "moving" in question_lower or "steady" in question_lower):
477
+ # Look for head movement measurements (only if asking about head movement)
478
+ lines = analysis_content.split('\n')
479
+ for line in lines:
480
+ if 'head movement' in line.lower() and ('in' in line or 'inches' in line):
481
+ import re
482
+ lateral_match = re.search(r'head movement \(lateral\)[:\s]*(\d+\.?\d*)\s*in', line.lower())
483
+ vertical_match = re.search(r'head movement \(vertical\)[:\s]*(\d+\.?\d*)\s*in', line.lower())
484
+ if lateral_match or vertical_match:
485
+ lateral_val = lateral_match.group(1) if lateral_match else "N/A"
486
+ vertical_val = vertical_match.group(1) if vertical_match else "N/A"
487
+ response_parts.append(f"I notice that your head movement is {lateral_val} inches laterally and {vertical_val} inches vertically during your swing.")
488
+ found_relevant_measurement = True
489
+ break
490
+
491
  elif "hip" in question_lower and ("rotation" in question_lower or "turn" in question_lower):
492
  # Look for hip rotation measurements (only if asking about hip rotation/turn)
493
  lines = analysis_content.split('\n')
 
524
  found_relevant_measurement = True
525
  break
526
 
527
+ # Part 2: Expert recommendation (synthesized from source - keep concise)
528
  sentences = chunk_content.split('. ')
529
+ meaningful_sentences = [s.strip() for s in sentences if len(s.strip()) > 20][:2]
530
  expert_advice = '. '.join(meaningful_sentences[:2]) + '.'
531
 
532
  response_parts.append(f"Based on {source_title}, {expert_advice}")
 
534
  # Part 3: Improvement recommendation (only connect to swing analysis if relevant)
535
  if user_swing_context and found_relevant_measurement and not is_non_biomechanics:
536
  # Only provide swing-analysis-specific advice if we found relevant measurements
537
+ response_parts.append("Focus on implementing this expert advice to address your specific swing characteristics.")
 
538
  else:
539
  # For non-biomechanics questions or when no relevant measurements found
540
+ response_parts.append("Focus on implementing this expert advice.")
 
 
 
541
 
542
+ # Combine all parts with space separation to keep it concise
543
+ final_response = " ".join(response_parts)
544
 
545
  return final_response
546