Girish Jeswani commited on
Commit
d7b2f43
·
1 Parent(s): b4a645a

rag test script

Browse files
multi_llm_chatbot_backend/app/tests/test_rag_system.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ import time
4
+
5
+ BASE_URL = "http://localhost:8000"
6
+
7
+ def test_rag_system():
8
+ """
9
+ Comprehensive test of the RAG system
10
+ """
11
+ print("🚀 Testing RAG System Integration\n")
12
+
13
+ # Test 1: Upload a document
14
+ print("📄 Test 1: Uploading a document...")
15
+
16
+ # Create a sample research document
17
+ sample_document = """
18
+ Research Methodology for Machine Learning PhD
19
+
20
+ Abstract: This document outlines the methodology for conducting research in machine learning,
21
+ focusing on experimental design, data collection, and validation techniques.
22
+
23
+ 1. Introduction
24
+ Machine learning research requires rigorous methodology to ensure reproducible results.
25
+ The theoretical framework must be grounded in statistical learning theory.
26
+
27
+ 2. Methodology
28
+ Our research design follows a mixed-methods approach combining quantitative experiments
29
+ with qualitative analysis. Data collection involves sampling from multiple datasets
30
+ to ensure statistical validity and external validity.
31
+
32
+ 3. Practical Implementation
33
+ The implementation strategy focuses on actionable steps: first, establish baseline models,
34
+ then implement incremental improvements, and finally conduct comprehensive evaluation.
35
+ Each step should have clear success metrics and timelines.
36
+
37
+ 4. Theoretical Framework
38
+ The conceptual foundation draws from information theory, statistical learning theory,
39
+ and computational complexity theory. The epistemological assumptions underlying
40
+ our approach assume that knowledge can be extracted from data through systematic analysis.
41
+
42
+ 5. Next Steps
43
+ Immediate action items include: data preprocessing, model selection, hyperparameter tuning,
44
+ and result validation. The timeline should prioritize high-impact activities first.
45
+ """
46
+
47
+ # Save as temporary file
48
+ with open("temp_research_doc.txt", "w") as f:
49
+ f.write(sample_document)
50
+
51
+ # Upload the document
52
+ with open("temp_research_doc.txt", "rb") as f:
53
+ files = {"file": ("research_methodology.txt", f, "text/plain")}
54
+ upload_response = requests.post(f"{BASE_URL}/upload-document", files=files)
55
+
56
+ print(f"Upload Status: {upload_response.status_code}")
57
+ print(f"Response: {json.dumps(upload_response.json(), indent=2)}\n")
58
+
59
+ # Test 2: Get document statistics
60
+ print("📊 Test 2: Getting document statistics...")
61
+ stats_response = requests.get(f"{BASE_URL}/document-stats")
62
+ print(f"Stats: {json.dumps(stats_response.json(), indent=2)}\n")
63
+
64
+ # Test 3: Test direct document search
65
+ print("🔍 Test 3: Testing direct document search...")
66
+
67
+ search_queries = [
68
+ {"query": "What methodology should I use?", "persona": "methodist"},
69
+ {"query": "What is the theoretical framework?", "persona": "theorist"},
70
+ {"query": "What are the next steps?", "persona": "pragmatist"}
71
+ ]
72
+
73
+ for search in search_queries:
74
+ print(f"\nSearching: '{search['query']}' for {search['persona']}")
75
+ search_response = requests.post(
76
+ f"{BASE_URL}/search-documents",
77
+ json=search
78
+ )
79
+
80
+ if search_response.status_code == 200:
81
+ results = search_response.json()
82
+ print(f"Found {results['results_count']} results")
83
+ for i, result in enumerate(results['results'][:2], 1): # Show top 2
84
+ print(f" Result {i}: {result['text'][:100]}... (score: {result['relevance_score']:.3f})")
85
+ else:
86
+ print(f"Search failed: {search_response.status_code}")
87
+
88
+ print("\n" + "="*60)
89
+
90
+ # Test 4: Test RAG-enhanced chat
91
+ print("💬 Test 4: Testing RAG-enhanced chat responses...\n")
92
+
93
+ chat_queries = [
94
+ "I need help with my research methodology. What approach should I take?",
95
+ "Can you explain the theoretical framework I should consider?",
96
+ "What are the practical next steps I should focus on?"
97
+ ]
98
+
99
+ for query in chat_queries:
100
+ print(f"Query: {query}")
101
+ chat_response = requests.post(
102
+ f"{BASE_URL}/chat-sequential",
103
+ json={"user_input": query, "response_length": "short"}
104
+ )
105
+
106
+ if chat_response.status_code == 200:
107
+ result = chat_response.json()
108
+ print(f"Response type: {result.get('type')}")
109
+
110
+ if 'rag_info' in result:
111
+ rag_info = result['rag_info']
112
+ print(f"RAG Info: {rag_info['personas_using_documents']}/{len(result.get('responses', []))} personas used documents")
113
+ print(f"Total chunks used: {rag_info['total_document_chunks_used']}")
114
+
115
+ # Show one advisor response
116
+ if 'responses' in result and result['responses']:
117
+ advisor = result['responses'][0]
118
+ print(f"\n{advisor['persona_name']}: {advisor['response'][:200]}...")
119
+ if advisor.get('used_documents'):
120
+ print(f"✅ Used {advisor.get('document_chunks_used', 0)} document chunks")
121
+ else:
122
+ print("❌ No documents used")
123
+ else:
124
+ print(f"Chat failed: {chat_response.status_code}")
125
+
126
+ print("\n" + "-"*40 + "\n")
127
+
128
+ # Test 5: Session statistics
129
+ print("📈 Test 5: Getting comprehensive session statistics...")
130
+ session_stats = requests.get(f"{BASE_URL}/session-stats")
131
+ if session_stats.status_code == 200:
132
+ stats = session_stats.json()
133
+ print(f"Session Stats:")
134
+ print(f" Messages: {stats.get('message_count', 0)}")
135
+ print(f" Uploaded files: {len(stats.get('uploaded_files', []))}")
136
+ print(f" RAG documents: {stats.get('rag_stats', {}).get('total_documents', 0)}")
137
+ print(f" RAG chunks: {stats.get('rag_stats', {}).get('total_chunks', 0)}")
138
+
139
+ # Cleanup
140
+ import os
141
+ try:
142
+ os.remove("temp_research_doc.txt")
143
+ except:
144
+ pass
145
+
146
+ print("\n🎉 RAG System Testing Complete!")
147
+ print("\nKey Improvements:")
148
+ print("✅ Documents are now chunked and stored in vector database")
149
+ print("✅ Each advisor gets persona-specific document chunks")
150
+ print("✅ Only relevant content is retrieved for each query")
151
+ print("✅ Session context is much more efficient")
152
+ print("✅ Supports semantic search across all uploaded documents")
153
+
154
+ if __name__ == "__main__":
155
+ test_rag_system()