Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Add template generation command for quick project setup
Reagan Hsua4839215f56e
diff --git a/browser_use/cli.py b/browser_use/cli.pyindex 279731bd6..3d83d4755 100644--- a/browser_use/cli.py+++ b/browser_use/cli.py@@ -1877,6 +1877,13 @@ async def run_auth_command():@click.group(invoke_without_command=True)@click.option('--version', is_flag=True, help='Print version and exit')+ '--template',+ type=click.Choice(['quickstart', 'advanced', 'tools'], case_sensitive=False),+ help='Generate a template file (quickstart, advanced, or tools)',+)[email protected]('--output', '-o', type=click.Path(), help='Output file path for template (default: browser_use_<template>.py)')[email protected]('--force', '-f', is_flag=True, help='Overwrite existing files without asking')@click.option('--model', type=str, help='Model to use (e.g., gpt-5-mini, claude-4-sonnet, gemini-2.5-flash)')@click.option('--debug', is_flag=True, help='Enable verbose startup logging')@click.option('--headless', is_flag=True, help='Run browser in headless mode', default=None)@@ -1898,8 +1905,17 @@ def main(ctx: click.Context, debug: bool = False, **kwargs):"""Browser Use - AI Agent for Web AutomationRun without arguments to start the interactive TUI.++ Examples:+ uvx browser-use --template quickstart+ uvx browser-use --template advanced --output my_script.py"""+ # Handle template generation+ if kwargs.get('template'):+ _run_template_generation(kwargs['template'], kwargs.get('output'), kwargs.get('force', False))+ return+if ctx.invoked_subcommand is None:# No subcommand, run the main interfacerun_main_interface(ctx, debug, **kwargs)@@ -2053,5 +2069,188 @@ def install():sys.exit(1)+# ============================================================================+# Template Generation - Generate template files+# ============================================================================++# Template metadata+INIT_TEMPLATES = {+ 'quickstart': {+ 'file': 'quickstart_template.py',+ 'description': 'Simplest setup - capable of any web task with minimal configuration',+ },+ 'advanced': {+ 'file': 'advanced_template.py',+ 'description': 'All configuration options shown with defaults',+ },+ 'tools': {+ 'file': 'tools_template.py',+ 'description': 'Custom action examples - extend the agent with your own functions',+ },+}+++def _run_template_generation(template: str, output: str | None, force: bool):+ """Generate a template file (called from main CLI)."""+ # Determine output path+ if output:+ output_path = Path(output)+ else:+ output_path = Path.cwd() / f'browser_use_{template}.py'++ # Read template file+ try:+ templates_dir = Path(__file__).parent / 'cli_templates'+ template_file = INIT_TEMPLATES[template]['file']+ template_path = templates_dir / template_file+ content = template_path.read_text(encoding='utf-8')+ except Exception as e:+ click.echo(f'❌ Error reading template: {e}', err=True)+ sys.exit(1)++ # Write file+ if _write_init_file(output_path, content, force):+ click.echo(f'✅ Created {output_path}')+ click.echo('\nNext steps:')+ click.echo(' 1. Install browser-use:')+ click.echo(' uv pip install browser-use')+ click.echo(' 2. Set up your API key in .env file or environment:')+ click.echo(' BROWSER_USE_API_KEY=your-key')+ click.echo(' (Get your key at https://cloud.browser-use.com/dashboard/api)')+ click.echo(' 3. Run your script:')+ click.echo(f' python {output_path.name}')+ else:+ sys.exit(1)+++def _write_init_file(output_path: Path, content: str, force: bool = False) -> bool:+ """Write content to a file, with safety checks."""+ # Check if file already exists+ if output_path.exists() and not force:+ click.echo(f'⚠️ File already exists: {output_path}')+ if not click.confirm('Overwrite?', default=False):+ click.echo('❌ Cancelled')+ return False++ # Ensure parent directory exists+ output_path.parent.mkdir(parents=True, exist_ok=True)++ # Write file+ try:+ output_path.write_text(content, encoding='utf-8')+ return True+ except Exception as e:+ click.echo(f'❌ Error writing file: {e}', err=True)+ return False++[email protected]('init')+ '--template',+ '-t',+ type=click.Choice(['quickstart', 'advanced', 'tools'], case_sensitive=False),+ help='Template to use',+)+ '--output',+ '-o',+ type=click.Path(),+ help='Output file path (default: browser_use_<template>.py)',+)+ '--force',+ '-f',+ is_flag=True,+ help='Overwrite existing files without asking',+)+ '--list',+ '-l',+ 'list_templates',+ is_flag=True,+ help='List available templates',+)+def init(+ template: str | None,+ output: str | None,+ force: bool,+ list_templates: bool,+):+ """+ Generate a browser-use template file to get started quickly.++ Examples:++ \b+ # Interactive mode - prompts for template selection+ uvx browser-use init++ \b+ # Generate quickstart template+ uvx browser-use init --template quickstart++ \b+ # Generate advanced template with custom filename+ uvx browser-use init --template advanced --output my_script.py++ \b+ # List available templates+ uvx browser-use init --list+ """++ # Handle --list flag+ if list_templates:+ click.echo('Available templates:\n')+ for name, info in INIT_TEMPLATES.items():+ click.echo(f' {name:12} - {info["description"]}')+ return++ # Interactive template selection if not provided+ if not template:+ click.echo('Available templates:\n')+ for name, info in INIT_TEMPLATES.items():+ click.echo(f' {name:12} - {info["description"]}')+ click.echo()++ template = click.prompt(+ 'Which template would you like to use?',+ type=click.Choice(['quickstart', 'advanced', 'tools'], case_sensitive=False),+ default='quickstart',+ )++ # Template is guaranteed to be set at this point (either from option or prompt)+ assert template is not None++ # Determine output path+ if output:+ output_path = Path(output)+ else:+ output_path = Path.cwd() / f'browser_use_{template}.py'++ # Read template file+ try:+ templates_dir = Path(__file__).parent / 'cli_templates'+ template_file = INIT_TEMPLATES[template]['file']+ template_path = templates_dir / template_file+ content = template_path.read_text(encoding='utf-8')+ except Exception as e:+ click.echo(f'❌ Error reading template: {e}', err=True)+ sys.exit(1)++ # Write file+ if _write_init_file(output_path, content, force):+ click.echo(f'✅ Created {output_path}')+ click.echo('\nNext steps:')+ click.echo(' 1. Install browser-use:')+ click.echo(' uv pip install browser-use')+ click.echo(' 2. Set up your API key in .env file or environment:')+ click.echo(' BROWSER_USE_API_KEY=your-key')+ click.echo(' (Get your key at https://cloud.browser-use.com/dashboard/api)')+ click.echo(' 3. Run your script:')+ click.echo(f' python {output_path.name}')+ else:+ sys.exit(1)++if __name__ == '__main__':main()diff --git a/browser_use/cli_templates/advanced_template.py b/browser_use/cli_templates/advanced_template.pynew file mode 100644index 000000000..0b240e0d1--- /dev/null+++ b/browser_use/cli_templates/advanced_template.py@@ -0,0 +1,51 @@+"""+Advanced Example++This example demonstrates how to configure the Agent and Browser+with many configuration options, all set to default values.++Check out all configuration settings at https://docs.browser-use.com/customize/agent/all-parameters.+"""++import asyncio++from dotenv import load_dotenv++from browser_use import Agent, Browser, ChatBrowserUse++load_dotenv()+++async def main():+ browser = Browser(+ use_cloud=False,+ # headless=False,+ # disable_security=False,+ # extra_chromium_args=[],+ # allowed_domains=None,+ # prohibited_domains=None,+ # cdp_url=None,+ )++ llm = ChatBrowserUse()++ agent = Agent(+ task='Find the number of stars of the browser-use repository on GitHub',+ llm=llm,+ browser=browser,+ # use_vision='auto',+ # save_conversation_path=None,+ # max_failures=3,+ # generate_gif=False,+ # max_actions_per_step=4,+ # use_thinking=True,+ # flash_mode=False,+ # calculate_cost=False,+ # step_timeout=180,+ )++ await agent.run()+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/browser_use/cli_templates/quickstart_template.py b/browser_use/cli_templates/quickstart_template.pynew file mode 100644index 000000000..806fca674--- /dev/null+++ b/browser_use/cli_templates/quickstart_template.py@@ -0,0 +1,30 @@+"""+Quickstart Example++This is the simplest way to use Browser Use- capable of any web task,+with minimal configuration.+"""++import asyncio++from dotenv import load_dotenv++from browser_use import Agent, Browser, ChatBrowserUse++load_dotenv()+++async def main():+ browser = Browser(use_cloud=False)+ llm = ChatBrowserUse()+ task = 'Find the number of stars of the browser-use repository on GitHub'+ agent = Agent(+ browser=browser,+ task=task,+ llm=llm,+ )+ await agent.run()+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/browser_use/cli_templates/tools_template.py b/browser_use/cli_templates/tools_template.pynew file mode 100644index 000000000..e48ff45de--- /dev/null+++ b/browser_use/cli_templates/tools_template.py@@ -0,0 +1,45 @@+"""+Custom Tools Example++This example demonstrates how to create custom tools that the agent can use+alongside the built-in browser actions.+"""++import asyncio++from dotenv import load_dotenv++from browser_use import ActionResult, Agent, Browser, ChatBrowserUse, Tools++load_dotenv()++# Create a Tools instance to register custom actions+tools = Tools()+[email protected]('Save text content to a file')+async def save_to_file(filename: str, content: str):+ from pathlib import Path++ try:+ Path(filename).write_text(content, encoding='utf-8')+ return ActionResult(extracted_content=f'Saved to {filename}', include_in_memory=True)+ except Exception as e:+ return ActionResult(extracted_content=f'Error saving file: {e}', include_in_memory=True)+++async def main():+ browser = Browser(use_cloud=False)+ llm = ChatBrowserUse()+ task = 'Go to github.com and find the number of GitHub stars for browser-use and use the save_to_file tool to save the result to stars.txt'+ agent = Agent(+ task=task,+ llm=llm,+ browser=browser,+ tools=tools,+ )++ await agent.run()+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/pyproject.toml b/pyproject.tomlindex b5d015931..f4ccf118f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -156,6 +156,7 @@ include = ["browser_use/agent/system_prompt_no_thinking.md","browser_use/agent/system_prompt_flash.md","browser_use/code_use/system_prompt.md",+ "browser_use/cli_templates/*.py","browser_use/py.typed","browser_use/dom/**/*.js","!tests/**/*.py",