# -*- coding: utf-8 -*- import os import re import json import requests import gradio as gr import time # ----------------------------- # Prompt # ----------------------------- SYSTEM_PROMPT = """Du bist HomeworkBuddy, ein geduldiger und verständnisvoller Lern-Assistent für Schülerinnen (13-15 Jahre). Deine Mission: Helfen, schwierige Themen zu VERSTEHEN – nicht die Hausaufgaben zu machen! Regeln: - Antworte IMMER auf Deutsch - Erkläre Schritt-für-Schritt mit klarer Struktur - Nutze Alltagsbeispiele und Metaphern aus dem Leben von Teenagerinnen - Fächer: Mathe, Deutsch, Englisch, Naturwissenschaften - WICHTIG: Mache NIEMALS die Hausaufgaben komplett - erkläre nur das Konzept oder die Methode - Bei der direkten Frage "Löse diese Aufgabe" oder "Mach meine Hausaufgaben": Antworte mit "Ich erkläre dir gerne, WIE es geht – aber lösen musst du es selbst, damit du es wirklich verstehst!" - Sei nie ungeduldig oder herablassend - Bei zu komplexen Fragen für das Alter: "Das ist schon sehr fortgeschritten! Frag am besten deine Lehrerin." - Keine Ratschläge zu: Gesundheit, persönlichen Problemen, Politik - Zeige niemals interne Gedanken - Wiederhole NICHT die Frage Tonfall: Wie ein geduldiger Tutor, der wirklich will, dass die Schülerin es versteht – nicht nur die richtige Antwort bekommt. FORMAT DEINER ANTWORT (sehr wichtig — antworte NUR mit diesem JSON, keine Backticks, kein anderer Text): { "emoji": "", "intro": "<1 Satz Einleitung oder Alltagsmetapher>", "steps": [ {"label": "Schritt 1", "text": ""}, {"label": "Schritt 2", "text": ""} ], "tip": "" } Bei Fragen ohne Schritte: steps = [] Beispiel für "Was ist Prozentrechnung?": {"emoji":"🍰","intro":"Prozent bedeutet einfach 'von Hundert' – stell dir den ganzen Kuchen als 100% vor!","steps":[{"label":"Schritt 1","text":"Teile den Betrag durch 100, um 1% zu finden. z.B. 50 / 100 = 0,5"},{"label":"Schritt 2","text":"Multipliziere mit dem gewünschten Prozentsatz. z.B. 0,5 x 20 = 10 Euro"}],"tip":"Merke: % bedeutet immer / 100. Danach einfach mal den Prozentwert!"} """ MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct" ROUTER_CHAT_URL = "https://router.huggingface.co/v1/chat/completions" # ----------------------------- # Helpers # ----------------------------- def _maybe_fix_mojibake(text: str) -> str: if any(bad in text for bad in ["Ã", "â", "ð", "â"]): try: return text.encode("latin1").decode("utf-8") except Exception: return text return text def _parse_json(raw: str): """ Extract and parse JSON from LLM response """ # Clean up raw = re.sub(r".*?", "", raw, flags=re.DOTALL | re.IGNORECASE) raw = raw.replace("```json", "").replace("```", "").strip() raw = _maybe_fix_mojibake(raw) # Extract JSON between first { and last } if '{' in raw and '}' in raw: start_idx = raw.index('{') end_idx = raw.rindex('}') + 1 json_str = raw[start_idx:end_idx] try: parsed = json.loads(json_str) # Validate it has required keys if isinstance(parsed, dict) and 'intro' in parsed: return parsed except Exception as e: print(f"⚠️ JSON parse error: {e}") print(f"Attempted to parse: {json_str[:200]}...") return None def render_html(data: dict) -> str: emoji = data.get("emoji", "📚") intro = data.get("intro", "") steps = data.get("steps", []) tip = data.get("tip", "") steps_html = "" for i, s in enumerate(steps): steps_html += ( '
' '
{i+1}
' '
' f'
{s.get("label","")}
' f'
{s.get("text","")}
' '
' ) tip_html = "" if tip: tip_html = ( '
' '💡' f'{tip}' '
' ) mb = "14px" if steps_html else "6px" return ( '
' f'
' f'{emoji}' f'

{intro}

' '
' f'{steps_html}' f'{tip_html}' '
' ) def fallback_html(text: str) -> str: clean = re.sub(r".*?", "", text, flags=re.DOTALL).strip() clean = _maybe_fix_mojibake(clean) return f'

