keefereuther Cursor commited on
Commit
83e112e
·
1 Parent(s): 10a471f

Migrate to TritonAI and add S26 exam review workflow.

Browse files

Switch from OpenAI Responses to LiteLLM chat completions, add Spring 2026 exam question bank and PDF resources, and fix exam-review payload handling and Connect Terms demo instructions.

Co-authored-by: Cursor <cursoragent@cursor.com>

Files changed (9) hide show
  1. .env.example +3 -0
  2. .gitattributes +2 -0
  3. BILD5_S26_Midterm.pdf +3 -0
  4. BILD5_SP26_Final.pdf +3 -0
  5. README.md +66 -32
  6. app.py +373 -190
  7. config.py +83 -303
  8. exam_questions_s26.py +203 -0
  9. requirements.txt +3 -4
.env.example ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # TritonAI LiteLLM endpoint (UCSD)
2
+ OPENAI_API_KEY=
3
+ OPENAI_API_BASE=https://tritonai-api.ucsd.edu
.gitattributes CHANGED
@@ -37,3 +37,5 @@ BILD_5_Syllabus_Reuther_SP25.pdf filter=lfs diff=lfs merge=lfs -text
37
  BILD_5_Syllabus_Reuther_F25[[:space:]](1).pdf filter=lfs diff=lfs merge=lfs -text
38
  BILD_5_Syllabus_Reuther_F25.pdf filter=lfs diff=lfs merge=lfs -text
39
  BILD_5_Syllabus_Reuther_SP26.pdf filter=lfs diff=lfs merge=lfs -text
 
 
 
37
  BILD_5_Syllabus_Reuther_F25[[:space:]](1).pdf filter=lfs diff=lfs merge=lfs -text
38
  BILD_5_Syllabus_Reuther_F25.pdf filter=lfs diff=lfs merge=lfs -text
39
  BILD_5_Syllabus_Reuther_SP26.pdf filter=lfs diff=lfs merge=lfs -text
40
+ BILD5_S26_Midterm.pdf filter=lfs diff=lfs merge=lfs -text
41
+ BILD5_SP26_Final.pdf filter=lfs diff=lfs merge=lfs -text
BILD5_S26_Midterm.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:40ecab372c85d2445c959e6fcd8bfcf8e43ab433802e44734c8cd27b9e032e89
3
+ size 378640
BILD5_SP26_Final.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7cbb95637e8e39071bb4f9104faf6d3e951aaffeb643b0628e1a1bf4c7328bf
3
+ size 464994
README.md CHANGED
@@ -13,14 +13,14 @@ short_description: AI-enhanced study app for UCSD BILD5 biology students
13
 
14
  # Schema Study: An AI-Enhanced Study App for Biology Students
15
 
16
- Schema Study is a modern, interactive study app designed to help biology students master core course concepts through AI-powered conversations. The app leverages OpenAI's latest GPT models via the Responses API to provide instant feedback, Socratic questioning, and personalized study support.
17
 
18
  ## Features
19
  - **Password Protection:** Secure access for your class or group.
20
  - **Customizable Terms:** Use your own CSV file of terms and definitions.
21
- - **Prompt Templates:** Engage with the material using creative, research-based prompts including midterm review.
22
- - **AI-Enhanced Feedback:** Get instant, formative feedback and guidance using GPT-5.1 (default) or GPT-4.1.
23
- - **Web Search Support:** Optional web search functionality for current information and citations (configurable in `config.py`).
24
  - **Real-Time Streaming:** Live token-by-token response streaming with visual typing indicator.
25
  - **Professional, Accessible UI:** Clean, modern design with a color palette for clarity and focus.
26
 
@@ -28,7 +28,15 @@ Schema Study is a modern, interactive study app designed to help biology student
28
  1. **Access the App:** Go to your Hugging Face Space URL. Enter the password provided by your instructor.
29
  2. **Select a Term:** Use the dropdown to pick a course term.
30
  3. **Start Studying:** Respond to the prompt or use a template button to begin your session.
31
- 4. **Chat with the AI:** Ask questions, answer prompts, and explore the term in depth.
 
 
 
 
 
 
 
 
32
 
33
  ## How to Use (Instructors)
34
 
@@ -42,21 +50,38 @@ Schema Study is a modern, interactive study app designed to help biology student
42
  2. **Edit Configuration:**
43
  - Update `config.py` for your course (title, instructions, prompt templates, etc).
44
  - Configure AI model settings:
45
- - `ai_model`: Choose "gpt-5.1" (default) or "gpt-4.1"
46
- - `reasoning_effort`: For GPT-5.1, set to "none" (fastest), "minimal", "low", or "medium"
47
- - `enable_web_search`: Set to `True` or `False` (default: True)
48
  - Place your terms CSV (e.g., `terms.csv`) in the root directory. Format: first column = term, second column = context/definition.
49
 
50
- 3. **Set Secrets:**
51
- - Create `.streamlit/secrets.toml` file locally or use Hugging Face Space secrets:
52
- ```toml
53
- username = "your_username"
54
- password = "your_password"
55
- OPENAI_API_KEY = "your_openai_api_key"
56
- ```
57
- - For Hugging Face Spaces, go to **Settings > Repository secrets** and add the same keys.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
- 4. **Push Changes:**
60
  ```bash
61
  git add .
62
  git commit -m "Update configuration and terms"
@@ -64,17 +89,21 @@ Schema Study is a modern, interactive study app designed to help biology student
64
  ```
65
 
66
  ### Model Selection Guide
67
- - **GPT-5.1** (default): Best for most use cases, fastest with reasoning="none", supports web search
68
- - **GPT-4.1**: Use if you need temperature control or prefer non-reasoning model, excellent web search support
 
69
 
70
  ## Configuration
71
 
72
  ### AI Model Settings (`config.py`)
73
- - **Default Model:** GPT-5.1 with reasoning="none" for faster responses
74
- - **Alternative Model:** GPT-4.1 with temperature control
75
- - **Web Search:** Configurable via `enable_web_search` (default: True)
76
- - **Reasoning Effort:** Configurable for GPT-5.1 (options: "none", "minimal", "low", "medium")
77
- - **Temperature:** Configurable for GPT-4.1 (0.0-2.0)
 
 
 
78
 
79
  ### Other Settings
80
  - All settings are in `config.py` (title, instructions, prompt templates, resources, AI model parameters, etc).
@@ -84,23 +113,28 @@ Schema Study is a modern, interactive study app designed to help biology student
84
  ## Technical Details
85
 
86
  ### API & Models
87
- - **API Framework:** OpenAI Responses API (streaming-enabled)
88
- - **Supported Models:** GPT-5.1 (default), GPT-4.1
 
89
  - **Streaming:** Real-time token-by-token response streaming
90
  - **Inactivity Guard:** Streaming stops after 60s of no server deltas
91
 
92
  ### File Structure
93
- - `app.py` — Main Streamlit app with Responses API integration
94
- - `config.py` — All app settings and customization (model selection, web search, prompt templates)
95
- - `.streamlit/secrets.toml` — Authentication credentials and API key (not tracked in git)
 
 
96
  - `requirements.txt` — Python dependencies
97
  - `terms.csv` — Your course terms and definitions (CSV format: term, context)
98
- - `BILD_5_Syllabus_Reuther_SP25.pdf` — Example resource
99
- - `BILD 5 F25 Midterm Exam.pdf` — Midterm exam resource
 
 
100
 
101
  ## License
102
  This project is licensed under the GNU GPL-3 License. See the [LICENSE](LICENSE) file for details.
103
 
104
  ## Acknowledgments
105
 
106
- Developed by Keefe Reuther, Assistant Teaching Professor in the UC San Diego School of Biological Sciences. Special thanks to Dr. Liam O Mueller and the members of the Reuther Lab for their support and contributions.
 
13
 
14
  # Schema Study: An AI-Enhanced Study App for Biology Students
15
 
16
+ Schema Study is a modern, interactive study app designed to help biology students master core course concepts through AI-powered conversations. The app routes requests through [TritonAI](https://tritonai.ucsd.edu) via LiteLLM to provide instant feedback, Socratic questioning, and personalized study support.
17
 
18
  ## Features
19
  - **Password Protection:** Secure access for your class or group.
20
  - **Customizable Terms:** Use your own CSV file of terms and definitions.
21
+ - **Prompt Templates:** Engage with the material using creative, research-based prompts including exam question review (S26 midterm and final).
22
+ - **AI-Enhanced Feedback:** Get instant, formative feedback and guidance via TritonAI models.
23
+ - **File & Image Uploads:** Students can attach images, PDFs, text files, audio, and video in chat.
24
  - **Real-Time Streaming:** Live token-by-token response streaming with visual typing indicator.
25
  - **Professional, Accessible UI:** Clean, modern design with a color palette for clarity and focus.
26
 
 
28
  1. **Access the App:** Go to your Hugging Face Space URL. Enter the password provided by your instructor.
29
  2. **Select a Term:** Use the dropdown to pick a course term.
30
  3. **Start Studying:** Respond to the prompt or use a template button to begin your session.
31
+ 4. **Chat with the AI:** Ask questions, answer prompts, and explore the term in depth. Use the **+** button in the chat box to attach images or files.
32
+
33
+ ### Supported uploads
34
+ Students can attach files via the chat **+** button. The model can analyze:
35
+ - **Images:** JPG, PNG, GIF, WebP (sent to the vision-capable model)
36
+ - **Documents:** PDF (text extracted), TXT, CSV, MD, JSON, PY, QMD
37
+ - **Audio / video:** MP3, WAV, M4A, MP4, MOV, WebM (uploaded and shown in chat; the model receives a filename note only — no transcription)
38
+
39
+ The AI still responds with **text only** (no generated images, audio, or downloadable files).
40
 
41
  ## How to Use (Instructors)
42
 
 
50
  2. **Edit Configuration:**
51
  - Update `config.py` for your course (title, instructions, prompt templates, etc).
52
  - Configure AI model settings:
53
+ - `ai_model`: TritonAI model name, e.g. `"openai/claude-sonnet-5"`, `"openai/gemini-3.5-flash"`, or `"openai/gpt-4.1"`
54
+ - `temperature`: Controls response randomness (default: 0.1)
55
+ - `max_tokens`: Maximum response length (default: 1000)
56
  - Place your terms CSV (e.g., `terms.csv`) in the root directory. Format: first column = term, second column = context/definition.
57
 
58
+ 3. **Set Credentials (local development):**
59
+
60
+ **TritonAI API** — create a `.env` file in the project root (copy from `.env.example`):
61
+ ```bash
62
+ OPENAI_API_KEY=your_tritonai_key
63
+ OPENAI_API_BASE=https://tritonai-api.ucsd.edu
64
+ ```
65
+
66
+ **Login gate** — create `.streamlit/secrets.toml`:
67
+ ```toml
68
+ username = "your_username"
69
+ password = "your_password"
70
+ ```
71
+
72
+ On Hugging Face Spaces, set the same keys as Space secrets (Settings > Repository secrets):
73
+ - `OPENAI_API_KEY`
74
+ - `OPENAI_API_BASE`
75
+ - `username`
76
+ - `password`
77
+
78
+ 4. **Install and run locally:**
79
+ ```bash
80
+ pip install -r requirements.txt
81
+ streamlit run app.py
82
+ ```
83
 
84
+ 5. **Push Changes:**
85
  ```bash
86
  git add .
87
  git commit -m "Update configuration and terms"
 
89
  ```
90
 
91
  ### Model Selection Guide
92
+ - **openai/claude-sonnet-5** (default): Strong general-purpose tutor for study conversations
93
+ - **openai/gemini-3.5-flash**: Faster responses, good for high-volume use
94
+ - **openai/gpt-4.1**: Alternative OpenAI-family model via TritonAI
95
 
96
  ## Configuration
97
 
98
  ### AI Model Settings (`config.py`)
99
+ - **Default Model:** `openai/claude-sonnet-5` via TritonAI
100
+ - **Temperature:** 0.0–2.0 (default: 0.1)
101
+ - **Max tokens:** Response length limit (default: 1000)
102
+
103
+ ### Credentials
104
+ - **`.env`** — TritonAI API key and base URL (local dev; gitignored)
105
+ - **`.streamlit/secrets.toml`** — Login username and password (local dev; gitignored)
106
+ - **Hugging Face Space secrets** — Same keys for deployed Spaces
107
 
108
  ### Other Settings
109
  - All settings are in `config.py` (title, instructions, prompt templates, resources, AI model parameters, etc).
 
113
  ## Technical Details
114
 
115
  ### API & Models
116
+ - **API Framework:** LiteLLM chat completions (streaming-enabled)
117
+ - **Endpoint:** TritonAI at `https://tritonai-api.ucsd.edu`
118
+ - **Supported Models:** `openai/claude-sonnet-5`, `openai/gemini-3.5-flash`, `openai/gpt-4.1`
119
  - **Streaming:** Real-time token-by-token response streaming
120
  - **Inactivity Guard:** Streaming stops after 60s of no server deltas
121
 
122
  ### File Structure
123
+ - `app.py` — Main Streamlit app with LiteLLM/TritonAI integration
124
+ - `config.py` — All app settings and customization (model selection, prompt templates)
125
+ - `.env` — TritonAI API credentials for local development (not tracked in git)
126
+ - `.env.example` — Template for `.env`
127
+ - `.streamlit/secrets.toml` — Login credentials for local development (not tracked in git)
128
  - `requirements.txt` — Python dependencies
129
  - `terms.csv` — Your course terms and definitions (CSV format: term, context)
130
+ - `exam_questions_s26.py` — Spring 2026 midterm and final question bank for the Review exam questions template
131
+ - `BILD5_S26_Midterm.pdf` — Spring 2026 midterm exam (sidebar download)
132
+ - `BILD5_SP26_Final.pdf` — Spring 2026 final exam (sidebar download)
133
+ - `BILD_5_Syllabus_Reuther_SP26.pdf` — Course syllabus
134
 
135
  ## License
136
  This project is licensed under the GNU GPL-3 License. See the [LICENSE](LICENSE) file for details.
137
 
138
  ## Acknowledgments
139
 
140
+ Developed by Keefe Reuther, Assistant Teaching Professor in the UC San Diego School of Biological Sciences. Special thanks to Dr. Liam O Mueller and the members of the Reuther Lab for their support and contributions.
app.py CHANGED
@@ -10,10 +10,18 @@ import hmac # Secure password validation
10
  import pandas as pd # Data handling
11
  import os # File operations
12
  import logging # Logging functionality
13
- import time # Time operations for retry logic
 
 
 
14
  import config # Local configuration module
15
- from openai import OpenAI # OpenAI API client
16
- from typing import Dict, List, Any, Optional # Type hints
 
 
 
 
 
17
 
18
  # Set up logging to track app activity
19
  logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
@@ -165,77 +173,298 @@ st.markdown("""
165
  """, unsafe_allow_html=True)
166
 
167
  ############################################################################################################
168
- # Model Configuration - Responses API model capabilities
169
  ############################################################################################################
170
 
171
- # Model configurations with capability flags
172
- MODEL_CONFIGS = {
173
- "gpt-5.1": {
174
- "api_type": "responses",
175
- "supports_reasoning": True,
176
- "supports_verbosity": False,
177
- "supports_temperature": False, # do NOT send temperature
178
- "supports_max_tokens": True, # maps to max_output_tokens
179
- "supports_web_search": True, # Supported
180
- },
181
- "gpt-4.1": {
182
- "api_type": "responses",
183
- "supports_reasoning": False,
184
- "supports_verbosity": False,
185
- "supports_temperature": True,
186
- "supports_max_tokens": True, # maps to max_output_tokens
187
- "supports_web_search": True, # Confirmed working
188
- },
 
 
 
 
 
 
189
  }
 
 
 
 
 
 
 
 
190
 
191
- def get_model_config(model: str) -> dict:
192
- """Get configuration for a specific model"""
193
- return MODEL_CONFIGS.get(
194
- model,
195
- {
196
- "api_type": "responses",
197
- "supports_reasoning": False,
198
- "supports_verbosity": False,
199
- "supports_temperature": True,
200
- "supports_max_tokens": True,
201
- "supports_web_search": False,
202
- },
203
  )
204
 
205
- def build_request_data(
206
- model: str,
207
- messages: List[Dict[str, str]],
208
- reasoning_effort: Optional[str] = None,
209
- temperature: Optional[float] = None,
210
- max_tokens: Optional[int] = None,
211
- enable_web_search: bool = False,
212
- ) -> dict:
213
- """Build a Responses API request body using capability flags."""
214
- model_config = get_model_config(model)
215
-
216
- # Base payload
217
- request_data = {"model": model, "input": messages}
218
-
219
- # Web search tool (if enabled and supported by model)
220
- if enable_web_search and model_config.get("supports_web_search", False):
221
- request_data["tools"] = [{"type": "web_search", "search_context_size": "low"}]
222
- request_data["tool_choice"] = "auto" # Let model decide when to search
223
- # Web search is incompatible with reasoning effort, so disable it
224
- reasoning_effort = None
225
-
226
- # GPT-5.1: reasoning (top-level) - only if web search is not enabled
227
- if model_config["supports_reasoning"] and reasoning_effort and not enable_web_search:
228
- request_data["reasoning"] = {"effort": reasoning_effort}
229
-
230
- # Temperature (only if supported)
231
- if model_config["supports_temperature"] and temperature is not None:
232
- request_data["temperature"] = temperature
233
-
234
- # Map max_tokens -> Responses max_output_tokens
235
- if model_config["supports_max_tokens"] and max_tokens is not None:
236
- request_data["max_output_tokens"] = max_tokens
237
-
238
- return request_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
 
240
  ############################################################################################################
241
  # Initialize all session state variables - Persistent data between app reruns
@@ -257,7 +486,16 @@ if 'old_term' not in st.session_state:
257
  if 'seen_terms' not in st.session_state:
258
  st.session_state.seen_terms = set() # Set of viewed terms
259
  if 'openai_model' not in st.session_state:
260
- st.session_state.openai_model = config.ai_model # AI model being used
 
 
 
 
 
 
 
 
 
261
 
262
  ############################################################################################################
263
  # Password protection - User authentication functionality
@@ -368,6 +606,8 @@ with left_col:
368
  # Update session state
369
  st.session_state.selected_context = term_context
370
  st.session_state.selected_term = selected_term
 
 
371
 
372
  # Create initial user message
373
  user_message = f"What is one thing you know about '{selected_term}'? What do you want to know about it? This could include a definition, examples, misconceptions, associations with other course terms, opinions, etc. You may also choose one of the template buttons on the left to help you get started."
@@ -390,6 +630,7 @@ with left_col:
390
  "Two Truths & a Lie": "🎮",
391
  "Connect Terms": "🔄",
392
  "Schema Map": "🗺️",
 
393
  "Create a Study Plan": "📚"
394
  }
