"""Gradio-based web UI for interacting with the NexaSci scientific agent.""" from __future__ import annotations import json from pathlib import Path from typing import Dict import gradio as gr from agent.controller import AgentController MODES: Dict[str, str] = { "General Q&A": "You are assisting with a general scientific research question.", "Design Experiment": "Design a reproducible experimental protocol.", "Run Simulation": "Decide which simulations or calculations to execute in the sandbox.", "Summarise Paper": "Summarise and critique relevant literature for the query.", } controller = AgentController() def _format_prompt(user_prompt: str, mode: str) -> str: mode_instruction = MODES.get(mode, MODES["General Q&A"]) return f"{mode_instruction}\n\n{user_prompt.strip()}" def run_agent(user_prompt: str, mode: str) -> tuple[str, str]: """Gradio callback that runs the agent and returns the response and tool trace.""" if not user_prompt.strip(): return "Please enter a prompt to begin.", "[]" formatted_prompt = _format_prompt(user_prompt, mode) result = controller.run(formatted_prompt) final_text = result.pretty() tool_trace = json.dumps([tool_result.output for tool_result in result.tool_results], indent=2) return final_text, tool_trace def build_interface() -> gr.Blocks: """Construct the Gradio Blocks interface.""" with gr.Blocks(title="NexaSci Agent") as demo: gr.Markdown( """ # NexaSci Scientific Agent Ask a scientific question, request an experiment design, or run lightweight simulations. The agent can call tools such as the Python sandbox and paper search APIs when needed. """ ) with gr.Row(): prompt_box = gr.Textbox( label="Prompt", placeholder="e.g. Propose a methodology to measure superconducting critical temperature in a lab setting.", lines=6, ) mode_dropdown = gr.Dropdown( label="Mode", choices=list(MODES.keys()), value="General Q&A", ) run_button = gr.Button("Run Agent", variant="primary") with gr.Tab("Final Response"): final_output = gr.Textbox(label="Agent Output", lines=12) with gr.Tab("Tool Trace"): tool_trace = gr.Textbox(label="Tool Invocations", lines=12) run_button.click( run_agent, inputs=[prompt_box, mode_dropdown], outputs=[final_output, tool_trace], ) return demo def main() -> None: """Launch the Gradio interface.""" build_interface().launch() if __name__ == "__main__": # pragma: no cover - manual launch helper main()