-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai_setup.py
More file actions
203 lines (168 loc) Β· 7.12 KB
/
ai_setup.py
File metadata and controls
203 lines (168 loc) Β· 7.12 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
# AI Configuration Setup Script
# Run this to configure AI features for your quiz app
import os
import sys
import json
from pathlib import Path
def setup_ai_config():
"""Interactive setup for AI configuration"""
print("π€ Quiz App AI Features Configuration")
print("=" * 50)
print()
config = {}
# OpenAI Configuration
print("π OpenAI Configuration:")
openai_key = input("Enter your OpenAI API key (or press Enter to skip): ").strip()
if openai_key:
config['OPENAI_API_KEY'] = openai_key
model = input("OpenAI model (default: gpt-3.5-turbo): ").strip() or "gpt-3.5-turbo"
config['OPENAI_MODEL'] = model
print()
# Anthropic Configuration
print("π Anthropic Configuration:")
anthropic_key = input("Enter your Anthropic API key (or press Enter to skip): ").strip()
if anthropic_key:
config['ANTHROPIC_API_KEY'] = anthropic_key
model = input("Anthropic model (default: claude-3-sonnet-20240229): ").strip() or "claude-3-sonnet-20240229"
config['ANTHROPIC_MODEL'] = model
print()
# Feature Configuration
print("βοΈ Feature Configuration:")
features = {
'ENABLE_QUESTION_GENERATION': input("Enable AI question generation? (y/N): ").lower().startswith('y'),
'ENABLE_PERSONALIZED_LEARNING': input("Enable personalized learning? (y/N): ").lower().startswith('y'),
'ENABLE_AI_EXPLANATIONS': input("Enable AI explanations? (y/N): ").lower().startswith('y'),
'CHATBOT_ENABLED': input("Enable AI chatbot? (y/N): ").lower().startswith('y'),
}
config.update({k: str(v).lower() for k, v in features.items()})
# Save to .env file
env_file = Path('.env')
existing_config = {}
# Read existing .env if it exists
if env_file.exists():
with open(env_file, 'r') as f:
for line in f:
if '=' in line and not line.startswith('#'):
key, value = line.strip().split('=', 1)
existing_config[key] = value
# Update with new config
existing_config.update(config)
# Write back to .env
with open(env_file, 'w') as f:
f.write("# Quiz App Configuration\n")
f.write("# Generated by AI setup script\n\n")
f.write("# Database Configuration\n")
if 'DATABASE_URL' in existing_config:
f.write(f"DATABASE_URL={existing_config['DATABASE_URL']}\n")
if 'POSTGRES_PASSWORD' in existing_config:
f.write(f"POSTGRES_PASSWORD={existing_config['POSTGRES_PASSWORD']}\n")
f.write("\n")
f.write("# AI Configuration\n")
for key, value in config.items():
f.write(f"{key}={value}\n")
f.write("\n")
# Add any other existing config
for key, value in existing_config.items():
if key not in config and not key.startswith(('DATABASE_URL', 'POSTGRES_PASSWORD')):
f.write(f"{key}={value}\n")
print()
print("β
Configuration saved to .env file")
print()
# Install dependencies if needed
if any(key.endswith('_API_KEY') for key in config.keys()):
print("π¦ Installing AI dependencies...")
install_deps = input("Install AI dependencies now? (Y/n): ").strip()
if not install_deps.lower().startswith('n'):
install_ai_dependencies()
print()
print("π AI configuration complete!")
print()
print("Next steps:")
print("1. Restart your application: ./dev.sh restart")
print("2. Check AI status: curl http://localhost:9080/api/ai/status")
print("3. Try the AI features in your quiz app!")
def install_ai_dependencies():
"""Install AI dependencies"""
try:
import subprocess
subprocess.run([sys.executable, '-m', 'pip', 'install', '-r', 'requirements-ai.txt'], check=True)
print("β
AI dependencies installed successfully")
except subprocess.CalledProcessError as e:
print(f"β Error installing dependencies: {e}")
print("You can install manually with: pip install -r requirements-ai.txt")
except Exception as e:
print(f"β Unexpected error: {e}")
def check_ai_status():
"""Check current AI configuration status"""
print("π Checking current AI configuration...")
try:
from ai_config import validate_ai_setup
status = validate_ai_setup()
print("\nπ AI Status:")
print(f"OpenAI Available: {'β
' if status['openai_available'] else 'β'}")
print(f"Anthropic Available: {'β
' if status['anthropic_available'] else 'β'}")
print(f"Overall Ready: {'β
' if status['ready'] else 'β'}")
print("\nβοΈ Feature Status:")
for feature, enabled in status['features_enabled'].items():
print(f"{feature.replace('_', ' ').title()}: {'β
' if enabled else 'β'}")
except ImportError:
print("β AI modules not available. Install dependencies first.")
except Exception as e:
print(f"β Error checking status: {e}")
def create_sample_questions():
"""Generate sample questions using AI"""
print("π§ͺ Generating sample questions...")
try:
import asyncio
from question_generator import generate_questions_for_category
async def generate_samples():
questions = await generate_questions_for_category(
category="general",
count=3,
difficulty="intermediate"
)
print("\nπ Sample Generated Questions:")
for i, q in enumerate(questions, 1):
print(f"\nQuestion {i}:")
print(f" Text: {q['text']}")
print(f" Choices: {q['choices']}")
print(f" Answer: {q['correct_answer']}")
print(f" Confidence: {q['confidence']:.1%}")
asyncio.run(generate_samples())
except ImportError:
print("β AI modules not available. Configure and install dependencies first.")
except Exception as e:
print(f"β Error generating questions: {e}")
def main():
"""Main CLI interface"""
if len(sys.argv) > 1:
command = sys.argv[1].lower()
if command == 'setup':
setup_ai_config()
elif command == 'status':
check_ai_status()
elif command == 'test':
create_sample_questions()
elif command == 'install':
install_ai_dependencies()
else:
print(f"Unknown command: {command}")
print_usage()
else:
print_usage()
def print_usage():
"""Print usage information"""
print("π€ AI Configuration Tool")
print("Usage: python ai_setup.py <command>")
print()
print("Commands:")
print(" setup - Interactive AI configuration")
print(" status - Check current AI status")
print(" test - Generate sample questions")
print(" install - Install AI dependencies")
print()
print("Examples:")
print(" python ai_setup.py setup")
print(" python ai_setup.py status")
if __name__ == '__main__':
main()