Spaces:
Runtime error
Runtime error
File size: 8,998 Bytes
eeb0f9c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
"""
Feedback Loop Example
Demonstrates collecting and learning from user feedback
"""
from feedback import get_feedback_collector, get_feedback_analyzer, FeedbackCategory
def example_collect_ratings():
"""Example: Collect user ratings"""
print("=" * 60)
print("COLLECTING USER RATINGS")
print("=" * 60)
collector = get_feedback_collector()
# Example 1: High rating (5 stars)
print("\n✅ Example 1: User loves the response")
feedback_id = collector.collect_rating(
user_id="user123",
agent_name="nutrition_agent",
user_message="Tôi muốn giảm cân, nên ăn gì?",
agent_response="Để giảm cân hiệu quả, bạn nên ăn nhiều rau xanh, protein...",
rating=5,
category=FeedbackCategory.HELPFULNESS,
comment="Rất hữu ích và chi tiết!"
)
print(f" Feedback ID: {feedback_id}")
print(f" Rating: 5/5 ⭐⭐⭐⭐⭐")
# Example 2: Low rating (2 stars)
print("\n❌ Example 2: User unhappy with response")
feedback_id = collector.collect_rating(
user_id="user456",
agent_name="nutrition_agent",
user_message="Tôi bị tiểu đường, ăn gì được?",
agent_response="Bạn nên ăn ít đường.",
rating=2,
category=FeedbackCategory.COMPLETENESS,
comment="Quá chung chung, không cụ thể"
)
print(f" Feedback ID: {feedback_id}")
print(f" Rating: 2/5 ⭐⭐")
# Example 3: Thumbs up
print("\n👍 Example 3: Quick thumbs up")
feedback_id = collector.collect_thumbs(
user_id="user789",
agent_name="exercise_agent",
user_message="Tập gì để giảm mỡ bụng?",
agent_response="Bạn nên tập plank, crunches, và cardio...",
is_positive=True,
comment="Hay!"
)
print(f" Feedback ID: {feedback_id}")
print(f" Thumbs: 👍")
def example_collect_corrections():
"""Example: Collect user corrections"""
print("\n" + "=" * 60)
print("COLLECTING USER CORRECTIONS")
print("=" * 60)
collector = get_feedback_collector()
# Example: User corrects wrong information
print("\n📝 User corrects incorrect BMI calculation")
feedback_id = collector.collect_correction(
user_id="user123",
agent_name="nutrition_agent",
user_message="Tôi 70kg, 175cm, BMI của tôi là bao nhiêu?",
agent_response="BMI của bạn là 24.5", # Wrong!
corrected_response="BMI của bạn là 22.9 (70 / 1.75²)",
correction_reason="calculation_error"
)
print(f" Correction ID: {feedback_id}")
print(f" Original: BMI = 24.5 ❌")
print(f" Corrected: BMI = 22.9 ✅")
def example_report_issue():
"""Example: Report problematic response"""
print("\n" + "=" * 60)
print("REPORTING ISSUES")
print("=" * 60)
collector = get_feedback_collector()
# Example: Report harmful advice
print("\n⚠️ User reports harmful medical advice")
report_id = collector.report_issue(
user_id="user999",
agent_name="symptom_agent",
user_message="Tôi bị đau ngực dữ dội",
agent_response="Bạn nên nghỉ ngơi, uống nước",
issue_type="harmful",
description="Đau ngực dữ dội cần đi bệnh viện ngay, không nên chỉ nghỉ ngơi",
severity="critical"
)
print(f" Report ID: {report_id}")
print(f" Severity: CRITICAL 🚨")
def example_analyze_feedback():
"""Example: Analyze feedback to find patterns"""
print("\n" + "=" * 60)
print("ANALYZING FEEDBACK")
print("=" * 60)
collector = get_feedback_collector()
# Add more sample data
print("\n📊 Adding sample feedback data...")
for i in range(10):
collector.collect_rating(
user_id=f"user{i}",
agent_name="nutrition_agent",
user_message=f"Question {i}",
agent_response=f"Response {i}",
rating=4 if i % 2 == 0 else 3,
category=FeedbackCategory.HELPFULNESS
)
# Get statistics
print("\n📈 Feedback Statistics:")
stats = collector.get_feedback_stats(agent_name="nutrition_agent")
print(f" Total ratings: {stats['total_ratings']}")
print(f" Average rating: {stats['average_rating']:.1f}/5.0")
print(f" Rating distribution:")
for rating in [5, 4, 3, 2, 1]:
count = stats['rating_distribution'][rating]
print(f" {rating} stars: {count}")
# Analyze performance
print("\n🔍 Performance Analysis:")
analyzer = get_feedback_analyzer(collector)
analysis = analyzer.analyze_agent_performance("nutrition_agent")
print(f" Overall rating: {analysis['overall_rating']:.1f}/5.0")
if analysis['strengths']:
print(f"\n Strengths:")
for strength in analysis['strengths']:
print(f" ✅ {strength}")
if analysis['weaknesses']:
print(f"\n Weaknesses:")
for weakness in analysis['weaknesses']:
print(f" ⚠️ {weakness}")
def example_get_insights():
"""Example: Get actionable insights"""
print("\n" + "=" * 60)
print("ACTIONABLE INSIGHTS")
print("=" * 60)
collector = get_feedback_collector()
analyzer = get_feedback_analyzer(collector)
# Get insights
insights = analyzer.get_actionable_insights("nutrition_agent", limit=3)
if insights:
print("\n💡 Top Improvement Opportunities:")
for i, insight in enumerate(insights, 1):
print(f"\n {i}. [{insight['priority'].upper()}] {insight['category']}")
print(f" Issue: {insight['issue']}")
print(f" Action: {insight['action']}")
if insight['examples']:
print(f" Examples: {', '.join(insight['examples'][:2])}")
else:
print("\n No insights available yet. Collect more feedback!")
def example_generate_report():
"""Example: Generate improvement report"""
print("\n" + "=" * 60)
print("IMPROVEMENT REPORT")
print("=" * 60)
collector = get_feedback_collector()
analyzer = get_feedback_analyzer(collector)
# Generate report
report = analyzer.generate_improvement_report("nutrition_agent")
print(report)
def example_export_for_training():
"""Example: Export feedback for fine-tuning"""
print("\n" + "=" * 60)
print("EXPORT FOR FINE-TUNING")
print("=" * 60)
collector = get_feedback_collector()
# Export high-quality feedback
print("\n📦 Exporting high-quality feedback (rating >= 4)...")
output_file = collector.export_for_fine_tuning(
agent_name="nutrition_agent",
min_rating=4,
include_corrections=True
)
print(f" ✅ Exported to: {output_file}")
print(f" Ready for fine-tuning!")
def example_compare_agents():
"""Example: Compare agent performance"""
print("\n" + "=" * 60)
print("AGENT COMPARISON")
print("=" * 60)
collector = get_feedback_collector()
# Add feedback for different agents
print("\n📊 Adding feedback for multiple agents...")
agents = ["nutrition_agent", "exercise_agent", "symptom_agent"]
for agent in agents:
for i in range(5):
rating = 5 if agent == "nutrition_agent" else (4 if agent == "exercise_agent" else 3)
collector.collect_rating(
user_id=f"user{i}",
agent_name=agent,
user_message=f"Question for {agent}",
agent_response=f"Response from {agent}",
rating=rating
)
# Compare
analyzer = get_feedback_analyzer(collector)
comparison = analyzer.compare_agents()
print(f"\n🏆 Agent Rankings:")
for i, agent in enumerate(comparison['agents'], 1):
print(f" {i}. {agent['agent']}: {agent['average_rating']:.1f}/5.0 ({agent['total_feedback']} feedback)")
if comparison['best_agent']:
print(f"\n Best: {comparison['best_agent']['agent']} 🥇")
if comparison['worst_agent']:
print(f" Needs improvement: {comparison['worst_agent']['agent']} ⚠️")
if __name__ == '__main__':
example_collect_ratings()
example_collect_corrections()
example_report_issue()
example_analyze_feedback()
example_get_insights()
example_generate_report()
example_export_for_training()
example_compare_agents()
print("\n" + "=" * 60)
print("✅ FEEDBACK LOOP DEMO COMPLETE!")
print("=" * 60)
print("\nNext steps:")
print("1. Integrate feedback collection into your UI")
print("2. Review feedback regularly")
print("3. Use insights to improve agents")
print("4. Export high-quality feedback for fine-tuning")
print("5. Monitor trends and act on critical issues")
|