""" Browser-Use REST API Server for Hugging Face Spaces """ import os import asyncio import base64 import io import shutil import hmac import hashlib import httpx import json from cryptography.fernet import Fernet from contextlib import asynccontextmanager from datetime import datetime, timedelta from pathlib import Path # 设置超时环境变量 os.environ["TIMEOUT_BrowserStartEvent"] = "120" os.environ["TIMEOUT_BrowserLaunchEvent"] = "120" from fastapi import FastAPI, HTTPException, BackgroundTasks, Depends, Header, Query, WebSocket, WebSocketDisconnect from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, StreamingResponse, Response, HTMLResponse from pydantic import BaseModel, HttpUrl from typing import Optional, List, Dict, Any import uuid # ==================== JSON 文件配置存储 ==================== # HF 配置持久化:使用 Dataset 仓库存储,避免触发 Space 重建 HF_SPACE_ID = os.environ.get("SPACE_ID", "") # HF Spaces 自动注入 # Dataset 仓库名:与 Space 同账号,名为 -configs _HF_OWNER = HF_SPACE_ID.split("/")[0] if HF_SPACE_ID else "" _HF_SPACE_NAME = HF_SPACE_ID.split("/")[1] if "/" in (HF_SPACE_ID or "") else "" HF_CONFIG_REPO = f"{_HF_OWNER}/{_HF_SPACE_NAME}-configs" if _HF_OWNER else "" # 本地配置文件路径 CONFIGS_FILE = Path("/tmp/configs.json") # API Key 加密密钥 def _get_fernet_key(): """获取或生成 Fernet 密钥""" env_key = os.environ.get("ENCRYPTION_KEY", "") if env_key and len(env_key) == 44: return env_key.encode() password = os.environ.get("ACCESS_PASSWORD", "") or "browserusedefaultkey" key_bytes = hashlib.sha256(password.encode()).digest() return base64.urlsafe_b64encode(key_bytes) ENCRYPTION_KEY = _get_fernet_key() fernet = Fernet(ENCRYPTION_KEY) def encrypt_api_key(api_key: str) -> str: if not api_key: return "" return fernet.encrypt(api_key.encode()).decode() def decrypt_api_key(encrypted_key: str) -> str: if not encrypted_key: return "" try: return fernet.decrypt(encrypted_key.encode()).decode() except Exception: return encrypted_key def _load_configs() -> list: """从本地文件加载配置;首次启动时从 HF Dataset 仓库拉取""" if not CONFIGS_FILE.exists() and HF_CONFIG_REPO: try: from huggingface_hub import hf_hub_download path = hf_hub_download( repo_id=HF_CONFIG_REPO, repo_type="dataset", filename="configs.json", ) import shutil as _shutil _shutil.copy(path, str(CONFIGS_FILE)) except Exception: pass if not CONFIGS_FILE.exists(): return [] try: return json.loads(CONFIGS_FILE.read_text(encoding="utf-8")) except (json.JSONDecodeError, OSError): return [] def _save_configs(configs: list): """保存配置到本地文件,并异步推送到 HF Dataset 仓库持久化""" content = json.dumps(configs, ensure_ascii=False, indent=2) CONFIGS_FILE.write_text(content, encoding="utf-8") if HF_CONFIG_REPO: import threading def _push(): try: from huggingface_hub import HfApi api = HfApi() # 确保 Dataset 仓库存在(首次会自动创建,设为私有) api.create_repo(repo_id=HF_CONFIG_REPO, repo_type="dataset", private=True, exist_ok=True) api.upload_file( path_or_fileobj=content.encode("utf-8"), path_in_repo="configs.json", repo_id=HF_CONFIG_REPO, repo_type="dataset", commit_message="update configs", ) except Exception: pass threading.Thread(target=_push, daemon=True).start() from browser_use import Agent, Browser, BrowserProfile, ChatOpenAI from browser_use.llm import ChatDeepSeek from browser_use import ChatAnthropic, ChatGoogle, ChatGroq, ChatOllama # 截图存储目录 SCREENSHOTS_DIR = Path("/tmp/browser_screenshots") SCREENSHOTS_DIR.mkdir(parents=True, exist_ok=True) # 访问密码(从环境变量读取) ACCESS_PASSWORD = os.environ.get("ACCESS_PASSWORD", "") # 配置管理密码(二次验证,从环境变量读取) CONFIG_PASSWORD = os.environ.get("CONFIG_PASSWORD", "") # 并发控制 MAX_CONCURRENT_TASKS = int(os.environ.get("MAX_CONCURRENT_TASKS", "3")) task_semaphore = asyncio.Semaphore(MAX_CONCURRENT_TASKS) # 任务保留时间(小时) TASK_RETENTION_HOURS = int(os.environ.get("TASK_RETENTION_HOURS", "24")) # 超时配置 TASK_TIMEOUT = int(os.environ.get("TASK_TIMEOUT", "300")) # 单个任务最大执行时间(秒),默认 5 分钟 STEP_TIMEOUT = int(os.environ.get("STEP_TIMEOUT", "30")) # 单步操作超时(秒),默认 30 秒 # 任务状态存储 tasks: Dict[str, Dict[str, Any]] = {} # 运行中的任务(用于取消) running_tasks: Dict[str, asyncio.Task] = {} # 运行中的浏览器实例(用于取消时关闭和实时截图) running_browsers: Dict[str, Browser] = {} # 运行中的 Agent 实例(保留以备扩展) running_agents: Dict[str, Agent] = {} # 任务截图列表 task_screenshots: Dict[str, List[Dict[str, Any]]] = {} # 任务实时日志 task_logs: Dict[str, List[Dict[str, Any]]] = {} # 清理任务 cleanup_task: Optional[asyncio.Task] = None class LLMConfig(BaseModel): """LLM 配置""" provider: str # deepseek, openai, ollama, custom model: str # 模型名称 api_key: Optional[str] = None # API 密钥(Ollama 可选) base_url: Optional[str] = None # 自定义 API 地址(可选) temperature: float = 0.0 class WebhookConfig(BaseModel): """Webhook 配置""" url: HttpUrl # Webhook URL secret: Optional[str] = None # 用于 HMAC 签名的密钥(可选) events: Optional[List[str]] = None # 订阅的事件类型,None 表示全部 class TaskRequest(BaseModel): task: str headless: bool = True save_screenshots: bool = True compress_screenshots: bool = True # 是否压缩截图 use_vision: bool = False # 是否启用视觉功能 timeout: Optional[int] = None # 自定义超时时间(秒),默认使用环境变量 TASK_TIMEOUT # LLM 配置 - 必填 llm_config: LLMConfig # Webhook 配置 - 可选 webhook: Optional[WebhookConfig] = None class TaskResponse(BaseModel): task_id: str status: str message: str class StepDetail(BaseModel): step: int action: Optional[str] = None result: Optional[str] = None timestamp: Optional[str] = None screenshot_id: Optional[str] = None class TaskResult(BaseModel): task_id: str status: str task: str result: Optional[str] = None error: Optional[str] = None steps: Optional[List[StepDetail]] = None screenshots: Optional[List[str]] = None llm_config: Optional[LLMConfig] = None created_at: Optional[str] = None started_at: Optional[str] = None completed_at: Optional[str] = None class TaskListResponse(BaseModel): tasks: List[TaskResult] total: int class CancelResponse(BaseModel): task_id: str status: str message: str class ScreenshotInfo(BaseModel): screenshot_id: str step: int timestamp: str url: str class ScreenshotListResponse(BaseModel): task_id: str screenshots: List[ScreenshotInfo] total: int # ==================== LLM 配置管理模型 ==================== class LLMConfigCreate(BaseModel): """创建 LLM 配置请求""" name: str # 配置名称 provider: str # 提供商 model: str # 模型名称 api_key: Optional[str] = None # API Key base_url: Optional[str] = None # 自定义 Base URL is_default: bool = False # 是否为默认配置 class LLMConfigResponse(BaseModel): """LLM 配置响应""" id: str name: str provider: str model: str api_key_masked: str # 掩码后的 API Key base_url: Optional[str] = None is_default: bool created_at: str updated_at: str class LLMConfigWithKey(BaseModel): """包含完整 API Key 的配置(用于加载)""" id: str name: str provider: str model: str api_key: str # 完整的 API Key base_url: Optional[str] = None is_default: bool class LLMConfigListResponse(BaseModel): """配置列表响应""" configs: List[LLMConfigResponse] total: int def mask_api_key(api_key: str) -> str: """掩码 API Key,只显示前4位和后4位""" if not api_key or len(api_key) < 12: return "****" return f"{api_key[:4]}{'*' * (len(api_key) - 8)}{api_key[-4:]}" async def periodic_cleanup(): """定期清理过期任务""" global cleanup_task while True: try: await asyncio.sleep(3600) # 每小时执行一次 cutoff_time = datetime.now() - timedelta(hours=TASK_RETENTION_HOURS) tasks_to_delete = [] for task_id, task_info in tasks.items(): # 跳过运行中的任务 if task_info["status"] in ["pending", "running"]: continue completed_at = task_info.get("completed_at") if completed_at: try: completed_time = datetime.fromisoformat(completed_at) if completed_time < cutoff_time: tasks_to_delete.append(task_id) except: pass # 删除过期任务 for task_id in tasks_to_delete: # 删除截图文件 task_dir = SCREENSHOTS_DIR / task_id if task_dir.exists(): shutil.rmtree(task_dir) # 删除内存数据 tasks.pop(task_id, None) task_screenshots.pop(task_id, None) task_logs.pop(task_id, None) if tasks_to_delete: print(f"🧹 定期清理: 删除了 {len(tasks_to_delete)} 个过期任务") except asyncio.CancelledError: break except Exception as e: print(f"❌ 定期清理失败: {e}") @asynccontextmanager async def lifespan(app: FastAPI): global cleanup_task print("🚀 Browser-Use API Server starting...") print(f"⚙️ 最大并发任务数: {MAX_CONCURRENT_TASKS}") print(f"⏰ 任务保留时间: {TASK_RETENTION_HOURS} 小时") print(f"⏱️ 任务超时: {TASK_TIMEOUT} 秒") # 清理旧截图 if SCREENSHOTS_DIR.exists(): shutil.rmtree(SCREENSHOTS_DIR) SCREENSHOTS_DIR.mkdir(parents=True, exist_ok=True) # 启动定期清理任务 cleanup_task = asyncio.create_task(periodic_cleanup()) yield print("👋 Browser-Use API Server shutting down...") # 停止清理任务 if cleanup_task: cleanup_task.cancel() try: await cleanup_task except asyncio.CancelledError: pass # 清理所有运行中的任务 for task_id, task in running_tasks.items(): if not task.done(): task.cancel() for browser in running_browsers.values(): try: await browser.stop() except: pass app = FastAPI( title="Browser-Use API", description="AI 浏览器自动化服务", version="1.2.0", lifespan=lifespan, ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 历史任务保留数量 MAX_HISTORY_TASKS = 5 def verify_password( x_access_password: Optional[str] = Header(None, alias="X-Access-Password"), password: Optional[str] = Query(None) ): """验证访问密码""" if not ACCESS_PASSWORD: # 未设置密码,允许访问 return True provided_password = x_access_password or password if provided_password != ACCESS_PASSWORD: raise HTTPException(status_code=401, detail="密码错误或未提供") return True def verify_config_password( x_config_password: Optional[str] = Header(None, alias="X-Config-Password"), config_password: Optional[str] = Query(None, alias="config_password") ): """验证配置管理密码(二次验证)""" if not CONFIG_PASSWORD: # 未设置配置密码,允许访问 return True provided_password = x_config_password or config_password if provided_password != CONFIG_PASSWORD: raise HTTPException(status_code=401, detail="配置密码错误") return True async def save_screenshot(task_id: str, agent: Agent, step: int, compress: bool = False) -> Optional[str]: """保存浏览器截图""" try: # 生成截图ID screenshot_id = f"{task_id}_{step}_{datetime.now().strftime('%H%M%S%f')}" # 创建任务截图目录 task_dir = SCREENSHOTS_DIR / task_id task_dir.mkdir(parents=True, exist_ok=True) # 保存截图路径 screenshot_path = task_dir / f"{screenshot_id}.png" # 使用 agent 的 browser session 截图 if hasattr(agent, 'browser') and agent.browser: browser_session = agent.browser # 新版本 API: 使用 take_screenshot 方法 if hasattr(browser_session, 'take_screenshot'): screenshot_data = await browser_session.take_screenshot(path=str(screenshot_path)) else: # 尝试旧版本 API return None else: return None # 压缩截图 if compress and screenshot_path.exists(): try: from PIL import Image img = Image.open(screenshot_path) # 转换为 RGB(如果是 RGBA) if img.mode == 'RGBA': img = img.convert('RGB') # 压缩保存为 JPEG,质量 70 jpg_path = task_dir / f"{screenshot_id}.jpg" img.save(jpg_path, 'JPEG', quality=70, optimize=True) # 删除原始 PNG screenshot_path.unlink() screenshot_path = jpg_path except Exception as e: print(f"截图压缩失败,使用原始 PNG: {e}") # 记录截图信息 if task_id not in task_screenshots: task_screenshots[task_id] = [] screenshot_info = { "screenshot_id": screenshot_id, "step": step, "timestamp": datetime.now().isoformat(), "path": str(screenshot_path), } task_screenshots[task_id].append(screenshot_info) return screenshot_id except Exception as e: print(f"截图保存失败: {e}") return None async def get_browser_from_pool(headless: bool) -> Browser: """创建新的浏览器实例 注意:browser-use 库的 Browser 对象在复用时存在内部状态问题, 会导致 BrowserStateRequestEvent 错误。因此禁用浏览器池复用, 每次任务都创建新的浏览器实例。 """ clok_chrome_executable_path = os.environ.get("CKB_BINARY") profile = BrowserProfile( headless=headless, enable_default_extensions=False, executable_path=clok_chrome_executable_path, chromium_sandbox=False, ) browser = Browser(browser_profile=profile) print(f"🆕 创建新浏览器实例") return browser async def release_browser_to_pool(browser: Browser): """停止并释放浏览器实例 注意:browser-use 库的 Browser 对象在复用时存在内部状态问题, 因此每次任务完成后直接关闭浏览器,而不是放回池中复用。 """ try: await browser.stop() print(f"✅ 浏览器已停止并释放") except Exception as e: print(f"⚠️ 停止浏览器失败: {e}") def cleanup_old_tasks(): """清理旧的历史任务,只保留最近的 MAX_HISTORY_TASKS 条""" # 获取所有已完成的任务(completed, failed, cancelled) finished_tasks = [ (task_id, task_info) for task_id, task_info in tasks.items() if task_info["status"] in ["completed", "failed", "cancelled"] ] # 按完成时间排序(最新的在前) finished_tasks.sort( key=lambda x: x[1].get("completed_at") or "", reverse=True ) # 删除超出限制的任务 tasks_to_delete = finished_tasks[MAX_HISTORY_TASKS:] for task_id, _ in tasks_to_delete: # 删除截图文件 task_dir = SCREENSHOTS_DIR / task_id if task_dir.exists(): shutil.rmtree(task_dir) task_screenshots.pop(task_id, None) task_logs.pop(task_id, None) # 删除任务记录 del tasks[task_id] if tasks_to_delete: print(f"已清理 {len(tasks_to_delete)} 条旧任务") def create_llm(config: LLMConfig): """根据配置创建 LLM 实例""" provider = config.provider.lower() api_key = config.api_key # 自动补全 base_url 的 /v1 后缀(Ollama 除外) base_url = config.base_url.rstrip("/") if config.base_url else None if base_url and provider != "ollama" and not base_url.endswith("/v1"): base_url = base_url + "/v1" # Ollama 不需要 API Key if provider == "ollama" and not api_key: api_key = "ollama" # 硅基流动 SiliconFlow (OpenAI 兼容) - 必须在 DeepSeek 之前检查 if provider == "siliconflow": return ChatOpenAI( model=config.model, api_key=api_key, base_url=base_url or "https://api.siliconflow.cn/v1", temperature=config.temperature, ) # DeepSeek if provider == "deepseek" or "deepseek" in config.model.lower(): return ChatDeepSeek( model=config.model, api_key=api_key, base_url=base_url or "https://api.deepseek.com/v1", ) # Anthropic (Claude) if provider == "anthropic": return ChatAnthropic( model=config.model, api_key=api_key, ) # Google Gemini if provider == "google" or provider == "gemini": return ChatGoogle( model=config.model, api_key=api_key, ) # Groq (快速推理) if provider == "groq": return ChatGroq( model=config.model, api_key=api_key, ) # Ollama (本地/远程) if provider == "ollama": host = config.base_url or "http://localhost:11434" # 移除 /v1 后缀(ChatOllama 不需要) if host.endswith("/v1"): host = host[:-3] return ChatOllama( model=config.model, host=host, ) # OpenAI 及兼容 API (custom) llm_kwargs = { "model": config.model, "api_key": api_key, "temperature": config.temperature, } if base_url: llm_kwargs["base_url"] = base_url elif provider == "openai": llm_kwargs["base_url"] = "https://api.openai.com/v1" return ChatOpenAI(**llm_kwargs) def add_task_log(task_id: str, log_type: str, content: str, step: int = 0): """添加任务日志""" if task_id not in task_logs: task_logs[task_id] = [] log_entry = { "type": log_type, "content": content, "step": step, "timestamp": datetime.now().isoformat() } task_logs[task_id].append(log_entry) async def send_webhook(webhook_config: WebhookConfig, event_type: str, data: Dict[str, Any], max_retries: int = 3): """发送 Webhook 通知""" if not webhook_config: print(f"⚠️ Webhook 配置为空,跳过发送 {event_type}") return # 检查是否订阅了该事件 if webhook_config.events and event_type not in webhook_config.events: print(f"⏭️ 事件 {event_type} 未订阅,跳过发送") return print(f"📤 准备发送 Webhook: {event_type} -> {webhook_config.url}") payload = { "event": event_type, "timestamp": datetime.now().isoformat(), "data": data } headers = {"Content-Type": "application/json"} # 添加 HMAC 签名 if webhook_config.secret: import json payload_str = json.dumps(payload, separators=(',', ':')) signature = hmac.new( webhook_config.secret.encode(), payload_str.encode(), hashlib.sha256 ).hexdigest() headers["X-Webhook-Signature"] = f"sha256={signature}" # 异步发送,带重试 for attempt in range(max_retries): try: async with httpx.AsyncClient(timeout=10.0) as client: response = await client.post( str(webhook_config.url), json=payload, headers=headers ) print(f"✅ Webhook 发送成功: {event_type} (状态码: {response.status_code})") if response.status_code < 500: return # 成功或客户端错误不重试 except Exception as e: if attempt == max_retries - 1: print(f"❌ Webhook 发送失败 ({event_type}): {e}") else: print(f"⚠️ Webhook 发送失败 ({event_type}),重试 {attempt + 1}/{max_retries}: {e}") await asyncio.sleep(2 ** attempt) # 指数退避 async def execute_task(task_id: str, task_description: str, headless: bool, save_screenshots: bool, llm_config: LLMConfig, webhook_config: Optional[WebhookConfig] = None, use_vision: bool = True, compress_screenshots: bool = False, timeout: Optional[int] = None): """后台执行浏览器自动化任务""" task_timeout = timeout or TASK_TIMEOUT async with task_semaphore: tasks[task_id]["status"] = "running" tasks[task_id]["started_at"] = datetime.now().isoformat() task_screenshots[task_id] = [] task_logs[task_id] = [] asyncio.create_task(send_webhook(webhook_config, "task.started", { "task_id": task_id, "task": task_description, "started_at": tasks[task_id]["started_at"] })) browser = None try: async def run_task(): nonlocal browser llm = create_llm(llm_config) browser = await get_browser_from_pool(headless) running_browsers[task_id] = browser step_count = [0] async def on_step_end(agent: Agent): step_count[0] += 1 current_step = step_count[0] try: thoughts = agent.history.model_thoughts() if thoughts and len(thoughts) > 0: latest_thought = thoughts[-1] if hasattr(latest_thought, 'evaluation_previous_goal') and latest_thought.evaluation_previous_goal: add_task_log(task_id, "eval", latest_thought.evaluation_previous_goal, current_step) if hasattr(latest_thought, 'memory') and latest_thought.memory: add_task_log(task_id, "memory", latest_thought.memory, current_step) if hasattr(latest_thought, 'next_goal') and latest_thought.next_goal: add_task_log(task_id, "next_goal", latest_thought.next_goal, current_step) actions = agent.history.model_actions() if actions and len(actions) > 0: latest_actions = actions[-1] if isinstance(actions[-1], list) else [actions[-1]] for i, action in enumerate(latest_actions): action_str = str(action) if action else "" if action_str: add_task_log(task_id, "action", f"[{i+1}/{len(latest_actions)}] {action_str}", current_step) urls = agent.history.urls() if urls and len(urls) > 0: current_url = urls[-1] if current_url: add_task_log(task_id, "url", current_url, current_step) except Exception as e: add_task_log(task_id, "error", f"日志捕获错误: {str(e)}", current_step) screenshot_id = None if save_screenshots: screenshot_id = await save_screenshot(task_id, agent, current_step, compress_screenshots) if screenshot_id: if "screenshots" not in tasks[task_id]: tasks[task_id]["screenshots"] = [] tasks[task_id]["screenshots"].append(screenshot_id) add_task_log(task_id, "screenshot", screenshot_id, current_step) step_data = {"task_id": task_id, "step": current_step, "timestamp": datetime.now().isoformat()} if screenshot_id: step_data["screenshot_id"] = screenshot_id asyncio.create_task(send_webhook(webhook_config, "task.step", step_data)) agent = Agent(task=task_description, llm=llm, browser=browser, use_vision=use_vision) running_agents[task_id] = agent # 保存 agent 引用用于实时截图 add_task_log(task_id, "info", f"开始执行任务: {task_description} (视觉: {'启用' if use_vision else '禁用'})", 0) history = await agent.run(on_step_end=on_step_end) steps = [] try: action_names = history.action_names() if hasattr(history, 'action_names') else [] extracted_contents = history.extracted_content() if hasattr(history, 'extracted_content') else [] errors = history.errors() if hasattr(history, 'errors') else [] urls = history.urls() if hasattr(history, 'urls') else [] model_thoughts = history.model_thoughts() if hasattr(history, 'model_thoughts') else [] num_steps = history.number_of_steps() if hasattr(history, 'number_of_steps') else len(action_names) for i in range(num_steps): step_detail = {"step": i + 1, "timestamp": datetime.now().isoformat()} if i < len(action_names): step_detail["action"] = action_names[i] if i < len(model_thoughts) and model_thoughts[i]: thought = model_thoughts[i] if hasattr(thought, 'evaluation_previous_goal'): step_detail["result"] = thought.evaluation_previous_goal elif hasattr(thought, 'memory'): step_detail["result"] = thought.memory if i < len(extracted_contents) and extracted_contents[i]: step_detail["result"] = extracted_contents[i] elif i < len(errors) and errors[i]: step_detail["result"] = f"Error: {errors[i]}" if i < len(urls) and urls[i]: step_detail["url"] = urls[i] steps.append(step_detail) if save_screenshots and browser: screenshot_paths = history.screenshot_paths() if hasattr(history, 'screenshot_paths') else [] for i, path in enumerate(screenshot_paths): if path: screenshot_id = f"{task_id}_{i+1}_{datetime.now().strftime('%H%M%S%f')}" if i < len(steps): steps[i]["screenshot_id"] = screenshot_id if "screenshots" not in tasks[task_id]: tasks[task_id]["screenshots"] = [] tasks[task_id]["screenshots"].append(screenshot_id) if task_id not in task_screenshots: task_screenshots[task_id] = [] task_screenshots[task_id].append({ "screenshot_id": screenshot_id, "step": i + 1, "timestamp": datetime.now().isoformat(), "path": path, }) except Exception as e: print(f"提取历史数据失败: {e}") result = history.final_result() if save_screenshots: final_screenshot_id = await save_screenshot(task_id, agent, len(steps) + 1, compress_screenshots) if final_screenshot_id: if "screenshots" not in tasks[task_id]: tasks[task_id]["screenshots"] = [] tasks[task_id]["screenshots"].append(final_screenshot_id) return result, steps # 执行任务并应用超时 result, steps = await asyncio.wait_for(run_task(), timeout=task_timeout) tasks[task_id]["status"] = "completed" tasks[task_id]["result"] = result tasks[task_id]["steps"] = steps tasks[task_id]["completed_at"] = datetime.now().isoformat() duration = (datetime.fromisoformat(tasks[task_id]["completed_at"]) - datetime.fromisoformat(tasks[task_id]["started_at"])).total_seconds() asyncio.create_task(send_webhook(webhook_config, "task.completed", { "task_id": task_id, "result": result, "steps": len(steps), "duration": duration, "completed_at": tasks[task_id]["completed_at"] })) except asyncio.TimeoutError: tasks[task_id]["status"] = "failed" tasks[task_id]["error"] = f"任务超时 (超过 {task_timeout} 秒)" tasks[task_id]["completed_at"] = datetime.now().isoformat() asyncio.create_task(send_webhook(webhook_config, "task.failed", { "task_id": task_id, "error": tasks[task_id]["error"], "failed_at": tasks[task_id]["completed_at"] })) except asyncio.CancelledError: tasks[task_id]["status"] = "cancelled" tasks[task_id]["error"] = "任务已被取消" tasks[task_id]["completed_at"] = datetime.now().isoformat() asyncio.create_task(send_webhook(webhook_config, "task.cancelled", { "task_id": task_id, "cancelled_at": tasks[task_id]["completed_at"] })) except Exception as e: tasks[task_id]["status"] = "failed" tasks[task_id]["error"] = str(e) tasks[task_id]["completed_at"] = datetime.now().isoformat() asyncio.create_task(send_webhook(webhook_config, "task.failed", { "task_id": task_id, "error": str(e), "failed_at": tasks[task_id]["completed_at"] })) finally: if browser: await release_browser_to_pool(browser) running_browsers.pop(task_id, None) running_tasks.pop(task_id, None) running_agents.pop(task_id, None) cleanup_old_tasks() @app.get("/", response_class=HTMLResponse) async def root(): return """ Browser-Use AI Agent

