mnadell commited on
Commit
0b56691
Β·
verified Β·
1 Parent(s): 42716ce

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +560 -0
  2. config.json +12 -0
  3. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tempfile
3
+ import os
4
+ import requests
5
+ import json
6
+ import re
7
+ from bs4 import BeautifulSoup
8
+ from datetime import datetime
9
+ import urllib.parse
10
+
11
+
12
+ # Configuration
13
+ SPACE_NAME = "Writing 102: From Brainstorming to Research Questions"
14
+ SPACE_DESCRIPTION = "A bot that moves students from ideas to questions"
15
+ SYSTEM_PROMPT = """You are a pedagogically-minded academic assistant designed for an advanced undergraduate elective that explores historical and literary approaches and their relative affordances and constraints in telling stories of the past. You should help students develop a set of questions, rooted in their interests. These questions will provide the framework for a research project. DO NOT PROVIDE THE QUESTIONS. The students should develop their own questions, but you should ask questions to help students develop their own questions. Your. approach follows constructivist learning principles: build on students' prior knowledge, scaffold complex concepts through graduated questioning, and use Socratic dialogue to guide discovery. Provide concise, evidence-based explanations that connect students' ideas to extant scholarship in both fields, including methodological work, narrative history, social history, demographic history, close reading, literary analysis, creative nonfiction, and fiction. Each response should model critical thinking by acknowledging multiple perspectives, identifying assumptions, and revealing conceptual relationships. Conclude with open-ended questions that promote higher-order thinkingβ€”analysis, synthesis, or evaluationβ€”rather than recall. Ask questions. DO NOT GIVE STUDENTS FORMULAIC ANSWERS. Students should do the cognitive work. Your job is to help them develop but not give them their own individual and original ideas."""
16
+ MODEL = "anthropic/claude-3.5-haiku"
17
+ GROUNDING_URLS = []
18
+ # Get access code from environment variable for security
19
+ # If SPACE_ACCESS_CODE is not set, no access control is applied
20
+ ACCESS_CODE = os.environ.get("SPACE_ACCESS_CODE")
21
+ ENABLE_DYNAMIC_URLS = False
22
+
23
+ # Get API key from environment - customizable variable name with validation
24
+ API_KEY = os.environ.get("OPENROUTER_API_KEY")
25
+ if API_KEY:
26
+ API_KEY = API_KEY.strip() # Remove any whitespace
27
+ if not API_KEY: # Check if empty after stripping
28
+ API_KEY = None
29
+
30
+ # API Key validation and logging
31
+ def validate_api_key():
32
+ """Validate API key configuration with detailed logging"""
33
+ if not API_KEY:
34
+ print(f"⚠️ API KEY CONFIGURATION ERROR:")
35
+ print(f" Variable name: OPENROUTER_API_KEY")
36
+ print(f" Status: Not set or empty")
37
+ print(f" Action needed: Set 'OPENROUTER_API_KEY' in HuggingFace Space secrets")
38
+ print(f" Expected format: sk-or-xxxxxxxxxx")
39
+ return False
40
+ elif not API_KEY.startswith('sk-or-'):
41
+ print(f"⚠️ API KEY FORMAT WARNING:")
42
+ print(f" Variable name: OPENROUTER_API_KEY")
43
+ print(f" Current value: {API_KEY[:10]}..." if len(API_KEY) > 10 else API_KEY)
44
+ print(f" Expected format: sk-or-xxxxxxxxxx")
45
+ print(f" Note: OpenRouter keys should start with 'sk-or-'")
46
+ return True # Still try to use it
47
+ else:
48
+ print(f"βœ… API Key configured successfully")
49
+ print(f" Variable: OPENROUTER_API_KEY")
50
+ print(f" Format: Valid OpenRouter key")
51
+ return True
52
+
53
+ # Validate on startup
54
+ try:
55
+ API_KEY_VALID = validate_api_key()
56
+ except NameError:
57
+ # During template generation, API_KEY might not be defined yet
58
+ API_KEY_VALID = False
59
+
60
+ def validate_url_domain(url):
61
+ """Basic URL domain validation"""
62
+ try:
63
+ from urllib.parse import urlparse
64
+ parsed = urlparse(url)
65
+ # Check for valid domain structure
66
+ if parsed.netloc and '.' in parsed.netloc:
67
+ return True
68
+ except:
69
+ pass
70
+ return False
71
+
72
+ def fetch_url_content(url):
73
+ """Enhanced URL content fetching with improved compatibility and error handling"""
74
+ if not validate_url_domain(url):
75
+ return f"Invalid URL format: {url}"
76
+
77
+ try:
78
+ # Enhanced headers for better compatibility
79
+ headers = {
80
+ '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',
81
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
82
+ 'Accept-Language': 'en-US,en;q=0.5',
83
+ 'Accept-Encoding': 'gzip, deflate',
84
+ 'Connection': 'keep-alive'
85
+ }
86
+
87
+ response = requests.get(url, timeout=15, headers=headers)
88
+ response.raise_for_status()
89
+ soup = BeautifulSoup(response.content, 'html.parser')
90
+
91
+ # Enhanced content cleaning
92
+ for element in soup(["script", "style", "nav", "header", "footer", "aside", "form", "button"]):
93
+ element.decompose()
94
+
95
+ # Extract main content preferentially
96
+ 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
97
+ text = main_content.get_text()
98
+
99
+ # Enhanced text cleaning
100
+ lines = (line.strip() for line in text.splitlines())
101
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
102
+ text = ' '.join(chunk for chunk in chunks if chunk and len(chunk) > 2)
103
+
104
+ # Smart truncation - try to end at sentence boundaries
105
+ if len(text) > 4000:
106
+ truncated = text[:4000]
107
+ last_period = truncated.rfind('.')
108
+ if last_period > 3000: # If we can find a reasonable sentence break
109
+ text = truncated[:last_period + 1]
110
+ else:
111
+ text = truncated + "..."
112
+
113
+ return text if text.strip() else "No readable content found at this URL"
114
+
115
+ except requests.exceptions.Timeout:
116
+ return f"Timeout error fetching {url} (15s limit exceeded)"
117
+ except requests.exceptions.RequestException as e:
118
+ return f"Error fetching {url}: {str(e)}"
119
+ except Exception as e:
120
+ return f"Error processing content from {url}: {str(e)}"
121
+
122
+ def extract_urls_from_text(text):
123
+ """Extract URLs from text using regex with enhanced validation"""
124
+ import re
125
+ url_pattern = r'https?://[^\s<>"{}|\\^`\[\]"]+'
126
+ urls = re.findall(url_pattern, text)
127
+
128
+ # Basic URL validation and cleanup
129
+ validated_urls = []
130
+ for url in urls:
131
+ # Remove trailing punctuation that might be captured
132
+ url = url.rstrip('.,!?;:')
133
+ # Basic domain validation
134
+ if '.' in url and len(url) > 10:
135
+ validated_urls.append(url)
136
+
137
+ return validated_urls
138
+
139
+ # Global cache for URL content to avoid re-crawling in generated spaces
140
+ _url_content_cache = {}
141
+
142
+ def get_grounding_context():
143
+ """Fetch context from grounding URLs with caching"""
144
+ if not GROUNDING_URLS:
145
+ return ""
146
+
147
+ # Create cache key from URLs
148
+ cache_key = tuple(sorted([url for url in GROUNDING_URLS if url and url.strip()]))
149
+
150
+ # Check cache first
151
+ if cache_key in _url_content_cache:
152
+ return _url_content_cache[cache_key]
153
+
154
+ context_parts = []
155
+ for i, url in enumerate(GROUNDING_URLS, 1):
156
+ if url.strip():
157
+ content = fetch_url_content(url.strip())
158
+ # Add priority indicators
159
+ priority_label = "PRIMARY" if i <= 2 else "SECONDARY"
160
+ context_parts.append(f"[{priority_label}] Context from URL {i} ({url}):\n{content}")
161
+
162
+ if context_parts:
163
+ result = "\n\n" + "\n\n".join(context_parts) + "\n\n"
164
+ else:
165
+ result = ""
166
+
167
+ # Cache the result
168
+ _url_content_cache[cache_key] = result
169
+ return result
170
+
171
+ def export_conversation_to_markdown(conversation_history):
172
+ """Export conversation history to markdown format"""
173
+ if not conversation_history:
174
+ return "No conversation to export."
175
+
176
+ markdown_content = f"""# Conversation Export
177
+ Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
178
+
179
+ ---
180
+
181
+ """
182
+
183
+ message_pair_count = 0
184
+ for i, message in enumerate(conversation_history):
185
+ if isinstance(message, dict):
186
+ role = message.get('role', 'unknown')
187
+ content = message.get('content', '')
188
+
189
+ if role == 'user':
190
+ message_pair_count += 1
191
+ markdown_content += f"## User Message {message_pair_count}\n\n{content}\n\n"
192
+ elif role == 'assistant':
193
+ markdown_content += f"## Assistant Response {message_pair_count}\n\n{content}\n\n---\n\n"
194
+ elif isinstance(message, (list, tuple)) and len(message) >= 2:
195
+ # Handle legacy tuple format: ["user msg", "assistant msg"]
196
+ message_pair_count += 1
197
+ user_msg, assistant_msg = message[0], message[1]
198
+ if user_msg:
199
+ markdown_content += f"## User Message {message_pair_count}\n\n{user_msg}\n\n"
200
+ if assistant_msg:
201
+ markdown_content += f"## Assistant Response {message_pair_count}\n\n{assistant_msg}\n\n---\n\n"
202
+
203
+ return markdown_content
204
+
205
+
206
+ def generate_response(message, history):
207
+ """Generate response using OpenRouter API"""
208
+
209
+ # Enhanced API key validation with helpful messages
210
+ if not API_KEY:
211
+ error_msg = f"πŸ”‘ **API Key Required**\n\n"
212
+ error_msg += f"Please configure your OpenRouter API key:\n"
213
+ error_msg += f"1. Go to Settings (βš™οΈ) in your HuggingFace Space\n"
214
+ error_msg += f"2. Click 'Variables and secrets'\n"
215
+ error_msg += f"3. Add secret: **OPENROUTER_API_KEY**\n"
216
+ error_msg += f"4. Value: Your OpenRouter API key (starts with `sk-or-`)\n\n"
217
+ error_msg += f"Get your API key at: https://openrouter.ai/keys"
218
+ print(f"❌ API request failed: No API key configured for OPENROUTER_API_KEY")
219
+ return error_msg
220
+
221
+ # Get grounding context
222
+ grounding_context = get_grounding_context()
223
+
224
+
225
+ # If dynamic URLs are enabled, check message for URLs to fetch
226
+ if ENABLE_DYNAMIC_URLS:
227
+ urls_in_message = extract_urls_from_text(message)
228
+ if urls_in_message:
229
+ # Fetch content from URLs mentioned in the message
230
+ dynamic_context_parts = []
231
+ for url in urls_in_message[:3]: # Limit to 3 URLs per message
232
+ content = fetch_url_content(url)
233
+ dynamic_context_parts.append(f"\n\nDynamic context from {url}:\n{content}")
234
+ if dynamic_context_parts:
235
+ grounding_context += "\n".join(dynamic_context_parts)
236
+
237
+ # Build enhanced system prompt with grounding context
238
+ enhanced_system_prompt = SYSTEM_PROMPT + grounding_context
239
+
240
+ # Build messages array for the API
241
+ messages = [{"role": "system", "content": enhanced_system_prompt}]
242
+
243
+ # Add conversation history - handle both modern messages format and legacy tuples
244
+ for chat in history:
245
+ if isinstance(chat, dict):
246
+ # Modern format: {"role": "user", "content": "..."} or {"role": "assistant", "content": "..."}
247
+ messages.append(chat)
248
+ elif isinstance(chat, (list, tuple)) and len(chat) >= 2:
249
+ # Legacy format: ["user msg", "assistant msg"] or ("user msg", "assistant msg")
250
+ user_msg, assistant_msg = chat[0], chat[1]
251
+ if user_msg:
252
+ messages.append({"role": "user", "content": user_msg})
253
+ if assistant_msg:
254
+ messages.append({"role": "assistant", "content": assistant_msg})
255
+
256
+ # Add current message
257
+ messages.append({"role": "user", "content": message})
258
+
259
+ # Make API request with enhanced error handling
260
+ try:
261
+ print(f"πŸ”„ Making API request to OpenRouter...")
262
+ print(f" Model: {MODEL}")
263
+ print(f" Messages: {len(messages)} in conversation")
264
+
265
+ response = requests.post(
266
+ url="https://openrouter.ai/api/v1/chat/completions",
267
+ headers={
268
+ "Authorization": f"Bearer {API_KEY}",
269
+ "Content-Type": "application/json",
270
+ "HTTP-Referer": "https://huggingface.co", # Required by some providers
271
+ "X-Title": "HuggingFace Space" # Helpful for tracking
272
+ },
273
+ json={
274
+ "model": MODEL,
275
+ "messages": messages,
276
+ "temperature": 1.3,
277
+ "max_tokens": 1700
278
+ },
279
+ timeout=30
280
+ )
281
+
282
+ print(f"πŸ“‘ API Response: {response.status_code}")
283
+
284
+ if response.status_code == 200:
285
+ try:
286
+ result = response.json()
287
+
288
+ # Enhanced validation of API response structure
289
+ if 'choices' not in result or not result['choices']:
290
+ print(f"⚠️ API response missing choices: {result}")
291
+ return "API Error: No response choices available"
292
+ elif 'message' not in result['choices'][0]:
293
+ print(f"⚠️ API response missing message: {result}")
294
+ return "API Error: No message in response"
295
+ elif 'content' not in result['choices'][0]['message']:
296
+ print(f"⚠️ API response missing content: {result}")
297
+ return "API Error: No content in message"
298
+ else:
299
+ content = result['choices'][0]['message']['content']
300
+
301
+ # Check for empty content
302
+ if not content or content.strip() == "":
303
+ print(f"⚠️ API returned empty content")
304
+ return "API Error: Empty response content"
305
+
306
+ print(f"βœ… API request successful")
307
+ return content
308
+
309
+ except (KeyError, IndexError, json.JSONDecodeError) as e:
310
+ print(f"❌ Failed to parse API response: {str(e)}")
311
+ return f"API Error: Failed to parse response - {str(e)}"
312
+ elif response.status_code == 401:
313
+ error_msg = f"πŸ” **Authentication Error**\n\n"
314
+ error_msg += f"Your API key appears to be invalid or expired.\n\n"
315
+ error_msg += f"**Troubleshooting:**\n"
316
+ error_msg += f"1. Check that your **OPENROUTER_API_KEY** secret is set correctly\n"
317
+ error_msg += f"2. Verify your API key at: https://openrouter.ai/keys\n"
318
+ error_msg += f"3. Ensure your key starts with `sk-or-`\n"
319
+ error_msg += f"4. Check that you have credits on your OpenRouter account"
320
+ print(f"❌ API authentication failed: {response.status_code} - {response.text[:200]}")
321
+ return error_msg
322
+ elif response.status_code == 429:
323
+ error_msg = f"⏱️ **Rate Limit Exceeded**\n\n"
324
+ error_msg += f"Too many requests. Please wait a moment and try again.\n\n"
325
+ error_msg += f"**Troubleshooting:**\n"
326
+ error_msg += f"1. Wait 30-60 seconds before trying again\n"
327
+ error_msg += f"2. Check your OpenRouter usage limits\n"
328
+ error_msg += f"3. Consider upgrading your OpenRouter plan"
329
+ print(f"❌ Rate limit exceeded: {response.status_code}")
330
+ return error_msg
331
+ elif response.status_code == 400:
332
+ try:
333
+ error_data = response.json()
334
+ error_message = error_data.get('error', {}).get('message', 'Unknown error')
335
+ except:
336
+ error_message = response.text
337
+
338
+ error_msg = f"⚠️ **Request Error**\n\n"
339
+ error_msg += f"The API request was invalid:\n"
340
+ error_msg += f"`{error_message}`\n\n"
341
+ if "model" in error_message.lower():
342
+ error_msg += f"**Model Issue:** The model `{MODEL}` may not be available.\n"
343
+ error_msg += f"Try switching to a different model in your Space configuration."
344
+ print(f"❌ Bad request: {response.status_code} - {error_message}")
345
+ return error_msg
346
+ else:
347
+ error_msg = f"🚫 **API Error {response.status_code}**\n\n"
348
+ error_msg += f"An unexpected error occurred. Please try again.\n\n"
349
+ error_msg += f"If this persists, check:\n"
350
+ error_msg += f"1. OpenRouter service status\n"
351
+ error_msg += f"2. Your API key and credits\n"
352
+ error_msg += f"3. The model availability"
353
+ print(f"❌ API error: {response.status_code} - {response.text[:200]}")
354
+ return error_msg
355
+
356
+ except requests.exceptions.Timeout:
357
+ error_msg = f"⏰ **Request Timeout**\n\n"
358
+ error_msg += f"The API request took too long (30s limit).\n\n"
359
+ error_msg += f"**Troubleshooting:**\n"
360
+ error_msg += f"1. Try again with a shorter message\n"
361
+ error_msg += f"2. Check your internet connection\n"
362
+ error_msg += f"3. Try a different model"
363
+ print(f"❌ Request timeout after 30 seconds")
364
+ return error_msg
365
+ except requests.exceptions.ConnectionError:
366
+ error_msg = f"🌐 **Connection Error**\n\n"
367
+ error_msg += f"Could not connect to OpenRouter API.\n\n"
368
+ error_msg += f"**Troubleshooting:**\n"
369
+ error_msg += f"1. Check your internet connection\n"
370
+ error_msg += f"2. Check OpenRouter service status\n"
371
+ error_msg += f"3. Try again in a few moments"
372
+ print(f"❌ Connection error to OpenRouter API")
373
+ return error_msg
374
+ except Exception as e:
375
+ error_msg = f"❌ **Unexpected Error**\n\n"
376
+ error_msg += f"An unexpected error occurred:\n"
377
+ error_msg += f"`{str(e)}`\n\n"
378
+ error_msg += f"Please try again or contact support if this persists."
379
+ print(f"❌ Unexpected error: {str(e)}")
380
+ return error_msg
381
+
382
+ # Access code verification
383
+ access_granted = gr.State(False)
384
+ _access_granted_global = False # Global fallback
385
+
386
+ def verify_access_code(code):
387
+ """Verify the access code"""
388
+ global _access_granted_global
389
+ if ACCESS_CODE is None:
390
+ _access_granted_global = True
391
+ return gr.update(visible=False), gr.update(visible=True), gr.update(value=True)
392
+
393
+ if code == ACCESS_CODE:
394
+ _access_granted_global = True
395
+ return gr.update(visible=False), gr.update(visible=True), gr.update(value=True)
396
+ else:
397
+ _access_granted_global = False
398
+ return gr.update(visible=True, value="❌ Incorrect access code. Please try again."), gr.update(visible=False), gr.update(value=False)
399
+
400
+ def protected_generate_response(message, history):
401
+ """Protected response function that checks access"""
402
+ # Check if access is granted via the global variable
403
+ if ACCESS_CODE is not None and not _access_granted_global:
404
+ return "Please enter the access code to continue."
405
+ return generate_response(message, history)
406
+
407
+ # Global variable to store chat history for export
408
+ chat_history_store = []
409
+
410
+ def store_and_generate_response(message, history):
411
+ """Wrapper function that stores history and generates response"""
412
+ global chat_history_store
413
+
414
+ # Generate response using the protected function
415
+ response = protected_generate_response(message, history)
416
+
417
+ # Convert current history to the format we need for export
418
+ # history comes in as [["user1", "bot1"], ["user2", "bot2"], ...]
419
+ chat_history_store = []
420
+ if history:
421
+ for exchange in history:
422
+ if isinstance(exchange, (list, tuple)) and len(exchange) >= 2:
423
+ chat_history_store.append({"role": "user", "content": exchange[0]})
424
+ chat_history_store.append({"role": "assistant", "content": exchange[1]})
425
+
426
+ # Add the current exchange
427
+ chat_history_store.append({"role": "user", "content": message})
428
+ chat_history_store.append({"role": "assistant", "content": response})
429
+
430
+ return response
431
+
432
+ def export_current_conversation():
433
+ """Export the current conversation"""
434
+ if not chat_history_store:
435
+ return gr.update(visible=False)
436
+
437
+ markdown_content = export_conversation_to_markdown(chat_history_store)
438
+
439
+ # Save to temporary file
440
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
441
+ f.write(markdown_content)
442
+ temp_file = f.name
443
+
444
+ return gr.update(value=temp_file, visible=True)
445
+
446
+ def export_conversation(history):
447
+ """Export conversation to markdown file"""
448
+ if not history:
449
+ return gr.update(visible=False)
450
+
451
+ markdown_content = export_conversation_to_markdown(history)
452
+
453
+ # Save to temporary file
454
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
455
+ f.write(markdown_content)
456
+ temp_file = f.name
457
+
458
+ return gr.update(value=temp_file, visible=True)
459
+
460
+ # Configuration status display
461
+ def get_configuration_status():
462
+ """Generate a configuration status message for display"""
463
+ status_parts = []
464
+
465
+ if API_KEY_VALID:
466
+ status_parts.append("βœ… **API Key:** Configured and valid")
467
+ else:
468
+ status_parts.append("❌ **API Key:** Not configured - Set `OPENROUTER_API_KEY` in Space secrets")
469
+
470
+ status_parts.append(f"πŸ€– **Model:** {MODEL}")
471
+ status_parts.append(f"🌑️ **Temperature:** 1.3")
472
+ status_parts.append(f"πŸ“ **Max Tokens:** 1700")
473
+
474
+ # URL Grounding details
475
+ if GROUNDING_URLS:
476
+ status_parts.append(f"πŸ”— **URL Grounding:** {len(GROUNDING_URLS)} URLs configured")
477
+ # Show first few URLs as examples
478
+ for i, url in enumerate(GROUNDING_URLS[:3], 1):
479
+ priority_label = "Primary" if i <= 2 else "Secondary"
480
+ status_parts.append(f" - [{priority_label}] {url}")
481
+ if len(GROUNDING_URLS) > 3:
482
+ status_parts.append(f" - ... and {len(GROUNDING_URLS) - 3} more URLs")
483
+ else:
484
+ status_parts.append("πŸ”— **URL Grounding:** No URLs configured")
485
+
486
+ if ENABLE_DYNAMIC_URLS:
487
+ status_parts.append("πŸ”„ **Dynamic URLs:** Enabled")
488
+ else:
489
+ status_parts.append("πŸ”„ **Dynamic URLs:** Disabled")
490
+
491
+ if ACCESS_CODE is not None:
492
+ status_parts.append("πŸ” **Access Control:** Enabled")
493
+ else:
494
+ status_parts.append("🌐 **Access:** Public Chatbot")
495
+
496
+ # System Prompt (add at the end)
497
+ status_parts.append("") # Empty line for spacing
498
+ status_parts.append("**System Prompt:**")
499
+ status_parts.append(f"{SYSTEM_PROMPT}")
500
+
501
+ return "\n".join(status_parts)
502
+
503
+ # Create interface with access code protection
504
+ with gr.Blocks(title=SPACE_NAME) as demo:
505
+ gr.Markdown(f"# {SPACE_NAME}")
506
+ gr.Markdown(SPACE_DESCRIPTION)
507
+
508
+ # Access code section (shown only if ACCESS_CODE is set)
509
+ with gr.Column(visible=(ACCESS_CODE is not None)) as access_section:
510
+ gr.Markdown("### πŸ” Access Required")
511
+ gr.Markdown("Please enter the access code provided by your instructor:")
512
+
513
+ access_input = gr.Textbox(
514
+ label="Access Code",
515
+ placeholder="Enter access code...",
516
+ type="password"
517
+ )
518
+ access_btn = gr.Button("Submit", variant="primary")
519
+ access_error = gr.Markdown(visible=False)
520
+
521
+ # Main chat interface (hidden until access granted)
522
+ with gr.Column(visible=(ACCESS_CODE is None)) as chat_section:
523
+ chat_interface = gr.ChatInterface(
524
+ fn=store_and_generate_response, # Use wrapper function to store history
525
+ title="", # Title already shown above
526
+ description="", # Description already shown above
527
+ examples=['Here are my ideas so far? How can I transform them into a set of research questions?', 'How will my questions differ if I am writing history or fiction?'],
528
+ type="messages" # Use modern message format for better compatibility
529
+ )
530
+
531
+ # Export functionality
532
+ with gr.Row():
533
+ export_btn = gr.Button("πŸ“₯ Export Conversation", variant="secondary", size="sm")
534
+ export_file = gr.File(label="Download Conversation", visible=False)
535
+
536
+ # Connect export functionality
537
+ export_btn.click(
538
+ export_current_conversation,
539
+ outputs=[export_file]
540
+ )
541
+
542
+ # Configuration status (always visible)
543
+ with gr.Accordion("πŸ“Š Configuration Status", open=not API_KEY_VALID):
544
+ gr.Markdown(get_configuration_status())
545
+
546
+ # Connect access verification
547
+ if ACCESS_CODE is not None:
548
+ access_btn.click(
549
+ verify_access_code,
550
+ inputs=[access_input],
551
+ outputs=[access_error, chat_section, access_granted]
552
+ )
553
+ access_input.submit(
554
+ verify_access_code,
555
+ inputs=[access_input],
556
+ outputs=[access_error, chat_section, access_granted]
557
+ )
558
+
559
+ if __name__ == "__main__":
560
+ demo.launch()
config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "Writing 102: From Brainstorming to Research Questions",
3
+ "description": "A bot that moves students from ideas to questions",
4
+ "system_prompt": "You are a pedagogically-minded academic assistant designed for an advanced undergraduate elective that explores historical and literary approaches and their relative affordances and constraints in telling stories of the past. You should help students develop a set of questions, rooted in their interests. These questions will provide the framework for a research project. DO NOT PROVIDE THE QUESTIONS. The students should develop their own questions, but you should ask questions to help students develop their own questions. Your. approach follows constructivist learning principles: build on students' prior knowledge, scaffold complex concepts through graduated questioning, and use Socratic dialogue to guide discovery. Provide concise, evidence-based explanations that connect students' ideas to extant scholarship in both fields, including methodological work, narrative history, social history, demographic history, close reading, literary analysis, creative nonfiction, and fiction. Each response should model critical thinking by acknowledging multiple perspectives, identifying assumptions, and revealing conceptual relationships. Conclude with open-ended questions that promote higher-order thinking\u2014analysis, synthesis, or evaluation\u2014rather than recall. Ask questions. DO NOT GIVE STUDENTS FORMULAIC ANSWERS. Students should do the cognitive work. Your job is to help them develop but not give them their own individual and original ideas.",
5
+ "model": "anthropic/claude-3.5-haiku",
6
+ "api_key_var": "OPENROUTER_API_KEY",
7
+ "temperature": 1.3,
8
+ "max_tokens": 1700,
9
+ "examples": "['Here are my ideas so far? How can I transform them into a set of research questions?', 'How will my questions differ if I am writing history or fiction?']",
10
+ "grounding_urls": "[]",
11
+ "enable_dynamic_urls": false
12
+ }
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio>=5.38.0
2
+ requests>=2.32.3
3
+ beautifulsoup4>=4.12.3
4
+ python-dotenv>=1.0.0