Spaces:
Running
Running
| """Gradio interface for the smolagents CodeAgent.""" | |
| import os | |
| import sys | |
| import logging | |
| from code_agent import run_agent | |
| # (Gradio update/analytics env flags removed per user request) | |
| 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 | |
| # We'll provide a readonly prompt field populated from the scoring API | |
| # and buttons to fetch a random task and run the agent on it. | |
| def fetch_random_task(): | |
| try: | |
| from evaluation_client import ScoringAPIClient | |
| client = ScoringAPIClient() | |
| q = client.get_random_question() | |
| if not q: | |
| return "(no question returned)" | |
| # extract prompt safely | |
| for key in ("question", "prompt", "input", "text", "task"): | |
| if key in q and isinstance(q[key], str): | |
| return q[key] | |
| return str(q) | |
| except Exception as e: | |
| logger.error("Failed to fetch random question: %s", e) | |
| return f"(fetch error) {type(e).__name__}: {str(e)[:200]}" | |
| def run_on_current(prompt_text: str): | |
| if not prompt_text or not prompt_text.strip(): | |
| return "(no prompt to run on)" | |
| try: | |
| return respond(prompt_text) | |
| except Exception as e: | |
| logger.error("Agent run failed: %s", e) | |
| return f"Agent error: {type(e).__name__}: {str(e)[:200]}" | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# Agents Course — Final Agent Demo") | |
| with gr.Row(): | |
| prompt_box = gr.Textbox(label="Fetched Prompt (read-only)", lines=6) | |
| with gr.Row(): | |
| fetch_btn = gr.Button("Fetch Random Task") | |
| run_btn = gr.Button("Run Agent on Fetched Task") | |
| output_box = gr.Textbox(label="Agent Response", lines=12) | |
| fetch_btn.click(fn=fetch_random_task, inputs=[], outputs=[prompt_box]) | |
| run_btn.click(fn=run_on_current, inputs=[prompt_box], outputs=[output_box]) | |
| _demo = demo | |
| return _demo | |
| if __name__ == "__main__": | |
| # Launch unconditionally when executed as a script. | |
| 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: %s", e) | |