🔐 访问验证

请输入访问密码

密码错误,请重试

🌐 Browser-Use AI Agent

AI 驱动的浏览器自动化服务 | API 文档 | 退出登录

⚙️ 已保存的配置

▼

需要输入配置密码才能查看和管理已保存的配置

加载中...

📝 创建新任务

💡 提示:压缩截图可节省 50-70% 存储空间,适合长时间任务。超时范围 60-1800 秒

⏳ 当前任务 0

暂无运行中的任务

📋 历史任务 0

暂无历史任务

📄 任务详情

任务描述

-

执行结果

-

LLM 配置

-

时间信息

-

📸 截图 (0)

🤖 Agent 实时日志

等待日志...

🖥️ 实时浏览器画面

等待连接...
Browser Screen
FPS: -- 未连接
× Screenshot
""" # 直接插入这段代码到 app.py @app.post("/direct_control") async def direct_control(request: Dict[str, Any], _: bool = Depends(verify_password)): raw_code = request.get("code", "") # 1. 启动浏览器 browser = await get_browser_from_pool(headless=True) try: # 2. 核心修复:先尝试获取现有页面,没有就从 context 开一个 page = await browser.get_current_page() if not page: # 兼容性最高的方法:直接从 browser 实例获取上下文 context = await browser.get_context() page = await context.new_page() # 3. 注入执行环境 exec_env = {"page": page, "asyncio": asyncio, "browser": browser} # 将代码包装并执行 wrapped_code = "async def _run(page):\n" + "\n".join(f" {line}" for line in raw_code.split("\n")) exec(wrapped_code, globals(), exec_env) await exec_env["_run"](page) return {"status": "success", "msg": "指令执行成功", "url": page.url} except Exception as e: import traceback print(f"❌ 运行错误:\n{traceback.format_exc()}") return {"status": "error", "msg": str(e)} finally: # 4. 释放资源,防止内存溢出 await release_browser_to_pool(browser) @app.get("/api") async def api_info(): return { "service": "Browser-Use API", "version": "1.2.0", "docs": "/docs", "endpoints": { "/task": "POST - 提交任务", "/task/{task_id}": "GET - 查询结果", "/task/{task_id}": "DELETE - 删除任务", "/task/{task_id}/cancel": "POST - 取消任务", "/task/{task_id}/screenshots": "GET - 获取任务截图列表", "/task/{task_id}/screenshot/latest": "GET - 获取最新截图", "/task/{task_id}/logs": "GET - 获取任务日志", "/task/{task_id}/logs/stream": "GET - 实时日志流 (SSE)", "/screenshot/{screenshot_id}": "GET - 获取指定截图", "/tasks": "GET - 所有任务", "/tasks/clear": "POST - 清理已完成任务", "/health": "GET - 健康检查", } } @app.websocket("/task/{task_id}/screen/stream") async def screen_stream(websocket: WebSocket, task_id: str): """ 实时浏览器画面流(WebSocket) 每 500ms 推送一帧 JPEG 截图(base64 编码) """ # 验证密码(从 query 参数获取) password = websocket.query_params.get("password", "") if ACCESS_PASSWORD and password != ACCESS_PASSWORD: await websocket.close(code=4001, reason="密码错误") return # 验证任务存在 if task_id not in tasks: await websocket.close(code=4004, reason="任务不存在") return await websocket.accept() try: while True: # 检查任务状态 task_info = tasks.get(task_id) if not task_info: await websocket.send_json({"event": "task_deleted"}) break if task_info["status"] not in ["pending", "running"]: await websocket.send_json({ "event": "task_ended", "status": task_info["status"] }) break # 获取 browser 并截图 browser = running_browsers.get(task_id) if browser: try: import base64 screenshot_b64 = None page = None method_used = None # 方法1: 通过 browser.get_current_page() 获取页面 if hasattr(browser, 'get_current_page'): try: page = await browser.get_current_page() if page: method_used = "get_current_page" except: pass # 方法2: 通过 browser.context 获取页面 if not page and hasattr(browser, 'context') and browser.context: ctx = browser.context if hasattr(ctx, 'current_page') and ctx.current_page: page = ctx.current_page method_used = "context.current_page" elif hasattr(ctx, 'pages') and ctx.pages: page = ctx.pages[-1] method_used = "context.pages[-1]" # 方法3: 通过 playwright_browser 获取页面 if not page and hasattr(browser, 'playwright_browser') and browser.playwright_browser: contexts = browser.playwright_browser.contexts if contexts and len(contexts) > 0: pages = contexts[0].pages if pages and len(pages) > 0: page = pages[-1] method_used = "playwright_browser.contexts[0].pages[-1]" # 截图 if page: screenshot_result = await page.screenshot() # 检查返回类型,转换为字节 if isinstance(screenshot_result, str): screenshot_bytes = base64.b64decode(screenshot_result) else: screenshot_bytes = screenshot_result # 使用 PIL 压缩为 JPEG try: from PIL import Image import io img = Image.open(io.BytesIO(screenshot_bytes)) if img.mode == 'RGBA': img = img.convert('RGB') # 缩小尺寸以减少带宽 max_width = 1280 if img.width > max_width: ratio = max_width / img.width new_size = (max_width, int(img.height * ratio)) img = img.resize(new_size, Image.Resampling.LANCZOS) # 压缩为 JPEG buffer = io.BytesIO() img.save(buffer, format='JPEG', quality=50, optimize=True) screenshot_b64 = base64.b64encode(buffer.getvalue()).decode('utf-8') except: # PIL 失败则使用原图 screenshot_b64 = base64.b64encode(screenshot_bytes).decode('utf-8') if screenshot_b64: await websocket.send_json({ "event": "frame", "data": screenshot_b64, "timestamp": datetime.now().isoformat() }) else: await websocket.send_json({ "event": "waiting", "message": "等待页面加载..." }) except Exception as e: await websocket.send_json({ "event": "error", "message": f"截图失败: {str(e)}" }) else: await websocket.send_json({ "event": "waiting", "message": "等待浏览器启动..." }) # 等待 1 秒(降低频率以减少性能开销) await asyncio.sleep(1.0) except WebSocketDisconnect: pass except Exception as e: try: await websocket.send_json({"event": "error", "message": str(e)}) except: pass @app.get("/health") async def health_check(): running_count = sum(1 for t in tasks.values() if t["status"] == "running") pending_count = sum(1 for t in tasks.values() if t["status"] == "pending") completed_count = sum(1 for t in tasks.values() if t["status"] == "completed") return { "status": "healthy", "running_tasks": running_count, "pending_tasks": pending_count, "completed_tasks": completed_count, "total_tasks": len(tasks), "max_concurrent_tasks": MAX_CONCURRENT_TASKS, "task_retention_hours": TASK_RETENTION_HOURS, } @app.post("/webhook/test") async def test_webhook(webhook_config: WebhookConfig, _: bool = Depends(verify_password)): """测试 Webhook 发送""" try: await send_webhook(webhook_config, "test.ping", { "message": "This is a test webhook", "timestamp": datetime.now().isoformat() }) return {"status": "success", "message": "Webhook 测试请求已发送,请检查接收端"} except Exception as e: return {"status": "error", "message": str(e)} @app.post("/task", response_model=TaskResponse) async def create_task(request: TaskRequest, background_tasks: BackgroundTasks, _: bool = Depends(verify_password)): # 检查并发限制 running_count = sum(1 for t in tasks.values() if t["status"] in ["pending", "running"]) if running_count >= MAX_CONCURRENT_TASKS: raise HTTPException( status_code=429, detail=f"已达到最大并发任务数 ({MAX_CONCURRENT_TASKS}),请稍后重试" ) task_id = str(uuid.uuid4()) # 使用请求中的 LLM 配置 llm_config = request.llm_config # 存储配置信息(隐藏 api_key) llm_config_display = LLMConfig( provider=llm_config.provider, model=llm_config.model, api_key="***", base_url=llm_config.base_url, temperature=llm_config.temperature, ) tasks[task_id] = { "task_id": task_id, "status": "pending", "task": request.task, "result": None, "error": None, "steps": [], "screenshots": [], "llm_config": llm_config_display.model_dump(), "webhook": request.webhook.model_dump() if request.webhook else None, "created_at": datetime.now().isoformat(), "started_at": None, "completed_at": None, } # 创建异步任务并保存引用 async def run_task(): await execute_task(task_id, request.task, request.headless, request.save_screenshots, llm_config, request.webhook, request.use_vision, request.compress_screenshots, request.timeout) loop = asyncio.get_event_loop() async_task = loop.create_task(run_task()) running_tasks[task_id] = async_task return TaskResponse( task_id=task_id, status="pending", message=f"任务已提交,使用 GET /task/{task_id} 查询状态" ) @app.get("/task/{task_id}", response_model=TaskResult) async def get_task(task_id: str, _: bool = Depends(verify_password)): if task_id not in tasks: raise HTTPException(status_code=404, detail="任务不存在") return TaskResult(**tasks[task_id]) @app.get("/task/{task_id}/screenshots", response_model=ScreenshotListResponse) async def get_task_screenshots(task_id: str, _: bool = Depends(verify_password)): """获取任务的所有截图列表""" if task_id not in tasks: raise HTTPException(status_code=404, detail="任务不存在") screenshots = task_screenshots.get(task_id, []) screenshot_list = [ ScreenshotInfo( screenshot_id=s["screenshot_id"], step=s["step"], timestamp=s["timestamp"], url=f"/screenshot/{s['screenshot_id']}" ) for s in screenshots ] return ScreenshotListResponse( task_id=task_id, screenshots=screenshot_list, total=len(screenshot_list) ) @app.get("/task/{task_id}/screenshot/latest") async def get_latest_screenshot(task_id: str, format: str = "image", _: bool = Depends(verify_password)): """ 获取任务的最新截图 - format=image: 返回图片文件 - format=base64: 返回 base64 编码 """ if task_id not in tasks: raise HTTPException(status_code=404, detail="任务不存在") screenshots = task_screenshots.get(task_id, []) if not screenshots: raise HTTPException(status_code=404, detail="暂无截图") latest = screenshots[-1] screenshot_path = Path(latest["path"]) if not screenshot_path.exists(): raise HTTPException(status_code=404, detail="截图文件不存在") if format == "base64": with open(screenshot_path, "rb") as f: image_data = base64.b64encode(f.read()).decode() return { "screenshot_id": latest["screenshot_id"], "step": latest["step"], "timestamp": latest["timestamp"], "image_base64": image_data, "content_type": "image/png" } return FileResponse( screenshot_path, media_type="image/png", filename=f"{latest['screenshot_id']}.png" ) @app.get("/screenshot/{screenshot_id}") async def get_screenshot(screenshot_id: str, format: str = "image", _: bool = Depends(verify_password)): """ 获取指定截图 - format=image: 返回图片文件 - format=base64: 返回 base64 编码 """ # 从 screenshot_id 解析 task_id parts = screenshot_id.split("_") if len(parts) < 2: raise HTTPException(status_code=400, detail="无效的截图ID") task_id = parts[0] # 查找截图 screenshots = task_screenshots.get(task_id, []) screenshot = next((s for s in screenshots if s["screenshot_id"] == screenshot_id), None) if not screenshot: raise HTTPException(status_code=404, detail="截图不存在") screenshot_path = Path(screenshot["path"]) if not screenshot_path.exists(): raise HTTPException(status_code=404, detail="截图文件不存在") if format == "base64": with open(screenshot_path, "rb") as f: image_data = base64.b64encode(f.read()).decode() return { "screenshot_id": screenshot["screenshot_id"], "step": screenshot["step"], "timestamp": screenshot["timestamp"], "image_base64": image_data, "content_type": "image/png" } return FileResponse( screenshot_path, media_type="image/png", filename=f"{screenshot_id}.png" ) @app.get("/task/{task_id}/screenshot/stream") async def stream_screenshots(task_id: str, password: Optional[str] = Query(None)): """ 实时流式获取截图(Server-Sent Events) 客户端可以持续接收新截图的通知 """ # SSE 端点手动验证密码(因为 SSE 不支持自定义 Header) if ACCESS_PASSWORD and password != ACCESS_PASSWORD: raise HTTPException(status_code=401, detail="密码错误或未提供") if task_id not in tasks: raise HTTPException(status_code=404, detail="任务不存在") async def event_generator(): last_count = 0 while True: # 检查任务是否还在运行 task_info = tasks.get(task_id) if not task_info: yield f"data: {{'event': 'task_deleted'}}\n\n" break screenshots = task_screenshots.get(task_id, []) current_count = len(screenshots) # 发送新截图通知 if current_count > last_count: for i in range(last_count, current_count): s = screenshots[i] yield f"data: {{\"event\": \"new_screenshot\", \"screenshot_id\": \"{s['screenshot_id']}\", \"step\": {s['step']}, \"timestamp\": \"{s['timestamp']}\", \"url\": \"/screenshot/{s['screenshot_id']}\"}}\n\n" last_count = current_count # 任务结束 if task_info["status"] in ["completed", "failed", "cancelled"]: yield f"data: {{\"event\": \"task_ended\", \"status\": \"{task_info['status']}\"}}\n\n" break await asyncio.sleep(1) # 每秒检查一次 return StreamingResponse( event_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", } ) @app.get("/task/{task_id}/logs") async def get_task_logs(task_id: str, _: bool = Depends(verify_password)): """获取任务的所有日志""" if task_id not in tasks: raise HTTPException(status_code=404, detail="任务不存在") logs = task_logs.get(task_id, []) return { "task_id": task_id, "logs": logs, "total": len(logs) } @app.get("/task/{task_id}/logs/stream") async def stream_task_logs(task_id: str, password: Optional[str] = Query(None)): """ 实时流式获取任务日志(Server-Sent Events) 客户端可以持续接收 Agent 的实时日志信息 """ # SSE 端点手动验证密码(因为 SSE 不支持自定义 Header) if ACCESS_PASSWORD and password != ACCESS_PASSWORD: raise HTTPException(status_code=401, detail="密码错误或未提供") if task_id not in tasks: raise HTTPException(status_code=404, detail="任务不存在") async def event_generator(): import json last_count = 0 while True: # 检查任务是否还存在 task_info = tasks.get(task_id) if not task_info: yield f"data: {json.dumps({'event': 'task_deleted'})}\n\n" break logs = task_logs.get(task_id, []) current_count = len(logs) # 发送新日志 if current_count > last_count: for i in range(last_count, current_count): log = logs[i] yield f"data: {json.dumps({'event': 'log', 'log': log})}\n\n" last_count = current_count # 任务结束 if task_info["status"] in ["completed", "failed", "cancelled"]: yield f"data: {json.dumps({'event': 'task_ended', 'status': task_info['status'], 'result': task_info.get('result'), 'error': task_info.get('error')})}\n\n" break await asyncio.sleep(0.5) # 每 0.5 秒检查一次 return StreamingResponse( event_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", } ) @app.post("/task/{task_id}/cancel", response_model=CancelResponse) async def cancel_task(task_id: str, _: bool = Depends(verify_password)): """取消正在运行的任务""" if task_id not in tasks: raise HTTPException(status_code=404, detail="任务不存在") task_info = tasks[task_id] if task_info["status"] in ["completed", "failed", "cancelled"]: raise HTTPException( status_code=400, detail=f"任务已结束,状态: {task_info['status']}" ) # 取消异步任务 if task_id in running_tasks: running_tasks[task_id].cancel() # 关闭浏览器 if task_id in running_browsers: try: await running_browsers[task_id].stop() except: pass tasks[task_id]["status"] = "cancelled" tasks[task_id]["error"] = "任务已被用户取消" tasks[task_id]["completed_at"] = datetime.now().isoformat() return CancelResponse( task_id=task_id, status="cancelled", message="任务已取消" ) @app.get("/tasks", response_model=TaskListResponse) async def list_tasks(status: Optional[str] = None, _: bool = Depends(verify_password)): """列出所有任务,可按状态筛选""" task_list = list(tasks.values()) if status: task_list = [t for t in task_list if t["status"] == status] return TaskListResponse( tasks=[TaskResult(**t) for t in task_list], total=len(task_list) ) @app.post("/tasks/clear") async def clear_completed_tasks(delete_screenshots: bool = True, _: bool = Depends(verify_password)): """清理所有已完成/失败/取消的任务""" to_delete = [ task_id for task_id, task in tasks.items() if task["status"] in ["completed", "failed", "cancelled"] ] for task_id in to_delete: # 删除截图 if delete_screenshots: task_dir = SCREENSHOTS_DIR / task_id if task_dir.exists(): shutil.rmtree(task_dir) task_screenshots.pop(task_id, None) del tasks[task_id] return { "message": f"已清理 {len(to_delete)} 个任务", "deleted_count": len(to_delete), "remaining_count": len(tasks) } @app.delete("/task/{task_id}") async def delete_task(task_id: str, force: bool = False, delete_screenshots: bool = True, _: bool = Depends(verify_password)): """ 删除任务 - force=False: 只能删除已结束的任务 - force=True: 强制删除(会先取消运行中的任务) - delete_screenshots=True: 同时删除截图文件 """ if task_id not in tasks: raise HTTPException(status_code=404, detail="任务不存在") task_info = tasks[task_id] # 如果任务正在运行 if task_info["status"] in ["pending", "running"]: if not force: raise HTTPException( status_code=400, detail="任务正在运行,使用 force=true 强制删除或先取消任务" ) # 强制删除:先取消任务 if task_id in running_tasks: running_tasks[task_id].cancel() if task_id in running_browsers: try: await running_browsers[task_id].stop() except: pass running_tasks.pop(task_id, None) running_browsers.pop(task_id, None) # 删除截图 if delete_screenshots: task_dir = SCREENSHOTS_DIR / task_id if task_dir.exists(): shutil.rmtree(task_dir) task_screenshots.pop(task_id, None) del tasks[task_id] return {"message": "任务已删除", "task_id": task_id} # ==================== LLM 配置管理 API ==================== @app.get("/configs", response_model=LLMConfigListResponse) async def list_configs(_: bool = Depends(verify_password), __: bool = Depends(verify_config_password)): """获取所有 LLM 配置列表(API Key 已掩码),需要配置密码""" try: configs_data = _load_configs() configs = [] for c in sorted(configs_data, key=lambda x: (not x.get("is_default", False), x.get("updated_at", ""))): decrypted_key = decrypt_api_key(c.get("api_key", "")) configs.append(LLMConfigResponse( id=c["id"], name=c["name"], provider=c["provider"], model=c["model"], api_key_masked=mask_api_key(decrypted_key), base_url=c.get("base_url", ""), is_default=c.get("is_default", False), created_at=c.get("created_at", ""), updated_at=c.get("updated_at", "") )) return LLMConfigListResponse(configs=configs, total=len(configs)) except Exception as e: raise HTTPException(status_code=500, detail=f"获取配置列表失败: {str(e)}") @app.post("/configs", response_model=LLMConfigResponse) async def create_config(config: LLMConfigCreate, _: bool = Depends(verify_password), __: bool = Depends(verify_config_password)): """创建新的 LLM 配置,需要配置密码""" try: configs_data = _load_configs() now = datetime.now().isoformat() if config.is_default: for c in configs_data: c["is_default"] = False new_config = { "id": str(uuid.uuid4()), "name": config.name, "provider": config.provider, "model": config.model, "api_key": encrypt_api_key(config.api_key or ""), "base_url": config.base_url or "", "is_default": config.is_default or False, "created_at": now, "updated_at": now, } configs_data.append(new_config) _save_configs(configs_data) decrypted_key = decrypt_api_key(new_config["api_key"]) return LLMConfigResponse( id=new_config["id"], name=new_config["name"], provider=new_config["provider"], model=new_config["model"], api_key_masked=mask_api_key(decrypted_key), base_url=new_config["base_url"], is_default=new_config["is_default"], created_at=new_config["created_at"], updated_at=new_config["updated_at"], ) except Exception as e: raise HTTPException(status_code=500, detail=f"创建配置失败: {str(e)}") @app.get("/configs/{config_id}", response_model=LLMConfigWithKey) async def get_config(config_id: str, _: bool = Depends(verify_password), __: bool = Depends(verify_config_password)): """获取单个配置详情(包含完整 API Key),需要配置密码""" try: configs_data = _load_configs() target = next((c for c in configs_data if c["id"] == config_id), None) if not target: raise HTTPException(status_code=404, detail="配置不存在") decrypted_key = decrypt_api_key(target.get("api_key", "")) return LLMConfigWithKey( id=target["id"], name=target["name"], provider=target["provider"], model=target["model"], api_key=decrypted_key, base_url=target.get("base_url", ""), is_default=target.get("is_default", False), ) except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}") @app.put("/configs/{config_id}", response_model=LLMConfigResponse) async def update_config(config_id: str, config: LLMConfigCreate, _: bool = Depends(verify_password), __: bool = Depends(verify_config_password)): """更新 LLM 配置,需要配置密码""" try: configs_data = _load_configs() target = next((c for c in configs_data if c["id"] == config_id), None) if not target: raise HTTPException(status_code=404, detail="配置不存在") if config.is_default: for c in configs_data: if c["id"] != config_id: c["is_default"] = False now = datetime.now().isoformat() target.update({ "name": config.name, "provider": config.provider, "model": config.model, "api_key": encrypt_api_key(config.api_key or ""), "base_url": config.base_url or "", "is_default": config.is_default or False, "updated_at": now, }) _save_configs(configs_data) decrypted_key = decrypt_api_key(target["api_key"]) return LLMConfigResponse( id=target["id"], name=target["name"], provider=target["provider"], model=target["model"], api_key_masked=mask_api_key(decrypted_key), base_url=target["base_url"], is_default=target["is_default"], created_at=target.get("created_at", ""), updated_at=target["updated_at"], ) except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=f"更新配置失败: {str(e)}") @app.delete("/configs/{config_id}") async def delete_config(config_id: str, _: bool = Depends(verify_password), __: bool = Depends(verify_config_password)): """删除 LLM 配置,需要配置密码""" try: configs_data = _load_configs() original_len = len(configs_data) configs_data = [c for c in configs_data if c["id"] != config_id] if len(configs_data) == original_len: raise HTTPException(status_code=404, detail="配置不存在") _save_configs(configs_data) return {"message": "配置已删除", "config_id": config_id} except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=f"删除配置失败: {str(e)}") @app.post("/configs/{config_id}/set-default") async def set_default_config(config_id: str, _: bool = Depends(verify_password), __: bool = Depends(verify_config_password)): """设置默认配置,需要配置密码""" try: configs_data = _load_configs() target = next((c for c in configs_data if c["id"] == config_id), None) if not target: raise HTTPException(status_code=404, detail="配置不存在") for c in configs_data: c["is_default"] = (c["id"] == config_id) _save_configs(configs_data) return {"message": "已设置为默认配置", "config_id": config_id} except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=f"设置默认配置失败: {str(e)}") if __name__ == "__main__": import uvicorn # HF Spaces 使用端口 7860 uvicorn.run(app, host="0.0.0.0", port=7860)