User Agents

Web browsers and everyday web tech, explained

How to Build an Ai Agent That Controls Browsers Terminals and Desktop Apps

· 6 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 shows you how to build an AI agent that can operate a web browser, run terminal commands, and click through desktop applications—essentially automating tasks a human would do on a computer. You'll use open-source tools like Playwright for browser control, subprocess for terminal access, and pyautogui for desktop interaction, all orchestrated by a large language model (LLM) that decides which action to take next. No prior AI experience is required, but basic Python knowledge helps.

What You'll Need

  • Python 3.9 or newer installed on your machine
  • An OpenAI API key (or another LLM API like Anthropic or a local model via Ollama)
  • Pip package manager
  • A code editor (VS Code recommended)
  • Basic familiarity with command line and Python syntax
  • For desktop control: Windows, macOS, or Linux with accessibility permissions enabled

Step-by-Step

  1. Set up your project environment. Create a new folder and a virtual environment: mkdir ai-agent && cd ai-agent && python -m venv venv. Activate it (on Windows: venv\Scripts\activate; on macOS/Linux: source venv/bin/activate).
  2. Install the required libraries. Run pip install openai playwright pyautogui pillow. Then install the browser drivers with playwright install chromium.
  3. Set your API key. Store your LLM API key as an environment variable, e.g., export OPENAI_API_KEY='your-key-here' (or set it in your code, but be careful not to commit it).
  4. Create the main agent script. Make a file called agent.py. This will contain the core loop: get a task from the user, send it to the LLM, parse the response into an action, execute the action, and repeat until the task is done.
  5. Define the LLM interaction. Use the OpenAI SDK to send a system prompt that tells the model what actions are available (e.g., click, type, run_terminal, open_app) and ask it to return a JSON object with the action and parameters. For example: {"action": "click", "x": 100, "y": 200}.
  6. Implement browser control. Use Playwright's sync API to launch a browser and navigate. For example, to open a URL: browser.goto(url). To click an element, use page.click(selector). You can also use the mouse coordinates if you prefer.
  7. Implement terminal control. Use Python's subprocess module to run shell commands. For example: subprocess.run(command, shell=True). Capture output and send it back to the LLM so it can decide the next step.
  8. Implement desktop control. Use pyautogui to move the mouse, click, and type. For example: pyautogui.moveTo(x, y), pyautogui.click(), pyautogui.write('text'). To open an app, use subprocess.Popen(['open', '-a', 'Calculator'])` on macOS or subprocess.Popen(['notepad.exe']) on Windows.
  9. Create the main loop. In a while True loop, ask the user for a task (or read from a file), send it to the LLM, execute the returned action, and then ask the LLM if the task is complete. If not, continue.
  10. Add error handling. Wrap each action in a try-except block so that if an action fails (e.g., element not found), the agent can report the error back to the LLM and try a different approach.
  11. Test with a simple task. Run your agent and ask it to "Open Google and search for 'weather'" or "Open the terminal and run 'ls'." Debug any issues.

Common Mistakes

  • Not giving the LLM enough context. The model needs to know what it can do and what the current state is (e.g., current URL, terminal output). Always include that in the prompt.
  • Using absolute coordinates for clicks. Screen sizes and window positions vary. Prefer using CSS selectors or accessibility labels for browser elements, and for desktop, use image recognition or window titles.
  • Forgetting to grant accessibility permissions. On macOS, you need to allow your terminal or IDE to control the computer in System Settings > Privacy & Security > Accessibility. On Windows, you may need to run as administrator for some operations.
  • Hardcoding the API key in the script. This is a security risk. Always use environment variables or a config file that is gitignored.
  • Not handling infinite loops. The agent might keep repeating the same action. Add a max iteration count and a condition to break if no progress is made.

Tips

  • Use a structured output format. Ask the LLM to return JSON with fields like action, target, value, and done. This makes parsing reliable.
  • Incorporate a "screenshot" action. For desktop control, take a screenshot with pyautogui.screenshot() and send it to a vision-capable LLM (like GPT-4o) so it can see the screen.
  • Log every action. Print or save each action and its result to a file. This helps debugging and gives the LLM a history to reference.
  • Start with a narrow scope. Build the agent to handle one type of task (e.g., web browsing) before adding terminal and desktop.
  • Use a local LLM for privacy. If you're handling sensitive data, run a model like Llama 3 locally via Ollama to avoid sending data to the cloud.

Troubleshooting

  • Playwright browser doesn't launch. Run playwright install chromium again and ensure you have the required system dependencies (on Linux, run playwright install-deps).
  • pyautogui clicks don't work on macOS. Go to System Settings > Privacy & Security > Accessibility and enable your terminal or IDE. You may need to restart the app.
  • LLM returns invalid JSON. Add a fallback: if parsing fails, ask the model to correct itself by sending the error message back.
  • Agent gets stuck in a loop. Implement a step counter and if it exceeds a threshold, break and ask the user for a new instruction.
  • Terminal commands hang. Use subprocess.run(..., timeout=10) to avoid indefinite hangs, and capture stderr as well.
  • Desktop control doesn't see the right window. Use pyautogui.getWindowsWithTitle() to bring a specific window to front before clicking.

Frequently Asked Questions

Can this agent work with any website?

Yes, as long as the site is accessible via a standard browser, Playwright can interact with it. However, sites with heavy JavaScript or anti-bot measures may require extra handling like waiting for elements or using stealth plugins.

Do I need a powerful computer to run this?

For basic tasks, no. A regular laptop works. But if you use a local LLM, you'll need a decent GPU for fast responses. Cloud APIs are more efficient for most use cases.

Is it safe to let the agent run terminal commands?

It can be risky if the agent makes a mistake. Always run it in a sandboxed environment or with a restricted user account. Also, you can add a confirmation step before executing destructive commands.

How do I make the agent learn from mistakes?

You can implement a feedback loop: when an action fails, send the error message back to the LLM and ask it to try a different approach. Over time, you can also fine-tune the model on successful trajectories.

Can I use this to automate my own repetitive tasks?

Absolutely. That's the primary use case. You can create custom prompts for tasks like filling forms, extracting data, or running scheduled backups.

What if the LLM API costs too much?

You can use a cheaper model like GPT-4o-mini or a free local model. Also, you can reduce token usage by sending only relevant context (e.g., screenshots instead of full page HTML).