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+
Script để test chatbot API endpoint.
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import requests
|
| 7 |
+
import json
|
| 8 |
+
import time
|
| 9 |
+
from typing import Dict, Any
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
API_BASE_URL = os.environ.get("API_BASE_URL", "http://localhost:8000").rstrip("/")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_health_endpoint():
|
| 16 |
+
"""Test health endpoint."""
|
| 17 |
+
print("="*60)
|
| 18 |
+
print("Test Health Endpoint")
|
| 19 |
+
print("="*60)
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
response = requests.get(f"{API_BASE_URL}/api/chatbot/health/", timeout=5)
|
| 23 |
+
print(f"Status Code: {response.status_code}")
|
| 24 |
+
if response.status_code == 200:
|
| 25 |
+
data = response.json()
|
| 26 |
+
print(f"Status: {data.get('status', 'N/A')}")
|
| 27 |
+
print(f"Service: {data.get('service', 'N/A')}")
|
| 28 |
+
print(f"Classifier Loaded: {data.get('classifier_loaded', False)}")
|
| 29 |
+
return True
|
| 30 |
+
else:
|
| 31 |
+
print(f"Error: {response.text}")
|
| 32 |
+
return False
|
| 33 |
+
except requests.exceptions.ConnectionError:
|
| 34 |
+
print("❌ Cannot connect to server. Is Django server running?")
|
| 35 |
+
print(" Start server with: cd backend/hue_portal && POSTGRES_HOST=localhost POSTGRES_PORT=5433 python manage.py runserver")
|
| 36 |
+
return False
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"❌ Error: {e}")
|
| 39 |
+
return False
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_chatbot_api(query: str, expected_intent: str = None) -> Dict[str, Any]:
|
| 43 |
+
"""Test chatbot API with a query."""
|
| 44 |
+
print(f"\n📝 Query: {query}")
|
| 45 |
+
|
| 46 |
+
start_time = time.time()
|
| 47 |
+
try:
|
| 48 |
+
response = requests.post(
|
| 49 |
+
f"{API_BASE_URL}/api/chat/",
|
| 50 |
+
json={"message": query},
|
| 51 |
+
headers={"Content-Type": "application/json"},
|
| 52 |
+
timeout=30
|
| 53 |
+
)
|
| 54 |
+
latency_ms = (time.time() - start_time) * 1000
|
| 55 |
+
|
| 56 |
+
print(f" Status Code: {response.status_code}")
|
| 57 |
+
|
| 58 |
+
if response.status_code == 200:
|
| 59 |
+
data = response.json()
|
| 60 |
+
intent = data.get('intent', 'N/A')
|
| 61 |
+
confidence = data.get('confidence', 0)
|
| 62 |
+
count = data.get('count', 0)
|
| 63 |
+
message_preview = data.get('message', '')[:100]
|
| 64 |
+
|
| 65 |
+
print(f" ✅ Intent: {intent}")
|
| 66 |
+
print(f" ✅ Confidence: {confidence:.4f}")
|
| 67 |
+
print(f" ✅ Results: {count}")
|
| 68 |
+
print(f" ✅ Latency: {latency_ms:.2f}ms")
|
| 69 |
+
print(f" ✅ Message preview: {message_preview}...")
|
| 70 |
+
|
| 71 |
+
if expected_intent and intent != expected_intent:
|
| 72 |
+
print(f" ⚠️ Expected intent: {expected_intent}, got: {intent}")
|
| 73 |
+
|
| 74 |
+
return {
|
| 75 |
+
"success": True,
|
| 76 |
+
"intent": intent,
|
| 77 |
+
"confidence": confidence,
|
| 78 |
+
"count": count,
|
| 79 |
+
"latency_ms": latency_ms
|
| 80 |
+
}
|
| 81 |
+
else:
|
| 82 |
+
print(f" ❌ Error: {response.text}")
|
| 83 |
+
return {"success": False, "error": response.text}
|
| 84 |
+
|
| 85 |
+
except requests.exceptions.ConnectionError:
|
| 86 |
+
print(" ❌ Cannot connect to server")
|
| 87 |
+
return {"success": False, "error": "Connection error"}
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f" ❌ Error: {e}")
|
| 90 |
+
return {"success": False, "error": str(e)}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def main():
|
| 94 |
+
print("="*60)
|
| 95 |
+
print("Chatbot API Endpoint Test")
|
| 96 |
+
print("="*60)
|
| 97 |
+
|
| 98 |
+
# Test health endpoint first
|
| 99 |
+
if not test_health_endpoint():
|
| 100 |
+
print("\n⚠️ Health check failed. Please start Django server first.")
|
| 101 |
+
return
|
| 102 |
+
|
| 103 |
+
# Test chatbot API with various queries
|
| 104 |
+
print("\n" + "="*60)
|
| 105 |
+
print("Test Chatbot API Endpoint")
|
| 106 |
+
print("="*60)
|
| 107 |
+
|
| 108 |
+
test_cases = [
|
| 109 |
+
("Làm thủ tục cư trú cần gì?", "search_procedure"),
|
| 110 |
+
("Cảnh báo lừa đảo giả danh công an", "search_advisory"),
|
| 111 |
+
("Thủ tục PCCC như thế nào?", "search_procedure"),
|
| 112 |
+
("Mức phạt vượt đèn đỏ", "search_fine"),
|
| 113 |
+
("Địa chỉ công an tỉnh", "search_office"),
|
| 114 |
+
("Lừa đảo mạo danh cán bộ", "search_advisory"),
|
| 115 |
+
]
|
| 116 |
+
|
| 117 |
+
results = []
|
| 118 |
+
for query, expected_intent in test_cases:
|
| 119 |
+
result = test_chatbot_api(query, expected_intent)
|
| 120 |
+
results.append(result)
|
| 121 |
+
time.sleep(0.5) # Small delay between requests
|
| 122 |
+
|
| 123 |
+
# Summary
|
| 124 |
+
print("\n" + "="*60)
|
| 125 |
+
print("Test Summary")
|
| 126 |
+
print("="*60)
|
| 127 |
+
|
| 128 |
+
successful = sum(1 for r in results if r.get("success", False))
|
| 129 |
+
total = len(results)
|
| 130 |
+
avg_latency = sum(r.get("latency_ms", 0) for r in results if r.get("success", False)) / successful if successful > 0 else 0
|
| 131 |
+
|
| 132 |
+
print(f"Successful: {successful}/{total}")
|
| 133 |
+
print(f"Average Latency: {avg_latency:.2f}ms")
|
| 134 |
+
|
| 135 |
+
# Intent accuracy
|
| 136 |
+
correct_intents = sum(1 for i, (_, expected) in enumerate(test_cases)
|
| 137 |
+
if results[i].get("intent") == expected)
|
| 138 |
+
print(f"Intent Accuracy: {correct_intents}/{total} ({correct_intents/total*100:.1f}%)")
|
| 139 |
+
|
| 140 |
+
print("\n" + "="*60)
|
| 141 |
+
print("Test Complete")
|
| 142 |
+
print("="*60)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
if __name__ == "__main__":
|
| 146 |
+
main()
|
| 147 |
+
|