User Agents

Web browsers and everyday web tech, explained

Deploy an AI Agent with Browser Automation Skills

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks you through deploying an AI agent that can control a web browser to perform tasks like filling forms, clicking buttons, and extracting data. You'll end up with a working agent that runs on your own machine or a server, using open-source tools. No prior AI experience is needed, but basic familiarity with the command line and Python is helpful.

What You'll Need

  • A computer with internet access (Windows, macOS, or Linux).
  • Python 3.9 or newer installed.
  • A code editor (like VS Code) and a terminal.
  • An OpenAI API key (or another LLM provider) — you'll sign up for one.
  • Git installed (optional but recommended).

Step-by-Step

  1. Set up a Python virtual environment. Open your terminal and run: python -m venv agent-env. Activate it with source agent-env/bin/activate on macOS/Linux or agent-env\Scripts\activate on Windows.
  2. Install the core libraries. Run: pip install playwright openai langchain langchain-openai. Playwright is the browser automation library; LangChain helps orchestrate the AI logic.
  3. Install the browser binary. Run playwright install chromium. This downloads a headless Chromium browser that the agent will control.
  4. Get your API key. Go to the OpenAI website, create an account, and generate an API key. Store it as an environment variable: export OPENAI_API_KEY="your-key-here" (on Windows use set instead of export).
  5. Create a simple agent script. Make a file called agent.py with the following content:
    from langchain.agents import AgentExecutor, create_react_agent
    from langchain.tools import Tool
    from langchain_openai import ChatOpenAI
    from playwright.sync_api import sync_playwright
    
    def browse(url: str) -> str:
        with sync_playwright() as p:
            browser = p.chromium.launch()
            page = browser.new_page()
            page.goto(url)
            text = page.inner_text('body')
            browser.close()
            return text[:1000]
    
    tools = [Tool(name="browse", func=browse, description="Open a URL and return page text")]
    llm = ChatOpenAI(model="gpt-4o", temperature=0)
    agent = create_react_agent(llm, tools, prompt="You are a helpful assistant. Use the browse tool to answer questions.")
    executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
    
    if __name__ == "__main__":
        question = input("Ask something: ")
        print(executor.run(question))
        
  6. Test the agent. Run python agent.py. Ask it "What is the title of example.com?" and it should use the browser tool to fetch the page and answer.
  7. Add interaction skills. Extend the browse function to handle clicks and form fills. For example, add a parameter for a CSS selector and action. Modify the tool description to mention it can click elements.
  8. Handle authentication. If the agent needs to log in, use Playwright's storage state. First, run a script to log in manually and save the session: context.storage_state(path="state.json"). Then in your agent, load it with browser.new_context(storage_state="state.json").
  9. Deploy to a server. Once your script works locally, copy it to a cloud server (like a VPS). Install Python and the dependencies there, and run the script with nohup python agent.py & to keep it running after you log out.
  10. Expose it as an API (optional). Use FastAPI to wrap your agent in a REST endpoint. Install fastapi uvicorn, create a route that accepts a question and returns the answer, then run uvicorn api:app --host 0.0.0.0 --port 8000.

Common Mistakes

  • Not activating the virtual environment — you'll get 'module not found' errors even after installing packages.
  • Forgetting to install the browser binary — Playwright needs a separate download; using it without will fail.
  • Hardcoding the API key — it's a security risk. Always use environment variables or a secrets manager.
  • Using a model that can't handle tool calls — older models like GPT-3 may not follow the ReAct pattern properly. Stick with GPT-4 or newer.
  • Ignoring rate limits — if you make many calls, you'll hit API limits. Add retry logic or use a queue.

Tips

  • Start with a narrow task (like fetching a single page) before building complex multi-step flows.
  • Log every action the agent takes. Playwright can record videos or screenshots — use page.screenshot(path="shot.png") to debug.
  • Use a headless browser in production to save resources, but keep headed mode for debugging.
  • For dynamic sites, add wait conditions like page.wait_for_selector(".result") instead of fixed sleeps.
  • Break long tasks into smaller, reusable functions — the agent will call them more reliably.

Troubleshooting

  • Agent doesn't call the tool: Check your prompt — be explicit about when to use the browse tool. Also ensure the tool description is clear.
  • Playwright 'Browser closed' error: Make sure you close the browser in a finally block or use a context manager. Also, avoid reusing a closed browser.
  • API key errors: Double-check that the key is set in the environment and has credits. Test with a simple API call using curl.
  • Slow performance: The agent may be making too many round trips. Cache page content locally, or use a faster model like GPT-4o-mini for simple tasks.
  • Site blocks the browser: Some sites detect headless browsers. Try using a real user-agent string or add --disable-blink-features=AutomationControlled to launch args.

Frequently Asked Questions

Can I use a free LLM instead of OpenAI?

Yes, you can swap the model to a free one like Llama 3 via Ollama, but you'll need to adjust the LangChain integration. The process is similar.

Is this safe to run on any website?

Only on sites you have permission to automate. Respect robots.txt and terms of service. Avoid entering personal data on untrusted sites.

How do I make the agent click a button?

Extend the browse tool to accept a selector and an action like 'click'. In Playwright, use page.click(selector).

Can the agent handle CAPTCHAs?

No, and you shouldn't try to bypass them. Design your agent to work on sites that don't require CAPTCHA, or handle them manually.

What if the page loads slowly?

Use page.wait_for_load_state("networkidle") or wait for a specific element to appear before extracting text.

Do I need a GPU?

No, the LLM runs in the cloud. Your machine only runs the browser and the orchestration code, which is lightweight.