395
 
@@ -409,6 +650,24 @@ with left_col:
409
  # Create button and handle click
410
  if btn_cols[i].button(button_text, key=f"btn_{row}_{i}"):
411
  # Format template with appropriate variables
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412
  if "term_list" in template["template"]:
413
  formatted_content = template["template"].format(term=selected_term, term_list=term_list)
414
  else:
@@ -431,7 +690,7 @@ with right_col:
431
  for message in st.session_state["display_messages"][1:]:
432
  if message["role"] == "user":
433
  with st.chat_message("user"):
434
- st.markdown(message["content"])
435
  else:
436
  with st.chat_message("assistant"):
437
  st.markdown(message["content"])
@@ -439,149 +698,72 @@ with right_col:
439
  # Generate and display AI response when triggered
440
  if st.session_state.get("trigger_llm", False):
441
  try:
442
- # Initialize OpenAI client
443
- client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
444
-
445
- # Generate system message with term context
446
- system_message = config.term_prompt(
447
- selected_term=st.session_state.selected_term,
448
- selected_context=st.session_state.selected_context,
449
- term_list=term_list
450
- )
451
-
 
452
  # Prepare messages for API call
453
- messages = [{"role": "system", "content": system_message}] + [
454
- {"role": m["role"], "content": m["content"]}
455
- for m in st.session_state["display_messages"]
456
- ]
457
-
458
- # Get model configuration
459
- model_config = get_model_config(st.session_state["openai_model"])
460
-
461
- # Prepare parameters based on model support
462
- reasoning_effort_param = None
463
- temperature_param = None
464
- enable_web_search_param = False
465
-
466
- # Check if web search is enabled and supported
467
- if config.enable_web_search and model_config.get("supports_web_search", False):
468
- enable_web_search_param = True
469
- # Web search disables reasoning automatically
470
- reasoning_effort_param = None
471
- elif model_config["supports_reasoning"]:
472
- reasoning_effort_param = config.reasoning_effort
473
-
474
- if model_config["supports_temperature"]:
475
- temperature_param = config.temperature
476
-
477
- # Build request data for Responses API
478
- request_data = build_request_data(
479
- model=st.session_state["openai_model"],
480
- messages=messages,
481
- reasoning_effort=reasoning_effort_param,
482
- temperature=temperature_param,
483
- max_tokens=config.max_tokens,
484
- enable_web_search=enable_web_search_param,
485
- )
486
-
487
- # Create streaming response using Responses API
488
  with st.chat_message("assistant"):
489
  message_placeholder = st.empty()
490
- buf: List[str] = [] # collect deltas safely
491
- last_delta_ts = time.time()
492
- inactivity_limit_s = 60 # stop if no deltas for 60s
493
-
494
  try:
495
- # Stream events with timeout handling
496
- with client.responses.stream(**request_data) as stream:
497
- completed = False
498
-
499
- for event in stream:
500
- et = getattr(event, "type", None)
501
-
502
- if et == "response.output_text.delta":
503
- # Append the new chunk, update the UI
504
- buf.append(event.delta)
505
- full_response = "".join(buf)
506
- message_placeholder.markdown(full_response + "▌")
507
- last_delta_ts = time.time()
508
- elif et == "response.error":
509
- # Show the error inline, then stop
510
- error_msg = getattr(event, "error", "Unknown streaming error")
511
- message_placeholder.error(f"⚠️ Error: {error_msg}")
512
- buf.clear()
513
- buf.append(f"Error while streaming: {error_msg}")
514
- break
515
- elif et == "response.completed":
516
- # Response completed successfully
517
- completed = True
518
- break
519
-
520
- # Inactivity guard: if no deltas for too long, stop
521
- if time.time() - last_delta_ts > inactivity_limit_s:
522
- message_placeholder.warning("⚠️ Streaming paused due to inactivity from the server. Partial content shown above.")
523
- break
524
-
525
- # Remove cursor and show final message
526
- if buf:
527
- message_placeholder.markdown("".join(buf))
528
-
529
- # Try to get final response, but don't fail if it's not available
530
- try:
531
- final = stream.get_final_response()
532
- except Exception as final_error:
533
- final = None
534
- if not completed:
535
- st.warning(f"⚠️ Note: Could not retrieve response metadata: {final_error}")
536
-
537
  except Exception as e:
538
- # Handle streaming exceptions gracefully
539
- error_msg = str(e)
540
- if "response.completed" in error_msg:
541
- # This is expected - the response completed without the event
542
- if buf:
543
- message_placeholder.markdown("".join(buf))
544
- st.info("ℹ️ Response completed successfully (streaming ended)")
545
- else:
546
- message_placeholder.error("❌ No response content received")
547
- buf.clear()
548
- buf.append("No response content received")
549
- else:
550
- # Other streaming errors
551
- message_placeholder.error(f"❌ Error while streaming: {error_msg}")
552
- buf.clear()
553
- buf.append(f"Error while streaming: {error_msg}")
554
-
555
- # Save response to chat history
556
- response = "".join(buf)
557
  st.session_state["display_messages"].append({"role": "assistant", "content": response})
558
- # Log the exchange
559
- logging.info(f"User prompt: {st.session_state['display_messages'][-2]['content']}")
560
- logging.info(f"Assistant response: {response}")
 
561
  except Exception as e:
562
- # Handle errors
563
  st.error(f"An error occurred: {str(e)}")
564
  logging.exception(f"Error generating response: {e}")
565
 
566
  # Reset trigger flag after response is generated
567
  st.session_state["trigger_llm"] = False
568
 
569
- # Chat input field
570
- prompt = st.chat_input("What do you know? What do you want to know?")
 
 
 
 
571
  if prompt:
572
- # Add user message to chat and trigger LLM response
573
- st.session_state.display_messages.append({"role": "user", "content": prompt})
574
- st.session_state["trigger_llm"] = True
575
- st.rerun()
 
 
 
576
 
577
  # Clear chat history button
578
  if st.button("Clear Chat History"):
579
  st.session_state["display_messages"] = []
580
  st.session_state["trigger_llm"] = False
 
 
 
581
  st.rerun()
582
 
583
  # Warning message about AI limitations
584
  st.markdown(config.warning_message, unsafe_allow_html=True)
 
585
 
586
  ############################################################################################################
587
  # Sidebar Content - Resources and information
@@ -614,6 +796,7 @@ for resource in config.resources:
614
 
615
  # About section
616
  st.sidebar.markdown("### About")
 
617
  st.sidebar.markdown(config.app_creation_message)
618
  st.sidebar.markdown("---")
619
  st.sidebar.markdown(config.app_repo_license_message)
 
10
  import pandas as pd # Data handling
11
  import os # File operations
12
  import logging # Logging functionality
13
+ import time # Time operations for streaming inactivity guard
14
+ import base64
15
+ import mimetypes
16
+ from io import BytesIO
17
  import config # Local configuration module
18
+ import litellm
19
+ import pypdf
20
+ from dotenv import load_dotenv
21
+ from pathlib import Path
22
+ from typing import Any, Dict, List, Optional, Union
23
+
24
+ load_dotenv(Path(__file__).resolve().parent / ".env")
25
 
26
  # Set up logging to track app activity
27
  logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
 
