### Install and Configure browser-use for News Monitoring Source: https://docs.browser-use.com/llms-full.txt These bash commands show how to install the 'browser-use' library, set up your Google API key, and clone the repository to access the news monitoring example. Ensure you have Python and pip installed. ```bash pip install -U browser-use ``` ```bash export GOOGLE_API_KEY='your-google-api-key-here' ``` ```bash git clone https://github.com/browser-use/browser-use.git cd browser-use/examples/apps/news-use ``` -------------------------------- ### Basic Sandbox Task Setup in Python Source: https://docs.browser-use.com/customize/sandbox/quickstart This snippet demonstrates the fundamental use of the @sandbox() decorator to wrap an asynchronous function for cloud execution. It initializes a Browser instance and an Agent to perform a task, which in this example is finding the top HN post. Dependencies include the browser_use library. ```python from browser_use import Browser, sandbox, ChatBrowserUse from browser_use.agent.service import Agent @sandbox() async def my_task(browser: Browser): agent = Agent(task="Find the top HN post", browser=browser, llm=ChatBrowserUse()) await agent.run() await my_task() ``` -------------------------------- ### Install with AI using npm Source: https://posthog.com/ This command initiates the AI-powered installation process for Product OS using npm. It's designed to be a quick and easy setup, taking approximately 90 seconds to complete. Ensure you have Node.js and npm installed before running this command. ```bash npx -y @posthog/wizard@latest ``` -------------------------------- ### Install browser-use Package Source: https://github.com/browser-use/browser-use/tree/main/examples/apps/news-use Installs or upgrades the browser-use Python package to the latest version using pip. Ensure you have Python and pip installed. ```shell pip install -U browser-use ``` -------------------------------- ### Install OpenLIT and Browser Use Source: https://docs.browser-use.com/llms-full.txt Installs the necessary libraries, OpenLIT and browser-use, using pip. This command is a prerequisite for enabling comprehensive observability with OpenLIT tracing. ```bash pip install openlit browser-use ``` -------------------------------- ### Install Browser-Use Runtime Source: https://docs.browser-use.com/llms-full.txt Installs the browser-use runtime using uvx. This command is essential for setting up the necessary browser components for Browser-Use to function. ```bash uvx browser-use install ``` -------------------------------- ### Install Browser-Use and Chromium using uv Source: https://docs.browser-use.com/llms-full.txt Installs the Browser-Use Python package and Chromium browser using the `uv` package manager. This involves creating a virtual environment, activating it, and then installing the necessary packages. ```bash pip install uv uv venv --python 3.12 ``` ```bash source .venv/bin/activate # On Windows use .venv\Scripts\activate ``` ```bash uv pip install browser-use uvx browser-use install ``` -------------------------------- ### Clone and Set Up Browser Use Repository (Bash) Source: https://docs.browser-use.com/llms-full.txt This Bash script outlines the initial steps for setting up the Browser Use project locally. It includes cloning the repository, navigating into the directory, and installing dependencies using uv. ```bash git clone https://github.com/browser-use/browser-use cd browser-use uv sync --all-extras --dev # or pip install -U git+https://github.com/browser-use/browser-use.git@main ``` -------------------------------- ### Perform Initial Login Source: https://github.com/browser-use/browser-use/tree/main/examples/apps/msg-use Executes the login script for the first-time setup. This will open a browser window prompting the user to scan a QR code for authentication. The session is saved for subsequent uses. ```python python login.py ``` -------------------------------- ### Basic Browser and Agent Setup Source: https://docs.browser-use.com/llms-full.txt Sets up a basic Browser instance with headless mode disabled and a specific window size, then initializes an Agent with a task and a ChatBrowserUse LLM. The async main function runs the agent's task. ```python from browser_use import Agent, Browser, ChatBrowserUse browser = Browser( headless=False, # Show browser window window_size={'width': 1000, 'height': 700}, # Set window size ) agent = Agent( task='Search for Browser Use', browser=browser, llm=ChatBrowserUse(), ) async def main(): await agent.run() ``` -------------------------------- ### Clone and Navigate to Ad Use Example Source: https://github.com/browser-use/browser-use/tree/main/examples/apps/ad-use Clones the browser-use repository from GitHub and changes the current directory to the ad-use example application folder, preparing the environment for running ad generation scripts. ```shell git clone https://github.com/browser-use/browser-use.git cd browser-use/examples/apps/ad-use ``` -------------------------------- ### Python Sandbox with Cloud Parameters Source: https://docs.browser-use.com/customize/sandbox/quickstart This example showcases how to configure the @sandbox() decorator with specific cloud parameters to control the execution environment. It allows specifying a cloud profile ID for authentication, a proxy country code for network routing, and a timeout for the browser session. The agent is used to visit a given URL. ```python @sandbox( cloud_profile_id='your-profile-id', cloud_proxy_country_code='us', cloud_timeout=60, ) async def task(browser: Browser, url: str): agent = Agent(task=f"Visit {url}", browser=browser, llm=ChatBrowserUse()) await agent.run() await task(url="https://example.com") ``` -------------------------------- ### Install Playwright and aiohttp Dependencies Source: https://docs.browser-use.com/llms-full.txt This bash command installs the necessary Python packages, `playwright` and `aiohttp`, required for advanced Playwright integration with Browser-Use. It also includes a suggestion to run `playwright install chromium` to download browser binaries. ```bash uv pip install playwright aiohttp ``` -------------------------------- ### Running Agent with Step Hooks (Python) Source: https://docs.browser-use.com/llms-full.txt Demonstrates how to initiate an agent run while providing custom callback functions for the start and end of each step. These hooks allow for custom logic execution at specific points in the agent's lifecycle. ```python await agent.run(on_step_start=..., on_step_end=...) ``` -------------------------------- ### Jupyter Notebook (.ipynb) Structure Example (Python) Source: https://docs.browser-use.com/llms-full.txt Illustrates the structure of a Jupyter notebook generated from a CodeAgent session. It includes a setup cell for browser initialization, cells for JavaScript code blocks as Python string variables, and subsequent cells for Python execution with outputs. ```Python # Cell 1: Setup import asyncio import json from browser_use import BrowserSession from browser_use.code_use import create_namespace browser = BrowserSession() await browser.start() namespace = create_namespace(browser) globals().update(namespace) # Cell 2: JavaScript variables extract_products = """(function(){ return Array.from(document.querySelectorAll('.product')).map(product => ({ name: product.querySelector('.name')?.textContent, price: product.querySelector('.price')?.textContent })); })()""" # Remaining cells: Python execution await navigate('https://example.com') ... products = await evaluate(extract_products) print(f"Found {len(products)} products") ``` -------------------------------- ### Create a Basic Agent with a Custom Tool in Python Source: https://docs.browser-use.com/llms-full.txt Demonstrates the basic setup for creating an agent with custom tools. It defines a simple 'ask_human' tool that prompts the user for input and returns the response. This requires the browser_use library. ```python from browser_use import Tools, ActionResult, Browser tools = Tools() @tools.action('Ask human for help with a question') def ask_human(question: str, browser: Browser) -> ActionResult: answer = input(f'{question} > ') return f'The human responded with: {answer}' agent = Agent( task='Ask human for help', llm=llm, tools=tools, ) ``` -------------------------------- ### Run Browser Use Examples (Bash) Source: https://docs.browser-use.com/llms-full.txt This Bash command demonstrates how to run the example Python scripts for the Browser Use project using the uv run command. This is useful for testing and understanding the library's functionality. ```bash uv run examples/simple.py ``` -------------------------------- ### Install Dependencies and Browser Playwright Source: https://github.com/browser-use/vibetest-use This code snippet outlines the necessary steps to install project dependencies using 'uv' and 'pip', and then installs the Playwright browser binaries for testing. Ensure you have Python and 'uv' installed. ```shell uv venv source .venv/bin/activate uv pip install -e . playwright install chromium --with-deps --no-shell ``` -------------------------------- ### Create Agent with Oracle Cloud Infrastructure (OCI) Model Source: https://docs.browser-use.com/llms-full.txt This example demonstrates using raw OCI generative AI models. It requires OCI configuration, model OCID, service endpoint, compartment ID, and authentication setup. ```bash # Required setup: # 1. Set up OCI configuration file at ~/.oci/config # 2. Have access to OCI Generative AI models in your tenancy # 3. Install the OCI Python SDK: pip install oci ``` ```python from browser_use import Agent, ChatOCIRaw # Initialize the OCI model llm = ChatOCIRaw( model_id="ocid1.generativeaimodel.oc1.us-chicago-1.amaaaaaask7dceya...", service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", compartment_id="ocid1.tenancy.oc1..aaaaaaaayeiis5uk2nuubznrekd...", provider="meta", # or "cohere" temperature=0.7, max_tokens=800, top_p=0.9, auth_type="API_KEY", auth_profile="DEFAULT" ) # Create agent with the model agent = Agent( task="Your task here", llm=llm ) ``` -------------------------------- ### Basic ChatLangchain with OpenAI and Browser Use Agent (Python) Source: https://github.com/browser-use/browser-use/blob/main/examples/models/langchain This example demonstrates how to initialize a Langchain OpenAI model, wrap it with ChatLangchain for browser-use compatibility, and then use it within a Browser Use Agent to perform a web search. It requires the 'langchain-openai' and 'browser-use' libraries. ```python from langchain_openai import ChatOpenAI from browser_use import Agent from .chat import ChatLangchain async def main(): """Basic example using ChatLangchain with OpenAI through LangChain.""" # Create a LangChain model (OpenAI) langchain_model = ChatOpenAI( model='gpt-4.1-mini', temperature=0.1, ) # Wrap it with ChatLangchain to make it compatible with browser-use llm = ChatLangchain(chat=langchain_model) agent = Agent( task="Go to google.com and search for 'browser automation with Python'", llm=llm, ) history = await agent.run() print(history.history) ``` -------------------------------- ### Start MCP Server Source: https://docs.browser-use.com/customize/integrations/mcp-server Start the MCP server in stdio mode to accept connections from compatible clients. ```APIDOC ## Start MCP Server ### Description Start the browser-use MCP server to enable AI assistants to control browser automation. ### Method CLI Command ### Endpoint N/A ### Parameters N/A ### Request Example ```bash uvx browser-use --mcp ``` ### Response N/A (Server starts and listens for connections) ``` -------------------------------- ### Clone OpenLIT Repository using Git Source: https://github.com/openlit/openlit This command clones the OpenLIT repository from GitHub. It's the first step to getting the project code locally. No specific inputs or outputs are detailed, but it requires Git to be installed. ```bash git clone git@github.com:openlit/openlit.git ``` -------------------------------- ### Browser Management: Get and Close Pages Source: https://docs.browser-use.com/llms-full.txt Demonstrates how to retrieve all open pages, get the current page, close a specific page, and stop the browser instance. Requires the 'browser' object to be initialized. ```python pages = await browser.get_pages() current = await browser.get_current_page() await browser.close_page(page) await browser.stop() ``` -------------------------------- ### Browser Use Development Helper Scripts (Bash) Source: https://docs.browser-use.com/llms-full.txt This collection of Bash commands provides helper scripts for common development tasks within the Browser Use project. It includes scripts for setup, linting, and running tests, ensuring consistency and ease of development. ```bash # Complete setup script - installs uv, creates a venv, and installs dependencies ./bin/setup.sh # Run all pre-commit hooks (formatting, linting, type checking) ./bin/lint.sh # Run the core test suite that's executed in CI ./bin/test.sh ``` -------------------------------- ### Initialize Browser Use LLM Source: https://docs.browser-use.com/llms-full.txt This Python snippet shows the basic initialization of the ChatBrowserUse LLM and an Agent. It requires the 'browser-use' library. This setup is used for tasks requiring optimized in-house model performance. ```python from browser_use import Agent, ChatBrowserUse # Initialize the model llm = ChatBrowserUse() # Create agent with the model agent = Agent( task="...", # Your task here llm=llm ) ``` -------------------------------- ### Install OpenLIT SDK using Pip Source: https://github.com/openlit/openlit This command installs the OpenLIT SDK using pip, the Python package installer. It's a prerequisite for integrating OpenLIT into Python applications. Requires pip to be available. ```bash pip install openlit ``` -------------------------------- ### Ollama LLM Integration with Browser Use Agent Source: https://docs.browser-use.com/supported-models Integrates the Ollama LLM with the Browser Use Agent. Requires Ollama to be installed and running, and a model to be pulled (e.g., 'llama3.1:8b'). Initializes ChatOllama with the specified model name. ```python from browser_use import Agent, ChatOllama llm = ChatOllama(model="llama3.1:8b") ``` -------------------------------- ### Select Fast LLM Models for Optimization (Python) Source: https://docs.browser-use.com/llms-full.txt Shows how to select fast LLM models for optimizing agent performance. Includes examples for Groq (Llama 4) and Google Gemini Flash, both known for their speed. ```python # Groq - Ultra-fast inference from browser_use import ChatGroq llm = ChatGroq(model='meta-llama/llama-4-maverick-17b-128e-instruct') # Google Gemini Flash - Optimized for speed from browser_use import ChatGoogle llm = ChatGoogle(model='gemini-flash-lite-latest') ``` -------------------------------- ### Python: Basic Sandbox Execution with LLM Source: https://docs.browser-use.com/llms-full.txt A basic example of using the `@sandbox` decorator to run a task with an LLM agent. It initializes an Agent with a task and a ChatBrowserUse LLM, then runs the agent. ```python @sandbox( cloud_profile_id='550e8400-e29b-41d4-a716-446655440000', cloud_proxy_country_code='us', cloud_timeout=60, on_browser_created=lambda data: print(f'Live: {data.live_url}'), ) async def task(browser: Browser): agent = Agent(task="your task", browser=browser, llm=ChatBrowserUse()) await agent.run() ``` -------------------------------- ### Install browser-use Package Source: https://docs.browser-use.com/customize/integrations/mcp-server Installs the 'browser-use' Python package using pip. This is a prerequisite for using the library and resolving 'MCP SDK is required' errors. ```bash uv pip install 'browser-use' ``` -------------------------------- ### Start browser-use MCP Server Source: https://docs.browser-use.com/customize/integrations/mcp-server Starts the browser-use MCP server in stdio mode, making browser automation capabilities available to compatible AI clients. This is the primary command to enable integration. ```shell uvx browser-use --mcp ``` -------------------------------- ### Run First Agent with OpenAI LLM Source: https://docs.browser-use.com/llms-full.txt This Python code initializes an agent to perform a task using OpenAI's language model. It requires the 'browser-use' and 'dotenv' libraries for setup and execution. The script runs an asynchronous main function to execute the agent's task. ```python from browser_use import Agent, ChatOpenAI from dotenv import load_dotenv import asyncio load_dotenv() async def main(): llm = ChatOpenAI(model="gpt-4.1-mini") task = "Find the number 1 post on Show HN" agent = Agent(task=task, llm=llm) await agent.run() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Google Gemini: Initialize ChatGoogle Agent Source: https://docs.browser-use.com/supported-models Initializes the ChatGoogle model (using Gemini) and creates an Agent. Requires the GOOGLE_API_KEY environment variable (previously GEMINI_API_KEY). ```python from browser_use import Agent, ChatGoogle from dotenv import load_dotenv # Read GOOGLE_API_KEY into env load_dotenv() # Initialize the model llm = ChatGoogle(model='gemini-flash-latest') # Create agent with the model agent = Agent( task="Your task here", llm=llm ) ``` -------------------------------- ### Clone and Navigate to News Monitor App Source: https://github.com/browser-use/browser-use/tree/main/examples/apps/news-use Clones the browser-use repository from GitHub and navigates into the examples/apps/news-use directory, where the news monitor script is located. ```shell git clone https://github.com/browser-use/browser-use.git cd browser-use/examples/apps/news-use ``` -------------------------------- ### Browser Core Settings Source: https://docs.browser-use.com/llms-full.txt Core settings for browser instances. ```APIDOC ## Browser Core Settings ### `cdp_url` - **Type**: string - **Description**: CDP URL for connecting to an existing browser instance (e.g., `"http://localhost:9222"`). ``` -------------------------------- ### Python: Example task to extract products from Flipkart Source: https://docs.browser-use.com/llms-full.txt An example demonstrating how to use the CodeAgent to extract product data from Flipkart, specifying the number of products to collect from different categories and save them to a CSV file. This showcases the agent's capability for large-scale data collection and targeted extraction. ```python import asyncio from browser_use.code_use import CodeAgent async def main(): task = """ Go to https://www.flipkart.com. Collect approximately 50 products from: 1. Books & Media - 15 products 2. Sports & Fitness - 15 products 3. Beauty & Personal Care - 10 products Save to products.csv """ agent = CodeAgent(task=task) await agent.run() asyncio.run(main()) ``` -------------------------------- ### Browser Use Cloud: Initialize ChatBrowserUse Agent Source: https://docs.browser-use.com/supported-models Initializes the optimized ChatBrowserUse model and creates an Agent for task execution. Requires the BROWSER_USE_API_KEY environment variable. ```python from browser_use import Agent, ChatBrowserUse # Initialize the model llm = ChatBrowserUse() # Create agent with the model agent = Agent( task="...", # Your task here llm=llm ) ``` -------------------------------- ### Azure OpenAI: Initialize ChatAzureOpenAI Agent Source: https://docs.browser-use.com/supported-models Initializes the ChatAzureOpenAI model and creates an Agent. Requires AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_API_KEY environment variables. ```python from browser_use import Agent, ChatAzureOpenAI from pydantic import SecretStr import os # Initialize the model llm = ChatAzureOpenAI( model="o4-mini", ) # Create agent with the model agent = Agent( task="...", # Your task here llm=llm ) ``` -------------------------------- ### Clone and Navigate Project Repository Source: https://github.com/browser-use/browser-use/tree/main/examples/apps/msg-use Clones the browser-use GitHub repository and navigates into the message scheduling application directory. ```shell git clone https://github.com/browser-use/browser-use.git cd browser-use/examples/apps/msg-use ``` -------------------------------- ### Google API Key Environment Variable Source: https://docs.browser-use.com/llms-full.txt This .env file example shows the required environment variable for authenticating with Google services. The GOOGLE_API_KEY needs to be provided for the ChatGoogle LLM to function correctly. ```bash GOOGLE_API_KEY= ``` -------------------------------- ### Configure API Keys in .env file Source: https://docs.browser-use.com/llms-full.txt Sets up the .env file to store API keys for various LLM providers, including Browser Use, Google, OpenAI, and Anthropic. This file is used by the application to authenticate with these services. Example keys are provided for each service. ```bash touch .env # On Windows, use `echo. > .env` ``` ```bash # add your key to .env file BROWSER_USE_API_KEY= # Get 10$ of free credits at https://cloud.browser-use.com/new-api-key ``` ```bash # add your key to .env file GOOGLE_API_KEY= # Get your free Gemini API key from https://aistudio.google.com/app/u/1/apikey?pli=1. ``` ```bash # add your key to .env file OPENAI_API_KEY= ``` ```bash # add your key to .env file ANTHROPIC_API_KEY= ``` -------------------------------- ### Programmatic Usage with MCP Client Source: https://docs.browser-use.com/customize/integrations/mcp-server Example of how to programmatically connect to and use the MCP server using the `mcp` Python library. ```APIDOC ## Programmatic Usage ### Description Connect to the MCP server programmatically using the `mcp` Python library to control browser automation. ### Method Python Script ### Endpoint N/A ### Parameters N/A (Code defines parameters) ### Request Example ```python import asyncio from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client async def use_browser_mcp(): # Connect to browser-use MCP server server_params = StdioServerParameters( command="uvx", args=["browser-use", "--mcp"] ) async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: await session.initialize() # Navigate to a website result = await session.call_tool( "browser_navigate", arguments={"url": "https://example.com"} ) print(result.content[0].text) # Get page state result = await session.call_tool( "browser_get_state", arguments={"include_screenshot": True} ) print("Page state retrieved!") asyncio.run(use_browser_mcp()) ``` ### Response Output depends on the executed tool calls. The example prints navigation results and confirmation of page state retrieval. ``` -------------------------------- ### Run News Monitor with Python Command-Line Arguments Source: https://docs.browser-use.com/llms-full.txt This section provides examples of how to run the news monitoring script ('news_monitor.py') using various command-line arguments. You can perform a one-time extraction, continuous monitoring, or specify an interval and URL. The script requires Python. ```bash # One-time extraction - Get the latest article and exit python news_monitor.py --once # Monitor Bloomberg continuously (default) python news_monitor.py # Monitor TechCrunch every 60 seconds python news_monitor.py --url https://techcrunch.com --interval 60 # Debug mode - See browser in action python news_monitor.py --once --debug ``` -------------------------------- ### Python Script (.py) Structure Example (Python) Source: https://docs.browser-use.com/llms-full.txt Provides the structure for a Python script generated from a CodeAgent session. This format is suitable for production deployment and version control, containing all necessary imports, JavaScript code as string variables, and executable Python code with proper indentation. ```Python # Generated from browser-use code-use session import asyncio import json from browser_use import BrowserSession from browser_use.code_use import create_namespace async def main(): # Initialize browser and namespace browser = BrowserSession() await browser.start() # Create namespace with all browser control functions namespace = create_namespace(browser) # Extract functions from namespace for direct access navigate = namespace["navigate"] click = namespace["click"] evaluate = namespace["evaluate"] # ... other functions # JavaScript Code Block: extract_products extract_products = """(function(){ return Array.from(document.querySelectorAll('.product')).map(product => ({ name: product.querySelector('.name')?.textContent, price: product.querySelector('.price')?.textContent })); })()""" # Cell 1 await navigate('https://example.com') # Cell 2 products = await evaluate(extract_products) print(f"Found {len(products)} products") await browser.stop() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Initialize and Run Agent (Python) Source: https://docs.browser-use.com/customize/agent/basics This Python code demonstrates how to initialize an Agent with a specific task and LLM, and then execute it asynchronously. It uses the `browser_use` library and requires specifying a task and an LLM, with an optional `max_steps` limit for execution. ```python from browser_use import Agent, ChatBrowserUse agent = Agent( task="Search for latest news about AI", llm=ChatBrowserUse(), ) async def main(): history = await agent.run(max_steps=100) ``` -------------------------------- ### Anthropic: Initialize ChatAnthropic Agent Source: https://docs.browser-use.com/supported-models Initializes the ChatAnthropic model (e.g., 'claude-sonnet-4-0') and creates an Agent. Requires the ANTHROPIC_API_KEY environment variable. ```python from browser_use import Agent, ChatAnthropic # Initialize the model llm = ChatAnthropic( model="claude-sonnet-4-0", ) # Create agent with the model agent = Agent( task="...", # Your task here llm=llm ) ``` -------------------------------- ### BrowserSession Management Source: https://docs.browser-use.com/llms-full.txt Manages the main browser session, allowing for starting, stopping, and creating new pages. ```APIDOC ## BrowserSession Management ### Description Manages the main browser session, allowing for starting, stopping, and creating new pages. ### Method (Implied asynchronous methods for a Python library) ### Endpoint N/A (Python library methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from browser_use import Browser browser = Browser() await browser.start() # Create a new page page = await browser.new_page("https://example.com") # Get all pages pages = await browser.get_pages() # Get the current page current = await browser.get_current_page() # Close a specific page await browser.close_page(page) # Stop the browser session await browser.stop() ``` ### Response #### Success Response (200) N/A (Python library methods return objects or None) #### Response Example N/A ``` -------------------------------- ### Set Gemini API Key Source: https://github.com/browser-use/browser-use/tree/main/examples/apps/msg-use Exports the Gemini API key as an environment variable, which is required for LLM authentication. The API key should be obtained from Google AI Studio. ```shell export GOOGLE_API_KEY='your-gemini-api-key-here' ``` -------------------------------- ### Initialize Browser Use with Disabled Instruments Source: https://docs.browser-use.com/llms-full.txt Initializes the Laminar SDK for browser use, specifically disabling the BROWSER_USE_SESSION instrument. This setup is for auto-instrumentation of browser usage. ```python from browser_use import Instruments Laminar.initialize(project_api_key="...", disabled_instruments={Instruments.BROWSER_USE_SESSION}) ``` -------------------------------- ### Create Agent with OpenAI Model Source: https://docs.browser-use.com/llms-full.txt This snippet shows how to create an agent using an OpenAI-compatible model. It requires an OpenAI API key to be set in the environment. ```bash # Required environment variables: OPENAI_API_KEY= ``` ```python from browser_use import Agent, ChatOpenAI # Initialize the model llm = ChatOpenAI( model="...", # Your model here base_url="...", # Your custom URL here ) # Create agent with the model agent = Agent( task="...", # Your task here llm=llm ) ``` -------------------------------- ### Create Agent with Ollama Model Source: https://docs.browser-use.com/llms-full.txt This snippet shows how to integrate with Ollama, a local LLM runner. It requires Ollama to be installed and running, and a model to be pulled (e.g., 'llama3.1:8b'). ```bash # 1. Install Ollama: https://github.com/ollama/ollama # 2. Run `ollama serve` to start the server # 3. In a new terminal, install the model you want to use: `ollama pull llama3.1:8b` ``` ```python from browser_use import Agent, ChatOllama llm = ChatOllama(model="llama3.1:8b") agent = Agent( task="Your task here", llm=llm ) ``` -------------------------------- ### OpenAI: Initialize ChatOpenAI Agent Source: https://docs.browser-use.com/supported-models Initializes the ChatOpenAI model (recommends 'o3' for accuracy) and creates an Agent. Requires the OPENAI_API_KEY environment variable. Supports custom URLs for OpenAI compatible models. ```python from browser_use import Agent, ChatOpenAI # Initialize the model llm = ChatOpenAI( model="o3", ) # Create agent with the model agent = Agent( task="...", # Your task here llm=llm ) ``` -------------------------------- ### Define Playwright Get Text Parameters Source: https://docs.browser-use.com/llms-full.txt Defines a Pydantic model for parameters used to retrieve text from a web page using Playwright selectors. It specifies the CSS selector for the target element. ```python from pydantic import BaseModel, Field class PlaywrightGetTextAction(BaseModel): """Parameters for getting text using Playwright selectors.""" selector: str = Field(..., description='CSS selector to get text from. Use "title" for page title.') ``` -------------------------------- ### Ollama REST API: Generate Response Source: https://github.com/ollama/ollama An example using `curl` to send a POST request to the Ollama API's `/api/generate` endpoint. It specifies the model and a prompt to get a text response. ```bash curl http://localhost:11434/api/generate -d '{ "model": "llama3.2", "prompt":"Why is the sky blue?" }' ``` -------------------------------- ### Python: Programmatic Browser Automation via MCP Source: https://docs.browser-use.com/llms-full.txt Demonstrates how to programmatically connect to the browser-use MCP server using Python's asyncio and mcp library. It shows how to initialize a session, navigate to a URL, and retrieve the page state. ```python import asyncio from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client async def use_browser_mcp(): # Connect to browser-use MCP server server_params = StdioServerParameters( command="uvx", args=["browser-use", "--mcp"] ) async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: await session.initialize() # Navigate to a website result = await session.call_tool( "browser_navigate", arguments={"url": "https://example.com"} ) print(result.content[0].text) # Get page state result = await session.call_tool( "browser_get_state", arguments={"include_screenshot": True} ) print("Page state retrieved!") asyncio.run(use_browser_mcp()) ``` -------------------------------- ### Self-Hosted OpenLIT with Docker (Bash) Source: https://docs.browser-use.com/llms-full.txt This Bash command shows how to run a self-hosted OpenLIT instance using Docker. It exposes the necessary ports for OTLP and the dashboard, allowing for on-premises data collection and visualization. ```bash # Using Docker docker run -d \ -p 4318:4318 \ -p 3000:3000 \ openlit/openlit:latest # Access dashboard at http://localhost:3000 ``` -------------------------------- ### Basic Vibetest Prompts Source: https://github.com/browser-use/vibetest-use Examples of basic prompts to initiate Vibetest using Browser Use agents. These prompts demonstrate how to specify the target website, run on localhost, and control agent count and headless mode. ```text > Vibetest my website with 5 agents: browser-use.com > Run vibetest on localhost:3000 > Run a headless vibetest on localhost:8080 with 10 agents ``` -------------------------------- ### Groq LLM Integration with Browser Use Agent Source: https://docs.browser-use.com/supported-models Integrates the Groq LLM with the Browser Use Agent. Requires the 'GROQ_API_KEY' environment variable and the 'browser-use' library. Initializes ChatGroq with a specific model and then creates an Agent with a defined task. ```python from browser_use import Agent, ChatGroq llm = ChatGroq(model="meta-llama/llama-4-maverick-17b-128e-instruct") agent = Agent( task="Your task here", llm=llm ) ``` -------------------------------- ### Start Chrome with Debug Port (Python) Source: https://docs.browser-use.com/llms-full.txt Launches a Chrome or Chromium browser instance with the remote debugging protocol enabled on a specified port. It handles finding the correct executable path and ensures the browser is ready for connection. ```python import asyncio import os import subprocess import tempfile import aiohttp async def start_chrome_with_debug_port(port: int = 9222): """ Start Chrome with remote debugging enabled. Returns the Chrome process. """ # Create temporary directory for Chrome user data user_data_dir = tempfile.mkdtemp(prefix='chrome_cdp_') # Chrome launch command chrome_paths = [ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', # macOS '/usr/bin/google-chrome', # Linux '/usr/bin/chromium-browser', # Linux Chromium 'chrome', # Windows/PATH 'chromium', # Generic ] chrome_exe = None for path in chrome_paths: if os.path.exists(path) or path in ['chrome', 'chromium']: try: # Test if executable works test_proc = await asyncio.create_subprocess_exec( path, '--version', stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) await test_proc.wait() chrome_exe = path break except Exception: continue if not chrome_exe: raise RuntimeError('❌ Chrome not found. Please install Chrome or Chromium.') # Chrome command arguments cmd = [ chrome_exe, f'--remote-debugging-port={port}', f'--user-data-dir={user_data_dir}', '--no-first-run', '--no-default-browser-check', '--disable-extensions', 'about:blank', # Start with blank page ] # Start Chrome process process = await asyncio.create_subprocess_exec(*cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # Wait for Chrome to start and CDP to be ready cdp_ready = False for _ in range(20): # 20 second timeout try: async with aiohttp.ClientSession() as session: aSync with session.get( f'http://localhost:{port}/json/version', timeout=aiohttp.ClientTimeout(total=1) ) as response: if response.status == 200: cdp_ready = True break except Exception: pass await asyncio.sleep(1) if not cdp_ready: process.terminate() raise RuntimeError('❌ Chrome failed to start with CDP') return process ``` -------------------------------- ### Browser Initialization with BrowserProfile Source: https://docs.browser-use.com/llms-full.txt Demonstrates how to initialize a Browser using a custom BrowserProfile for backward compatibility. This allows passing various browser configuration parameters through the profile object. ```python from browser_use import BrowserProfile profile = BrowserProfile(headless=False) browser = Browser(browser_profile=profile) ``` -------------------------------- ### Python: Agent Initialization with Custom Tools Source: https://docs.browser-use.com/llms-full.txt Illustrates how to initialize an `Agent` instance and pass a `Tools` object containing custom tools to it. This allows the agent to utilize the defined custom actions during its execution. ```python agent = Agent(task='...', llm=llm, tools=tools) ``` -------------------------------- ### Secure Azure OpenAI Setup with Browser-Use Source: https://docs.browser-use.com/llms-full.txt Configures Browser-Use with Azure OpenAI for enterprise-grade security, data privacy, and restricted browser access. It demonstrates how to set environment variables, define allowed domains, and filter sensitive data. ```python import asyncio import os from dotenv import load_dotenv load_dotenv() os.environ['ANONYMIZED_TELEMETRY'] = 'false' from browser_use import Agent, BrowserProfile, ChatAzureOpenAI # Azure OpenAI configuration api_key = os.getenv('AZURE_OPENAI_KEY') azure_endpoint = os.getenv('AZURE_OPENAI_ENDPOINT') llm = ChatAzureOpenAI(model='gpt-4.1-mini', api_key=api_key, azure_endpoint=azure_endpoint) # Secure browser configuration browser_profile = BrowserProfile( allowed_domains=['*google.com', 'browser-use.com'], enable_default_extensions=False ) # Sensitive data filtering sensitive_data = {'company_name': 'browser-use'} # Create secure agent agent = Agent( task='Find the founders of the sensitive company_name', llm=llm, browser_profile=browser_profile, sensitive_data=sensitive_data ) async def main(): await agent.run(max_steps=10) asyncio.run(main()) ``` -------------------------------- ### LLM-Powered Element Finding and Data Extraction Source: https://docs.browser-use.com/llms-full.txt Illustrates using an LLM (OpenAI's ChatOpenAI) to find elements via natural language prompts and extract structured data into Pydantic models. Requires 'browser_use.llm.openai' and 'pydantic' to be installed, and an API key. ```python from browser_use.llm.openai import ChatOpenAI from pydantic import BaseModel llm = ChatOpenAI(api_key="your-api-key") # Find elements using natural language button = await page.get_element_by_prompt("login button", llm=llm) await button.click() # Extract structured data class ProductInfo(BaseModel): name: str price: float product = await page.extract_content( "Extract product name and price", ProductInfo, llm=llm ) ``` -------------------------------- ### Programmatic Ad Generation Source: https://github.com/browser-use/browser-use/tree/main/examples/apps/ad-use Demonstrates how to programmatically generate ads using the `create_ad_from_landing_page` function within an async Python script. It specifies the landing page URL and controls debug mode. ```python import asyncio from ad_generator import create_ad_from_landing_page async def main(): results = await create_ad_from_landing_page( url="https://your-landing-page.com", debug=False ) print(f"Generated ads: {results}") asyncio.run(main()) ``` -------------------------------- ### Playwright Integration with Browser-Use Source: https://docs.browser-use.com/llms-full.txt This Python snippet outlines the setup for integrating Playwright with Browser-Use, allowing both tools to share a Chrome instance via CDP. It includes dependency checks for `aiohttp` and `playwright` and initializes global Playwright browser and page objects. ```python import asyncio import os import subprocess import sys import tempfile from pydantic import BaseModel, Field # Check for required dependencies first - before other imports try: import aiohttp # type: ignore from playwright.async_api import Browser, Page, async_playwright # type: ignore except ImportError as e: print(f'❌ Missing dependencies for this example: {e}') print('This example requires: playwright aiohttp') print('Install with: uv add playwright aiohttp') print('Also run: playwright install chromium') sys.exit(1) from browser_use import Agent, BrowserSession, ChatOpenAI, Tools from browser_use.agent.views import ActionResult # Global Playwright browser instance - shared between custom actions playwright_browser: Browser | None = None playwright_page: Page | None = None ``` -------------------------------- ### Running Ollama Server and Local Builds Source: https://github.com/ollama/ollama Instructions for running Ollama locally from a build. It involves starting the Ollama server using `./ollama serve` and then running a model in a separate shell. ```bash ./ollama serve ./ollama run llama3.2 ``` -------------------------------- ### Oracle Cloud Infrastructure (OCI) Raw LLM Integration Source: https://docs.browser-use.com/supported-models Integrates OCI's Generative AI service with the Browser Use Agent using ChatOCIRaw. Requires OCI configuration setup and specific model OCIDs. Supports API_KEY, INSTANCE_PRINCIPAL, and RESOURCE_PRINCIPAL authentication types. ```python from browser_use import Agent, ChatOCIRaw llm = ChatOCIRaw( model_id="ocid1.generativeaimodel.oc1.us-chicago-1.amaaaaaask7dceya...", service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", compartment_id="ocid1.tenancy.oc1..aaaaaaaayeiis5uk2nuubznrekd...", provider="meta", # or "cohere" temperature=0.7, max_tokens=800, top_p=0.9, auth_type="API_KEY", auth_profile="DEFAULT" ) agent = Agent( task="Your task here", llm=llm ) ``` -------------------------------- ### Add Comprehensive Tracing with Laminar SDK Source: https://lmnr.ai/ This example shows how to use the Laminar SDK to add comprehensive tracing to your agent. This allows for detailed monitoring and debugging of your AI agent's execution flow, including tool usage and structured output. It requires the Laminar SDK to be installed. ```python from laminar import trace @trace def my_agent_function(...): # Your agent logic here pass ``` -------------------------------- ### Qwen VL Max LLM Integration with Browser Use Agent Source: https://docs.browser-use.com/supported-models Integrates the Qwen VL Max LLM with the Browser Use Agent, enabling vision capabilities. Requires Alibaba Cloud API key and specifies a base URL for the service. Note: Other Qwen models may have issues with action schema formatting. ```python from browser_use import Agent, ChatOpenAI from dotenv import load_dotenv import os load_dotenv() api_key = os.getenv('ALIBABA_CLOUD') base_url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1' llm = ChatOpenAI(model='qwen-vl-max', api_key=api_key, base_url=base_url) agent = Agent( task="Your task here", llm=llm, use_vision=True ) ``` -------------------------------- ### AWS Bedrock: Initialize General ChatAWSBedrock Agent Source: https://docs.browser-use.com/supported-models Initializes a general ChatAWSBedrock client for any Bedrock-supported model and creates an Agent. Requires AWS credentials and the AWS region. ```python from browser_use import Agent, ChatAWSBedrock # Works with any Bedrock model (Anthropic, Meta, AI21, etc.) llm = ChatAWSBedrock( model="anthropic.claude-3-5-sonnet-20240620-v1:0", # or any Bedrock model aws_region="us-east-1", ) # Create agent with the model agent = Agent( task="Your task here", llm=llm ) ``` -------------------------------- ### Install Browser Use Agent Source: https://browser-use.com/posts/speed-matters This command installs or updates the Browser Use agent to version 0.8.0. Ensure you have 'uv' installed for package management. ```bash uv add browser-use==0.8.0 ``` -------------------------------- ### Configure Qwen LLM with Browser Use Source: https://docs.browser-use.com/llms-full.txt Sets up the Qwen-vl-max model for use with Browser Use. Requires an Alibaba Cloud API key and specifies the base URL for the compatible API. This configuration enables vision capabilities for the agent. ```python from browser_use import Agent, ChatOpenAI from dotenv import load_dotenv import os load_dotenv() # Get API key from https://modelstudio.console.alibabacloud.com/?tab=playground#/api-key api_key = os.getenv('ALIBABA_CLOUD') base_url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1' llm = ChatOpenAI(model='qwen-vl-max', api_key=api_key, base_url=base_url) agent = Agent( task="Your task here", llm=llm, use_vision=True ) ``` -------------------------------- ### AWS Bedrock: Initialize Anthropic Claude Convenience Class Source: https://docs.browser-use.com/supported-models Initializes a convenience ChatAnthropicBedrock class for Anthropic Claude models on AWS Bedrock and creates an Agent. Requires AWS credentials and the AWS region. ```python from browser_use import Agent, ChatAnthropicBedrock # Anthropic-specific class with Claude defaults llm = ChatAnthropicBedrock( model="anthropic.claude-3-5-sonnet-20240620-v1:0", aws_region="us-east-1", ) # Create agent with the model agent = Agent( task="Your task here", llm=llm ) ``` -------------------------------- ### Install Ollama via Shell Script (Linux) Source: https://github.com/ollama/ollama This command downloads and executes the official Ollama installation script for Linux systems. It ensures the latest version of Ollama is installed and configured. ```shell curl -fsSL https://ollama.com/install.sh | sh ``` -------------------------------- ### Create Agent with Anthropic Claude Model Source: https://docs.browser-use.com/llms-full.txt This example demonstrates initializing and using an Anthropic Claude model with the Browser Use agent. It requires the ANTHROPIC_API_KEY environment variable. ```bash # Required environment variables: ANTHROPIC_API_KEY= ``` ```python from browser_use import Agent, ChatAnthropic # Initialize the model llm = ChatAnthropic( model="claude-sonnet-4-0", ) # Create agent with the model agent = Agent( task="...", # Your task here llm=llm ) ``` -------------------------------- ### Mouse Operations: Clicks, Drags, and Scrolling Source: https://docs.browser-use.com/llms-full.txt Provides examples of controlling the mouse for various interactions, including clicking at specific coordinates, performing drag-and-drop actions, and scrolling the page. ```python mouse = await page.mouse # Click at coordinates await mouse.click(x=100, y=200) # Drag and drop await mouse.down() await mouse.move(x=500, y=600) await mouse.up() # Scroll await mouse.scroll(x=0, y=100, delta_y=-500) ```