# FILE: app.py # FINAL REFACTORED VERSION WITH ADVANCED UI/UX import gradio as gr import os import logging from typing import Dict, Any, List, Optional from dotenv import load_dotenv # --- Backend & Configuration Imports --- load_dotenv() import dspy from config import ( initialize_dspy, RateLimiter, STATE_STAGE, STATE_HISTORY, STATE_CURRENT_TITLE, STATE_GENERATED_TITLE, STATE_EXPLAINER_PROMPT, STATE_TRANSITION_EXPLAINER_FLAG, STAGE_START, STATE_IS_FIRST_TURN, DEFAULT_CHAT_TITLE, ) from orchestrator import process_chat_message, initialize_orchestrator_modules from resource_processor import process_uploaded_files # --- Setup Logging --- logging.basicConfig(level=logging.INFO, format='{levelname} {asctime} {name}: {message}', style='{') logger = logging.getLogger(__name__) # --- Application Mode & UI Configuration --- APP_MODE = os.getenv("APP_MODE", "visitor").lower() if APP_MODE not in ["admin", "visitor"]: raise ValueError("APP_MODE environment variable must be 'admin' or 'visitor'") UI_FEEDBACK_MAP = { "PROCESSING_INPUT": "🧠 Thinking...", "ANALYZING_RESOURCES_INITIAL": "📄 Analyzing your documents...", "GENERATING_SYLLABUS": "✍️ Crafting syllabus...", "EXPLAINER_RESPONSE": "💬 Tutor is responding...", # NOTE: The UI will use these for more granular feedback in the future if needed. # For now, we use a general "Thinking..." message for stability during backend processing. } # --- Helper & Core Functions --- def initialize_session_state() -> Dict[str, Any]: """Creates a fresh session state dictionary, including the initial greeting.""" initial_history = [{'role': 'model', 'parts': [{'text': "Hello! I'm ready to help build a personalized syllabus. What topic are you interested in learning about?"}]}] return { STATE_STAGE: STAGE_START, STATE_HISTORY: initial_history, STATE_CURRENT_TITLE: DEFAULT_CHAT_TITLE, STATE_IS_FIRST_TURN: True, } def start_session(api_key: str, api_tier: str): """ (Visitor Mode) Validates API, initializes backends, and transitions UI. ADDED: Debugging print statements to trace the authentication flow. """ # --- START OF DEBUG BLOCK --- print("\n--- [start_session] Function Entered ---") # Use slicing to avoid printing the full secret key in logs print(f"[start_session] Received API Key ending in: '...{api_key[-4:] if len(api_key) > 4 else api_key}'") print(f"[start_session] Received API Tier: {api_tier}") # --- END OF DEBUG BLOCK --- # --- Case 1: Empty API Key --- if not api_key.strip(): print("[start_session] DEBUG: Condition MET - API Key is empty or whitespace.") error_msg = "
API Key cannot be empty. Please provide a valid key.
" yield (gr.update(visible=True), gr.update(visible=False), None, gr.update(value=error_msg, visible=True)) print("--- [start_session] END ---\n") return # --- Case 2: Authentication with DSPy Fails --- print("[start_session] DEBUG: Attempting to call initialize_dspy...") # Store the result in a variable so we can print it auth_result = initialize_dspy(api_key=api_key) print(f"[start_session] DEBUG: Result from initialize_dspy is: '{auth_result}' (Type: {type(auth_result)})") if not isinstance(auth_result, list) : # print("[start_session] DEBUG: Condition MET - `if not auth_result` is TRUE. Authentication failed.") error_msg = "Authentication failed. The provided API key is invalid or has expired. Please check the key and try again.
" yield (gr.update(visible=True), gr.update(visible=False), None, gr.update(value=error_msg, visible=True)) print("--- [start_session] END ---\n") return print("[start_session] DEBUG: Condition SKIPPED - `if not auth_result` is FALSE. Assuming auth succeeded.") # --- Case 3: Backend Module Initialization Fails --- print("[start_session] DEBUG: Attempting to call initialize_orchestrator_modules...") modules_result = initialize_orchestrator_modules() print(f"[start_session] DEBUG: Result from initialize_orchestrator_modules is: {modules_result}") if not modules_result: print("[start_session] DEBUG: Condition MET - Backend module initialization failed.") error_msg = "Failed to initialize backend AI modules after authentication. Please contact support.
" yield (gr.update(visible=True), gr.update(visible=False), None, gr.update(value=error_msg, visible=True)) print("--- [start_session] END ---\n") return # --- Case 4: Success --- print("[start_session] DEBUG: All checks passed. Proceeding to success case.") max_calls = 7 if "Free" in api_tier else 1000 limiter = RateLimiter(max_calls=max_calls, time_period=60) yield ( gr.update(visible=False), # Hide API view gr.update(visible=True), # Show chat view limiter, # Set the rate limiter state gr.update(visible=False), # Hide the error message ) print("--- [start_session] END: UI transitioned successfully. ---\n") # FILE: app.py # REPLACE the existing function with this new "consumer" version. def handle_user_interaction( user_message: str, uploaded_files: Optional[List[Any]], current_state: Dict[str, Any], file_names_state: List[str], limiter: Optional[RateLimiter], modified_explainer_prompt: str ): """ Main generator function, refactored for cleaner history management and clarity while consuming the stream of updates from the orchestrator. """ # --- 1. PREPARATION AND UI UPDATE (YIELD 1) --- # Get the *current* UI-compatible history from the state for a clean start # We will build on top of this for all UI updates ui_history = [] is_first_turn = current_state.get(STATE_IS_FIRST_TURN, False) for msg in current_state.get(STATE_HISTORY, []): if msg.get('message_type') != "internal_resource_summary": role = "assistant" if msg.get("role") == "model" else "user" content = msg.get("content", "") or (msg.get("parts")[0].get("text", "") if msg.get("parts") else "") ui_history.append({"role": role, "content": content}) # Add the new user message in the clean UI format ui_history.append({"role": "user", "content": user_message}) # Add the initial placeholder for the bot's response/status ui_history.append({"role": "assistant", "content": f"*{UI_FEEDBACK_MAP['PROCESSING_INPUT']}*"}) # Update the backend-formatted history in the state for the orchestrator backend_history = current_state.get(STATE_HISTORY, []) backend_history.append({'role': 'user', 'parts': [{'text': user_message}]}) current_state[STATE_HISTORY] = backend_history # Handle file display logic (this part remains the same) all_file_names = sorted(list(set(file_names_state + [f.name for f in uploaded_files or []]))) file_display_md = "#### Uploaded Resources:\n" + "\n".join([f"- `{os.path.basename(name)}`" for name in all_file_names]) if all_file_names else "" file_uploader_visible = is_first_turn and not bool(uploaded_files) file_display_visible = bool(all_file_names) print("YIELD 1: Displaying user message and initial status.") yield ( gr.update(value=ui_history), # Use the cleanly built UI history gr.update(value=""), current_state, gr.update(visible=file_uploader_visible), gr.update(interactive=False), gr.update(), gr.update(), gr.update(value=file_display_md, visible=file_display_visible), all_file_names, gr.update(visible=False), gr.update(), gr.update() ) # --- 2. BACKEND PROCESSING (CONSUMER LOOP) --- orchestrator_kwargs = { "user_message_text": user_message, "current_session_state": current_state, "modified_explainer_prompt": modified_explainer_prompt or None, "uploaded_resource_data": process_uploaded_files(uploaded_files) if uploaded_files else None } current_state[STATE_IS_FIRST_TURN] = False if limiter: limiter.wait_if_needed() final_state = None try: # This loop consumes the `yield`ed updates from the backend orchestrator for update_type, payload in process_chat_message(**orchestrator_kwargs): if update_type == "status": status_message = UI_FEEDBACK_MAP.get(payload, "Processing...") # Update the last message in the chat (our status placeholder) ui_history[-1]['content'] = f"*{status_message}*" print(f"YIELD (Status Update): {status_message}") # Yield a UI update with the new status message yield ( gr.update(value=ui_history), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update() ) elif update_type == "final_result": final_state = payload break except Exception as e: logger.error(f"Orchestrator stream error: {e}", exc_info=True) current_state[STATE_HISTORY].append({'role': 'model', 'parts': [{'text': "An error occurred during processing."}]}) final_state = current_state # --- 3. FINAL UI UPDATE (YIELD 2) --- if not final_state: logger.error("Processing finished without a final state.") current_state[STATE_HISTORY].append({'role': 'model', 'parts': [{'text': "A critical error occurred."}]}) final_state = current_state # --- Final Robust Translator --- final_ui_history = [] for message in final_state.get(STATE_HISTORY, []): if message.get('message_type') == "internal_resource_summary": continue role = "assistant" if message.get("role") == "model" else "user" content = message.get('content', '') or (message.get("parts")[0].get("text", "") if message.get("parts") else "") final_ui_history.append({"role": role, "content": content}) # Logic for Suggested Replies and Tab Switching looks_good_btn_update = gr.update(visible=False) if final_ui_history and "what are your thoughts?" in final_ui_history[-1]['content'].lower(): looks_good_btn_update = gr.update(visible=True) explainer_accordion_update, explainer_box_update, app_tabs_update, documentation_update = (gr.update(),)*4 if final_state.get(STATE_TRANSITION_EXPLAINER_FLAG): explainer_accordion_update = gr.update(visible=True, open=True) explainer_prompt_value = final_state.get(STATE_EXPLAINER_PROMPT, "") explainer_box_update = gr.update(value=explainer_prompt_value) app_tabs_update = gr.update(selected="doc_tab") full_documentation_text = f""" # Generated Tutor Persona *This document contains the complete system prompt, including the finalized syllabus, that defines the AI tutor's behavior, personality, and knowledge base. You can copy this for reference or use in other applications.* *** {explainer_prompt_value} """ documentation_update = gr.update(value=full_documentation_text) print("YIELD 2: Displaying final AI response.") yield ( gr.update(value=final_ui_history), gr.update(value=""), final_state, gr.update(visible=False, interactive=False), gr.update(interactive=True), explainer_accordion_update, explainer_box_update, gr.update(value=file_display_md, visible=file_display_visible), all_file_names, looks_good_btn_update, app_tabs_update, documentation_update, ) # --- NEW AESTHETIC CSS --- # --- NEW, LAYOUT-FOCUSED CSS --- # --- FINAL, CORRECTED CSS --- custom_css = """ /* --- Overall Page & Theme --- */ .gradio-container { background-color: #F9FAFB; } .dark .gradio-container { background-color: #111827; } /* --- THE KEY FIX: Make the chatbot tall and scrollable --- */ #chatbot { /* Use vh (viewport height) to make the chatbot take up most of the screen */ min-height: 60vh !important; background-color: white !important; /* Distinct white background */ border: 1px solid #E5E7EB !important; border-radius: 12px !important; } .dark #chatbot { background-color: #1F2937 !important; /* Distinct dark background for chatbot */ border-color: #374151 !important; } /* --- Input Bar Styling --- */ /* Add a top margin to the input row to create visual space from the chatbot */ .chat-input-row { margin-top: 1rem !important; } /* Style the textbox itself for a clean look */ #user_input_textbox textarea { background-color: #FFFFFF !important; border: 1px solid #D1D5DB !important; border-radius: 8px !important; } .dark #user_input_textbox textarea { background-color: #374151 !important; color: #F3F4F6 !important; border-color: #4B5563 !important; } /* --- General styling from before (tabs, small buttons) --- */ /* (This part remains the same as the version you liked) */ #app-header { text-align: center; color: #4A5568; margin-bottom: 0.5rem !important; } .dark #app-header { color: #D1D5DB; } .sm-button { min-width: 0 !important; padding: 0.2rem 0.6rem !important; /* ...etc... */ } #app-tabs .tab-nav button.selected { border-bottom-color: #4F46E5 !important; color: #4F46E5 !important; } .dark #app-tabs .tab-nav button.selected { border-bottom-color: #A5B4FC !important; color: #A5B4FC !important; } """ # --- Gradio UI Definition --- with gr.Blocks(theme=gr.themes.Soft(), css=custom_css, title="AI Syllabus Architect") as demo: # --- State Management --- session_state = gr.State(value=initialize_session_state) rate_limiter_state = gr.State(value=None) uploaded_file_names_state = gr.State([]) header_visibility_state = gr.State(value=True) # --- TOP LEVEL HEADER (Collapsible) --- with gr.Column(visible=True) as header_view: gr.Markdown( """ # AI Tutor & Syllabus Planner * Upload a resource or ask what you want to learn to generate a syllabus. Finalize the plan,