173
  """, unsafe_allow_html=True)
174
 
175
  ############################################################################################################
176
+ # TritonAI / LiteLLM configuration
177
  ############################################################################################################
178
 
179
+ def _resolve_openai_base() -> str:
180
+ raw = (os.environ.get("OPENAI_API_BASE") or os.environ.get("OPENAI_BASE_URL") or "").strip()
181
+ if not raw:
182
+ return ""
183
+ base = raw.rstrip("/")
184
+ if not base.endswith("/v1"):
185
+ base += "/v1"
186
+ return base
187
+
188
+
189
+ OPENAI_BASE = _resolve_openai_base()
190
+ if OPENAI_BASE:
191
+ os.environ["OPENAI_API_BASE"] = OPENAI_BASE
192
+
193
+ MODEL_NAME = config.ai_model
194
+
195
+ try:
196
+ _supported = set(litellm.get_supported_openai_params(model=MODEL_NAME) or [])
197
+ except Exception:
198
+ _supported = {"max_tokens", "temperature"}
199
+
200
+ _wanted = {
201
+ "temperature": config.temperature,
202
+ "max_tokens": config.max_tokens,
203
  }
204
+ GEN_PARAMS = {k: v for k, v in _wanted.items() if v is not None and k in _supported}
205
+ _skipped = [k for k, v in _wanted.items() if v is not None and k not in _supported]
206
+
207
+ logging.info(
208
+ f"[config] MODEL_NAME={MODEL_NAME} | OPENAI_API_BASE={OPENAI_BASE or '(unset)'} | "
209
+ f"OPENAI_API_KEY set={bool(os.environ.get('OPENAI_API_KEY'))} | "
210
+ f"gen_params={GEN_PARAMS} | skipped_unsupported={_skipped}"
211
+ )
212
 
213
+ if MODEL_NAME.startswith("openai/") and not OPENAI_BASE:
214
+ logging.warning(
215
+ "[config] no OPENAI_API_BASE is set, but the model is "
216
+ f"'{MODEL_NAME}'. Requests will go to api.openai.com unless the endpoint is configured."
 
 
 
 
 
 
 
 
217
  )
218
 
219
+
220
+ def _build_completion_kwargs() -> dict:
221
+ completion_kwargs = {}
222
+ if MODEL_NAME.startswith("openai/") and OPENAI_BASE:
223
+ completion_kwargs["api_base"] = OPENAI_BASE
224
+ completion_kwargs["api_key"] = os.environ.get("OPENAI_API_KEY")
225
+ completion_kwargs.update(GEN_PARAMS)
226
+ return completion_kwargs
227
+
228
+
229
+ def _stream_assistant_response(
230
+ messages: List[Dict[str, Any]],
231
+ message_placeholder,
232
+ ) -> str:
233
+ completion_kwargs = _build_completion_kwargs()
234
+ buf: List[str] = []
235
+ last_delta_ts = time.time()
236
+ inactivity_limit_s = 60
237
+ received_content = False
238
+
239
+ try:
240
+ response = litellm.completion(
241
+ model=MODEL_NAME,
242
+ messages=messages,
243
+ stream=True,
244
+ **completion_kwargs,
245
+ )
246
+
247
+ for chunk in response:
248
+ if not chunk.choices:
249
+ continue
250
+ delta = chunk.choices[0].delta.content
251
+ if delta:
252
+ buf.append(delta)
253
+ message_placeholder.markdown("".join(buf) + "▌")
254
+ last_delta_ts = time.time()
255
+ received_content = True
256
+ elif received_content and time.time() - last_delta_ts > inactivity_limit_s:
257
+ message_placeholder.warning(
258
+ "Streaming paused due to inactivity from the server. Partial content shown above."
259
+ )
260
+ break
261
+ except Exception as stream_err:
262
+ logging.warning(f"Streaming failed, trying non-streaming fallback: {stream_err}")
263
+
264
+ if not buf:
265
+ fallback = litellm.completion(
266
+ model=MODEL_NAME,
267
+ messages=messages,
268
+ stream=False,
269
+ **completion_kwargs,
270
+ )
271
+ fallback_content = fallback.choices[0].message.content
272
+ if fallback_content:
273
+ buf.append(fallback_content)
274
+
275
+ if buf:
276
+ message_placeholder.markdown("".join(buf))
277
+ return "".join(buf)
278
+
279
+ message_placeholder.error("No response content received")
280
+ return "No response content received"
281
+
282
+
283
+ def _encode_bytes_to_data_url(data: bytes, mime_type: str) -> str:
284
+ encoded = base64.b64encode(data).decode("utf-8")
285
+ return f"data:{mime_type};base64,{encoded}"
286
+
287
+
288
+ def _guess_mime_type(name: str, uploaded_type: Optional[str] = None) -> str:
289
+ if uploaded_type:
290
+ return uploaded_type
291
+ guessed, _ = mimetypes.guess_type(name)
292
+ return guessed or "application/octet-stream"
293
+
294
+
295
+ def _attachments_from_uploaded_files(files) -> List[Dict[str, Any]]:
296
+ attachments = []
297
+ for uploaded in files or []:
298
+ attachments.append(
299
+ {
300
+ "name": uploaded.name,
301
+ "mime": _guess_mime_type(uploaded.name, getattr(uploaded, "type", None)),
302
+ "bytes": uploaded.getvalue(),
303
+ }
304
+ )
305
+ return attachments
306
+
307
+
308
+ def _build_content_parts(text: str, attachments: List[Dict[str, Any]]) -> Union[str, List[Dict[str, Any]]]:
309
+ parts: List[Dict[str, Any]] = []
310
+ if text:
311
+ parts.append({"type": "text", "text": text})
312
+
313
+ for attachment in attachments:
314
+ name = attachment["name"]
315
+ mime_type = attachment["mime"]
316
+ data = attachment["bytes"]
317
+
318
+ if mime_type.startswith("image/"):
319
+ parts.append(
320
+ {
321
+ "type": "image_url",
322
+ "image_url": {"url": _encode_bytes_to_data_url(data, mime_type)},
323
+ }
324
+ )
325
+ elif name.lower().endswith(".pdf") or mime_type == "application/pdf":
326
+ try:
327
+ reader = pypdf.PdfReader(BytesIO(data))
328
+ pdf_text = ""
329
+ for i, page in enumerate(reader.pages):
330
+ extracted = page.extract_text()
331
+ if extracted:
332
+ pdf_text += f"--- Page {i + 1} ---\n{extracted}\n\n"
333
+ parts.append(
334
+ {
335
+ "type": "text",
336
+ "text": (
337
+ f"\n\n--- PDF Document: {name} ---\n"
338
+ f"{pdf_text}\n--- End PDF ---\n"
339
+ ),
340
+ }
341
+ )
342
+ except Exception as e:
343
+ parts.append(
344
+ {
345
+ "type": "text",
346
+ "text": (
347
+ f"\n[System: Could not read PDF {name}. Error: {str(e)}]\n"
348
+ ),
349
+ }
350
+ )
351
+ elif name.lower().endswith((".qmd", ".rmd")):
352
+ try:
353
+ file_text = data.decode("utf-8")
354
+ parts.append(
355
+ {
356
+ "type": "text",
357
+ "text": (
358
+ f"\n\n--- Quarto/R Markdown: {name} ---\n"
359
+ f"{file_text}\n--- End Document ---\n"
360
+ ),
361
+ }
362
+ )
363
+ except UnicodeDecodeError:
364
+ parts.append(
365
+ {
366
+ "type": "text",
367
+ "text": f"\n[System: Could not read file as text: {name}]\n",
368
+ }
369
+ )
370
+ elif mime_type.startswith("audio/") or mime_type.startswith("video/"):
371
+ media_kind = mime_type.split("/")[0]
372
+ parts.append(
373
+ {
374
+ "type": "text",
375
+ "text": (
376
+ f"\n[Attached {media_kind} file: {name}. "
377
+ "The app cannot transcribe this file; respond using any text the student provided "
378
+ "and ask clarifying questions if needed.]\n"
379
+ ),
380
+ }
381
+ )
382
+ else:
383
+ try:
384
+ file_text = data.decode("utf-8")
385
+ parts.append(
386
+ {
387
+ "type": "text",
388
+ "text": (
389
+ f"\n\n--- Document: {name} ---\n"
390
+ f"{file_text}\n--- End Document ---\n"
391
+ ),
392
+ }
393
+ )
394
+ except UnicodeDecodeError:
395
+ parts.append(
396
+ {
397
+ "type": "text",
398
+ "text": f"\n[System: Could not read file as text: {name}]\n",
399
+ }
400
+ )
401
+
402
+ if not parts:
403
+ return ""
404
+ if len(parts) == 1 and parts[0]["type"] == "text":
405
+ return parts[0]["text"]
406
+ return parts
407
+
408
+
409
+ def _build_api_messages(system_message: str, display_messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
410
+ messages = [{"role": "system", "content": system_message}]
411
+ for message in display_messages:
412
+ if message["role"] == "assistant":
413
+ content = message.get("content", "")
414
+ if content.startswith("**An error occurred:**") or content == "No response content received":
415
+ continue
416
+ messages.append({"role": "assistant", "content": content})
417
+ else:
418
+ content = _build_content_parts(
419
+ message.get("content", ""),
420
+ message.get("attachments", []),
421
+ )
422
+ messages.append({"role": "user", "content": content})
423
+ return messages
424
+
425
+
426
+ def _render_user_message(message: Dict[str, Any]) -> None:
427
+ content = message.get("content", "")
428
+ if content:
429
+ st.markdown(content)
430
+
431
+ for attachment in message.get("attachments", []):
432
+ name = attachment["name"]
433
+ mime_type = attachment["mime"]
434
+ data = attachment["bytes"]
435
+
436
+ if mime_type.startswith("image/"):
437
+ st.image(data, caption=name, use_container_width=True)
438
+ elif mime_type.startswith("audio/"):
439
+ st.audio(data, format=mime_type)
440
+ st.caption(f"Attached audio: {name}")
441
+ elif mime_type.startswith("video/"):
442
+ st.video(data)
443
+ st.caption(f"Attached video: {name}")
444
+ else:
445
+ st.caption(f"Attached file: {name}")
446
+
447
+
448
+ def _parse_chat_input(prompt) -> tuple[str, List[Dict[str, Any]]]:
449
+ if hasattr(prompt, "text"):
450
+ text = prompt.text or ""
451
+ attachments = _attachments_from_uploaded_files(getattr(prompt, "files", None))
452
+ return text, attachments
453
+ return prompt or "", []
454
+
455
+
456
+ def _sanitize_display_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
457
+ """Drop legacy exam-bank payloads that were stored in chat history."""
458
+ cleaned: List[Dict[str, Any]] = []
459
+ for message in messages:
460
+ msg = dict(message)
461
+ msg.pop("api_content", None)
462
+ content = msg.get("content", "")
463
+ if msg.get("role") == "user" and isinstance(content, str) and len(content) > 10000:
464
+ if "END OF EXAM" in content or "# SPRING 2026" in content:
465
+ msg["content"] = config.EXAM_REVIEW_DISPLAY
466
+ cleaned.append(msg)
467
+ return cleaned
468
 
469
  ############################################################################################################
470
  # Initialize all session state variables - Persistent data between app reruns
 
486
  if 'seen_terms' not in st.session_state:
487
  st.session_state.seen_terms = set() # Set of viewed terms
488
  if 'openai_model' not in st.session_state:
489
+ st.session_state.openai_model = MODEL_NAME # AI model being used
490
+ if 'exam_review_mode' not in st.session_state:
491
+ st.session_state.exam_review_mode = False
492
+ if 'exam_review_context' not in st.session_state:
493
+ st.session_state.exam_review_context = None
494
+ if 'messages_sanitized' not in st.session_state:
495
+ st.session_state.messages_sanitized = False
496
+ if st.session_state.display_messages and not st.session_state.messages_sanitized:
497
+ st.session_state.display_messages = _sanitize_display_messages(st.session_state.display_messages)
498
+ st.session_state.messages_sanitized = True
499
 
500
  ############################################################################################################
501
  # Password protection - User authentication functionality
 
606
  # Update session state
607
  st.session_state.selected_context = term_context
608
  st.session_state.selected_term = selected_term
609
+ st.session_state.exam_review_mode = False
610
+ st.session_state.exam_review_context = None
611
 
612
  # Create initial user message
613
  user_message = f"What is one thing you know about '{selected_term}'? What do you want to know about it? This could include a definition, examples, misconceptions, associations with other course terms, opinions, etc. You may also choose one of the template buttons on the left to help you get started."
 
630
  "Two Truths & a Lie": "🎮",
631
  "Connect Terms": "🔄",
632
  "Schema Map": "🗺️",
633
+ "Review exam questions": "📝",
634
  "Create a Study Plan": "📚"
635
  }
636
 
 
650
  # Create button and handle click
651
  if btn_cols[i].button(button_text, key=f"btn_{row}_{i}"):
652
  # Format template with appropriate variables
653
+ if template_name == "Review exam questions":
654
+ # Question bank contains literal braces (e.g. t_{obs}); format instructions only
655
+ st.session_state.exam_review_context = (
656
+ config.EXAM_REVIEW_INSTRUCTIONS.format(
657
+ term=selected_term, term_list=term_list
658
+ )
659
+ + config.EXAM_QUESTION_BANK
660
+ )
661
+ st.session_state.exam_review_mode = True
662
+ st.session_state.display_messages.append(
663
+ {"role": "user", "content": config.EXAM_REVIEW_DISPLAY}
664
+ )
665
+ st.session_state["trigger_llm"] = True
666
+ st.rerun()
667
+ continue
668
+
669
+ st.session_state.exam_review_mode = False
670
+ st.session_state.exam_review_context = None
671
  if "term_list" in template["template"]:
672
  formatted_content = template["template"].format(term=selected_term, term_list=term_list)
673
  else:
 
690
  for message in st.session_state["display_messages"][1:]:
691
  if message["role"] == "user":
692
  with st.chat_message("user"):
693
+ _render_user_message(message)
694
  else:
695
  with st.chat_message("assistant"):
696
  st.markdown(message["content"])
 
698
  # Generate and display AI response when triggered
699
  if st.session_state.get("trigger_llm", False):
700
  try:
701
+ if st.session_state.exam_review_mode and st.session_state.exam_review_context:
702
+ system_message = config.exam_review_system_prompt(
703
+ st.session_state.exam_review_context
704
+ )
705
+ else:
706
+ system_message = config.term_prompt(
707
+ selected_term=st.session_state.selected_term,
708
+ selected_context=st.session_state.selected_context,
709
+ term_list=term_list,
710
+ )
711
+
712
  # Prepare messages for API call
713
+ messages = _build_api_messages(system_message, st.session_state["display_messages"])
714
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
715
  with st.chat_message("assistant"):
716
  message_placeholder = st.empty()
 
 
 
 
717
  try:
718
+ response = _stream_assistant_response(messages, message_placeholder)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
719
  except Exception as e:
720
+ message_placeholder.error(f"Error while contacting the AI service: {e}")
721
+ response = (
722
+ f"**An error occurred:** {e}\n\n"
723
+ "*Check your API keys, OPENAI_API_BASE, and model name in config.py. "
724
+ "If the problem persists, TritonAI may be temporarily unavailable — try again in a moment.*"
725
+ )
726
+ message_placeholder.markdown(response)
727
+
 
 
 
 
 
 
 
 
 
 
 
728
  st.session_state["display_messages"].append({"role": "assistant", "content": response})
729
+ prior = st.session_state["display_messages"][-2]
730
+ logged_prompt = prior.get("content", "")
731
+ logging.info(f"User prompt: {logged_prompt[:500]}{'...' if len(logged_prompt) > 500 else ''}")
732
+ logging.info(f"Assistant response: {response[:500]}{'...' if len(response) > 500 else ''}")
733
  except Exception as e:
 
734
  st.error(f"An error occurred: {str(e)}")
735
  logging.exception(f"Error generating response: {e}")
736
 
737
  # Reset trigger flag after response is generated
738
  st.session_state["trigger_llm"] = False
739
 
740
+ # Chat input with optional file attachments
741
+ prompt = st.chat_input(
742
+ "What do you know? What do you want to know? Use + to attach files or images.",
743
+ accept_file="multiple",
744
+ file_type=config.upload_file_types,
745
+ )
746
  if prompt:
747
+ text, attachments = _parse_chat_input(prompt)
748
+ if text or attachments:
749
+ st.session_state.display_messages.append(
750
+ {"role": "user", "content": text, "attachments": attachments}
751
+ )
752
+ st.session_state["trigger_llm"] = True
753
+ st.rerun()
754
 
755
  # Clear chat history button
756
  if st.button("Clear Chat History"):
757
  st.session_state["display_messages"] = []
758
  st.session_state["trigger_llm"] = False
759
+ st.session_state.exam_review_mode = False
760
+ st.session_state.exam_review_context = None
761
+ st.session_state.messages_sanitized = True
762
  st.rerun()
763
 
764
  # Warning message about AI limitations
765
  st.markdown(config.warning_message, unsafe_allow_html=True)
766
+ st.caption(config.tritonai_notice)
767
 
768
  ############################################################################################################
769
  # Sidebar Content - Resources and information
 
796
 
797
  # About section
798
  st.sidebar.markdown("### About")
799
+ st.sidebar.caption(config.tritonai_notice)
800
  st.sidebar.markdown(config.app_creation_message)
801
  st.sidebar.markdown("---")
802
  st.sidebar.markdown(config.app_repo_license_message)
config.py CHANGED
@@ -31,40 +31,42 @@ app_title = "Schema Study"
31
  default_terms_csv = "terms.csv"
32
 
33
  # Warning message shown at the bottom of the chat window
34
- warning_message = "**ChatGPT can make errors and does not replace verified and reputable online and classroom resources. Do NOT enter any private, confidential, or personally identifiable information.**"
 
 
 
35
 
36
 
37
  # ==============================================
38
  # 2. AI MODEL SETTINGS
39
  # ==============================================
40
 
41
- # The OpenAI model used by the app
42
- # Options: "gpt-5.1" (default, reasoning model) or "gpt-4.1" (non-reasoning model)
43
- # - gpt-5.1: Latest reasoning model with reasoning="none" default for faster responses
44
- # - gpt-4.1: Non-reasoning model with temperature control
45
- ai_model = "gpt-5.4-mini"
46
 
47
- # Reasoning effort for gpt-5.1 (only applies when ai_model = "gpt-5.1")
48
- # Options: "none" (default, fastest), "minimal", "low", "medium"
49
- # "none" disables reasoning for faster responses without reasoning overhead
50
  reasoning_effort = "minimal"
51
 
52
- # Temperature for gpt-4.1 (only applies when ai_model = "gpt-4.1")
53
- # Controls randomness/creativity (0-2)
54
  # Lower values (0.1-0.3) = more focused, precise responses
55
  # Higher values (0.7-1.0) = more creative, varied responses
56
  temperature = 0.1
57
 
58
  # Maximum length of AI responses (measured in tokens)
59
  # Higher values allow for longer responses (1000-2000 is usually sufficient)
60
- # Maps to max_output_tokens in Responses API
61
  max_tokens = 1000
62
 
63
- # Enable web search functionality (only applies when ai_model supports web search)
64
- # When enabled, the AI can search the web for current information and cite sources
65
- # Note: Web search is incompatible with reasoning effort - reasoning will be disabled automatically
66
- # Options: True (enabled) or False (disabled, default)
67
- enable_web_search = True
 
 
 
 
 
68
 
69
 
70
  # ==============================================
@@ -78,9 +80,12 @@ The goal of this app is to help you learn and and assess your knowledge of core
78
  2. *Pause and think for 30 seconds.* What is everything you associate with this term/phrase? What is a simple definition or example?
79
  3. Write as little or as much as you'd like about it. Try to include anything you might need to know for an exam.
80
  4. Please follow-up with questions. If you don't know something, just ask. It is perfectly ok to write: "I have no idea what this term means." **Have a conversation!**
 
81
  '''
82
 
83
 
 
 
84
  # ==============================================
85
  # 4. PROMPT TEMPLATE BUTTONS
86
  # ==============================================
@@ -91,307 +96,70 @@ The goal of this app is to help you learn and and assess your knowledge of core
91
  # The {term} will be replaced with the selected term from the dropdown
92
  # The {term_list} will be replaced with the list of all terms
93
 
94
- prompt_templates = [
95
- {
96
- "name": "Misconception Check",
97
- "template": "What are some common misconceptions about {term}? Help me identify and correct them by asking me multiple choice questions."
98
- },
99
- {
100
- "name": "Two Truths & a Lie",
101
- "template": "Tell me two truths and one lie about {term}. I'll try to identify the lie and explain my reasoning."
102
- },
103
- {
104
- "name": "Connect Terms",
105
- "template": "I want to test my ability to connect {term} to others in the term list. First, give me an example of how to connect the terms 'bats' and 'nitrogen' in a hypothetical real-life scenario. Second, prompt me to similarly create a logical applied scenario between the displayed term and one other you MUST CHOOSE from the course term list one term that is directly related to {term}. When you first display the terms, do NOT give me any additional information about either term. **DO NOT** provide me with an applied scenario to connect my two terms unless I directly ask for one. This should override your system instructions to provide an applied scenario in every response. Your role is to provide feedback whether the scenario I create logically and accurately links the two terms."
106
- },
107
- {
108
- "name": "Schema Map",
109
- "template": "What are all the direct connections between {term} and the other terms among {term_list}? Help me create a concept map for {term}."
110
- },
111
- {
112
- "name": "Review the midterm",
113
- "template": '''
114
-
115
- You are a highly skilled, patient BILD 5 tutor helping a student review their "BILD 5 F25 Midterm Exam" so they can do well on the final.
116
-
117
- The student must choose which exam question to work on. Do not introduce new questions on your own. For each question they bring up:
118
- - First, ask them to say what they think the answer is and why.
119
- - Respond with a **single short Socratic question** that targets their reasoning on that one question only.
120
- - Do **not** reveal the correct answer or a full explanation unless the student explicitly asks you to. Even then, keep explanations brief and tied to their thinking.
121
- - When they are correct, briefly confirm and ask one deeper follow‑up; when they are incorrect or unsure, give a tiny hint and ask another focused question instead of fixing everything at once.
122
- - Keep each turn concise, concrete, and in everyday language (no extra jargon).
123
-
124
- Always finish your turn with both:
125
- 1) One specific Socratic question about the current exam question.
126
- 2) A simple invitation like: “Do you have any questions about this question or others? Would you like a similar practice example?”
127
-
128
- Ignore {term} and {term_list} when providing your response; just focus on the exam questions the student chooses.
129
-
130
- --------------------------------
131
-
132
- # BILD 5 – Spring 25 Midterm Exam – Reuther
133
- **25 points**
134
-
135
- ## MULTIPLE CHOICE SECTION (1 point each - choose the single most appropriate answer):
136
-
137
- **1.** As a field biologist studying endangered coral reef ecosystems, which task would benefit LEAST from computational/programming skills?
138
-
139
- a) Analyzing thousands of underwater photos to quantify coral bleaching rates
140
- b) Creating a drawing of a newly discovered species
141
- c) Processing environmental sensor data collected every minute for six months
142
- d) Building predictive models of reef recovery under different temperature scenarios
143
- e) Automating species identification from acoustic recordings
144
-
145
- **2.** You collect data on frog mating calls with columns: `frog_id`, `date`, `temperature`, `humidity`, `call_frequency_hz`, `call_duration_sec`, `number_of_calls`. Is this dataset "tidy"?
146
-
147
- a) No—environmental variables should be in a separate table
148
- b) Yes—each row represents one observation with variables in separate columns
149
- c) No—multiple call measurements should be combined into one column
150
- d) Yes—but only if we reshape it to have one row per individual frog
151
- e) Cannot determine without seeing the actual data values
152
-
153
- **3.** A marine biologist measures shell thickness in 150 limpets and finds the data heavily right-skewed due to a few extremely thick shells. Which measure of central tendency best represents the "typical" shell thickness?
154
-
155
- a) Mean, because it uses all data points
156
- b) Mode, because it shows the most common value
157
- c) Range, because it captures the full variation
158
- d) Median, because it's resistant to extreme values
159
- e) Standard deviation, because it quantifies spread
160
-
161
- **4.** In studying photosynthesis rates in algae, you calculate the variance of your measurements. This statistic specifically tells you:
162
-
163
- a) The average photosynthesis rate across all samples
164
- b) How much individual measurements differ from the mean
165
- c) The middle value when all rates are ordered
166
- d) The probability of obtaining your results by chance
167
- e) The difference between highest and lowest rates
168
-
169
- **5.** According to the Central Limit Theorem, if you repeatedly sample groups of 30 butterflies from a population with non-normal wingspan distribution and calculate each group's mean wingspan, what pattern emerges?
170
-
171
- a) The sample means will match the original skewed distribution
172
- b) The sample means will form an approximately normal distribution
173
- c) The sample means will become increasingly variable
174
- d) The sample means will cluster around the population median
175
- e) Nothing predictable—the pattern will be random
176
 
177
- **6.** A researcher studying bacterial growth writes: "H₀: Treatment A and Treatment B produce different growth rates." What is wrong with this hypothesis statement?
 
178
 
179
- a) It's not testable with statistics
180
- b) The null hypothesis should be a specific statement of equality (μ₁ = μ₂), not a vague claim about differences
181
- c) It doesn't specify which statistical test to use
182
- d) The null hypothesis must ALWAYS be one of zero difference or no effect.
183
- e) Nothing—this is correctly stated
 
 
184
 
185
- **7.** You're comparing nest-building times between two bird species. Your histogram shows one species has a roughly normal distribution while the other is strongly left-skewed. To proceed with a t-test, you should:
 
 
186
 
187
- a) Use the t-test anyway since one group is normal
188
- b) Remove all data from the skewed group
189
- c) Check sample sizes and consider transformations or non-parametric alternatives
190
- d) Only analyze the normally distributed group
191
- e) Combine both groups into one dataset
192
-
193
- **8.** In a power analysis for an experiment on fish growth rates, increasing your sample size from n=10 to n=50 per group while keeping everything else constant will:
194
-
195
- a) Decrease both Type I and Type II error rates
196
- b) Increase your ability to detect a true effect if it exists
197
- c) Make the effect size larger
198
- d) Guarantee statistical significance
199
- e) Reduce the need for proper experimental controls
200
-
201
- **9.** You obtain p = 0.03 with α = 0.05 and reject the null hypothesis. Unknown to you, the null hypothesis was actually true. This represents:
202
-
203
- a) A correct decision (true negative)
204
- b) Type I error (false positive)
205
- c) Type II error (false negative)
206
- d) A correct decision (true positive)
207
- e) Insufficient information to classify
208
-
209
- **10.** Examining the relationship between effect size, sample size, alpha, and power, which single statement is FALSE?
210
-
211
- a) Larger effect sizes are easier to detect with smaller samples
212
- b) Increasing alpha increases power but also increases Type I error risk
213
- c) Power increases as sample size increases
214
- d) Observed effect size determines the biological importance. Large effect sizes are more biologically important.
215
- e) You can achieve the same power with a smaller sample by increasing the minimum effect size you're willing to detect
216
 
217
- **11.** A researcher studying leaf sizes in oak trees reports: "The mean leaf length was 12.3 cm (SE = 0.45 cm, SD = 3.2 cm, n = 50)." A colleague questions why both SE and SD are reported. Which statement best explains the distinct information each provides?
218
-
219
- a) SE and SD are the same thing, just calculated differently
220
- b) SD describes variability in the individual leaves; SE describes uncertainty about the estimated mean
221
- c) SE describes variability in the individual leaves; SD describes uncertainty about the estimated mean
222
- d) SD is always larger than SE due to calculation errors
223
- e) Both describe the same variability but SE is preferred for larger samples
224
-
225
- **12.** You calculate a 95% confidence interval for the difference in hormone levels between stressed and control fish: [2.3, 8.7] ng/mL. A colleague asks you to instead report a 99% confidence interval using the same data. Without recalculating, what can you predict about the 99% CI?
226
-
227
- a) It will be narrower than [2.3, 8.7] because 99% is more confident
228
- b) It will be wider than [2.3, 8.7] because greater confidence requires a wider range
229
- c) It will have the same width but shifted to center on zero
230
- d) It will be [0.23, 0.87] because confidence scales proportionally
231
- e) Cannot predict without knowing the sample size
232
-
233
- **13.** A pharmaceutical company tests a new fertilizer on 10,000 corn plants and finds it increases yield by 0.02% (p = 0.0001). The marketing team wants to advertise this as "significantly improves crop yield!" As the data scientist, what is your primary concern?
234
-
235
- a) The p-value is too small to be trustworthy
236
- b) The sample size is too large for valid statistics
237
- c) The effect is statistically significant but practically meaningless
238
- d) The null hypothesis was incorrectly specified
239
- e) Corn yield cannot be measured precisely enough
240
-
241
- **14.** A student analyzing butterfly wing patterns writes the following R code:
242
-
243
- ```r
244
- butterfly_data <- read.csv("butterflies.csv")
245
- mean_wingspan <- mean(butterfly_data$wingspan_mm)
246
- median_wingspan <- median(butterfly_data$wingspan_mm)
247
- mean_wingspan
248
- ```
249
-
250
- What will be displayed in the R console when this code runs?
251
-
252
- a) Both the mean and median wingspan values
253
- b) Only the mean wingspan value
254
- c) Only the median wingspan value
255
- d) The entire butterfly_data dataset
256
- e) An error message because median_wingspan was not printed
257
-
258
- **15.** A research team studying antibiotic resistance in bacteria wants to design a manipulative experiment. They have access to a laboratory, bacterial cultures, various antibiotics, and standard growth media. Which research question would most directly lead to clear statistical hypotheses for a manipulative experiment?
259
-
260
- a) How does antibiotic exposure affect bacterial populations in natural environments?
261
- b) What factors influence the development of antibiotic resistance in bacteria?
262
- c) Does exposure to sub-lethal doses of ampicillin (0.5 μg/mL for 48 hours) increase the survival rate of E. coli when subsequently treated with a lethal dose (10 μg/mL)?
263
- d) Is there a relationship between antibiotic concentration and bacterial resistance?
264
- e) Do bacteria develop resistance faster when exposed to antibiotics compared to bacteria that are not exposed to antibiotics?
265
-
266
- ---
267
 
268
- ## SHORT ANSWER SECTION:
269
-
270
- **16.** A graduate student studying desert lizard metabolism has the following R code and output:
271
-
272
- ```r
273
- # Load data
274
- lizard_data <- read.csv("desert_lizards.csv")
275
 
276
- # Check structure
277
- str(lizard_data)
278
- # 'data.frame': 120 obs. of 5 variables:
279
- # $ species : chr "horned" "horned" "collared" ...
280
- # $ temp_C : num 28.5 31.2 29.8 ...
281
- # $ mass_g : num 45.2 38.9 52.1 ...
282
- # $ metabolic_rate: num 0.82 0.91 1.05 ...
283
- # $ activity_level: chr "low" "medium" "high" ...
284
 
285
- # Create visualization
286
- library(ggplot2)
287
- ggplot(lizard_data, aes(x = temp_C, y = metabolic_rate, color = species)) +
288
- geom_point(size = 3) +
289
- geom_smooth(method = "lm", se = FALSE) +
290
- facet_wrap(~ activity_level) +
291
- labs(title = "Desert Lizard Metabolic Rates",
292
- x = "Temperature (°C)",
293
- y = "Metabolic Rate (mL O2/g/hr)")
294
- ```
295
-
296
- a) **[2 points]** Describe in words what visualization this code produces. Be specific about what is shown.
297
 
298
- **GRADING RUBRIC (2 points total):**
299
- - 0.5 points: Identifies as a scatterplot
300
- - 0.5 points: Identifies X axis as temperature (temp_C)
301
- - 0.5 points: Identifies Y axis as metabolic rate
302
- - 0.5 points: Identifies color as representing different species
303
-
304
- b) **[2 points]** The student wants to test if the mean metabolic rate differs between species. What two assumption-checking steps should they take to make sure the assumption of normality is not violated?
305
 
306
- **GRADING RUBRIC (2 points total):**
307
- - 0.5 points: Names appropriate method (histogram, Q-Q plot, density plot, boxplot)
308
- - 0.5 points: Names they are looking for deviations from normality (can also optionally mention outliers)
309
- - 0.5 points: Names a statistical test like Kolmogorov-Smirnov (KS) or Shapiro-Wilk
310
- - 0.5 points: States that a p-value < 0.05 indicates a violation of normality
311
-
312
- **17.** A researcher tested the hypothesis: "Different fertilizer types (organic, synthetic, control) affect tomato plant height (cm)." They collected height measurements from 40 plants per fertilizer type and created the following figure:
313
 
314
- ### FIGURE DESCRIPTION:
315
- The figure is a line graph with the following characteristics:
316
- - **Title**: "data" (appears in the top left corner)
317
- - **X-axis**: Labeled "type" with three categorical values: "Control", "Organic", and "Synthetic"
318
- - **Y-axis**: Labeled "values" with a scale ranging from 40 to 55
319
- - **Data representation**: Three data points connected by black lines:
320
- - Control: approximately 45 units
321
- - Organic: approximately 52 units (highest point)
322
- - Synthetic: approximately 48 units
323
- - **Graph style**: The three points are connected by straight black lines forming a peaked shape, with the organic fertilizer showing the highest value
324
- - **Grid**: Light gray gridlines in the background
325
- - **Point markers**: Black filled circles at each data point
326
 
327
- a) **[2 points]** List TWO specific problems with this figure.
328
 
329
- **GRADING RUBRIC (2 points total):**
330
- - 0.75 points: States one problem
331
- - Acceptable problems:
332
- 1. Wrong geom type (line graph for categorical data)
333
- 2. Poor/missing labels
334
- 3. No variability shown (no error bars)
335
- 4. No sample size information
336
- - 0.25 points: States why the first problem is a bad decision
337
- - 0.75 points: States a second problem
338
- - 0.25 points: States why the second problem is wrong
339
 
340
- b) **[2 points]** What type of visualization should the researcher have used instead?
341
 
342
- **GRADING RUBRIC (2 points total):**
343
- - 2.0 points: Names appropriate type (boxplot, violin plot, bar plot with error bars)
344
- - 1.0 point: Partial credit for another visualization that could use categorical data but is not optimal (like a pie chart)
345
 
346
- **18. [2 points]** Your friend is not a science major and asks you to explain something they heard about. Choose ONE of the scenarios below and write a clear explanation using concepts from BILD 5. Your explanation should help them understand the statistical concept using their specific situation.
347
-
348
- **SCENARIO A: Confidence Interval**
349
-
350
- Your friend is working on a psychology research project about college student sleep patterns. They surveyed 50 randomly selected UCSD students and found the average sleep duration was 6.5 hours per night, with a 95% confidence interval of [6.1, 6.9] hours. Your friend says: "So this means that 95% of UCSD students sleep between 6.1 and 6.9 hours, right?"
351
-
352
- Use this specific scenario to help them understand what "95% confident" refers to.
353
-
354
- **GRADING RUBRIC FOR SCENARIO A (2 points total):**
355
- - 0.5 points: Clarifies the CI is NOT about 95% of individuals falling in the range
356
- - 0.5 points: Explains it's about uncertainty in estimating the population mean
357
- - 1.0 point: Explains the repeated sampling interpretation or another accurate definition (if we repeated this study 100 times, 95 intervals would capture the true mean)
358
- - 0.5 points: Partial credit for a CI definition that is generally OK but has some aspect that is incorrect
359
-
360
- **OR**
361
-
362
- **SCENARIO B: p-value**
363
-
364
- Your friend is reading a news article that says: "A new study found that people who eat chocolate daily have better memory (p = 0.04). This proves chocolate improves memory!" Your friend asks: "What does p = 0.04 mean? Does it mean there's only a 4% chance they're wrong?"
365
-
366
- Explain what the p-value actually tells us in this study.
367
-
368
- **GRADING RUBRIC FOR SCENARIO B (2 points total):**
369
- - 0.5 points: Corrects the "4% chance they're wrong" misconception
370
- - 0.5 points: Includes an explicit reference to "assuming the null hypothesis is true"
371
- - 1.0 point: Clearly defining it as a probability you'd see a difference/test statistic at least this large due to random chance alone
372
- - 0.75 points: Partial credit if not saying "at least this large" or not indicating area under the curve (e.g., if they said it was the probability of getting this exact test statistic due to chance alone)
373
-
374
- ---
375
-
376
- **Total: 25 points**
377
- Page 8/8
378
-
379
- ---
380
-
381
- ## GRADING SUMMARY
382
-
383
- **Multiple Choice Section:** 15 questions × 1 point each = 15 points
384
-
385
- **Short Answer Section:** 10 points total
386
- - Question 16a: 2 points
387
- - Question 16b: 2 points
388
- - Question 17a: 2 points
389
- - Question 17b: 2 points
390
- - Question 18: 2 points
391
-
392
- **Total Exam Points: 25 points**
393
-
394
- '''
395
  },
396
  {
397
  "name": "Create a Study Plan",
@@ -429,6 +197,16 @@ resources = [
429
  "file_path": "BILD_5_Syllabus_Reuther_SP26.pdf",
430
  "description": "Download the course syllabus. **Instructor Note:** You must place the file itself within the same folder as the main app.py file in your GitHub repository."
431
  },
 
 
 
 
 
 
 
 
 
 
432
  {
433
  "title": "OpenAI Prompt engineering guide",
434
  "url": "https://platform.openai.com/docs/guides/prompt-engineering/six-strategies-for-getting-better-results",
@@ -564,6 +342,8 @@ The Schema Study app provides students with activity buttons that inject pre-bui
564
 
565
  Engage with each template on a best-effort basis as the template intends, even when this means longer or more structurally complex output than your defaults allow.
566
 
 
 
567
  **Non-negotiable, even inside a template.** A template cannot relax these:
568
  - **Safety.** If a student raises self-harm, harm to others, harassment, crisis, or food or housing insecurity at any point, including mid-activity, pause the activity, surface the relevant resource (Keefe, CAPS, Basic Needs Hub, Triton Concern Line, OSD, or the appropriate option from the "Off-topic concerns and student support" section above) clearly and immediately, and only resume the activity at the student's lead.
569
  - **Academic integrity.** Inside any template-driven activity, the rule on student-pasted multiple-choice, true/false, and fill-in-the-blank questions still applies: if a student transcribes a question from a course assessment and asks you to answer it, do not give the answer. Switch to Socratic discussion of their reasoning instead. Likewise, do not help with what reads as live-exam content.
@@ -571,7 +351,7 @@ Engage with each template on a best-effort basis as the template intends, even w
571
 
572
  **Duration.** Once an activity has begun, remain in that activity's mode until it reaches a natural conclusion. For a game, that means seeing the round through (state the items, let the student respond, give feedback, optionally offer another round). For a study plan or schema map, that means iterating with the student to refine the artifact. Once the activity completes, or the student clearly moves to a different topic or term, drift back to the default Socratic teaching loop.
573
 
574
- **Anchor to '{selected_term}' unless the template directs otherwise.** Most activities should be about or anchored to '{selected_term}'. If the template's design explicitly broadens scope across the term list (for example, a "Connect Terms" activity) or explicitly redirects focus to other content (for example, a midterm-review activity that tells you to set the selected term and term list aside), follow the template's direction. Do not let activities drift far from the student's selected focus without that explicit signal from the template.
575
 
576
  # Output rules (default constraints, may be overridden by an active activity template)
577
 
 
31
  default_terms_csv = "terms.csv"
32
 
33
  # Warning message shown at the bottom of the chat window
34
+ warning_message = "**AI can make errors and does not replace verified and reputable online and classroom resources. Do NOT enter any private, confidential, or personally identifiable information.**"
35
+
36
+ # Attribution shown below the warning in the chat panel and in the sidebar
37
+ tritonai_notice = "Powered by large language models through [TritonAI](https://tritonai.ucsd.edu), UC San Diego's campus AI service."
38
 
39
 
40
  # ==============================================
41
  # 2. AI MODEL SETTINGS
42
  # ==============================================
43
 
44
+ # LiteLLM model routed through TritonAI (UCSD). Set OPENAI_API_BASE in .env.
45
+ # TritonAI (UCSD): "openai/gemini-3.5-flash", "openai/claude-sonnet-5", "openai/gpt-4.1"
46
+ ai_model = "openai/claude-sonnet-5"
 
 
47
 
48
+ # Reasoning effort (legacy setting; not used on the openai/ TritonAI route)
 
 
49
  reasoning_effort = "minimal"
50
 
51
+ # Temperature — controls randomness/creativity (0-2)
 
52
  # Lower values (0.1-0.3) = more focused, precise responses
53
  # Higher values (0.7-1.0) = more creative, varied responses
54
  temperature = 0.1
55
 
56
  # Maximum length of AI responses (measured in tokens)
57
  # Higher values allow for longer responses (1000-2000 is usually sufficient)
 
58
  max_tokens = 1000
59
 
60
+ # Web search is not supported on the TritonAI chat-completions route
61
+ enable_web_search = False
62
+
63
+ # File types students can attach in chat (images, documents, audio, video)
64
+ upload_file_types = [
65
+ "jpg", "jpeg", "png", "gif", "webp",
66
+ "txt", "csv", "md", "json", "py", "pdf", "qmd", "rmd",
67
+ "mp3", "wav", "m4a", "aac", "ogg",
68
+ "mp4", "mov", "webm",
69
+ ]
70
 
71
 
72
  # ==============================================
 
80
  2. *Pause and think for 30 seconds.* What is everything you associate with this term/phrase? What is a simple definition or example?
81
  3. Write as little or as much as you'd like about it. Try to include anything you might need to know for an exam.
82
  4. Please follow-up with questions. If you don't know something, just ask. It is perfectly ok to write: "I have no idea what this term means." **Have a conversation!**
83
+ 5. You can attach images, PDFs, text files, or other supported files using the **+** button in the chat box.
84
  '''
85
 
86
 
87
+ from exam_questions_s26 import EXAM_QUESTION_BANK
88
+
89
  # ==============================================
90
  # 4. PROMPT TEMPLATE BUTTONS
91
  # ==============================================
 
96
  # The {term} will be replaced with the selected term from the dropdown
97
  # The {term_list} will be replaced with the list of all terms
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
+ EXAM_REVIEW_INSTRUCTIONS = """
101
+ You are a highly skilled, patient BILD 5 tutor helping a student review the Spring 2026 midterm and final exams.
102
 
