test_aquery_data_endpoint.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. #!/usr/bin/env python3
  2. """
  3. Test script: Demonstrates usage of aquery_data FastAPI endpoint
  4. Query content: Who is the author of LightRAG
  5. Updated to handle the new data format where:
  6. - Response includes status, message, data, and metadata fields at top level
  7. - Actual query results (entities, relationships, chunks, references) are nested under 'data' field
  8. - Includes backward compatibility with legacy format
  9. """
  10. import pytest
  11. import requests
  12. import time
  13. import json
  14. from typing import Dict, Any, List, Optional
  15. # API configuration
  16. API_KEY = "your-secure-api-key-here-123"
  17. BASE_URL = "http://localhost:9621"
  18. # Unified authentication headers
  19. AUTH_HEADERS = {"Content-Type": "application/json", "X-API-Key": API_KEY}
  20. def validate_references_format(references: List[Dict[str, Any]]) -> bool:
  21. """Validate the format of references list"""
  22. if not isinstance(references, list):
  23. print(f"❌ References should be a list, got {type(references)}")
  24. return False
  25. for i, ref in enumerate(references):
  26. if not isinstance(ref, dict):
  27. print(f"❌ Reference {i} should be a dict, got {type(ref)}")
  28. return False
  29. required_fields = ["reference_id", "file_path"]
  30. for field in required_fields:
  31. if field not in ref:
  32. print(f"❌ Reference {i} missing required field: {field}")
  33. return False
  34. if not isinstance(ref[field], str):
  35. print(
  36. f"❌ Reference {i} field '{field}' should be string, got {type(ref[field])}"
  37. )
  38. return False
  39. return True
  40. def parse_streaming_response(
  41. response_text: str,
  42. ) -> tuple[Optional[List[Dict]], List[str], List[str]]:
  43. """Parse streaming response and extract references, response chunks, and errors"""
  44. references = None
  45. response_chunks = []
  46. errors = []
  47. lines = response_text.strip().split("\n")
  48. for line in lines:
  49. line = line.strip()
  50. if not line or line.startswith("data: "):
  51. if line.startswith("data: "):
  52. line = line[6:] # Remove 'data: ' prefix
  53. if not line:
  54. continue
  55. try:
  56. data = json.loads(line)
  57. if "references" in data:
  58. references = data["references"]
  59. if "response" in data:
  60. response_chunks.append(data["response"])
  61. if "error" in data:
  62. errors.append(data["error"])
  63. except json.JSONDecodeError:
  64. # Skip non-JSON lines (like SSE comments)
  65. continue
  66. return references, response_chunks, errors
  67. @pytest.mark.integration
  68. @pytest.mark.requires_api
  69. def test_query_endpoint_references():
  70. """Test /query endpoint references functionality"""
  71. print("\n" + "=" * 60)
  72. print("Testing /query endpoint references functionality")
  73. print("=" * 60)
  74. query_text = "who authored LightRAG"
  75. endpoint = f"{BASE_URL}/query"
  76. # Test 1: References enabled (default)
  77. print("\n🧪 Test 1: References enabled (default)")
  78. print("-" * 40)
  79. try:
  80. response = requests.post(
  81. endpoint,
  82. json={"query": query_text, "mode": "mix", "include_references": True},
  83. headers=AUTH_HEADERS,
  84. timeout=30,
  85. )
  86. if response.status_code == 200:
  87. data = response.json()
  88. # Check response structure
  89. if "response" not in data:
  90. print("❌ Missing 'response' field")
  91. return False
  92. if "references" not in data:
  93. print("❌ Missing 'references' field when include_references=True")
  94. return False
  95. references = data["references"]
  96. if references is None:
  97. print("❌ References should not be None when include_references=True")
  98. return False
  99. if not validate_references_format(references):
  100. return False
  101. print(f"✅ References enabled: Found {len(references)} references")
  102. print(f" Response length: {len(data['response'])} characters")
  103. # Display reference list
  104. if references:
  105. print(" 📚 Reference List:")
  106. for i, ref in enumerate(references, 1):
  107. ref_id = ref.get("reference_id", "Unknown")
  108. file_path = ref.get("file_path", "Unknown")
  109. print(f" {i}. ID: {ref_id} | File: {file_path}")
  110. else:
  111. print(f"❌ Request failed: {response.status_code}")
  112. print(f" Error: {response.text}")
  113. return False
  114. except Exception as e:
  115. print(f"❌ Test 1 failed: {str(e)}")
  116. return False
  117. # Test 2: References disabled
  118. print("\n🧪 Test 2: References disabled")
  119. print("-" * 40)
  120. try:
  121. response = requests.post(
  122. endpoint,
  123. json={"query": query_text, "mode": "mix", "include_references": False},
  124. headers=AUTH_HEADERS,
  125. timeout=30,
  126. )
  127. if response.status_code == 200:
  128. data = response.json()
  129. # Check response structure
  130. if "response" not in data:
  131. print("❌ Missing 'response' field")
  132. return False
  133. references = data.get("references")
  134. if references is not None:
  135. print("❌ References should be None when include_references=False")
  136. return False
  137. print("✅ References disabled: No references field present")
  138. print(f" Response length: {len(data['response'])} characters")
  139. else:
  140. print(f"❌ Request failed: {response.status_code}")
  141. print(f" Error: {response.text}")
  142. return False
  143. except Exception as e:
  144. print(f"❌ Test 2 failed: {str(e)}")
  145. return False
  146. print("\n✅ /query endpoint references tests passed!")
  147. return True
  148. @pytest.mark.integration
  149. @pytest.mark.requires_api
  150. def test_query_stream_endpoint_references():
  151. """Test /query/stream endpoint references functionality"""
  152. print("\n" + "=" * 60)
  153. print("Testing /query/stream endpoint references functionality")
  154. print("=" * 60)
  155. query_text = "who authored LightRAG"
  156. endpoint = f"{BASE_URL}/query/stream"
  157. # Test 1: Streaming with references enabled
  158. print("\n🧪 Test 1: Streaming with references enabled")
  159. print("-" * 40)
  160. try:
  161. response = requests.post(
  162. endpoint,
  163. json={"query": query_text, "mode": "mix", "include_references": True},
  164. headers=AUTH_HEADERS,
  165. timeout=30,
  166. stream=True,
  167. )
  168. if response.status_code == 200:
  169. # Collect streaming response
  170. full_response = ""
  171. for chunk in response.iter_content(chunk_size=1024, decode_unicode=True):
  172. if chunk:
  173. # Ensure chunk is string type
  174. if isinstance(chunk, bytes):
  175. chunk = chunk.decode("utf-8")
  176. full_response += chunk
  177. # Parse streaming response
  178. references, response_chunks, errors = parse_streaming_response(
  179. full_response
  180. )
  181. if errors:
  182. print(f"❌ Errors in streaming response: {errors}")
  183. return False
  184. if references is None:
  185. print("❌ No references found in streaming response")
  186. return False
  187. if not validate_references_format(references):
  188. return False
  189. if not response_chunks:
  190. print("❌ No response chunks found in streaming response")
  191. return False
  192. print(f"✅ Streaming with references: Found {len(references)} references")
  193. print(f" Response chunks: {len(response_chunks)}")
  194. print(
  195. f" Total response length: {sum(len(chunk) for chunk in response_chunks)} characters"
  196. )
  197. # Display reference list
  198. if references:
  199. print(" 📚 Reference List:")
  200. for i, ref in enumerate(references, 1):
  201. ref_id = ref.get("reference_id", "Unknown")
  202. file_path = ref.get("file_path", "Unknown")
  203. print(f" {i}. ID: {ref_id} | File: {file_path}")
  204. else:
  205. print(f"❌ Request failed: {response.status_code}")
  206. print(f" Error: {response.text}")
  207. return False
  208. except Exception as e:
  209. print(f"❌ Test 1 failed: {str(e)}")
  210. return False
  211. # Test 2: Streaming with references disabled
  212. print("\n🧪 Test 2: Streaming with references disabled")
  213. print("-" * 40)
  214. try:
  215. response = requests.post(
  216. endpoint,
  217. json={"query": query_text, "mode": "mix", "include_references": False},
  218. headers=AUTH_HEADERS,
  219. timeout=30,
  220. stream=True,
  221. )
  222. if response.status_code == 200:
  223. # Collect streaming response
  224. full_response = ""
  225. for chunk in response.iter_content(chunk_size=1024, decode_unicode=True):
  226. if chunk:
  227. # Ensure chunk is string type
  228. if isinstance(chunk, bytes):
  229. chunk = chunk.decode("utf-8")
  230. full_response += chunk
  231. # Parse streaming response
  232. references, response_chunks, errors = parse_streaming_response(
  233. full_response
  234. )
  235. if errors:
  236. print(f"❌ Errors in streaming response: {errors}")
  237. return False
  238. if references is not None:
  239. print("❌ References should be None when include_references=False")
  240. return False
  241. if not response_chunks:
  242. print("❌ No response chunks found in streaming response")
  243. return False
  244. print("✅ Streaming without references: No references present")
  245. print(f" Response chunks: {len(response_chunks)}")
  246. print(
  247. f" Total response length: {sum(len(chunk) for chunk in response_chunks)} characters"
  248. )
  249. else:
  250. print(f"❌ Request failed: {response.status_code}")
  251. print(f" Error: {response.text}")
  252. return False
  253. except Exception as e:
  254. print(f"❌ Test 2 failed: {str(e)}")
  255. return False
  256. print("\n✅ /query/stream endpoint references tests passed!")
  257. return True
  258. @pytest.mark.integration
  259. @pytest.mark.requires_api
  260. def test_references_consistency():
  261. """Test references consistency across all endpoints"""
  262. print("\n" + "=" * 60)
  263. print("Testing references consistency across endpoints")
  264. print("=" * 60)
  265. query_text = "who authored LightRAG"
  266. query_params = {
  267. "query": query_text,
  268. "mode": "mix",
  269. "top_k": 10,
  270. "chunk_top_k": 8,
  271. "include_references": True,
  272. }
  273. references_data = {}
  274. # Test /query endpoint
  275. print("\n🧪 Testing /query endpoint")
  276. print("-" * 40)
  277. try:
  278. response = requests.post(
  279. f"{BASE_URL}/query", json=query_params, headers=AUTH_HEADERS, timeout=30
  280. )
  281. if response.status_code == 200:
  282. data = response.json()
  283. references_data["query"] = data.get("references", [])
  284. print(f"✅ /query: {len(references_data['query'])} references")
  285. else:
  286. print(f"❌ /query failed: {response.status_code}")
  287. return False
  288. except Exception as e:
  289. print(f"❌ /query test failed: {str(e)}")
  290. return False
  291. # Test /query/stream endpoint
  292. print("\n🧪 Testing /query/stream endpoint")
  293. print("-" * 40)
  294. try:
  295. response = requests.post(
  296. f"{BASE_URL}/query/stream",
  297. json=query_params,
  298. headers=AUTH_HEADERS,
  299. timeout=30,
  300. stream=True,
  301. )
  302. if response.status_code == 200:
  303. full_response = ""
  304. for chunk in response.iter_content(chunk_size=1024, decode_unicode=True):
  305. if chunk:
  306. # Ensure chunk is string type
  307. if isinstance(chunk, bytes):
  308. chunk = chunk.decode("utf-8")
  309. full_response += chunk
  310. references, _, errors = parse_streaming_response(full_response)
  311. if errors:
  312. print(f"❌ Errors: {errors}")
  313. return False
  314. references_data["stream"] = references or []
  315. print(f"✅ /query/stream: {len(references_data['stream'])} references")
  316. else:
  317. print(f"❌ /query/stream failed: {response.status_code}")
  318. return False
  319. except Exception as e:
  320. print(f"❌ /query/stream test failed: {str(e)}")
  321. return False
  322. # Test /query/data endpoint
  323. print("\n🧪 Testing /query/data endpoint")
  324. print("-" * 40)
  325. try:
  326. response = requests.post(
  327. f"{BASE_URL}/query/data",
  328. json=query_params,
  329. headers=AUTH_HEADERS,
  330. timeout=30,
  331. )
  332. if response.status_code == 200:
  333. data = response.json()
  334. query_data = data.get("data", {})
  335. references_data["data"] = query_data.get("references", [])
  336. print(f"✅ /query/data: {len(references_data['data'])} references")
  337. else:
  338. print(f"❌ /query/data failed: {response.status_code}")
  339. return False
  340. except Exception as e:
  341. print(f"❌ /query/data test failed: {str(e)}")
  342. return False
  343. # Compare references consistency
  344. print("\n🔍 Comparing references consistency")
  345. print("-" * 40)
  346. # Convert to sets of (reference_id, file_path) tuples for comparison
  347. def refs_to_set(refs):
  348. return set(
  349. (ref.get("reference_id", ""), ref.get("file_path", "")) for ref in refs
  350. )
  351. query_refs = refs_to_set(references_data["query"])
  352. stream_refs = refs_to_set(references_data["stream"])
  353. data_refs = refs_to_set(references_data["data"])
  354. # Check consistency
  355. consistency_passed = True
  356. if query_refs != stream_refs:
  357. print("❌ References mismatch between /query and /query/stream")
  358. print(f" /query only: {query_refs - stream_refs}")
  359. print(f" /query/stream only: {stream_refs - query_refs}")
  360. consistency_passed = False
  361. if query_refs != data_refs:
  362. print("❌ References mismatch between /query and /query/data")
  363. print(f" /query only: {query_refs - data_refs}")
  364. print(f" /query/data only: {data_refs - query_refs}")
  365. consistency_passed = False
  366. if stream_refs != data_refs:
  367. print("❌ References mismatch between /query/stream and /query/data")
  368. print(f" /query/stream only: {stream_refs - data_refs}")
  369. print(f" /query/data only: {data_refs - stream_refs}")
  370. consistency_passed = False
  371. if consistency_passed:
  372. print("✅ All endpoints return consistent references")
  373. print(f" Common references count: {len(query_refs)}")
  374. # Display common reference list
  375. if query_refs:
  376. print(" 📚 Common Reference List:")
  377. for i, (ref_id, file_path) in enumerate(sorted(query_refs), 1):
  378. print(f" {i}. ID: {ref_id} | File: {file_path}")
  379. return consistency_passed
  380. @pytest.mark.integration
  381. @pytest.mark.requires_api
  382. def test_aquery_data_endpoint():
  383. """Test the /query/data endpoint"""
  384. # Use unified configuration
  385. endpoint = f"{BASE_URL}/query/data"
  386. # Query request
  387. query_request = {
  388. "query": "who authored LighRAG",
  389. "mode": "mix", # Use mixed mode to get the most comprehensive results
  390. "top_k": 20,
  391. "chunk_top_k": 15,
  392. "max_entity_tokens": 4000,
  393. "max_relation_tokens": 4000,
  394. "max_total_tokens": 16000,
  395. "enable_rerank": True,
  396. }
  397. print("=" * 60)
  398. print("LightRAG aquery_data endpoint test")
  399. print(
  400. " Returns structured data including entities, relationships and text chunks"
  401. )
  402. print(" Can be used for custom processing and analysis")
  403. print("=" * 60)
  404. print(f"Query content: {query_request['query']}")
  405. print(f"Query mode: {query_request['mode']}")
  406. print(f"API endpoint: {endpoint}")
  407. print("-" * 60)
  408. try:
  409. # Send request
  410. print("Sending request...")
  411. start_time = time.time()
  412. response = requests.post(
  413. endpoint, json=query_request, headers=AUTH_HEADERS, timeout=30
  414. )
  415. end_time = time.time()
  416. response_time = end_time - start_time
  417. print(f"Response time: {response_time:.2f} seconds")
  418. print(f"HTTP status code: {response.status_code}")
  419. if response.status_code == 200:
  420. data = response.json()
  421. print_query_results(data)
  422. else:
  423. print(f"Request failed: {response.status_code}")
  424. print(f"Error message: {response.text}")
  425. except requests.exceptions.ConnectionError:
  426. print("❌ Connection failed: Please ensure LightRAG API service is running")
  427. print(" Start command: python -m lightrag.api.lightrag_server")
  428. except requests.exceptions.Timeout:
  429. print("❌ Request timeout: Query processing took too long")
  430. except Exception as e:
  431. print(f"❌ Error occurred: {str(e)}")
  432. def print_query_results(data: Dict[str, Any]):
  433. """Format and print query results"""
  434. # Check for new data format with status and message
  435. status = data.get("status", "unknown")
  436. message = data.get("message", "")
  437. print(f"\n📋 Query Status: {status}")
  438. if message:
  439. print(f"📋 Message: {message}")
  440. # Handle new nested data format
  441. query_data = data.get("data", {})
  442. # Fallback to old format if new format is not present
  443. if not query_data and any(
  444. key in data for key in ["entities", "relationships", "chunks"]
  445. ):
  446. print(" (Using legacy data format)")
  447. query_data = data
  448. entities = query_data.get("entities", [])
  449. relationships = query_data.get("relationships", [])
  450. chunks = query_data.get("chunks", [])
  451. references = query_data.get("references", [])
  452. print("\n📊 Query result statistics:")
  453. print(f" Entity count: {len(entities)}")
  454. print(f" Relationship count: {len(relationships)}")
  455. print(f" Text chunk count: {len(chunks)}")
  456. print(f" Reference count: {len(references)}")
  457. # Print metadata (now at top level in new format)
  458. metadata = data.get("metadata", {})
  459. if metadata:
  460. print("\n🔍 Query metadata:")
  461. print(f" Query mode: {metadata.get('query_mode', 'unknown')}")
  462. keywords = metadata.get("keywords", {})
  463. if keywords:
  464. high_level = keywords.get("high_level", [])
  465. low_level = keywords.get("low_level", [])
  466. if high_level:
  467. print(f" High-level keywords: {', '.join(high_level)}")
  468. if low_level:
  469. print(f" Low-level keywords: {', '.join(low_level)}")
  470. processing_info = metadata.get("processing_info", {})
  471. if processing_info:
  472. print(" Processing info:")
  473. for key, value in processing_info.items():
  474. print(f" {key}: {value}")
  475. # Print entity information
  476. if entities:
  477. print("\n👥 Retrieved entities (first 5):")
  478. for i, entity in enumerate(entities[:5]):
  479. entity_name = entity.get("entity_name", "Unknown")
  480. entity_type = entity.get("entity_type", "Unknown")
  481. description = entity.get("description", "No description")
  482. file_path = entity.get("file_path", "Unknown source")
  483. reference_id = entity.get("reference_id", "No reference")
  484. print(f" {i + 1}. {entity_name} ({entity_type})")
  485. print(
  486. f" Description: {description[:100]}{'...' if len(description) > 100 else ''}"
  487. )
  488. print(f" Source: {file_path}")
  489. print(f" Reference ID: {reference_id}")
  490. print()
  491. # Print relationship information
  492. if relationships:
  493. print("🔗 Retrieved relationships (first 5):")
  494. for i, rel in enumerate(relationships[:5]):
  495. src = rel.get("src_id", "Unknown")
  496. tgt = rel.get("tgt_id", "Unknown")
  497. description = rel.get("description", "No description")
  498. keywords = rel.get("keywords", "No keywords")
  499. file_path = rel.get("file_path", "Unknown source")
  500. reference_id = rel.get("reference_id", "No reference")
  501. print(f" {i + 1}. {src} → {tgt}")
  502. print(f" Keywords: {keywords}")
  503. print(
  504. f" Description: {description[:100]}{'...' if len(description) > 100 else ''}"
  505. )
  506. print(f" Source: {file_path}")
  507. print(f" Reference ID: {reference_id}")
  508. print()
  509. # Print text chunk information
  510. if chunks:
  511. print("📄 Retrieved text chunks (first 3):")
  512. for i, chunk in enumerate(chunks[:3]):
  513. content = chunk.get("content", "No content")
  514. file_path = chunk.get("file_path", "Unknown source")
  515. chunk_id = chunk.get("chunk_id", "Unknown ID")
  516. reference_id = chunk.get("reference_id", "No reference")
  517. print(f" {i + 1}. Text chunk ID: {chunk_id}")
  518. print(f" Source: {file_path}")
  519. print(f" Reference ID: {reference_id}")
  520. print(
  521. f" Content: {content[:200]}{'...' if len(content) > 200 else ''}"
  522. )
  523. print()
  524. # Print references information (new in updated format)
  525. if references:
  526. print("📚 References:")
  527. for i, ref in enumerate(references):
  528. reference_id = ref.get("reference_id", "Unknown ID")
  529. file_path = ref.get("file_path", "Unknown source")
  530. print(f" {i + 1}. Reference ID: {reference_id}")
  531. print(f" File Path: {file_path}")
  532. print()
  533. print("=" * 60)
  534. @pytest.mark.integration
  535. @pytest.mark.requires_api
  536. def compare_with_regular_query():
  537. """Compare results between regular query and data query"""
  538. query_text = "LightRAG的作者是谁"
  539. print("\n🔄 Comparison test: Regular query vs Data query")
  540. print("-" * 60)
  541. # Regular query
  542. try:
  543. print("1. Regular query (/query):")
  544. regular_response = requests.post(
  545. f"{BASE_URL}/query",
  546. json={"query": query_text, "mode": "mix"},
  547. headers=AUTH_HEADERS,
  548. timeout=30,
  549. )
  550. if regular_response.status_code == 200:
  551. regular_data = regular_response.json()
  552. response_text = regular_data.get("response", "No response")
  553. print(
  554. f" Generated answer: {response_text[:300]}{'...' if len(response_text) > 300 else ''}"
  555. )
  556. else:
  557. print(f" Regular query failed: {regular_response.status_code}")
  558. if regular_response.status_code == 403:
  559. print(" Authentication failed - Please check API Key configuration")
  560. elif regular_response.status_code == 401:
  561. print(" Unauthorized - Please check authentication information")
  562. print(f" Error details: {regular_response.text}")
  563. except Exception as e:
  564. print(f" Regular query error: {str(e)}")
  565. @pytest.mark.integration
  566. @pytest.mark.requires_api
  567. def run_all_reference_tests():
  568. """Run all reference-related tests"""
  569. print("\n" + "🚀" * 20)
  570. print("LightRAG References Test Suite")
  571. print("🚀" * 20)
  572. all_tests_passed = True
  573. # Test 1: /query endpoint references
  574. try:
  575. if not test_query_endpoint_references():
  576. all_tests_passed = False
  577. except Exception as e:
  578. print(f"❌ /query endpoint test failed with exception: {str(e)}")
  579. all_tests_passed = False
  580. # Test 2: /query/stream endpoint references
  581. try:
  582. if not test_query_stream_endpoint_references():
  583. all_tests_passed = False
  584. except Exception as e:
  585. print(f"❌ /query/stream endpoint test failed with exception: {str(e)}")
  586. all_tests_passed = False
  587. # Test 3: References consistency across endpoints
  588. try:
  589. if not test_references_consistency():
  590. all_tests_passed = False
  591. except Exception as e:
  592. print(f"❌ References consistency test failed with exception: {str(e)}")
  593. all_tests_passed = False
  594. # Final summary
  595. print("\n" + "=" * 60)
  596. print("TEST SUITE SUMMARY")
  597. print("=" * 60)
  598. if all_tests_passed:
  599. print("🎉 ALL TESTS PASSED!")
  600. print("✅ /query endpoint references functionality works correctly")
  601. print("✅ /query/stream endpoint references functionality works correctly")
  602. print("✅ References are consistent across all endpoints")
  603. print("\n🔧 System is ready for production use with reference support!")
  604. else:
  605. print("❌ SOME TESTS FAILED!")
  606. print("Please check the error messages above and fix the issues.")
  607. print("\n🔧 System needs attention before production deployment.")
  608. return all_tests_passed
  609. if __name__ == "__main__":
  610. import sys
  611. if len(sys.argv) > 1 and sys.argv[1] == "--references-only":
  612. # Run only the new reference tests
  613. success = run_all_reference_tests()
  614. sys.exit(0 if success else 1)
  615. else:
  616. # Run original tests plus new reference tests
  617. print("Running original aquery_data endpoint test...")
  618. test_aquery_data_endpoint()
  619. print("\nRunning comparison test...")
  620. compare_with_regular_query()
  621. print("\nRunning new reference tests...")
  622. run_all_reference_tests()
  623. print("\n💡 Usage tips:")
  624. print("1. Ensure LightRAG API service is running")
  625. print("2. Adjust base_url and authentication information as needed")
  626. print("3. Modify query parameters to test different retrieval strategies")
  627. print("4. Data query results can be used for further analysis and processing")
  628. print("5. Run with --references-only flag to test only reference functionality")