扩展默认代理并编写自定义函数调用
基本函数注册
函数可以是 同步 (sync) 或 异步 (async),但要保持其 专注且单一用途。
示例:注册基本函数
from browser_use import Controller, ActionResult# 初始化 Controllercontroller = Controller()@controller.action('Ask user for information')def ask_human(question: str) -> str:answer = input(f'\n{question}\nInput: ')return ActionResult(extracted_content=answer)
默认 Controller 已经实现了与浏览器交互所需的基本功能。
# 传递 Controller 给 Agentagent = Agent(task=task,llm=llm,controller=controller)
⚠️ 注意:
- 函数名称和描述要简短清晰,因为 Agent 仅根据名称和描述决定调用哪个函数。
- 函数的输出是字符串化的,并传递给 Agent。
基于浏览器的函数
如果函数需要访问 浏览器实例,只需在参数中添加 browser:
from browser_use import Browser, Controller, ActionResultcontroller = Controller()@controller.action('Open website')async def open_website(url: str, browser: Browser):page = browser.get_current_page()await page.goto(url)return ActionResult(extracted_content='Website opened')
使用 Pydantic 定义结构化参数
对于复杂的操作,可以使用 Pydantic 定义参数模型:
from pydantic import BaseModelfrom typing import Optionalfrom browser_use import Controller, ActionResult, Browsercontroller = Controller()# 定义 Pydantic 模型class JobDetails(BaseModel):title: strcompany: strjob_link: strsalary: Optional[str] = None # 可选字段@controller.action('Save job details which you found on page',param_model=JobDetails)async def save_job(params: JobDetails, browser: Browser):print(f"Saving job: {params.title} at {params.company}")# 访问浏览器page = browser.get_current_page()await page.goto(params.job_link)
多个代理共享自定义操作
同一个 controller 可以被多个 Agent 共享。
controller = Controller()# ... 先注册所需的自定义操作到 Controlleragent = Agent(task="Go to website X and find the latest news",llm=llm,controller=controller)await agent.run()agent2 = Agent(task="Go to website Y and find the latest news",llm=llm,controller=controller)await agent2.run()
Controller 无状态 (stateless),可以用来管理多个操作,并支持多个代理 (agents)。
排除某些函数
如果不希望某些操作被 Agent 调用,可以在 Controller 中排除它们:
controller = Controller(exclude_actions=['open_tab', 'search_google'])
更多示例
如文件上传、通知等示例,请访问: 🔗 examples/custom-functions