103
+ The student must choose which exam (midterm or final) and which question number to work on. Do not introduce new questions on your own. For each question they bring up:
104
+ - First, ask them to say what they think the answer is and why.
105
+ - Respond with a **single short Socratic question** that targets their reasoning on that one question only.
106
+ - Do **not** reveal the correct answer or a full explanation unless the student explicitly asks you to. Even then, keep explanations brief and tied to their thinking.
107
+ - When they are correct, briefly confirm and ask one deeper follow-up; when they are incorrect or unsure, give a tiny hint and ask another focused question instead of fixing everything at once.
108
+ - Keep each turn concise, concrete, and in everyday language (no extra jargon).
109
+ - If a question references a figure, plot, or R output, remind the student to open the matching PDF in Resources.
110
 
111
+ Always finish your turn with both:
112
+ 1) One specific Socratic question about the current exam question.
113
+ 2) A simple invitation like: "Do you have any questions about this question or others? Would you like a similar practice example?"
114
 
115
+ Ignore {term} and {term_list} when providing your response; just focus on the exam questions the student chooses.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
+ The full question bank for both exams follows below.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
+ """
 
 
 
 
 
 
120
 
121
+ # Shown in the chat UI when the student clicks Review exam questions (full bank lives in session state)
122
+ EXAM_REVIEW_DISPLAY = (
123
+ "Let's review the Spring 2026 midterm and final exam questions. "
124
+ "Which exam would you like to work on — the **midterm** or the **final** — and which question number?"
125
+ )
 
 
 
126
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
+ def exam_review_system_prompt(question_bank: str) -> str:
129
+ """System prompt for exam review with the question bank (avoids the full term list)."""
130
+ return f"""You are Pliny, a friendly BILD 5 (Data Analysis and Design for Biologists) tutor at UC San Diego.
 
 
 
 
131
 
