-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
263 lines (224 loc) · 9.8 KB
/
main.py
File metadata and controls
263 lines (224 loc) · 9.8 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
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import requests
import json
import os
app = Flask(__name__)
CORS(app)
@app.route('/')
def index():
return jsonify({
'status': 'HKBU Student Chatbot API is running!',
'endpoints': [
'/api/chat',
'/api/test',
'/aitutor/bots/basicBot.html',
'/aitutor/bots/videoHelper.html',
'/frontend'
]
})
@app.route('/api/chat', methods=['POST', 'OPTIONS'])
def chat():
if request.method == 'OPTIONS':
response = jsonify({'status': 'OK'})
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS')
return response
try:
data = request.json
if data is None:
return jsonify({'error': 'No JSON data provided'}), 400
user_message = data.get('message', '')
api_key = data.get('apiKey', '')
provider = data.get('provider', 'hkbu')
model = data.get('model', 'gpt-4.1')
system_prompt = data.get('systemPrompt', '')
if not api_key:
return jsonify({'error': 'No API key provided'}), 400
if not user_message:
return jsonify({'error': 'No message provided'}), 400
if provider == 'hkbu':
response_text = call_hkbu_api(user_message, api_key, model, system_prompt)
elif provider == 'openrouter':
response_text = call_openrouter_api(user_message, api_key, model, system_prompt)
else:
return jsonify({'error': 'Unsupported provider'}), 400
return jsonify({
'response': response_text
})
except Exception as e:
return jsonify({
'error': str(e)
}), 400
@app.route('/api/test', methods=['POST'])
def test_connection():
try:
data = request.json
if data is None:
return jsonify({'error': 'No JSON data provided'}), 400
api_key = data.get('apiKey', '')
provider = data.get('provider', 'hkbu')
model = data.get('model', 'gpt-4.1')
if not api_key:
return jsonify({'error': 'No API key provided'}), 400
if provider == 'hkbu':
response = call_hkbu_api('Hello, this is a test.', api_key, model, 'You are a helpful assistant.')
elif provider == 'openrouter':
response = call_openrouter_api('Hello, this is a test.', api_key, model, 'You are a helpful assistant.')
else:
return jsonify({'error': 'Unsupported provider'}), 400
return jsonify({
'response': f'Connection successful! Response: {response[:50]}...'
})
except Exception as e:
return jsonify({
'error': str(e)
}), 400
@app.route('/aitutor/prompts/<filename>')
def serve_aitutor_prompts(filename):
try:
# Try clean-aitutor-v2 first, then fallback to aitutor
for path in ['clean-aitutor-v2/prompts', 'aitutor/prompts', 'prompts']:
filepath = os.path.join(path, filename)
if os.path.exists(filepath):
with open(filepath, 'r', encoding='utf-8') as file:
content = file.read()
return jsonify({'content': content})
return jsonify({'error': f'Prompt file {filename} not found'}), 404
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/aitutor/bots/basicBot.html')
def serve_basic_bot():
# Try clean-aitutor-v2 first, then fallback to aitutor
for path in ['clean-aitutor-v2/bots/basicBot.html', 'aitutor/bots/basicBot.html', 'bots/basicBot.html']:
if os.path.exists(path):
return send_file(path)
return jsonify({'error': 'basicBot.html not found'}), 404
@app.route('/aitutor/bots/videoHelper.html')
def serve_video_helper():
# Try clean-aitutor-v2 first, then fallback to aitutor
for path in ['clean-aitutor-v2/bots/videoHelper.html', 'aitutor/bots/videoHelper.html', 'bots/videoHelper.html']:
if os.path.exists(path):
return send_file(path)
return jsonify({'error': 'videoHelper.html not found'}), 404
@app.route('/aitutor/bots/css/<filename>')
def serve_css(filename):
# Try clean-aitutor-v2 first, then fallback to aitutor
for path in [f'clean-aitutor-v2/bots/css/{filename}', f'aitutor/bots/css/{filename}', f'bots/css/{filename}']:
if os.path.exists(path):
return send_file(path)
return jsonify({'error': f'CSS file {filename} not found'}), 404
@app.route('/aitutor/bots/js/<filename>')
def serve_js(filename):
# Try clean-aitutor-v2 first, then fallback to aitutor
for path in [f'clean-aitutor-v2/bots/js/{filename}', f'aitutor/bots/js/{filename}', f'bots/js/{filename}']:
if os.path.exists(path):
return send_file(path)
return jsonify({'error': f'JS file {filename} not found'}), 404
@app.route('/frontend')
def serve_frontend():
# Try different locations for the frontend
for path in ['clean-aitutor-v2/index.html', 'aitutor/index.html', 'index.html']:
if os.path.exists(path):
return send_file(path)
return jsonify({'error': 'Frontend not found'}), 404
def call_hkbu_api(message, api_key, model, system_prompt):
"""Call HKBU GenAI API"""
base_url = "https://genai.hkbu.edu.hk/api/v0/rest"
api_version = "2024-12-01-preview"
url = f"{base_url}/deployments/{model}/chat/completions?api-version={api_version}"
messages = []
if system_prompt.strip():
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": message})
headers = {
"Content-Type": "application/json",
"api-key": api_key
}
payload = {
"messages": messages,
"max_tokens": 1000,
"temperature": 0.7,
"top_p": 0.9,
"stream": False
}
try:
print(f"HKBU API Request to: {url}")
response = requests.post(url, headers=headers, json=payload, timeout=30)
print(f"HKBU Response status: {response.status_code}")
if response.status_code == 200:
result = response.json()
if "choices" in result and len(result["choices"]) > 0:
return result["choices"][0]["message"]["content"]
else:
raise Exception("Invalid response format from HKBU API")
elif response.status_code == 401:
raise Exception("HKBU API: Invalid API key or access denied")
elif response.status_code == 404:
raise Exception(f"HKBU API: Model '{model}' not found")
else:
error_text = response.text
raise Exception(f"HKBU API Error {response.status_code}: {error_text}")
except requests.exceptions.Timeout:
raise Exception("HKBU API: Request timeout")
except requests.exceptions.RequestException as e:
raise Exception(f"HKBU API: Network error - {str(e)}")
def call_openrouter_api(message, api_key, model, system_prompt):
"""Call OpenRouter API"""
url = "https://openrouter.ai/api/v1/chat/completions"
messages = []
if system_prompt.strip():
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": message})
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
"HTTP-Referer": "https://smartlessons.hkbu.tech",
"X-Title": "HKBU Student Chatbot"
}
payload = {
"model": model,
"messages": messages,
"max_tokens": 1000,
"temperature": 0.7,
"top_p": 0.9
}
try:
print(f"OpenRouter API Request to: {url}")
response = requests.post(url, headers=headers, json=payload, timeout=30)
print(f"OpenRouter Response status: {response.status_code}")
if response.status_code == 200:
result = response.json()
if "choices" in result and len(result["choices"]) > 0:
return result["choices"][0]["message"]["content"]
else:
raise Exception("Invalid response format from OpenRouter API")
elif response.status_code == 401:
raise Exception("OpenRouter API: Invalid API key")
elif response.status_code == 402:
raise Exception("OpenRouter API: Insufficient credits")
else:
error_text = response.text
raise Exception(f"OpenRouter API Error {response.status_code}: {error_text}")
except requests.exceptions.Timeout:
raise Exception("OpenRouter API: Request timeout")
except requests.exceptions.RequestException as e:
raise Exception(f"OpenRouter API: Network error - {str(e)}")
if __name__ == '__main__':
print("🚀 Starting HKBU Student Chatbot Server...")
print("📝 Available endpoints:")
print(" GET / - API status")
print(" GET /frontend - Web interface")
print(" GET /aitutor/bots/basicBot.html - Basic chatbot")
print(" GET /aitutor/bots/videoHelper.html - Video helper bot")
print(" POST /api/chat - Chat with AI")
print(" POST /api/test - Test API connection")
print(" GET /aitutor/prompts/<filename> - Serve prompt files")
print("\n🔧 Make sure to:")
print(" 1. Install: pip install flask flask-cors requests")
print(" 2. Get HKBU API key: https://genai.hkbu.edu.hk/settings/api-docs")
print(" 3. Get OpenRouter key: https://openrouter.ai/keys")
# Use PORT environment variable for Railway deployment
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=False)