Build Custom AI Demos with Browser Automation
In this article
Building custom AI demos with browser automation allows you to showcase how a language model or agent interacts with real-world web interfaces in real-time. By combining a headless browser with an LLM, you can create a system where the AI observes the DOM, decides on an action, and executes clicks or keystrokes to complete a specific task, providing a tangible proof-of-concept for autonomous web agents.
What You'll Need
- Node.js or Python: The primary runtime for your automation scripts.
- Browser Automation Framework: Playwright, Puppeteer, or Selenium (Playwright is recommended for its auto-waiting and modern API).
- LLM API Key: Access to a model capable of tool use or function calling (e.g., OpenAI GPT-4o or Anthropic Claude 3.5 Sonnet).
- Code Editor: Visual Studio Code or a similar IDE.
- Basic Knowledge of HTML/CSS: To understand how to identify elements via selectors.
Step-by-Step
- Initialize Your Project: Create a new directory and initialize your environment. If using Node.js, run
npm init -yand install Playwright usingnpm install playwright. Runnpx playwright installto download the necessary browser binaries. - Set Up the Browser Instance: Write a script to launch a browser. For a demo, it is often better to launch in "headed" mode (
headless: false) so viewers can see the AI interacting with the page. Set a slow-motion delay (slowMo: 100) to make the movements human-readable. - Implement the DOM Parser: The AI cannot "see" the browser directly; it needs a text representation of the page. Create a function that extracts the current page content. To avoid hitting token limits, do not send the entire HTML. Instead, extract only interactive elements like buttons, inputs, and links, along with their IDs, roles, and labels.
- Define the Action Schema: Create a set of tools the AI can call. These should be structured as JSON functions. Common actions include
click(selector),type(selector, text),navigate(url), andread_page(). - Build the Control Loop: Implement a "Observe-Think-Act" loop.
- Observe: The script captures the current state of the page and the current URL.
- Think: This state is sent to the LLM along with the user's goal. The LLM returns the next tool call.
- Act: The automation framework executes the tool call (e.g., clicking a button).
- Handle Dynamic Content: Use "wait for selector" or "wait for load state" commands between actions. Since web pages load asynchronously, the AI may try to click an element before it exists. Ensuring the page is stable before the next observation is critical.
- Create a User Interface for the Demo: Instead of running the demo purely in a terminal, build a simple frontend (using Streamlit or a basic React app) where users can enter a prompt and watch the browser window execute the steps in a side-by-side view.
Common Mistakes
- Sending Full HTML: Passing the entire DOM to an LLM consumes excessive tokens and introduces noise, which often leads to the AI hallucinating selectors.
- Hard-coding Selectors: Relying on absolute XPaths (e.g.,
/html/body/div[1]/div[2]/button) makes the demo fragile. If the site changes slightly, the demo breaks. Use ARIA labels or text-based selectors. - Ignoring Rate Limits: Rapidly looping requests to an LLM API can trigger rate limits. Implement a small delay or a confirmation step between actions.
- Lack of Error Handling: Assuming every click will succeed. If an element is obscured by a popup or a cookie banner, the script will crash without a try-catch block.
Tips
- Use Accessibility Trees: Instead of raw HTML, use the browser's accessibility tree. This provides a cleaner representation of the page that is specifically designed for screen readers and is highly compatible with LLM reasoning.
- Implement a "Human-in-the-Loop" Toggle: For complex demos, add a feature where the AI pauses and asks for confirmation before performing a critical action, such as submitting a form.
- Visual Markers: When the AI decides to click an element, use JavaScript to highlight that element with a red border in the browser before clicking. This makes the demo much more impressive and understandable for the audience.
- Session Persistence: Use browser contexts to save cookies and session data. This prevents the AI from having to log in every time the demo restarts.
Troubleshooting
- AI cannot find the element: Check if the element is inside an iframe or a Shadow DOM. Standard selectors cannot reach these; you must first switch the browser context to the iframe.
- Browser is detected as a bot: Some sites block automation. Try using
playwright-stealthor adjusting the User-Agent string to mimic a standard Chrome browser. - Infinite Loops: If the AI keeps clicking the same button without progress, implement a "max steps" counter (e.g., 10 steps) that terminates the process and reports a failure.
- Slow Response Times: If the LLM is taking too long to respond, try a smaller, faster model for simple navigation tasks and reserve the larger model for complex reasoning.
Frequently Asked Questions
Which is better: Playwright or Selenium?
Playwright is generally preferred for AI demos because it has built-in auto-waiting, better support for modern web frameworks, and a more intuitive API for handling asynchronous events.
How do I handle CAPTCHAs during a demo?
CAPTCHAs are designed to stop automation. For demos, it is best to use a staging environment where CAPTCHAs are disabled or use pre-authenticated session cookies to bypass the login screen.
Can I run this in a cloud environment?
Yes, but you will need to run the browser in headless mode and use a VNC server or a service like Browserless.io if you want to stream the visual output to a user.
How do I prevent the AI from getting lost on a page?
Provide the AI with a "breadcrumb" or a history of its previous actions in the prompt. This prevents it from repeating the same mistake and helps it realize when it has reached a dead end.
Do I need a GPU to run the browser automation?
No, browser automation is CPU and RAM intensive, not GPU intensive. The heavy lifting (the reasoning) happens on the LLM provider's servers via API.