132
+ The student is reviewing Spring 2026 midterm and final exam questions. Follow the exam-review instructions below exactly. Do not introduce new exam questions unless the student asks for a similar practice example.
 
 
 
 
 
 
133
 
134
+ Academic integrity: If a student asks for a direct answer to a multiple-choice or true/false exam item before attempting it, ask what they think and why first. Do not reveal the correct letter or option until they have reasoned through it or explicitly ask for the answer after trying.
 
 
 
 
 
 
 
 
 
 
 
135
 
136
+ When a question references a figure, plot, or R output, remind them to open the matching PDF in Resources (BILD5_S26_Midterm.pdf or BILD5_SP26_Final.pdf).
137
 
138
+ Be warm, concise, and use plain language.
 
 
 
 
 
 
 
 
 
139
 
140
+ {question_bank}"""
141
 
 
 
 
142
 
143
+ prompt_templates = [
144
+ {
145
+ "name": "Misconception Check",
146
+ "template": "What are some common misconceptions about {term}? Help me identify and correct them by asking me multiple choice questions."
147
+ },
148
+ {
149
+ "name": "Two Truths & a Lie",
150
+ "template": "Tell me two truths and one lie about {term}. I'll try to identify the lie and explain my reasoning."
151
+ },
152
+ {
153
+ "name": "Connect Terms",
154
+ "template": "I want to practice connecting '{term}' to other course terms.\n\nStep 1 (demo only): Give a brief example of how 'bats' and 'nitrogen' connect in one applied scenario (2–3 sentences). You MUST use the words 'bats' and 'nitrogen' exactly as written here — they are intentional off-list demo vocabulary to show how term-connection works. Do NOT substitute course terms from the term list for this demo, and do NOT explain that they are not on the list.\n\nStep 2 (my turn): Choose one other term from the course term list that is directly related to '{term}'. Show only the two term names — no definitions yet. Ask me to write a short applied scenario linking them.\n\nDo not write my scenario for me unless I explicitly ask. After I respond, give feedback on whether my scenario logically and accurately links the two terms."
155
+ },
156
+ {
157
+ "name": "Schema Map",
158
+ "template": "What are all the direct connections between {term} and the other terms among {term_list}? Help me create a concept map for {term}."
159
+ },
160
+ {
161
+ "name": "Review exam questions",
162
+ "template": EXAM_REVIEW_INSTRUCTIONS + EXAM_QUESTION_BANK
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  },
164
  {
165
  "name": "Create a Study Plan",
 
197
  "file_path": "BILD_5_Syllabus_Reuther_SP26.pdf",
198
  "description": "Download the course syllabus. **Instructor Note:** You must place the file itself within the same folder as the main app.py file in your GitHub repository."
199
  },
200
+ {
201
+ "title": "BILD 5 S26 Midterm Exam",
202
+ "file_path": "BILD5_S26_Midterm.pdf",
203
+ "description": "Download the Spring 2026 midterm. Use with the Review exam questions template when a question references a figure."
204
+ },
205
+ {
206
+ "title": "BILD 5 SP26 Final Exam",
207
+ "file_path": "BILD5_SP26_Final.pdf",
208
+ "description": "Download the Spring 2026 final exam. Use with the Review exam questions template when a question references a figure or R output."
209
+ },
210
  {
211
  "title": "OpenAI Prompt engineering guide",
212
  "url": "https://platform.openai.com/docs/guides/prompt-engineering/six-strategies-for-getting-better-results",
 
342
 
343
  Engage with each template on a best-effort basis as the template intends, even when this means longer or more structurally complex output than your defaults allow.
344
 
345
+ **Connect Terms demo (required).** The "Connect Terms" template includes Step 1: a demo linking **bats** and **nitrogen**. These are deliberate off-list pedagogical examples — they are not on the course term list, and that is intentional. When this template is active, you MUST deliver the bats/nitrogen demo in 2–3 sentences exactly as Step 1 requests. Do not refuse, apologize, or replace them with course terms (for example, Palmer Penguins, ANOVA, or anything from '{term_list}'). Step 2 then uses course terms from the term list as usual.
346
+
347
  **Non-negotiable, even inside a template.** A template cannot relax these:
348
  - **Safety.** If a student raises self-harm, harm to others, harassment, crisis, or food or housing insecurity at any point, including mid-activity, pause the activity, surface the relevant resource (Keefe, CAPS, Basic Needs Hub, Triton Concern Line, OSD, or the appropriate option from the "Off-topic concerns and student support" section above) clearly and immediately, and only resume the activity at the student's lead.
349
  - **Academic integrity.** Inside any template-driven activity, the rule on student-pasted multiple-choice, true/false, and fill-in-the-blank questions still applies: if a student transcribes a question from a course assessment and asks you to answer it, do not give the answer. Switch to Socratic discussion of their reasoning instead. Likewise, do not help with what reads as live-exam content.
 
351
 
352
  **Duration.** Once an activity has begun, remain in that activity's mode until it reaches a natural conclusion. For a game, that means seeing the round through (state the items, let the student respond, give feedback, optionally offer another round). For a study plan or schema map, that means iterating with the student to refine the artifact. Once the activity completes, or the student clearly moves to a different topic or term, drift back to the default Socratic teaching loop.
353
 
354
+ **Anchor to '{selected_term}' unless the template directs otherwise.** Most activities should be about or anchored to '{selected_term}'. If the template's design explicitly broadens scope across the term list (for example, a "Connect Terms" activity) or explicitly redirects focus to other content (for example, an exam-review activity that tells you to set the selected term and term list aside), follow the template's direction. Do not let activities drift far from the student's selected focus without that explicit signal from the template.
355
 
356
  # Output rules (default constraints, may be overridden by an active activity template)
357
 
exam_questions_s26.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Question bank for BILD 5 Spring 2026 midterm and final exams.
2
+ # Used by the "Review exam questions" prompt template in config.py.
3
+
4
+ EXAM_QUESTION_BANK = '''
5
+ --------------------------------
6
+
7
+ # BILD 5 – Spring 26 Midterm Exam – Reuther
8
+ **38 points**
9
+
10
+ ## MULTIPLE CHOICE SECTION (1 point each — choose the single most appropriate answer):
11
+
12
+ 1. Two researchers describe their daily work. Researcher X spends most of each day taking measurements at a lab bench, recording observations in a paper notebook, and sending samples to a shared facility for processing. Researcher Y spends most of each day writing code to clean and analyze data, building statistical models, and producing visualizations from large datasets. Which statement best describes the value of computational/programming skills for these two researchers? a) Only Researcher Y benefits from computational skills, because Researcher X has no data to analyze b) Researcher X has no need for these skills now, but the data Researcher X generates will eventually need to be cleaned, analyzed, and visualized — so even bench-based researchers benefit from understanding how their data are processed c) Both researchers benefit equally from coding skills regardless of their workflow, because all biology skills and tasks require computational skills.
13
+
14
+ 2. You collect data on bumblebee foraging with the columns: bee_id, date, flower_species, visit_duration_sec, pollen_load_mg, ambient_temp_C, wind_speed_mps . Each row represents one observed flower visit by one bee. Is this dataset "tidy"? a) No — bee-related and weather-related columns should be in separate tables b) Yes — each row is one observation and each column is one variable c) Yes — but only after reshaping to one row per bee_id
15
+
16
+ 3. A biologist measures a continuous trait in a large sample and finds the data are heavily right-skewed. Which measure best represents the "typical" value? a) Mean, because it uses every value in the dataset and gives the most complete picture b) Median, because it is robust to extreme values c) Mode, because the most frequent value best represents a typical individual
17
+
18
+ 4. A researcher reports the variance of leaf nitrogen content across 50 plants. A student asks what this variance value means. Which interpretation is correct? a) It is the average nitrogen content across the 50 plants b) It is the difference between the most and least nitrogen-rich plants in the sample c) It captures how far each measurement typically deviates from the mean, as the average squared residual
19
+
20
+ 5. A student studying butterfly wing length doesn't know whether the underlying population distribution is normal or not. To find out something useful for their analysis, they take 100 random samples of n = 50 butterflies each and plot the distribution of the 100 sample means. The histogram of sample means looks approximately normal and bell-shaped. What can the student reasonably conclude? a) The original population of butterfly wing lengths must also be approximately normal, since the sample means are b) Nothing — the sample means must always look normal regardless of the population, so this histogram tells the student nothing about either the population or the analysis c) The Central Limit Theorem is working as expected, so the student can use methods that assume the sampling distribution of the mean is normal — even though the underlying population shape remains unknown
21
+
22
+ 6. A researcher is preparing to test whether plants grow taller when given a new fertilizer compared to plain water. They write three candidate null hypotheses on the whiteboard. Which one is correctly stated? a) H ₀ : The fertilizer has a real effect on plant growth b) H ₀ : There is no difference in mean plant height between fertilizer-treated and water-only plants (μ_ fertilizer = μ_ water) c) H ₀ : Fertilizer-treated plants will reach a different height than water-only plants
23
+
24
+ 7. You are comparing leaf surface area between two oak species. A histogram shows one species has a roughly normal distribution while the other is strongly right-skewed. To proceed with a t-test, you should: a) Check sample sizes and consider transformations or non-parametric alternatives b) Use the t-test anyway because one of the two groups is normal c) Drop the skewed group entirely from the analysis
25
+
26
+ 8. In a power analysis for an experiment on zebrafish development, increasing your sample size from n = 12 to n = 60 per group while keeping all other parameters constant will: a) Make the underlying biological effect size larger b) Increase your ability to detect a true effect if one exists c) Guarantee that your result will be statistically significant
27
+
28
+ 9. Three researchers each conduct a hypothesis test. Which researcher has committed a Type I error? a) Researcher A obtains p = 0.04 with α = 0.05 and rejects the null. In reality, no effect exists in the population b) Researcher B obtains p = 0.20 with α = 0.05 and fails to reject the null. In reality, an effect does exist in the population c) Researcher C obtains p = 0.80 with α = 0.05 and fails to reject the null. In reality, no effect exists in the population
29
+
30
+ 10. A researcher conducts a small study and finds a Cohen's d of 1.2 for the difference in leaf color between two ornamental plant varieties (p = 0.01). She concludes the result is biologically very important because the effect size is large. Why is her reasoning flawed? a) Cohen's d values above 1 are statistically suspect and usually indicate a calculation error b) Effect size is only meaningful when paired with a non-significant p-value, so her conclusion contradicts itself c) Effect size is a statistical measure of magnitude; biological importance depends on context and judgment, not on the size of the statistic
31
+
32
+ 11. A graduate student is preparing a figure for publication showing the mean stem length of 50 sunflowers from one experimental plot. The student wants to communicate to readers how confident they should be that the reported mean accurately represents the true mean of all sunflowers in that plot. Which statistic should appear as the error bar on the mean? a) The standard deviation, because it shows readers the actual spread of stem lengths in the data b) The standard error, because it shows readers the precision of the estimated mean c) Either is fine, because for any sample size SD and SE communicate the same information about the mean
33
+
34
+ 12. A researcher reports a 95% confidence interval for mean nestling mass: [12.4 g, 14.8 g]. A student in the lab interprets this as: "There's a 95% chance that any randomly chosen nestling has a mass between 12.4 g and 14.8 g." Why is the student's interpretation incorrect? a) The 95% applies to the procedure, not to the data: if we repeated this study many times, about 95% of the resulting confidence intervals would contain the true mean nestling mass — the interval is about the mean of the population, not about individual nestlings b) The student should have written 5%, since the alpha level is what determines the percentage c) The student is correct — 95% confidence intervals do tell us about the range of individual values in the population
35
+
36
+ 13. An agricultural company tests a new growth additive on a very large flock of chickens and finds it increases body mass at slaughter by a tiny fraction of a percent. The result is highly statistically significant (p < 0.001). The marketing team wants to advertise the additive as "significantly improves growth." As the data scientist, your primary concern is that: a) The effect is statistically significant but practically meaningless b) The p-value is so small it suggests the test is unreliable at this sample size c) The sample size is too large for valid statistical inference
37
+
38
+ 14. A student tries to create two separate R objects with these lines, run independently in two different sessions: replicate_alpha <- 22 replicate_alpha <- 24 What is the result of running each line? a) The first line runs successfully, but the second line produces an error because replicate_alpha already exists and R does not allow an object name to be reused b) Both lines run successfully; after the second line, replicate_alpha holds the value 24 because R silently overwrites existing objects when the same name is reassigned c) The first line runs successfully, but the second line produces a warning and replicate_alpha retains its original value of 22 unless the warning is dismissed
39
+
40
+ 15. A biologist measures stem length in 60 sunflowers from a single field and calculates a mean of 142 cm. The biologist then writes: "Based on my data, I want to make a claim about how tall sunflowers grow." Why does the biologist need statistics rather than simply reporting the sample mean as the answer? a) Because the sample of 60 sunflowers IS the population of interest, and statistics are used to summarize all members of a population b) Because statistics convert sample data into population data by extrapolating measurements to unmeasured individuals c) Because the biologist actually wants to draw a conclusion about a larger population of sunflowers but only has data from a sample — statistics are needed to make inferences about the population from the sample
41
+
42
+ (Original exam included a figure — see BILD5_S26_Midterm.pdf in Resources.)
43
+
44
+ 16. Look at the figure above, which displays a t-distribution, the critical thresholds (alpha) and a measured sample t-statistic (t_{obs}). Assume that the distribution shown—which is centered exactly on zero—is the true distribution from which the data actually arise. Based on this assumption and the outcome shown in the figure, what type of result does this represent? a) True Positive b) False Positive c) True Negative d) False Negative
45
+
46
+ 17. A field ornithologist measures meal mass (g) delivered to warbler nestlings and obtains 14 typical values between 0.5 g and 12 g, plus a single recorded value of 1673.789 g — biologically impossible for a warbler chick's meal. The most appropriate handling of this value is: a) Remove (trim) it from the analysis because it is an impossible value, almost certainly a recording error b) Winsorize it down to the 95th percentile because it carries some biological information c) Apply a log transformation so the value no longer dominates the analysis
47
+
48
+ 18. A student wants to compare the distribution of leaf area (a continuous variable) across three different forest sites (a categorical variable) and is choosing which ggplot geom to use. Which choice best matches the visualization goal? a) geom_point() with site on the x-axis and leaf area on the y-axis, because individual data points are always the most informative display b) geom_bar() with site on the x-axis, because bar plots are the only valid choice when the x-axis variable is categorical c) geom_boxplot() with site on the x-axis and leaf area on the y-axis, because it displays the median, IQR, and spread for each site side-by-side
49
+
50
+ 19. Consider a typical test statistic structured as signal-over-noise (e.g., a t-statistic). All else equal, which combination would produce the LARGEST test statistic and thus the strongest evidence against the null hypothesis? a) A large difference between group means combined with small within-group standard deviations b) A small difference between group means combined with small within-group standard deviations c) A large difference between group means combined with large within-group standard deviations
51
+
52
+ 20. A researcher reports that their t-test comparing two species produced p = 0.03. A student writes in their lab notebook: "This means there is a 3% chance that the null hypothesis is true." Why is the student's interpretation incorrect? a) The student is correct — that is exactly what a p-value of 0.03 means b) The p-value tells us whether the difference between the two species is real, not whether the null hypothesis is true c) The p-value tells us, assuming the null hypothesis is true, the probability of getting a test statistic at least as large as the one observed — it does not tell us the probability that the null itself is true
53
+
54
+ 21. A senior biology major argues to a younger student: "I'm going to work in a lab doing experiments, so I don't really need to learn coding or data analysis — those skills are only for people who do computer-based research." Which response best captures why this view is incorrect? a) Modern biology of nearly every kind generates large datasets — from images and recordings to automated measurements and surveys — and the researchers who can analyze their own data are better positioned to ask, answer, and communicate scientific questions b) Coding skills are only useful for researchers who plan to publish in computer-science journals; people who work in laboratories without publishing computational work can safely skip them c) Coding is no longer needed in biology because modern AI tools and graphical software now perform all data analysis automatically without human input
55
+
56
+ 22. A researcher runs a study with low statistical power (power = 0.40). Assuming the alternative hypothesis is true (a real effect exists), what is the probability that the researcher will fail to detect that effect — that is, commit a Type II error (β)? a) 0.05, because alpha sets the false negative rate b) 0.60, because power is defined as 1 − β, so β = 1 − 0.40 c) 0.40, because power and beta are equal when both are below 0.50
57
+
58
+ 23. In a hypothesis test, the underlying reality is unknown but can be either "effect exists" or "no effect." The data lead the researcher to either reject or fail to reject the null. Which combination represents a TRUE POSITIVE? a) An effect truly exists in reality, and the data lead the researcher to reject the null hypothesis b) No effect exists in reality, and the data lead the researcher to fail to reject the null hypothesis c) An effect truly exists in reality, but the data lead the researcher to fail to reject the null hypothesis
59
+
60
+ 24. A student argues: "I don't see why we need formal statistics and the scientific method. If I observe something happen consistently, I can just trust my own observations — humans have evolved to recognize patterns in nature." Which response best captures why the scientific method and statistical reasoning are necessary, even for careful observers? a) Human cognition is shaped by biases — confirmation bias, memory distortions — that make individual observation unreliable as a basis for scientific claims; the scientific method and statistics formalize what counts as evidence so that conclusions don't depend on any one person's perception b) Formal statistics are needed only for very large datasets that the human brain cannot process; for everyday biological observations, careful pattern recognition is sufficient c) The scientific method is primarily a cultural convention adopted by researchers; while it produces consistent results, it is not strictly necessary as long as observers are careful and honest
61
+
62
+ 25. A researcher runs a t-test in R comparing two feed types and gets the following output: Welch Two Sample t-test data: weights_meatmeal and weights_linseed t = 2.3542, df = 19.236, p-value = 0.02933 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: 6.495503 109.822679 sample estimates: mean of x mean of y 276.9091 218.7500 Using α = 0.05, what is the correct conclusion? a) Fail to reject the null hypothesis; there is no significant difference between the two feeds because the confidence interval contains values close to zero b) The result is inconclusive because the t-statistic is below 3, which is typically required for statistical significance c) Reject the null hypothesis; the data provide evidence that the two feeds produce different mean weights, with meatmeal producing higher weights on average than linseed.
63
+
64
+ ---
65
+
66
+ ## SHORT ANSWER SECTION:
67
+
68
+ 26. A student is trying to load a dataset of plant measurements and visualize it. They write the code below and run each section. The code produces TWO errors. Both errors and the relevant error messages are shown below. # (1) Load the data and assign it to an object 1plant_data <- read.csv("plants.csv") # Error message: # Error: unexpected symbol in "1plant_data" # After fixing the first error and successfully loading the data, # the student inspects the structure: # 'data.frame': 120 obs. of 4 variables: # $ plant_id : int 1 2 3 4 5 ... # $ treatment : chr "control" "fertilizer" "control" ... # $ height_cm : num 42.1 51.3 39.8 ... # $ leaf_count: int 8 11 7 9 ... # (2) The student now tries to make a scatterplot of height vs. leaf count, # colored by treatment group: library(ggplot2) ggplot(plant_data, aes(x = treatment, y = height_cm, color = leaf_count)) + geom_point() # The plot is produced, but it does NOT show what the student intended. # leaf_count appears as a continuous color gradient on the points, # and treatment appears on the x-axis instead of leaf_count. a) [2 points] Identify and fix the FIRST error (the one that produced "unexpected symbol"). Explain what is wrong with the line of code and write a corrected version. b) [2 points] Identify the mapping mistake in the ggplot code. Explain which variable is mapped to the wrong aesthetic, what the student likely intended, and write a corrected version of the aes() line.
69
+
70
+ (Original exam included a figure — see BILD5_S26_Midterm.pdf in Resources.)
71
+
72
+ 27. A researcher tested the hypothesis that a new soil treatment changes plant height. They collected height measurements from 35 plants per group across three groups (Control, Treatment A, Treatment B) and produced two different versions of a figure to communicate their results. Both figures use the SAME underlying data. FIGURE 1: FIGURE 2: a) [2 points] Identify TWO specific design choices that differ between the figures and explain why each makes Figure 2 a better representation of the data. b) [1 point] Based on Figure 2, do the three groups appear meaningfully different from one another? Briefly justify your answer using what you can see in the figure.
73
+
74
+ 28. A researcher wants to test whether a new vitamin supplement affects mouse body weight after four weeks. They plan to use n = 8 mice per group with α = 0.05. a) [2 points] Write a properly specified null and alternative hypothesis for this study. Be specific about the variables compared. b) [1 point] Suppose the researcher worries their study will not be powerful enough to detect a small effect. Name one thing they could change about the study (without changing α) that would increase the power, and explain in one sentence why it would help.
75
+
76
+ 29. Your friend is not a science major and asks you to explain something they heard about. Choose ONE of the scenarios below and write a clear explanation using concepts from BILD
77
+
78
+ 5. Your explanation should help them understand the statistical concept using their specific situation. [3 points] SCENARIO A: Effect Size vs. Statistical Significance Your friend reads a headline: "Major study of 50,000 people finds that drinking coffee daily is significantly linked to longer lifespan (p < 0.001)!" They say: "I'm going to start drinking coffee — it works!" Then they read the fine print: the study found coffee drinkers lived an average of 2 days longer than non-coffee drinkers. Use the distinction between statistical significance and effect size to explain why your friend's enthusiasm may be misplaced. OR SCENARIO B: Power and False Negatives Your friend's lab tested whether a new fertilizer increases tomato yield using only 6 plants per group. The experiment found a 15% yield increase, but the result was not statistically significant (p = 0.18). Your friend says: "So the fertilizer doesn't work — the test said no." Explain why the friend's conclusion is wrong using the concepts of statistical power and the difference between "no effect" and "no detected effect."
79
+
80
+ --------------------------------
81
+
82
+ # BILD 5 – Spring 26 Final Exam – Reuther
83
+ **60 points + 2 points extra credit**
84
+
85
+ ## MULTIPLE CHOICE SECTION (1 point each — choose the single most appropriate answer):
86
+
87
+ 1. A student is working with a dataset called wings that contains wing length measurements for birds in three forest types: old growth , secondary , and tree farm . The dataset has columns forest (character), species (character), and wing_mm (numeric). The student writes: wings |> group_by(forest, species) |> summarize(mean_wing = mean(wing_mm)) Which best describes the output of this code? - a) The overall mean wing length across all birds, ignoring forest and species. - b) The mean wing length for each species, pooled across all three forest types. - c) The mean wing length for each species within each forest type.
88
+
89
+ 2. A student opens a new RStudio session and immediately runs the following code to filter and summarize a dataset on penguins: penguins |> filter(species == "Adelie") |> summarize(mean_mass = mean(body_mass_g)) R returns the error could not find function "filter". What is the most likely cause? - a) The student has not loaded the tidyverse (or dplyr) package, so filter() is not available in the current session. - b) The pipe operator |> requires a special package to be installed first. - c) The variable species does not exist in any R dataset.
90
+
91
+ 3. A student is working with a dataset called plants that contains the following columns: plant_id (numeric), treatment (character — either "control" or "fertilizer"), biomass (numeric, in grams), and height_cm (numeric). The student writes: plants |> filter(treatment == "fertilizer") |> mutate(log_biomass = log(biomass)) |> ggplot(aes(x = log_biomass)) + geom_histogram() Which best describes the output of this code? - a) A histogram of the raw biomass values for all plants in the dataset. - b) A histogram of the log-transformed biomass values for plants in the fertilizer treatment only. - c) A scatterplot of biomass against treatment for plants in the fertilizer group.
92
+
93
+ 4. A student wants to create a scatterplot to visualize the relationship between body mass and flipper length in a dataset of penguins. They write the following code: penguins |> ggplot(aes(x = body_mass_g, y = flipper_length_mm)) |> geom_point() What is the result of running this code? - a) R will generate the requested scatterplot of flipper length against body mass. - b) R will return an error, because the pipe operator (|>) cannot be used to add layers to a ggplot object; the + operator must be used instead. - c) R will generate a blank plot, because geom_point() requires the variables to be explicitly redefined inside it when using the pipe.
94
+
95
+ 5. A biologist is analyzing data on 80 frogs and wants to test whether the number of eggs laid (a count, ranging from 0 to several hundred) is associated with female body mass. What storage type is most appropriate for the egg-count variable? - a) Factor, because egg counts naturally fall into categories. - b) Logical, because each female either laid eggs or did not. - c) Integer or numeric, because egg count is a quantitative variable.
96
+
97
+ 6. A graduate student wants to show how the average body mass of 200 elephant seals changes continuously over the months of a year. Which plot type best displays this trend? - a) Bar chart of mean mass per month. - b) Line plot of mean mass against month. - c) Boxplot of mass per month.
98
+
99
+ 7. A team has collected body length measurements for 200 fish across four different lakes. They want to visualize how the distribution of body lengths varies among lakes. Distributions with a single peak are called unimodal ; distributions with two or more peaks are called multimodal . In which scenario is a violin plot the better choice over a boxplot? - a) When the data are roughly symmetric and unimodal in each lake. - b) When some lakes' distributions are suspected to be multimodal — for example, one peak for juveniles and another for adults. - c) When the dataset contains many extreme outliers in each lake.
100
+
101
+ 8. A wildlife geneticist sequences DNA from 300 endangered mountain lions and looks for regions of the genome shaped by recent natural selection. Twenty years ago, a comparable study could analyze only 5 lions. Which best describes the contribution of modern computational tools to this work? - a) Modern tools allow detection of selection signals from variation across hundreds of genomes, patterns that were not detectable at the older, smaller scale. - b) Modern tools remove the need for prior knowledge about lion biology. - c) Modern tools guarantee that any pattern detected reflects natural selection rather than chance.
102
+
103
+ 9. A field biologist measures body length in 50 lizards. After data entry, they realize one value was recorded as 2230 mm instead of the correct 223 mm. The biologist has not yet corrected the typo. Compared with the corrected data, which summary statistic of the uncorrected data is least affected by this typo? - a) The mean - b) The median - c) The standard deviation
104
+
105
+ 10. A wildlife biologist surveys body mass in 50 island bears. The histogram of the data is clearly bimodal: most bears cluster around 100 kg (juveniles), and a second cluster sits around 350 kg (mature males). The biologist wants to report a single summary statistic for the "typical" bear in this population. Which is the most appropriate choice? - a) The mean, because it incorporates information from every bear. - b) The median, because it is robust to the unusual shape. - c) Neither a single mean nor a single median — when a distribution is bimodal, no single summary statistic faithfully represents a "typical" individual. The biologist should describe the bimodality directly or report a summary for each cluster.
106
+
107
+ 11. A graduate student increases their sample size from 30 to 60 mice in a study of body mass. The variability of body mass among individual mice is unchanged. What happens to the standard error of the mean, and why? - a) The standard error stays the same, because individual variability is what determines it. - b) The standard error gets smaller, because a larger sample is more representative of the underlying population — making the sample mean a more reliable estimate of the population mean. - c) The standard error gets larger, because there are now more measurements that can vary.
108
+
109
+ 12. Which of the following best describes the relationship between the standard error of the mean and the standard deviation of a sample? - a) Standard error of the mean describes variability among individual measurements; standard deviation describes uncertainty in the sample mean. - b) Standard error of the mean describes uncertainty in the sample mean; standard deviation describes variability among individual measurements. - c) Standard error of the mean and standard deviation are the same quantity calculated by different methods.
110
+
111
+ 13. A wildlife biologist reports that for a sample of 60 deer, the mean antler length is 28.4 cm with a 95% confidence interval of [27.1, 29.7]. A colleague concludes, "The true population mean must fall somewhere between 27.1 and 29.7 cm." What is the best critique of the colleague's claim? - a) The colleague is correct: a 95% CI is guaranteed to contain the true mean. - b) The colleague is overstating certainty — a 95% CI represents a procedure that captures the true mean 95% of the time across repeated samples, not a guarantee for any one interval. - c) The colleague has misread the CI — a 95% CI describes where 95% of individual deer fall, not the population mean.
112
+
113
+ 14. A microbiologist wants to test whether soil from a coffee farm has a different average pH than soil from a nearby forest. Which correctly states the null and alternative hypotheses? - a) H ₀ : the coffee soil has a higher pH than the forest soil. H ₐ : the coffee soil has a lower pH than the forest soil. - b) H ₀ : the mean pH differs between the two soil types. H ₐ : the mean pH is the same. - c) H ₀ : the mean pH does not differ between the two soil types. H ₐ : the mean pH differs between the two soil types.
114
+
115
+ 15. A researcher samples 100 fish from a lake and finds that the distribution of individual body lengths is strongly right-skewed (a few very long fish pull the tail to the right). The researcher wants to estimate the mean body length of fish in the lake. According to the Central Limit Theorem, what can the researcher reasonably assume about the distribution of sample means in this situation? - a) The sample means will be right-skewed in the same way the individual data are skewed. - b) When the sample size is large enough, the distribution of sample means is approximately normal — even when the individual data are not normal. - c) The Central Limit Theorem does not apply to skewed data; the researcher must transform the data first.
116
+
117
+ 16. A biologist measures bacterial colony counts on 80 petri dishes and finds the data are strongly right-skewed, with most counts under 50 but a few over
118
+
119
+ 500. The biologist wants to compare two treatments with a two-sample t-test. Which approach best addresses the skewness while preserving the original research question? - a) Apply a log transformation to the counts, then run the t-test on the log-transformed values. - b) Remove the high counts and run the t-test on the remaining values. - c) Run the t-test on the raw skewed data, since t-tests are completely robust to skewness in all cases.
120
+
121
+ 17. A field biologist measures water temperature at 30 different locations along a single stream and uses these 30 measurements to estimate the average temperature of the stream. They then run a one-sample t-test assuming the 30 measurements are independent. Why might the independence assumption be problematic in this study? - a) Sample sizes of 30 are always too small for the independence assumption to hold. - b) Independence is only required for two-sample tests, not for one-sample tests. - c) Measurements taken close together along the same stream are likely to be more similar to each other than measurements drawn at random — so the 30 readings may not be statistically independent.
122
+
123
+ 18. A pharmacologist tests whether a new drug lowers blood pressure. The drug really does lower blood pressure on average, but the pharmacologist's small-sample study returns p = 0.21 and they fail to reject the null hypothesis. Which best describes this outcome? - a) Type I error (false positive) — they concluded there is an effect when there is none. - b) Type II error (false negative) — they failed to detect a real effect. - c) Correct conclusion (true negative) — there is no real effect.
124
+
125
+ 19. A study reports p = 0.001 for a comparison of mean height between corn plants grown with two fertilizers. The difference in sample means is 0.2 mm. The sample size in each group is 50,000 plants. Which interpretation is most appropriate? - a) Because p < 0.05, the fertilizers cause an important difference in plant height. - b) The result is statistically significant, but the 0.2 mm effect size may not be biologically meaningful. - c) The p-value is too small to be valid; the analysis must be repeated.
126
+
127
+ 20. A researcher is designing a clinical trial and considering trade-offs between several design choices. Holding every other choice constant, which single change will both decrease the false-positive rate and decrease the power of the study? - a) Decreasing the significance threshold α from 0.05 to 0.01. - b) Increasing the sample size per group. - c) Increasing the expected effect size of the intervention.
128
+
129
+ 21. A team is planning a study comparing two diets in mice. Their pilot data suggest the difference in mean weight gain between diets will be small. To achieve 80% power to detect this small effect at α = 0.05, which change most directly increases their chance of detecting the effect if it is real? - a) Increase the sample size per group. - b) Switch from a two-tailed to a one-tailed test. - c) Decrease α from 0.05 to 0.01.
130
+
131
+ 22. A nutritionist measures vitamin D blood levels in 30 indoor-working office employees and 30 outdoor-working construction employees. The vitamin D levels are approximately normal in both groups and the variances are similar. Which test directly evaluates whether the mean vitamin D level differs between the two occupations? - a) Paired t-test - b) Chi-squared test of independence - c) Two-sample t-test
132
+
133
+ 23. A wildlife biologist wants to know whether the mean body mass of a sample of 40 deer differs from a published historical mean of 70 kg. Which test is most appropriate? - a) One-sample t-test - b) Two-sample t-test - c) Chi-squared goodness-of-fit test
134
+
135
+ 24. A plant biologist measures the height of 30 bean seedlings on Monday and again on Friday of the same week. The biologist wants to know whether the seedlings grew on average during that week. Which test is most appropriate? - a) Two-sample t-test, treating Monday and Friday measurements as independent groups. - b) Paired t-test on the within-seedling difference (Friday − Monday). - c) One-way ANOVA, treating the two time points as separate groups.
136
+
137
+ 25. A scientist tests whether four diets (A, B, C, D) produce different mean weight gains in rats. The one-way ANOVA returns F = 5.2, p = 0.002. Which is the most appropriate conclusion from this ANOVA result alone? - a) At least one of the four diets produces a different mean weight gain from at least one other. - b) All four diets produce different mean weight gains from each other. - c) Diet A produces the largest mean weight gain.
138
+
139
+ 26. A geneticist wants to test whether eye color (blue, brown, green) is associated with hair color (blonde, brown, black) in a sample of 400 students. The data are counts in each eye-color/hair-color combination. Which test is most appropriate? - a) One-way ANOVA - b) Chi-squared goodness-of-fit test - c) Chi-squared test of independence
140
+
141
+ 27. A graduate student is designing a study of whether a new herbicide reduces germination rates in a crop species. What is the most important reason to first review the published literature on this herbicide before designing the experiment? - a) To identify concentrations that have been shown to be biologically meaningful and to anticipate confounding variables documented in prior work. - b) To find a previous study with a similar conclusion that can be cited as authority for the new study's hypothesis. - c) To confirm that no one has previously tested this exact question, so the new study can be reported as novel.
142
+
143
+ 28. A linear regression of fruit weight (in grams) on sunlight exposure (in hours per day) yields a slope of 2.5, a p-value of 0.02, and an R² of 0.30. Which statement is the best interpretation of this R² value? - a) There is a 30% probability that the relationship between sunlight and fruit weight is due to chance. - b) Sunlight exposure accounts for about 30% of the variation in fruit weight in this sample. - c) For every 1-hour increase in sunlight, the average fruit weight increases by 30%.
144
+
145
+ 29. A team fits a linear regression model and inspects a plot of the model's residuals against the fitted values. The plot shows a clear funnel shape, with residuals close to zero at low fitted values and spreading widely at high fitted values. Which assumption of linear regression is most directly violated? - a) Homoscedasticity (constant variance of residuals across fitted values). - b) Linearity of the relationship. - c) Independence of observations.
146
+
147
+ 30. A researcher tests whether a new fertilizer increases tomato yield. They apply the fertilizer to all plants in Greenhouse A and no fertilizer to all plants in Greenhouse B. They find higher yield in Greenhouse A. What is the most important weakness in this design? - a) The researcher did not randomly sample plants within each greenhouse to estimate yield, so the sample means may not accurately represent each greenhouse. - b) The researcher should have included a third greenhouse with a different fertilizer dose to estimate a dose-response relationship. - c) The two greenhouses may differ in other environmental variables (light, temperature, humidity, soil composition), so any yield difference could be due to those variables rather than the fertilizer.
148
+
149
+ 31. A graduate student is running a three-step biological protocol to detect a particular protein in cell samples. The three steps are performed in sequence, and each step relies on the product of the previous step: Step 2 uses the output of Step 1, and Step 3 uses the output of Step
150
+
151
+ 2. At each step the student includes both a positive control and a negative control. After running the protocol they observe: - Step 1 : positive control shows the expected signal; negative control shows an expected lack of signal. - Step 2 : positive control shows NO signal; negative control shows an expected lack of signal. - Step 3 : positive control shows NO signal; negative control shows an expected lack of signal. The experimental samples also show no signal after Step
152
+
153
+ 3. Based on these control results, what is the most likely problem and the most appropriate next step? - a) Cross-contamination has occurred somewhere in the protocol; the student should sterilize all equipment and re-run from Step
154
+
155
+ 1. - b) The protocol is functioning correctly; the experimental samples truly have no protein of interest, and the result should be reported. - c) Something has gone wrong at Step 2, and because the downstream steps depended on Step 2's output, the student should troubleshoot Step 2 (reagents, temperature, timing, equipment) before trusting any sample results. - d) Something has gone wrong with both Step 2 and Step 3; the student should spend time troubleshooting both steps simultaneously.
156
+
157
+ 32. A biologist wants to estimate the average pH of soil along a 5-kilometer river. They walk along the river and collect a soil sample every 500 meters. Which sampling technique best describes what they are doing? - a) Systematic sampling — collecting samples at regular fixed intervals along a gradient. - b) Cluster sampling — dividing the river into separate clusters and randomly selecting which clusters to sample. - c) This approach is invalid because samples must be chosen using a random number generator; collecting at regular intervals introduces bias.
158
+
159
+ 33. A researcher wants to estimate the average bill length of all rufous hummingbirds (a small migratory hummingbird species) across North America. Due to logistical constraints, the researcher can only capture and measure rufous hummingbirds that pass through three banding stations in Oregon. Which statement best distinguishes the biological population from the statistical population ? - a) The biological and statistical populations are the same — any researcher studying rufous hummingbirds is automatically studying all of them. - b) The biological population is all rufous hummingbirds in North America. Inferences from the sample apply most directly to the biological population, because that is the group the researcher cares about. - c) The biological population is all rufous hummingbirds in North America. The statistical population — the group from which the data are actually drawn — is rufous hummingbirds that pass through these three Oregon banding stations. Inferences from the data apply most directly to the statistical population.
160
+
161
+ 34. A team wants to test whether a new pain medication reduces self-reported pain in patients undergoing knee replacement surgery. They also want to know whether pain outcomes differ among age groups, because age is one of the variables they plan to include in their final hypotheses. They sort patients into three age groups: under 50, 50–65, and over
162
+
163
+ 65. Within each age group, they randomly assign half to the medication and half to the placebo. Which design best describes this approach? - a) Stratification - b) Blocking - c) Full factorial design
164
+
165
+ 35. A team wants to study the association between a workplace chemical and a rare lung cancer that affects only 1 in 50,000 workers. They identify 100 workers diagnosed with the cancer and 100 demographically similar workers without it, then compare each group's history of exposure to the chemical. Which experimental design best describes this study? - a) Case-control study — researchers begin with disease status (cases vs. controls) and look backward at past exposures. - b) Crossover study — each worker receives every treatment in sequence, serving as their own control. - c) An invalid design — because the researcher cannot control which workers have the disease, no useful comparison can be made. - d) This would not be an ethical study because it involves exposure to noxious chemicals.
166
+
167
+ 36. A researcher publishes a paper based on genetic data from 500 patients with a rare disease. Other researchers ask whether the data will be made available for independent verification. Which option best reflects ethical and scientific best practice? - a) Share the data after de-identifying it and removing any information that could re-identify individual participants, consistent with the original consent agreement. - b) Share the de-identified data only with researchers who first sign a non-disclosure agreement, ensuring no one can use the data to challenge the original published conclusions. - c) Refuse to share the data, since other researchers might reach different conclusions.
168
+
169
+ 37. A team is comparing two pain medications (A and B) in 30 chronic-pain patients. Each patient takes Medication A for two weeks, washes out for one week, then takes Medication B for two weeks. To check that the order does not affect results, the team randomly assigns half the patients to receive A first and the other half to receive B first. Which experimental design best describes this approach? - a) Repeated-measures design — patients are measured under different conditions in chronological sequence, and the order itself is part of the design (as in before-and-after comparisons). - b) Case-control study — patients are grouped by disease status and compared on past exposures. - c) Crossover study — each patient receives both treatments, but the order is randomized so that order does not bias the comparison. Each patient still serves as their own control.
170
+
171
+ 38. A graduate student wants to use a generative AI assistant to write R code for analyzing their thesis data. Which workflow is the most effective way to use AI in this context? - a) The student types a one-line prompt ("write code to analyze my data"), copies the response into RStudio, and runs it as long as it executes without errors. - b) The student writes the full analysis script themselves first, then asks the AI to clean up the formatting and improve the comments before submission. - c) The student writes a detailed description of their data, their analysis goals, and the statistical approach they want; asks the AI to draft the code; then evaluates the draft, refines the parts that do not match their intent, and tests the result against data with known outputs to verify it works correctly. Exam continued on the next page
172
+
173
+ ---
174
+
175
+ ## SHORT ANSWER SECTION:
176
+
177
+ Question 1 (3 points) A plant biologist wants to test whether bean plants grown on a once-per-day watering schedule produce different average leaf widths than bean plants grown on a once-every-three-days watering schedule. They grew 20 plants on each schedule under otherwise identical conditions and measured the widest leaf on each plant (in millimeters) at six weeks. (a) [1 point] State the null hypothesis (H ₀ ) and the alternative hypothesis (Hₐ) for this study. You may write each hypothesis as a sentence, as a mathematical statement, or both — any clearly written form is acceptable. (b) [1 point] Name the statistical test the biologist should use to evaluate these hypotheses. Justify your choice in one sentence. (c) [1 point] List two assumptions the test makes about the data. For each assumption, briefly state one way the biologist could check it.
178
+
179
+ (Original exam included a figure, plot, or R output — see BILD5_SP26_Final.pdf in Resources.)
180
+
181
+ Question 2 (5 points) A physiologist measured maximal oxygen consumption (VO ₂ max, in milliliters of oxygen per minute per gram of body mass) in 34 mice. Each mouse was tested once and then again 24 hours later. The biologist wants to know whether the second measurement systematically differs from the first measurement. The R output, a histogram of the within-mouse differences (Second − First), and a scatterplot of each mouse's First measurement against its Second measurement appear below. (a) [1 point] What statistical test is being performed in the R output? (b) [2 points] Based on results shown above, does the normality assumption of the test appear to be reasonably satisfied? Briefly explain by listing two pieces of evidence to support your conclusion. The dashed line in the scatterplot is NOT a linear regression. Dots that sit on the line have identical before and after values. (c) [2 points] Using the test result, state your conclusion about whether the second VO ₂ max measurement differs from the first measurement in this group of mice. Your answer must reference the p-value and, if there is an effect, its direction (e.g., positive or negative)
182
+
183
+ (Original exam included a figure, plot, or R output — see BILD5_SP26_Final.pdf in Resources.)
184
+
185
+ Question 3 (4 points) A field ecologist measured body mass (in grams) in three species of small African seed-eating birds: the white-browed sparrow weaver (a sparrow-sized bird), the crimson-rumped waxbill (a very small finch-like bird), and the cutthroat finch (a medium-sized finch). The researcher wants to know whether average body mass differs across these three species. (a) [1 point] Using the ANOVA output below ALONE , state your conclusion and what specifically in the result supports your interpretation. (b) [1 point] Using the Tukey HSD output below ALONE , identify which pairs of species differ significantly in average body mass. For each significant pair, state which species is heavier. (c) [2 points] The ecologist just realized they forgot to plot their data. Based on the plot below:
186
+
187
+ 1. What would your next step be? There are many correct answers to this, we only need one.
188
+
189
+ 2. How does this impact your previous interpretation from steps a and b?
190
+
191
+ Question 4 (3 points) A team of agricultural scientists wants to test whether a newly developed variety of wheat produces a higher average yield than the standard variety. They have access to a 5-acre experimental field that has been divided into 30 equal-sized plots, and they will assign each plot to grow one of the two varieties. The scientists notice that soil fertility varies across the field: plots at the eastern end of the field tend to have noticeably richer soil than plots at the western end. (a) [1 point] Identify one variable in this study that could confound the comparison between the two wheat varieties and would be considered a nuisance variable. (b) [2 points] Describe an experimental design the team could use to control for the confound you identified. Your description should be specific enough that another scientist could follow it without asking you for clarification.
192
+
193
+ (Original exam included a figure, plot, or R output — see BILD5_SP26_Final.pdf in Resources.)
194
+
195
+ Question 5 (4 points) A scientist studied beak length (in mm) in three species of small African seed-eating birds. They produced the figure below to summarize their data. (a) [3 points] Identify three specific problems with this figure that limit how clearly it communicates the data. Briefly explain why each one is a problem. (b) [1 point] Describe a single alternative figure that would better communicate the same data. Limit your description to only list the type of plot and the variables on each axis.
196
+
197
+ Question 6 (3 points) A team of epidemiologists wants to test whether early-life exposure to a common agricultural pesticide is associated with a higher risk of developing Parkinson's disease later in adulthood. The team is choosing between two study designs: - Design A (prospective): Recruit 5,000 children today, measure their pesticide exposure each year, and follow them for the next 50 years to track who develops Parkinson's disease. - Design B (historical / retrospective): Identify 5,000 adults currently diagnosed with Parkinson's disease and 5,000 adults without it, then look back at existing medical and agricultural records to estimate each person's childhood pesticide exposure. (a) [1 point] Identify one ethical concern that one of these two designs raises more strongly than the other. Name the design ( A or B) and briefly explain the concern. (b) [2 points] Identify one financial cost or logistics tradeoff between Design A and Design B. State which design has the advantage on that tradeoff, and briefly explain your reasoning in one or two sentences.
198
+
199
+ Extra Credit (2 points) Pick one concept from the list below, define it in your own words, and explain how it connects to any one other course concept. - Tidy data - Covariance and correlation - Pseudoreplication (You must mention experimental units and observational units.) - The multiple comparisons problem of running many statistical tests on the same data set
200
+
201
+ END OF EXAM
202
+
203
+ '''
requirements.txt CHANGED
@@ -1,6 +1,5 @@
1
- openai
2
- openapi-schema-pydantic==1.2.4
3
  pandas==2.2.3
4
- pydantic>=2.10.0,<3
5
  streamlit
6
- httpx==0.24.1
 
1
+ litellm
2
+ python-dotenv
3
  pandas==2.2.3
4
+ pypdf
5
  streamlit