Upload 2 files
Browse files- app.py +797 -37
- config.json +18 -7
app.py
CHANGED
@@ -11,21 +11,21 @@ import urllib.parse
|
|
11 |
|
12 |
# Configuration
|
13 |
SPACE_NAME = 'AI Assistant'
|
14 |
-
SPACE_DESCRIPTION = 'A
|
15 |
|
16 |
# Default configuration values (used only if config.json is missing)
|
17 |
DEFAULT_CONFIG = {
|
18 |
'name': SPACE_NAME,
|
19 |
'description': SPACE_DESCRIPTION,
|
20 |
-
'system_prompt': "You are a Socratic conversation partner for general education courses across all disciplines,
|
21 |
-
'temperature': 0.
|
22 |
-
'max_tokens':
|
23 |
-
'model': '
|
24 |
'api_key_var': 'API_KEY',
|
25 |
'theme': 'Glass',
|
26 |
-
'grounding_urls': '[]',
|
27 |
'enable_dynamic_urls': True,
|
28 |
-
'examples': ['Can you help me understand why the sky is blue?'],
|
29 |
'locked': False
|
30 |
}
|
31 |
|
@@ -76,6 +76,118 @@ if API_KEY:
|
|
76 |
API_KEY = API_KEY.strip() # Remove any whitespace
|
77 |
if not API_KEY: # Check if empty after stripping
|
78 |
API_KEY = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
|
80 |
def get_grounding_context():
|
81 |
"""Fetch context from grounding URLs with caching"""
|
@@ -90,9 +202,29 @@ def get_grounding_context():
|
|
90 |
if not urls:
|
91 |
return ""
|
92 |
|
93 |
-
#
|
94 |
-
|
95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
|
97 |
def export_conversation_to_markdown(conversation_history):
|
98 |
"""Export conversation history to markdown format"""
|
@@ -117,33 +249,68 @@ Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
|
117 |
markdown_content += f"## User Message {message_pair_count}\n\n{content}\n\n"
|
118 |
elif role == 'assistant':
|
119 |
markdown_content += f"## Assistant Response {message_pair_count}\n\n{content}\n\n---\n\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
|
121 |
return markdown_content
|
122 |
|
|
|
123 |
def generate_response(message, history):
|
124 |
"""Generate response using OpenRouter API"""
|
125 |
|
126 |
# Enhanced API key validation with helpful messages
|
127 |
if not API_KEY:
|
128 |
error_msg = f"π **API Key Required**\n\n"
|
129 |
-
error_msg += f"Please configure your OpenRouter API key
|
130 |
error_msg += f"1. Go to Settings (βοΈ) in your HuggingFace Space\n"
|
131 |
error_msg += f"2. Click 'Variables and secrets'\n"
|
132 |
error_msg += f"3. Add secret: **{API_KEY_VAR}**\n"
|
133 |
error_msg += f"4. Value: Your OpenRouter API key (starts with `sk-or-`)\n\n"
|
134 |
error_msg += f"Get your API key at: https://openrouter.ai/keys"
|
|
|
135 |
return error_msg
|
136 |
|
137 |
# Get grounding context
|
138 |
grounding_context = get_grounding_context()
|
139 |
|
140 |
-
#
|
141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
|
143 |
# Build messages array for the API
|
144 |
messages = [{"role": "system", "content": enhanced_system_prompt}]
|
145 |
|
146 |
-
# Add conversation history
|
147 |
for chat in history:
|
148 |
if isinstance(chat, dict):
|
149 |
messages.append(chat)
|
@@ -154,8 +321,12 @@ def generate_response(message, history):
|
|
154 |
# Add current message
|
155 |
messages.append({"role": "user", "content": message})
|
156 |
|
157 |
-
# Make API request
|
158 |
try:
|
|
|
|
|
|
|
|
|
159 |
response = requests.post(
|
160 |
url="https://openrouter.ai/api/v1/chat/completions",
|
161 |
headers={
|
@@ -173,36 +344,625 @@ def generate_response(message, history):
|
|
173 |
timeout=30
|
174 |
)
|
175 |
|
|
|
|
|
176 |
if response.status_code == 200:
|
177 |
-
|
178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
179 |
else:
|
180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
181 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
182 |
except Exception as e:
|
183 |
-
|
|
|
|
|
|
|
|
|
|
|
184 |
|
185 |
-
#
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
190 |
|
191 |
-
#
|
192 |
-
|
193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
194 |
try:
|
195 |
-
|
|
|
196 |
except:
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
206 |
|
207 |
if __name__ == "__main__":
|
208 |
demo.launch()
|
|
|
11 |
|
12 |
# Configuration
|
13 |
SPACE_NAME = 'AI Assistant'
|
14 |
+
SPACE_DESCRIPTION = 'A customizable AI assistant'
|
15 |
|
16 |
# Default configuration values (used only if config.json is missing)
|
17 |
DEFAULT_CONFIG = {
|
18 |
'name': SPACE_NAME,
|
19 |
'description': SPACE_DESCRIPTION,
|
20 |
+
'system_prompt': "You are a Socratic conversation partner for students in general education courses across all disciplines with strengths in the pebble-in-the-pond learning model, responsive teaching, and constructivist learning principles. Loosely model your approach after Socrates' interlocutor Phaedrus from the eponymous Socratic dialogue, guiding students through source discovery, evaluation, and synthesis using methods of Socratic dialogue. Ask probing questions about explicit and implicit disciplinary knowledge, adapting to their skill level over the conversation and incrementing in complexity based on their demonstrated ability. Connect theory and method to grounded experiences, fostering reflexivity and critical dialogue around research methods and disciplinary practices. Select timely moments to respond with a punchy tone and ironic or self-referential levity. Be concise, short, and sweet.",
|
21 |
+
'temperature': 0.9,
|
22 |
+
'max_tokens': 500,
|
23 |
+
'model': 'nvidia/llama-3.1-nemotron-70b-instruct',
|
24 |
'api_key_var': 'API_KEY',
|
25 |
'theme': 'Glass',
|
26 |
+
'grounding_urls': '["https://classics.mit.edu/Plato/phaedrus.1b.txt", "https://plato.stanford.edu/entries/plato-rhetoric/#Pha", "https://plato.stanford.edu/entries/plato-myths/", "https://en.wikipedia.org/wiki/Socratic_method", "https://en.wikipedia.org/wiki/Research_methodology", "https://en.wikipedia.org/wiki/Academic_research", "https://www.reddit.com/r/askphilosophy/comments/m6u36v/can_someone_go_over_the_socratic_method_and_give/", "https://www.reddit.com/r/askphilosophy/comments/k5td4z/is_socratic_method_the_best_way_to_change/"]',
|
27 |
'enable_dynamic_urls': True,
|
28 |
+
'examples': ['Can you help me understand why the sky is blue?', 'What makes democracy different from other forms of government?', 'How does the Socratic method apply to modern education?'],
|
29 |
'locked': False
|
30 |
}
|
31 |
|
|
|
76 |
API_KEY = API_KEY.strip() # Remove any whitespace
|
77 |
if not API_KEY: # Check if empty after stripping
|
78 |
API_KEY = None
|
79 |
+
|
80 |
+
# API Key validation and logging
|
81 |
+
def validate_api_key():
|
82 |
+
"""Validate API key configuration with detailed logging"""
|
83 |
+
if not API_KEY:
|
84 |
+
print(f"β οΈ API KEY CONFIGURATION ERROR:")
|
85 |
+
print(f" Variable name: {API_KEY_VAR}")
|
86 |
+
print(f" Status: Not set or empty")
|
87 |
+
print(f" Action needed: Set '{API_KEY_VAR}' in HuggingFace Space secrets")
|
88 |
+
print(f" Expected format: sk-or-xxxxxxxxxx")
|
89 |
+
return False
|
90 |
+
elif not API_KEY.startswith('sk-or-'):
|
91 |
+
print(f"β οΈ API KEY FORMAT WARNING:")
|
92 |
+
print(f" Variable name: {API_KEY_VAR}")
|
93 |
+
print(f" Current value: {API_KEY[:10]}..." if len(API_KEY) > 10 else "{API_KEY}")
|
94 |
+
print(f" Expected format: sk-or-xxxxxxxxxx")
|
95 |
+
print(f" Note: OpenRouter keys should start with 'sk-or-'")
|
96 |
+
return True # Still try to use it
|
97 |
+
else:
|
98 |
+
print(f"β
API Key configured successfully")
|
99 |
+
print(f" Variable: {API_KEY_VAR}")
|
100 |
+
print(f" Format: Valid OpenRouter key")
|
101 |
+
return True
|
102 |
+
|
103 |
+
# Validate on startup
|
104 |
+
try:
|
105 |
+
API_KEY_VALID = validate_api_key()
|
106 |
+
except NameError:
|
107 |
+
# During template generation, API_KEY might not be defined yet
|
108 |
+
API_KEY_VALID = False
|
109 |
+
|
110 |
+
def validate_url_domain(url):
|
111 |
+
"""Basic URL domain validation"""
|
112 |
+
try:
|
113 |
+
from urllib.parse import urlparse
|
114 |
+
parsed = urlparse(url)
|
115 |
+
# Check for valid domain structure
|
116 |
+
if parsed.netloc and '.' in parsed.netloc:
|
117 |
+
return True
|
118 |
+
except:
|
119 |
+
pass
|
120 |
+
return False
|
121 |
+
|
122 |
+
def fetch_url_content(url):
|
123 |
+
"""Enhanced URL content fetching with improved compatibility and error handling"""
|
124 |
+
if not validate_url_domain(url):
|
125 |
+
return f"Invalid URL format: {url}"
|
126 |
+
|
127 |
+
try:
|
128 |
+
# Enhanced headers for better compatibility
|
129 |
+
headers = {
|
130 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
|
131 |
+
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
132 |
+
'Accept-Language': 'en-US,en;q=0.5',
|
133 |
+
'Accept-Encoding': 'gzip, deflate',
|
134 |
+
'Connection': 'keep-alive'
|
135 |
+
}
|
136 |
+
|
137 |
+
response = requests.get(url, timeout=15, headers=headers)
|
138 |
+
response.raise_for_status()
|
139 |
+
soup = BeautifulSoup(response.content, 'html.parser')
|
140 |
+
|
141 |
+
# Enhanced content cleaning
|
142 |
+
for element in soup(["script", "style", "nav", "header", "footer", "aside", "form", "button"]):
|
143 |
+
element.decompose()
|
144 |
+
|
145 |
+
# Extract main content preferentially
|
146 |
+
main_content = soup.find('main') or soup.find('article') or soup.find('div', class_=lambda x: bool(x and 'content' in x.lower())) or soup
|
147 |
+
text = main_content.get_text()
|
148 |
+
|
149 |
+
# Enhanced text cleaning
|
150 |
+
lines = (line.strip() for line in text.splitlines())
|
151 |
+
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
|
152 |
+
text = ' '.join(chunk for chunk in chunks if chunk and len(chunk) > 2)
|
153 |
+
|
154 |
+
# Smart truncation - try to end at sentence boundaries
|
155 |
+
if len(text) > 4000:
|
156 |
+
truncated_text = text[:4000]
|
157 |
+
# Try to find the last complete sentence
|
158 |
+
last_period = truncated_text.rfind('.')
|
159 |
+
if last_period > 3500: # Only if we have a reasonably long truncation
|
160 |
+
text = truncated_text[:last_period + 1]
|
161 |
+
else:
|
162 |
+
text = truncated_text + "..."
|
163 |
+
|
164 |
+
return text if text.strip() else "No readable content found at this URL"
|
165 |
+
|
166 |
+
except requests.exceptions.Timeout:
|
167 |
+
return f"Timeout error fetching {url} (15s limit exceeded)"
|
168 |
+
except requests.exceptions.RequestException as e:
|
169 |
+
return f"Error fetching {url}: {str(e)}"
|
170 |
+
except Exception as e:
|
171 |
+
return f"Error processing content from {url}: {str(e)}"
|
172 |
+
|
173 |
+
def extract_urls_from_text(text):
|
174 |
+
"""Extract URLs from text using regex with enhanced validation"""
|
175 |
+
url_pattern = r'https?://[^\s<>"{}|\\^`\[\]"]+'
|
176 |
+
urls = re.findall(url_pattern, text)
|
177 |
+
|
178 |
+
# Basic URL validation and cleanup
|
179 |
+
validated_urls = []
|
180 |
+
for url in urls:
|
181 |
+
# Remove trailing punctuation that might be captured
|
182 |
+
url = url.rstrip('.,!?;:')
|
183 |
+
# Basic domain validation
|
184 |
+
if '.' in url and len(url) > 10:
|
185 |
+
validated_urls.append(url)
|
186 |
+
|
187 |
+
return validated_urls
|
188 |
+
|
189 |
+
# Global cache for URL content to avoid re-crawling in generated spaces
|
190 |
+
_url_content_cache = {}
|
191 |
|
192 |
def get_grounding_context():
|
193 |
"""Fetch context from grounding URLs with caching"""
|
|
|
202 |
if not urls:
|
203 |
return ""
|
204 |
|
205 |
+
# Create cache key from URLs
|
206 |
+
cache_key = tuple(sorted([url for url in urls if url and url.strip()]))
|
207 |
+
|
208 |
+
# Check cache first
|
209 |
+
if cache_key in _url_content_cache:
|
210 |
+
return _url_content_cache[cache_key]
|
211 |
+
|
212 |
+
context_parts = []
|
213 |
+
for i, url in enumerate(urls, 1):
|
214 |
+
if url.strip():
|
215 |
+
content = fetch_url_content(url.strip())
|
216 |
+
# Add priority indicators
|
217 |
+
priority_label = "PRIMARY" if i <= 2 else "SECONDARY"
|
218 |
+
context_parts.append(f"[{priority_label}] Context from URL {i} ({url}):\n{content}")
|
219 |
+
|
220 |
+
if context_parts:
|
221 |
+
result = "\n\n" + "\n\n".join(context_parts) + "\n\n"
|
222 |
+
else:
|
223 |
+
result = ""
|
224 |
+
|
225 |
+
# Cache the result
|
226 |
+
_url_content_cache[cache_key] = result
|
227 |
+
return result
|
228 |
|
229 |
def export_conversation_to_markdown(conversation_history):
|
230 |
"""Export conversation history to markdown format"""
|
|
|
249 |
markdown_content += f"## User Message {message_pair_count}\n\n{content}\n\n"
|
250 |
elif role == 'assistant':
|
251 |
markdown_content += f"## Assistant Response {message_pair_count}\n\n{content}\n\n---\n\n"
|
252 |
+
elif isinstance(message, (list, tuple)) and len(message) >= 2:
|
253 |
+
# Handle legacy tuple format: ["user msg", "assistant msg"]
|
254 |
+
message_pair_count += 1
|
255 |
+
user_msg, assistant_msg = message[0], message[1]
|
256 |
+
if user_msg:
|
257 |
+
markdown_content += f"## User Message {message_pair_count}\n\n{user_msg}\n\n"
|
258 |
+
if assistant_msg:
|
259 |
+
markdown_content += f"## Assistant Response {message_pair_count}\n\n{assistant_msg}\n\n---\n\n"
|
260 |
|
261 |
return markdown_content
|
262 |
|
263 |
+
|
264 |
def generate_response(message, history):
|
265 |
"""Generate response using OpenRouter API"""
|
266 |
|
267 |
# Enhanced API key validation with helpful messages
|
268 |
if not API_KEY:
|
269 |
error_msg = f"π **API Key Required**\n\n"
|
270 |
+
error_msg += f"Please configure your OpenRouter API key:\n"
|
271 |
error_msg += f"1. Go to Settings (βοΈ) in your HuggingFace Space\n"
|
272 |
error_msg += f"2. Click 'Variables and secrets'\n"
|
273 |
error_msg += f"3. Add secret: **{API_KEY_VAR}**\n"
|
274 |
error_msg += f"4. Value: Your OpenRouter API key (starts with `sk-or-`)\n\n"
|
275 |
error_msg += f"Get your API key at: https://openrouter.ai/keys"
|
276 |
+
print(f"β API request failed: No API key configured for {API_KEY_VAR}")
|
277 |
return error_msg
|
278 |
|
279 |
# Get grounding context
|
280 |
grounding_context = get_grounding_context()
|
281 |
|
282 |
+
# Process uploaded files if any
|
283 |
+
file_context = ""
|
284 |
+
if files:
|
285 |
+
file_contents = []
|
286 |
+
for file_obj in files:
|
287 |
+
if file_obj is not None:
|
288 |
+
try:
|
289 |
+
file_content = extract_file_content(file_obj.name)
|
290 |
+
file_contents.append(file_content)
|
291 |
+
except Exception as e:
|
292 |
+
file_contents.append(f"Error processing file: {str(e)}")
|
293 |
+
|
294 |
+
if file_contents:
|
295 |
+
file_context = "\n\n[UPLOADED FILES]\n" + "\n\n".join(file_contents) + "\n"
|
296 |
+
|
297 |
+
# If dynamic URLs are enabled, check message for URLs to fetch
|
298 |
+
if ENABLE_DYNAMIC_URLS:
|
299 |
+
urls_in_message = extract_urls_from_text(message)
|
300 |
+
if urls_in_message:
|
301 |
+
dynamic_context = ""
|
302 |
+
for url in urls_in_message[:3]: # Limit to 3 URLs per message
|
303 |
+
content = fetch_url_content(url)
|
304 |
+
dynamic_context += f"\n\n[DYNAMIC] Context from {url}:\n{content}"
|
305 |
+
grounding_context += dynamic_context
|
306 |
+
|
307 |
+
# Build enhanced system prompt with grounding context and file content
|
308 |
+
enhanced_system_prompt = SYSTEM_PROMPT + grounding_context + file_context
|
309 |
|
310 |
# Build messages array for the API
|
311 |
messages = [{"role": "system", "content": enhanced_system_prompt}]
|
312 |
|
313 |
+
# Add conversation history - handle both modern messages format and legacy tuples
|
314 |
for chat in history:
|
315 |
if isinstance(chat, dict):
|
316 |
messages.append(chat)
|
|
|
321 |
# Add current message
|
322 |
messages.append({"role": "user", "content": message})
|
323 |
|
324 |
+
# Make API request with enhanced error handling
|
325 |
try:
|
326 |
+
print(f"π Making API request to OpenRouter...")
|
327 |
+
print(f" Model: {MODEL}")
|
328 |
+
print(f" Messages: {len(messages)} in conversation")
|
329 |
+
|
330 |
response = requests.post(
|
331 |
url="https://openrouter.ai/api/v1/chat/completions",
|
332 |
headers={
|
|
|
344 |
timeout=30
|
345 |
)
|
346 |
|
347 |
+
print(f"π‘ API Response: {response.status_code}")
|
348 |
+
|
349 |
if response.status_code == 200:
|
350 |
+
try:
|
351 |
+
result = response.json()
|
352 |
+
return result['choices'][0]['message']['content']
|
353 |
+
except (KeyError, IndexError, json.JSONDecodeError) as e:
|
354 |
+
error_msg = f"β **Response Parsing Error**\n\n"
|
355 |
+
error_msg += f"Received response from API but couldn't parse it properly.\n"
|
356 |
+
error_msg += f"Error: {str(e)}\n\n"
|
357 |
+
error_msg += f"**Troubleshooting:**\n"
|
358 |
+
error_msg += f"1. Check OpenRouter service status\n"
|
359 |
+
error_msg += f"2. Try again in a few moments\n"
|
360 |
+
error_msg += f"3. Try a different model if available"
|
361 |
+
print(f"β Response parsing error: {str(e)}")
|
362 |
+
return error_msg
|
363 |
+
elif response.status_code == 401:
|
364 |
+
error_msg = f"π **Authentication Error**\n\n"
|
365 |
+
error_msg += f"Your API key appears to be invalid or expired.\n\n"
|
366 |
+
error_msg += f"**Troubleshooting:**\n"
|
367 |
+
error_msg += f"1. Check that your **{API_KEY_VAR}** secret is set correctly\n"
|
368 |
+
error_msg += f"2. Verify your OpenRouter API key at https://openrouter.ai/keys\n"
|
369 |
+
error_msg += f"3. Make sure the key starts with `sk-or-`\n"
|
370 |
+
error_msg += f"4. Check if you have sufficient credits"
|
371 |
+
print(f"β Authentication failed: Invalid API key")
|
372 |
+
return error_msg
|
373 |
+
elif response.status_code == 429:
|
374 |
+
error_msg = f"β±οΈ **Rate Limit Exceeded**\n\n"
|
375 |
+
error_msg += f"Too many requests. Please wait a moment and try again.\n\n"
|
376 |
+
error_msg += f"**Troubleshooting:**\n"
|
377 |
+
error_msg += f"1. Wait 30-60 seconds before trying again\n"
|
378 |
+
error_msg += f"2. Check your OpenRouter usage limits\n"
|
379 |
+
error_msg += f"3. Consider upgrading your OpenRouter plan"
|
380 |
+
print(f"β Rate limit exceeded")
|
381 |
+
return error_msg
|
382 |
+
elif response.status_code == 400:
|
383 |
+
error_msg = f"π **Request Error**\n\n"
|
384 |
+
error_msg += f"There was a problem with the request format.\n"
|
385 |
+
error_msg += f"Response: {response.text[:500]}\n\n"
|
386 |
+
error_msg += f"**Troubleshooting:**\n"
|
387 |
+
error_msg += f"1. Try a shorter message\n"
|
388 |
+
error_msg += f"2. Check for special characters in your message\n"
|
389 |
+
error_msg += f"3. Try a different model"
|
390 |
+
print(f"β Bad request: {response.status_code} - {response.text[:200]}")
|
391 |
+
return error_msg
|
392 |
else:
|
393 |
+
error_msg = f"π **API Error {response.status_code}**\n\n"
|
394 |
+
error_msg += f"An unexpected error occurred.\n"
|
395 |
+
error_msg += f"Response: {response.text[:500]}\n\n"
|
396 |
+
error_msg += f"**Troubleshooting:**\n"
|
397 |
+
error_msg += f"1. Try again in a few moments\n"
|
398 |
+
error_msg += f"2. Check OpenRouter service status\n"
|
399 |
+
error_msg += f"3. Contact support if this persists"
|
400 |
+
print(f"β API error: {response.status_code} - {response.text[:200]}")
|
401 |
+
return error_msg
|
402 |
|
403 |
+
except requests.exceptions.Timeout:
|
404 |
+
error_msg = f"β° **Request Timeout**\n\n"
|
405 |
+
error_msg += f"The API request took too long (30s limit).\n\n"
|
406 |
+
error_msg += f"**Troubleshooting:**\n"
|
407 |
+
error_msg += f"1. Try again with a shorter message\n"
|
408 |
+
error_msg += f"2. Check your internet connection\n"
|
409 |
+
error_msg += f"3. Try a different model"
|
410 |
+
print(f"β Request timeout after 30 seconds")
|
411 |
+
return error_msg
|
412 |
+
except requests.exceptions.ConnectionError:
|
413 |
+
error_msg = f"π **Connection Error**\n\n"
|
414 |
+
error_msg += f"Could not connect to OpenRouter API.\n\n"
|
415 |
+
error_msg += f"**Troubleshooting:**\n"
|
416 |
+
error_msg += f"1. Check your internet connection\n"
|
417 |
+
error_msg += f"2. Check OpenRouter service status\n"
|
418 |
+
error_msg += f"3. Try again in a few moments"
|
419 |
+
print(f"β Connection error to OpenRouter API")
|
420 |
+
return error_msg
|
421 |
except Exception as e:
|
422 |
+
error_msg = "β **Unexpected Error**\n\n"
|
423 |
+
error_msg += "An unexpected error occurred:\n"
|
424 |
+
error_msg += f"`{str(e)}`\n\n"
|
425 |
+
error_msg += "Please try again or contact support if this persists."
|
426 |
+
print(f"β Unexpected error: {str(e)}")
|
427 |
+
return error_msg
|
428 |
|
429 |
+
# Access code verification
|
430 |
+
access_granted = gr.State(False)
|
431 |
+
_access_granted_global = False # Global fallback
|
432 |
+
|
433 |
+
def verify_access_code(code):
|
434 |
+
"""Verify the access code"""
|
435 |
+
global _access_granted_global
|
436 |
+
if ACCESS_CODE is None:
|
437 |
+
_access_granted_global = True
|
438 |
+
return gr.update(value="No access code required.", style={"color": "green"}), gr.update(visible=True), True
|
439 |
+
|
440 |
+
if code == ACCESS_CODE:
|
441 |
+
_access_granted_global = True
|
442 |
+
return gr.update(value="β
Access granted!", style={"color": "green"}), gr.update(visible=True), True
|
443 |
+
else:
|
444 |
+
_access_granted_global = False
|
445 |
+
return gr.update(value="β Invalid access code. Please try again.", style={"color": "red"}), gr.update(visible=False), False
|
446 |
+
|
447 |
+
def protected_generate_response(message, history, files=None):
|
448 |
+
"""Protected response function that checks access"""
|
449 |
+
# Check if access is granted via the global variable
|
450 |
+
if ACCESS_CODE is not None and not _access_granted_global:
|
451 |
+
return "Please enter the access code to continue."
|
452 |
+
return generate_response(message, history, files)
|
453 |
+
|
454 |
+
# Global variable to store chat history for export
|
455 |
+
chat_history_store = []
|
456 |
+
|
457 |
+
def store_and_generate_response(message, history, files=None):
|
458 |
+
"""Wrapper function that stores history and generates response"""
|
459 |
+
global chat_history_store
|
460 |
+
|
461 |
+
# Generate response using the protected function
|
462 |
+
response = protected_generate_response(message, history, files)
|
463 |
|
464 |
+
# Convert current history to the format we need for export
|
465 |
+
# history comes in as [["user1", "bot1"], ["user2", "bot2"], ...]
|
466 |
+
chat_history_store = []
|
467 |
+
if history:
|
468 |
+
for exchange in history:
|
469 |
+
if isinstance(exchange, dict):
|
470 |
+
chat_history_store.append(exchange)
|
471 |
+
elif isinstance(exchange, (list, tuple)) and len(exchange) >= 2:
|
472 |
+
chat_history_store.append({"role": "user", "content": exchange[0]})
|
473 |
+
chat_history_store.append({"role": "assistant", "content": exchange[1]})
|
474 |
+
|
475 |
+
# Add the current exchange
|
476 |
+
chat_history_store.append({"role": "user", "content": message})
|
477 |
+
chat_history_store.append({"role": "assistant", "content": response})
|
478 |
+
|
479 |
+
return response
|
480 |
+
|
481 |
+
def export_current_conversation():
|
482 |
+
"""Export the current conversation"""
|
483 |
+
if not chat_history_store:
|
484 |
+
return gr.update(visible=False)
|
485 |
+
|
486 |
+
markdown_content = export_conversation_to_markdown(chat_history_store)
|
487 |
+
|
488 |
+
# Save to temporary file
|
489 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
|
490 |
+
f.write(markdown_content)
|
491 |
+
temp_file = f.name
|
492 |
+
|
493 |
+
return gr.update(value=temp_file, visible=True)
|
494 |
+
|
495 |
+
def export_conversation(history):
|
496 |
+
"""Export conversation to markdown file"""
|
497 |
+
if not history:
|
498 |
+
return gr.update(visible=False)
|
499 |
+
|
500 |
+
markdown_content = export_conversation_to_markdown(history)
|
501 |
+
|
502 |
+
# Save to temporary file
|
503 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
|
504 |
+
f.write(markdown_content)
|
505 |
+
temp_file = f.name
|
506 |
+
|
507 |
+
return gr.update(value=temp_file, visible=True)
|
508 |
+
|
509 |
+
# Configuration status display
|
510 |
+
def get_configuration_status():
|
511 |
+
"""Generate a clean configuration status message for display"""
|
512 |
+
status_parts = []
|
513 |
+
|
514 |
+
# Basic configuration info (without redundant "Configuration:" header)
|
515 |
+
status_parts.append(f"**Name:** {SPACE_NAME}")
|
516 |
+
status_parts.append(f"**Model:** {MODEL}")
|
517 |
+
status_parts.append(f"**Theme:** {THEME}")
|
518 |
+
status_parts.append(f"**Temperature:** {temperature}")
|
519 |
+
status_parts.append(f"**Max Response Tokens:** {max_tokens}")
|
520 |
+
status_parts.append("")
|
521 |
+
|
522 |
+
# Example prompts
|
523 |
+
status_parts.append("")
|
524 |
+
examples_list = config.get('examples', [])
|
525 |
+
if isinstance(examples_list, str):
|
526 |
+
try:
|
527 |
+
import ast
|
528 |
+
examples_list = ast.literal_eval(examples_list)
|
529 |
+
except:
|
530 |
+
examples_list = []
|
531 |
+
|
532 |
+
if examples_list and len(examples_list) > 0:
|
533 |
+
status_parts.append("**Example Prompts:**")
|
534 |
+
for example in examples_list[:5]: # Show first 5 examples
|
535 |
+
status_parts.append(f"β’ {example}")
|
536 |
+
if len(examples_list) > 5:
|
537 |
+
status_parts.append(f"β’ ... and {len(examples_list) - 5} more")
|
538 |
+
else:
|
539 |
+
status_parts.append("**Example Prompts:** No example prompts configured")
|
540 |
+
|
541 |
+
# URL Context if configured
|
542 |
+
urls = GROUNDING_URLS
|
543 |
+
if isinstance(urls, str):
|
544 |
try:
|
545 |
+
import ast
|
546 |
+
urls = ast.literal_eval(urls)
|
547 |
except:
|
548 |
+
urls = []
|
549 |
+
|
550 |
+
if urls and len(urls) > 0:
|
551 |
+
status_parts.append("")
|
552 |
+
status_parts.append("**Grounding URLs:**")
|
553 |
+
for i, url in enumerate(urls[:5], 1): # Show first 5 URLs
|
554 |
+
status_parts.append(f"{i}. {url}")
|
555 |
+
if len(urls) > 5:
|
556 |
+
status_parts.append(f"... and {len(urls) - 5} more URLs")
|
557 |
+
|
558 |
+
# System prompt at the end
|
559 |
+
status_parts.append("")
|
560 |
+
status_parts.append(f"**System Prompt:** {SYSTEM_PROMPT}")
|
561 |
+
|
562 |
+
# API Key status (minimal, at the end)
|
563 |
+
status_parts.append("")
|
564 |
+
if not API_KEY_VALID:
|
565 |
+
status_parts.append(f"**Note:** API key ({API_KEY_VAR}) not configured in Space secrets")
|
566 |
+
|
567 |
+
return "\n".join(status_parts)
|
568 |
+
|
569 |
+
# Create interface with access code protection
|
570 |
+
# Dynamically set theme based on configuration
|
571 |
+
theme_class = getattr(gr.themes, THEME, gr.themes.Default)
|
572 |
+
with gr.Blocks(title=SPACE_NAME, theme=theme_class()) as demo:
|
573 |
+
# Check if faculty password is configured to determine tab structure
|
574 |
+
FACULTY_PASSWORD = os.environ.get("CONFIG_CODE", "").strip()
|
575 |
+
|
576 |
+
# If faculty config is enabled, use tabs for better organization
|
577 |
+
if FACULTY_PASSWORD:
|
578 |
+
with gr.Tabs() as main_tabs:
|
579 |
+
with gr.Tab("Chat U/I"):
|
580 |
+
gr.Markdown(f"# {SPACE_NAME}")
|
581 |
+
gr.Markdown(SPACE_DESCRIPTION)
|
582 |
+
|
583 |
+
# Access code section (shown only if ACCESS_CODE is set)
|
584 |
+
with gr.Column(visible=(ACCESS_CODE is not None)) as access_section:
|
585 |
+
gr.Markdown("### π Access Required")
|
586 |
+
gr.Markdown("Please enter the access code provided by your instructor:")
|
587 |
+
|
588 |
+
access_input = gr.Textbox(
|
589 |
+
label="Access Code",
|
590 |
+
placeholder="Enter access code...",
|
591 |
+
type="password"
|
592 |
+
)
|
593 |
+
access_btn = gr.Button("Submit", variant="primary")
|
594 |
+
access_error = gr.Markdown(visible=False)
|
595 |
+
|
596 |
+
# Main chat interface (hidden until access granted)
|
597 |
+
with gr.Column(visible=(ACCESS_CODE is None)) as chat_section:
|
598 |
+
# Get examples from config
|
599 |
+
examples = config.get('examples', [])
|
600 |
+
if isinstance(examples, str):
|
601 |
+
try:
|
602 |
+
import ast
|
603 |
+
examples = ast.literal_eval(examples)
|
604 |
+
except:
|
605 |
+
examples = []
|
606 |
+
|
607 |
+
chat_interface = gr.ChatInterface(
|
608 |
+
fn=store_and_generate_response, # Use wrapper function to store history
|
609 |
+
title="", # Title already shown above
|
610 |
+
description="", # Description already shown above
|
611 |
+
examples=examples if examples else None,
|
612 |
+
type="messages", # Use modern message format for better compatibility
|
613 |
+
additional_inputs=[
|
614 |
+
gr.File(
|
615 |
+
label="π",
|
616 |
+
file_types=None, # Accept all file types
|
617 |
+
file_count="multiple",
|
618 |
+
visible=True
|
619 |
+
)
|
620 |
+
]
|
621 |
+
)
|
622 |
+
|
623 |
+
# Export functionality
|
624 |
+
with gr.Row():
|
625 |
+
export_btn = gr.Button("π₯ Export Conversation", variant="secondary", size="sm")
|
626 |
+
export_file = gr.File(label="Download", visible=False)
|
627 |
+
|
628 |
+
# Connect export functionality
|
629 |
+
export_btn.click(
|
630 |
+
export_current_conversation,
|
631 |
+
outputs=[export_file]
|
632 |
+
)
|
633 |
+
|
634 |
+
# Configuration status
|
635 |
+
with gr.Accordion("Configuration", open=False):
|
636 |
+
gr.Markdown(get_configuration_status())
|
637 |
+
|
638 |
+
# Connect access verification within tab context
|
639 |
+
if ACCESS_CODE is not None:
|
640 |
+
access_btn.click(
|
641 |
+
verify_access_code,
|
642 |
+
inputs=[access_input],
|
643 |
+
outputs=[access_error, chat_section, access_granted]
|
644 |
+
)
|
645 |
+
access_input.submit(
|
646 |
+
verify_access_code,
|
647 |
+
inputs=[access_input],
|
648 |
+
outputs=[access_error, chat_section, access_granted]
|
649 |
+
)
|
650 |
+
|
651 |
+
# Add Configuration tab
|
652 |
+
with gr.Tab("Configuration"):
|
653 |
+
gr.Markdown("### Faculty Configuration")
|
654 |
+
gr.Markdown("Edit assistant configuration. Requires authentication.")
|
655 |
+
|
656 |
+
faculty_auth_state = gr.State(False)
|
657 |
+
faculty_auth_state = gr.State(False)
|
658 |
+
|
659 |
+
# Authentication row
|
660 |
+
with gr.Column() as faculty_auth_row:
|
661 |
+
with gr.Row():
|
662 |
+
faculty_password_input = gr.Textbox(
|
663 |
+
label="Faculty Password",
|
664 |
+
type="password",
|
665 |
+
placeholder="Enter faculty configuration password",
|
666 |
+
scale=3
|
667 |
+
)
|
668 |
+
faculty_auth_btn = gr.Button("Unlock Configuration", variant="primary", scale=1)
|
669 |
+
faculty_auth_status = gr.Markdown("")
|
670 |
+
|
671 |
+
# Configuration editor (hidden until authenticated)
|
672 |
+
with gr.Column(visible=False) as faculty_config_section:
|
673 |
+
gr.Markdown("### Edit Assistant Configuration")
|
674 |
+
gr.Markdown("β οΈ **Warning:** Changes will affect all users immediately.")
|
675 |
+
|
676 |
+
# Load current configuration
|
677 |
+
try:
|
678 |
+
with open('config.json', 'r') as f:
|
679 |
+
current_config = json.load(f)
|
680 |
+
except:
|
681 |
+
# Use DEFAULT_CONFIG as fallback
|
682 |
+
current_config = DEFAULT_CONFIG.copy()
|
683 |
+
|
684 |
+
# Editable fields
|
685 |
+
# System Prompt
|
686 |
+
edit_system_prompt = gr.Textbox(
|
687 |
+
label="System Prompt",
|
688 |
+
value=current_config.get('system_prompt', SYSTEM_PROMPT),
|
689 |
+
lines=5
|
690 |
+
)
|
691 |
+
|
692 |
+
# 3. Model Selection
|
693 |
+
edit_model = gr.Dropdown(
|
694 |
+
label="Model",
|
695 |
+
choices=[
|
696 |
+
"google/gemini-2.0-flash-001",
|
697 |
+
"google/gemma-3-27b-it",
|
698 |
+
"anthropic/claude-3.5-sonnet",
|
699 |
+
"anthropic/claude-3.5-haiku",
|
700 |
+
"openai/gpt-4o-mini-search-preview",
|
701 |
+
"openai/gpt-4.1-nano",
|
702 |
+
"nvidia/llama-3.1-nemotron-70b-instruct",
|
703 |
+
"mistralai/devstral-small"
|
704 |
+
],
|
705 |
+
value=current_config.get('model', MODEL)
|
706 |
+
)
|
707 |
+
|
708 |
+
# 4. Example prompts field
|
709 |
+
examples_value = current_config.get('examples', [])
|
710 |
+
if isinstance(examples_value, list):
|
711 |
+
examples_text_value = "\n".join(examples_value)
|
712 |
+
else:
|
713 |
+
examples_text_value = ""
|
714 |
+
|
715 |
+
edit_examples = gr.Textbox(
|
716 |
+
label="Example Prompts (one per line)",
|
717 |
+
value=examples_text_value,
|
718 |
+
lines=3,
|
719 |
+
placeholder="What can you help me with?\nExplain this concept\nHelp me understand..."
|
720 |
+
)
|
721 |
+
|
722 |
+
# 5. Model Parameters
|
723 |
+
with gr.Row():
|
724 |
+
edit_temperature = gr.Slider(
|
725 |
+
label="Temperature",
|
726 |
+
minimum=0,
|
727 |
+
maximum=2,
|
728 |
+
value=current_config.get('temperature', 0.7),
|
729 |
+
step=0.1
|
730 |
+
)
|
731 |
+
edit_max_tokens = gr.Slider(
|
732 |
+
label="Max Tokens",
|
733 |
+
minimum=50,
|
734 |
+
maximum=4096,
|
735 |
+
value=current_config.get('max_tokens', 750),
|
736 |
+
step=50
|
737 |
+
)
|
738 |
+
|
739 |
+
# URL Grounding fields
|
740 |
+
gr.Markdown("### URL Grounding")
|
741 |
+
grounding_urls_value = current_config.get('grounding_urls', [])
|
742 |
+
if isinstance(grounding_urls_value, str):
|
743 |
+
try:
|
744 |
+
import ast
|
745 |
+
grounding_urls_value = ast.literal_eval(grounding_urls_value)
|
746 |
+
except:
|
747 |
+
grounding_urls_value = []
|
748 |
+
|
749 |
+
# Create 10 URL input fields
|
750 |
+
url_fields = []
|
751 |
+
for i in range(10):
|
752 |
+
url_value = grounding_urls_value[i] if i < len(grounding_urls_value) else ""
|
753 |
+
url_field = gr.Textbox(
|
754 |
+
label=f"URL {i+1}" + (" (Primary)" if i < 2 else " (Secondary)"),
|
755 |
+
value=url_value,
|
756 |
+
placeholder="https://..."
|
757 |
+
)
|
758 |
+
url_fields.append(url_field)
|
759 |
+
|
760 |
+
config_locked = gr.Checkbox(
|
761 |
+
label="Lock Configuration (Prevent further edits)",
|
762 |
+
value=current_config.get('locked', False)
|
763 |
+
)
|
764 |
+
|
765 |
+
with gr.Row():
|
766 |
+
save_config_btn = gr.Button("Save Configuration", variant="primary")
|
767 |
+
reset_config_btn = gr.Button("Reset to Defaults", variant="secondary")
|
768 |
+
|
769 |
+
config_status = gr.Markdown("")
|
770 |
+
|
771 |
+
# Faculty authentication function
|
772 |
+
def verify_faculty_password(password):
|
773 |
+
if password == FACULTY_PASSWORD:
|
774 |
+
return (
|
775 |
+
gr.update(value="Authentication successful!"),
|
776 |
+
gr.update(visible=False), # Hide auth row
|
777 |
+
gr.update(visible=True), # Show config section
|
778 |
+
True # Update auth state
|
779 |
+
)
|
780 |
+
else:
|
781 |
+
return (
|
782 |
+
gr.update(value="Invalid password"),
|
783 |
+
gr.update(visible=True), # Keep auth row visible
|
784 |
+
gr.update(visible=False), # Keep config hidden
|
785 |
+
False # Auth failed
|
786 |
+
)
|
787 |
+
|
788 |
+
# Save configuration function
|
789 |
+
def save_configuration(new_prompt, new_model, new_examples, new_temp, new_tokens, *url_values, lock_config, is_authenticated):
|
790 |
+
if not is_authenticated:
|
791 |
+
return "Not authenticated"
|
792 |
+
|
793 |
+
# Check if configuration is already locked
|
794 |
+
try:
|
795 |
+
with open('config.json', 'r') as f:
|
796 |
+
existing_config = json.load(f)
|
797 |
+
if existing_config.get('locked', False):
|
798 |
+
return "Configuration is locked and cannot be modified"
|
799 |
+
except:
|
800 |
+
pass
|
801 |
+
|
802 |
+
# Load current config to preserve all values
|
803 |
+
try:
|
804 |
+
with open('config.json', 'r') as f:
|
805 |
+
current_full_config = json.load(f)
|
806 |
+
except:
|
807 |
+
# If config.json doesn't exist, use default configuration
|
808 |
+
current_full_config = DEFAULT_CONFIG.copy()
|
809 |
+
|
810 |
+
# Process example prompts
|
811 |
+
examples_list = [ex.strip() for ex in new_examples.split('\n') if ex.strip()]
|
812 |
+
|
813 |
+
# Process URL values - lock_config is the last parameter
|
814 |
+
urls = list(url_values[:-1]) # All but last are URLs
|
815 |
+
lock_config_from_args = url_values[-1] # Last is lock_config
|
816 |
+
# Filter out empty URLs
|
817 |
+
grounding_urls = [url.strip() for url in urls if url.strip()]
|
818 |
+
|
819 |
+
# Create backup before making changes
|
820 |
+
try:
|
821 |
+
# Create backups directory if it doesn't exist
|
822 |
+
os.makedirs('config_backups', exist_ok=True)
|
823 |
+
|
824 |
+
# Create timestamped backup
|
825 |
+
backup_filename = f"config_backups/config_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
|
826 |
+
with open(backup_filename, 'w') as backup_file:
|
827 |
+
json.dump(current_full_config, backup_file, indent=2)
|
828 |
+
|
829 |
+
# Keep only last 10 backups
|
830 |
+
backups = sorted([f for f in os.listdir('config_backups') if f.endswith('.json')])
|
831 |
+
if len(backups) > 10:
|
832 |
+
for old_backup in backups[:-10]:
|
833 |
+
os.remove(os.path.join('config_backups', old_backup))
|
834 |
+
except Exception as backup_error:
|
835 |
+
print(f"Warning: Could not create backup: {backup_error}")
|
836 |
+
# Continue with save even if backup fails
|
837 |
+
|
838 |
+
# Update all editable fields while preserving everything else
|
839 |
+
current_full_config.update({
|
840 |
+
'system_prompt': new_prompt,
|
841 |
+
'model': new_model,
|
842 |
+
'examples': examples_list,
|
843 |
+
'temperature': new_temp,
|
844 |
+
'max_tokens': int(new_tokens),
|
845 |
+
'grounding_urls': grounding_urls,
|
846 |
+
'locked': lock_config_from_args,
|
847 |
+
'last_modified': datetime.now().isoformat(),
|
848 |
+
'last_modified_by': 'faculty'
|
849 |
+
})
|
850 |
+
|
851 |
+
try:
|
852 |
+
with open('config.json', 'w') as f:
|
853 |
+
json.dump(current_full_config, f, indent=2)
|
854 |
+
|
855 |
+
# Optional: Auto-commit to HuggingFace if token is available
|
856 |
+
hf_token = os.environ.get("HF_TOKEN")
|
857 |
+
space_id = os.environ.get("SPACE_ID")
|
858 |
+
|
859 |
+
if hf_token and space_id:
|
860 |
+
try:
|
861 |
+
from huggingface_hub import HfApi, restart_space
|
862 |
+
api = HfApi(token=hf_token)
|
863 |
+
|
864 |
+
# Upload file (overwrites existing)
|
865 |
+
api.upload_file(
|
866 |
+
path_or_fileobj="config.json",
|
867 |
+
path_in_repo="config.json",
|
868 |
+
repo_id=space_id,
|
869 |
+
repo_type="space",
|
870 |
+
commit_message=f"Update configuration by faculty at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
|
871 |
+
)
|
872 |
+
|
873 |
+
# Automatic restart
|
874 |
+
try:
|
875 |
+
restart_space(space_id, token=hf_token)
|
876 |
+
return f"β
Configuration saved and committed at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\nπ **Space is restarting automatically!**\n\nThe page will refresh in about 30 seconds. Your changes will be applied."
|
877 |
+
except Exception as restart_error:
|
878 |
+
print(f"Could not auto-restart: {restart_error}")
|
879 |
+
return f"β
Configuration saved and committed at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\nπ **Please restart manually** (auto-restart failed)\n\n1. Go to Settings (βοΈ)\n2. Click 'Factory reboot'\n3. Wait ~30 seconds"
|
880 |
+
except Exception as commit_error:
|
881 |
+
print(f"Note: Could not auto-commit to repository: {commit_error}")
|
882 |
+
return f"β
Configuration saved locally at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\nπ **Manual Restart Required**\nFor changes to take effect:\n1. Go to Settings (βοΈ)\n2. Click 'Factory reboot'\n3. Wait ~30 seconds for restart"
|
883 |
+
else:
|
884 |
+
return f"β
Configuration saved at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\nπ **Manual Restart Required**\nFor changes to take effect:\n1. Go to Settings (βοΈ)\n2. Click 'Factory reboot'\n3. Wait ~30 seconds for restart"
|
885 |
+
except Exception as e:
|
886 |
+
return f"β Error saving configuration: {str(e)}"
|
887 |
+
|
888 |
+
# Reset configuration function
|
889 |
+
def reset_configuration(is_authenticated):
|
890 |
+
if not is_authenticated:
|
891 |
+
updates = ["Not authenticated"] + [gr.update() for _ in range(14)] # 1 status + 14 fields (prompt, model, examples, temp, tokens + 10 urls)
|
892 |
+
return tuple(updates)
|
893 |
+
|
894 |
+
# Check if locked
|
895 |
+
try:
|
896 |
+
with open('config.json', 'r') as f:
|
897 |
+
existing_config = json.load(f)
|
898 |
+
if existing_config.get('locked', False):
|
899 |
+
updates = ["Configuration is locked"] + [gr.update() for _ in range(14)]
|
900 |
+
return tuple(updates)
|
901 |
+
except:
|
902 |
+
pass
|
903 |
+
|
904 |
+
# Get default examples as text
|
905 |
+
default_examples = DEFAULT_CONFIG.get('examples', [])
|
906 |
+
if isinstance(default_examples, list):
|
907 |
+
examples_text = "\n".join(default_examples)
|
908 |
+
else:
|
909 |
+
examples_text = ""
|
910 |
+
|
911 |
+
# Get default URLs - parse from JSON string if needed
|
912 |
+
default_urls = DEFAULT_CONFIG.get('grounding_urls', [])
|
913 |
+
if isinstance(default_urls, str):
|
914 |
+
try:
|
915 |
+
import json
|
916 |
+
default_urls = json.loads(default_urls)
|
917 |
+
except:
|
918 |
+
default_urls = []
|
919 |
+
elif not isinstance(default_urls, list):
|
920 |
+
default_urls = []
|
921 |
+
|
922 |
+
# Reset to original default values
|
923 |
+
updates = [
|
924 |
+
"Reset to default values",
|
925 |
+
gr.update(value=DEFAULT_CONFIG.get('system_prompt', SYSTEM_PROMPT)),
|
926 |
+
gr.update(value=DEFAULT_CONFIG.get('model', MODEL)),
|
927 |
+
gr.update(value=examples_text),
|
928 |
+
gr.update(value=DEFAULT_CONFIG.get('temperature', temperature)),
|
929 |
+
gr.update(value=DEFAULT_CONFIG.get('max_tokens', max_tokens))
|
930 |
+
]
|
931 |
+
|
932 |
+
# Add URL updates
|
933 |
+
for i in range(10):
|
934 |
+
url_value = default_urls[i] if i < len(default_urls) else ""
|
935 |
+
updates.append(gr.update(value=url_value))
|
936 |
+
|
937 |
+
return tuple(updates)
|
938 |
+
|
939 |
+
# Connect authentication
|
940 |
+
faculty_auth_btn.click(
|
941 |
+
verify_faculty_password,
|
942 |
+
inputs=[faculty_password_input],
|
943 |
+
outputs=[faculty_auth_status, faculty_auth_row, faculty_config_section, faculty_auth_state]
|
944 |
+
)
|
945 |
+
|
946 |
+
faculty_password_input.submit(
|
947 |
+
verify_faculty_password,
|
948 |
+
inputs=[faculty_password_input],
|
949 |
+
outputs=[faculty_auth_status, faculty_auth_row, faculty_config_section, faculty_auth_state]
|
950 |
+
)
|
951 |
+
|
952 |
+
# Connect configuration buttons
|
953 |
+
save_config_btn.click(
|
954 |
+
save_configuration,
|
955 |
+
inputs=[edit_system_prompt, edit_model, edit_examples, edit_temperature, edit_max_tokens] + url_fields + [config_locked, faculty_auth_state],
|
956 |
+
outputs=[config_status]
|
957 |
+
)
|
958 |
+
|
959 |
+
reset_config_btn.click(
|
960 |
+
reset_configuration,
|
961 |
+
inputs=[faculty_auth_state],
|
962 |
+
outputs=[config_status, edit_system_prompt, edit_model, edit_examples, edit_temperature, edit_max_tokens] + url_fields
|
963 |
+
)
|
964 |
+
else:
|
965 |
+
gr.Markdown("Faculty configuration is not enabled. Set CONFIG_CODE in Space secrets to enable.")
|
966 |
|
967 |
if __name__ == "__main__":
|
968 |
demo.launch()
|
config.json
CHANGED
@@ -1,15 +1,26 @@
|
|
1 |
{
|
2 |
"name": "AI Assistant",
|
3 |
-
"description": "A
|
4 |
-
"system_prompt": "You are a Socratic conversation partner for general education courses across all disciplines,
|
5 |
-
"model": "
|
6 |
"api_key_var": "API_KEY",
|
7 |
-
"temperature": 0.
|
8 |
-
"max_tokens":
|
9 |
"examples": [
|
10 |
-
"Can you help me understand why the sky is blue?"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
],
|
12 |
-
"grounding_urls": [],
|
13 |
"enable_dynamic_urls": true,
|
14 |
"theme": "Glass"
|
15 |
}
|
|
|
1 |
{
|
2 |
"name": "AI Assistant",
|
3 |
+
"description": "A customizable AI assistant",
|
4 |
+
"system_prompt": "You are a Socratic conversation partner for students in general education courses across all disciplines with strengths in the pebble-in-the-pond learning model, responsive teaching, and constructivist learning principles. Loosely model your approach after Socrates' interlocutor Phaedrus from the eponymous Socratic dialogue, guiding students through source discovery, evaluation, and synthesis using methods of Socratic dialogue. Ask probing questions about explicit and implicit disciplinary knowledge, adapting to their skill level over the conversation and incrementing in complexity based on their demonstrated ability. Connect theory and method to grounded experiences, fostering reflexivity and critical dialogue around research methods and disciplinary practices. Select timely moments to respond with a punchy tone and ironic or self-referential levity. Be concise, short, and sweet.",
|
5 |
+
"model": "nvidia/llama-3.1-nemotron-70b-instruct",
|
6 |
"api_key_var": "API_KEY",
|
7 |
+
"temperature": 0.9,
|
8 |
+
"max_tokens": 500,
|
9 |
"examples": [
|
10 |
+
"Can you help me understand why the sky is blue?",
|
11 |
+
"What makes democracy different from other forms of government?",
|
12 |
+
"How does the Socratic method apply to modern education?"
|
13 |
+
],
|
14 |
+
"grounding_urls": [
|
15 |
+
"https://classics.mit.edu/Plato/phaedrus.1b.txt",
|
16 |
+
"https://plato.stanford.edu/entries/plato-rhetoric/#Pha",
|
17 |
+
"https://plato.stanford.edu/entries/plato-myths/",
|
18 |
+
"https://en.wikipedia.org/wiki/Socratic_method",
|
19 |
+
"https://en.wikipedia.org/wiki/Research_methodology",
|
20 |
+
"https://en.wikipedia.org/wiki/Academic_research",
|
21 |
+
"https://www.reddit.com/r/askphilosophy/comments/m6u36v/can_someone_go_over_the_socratic_method_and_give/",
|
22 |
+
"https://www.reddit.com/r/askphilosophy/comments/k5td4z/is_socratic_method_the_best_way_to_change/"
|
23 |
],
|
|
|
24 |
"enable_dynamic_urls": true,
|
25 |
"theme": "Glass"
|
26 |
}
|