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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Debug RAG Chat Integration
|
| 4 |
+
|
| 5 |
+
This script helps debug why RAG isn't working in chat responses.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import requests
|
| 9 |
+
import json
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
BASE_URL = "http://localhost:8000"
|
| 13 |
+
|
| 14 |
+
def test_direct_search():
|
| 15 |
+
"""Test direct document search with detailed output"""
|
| 16 |
+
print("🔍 Testing direct document search...")
|
| 17 |
+
|
| 18 |
+
test_queries = [
|
| 19 |
+
{"query": "research methodology approach", "persona": "methodist"},
|
| 20 |
+
{"query": "theoretical framework theory", "persona": "theorist"},
|
| 21 |
+
{"query": "practical steps implementation", "persona": "pragmatist"}
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
for test in test_queries:
|
| 25 |
+
print(f"\nTesting: '{test['query']}' for {test['persona']}")
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
response = requests.post(
|
| 29 |
+
f"{BASE_URL}/search-documents",
|
| 30 |
+
json=test,
|
| 31 |
+
timeout=10
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
if response.status_code == 200:
|
| 35 |
+
result = response.json()
|
| 36 |
+
print(f"✅ Found {result['results_count']} results")
|
| 37 |
+
|
| 38 |
+
for i, chunk in enumerate(result['results'], 1):
|
| 39 |
+
score = chunk['relevance_score']
|
| 40 |
+
distance = chunk.get('distance', 'unknown')
|
| 41 |
+
text_preview = chunk['text'][:100]
|
| 42 |
+
|
| 43 |
+
print(f" Result {i}:")
|
| 44 |
+
print(f" Relevance: {score:.4f}")
|
| 45 |
+
print(f" Distance: {distance}")
|
| 46 |
+
print(f" Text: {text_preview}...")
|
| 47 |
+
print(f" Meets 0.1 threshold: {'✅' if score > 0.1 else '❌'}")
|
| 48 |
+
else:
|
| 49 |
+
print(f"❌ Search failed: {response.status_code}")
|
| 50 |
+
|
| 51 |
+
except Exception as e:
|
| 52 |
+
print(f"❌ Search error: {e}")
|
| 53 |
+
|
| 54 |
+
def test_single_persona_chat():
|
| 55 |
+
"""Test individual persona chat to isolate issues"""
|
| 56 |
+
print("\n💬 Testing individual persona chat...")
|
| 57 |
+
|
| 58 |
+
personas = ["methodist", "theorist", "pragmatist"]
|
| 59 |
+
query = "What research methodology should I use based on the uploaded document?"
|
| 60 |
+
|
| 61 |
+
for persona in personas:
|
| 62 |
+
print(f"\nTesting {persona}...")
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
# Note: This endpoint might not exist yet, but we can try
|
| 66 |
+
response = requests.post(
|
| 67 |
+
f"{BASE_URL}/chat/{persona}",
|
| 68 |
+
json={"user_input": query, "response_length": "short"},
|
| 69 |
+
timeout=15
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
if response.status_code == 200:
|
| 73 |
+
result = response.json()
|
| 74 |
+
print(f"✅ {persona} response received")
|
| 75 |
+
|
| 76 |
+
if 'rag_info' in result:
|
| 77 |
+
rag_info = result['rag_info']
|
| 78 |
+
print(f" Used documents: {rag_info.get('used_documents', False)}")
|
| 79 |
+
print(f" Chunks used: {rag_info.get('document_chunks_used', 0)}")
|
| 80 |
+
|
| 81 |
+
if 'persona' in result:
|
| 82 |
+
response_text = result['persona'].get('response', '')[:150]
|
| 83 |
+
print(f" Response: {response_text}...")
|
| 84 |
+
else:
|
| 85 |
+
print(f"❌ {persona} chat failed: {response.status_code}")
|
| 86 |
+
|
| 87 |
+
except Exception as e:
|
| 88 |
+
print(f"❌ {persona} chat error: {e}")
|
| 89 |
+
|
| 90 |
+
def test_sequential_chat_debug():
|
| 91 |
+
"""Test sequential chat with more detailed debugging"""
|
| 92 |
+
print("\n🔄 Testing sequential chat with debug info...")
|
| 93 |
+
|
| 94 |
+
query = "Based on the methodology document I uploaded, what approach should I take?"
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
response = requests.post(
|
| 98 |
+
f"{BASE_URL}/chat-sequential",
|
| 99 |
+
json={"user_input": query, "response_length": "short"},
|
| 100 |
+
timeout=30
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
if response.status_code == 200:
|
| 104 |
+
result = response.json()
|
| 105 |
+
print(f"✅ Sequential chat response received")
|
| 106 |
+
print(f" Response type: {result.get('type')}")
|
| 107 |
+
|
| 108 |
+
if 'rag_info' in result:
|
| 109 |
+
rag_info = result['rag_info']
|
| 110 |
+
print(f" RAG enabled: {rag_info.get('rag_enabled', False)}")
|
| 111 |
+
print(f" Personas using documents: {rag_info.get('personas_using_documents', 0)}")
|
| 112 |
+
print(f" Total chunks used: {rag_info.get('total_document_chunks_used', 0)}")
|
| 113 |
+
|
| 114 |
+
if 'responses' in result:
|
| 115 |
+
print(f"\n Individual persona results:")
|
| 116 |
+
for resp in result['responses']:
|
| 117 |
+
persona_name = resp.get('persona_name', 'Unknown')
|
| 118 |
+
used_docs = resp.get('used_documents', False)
|
| 119 |
+
chunks_used = resp.get('document_chunks_used', 0)
|
| 120 |
+
error = resp.get('error', False)
|
| 121 |
+
|
| 122 |
+
print(f" {persona_name}:")
|
| 123 |
+
print(f" Used documents: {used_docs}")
|
| 124 |
+
print(f" Chunks used: {chunks_used}")
|
| 125 |
+
print(f" Error: {error}")
|
| 126 |
+
|
| 127 |
+
if resp.get('response'):
|
| 128 |
+
response_preview = resp['response'][:100]
|
| 129 |
+
print(f" Response: {response_preview}...")
|
| 130 |
+
else:
|
| 131 |
+
print(f"❌ Sequential chat failed: {response.status_code}")
|
| 132 |
+
print(f" Response: {response.text}")
|
| 133 |
+
|
| 134 |
+
except Exception as e:
|
| 135 |
+
print(f"❌ Sequential chat error: {e}")
|
| 136 |
+
|
| 137 |
+
def upload_better_test_document():
|
| 138 |
+
"""Upload a more targeted test document"""
|
| 139 |
+
print("\n📄 Uploading better test document...")
|
| 140 |
+
|
| 141 |
+
better_doc = """
|
| 142 |
+
PhD Research Methodology Guide for Machine Learning
|
| 143 |
+
|
| 144 |
+
METHODOLOGY SECTION:
|
| 145 |
+
For machine learning research, you should use a mixed-methods approach combining quantitative experiments with qualitative analysis. Start with baseline models and incrementally add complexity. Use proper train/validation/test splits with stratified sampling. Statistical significance testing is crucial for methodology validation.
|
| 146 |
+
|
| 147 |
+
THEORETICAL FRAMEWORK SECTION:
|
| 148 |
+
Ground your work in established learning theory and computational complexity theory. Consider information theory principles and statistical learning theory. The epistemological assumptions should assume that knowledge can be extracted from data through systematic analysis. Review relevant literature and position your work within existing theoretical frameworks.
|
| 149 |
+
|
| 150 |
+
PRACTICAL IMPLEMENTATION SECTION:
|
| 151 |
+
Your next steps should include: 1) Define clear research questions, 2) Design data collection methods, 3) Implement baseline models, 4) Conduct hyperparameter tuning, 5) Perform comprehensive evaluation, 6) Document all results. Create a timeline with specific milestones and success metrics for each phase.
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
try:
|
| 155 |
+
with open("better_test_doc.txt", "w") as f:
|
| 156 |
+
f.write(better_doc)
|
| 157 |
+
|
| 158 |
+
with open("better_test_doc.txt", "rb") as f:
|
| 159 |
+
files = {"file": ("ml_methodology_guide.txt", f, "text/plain")}
|
| 160 |
+
response = requests.post(f"{BASE_URL}/upload-document", files=files)
|
| 161 |
+
|
| 162 |
+
import os
|
| 163 |
+
os.remove("better_test_doc.txt")
|
| 164 |
+
|
| 165 |
+
if response.status_code == 200:
|
| 166 |
+
result = response.json()
|
| 167 |
+
print(f"✅ Better document uploaded: {result['chunks_created']} chunks")
|
| 168 |
+
return True
|
| 169 |
+
else:
|
| 170 |
+
print(f"❌ Upload failed: {response.status_code}")
|
| 171 |
+
return False
|
| 172 |
+
|
| 173 |
+
except Exception as e:
|
| 174 |
+
print(f"❌ Upload error: {e}")
|
| 175 |
+
return False
|
| 176 |
+
|
| 177 |
+
def main():
|
| 178 |
+
"""Run debug sequence"""
|
| 179 |
+
print("🔧 RAG Chat Debug Tool")
|
| 180 |
+
print("=" * 40)
|
| 181 |
+
|
| 182 |
+
# Test 1: Upload better document
|
| 183 |
+
if not upload_better_test_document():
|
| 184 |
+
print("❌ Document upload failed, continuing with existing document...")
|
| 185 |
+
|
| 186 |
+
# Test 2: Direct search
|
| 187 |
+
test_direct_search()
|
| 188 |
+
|
| 189 |
+
# Test 3: Individual persona chat (if endpoint exists)
|
| 190 |
+
test_single_persona_chat()
|
| 191 |
+
|
| 192 |
+
# Test 4: Sequential chat with debug
|
| 193 |
+
test_sequential_chat_debug()
|
| 194 |
+
|
| 195 |
+
print("\n" + "=" * 40)
|
| 196 |
+
print("🔍 Debug Analysis:")
|
| 197 |
+
print("1. Check if direct search shows relevance scores > 0.1")
|
| 198 |
+
print("2. Check if individual personas work (may not be implemented)")
|
| 199 |
+
print("3. Check if sequential chat shows 'used_documents: true' for any persona")
|
| 200 |
+
print("4. Look for server logs showing document retrieval attempts")
|
| 201 |
+
|
| 202 |
+
print("\nIf RAG still isn't working:")
|
| 203 |
+
print("- Check server logs for 'Retrieved X chunks for persona_name'")
|
| 204 |
+
print("- Verify relevance scores are above 0.1 threshold")
|
| 205 |
+
print("- Ensure document context is being passed to personas")
|
| 206 |
+
|
| 207 |
+
if __name__ == "__main__":
|
| 208 |
+
main()
|