app.py
3.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""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)