app.py 3.66 KB
"""browser-use 体验 demo:网页聊天窗口,用自然语言让 Agent 操作浏览器(如 Google 搜索)。

运行:uv run app.py  ->  http://127.0.0.1:7860
聊天里发送 /reset 可关闭浏览器、开始新会话。
"""
import asyncio
import os

import gradio as gr
from browser_use import Agent, Browser, ChatOpenAI
from dotenv import load_dotenv

load_dotenv()

RULES = """
回答规则:
- 用中文回答。
- 如果是搜索任务,用 Markdown 表格列出「标题 | 链接 | 摘要」,忽略广告。
- 遇到 cookie/同意弹窗选择拒绝或关闭。
- 遇到验证码(captcha)不要尝试绕过,直接停止并如实说明。
"""

_browser: Browser | None = None
_agent: Agent | None = None
_busy = asyncio.Lock()


def make_llm() -> ChatOpenAI:
    return ChatOpenAI(
        model=os.environ["LLM_MODEL"],
        api_key=os.environ["DASHSCOPE_API_KEY"],
        base_url=os.environ["LLM_BASE_URL"],
        temperature=0,
        # 非 OpenAI 模型:不强制 JSON schema 输出,把 schema 写进 system prompt
        dont_force_structured_output=True,
        add_schema_to_system_prompt=True,
    )


async def reset() -> None:
    global _browser, _agent
    _agent = None
    if _browser is not None:
        try:
            await _browser.kill()
        except Exception:
            pass
        _browser = None


async def chat(message: str, history):
    global _browser, _agent
    if message.strip() == "/reset":
        await reset()
        yield "已关闭浏览器,下一条消息将开始新会话。"
        return
    if _busy.locked():
        yield "上一个任务还在执行,请稍候或点停止。"
        return

    async with _busy:
        queue: asyncio.Queue = asyncio.Queue()

        async def on_step(state, output, step):
            goal = getattr(output, "next_goal", "") or ""
            queue.put_nowait(f"**步骤 {step}** · {goal}\n\n`{state.url}`")

        if _agent is None:
            headless = os.environ.get("HEADLESS", "true").lower() in ("1", "true", "yes")
            _browser = Browser(headless=headless, keep_alive=True)
            _agent = Agent(
                task=message + "\n" + RULES,
                llm=make_llm(),
                browser=_browser,
                use_vision=True,
                use_judge=False,  # 省掉额外的评判调用
                register_new_step_callback=on_step,
            )
        else:
            _agent.register_new_step_callback = on_step
            _agent.add_new_task(message + "\n" + RULES)

        agent = _agent
        run = asyncio.create_task(agent.run(max_steps=20))
        steps: list[str] = []
        try:
            while not run.done() or not queue.empty():
                try:
                    steps.append(await asyncio.wait_for(queue.get(), timeout=0.5))
                    yield "\n\n".join(steps) + "\n\n⏳ 执行中…"
                except asyncio.TimeoutError:
                    pass
            history_result = run.result()
            final = history_result.final_result() or "(Agent 没有返回结果,可展开上方步骤查看过程)"
            yield "\n\n".join(steps) + "\n\n---\n### 结果\n" + final
        except BaseException:
            agent.stop()
            run.cancel()
            raise


demo = gr.ChatInterface(
    chat,
    title="browser-use Demo",
    description="用自然语言告诉我要做什么,例如:去 Google 搜索「Claude Code 是什么」,给我前 5 条结果。发送 /reset 开启新会话。",
    examples=["去 Google 搜索「Claude Code 是什么」,给我前 5 条结果的标题、链接和摘要"],
)

if __name__ == "__main__":
    demo.launch(server_name="127.0.0.1", server_port=7860)