-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_test.py
More file actions
274 lines (216 loc) · 8.37 KB
/
Copy pathquick_test.py
File metadata and controls
274 lines (216 loc) · 8.37 KB
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
269
270
271
272
273
274
"""
Quick Test Script for Multi-Modal RAG Agent with Web Search
Run this to verify your installation and configuration
"""
import os
import sys
from dotenv import load_dotenv
def check_dependencies():
"""Check if all required packages are installed"""
print("🔍 Checking dependencies...")
required_packages = {
'langchain': 'LangChain',
'chromadb': 'ChromaDB',
'sentence_transformers': 'Sentence Transformers',
'openai': 'OpenAI',
'duckduckgo_search': 'DuckDuckGo Search',
'unstructured': 'Unstructured',
'docx': 'python-docx',
'streamlit': 'Streamlit'
}
missing = []
for package, name in required_packages.items():
try:
__import__(package)
print(f" ✓ {name}")
except ImportError:
print(f" ✗ {name} - MISSING")
missing.append(name)
if missing:
print(f"\n❌ Missing packages: {', '.join(missing)}")
print("Run: pip install -r requirements.txt")
return False
print("✓ All dependencies installed!\n")
return True
def check_environment():
"""Check environment configuration"""
print("🔍 Checking environment configuration...")
load_dotenv()
openrouter_key = os.getenv("OPENROUTER_API_KEY")
if openrouter_key:
print(f" ✓ OPENROUTER_API_KEY found ({openrouter_key[:10]}...)")
else:
print(" ✗ OPENROUTER_API_KEY not found")
print(" Get your key from: https://openrouter.ai/keys")
return False
print("✓ Environment configured!\n")
return True
def test_basic_initialization():
"""Test basic agent initialization"""
print("🔍 Testing basic initialization...")
try:
from multimodal_rag import MultiModalRAGAgent
agent = MultiModalRAGAgent(
api_key=os.getenv("OPENROUTER_API_KEY"),
model="meituan/longcat-flash-chat:free",
enable_web_search=False # Start without web search
)
print(" ✓ Agent initialized successfully")
return True, agent
except Exception as e:
print(f" ✗ Initialization failed: {e}")
return False, None
def test_web_search():
"""Test web search functionality"""
print("\n🔍 Testing web search...")
try:
from multimodal_rag import MultiModalRAGAgent, WebSearchTool
# Test DuckDuckGo (free)
print(" Testing DuckDuckGo (free)...")
search_tool = WebSearchTool(provider="duckduckgo")
results = search_tool.search("Python programming", max_results=2)
if results:
print(f" ✓ DuckDuckGo working - Found {len(results)} results")
print(f" Example: {results[0]['title']}")
else:
print(" ⚠ DuckDuckGo returned no results (might be rate limited)")
return True
except Exception as e:
print(f" ✗ Web search test failed: {e}")
return False
def test_full_agent_with_web():
"""Test full agent with web search"""
print("\n🔍 Testing full agent with web search...")
try:
from multimodal_rag import MultiModalRAGAgent
agent = MultiModalRAGAgent(
api_key=os.getenv("OPENROUTER_API_KEY"),
model="meituan/longcat-flash-chat:free",
enable_web_search=True,
search_provider="duckduckgo"
)
print(" ✓ Agent with web search initialized")
# Test standalone web search
print(" Testing standalone web search...")
results = agent.search_and_augment("latest AI news", max_results=2)
if results:
print(f" ✓ Web search working - Found {len(results)} results")
for i, result in enumerate(results, 1):
print(f" {i}. {result['title'][:60]}...")
else:
print(" ⚠ No results returned (might be rate limited)")
return True
except Exception as e:
print(f" ✗ Full agent test failed: {e}")
return False
def test_llm_connection():
"""Test LLM connection"""
print("\n🔍 Testing LLM connection...")
try:
from openai import OpenAI
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.getenv("OPENROUTER_API_KEY")
)
response = client.chat.completions.create(
model="meituan/longcat-flash-chat:free",
messages=[
{"role": "user", "content": "Say 'Hello' in one word"}
],
max_tokens=10
)
reply = response.choices[0].message.content
print(f" ✓ LLM connection working")
print(f" Response: {reply}")
return True
except Exception as e:
print(f" ✗ LLM connection failed: {e}")
return False
def interactive_test():
"""Run an interactive test"""
print("\n" + "="*60)
print("🎯 Interactive Test")
print("="*60)
try:
from multimodal_rag import MultiModalRAGAgent
agent = MultiModalRAGAgent(
api_key=os.getenv("OPENROUTER_API_KEY"),
model="meituan/longcat-flash-chat:free",
enable_web_search=True,
search_provider="duckduckgo"
)
print("\nAgent ready! You can now:")
print("1. Test web search")
print("2. Test Q&A (without documents)")
print("3. Exit")
while True:
choice = input("\nEnter choice (1-3): ").strip()
if choice == "1":
query = input("Enter search query: ").strip()
if query:
print("\n🔍 Searching...")
results = agent.search_and_augment(query, max_results=3)
if results:
print(f"\nFound {len(results)} results:")
for i, r in enumerate(results, 1):
print(f"\n{i}. {r['title']}")
print(f" {r['url']}")
print(f" {r['snippet'][:100]}...")
else:
print("No results found.")
elif choice == "2":
question = input("Enter question: ").strip()
if question:
print("\n💭 Thinking...")
result = agent.answer_question(question, use_web_search=True)
print(f"\n📝 Answer:\n{result['answer']}")
if result['web_results']:
print(f"\n🌐 Used {len(result['web_results'])} web sources")
elif choice == "3":
print("\n👋 Goodbye!")
break
else:
print("Invalid choice. Please enter 1-3.")
except KeyboardInterrupt:
print("\n\n👋 Test interrupted by user")
except Exception as e:
print(f"\n❌ Error: {e}")
def main():
"""Run all tests"""
print("\n" + "="*60)
print("Multi-Modal RAG Agent - Quick Test Script")
print("="*60 + "\n")
# Check dependencies
if not check_dependencies():
sys.exit(1)
# Check environment
if not check_environment():
sys.exit(1)
# Test basic initialization
success, agent = test_basic_initialization()
if not success:
sys.exit(1)
# Test LLM connection
if not test_llm_connection():
print("\n⚠ Warning: LLM connection issues. Check your API key and internet connection.")
# Test web search
if not test_web_search():
print("\n⚠ Warning: Web search issues. Will continue without web search.")
# Test full agent with web
test_full_agent_with_web()
# Summary
print("\n" + "="*60)
print("✓ Basic tests completed!")
print("="*60)
print("\nNext steps:")
print("1. Run the Streamlit UI: streamlit run app.py")
print("2. Try the examples: python usage_examples.py")
print("3. Run interactive test (below)")
# Ask if user wants interactive test
response = input("\nWould you like to run the interactive test? (y/n): ").strip().lower()
if response == 'y':
interactive_test()
else:
print("\n👋 Test complete! Your agent is ready to use.")
if __name__ == "__main__":
main()