""" Gradio interface for the smolagents CodeAgent. By default this script will NOT launch a local Gradio server. To allow local runs (for testing) set the environment variable `RUN_LOCAL=1` or pass `--run-local` on the command line. This prevents accidental local launches when you intended to deploy to Hugging Face Spaces. Run locally (explicit): RUN_LOCAL=1 python app.py or python app.py --run-local When running in a Space you can set `RUN_LOCAL=1` in Space secrets if desired, but Spaces typically run the app directly; set `RUN_LOCAL` only when you want explicit local behavior. """ import os import sys import logging from code_agent import run_agent # Prevent Gradio from contacting its update/analytics endpoints on import. # These environment variables should be set before importing `gradio`. os.environ.setdefault("GRADIO_CHECK_FOR_UPDATES", "false") os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "false") logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def respond(prompt: str) -> str: if not prompt or not prompt.strip(): return "Please provide a prompt." try: return run_agent(prompt) except Exception as e: logger.error("Agent failed: %s", e) return f"Agent error: {type(e).__name__}: {str(e)[:200]}" _demo = None def _get_demo(): """Lazily import gradio and construct the demo to avoid network calls on import.""" global _demo if _demo is not None: return _demo try: import gradio as gr except Exception as e: logger.error("Failed to import gradio: %s", e) raise _demo = gr.Interface( fn=respond, inputs=gr.Textbox(lines=5, label="User Prompt"), outputs=gr.Textbox(lines=10, label="Agent Response"), title="Agents Course — Final Agent Demo", description="smolagents CodeAgent demo for the course final project.", ) return _demo def _should_launch_in_space() -> bool: """Decide whether to launch inside a Hugging Face Space or similar environment. We intentionally DO NOT support local launches. To run in a Space, set one of: - environment variable `RUN_IN_SPACE=1`, or - environment variable `HF_SPACE` (any value), or - environment variable `SPACE_ID` (any value) """ if os.environ.get("RUN_IN_SPACE", "0") == "1": return True if os.environ.get("HF_SPACE"): return True if os.environ.get("SPACE_ID"): return True return False if __name__ == "__main__": # Never launch locally. Only allow launch when explicitly running inside # a Space or when RUN_IN_SPACE is set. This prevents accidental local runs. if _should_launch_in_space(): logger.info("Launching Gradio in Space mode") try: _get_demo().launch(server_name="0.0.0.0", server_port=7860, share=False) except Exception as e: logger.error("Failed to launch Gradio demo in Space mode: %s", e) else: logger.error( "Local launch disabled. To run the app in a Space set RUN_IN_SPACE=1 or set HF_SPACE/SPACE_ID in the environment." )