📚 {clean}

' # ----------------------------- # Chat function # ----------------------------- def chat(user_message, history): token = os.getenv("HF_TOKEN") if not token: yield "HF_TOKEN fehlt im Space (Settings → Secrets). 📚" return messages = [{"role": "system", "content": SYSTEM_PROMPT}] # Keep last 2 exchanges only recent_history = history[-2:] if len(history) > 2 else history print(f"📊 History: {len(history)} total, keeping: {len(recent_history)}") # Process history - ONLY keep user messages to avoid JSON pollution for item in recent_history: try: if isinstance(item, (list, tuple)) and len(item) >= 2: u = str(item[0]) if item[0] else "" # Skip assistant response entirely - don't send back to API if u: messages.append({"role": "user", "content": u}) except Exception as e: print(f"⚠️ Skipped history item: {e}") continue # Add current message messages.append({"role": "user", "content": user_message}) print(f"📝 Sending {len(messages)} messages to API") headers = { "Authorization": f"Bearer {token}", "Content-Type": "application/json; charset=utf-8", } payload = { "model": MODEL_ID, "messages": messages, "max_tokens": 400, "temperature": 0.4, "stream": True, } # Retry with backoff max_retries = 2 for attempt in range(max_retries): try: response_raw = "" with requests.post( ROUTER_CHAT_URL, headers=headers, json=payload, stream=True, timeout=90 ) as r: r.encoding = "utf-8" if r.status_code != 200: print(f"❌ API error {r.status_code} (attempt {attempt+1})") if r.status_code == 429 and attempt < max_retries - 1: time.sleep(2 ** attempt) continue if "model_not_supported" in r.text: yield "Upsi — dieses Modell ist gerade nicht verfügbar. 📚" else: yield "Upsi — gerade ist das Modell nicht erreichbar. 📚" return # Collect streaming response for line in r.iter_lines(decode_unicode=True): if not line or not line.startswith("data: "): continue data = line[len("data: "):].strip() if data == "[DONE]": break try: chunk = json.loads(data) delta = chunk["choices"][0].get("delta", {}).get("content") if delta: response_raw += delta except: continue # Process response AFTER streaming completes print(f"✅ Got response: {len(response_raw)} chars") print(f"First 100 chars: {response_raw[:100]}") # Try to parse JSON parsed = _parse_json(response_raw) if parsed: print(f"✅ JSON parsed successfully: {list(parsed.keys())}") # Render as HTML html_output = render_html(parsed) yield html_output else: print(f"⚠️ JSON parse failed, using fallback") # Use fallback yield fallback_html(response_raw) # Success - exit retry loop return except requests.exceptions.Timeout: print(f"⏰ Timeout (attempt {attempt+1})") if attempt < max_retries - 1: time.sleep(2) continue yield "Upsi — die Anfrage hat zu lange gedauert. 📚" return except Exception as e: print(f"❌ Error (attempt {attempt+1}): {repr(e)}") if attempt < max_retries - 1: time.sleep(2) continue yield "Upsi — gerade klappt die Verbindung nicht. 📚" return yield "Upsi — gerade klappt die Verbindung nicht. 📚" # ----------------------------- # UI # ----------------------------- demo = gr.ChatInterface( fn=chat, title="📚 HomeworkBuddy", description=( "**Willkommen bei HomeworkBuddy!**\n\n" "Ich helfe dir, schwierige Themen zu VERSTEHEN! Aber Achtung: Ich mache deine Hausaufgaben NICHT für dich - " "ich zeige dir, WIE du sie selbst lösen kannst! 🎓\n\n" "**Beispiel-Fragen:**\n" "- Was ist Prozentrechnung?\n" "- Erkläre mir das Dreisatz-Prinzip\n" "- Wie funktioniert Photosynthese?\n" "- Ich verstehe Bruchrechnung nicht\n\n" "Stell mir deine Fragen! 💪" ), examples=[ "Was ist 20% von 150?", "Erkläre mir Bruchrechnung", "Wie funktioniert Photosynthese?", "Was ist das Dreisatz-Prinzip?", "Kannst du meine Mathe-Hausaufgabe lösen?", ], chatbot=gr.Chatbot( height=480, sanitize_html=False, ) ) if __name__ == "__main__": demo.launch(ssr_mode=False)