File size: 10,772 Bytes
aa018e3 |
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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
"""
Test script for RAG Agent logic.
Tests the agent workflow, nodes, state management, and retrieval.
"""
import sys
from pathlib import Path
# Add project root to path
sys.path.insert(0, str(Path(__file__).parent))
from langchain_core.messages import HumanMessage, AIMessage
from agent.state import AgentState
from core.rag_agent import RAGAgent
def print_separator(title: str):
"""Print a visual separator."""
print("\n" + "="*70)
print(f" {title}")
print("="*70 + "\n")
def test_agent_initialization():
"""Test RAGAgent can be initialized properly."""
print_separator("TEST 1: Agent Initialization")
try:
agent = RAGAgent()
print("β RAGAgent initialized successfully")
print(f" - Thread ID: {agent.thread_id}")
print(f" - LLM Model: {agent.llm.model_name if hasattr(agent.llm, 'model_name') else 'initialized'}")
print(f" - Graph: {type(agent.agent_graph).__name__}")
return agent
except Exception as e:
print(f"β Failed to initialize RAGAgent: {e}")
import traceback
traceback.print_exc()
return None
def test_simple_query(agent: RAGAgent):
"""Test a simple query execution."""
print_separator("TEST 2: Simple Query")
if agent is None:
print("β Skipping - agent not initialized")
return False
try:
query = "What is DeepAnalyze?"
print(f"Query: '{query}'")
initial_state = {
"messages": [HumanMessage(content=query)],
}
result = agent.agent_graph.invoke(
initial_state,
config=agent.get_config()
)
messages = result.get("messages", [])
ai_messages = [m for m in messages if isinstance(m, AIMessage)]
if ai_messages:
print(f"β Query executed successfully")
print(f" Total messages: {len(messages)}")
print(f" Response length: {len(ai_messages[-1].content)} chars")
print(f"\n Response preview:")
print(f" {ai_messages[-1].content[:300]}...")
return True
else:
print(f"β No AI response generated")
return False
except Exception as e:
print(f"β Query execution failed: {e}")
import traceback
traceback.print_exc()
return False
def test_rag_query(agent: RAGAgent):
"""Test a query that should use RAG (local documents)."""
print_separator("TEST 3: RAG Query")
if agent is None:
print("β Skipping - agent not initialized")
return False
try:
query = "Explain the architecture of SAM 3"
print(f"Query: '{query}' (should use local documents)")
initial_state = {
"messages": [HumanMessage(content=query)],
}
result = agent.agent_graph.invoke(
initial_state,
config=agent.get_config()
)
messages = result.get("messages", [])
rag_method = result.get("rag_method", "UNKNOWN")
ai_messages = [m for m in messages if isinstance(m, AIMessage)]
print(f" Routing decision: {rag_method}")
if ai_messages:
print(f"β RAG query executed")
print(f" Response preview:")
print(f" {ai_messages[-1].content[:300]}...")
return True
else:
print(f"β No response generated")
return False
except Exception as e:
print(f"β RAG query failed: {e}")
import traceback
traceback.print_exc()
return False
def test_web_search_query(agent: RAGAgent):
"""Test a query that should use web search."""
print_separator("TEST 4: Web Search Query")
if agent is None:
print("β Skipping - agent not initialized")
return False
try:
query = "What's the latest news about AI in 2025?"
print(f"Query: '{query}' (should use web search)")
initial_state = {
"messages": [HumanMessage(content=query)],
}
result = agent.agent_graph.invoke(
initial_state,
config=agent.get_config()
)
messages = result.get("messages", [])
rag_method = result.get("rag_method", "UNKNOWN")
ai_messages = [m for m in messages if isinstance(m, AIMessage)]
print(f" Routing decision: {rag_method}")
if ai_messages:
print(f"β Web search query executed")
print(f" Response preview:")
print(f" {ai_messages[-1].content[:300]}...")
return True
else:
print(f"β No response generated")
return False
except Exception as e:
print(f"β Web search query failed: {e}")
import traceback
traceback.print_exc()
return False
def test_general_query(agent: RAGAgent):
"""Test a general query that doesn't need RAG or web search."""
print_separator("TEST 5: General Query")
if agent is None:
print("β Skipping - agent not initialized")
return False
try:
query = "What is 15 multiplied by 7?"
print(f"Query: '{query}' (should use general LLM)")
initial_state = {
"messages": [HumanMessage(content=query)],
}
result = agent.agent_graph.invoke(
initial_state,
config=agent.get_config()
)
messages = result.get("messages", [])
rag_method = result.get("rag_method", "UNKNOWN")
ai_messages = [m for m in messages if isinstance(m, AIMessage)]
print(f" Routing decision: {rag_method}")
if ai_messages:
print(f"β General query executed")
print(f" Response: {ai_messages[-1].content}")
return True
else:
print(f"β No response generated")
return False
except Exception as e:
print(f"β General query failed: {e}")
import traceback
traceback.print_exc()
return False
def test_conversation_memory(agent: RAGAgent):
"""Test multi-turn conversation with memory."""
print_separator("TEST 6: Conversation Memory")
if agent is None:
print("β Skipping - agent not initialized")
return False
try:
# Reset thread for clean test
agent.reset_thread()
# First turn
print("Turn 1: 'What is DeepAnalyze?'")
state1 = {
"messages": [HumanMessage(content="What is DeepAnalyze?")],
}
result1 = agent.agent_graph.invoke(state1, config=agent.get_config())
ai_msg_1 = [m for m in result1["messages"] if isinstance(m, AIMessage)]
if not ai_msg_1:
print("β No response in turn 1")
return False
print(f"β Turn 1 response: {ai_msg_1[-1].content[:100]}...")
# Second turn - follow-up question
print("\nTurn 2: 'What are its main features?' (requires context)")
state2 = {
"messages": [HumanMessage(content="What are its main features?")],
}
result2 = agent.agent_graph.invoke(state2, config=agent.get_config())
ai_msg_2 = [m for m in result2["messages"] if isinstance(m, AIMessage)]
if not ai_msg_2:
print("β No response in turn 2")
return False
print(f"β Turn 2 response: {ai_msg_2[-1].content[:100]}...")
# Check if response makes sense in context
response = ai_msg_2[-1].content.lower()
if "deepanalyze" in response or "feature" in response or "agent" in response:
print("β Conversation memory working - response uses context")
return True
else:
print("β Response may not be using conversation context properly")
return True # Still pass, as it generated a response
except Exception as e:
print(f"β Conversation memory test failed: {e}")
import traceback
traceback.print_exc()
return False
def test_thread_reset(agent: RAGAgent):
"""Test thread reset functionality."""
print_separator("TEST 7: Thread Reset")
if agent is None:
print("β Skipping - agent not initialized")
return False
try:
old_thread_id = agent.thread_id
print(f"Old thread ID: {old_thread_id}")
agent.reset_thread()
new_thread_id = agent.thread_id
print(f"New thread ID: {new_thread_id}")
if old_thread_id != new_thread_id:
print("β Thread reset successfully")
return True
else:
print("β Thread ID unchanged after reset")
return False
except Exception as e:
print(f"β Thread reset failed: {e}")
import traceback
traceback.print_exc()
return False
def run_all_tests():
"""Run all tests and provide summary."""
print("\n" + "β"*70)
print(" RAG AGENT TEST SUITE")
print("β"*70)
# Initialize agent once
agent = test_agent_initialization()
if agent is None:
print("\nβ Cannot proceed - agent initialization failed")
return False
tests = [
("Simple Query", lambda: test_simple_query(agent)),
("RAG Query", lambda: test_rag_query(agent)),
("Web Search Query", lambda: test_web_search_query(agent)),
("General Query", lambda: test_general_query(agent)),
("Conversation Memory", lambda: test_conversation_memory(agent)),
("Thread Reset", lambda: test_thread_reset(agent)),
]
results = {}
for name, test_func in tests:
try:
results[name] = test_func()
except Exception as e:
print(f"\nβ Test '{name}' crashed: {e}")
import traceback
traceback.print_exc()
results[name] = False
# Print summary
print_separator("TEST SUMMARY")
passed = sum(results.values())
total = len(results)
for name, passed_test in results.items():
status = "β PASS" if passed_test else "β FAIL"
print(f"{status}: {name}")
print(f"\n{'='*70}")
print(f" TOTAL: {passed}/{total} tests passed ({passed/total*100:.1f}%)")
print(f"{'='*70}\n")
return passed == total
if __name__ == "__main__":
success = run_all_tests()
sys.exit(0 if success else 1) |