add load and save config tab

This commit is contained in:
vvincent1234
2025-04-28 09:37:49 +08:00
parent 6ac9e268d3
commit 0d259efbeb
6 changed files with 154 additions and 15 deletions

View File

@@ -27,14 +27,14 @@ def update_mcp_server(mcp_file: str):
"""
Update the MCP server.
"""
if not mcp_file or not os.path.exists(mcp_file) or mcp_file.endswith('.json'):
if not mcp_file or not os.path.exists(mcp_file) or not mcp_file.endswith('.json'):
logger.warning(f"{mcp_file} is not a valid MCP file.")
return gr.update()
return None, gr.update(visible=False)
with open(mcp_file, 'r') as f:
mcp_server = json.load(f)
return gr.update(value=json.dumps(mcp_server, indent=2), visible=True)
return json.dumps(mcp_server, indent=2), gr.update(visible=True)
def create_agent_settings_tab(webui_manager: WebuiManager) -> dict[str, Component]:
@@ -50,7 +50,7 @@ def create_agent_settings_tab(webui_manager: WebuiManager) -> dict[str, Componen
extend_system_prompt = gr.Textbox(label="Extend system prompt", lines=4, interactive=True)
with gr.Group():
mcp_json_file = gr.File(label="MCP server file", interactive=True, file_types=["json"])
mcp_json_file = gr.File(label="MCP server file", interactive=True, file_types=[".json"])
mcp_server_config = gr.Textbox(label="MCP server", lines=6, interactive=True, visible=False)
with gr.Group():
@@ -202,7 +202,7 @@ def create_agent_settings_tab(webui_manager: WebuiManager) -> dict[str, Componen
allow_custom_value=True,
choices=["auto", "json_schema", "function_calling", "None"],
info="Tool Calls Function Name",
visible=False
visible=True
)
tab_components.update(dict(
override_system_prompt=override_system_prompt,
@@ -252,7 +252,7 @@ def create_agent_settings_tab(webui_manager: WebuiManager) -> dict[str, Componen
mcp_json_file.change(
update_mcp_server,
inputs=mcp_json_file,
outputs=mcp_server_config
outputs=[mcp_server_config, mcp_server_config]
)
return tab_components

View File

@@ -22,7 +22,7 @@ def create_browser_use_agent_tab(webui_manager: WebuiManager) -> dict[str, Compo
with gr.Row():
stop_button = gr.Button("⏹️ Stop", interactive=False, variant="stop", scale=2)
clear_button = gr.Button("🧹 Clear", interactive=False, variant="stop", scale=2)
clear_button = gr.Button("🧹 Clear", interactive=True, variant="stop", scale=2)
run_button = gr.Button("▶️ Summit", variant="primary", scale=3)
browser_view = gr.HTML(

View File

@@ -0,0 +1,41 @@
import gradio as gr
from gradio.components import Component
from src.webui.webui_manager import WebuiManager
from src.utils import config
def create_deep_research_agent_tab(webui_manager: WebuiManager) -> dict[str, Component]:
"""
Creates a deep research agent tab
"""
input_components = set(webui_manager.get_components())
tab_components = {}
research_task = gr.Textbox(label="Research Task", lines=5,
value="Give me a detailed plan for traveling to Switzerland on June 1st.",
interactive=True)
with gr.Row():
max_iteration = gr.Number(label="Max Search Iteration", value=3,
precision=0,
interactive=True) # precision=0 确保是整数
max_query = gr.Number(label="Max Query per Iteration", value=1,
precision=0,
interactive=True) # precision=0 确保是整数
with gr.Row():
stop_button = gr.Button("⏹️ Stop", variant="stop", scale=2)
start_button = gr.Button("▶️ Run", variant="primary", scale=3)
markdown_display = gr.Markdown(label="Research Report")
markdown_download = gr.File(label="Download Research Report", interactive=False)
tab_components.update(
dict(
research_task=research_task,
max_iteration=max_iteration,
max_query=max_query,
start_button=start_button,
stop_button=stop_button,
markdown_display=markdown_display,
markdown_download=markdown_download,
)
)
return tab_components

View File

@@ -0,0 +1,49 @@
import gradio as gr
from gradio.components import Component
from src.webui.webui_manager import WebuiManager
from src.utils import config
def create_load_save_config_tab(webui_manager: WebuiManager) -> dict[str, Component]:
"""
Creates a load and save config tab.
"""
input_components = set(webui_manager.get_components())
tab_components = {}
config_file = gr.File(
label="Load UI Settings from Config File",
file_types=[".json"],
interactive=True
)
with gr.Row():
load_config_button = gr.Button("Load Config", variant="primary")
save_config_button = gr.Button("Save UI Settings", variant="primary")
config_status = gr.Textbox(
label="Status",
lines=2,
interactive=False
)
tab_components.update(dict(
load_config_button=load_config_button,
save_config_button=save_config_button,
config_status=config_status,
config_file=config_file,
))
save_config_button.click(
fn=webui_manager.save_current_config,
inputs=[],
outputs=[config_status]
)
load_config_button.click(
fn=webui_manager.load_config,
inputs=[config_file],
outputs=[config_status]
)
return tab_components

View File

@@ -4,6 +4,8 @@ from src.webui.webui_manager import WebuiManager
from src.webui.components.agent_settings_tab import create_agent_settings_tab
from src.webui.components.browser_settings_tab import create_browser_settings_tab
from src.webui.components.browser_use_agent_tab import create_browser_use_agent_tab
from src.webui.components.deep_research_agent_tab import create_deep_research_agent_tab
from src.webui.components.load_save_config_tab import create_load_save_config_tab
theme_map = {
"Default": gr.themes.Default(),
@@ -37,10 +39,22 @@ def create_ui(theme_name="Ocean"):
}
"""
# dark mode in default
js_func = """
function refresh() {
const url = new URL(window.location);
if (url.searchParams.get('__theme') !== 'dark') {
url.searchParams.set('__theme', 'dark');
window.location.href = url.href;
}
}
"""
ui_manager = WebuiManager()
with gr.Blocks(
title="Browser Use WebUI", theme=theme_map[theme_name], css=css
title="Browser Use WebUI", theme=theme_map[theme_name], css=css, js=js_func,
) as demo:
with gr.Row():
gr.Markdown(
@@ -62,9 +76,9 @@ def create_ui(theme_name="Ocean"):
ui_manager.add_components("browser_use_agent", create_browser_use_agent_tab(ui_manager))
with gr.TabItem("🧐 Deep Research"):
pass
ui_manager.add_components("deep_research_agent", create_deep_research_agent_tab(ui_manager))
with gr.TabItem("📁 UI Configuration"):
pass
with gr.TabItem("📁 Load & Save Config"):
ui_manager.add_components("load_save_config", create_load_save_config_tab(ui_manager))
return demo

View File

@@ -1,19 +1,24 @@
import json
from collections.abc import Generator
from typing import TYPE_CHECKING
import os
import gradio as gr
from datetime import datetime
if TYPE_CHECKING:
from gradio.components import Component
from gradio.components import Component
from browser_use.browser.browser import Browser
from browser_use.browser.context import BrowserContext
from browser_use.agent.service import Agent
class WebuiManager:
def __init__(self):
def __init__(self, settings_save_dir: str = "./tmp/webui_settings"):
self.id_to_component: dict[str, Component] = {}
self.component_to_id: dict[Component, str] = {}
self.settings_save_dir = settings_save_dir
os.makedirs(self.settings_save_dir, exist_ok=True)
self.browser: Browser = None
self.browser_context: BrowserContext = None
self.bu_agent: Agent = None
@@ -44,3 +49,33 @@ class WebuiManager:
Get id by component
"""
return self.component_to_id[comp]
def save_current_config(self):
"""
Save current config
"""
cur_settings = {}
for comp_id, comp in self.id_to_component.items():
if not isinstance(comp, gr.Button) and not isinstance(comp, gr.File) and str(
getattr(comp, "interactive", True)).lower() != "false":
cur_settings[comp_id] = getattr(comp, "value", None)
config_name = datetime.now().strftime("%Y%m%d-%H%M%S")
with open(os.path.join(self.settings_save_dir, f"{config_name}.json"), "w") as fw:
json.dump(cur_settings, fw, indent=4)
return os.path.join(self.settings_save_dir, f"{config_name}.json")
def load_config(self, config_path: str):
"""
Load config
"""
with open(config_path, "r") as fr:
ui_settings = json.load(fr)
update_components = {}
for comp_id, comp_val in ui_settings.items():
if comp_id in self.id_to_component:
update_components[self.id_to_component[comp_id]].value = comp_val
return f"Successfully loaded config from {config_path}"