-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapp.py
150 lines (127 loc) · 4.66 KB
/
app.py
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
"""Main application module"""
import os
import logging
from flask import Flask, request, jsonify
from flask_cors import CORS
from src.experts import SportsExpert, FoodExpert, AIExpert, SudoStarExpert
from src.experts.selector import ExpertSelector
from src.utils.openai_client import init_openai
from config.config import EXPERT_CONFIG
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Initialize Flask app
app = Flask(__name__)
CORS(app)
# Initialize expert system
expert_system = {}
def init_app():
"""Initialize application
Returns:
bool: True if initialization successful, False otherwise
"""
try:
# Initialize OpenAI client
global openai_api_key
logger.info("Initializing OpenAI client...")
openai_api_key = init_openai()
if not openai_api_key:
logger.error("OpenAI API key not found")
return False
logger.info("OpenAI client initialized successfully")
# Initialize experts
global expert_system
logger.info("Initializing expert system...")
try:
expert_system = {
'sports': SportsExpert(config=EXPERT_CONFIG['sports']),
'food': FoodExpert(config=EXPERT_CONFIG['food']),
'ai': AIExpert(config=EXPERT_CONFIG['ai']),
'sudostar': SudoStarExpert(config=EXPERT_CONFIG['sudostar'])
}
logger.info("Experts initialized successfully")
except Exception as e:
logger.error(f"Error initializing experts: {str(e)}")
return False
# Initialize expert selector
try:
logger.info("Initializing expert selector...")
expert_system['selector'] = ExpertSelector()
logger.info("Expert selector initialized successfully")
except Exception as e:
logger.error(f"Error initializing expert selector: {str(e)}")
return False
logger.info("Expert system initialized successfully")
return True
except Exception as e:
logger.error(f"Error initializing application: {str(e)}")
return False
@app.route('/health')
def health():
is_initialized = init_app()
response = {
'status': 'healthy' if is_initialized else 'unhealthy',
'services': {
'api': 'running',
'openai_api': 'configured' if openai_api_key else 'missing',
'expert_system': 'running' if expert_system else 'error'
}
}
if not is_initialized:
response['error'] = 'System not properly initialized'
return jsonify(response), 200 if is_initialized else 503
@app.route('/', methods=['POST'])
@app.route('/ask', methods=['POST'])
async def ask():
if not init_app():
return jsonify({
'status': 'error',
'error': 'System not properly initialized',
'code': 'INIT_ERROR'
}), 503
try:
data = request.get_json()
if not data or 'question' not in data:
return jsonify({
'status': 'error',
'error': 'Question is required',
'code': 'MISSING_QUESTION'
}), 400
question = data['question']
logger.info(f"Received question: {question}")
# Select expert and get response
expert_type, direct_response = await expert_system['selector'].select_expert(question)
logger.info(f"Selected expert: {expert_type}")
response = None
if expert_type and expert_type in expert_system:
response = await expert_system[expert_type].get_response(question)
else:
response = direct_response
if not response:
return jsonify({
'status': 'error',
'error': 'Could not generate response',
'code': 'NO_RESPONSE'
}), 500
logger.info(f"Generated response for {expert_type} expert")
return jsonify({
'status': 'success',
'data': {
'answer': response,
'expert_type': expert_type or 'general'
}
})
except Exception as e:
logger.error(f"Error in /ask endpoint: {str(e)}")
return jsonify({
'status': 'error',
'error': str(e),
'code': 'INTERNAL_ERROR'
}), 500
if __name__ == '__main__':
port = int(os.environ.get('PORT', 8080)) # Railway uses port 8080
logger.info(f"Starting Flask app on port {port}")
app.run(host='0.0.0.0', port=port)