Spaces:
Runtime error
Runtime error
File size: 7,643 Bytes
42202c9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | """Classroom Space: students prompt an OpenAI model, the teacher watches prompts and
token usage, and everyone can follow the teacher's own prompts live."""
import os
import tempfile
import threading
from dataclasses import asdict, dataclass
from datetime import datetime
import gradio as gr
import pandas as pd
from openai import OpenAI, OpenAIError
def require_env(name: str) -> str:
value = os.environ.get(name, "").strip()
if not value:
raise RuntimeError(f"Missing Space secret: {name}")
return value
CLASS_CODE = require_env("CLASS_CODE")
TEACHER_CODE = require_env("TEACHER_CODE")
MODEL = os.environ.get("OPENAI_MODEL", "gpt-4o-mini")
TOKEN_LIMIT = int(os.environ.get("TOKEN_LIMIT_PER_STUDENT", "0")) # 0 = unlimited
TEACHER = "Teacher"
REFRESH_SECONDS = 3
client = OpenAI(api_key=require_env("OPENAI_API_KEY"))
# --- In-memory class log (resets when the Space restarts) -------------------
@dataclass
class Entry:
time: str
user: str
prompt: str
answer: str
input_tokens: int
output_tokens: int
entries: list[Entry] = []
lock = threading.Lock()
def entries_for(user: str) -> list[Entry]:
with lock:
return [e for e in entries if e.user == user]
def history_for(user: str) -> list[dict]:
"""A user's conversation, in the chat-message format both OpenAI and Gradio use."""
history = []
for e in entries_for(user):
history.append({"role": "user", "content": e.prompt})
history.append({"role": "assistant", "content": e.answer})
return history
def tokens_used(user: str) -> int:
return sum(e.input_tokens + e.output_tokens for e in entries_for(user))
def ask(user: str, prompt: str) -> None:
"""Send the prompt with the user's earlier conversation, and log the result."""
if TOKEN_LIMIT and user != TEACHER and tokens_used(user) >= TOKEN_LIMIT:
raise gr.Error(f"You've used your token allowance ({TOKEN_LIMIT}).")
messages = history_for(user) + [{"role": "user", "content": prompt}]
try:
response = client.chat.completions.create(model=MODEL, messages=messages)
except OpenAIError as err:
raise gr.Error(f"The model request failed: {err}")
entry = Entry(
time=datetime.now().strftime("%H:%M:%S"),
user=user,
prompt=prompt,
answer=response.choices[0].message.content or "",
input_tokens=response.usage.prompt_tokens,
output_tokens=response.usage.completion_tokens,
)
with lock:
entries.append(entry)
def usage_text(user: str) -> str:
limit = f" / {TOKEN_LIMIT}" if TOKEN_LIMIT and user != TEACHER else ""
return f"Tokens used: **{tokens_used(user)}{limit}**"
# --- Student tab ------------------------------------------------------------
def join(name: str, code: str):
name = name.strip()
if not name:
raise gr.Error("Please enter your name.")
if name.lower() == TEACHER.lower():
raise gr.Error(f'"{TEACHER}" is reserved. Please choose another name.')
if code.strip() != CLASS_CODE:
raise gr.Error("Wrong class code.")
return name, gr.update(visible=False), gr.update(visible=True), history_for(name), usage_text(name)
def student_send(user: str, prompt: str):
if not prompt.strip():
return gr.skip(), gr.skip(), gr.skip()
ask(user, prompt.strip())
return "", history_for(user), usage_text(user)
# --- Teacher tab ------------------------------------------------------------
def unlock(code: str):
if code.strip() != TEACHER_CODE:
raise gr.Error("Wrong teacher code.")
return gr.update(visible=False), gr.update(visible=True), gr.Timer(active=True)
def teacher_send(prompt: str):
if not prompt.strip():
return gr.skip(), gr.skip()
ask(TEACHER, prompt.strip())
return "", history_for(TEACHER)
def prompts_table() -> pd.DataFrame:
with lock:
rows = [asdict(e) for e in reversed(entries)]
return pd.DataFrame(rows, columns=list(Entry.__dataclass_fields__))
def usage_table() -> pd.DataFrame:
df = prompts_table()
if df.empty:
return pd.DataFrame(columns=["user", "prompts", "input_tokens", "output_tokens", "total_tokens"])
summary = df.groupby("user").agg(
prompts=("prompt", "count"),
input_tokens=("input_tokens", "sum"),
output_tokens=("output_tokens", "sum"),
)
summary["total_tokens"] = summary.input_tokens + summary.output_tokens
return summary.sort_values("total_tokens", ascending=False).reset_index()
def export_csv() -> str:
path = os.path.join(tempfile.gettempdir(), f"classroom_{datetime.now():%Y%m%d_%H%M%S}.csv")
prompts_table().to_csv(path, index=False)
return path
# --- UI ---------------------------------------------------------------------
with gr.Blocks(title="Classroom") as demo:
gr.Markdown(f"# Classroom\nModel: `{MODEL}`")
with gr.Tab("Student"):
student = gr.State("")
with gr.Column() as join_panel:
name_box = gr.Textbox(label="Your name")
code_box = gr.Textbox(label="Class code", type="password")
join_btn = gr.Button("Join", variant="primary")
with gr.Column(visible=False) as chat_panel:
student_chat = gr.Chatbot(type="messages", height=450)
student_prompt = gr.Textbox(label="Your prompt", lines=3)
student_btn = gr.Button("Send", variant="primary")
student_usage = gr.Markdown()
join_btn.click(
join,
[name_box, code_box],
[student, join_panel, chat_panel, student_chat, student_usage],
)
for trigger in (student_btn.click, student_prompt.submit):
trigger(student_send, [student, student_prompt], [student_prompt, student_chat, student_usage])
with gr.Tab("Follow the teacher"):
gr.Markdown(f"The teacher's prompts and answers. Updates every {REFRESH_SECONDS} seconds.")
feed = gr.Chatbot(type="messages", height=550)
gr.Timer(REFRESH_SECONDS).tick(lambda: history_for(TEACHER), outputs=feed)
with gr.Tab("Teacher"):
with gr.Column() as lock_panel:
teacher_code = gr.Textbox(label="Teacher code", type="password")
unlock_btn = gr.Button("Unlock", variant="primary")
with gr.Column(visible=False) as teacher_panel:
with gr.Row():
with gr.Column():
gr.Markdown("### Your prompts (shown live to students)")
teacher_chat = gr.Chatbot(type="messages", height=400)
teacher_prompt = gr.Textbox(label="Prompt", lines=3)
teacher_btn = gr.Button("Send", variant="primary")
with gr.Column():
gr.Markdown("### Token usage per person")
usage_df = gr.Dataframe(interactive=False)
export_btn = gr.Button("Export all prompts to CSV")
export_file = gr.File(label="CSV")
gr.Markdown("### All prompts (newest first)")
prompts_df = gr.Dataframe(interactive=False, wrap=True)
dashboard_timer = gr.Timer(REFRESH_SECONDS, active=False)
dashboard_timer.tick(lambda: (usage_table(), prompts_table()), outputs=[usage_df, prompts_df])
unlock_btn.click(unlock, teacher_code, [lock_panel, teacher_panel, dashboard_timer])
for trigger in (teacher_btn.click, teacher_prompt.submit):
trigger(teacher_send, teacher_prompt, [teacher_prompt, teacher_chat])
export_btn.click(export_csv, outputs=export_file)
if __name__ == "__main__":
demo.launch()
|