davidtran999 commited on
Commit
13340b6
·
verified ·
1 Parent(s): e584168

Upload backend/test_api_mode.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. backend/test_api_mode.py +138 -0
backend/test_api_mode.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Test script để kiểm tra API mode có hoạt động không.
4
+ """
5
+ import os
6
+ import sys
7
+
8
+ # Set API mode
9
+ os.environ["LLM_PROVIDER"] = "api"
10
+ os.environ["HF_API_BASE_URL"] = "https://davidtran999-hue-portal-backend.hf.space/api"
11
+
12
+ # Add project to path
13
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
14
+
15
+ def test_api_mode():
16
+ """Test API mode initialization and connection."""
17
+ print("=" * 60)
18
+ print("Testing API Mode")
19
+ print("=" * 60)
20
+
21
+ try:
22
+ # Import và clear global instance
23
+ import hue_portal.chatbot.llm_integration as llm_module
24
+ llm_module._llm_generator = None
25
+
26
+ from hue_portal.chatbot.llm_integration import LLMGenerator, LLM_PROVIDER_API, get_llm_generator
27
+
28
+ print("\n1. Testing LLMGenerator initialization...")
29
+ generator = LLMGenerator(provider=LLM_PROVIDER_API)
30
+
31
+ if generator.provider == LLM_PROVIDER_API:
32
+ print("✅ Provider set correctly: API")
33
+ else:
34
+ print(f"❌ Provider incorrect: {generator.provider}")
35
+ return False
36
+
37
+ if generator.api_base_url:
38
+ print(f"✅ API base URL: {generator.api_base_url}")
39
+ else:
40
+ print("❌ API base URL not set")
41
+ return False
42
+
43
+ print("\n2. Testing is_available()...")
44
+ available = generator.is_available()
45
+ if available:
46
+ print("✅ API mode is available")
47
+ else:
48
+ print("❌ API mode not available")
49
+ return False
50
+
51
+ print("\n3. Testing get_llm_generator()...")
52
+ llm = get_llm_generator()
53
+ if llm and llm.provider == LLM_PROVIDER_API:
54
+ print("✅ get_llm_generator() returns API generator")
55
+ else:
56
+ print("❌ get_llm_generator() failed")
57
+ return False
58
+
59
+ print("\n4. Testing API connection (sending test request)...")
60
+ try:
61
+ import requests
62
+
63
+ # Test API endpoint
64
+ test_url = f"{generator.api_base_url}/chatbot/chat/"
65
+ test_payload = {
66
+ "message": "Xin chào",
67
+ "reset_session": False
68
+ }
69
+
70
+ print(f" Calling: {test_url}")
71
+ print(f" Payload: {test_payload}")
72
+
73
+ response = requests.post(
74
+ test_url,
75
+ json=test_payload,
76
+ headers={"Content-Type": "application/json"},
77
+ timeout=10
78
+ )
79
+
80
+ print(f" Status Code: {response.status_code}")
81
+
82
+ if response.status_code == 200:
83
+ result = response.json()
84
+ print("✅ API connection successful!")
85
+ print(f" Response keys: {list(result.keys())}")
86
+ if "message" in result:
87
+ print(f" Message preview: {result['message'][:100]}...")
88
+ return True
89
+ elif response.status_code == 503:
90
+ print("⚠️ API endpoint is loading (503) - this is normal for first request")
91
+ print(" The API is available but model is still loading")
92
+ return True
93
+ else:
94
+ print(f"❌ API connection failed: {response.status_code}")
95
+ print(f" Response: {response.text[:200]}")
96
+ return False
97
+
98
+ except requests.exceptions.Timeout:
99
+ print("❌ API connection timeout")
100
+ return False
101
+ except requests.exceptions.ConnectionError as e:
102
+ print(f"❌ API connection error: {e}")
103
+ print(" Check if the API URL is correct and accessible")
104
+ return False
105
+ except Exception as e:
106
+ print(f"❌ Error testing API connection: {e}")
107
+ import traceback
108
+ traceback.print_exc()
109
+ return False
110
+
111
+ except Exception as e:
112
+ print(f"❌ Test failed: {e}")
113
+ import traceback
114
+ traceback.print_exc()
115
+ return False
116
+
117
+ def main():
118
+ """Main function."""
119
+ success = test_api_mode()
120
+
121
+ print("\n" + "=" * 60)
122
+ if success:
123
+ print("✅ API Mode Test: PASSED")
124
+ print("\n💡 Project is ready to use API mode!")
125
+ print(" Just restart your Django server to apply changes.")
126
+ else:
127
+ print("❌ API Mode Test: FAILED")
128
+ print("\n⚠️ Please check:")
129
+ print(" 1. API URL is correct")
130
+ print(" 2. Hugging Face Space is running")
131
+ print(" 3. Internet connection is available")
132
+ print("=" * 60)
133
+
134
+ return 0 if success else 1
135
+
136
+ if __name__ == "__main__":
137
+ sys.exit(main())
138
+