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
Example to run agent with fast api and pause / stop run
magmuellere02b31c76b56
diff --git a/examples/fastapi/README.md b/examples/fastapi/README.mdnew file mode 100644index 000000000..60c372051--- /dev/null+++ b/examples/fastapi/README.md@@ -0,0 +1,34 @@+# FastAPI Browser Agent Example++This example demonstrates how to create a web interface for controlling a Browser Agent using FastAPI.++## Requirements++```bash+uv pip install fastapi uvicorn sse-starlette langchain-openai+```++## Running the Example++1. Navigate to the fastapi example directory:+```bash+cd examples/fastapi+```++2. Run the FastAPI application:+```bash+python main.py+```++3. Open your web browser and navigate to `http://localhost:8000`+++## API Endpoints++- `GET /` - Serves the web interface+- `POST /agent/run` - Creates and runs an agent with the specified task+- `POST /agent/pause` - Pauses the current agent+- `POST /agent/resume` - Resumes the paused agent+- `POST /agent/stop` - Stops the current agent+- `GET /agent/status` - Gets the current status of the agent+- `GET /logs` - Server-sent events endpoint for real-time logs\ No newline at end of filediff --git a/examples/fastapi/main.py b/examples/fastapi/main.pynew file mode 100644index 000000000..23241cbd1--- /dev/null+++ b/examples/fastapi/main.py@@ -0,0 +1,179 @@+import asyncio+import logging+import os+from queue import Queue+from threading import Lock+from typing import Optional++from fastapi import FastAPI, HTTPException+from fastapi.middleware.cors import CORSMiddleware+from fastapi.responses import FileResponse, JSONResponse+from fastapi.staticfiles import StaticFiles+from langchain_openai import ChatOpenAI+from pydantic import BaseModel+from sse_starlette.sse import EventSourceResponse++from browser_use import Agent++# Configure logging+logging.basicConfig(level=logging.INFO)+logger = logging.getLogger(__name__)++# Create a queue for log messages+log_queue = Queue()+log_lock = Lock()+++class LogHandler(logging.Handler):+ def emit(self, record):+ log_entry = self.format(record)+ with log_lock:+ log_queue.put(log_entry)+++# Add custom handler to the root logger+root_logger = logging.getLogger('browser_use')+root_logger.addHandler(LogHandler())++app = FastAPI()++# Enable CORS+app.add_middleware(+ CORSMiddleware,+ allow_origins=['*'], # Allows all origins+ allow_credentials=True,+ allow_methods=['*'], # Allows all methods+ allow_headers=['*'], # Allows all headers+)++# Create static directory if it doesn't exist+STATIC_DIR = os.path.join(os.path.dirname(__file__), 'static')+os.makedirs(STATIC_DIR, exist_ok=True)++# Serve static files+app.mount('/static', StaticFiles(directory=STATIC_DIR), name='static')+++class TaskRequest(BaseModel):+ task: str+++class AgentManager:+ def __init__(self):+ self.agent: Optional[Agent] = None+ self.task: Optional[str] = None+ self._running = False++ def create_agent(self, task: str):+ llm = ChatOpenAI(model='gpt-4o')+ self.agent = Agent(task=task, llm=llm)+ self.task = task+ self._running = False++ def get_agent(self) -> Agent:+ if not self.agent:+ raise ValueError('Agent not initialized')+ return self.agent++ @property+ def is_running(self):+ return self._running++ @is_running.setter+ def is_running(self, value: bool):+ self._running = value+++# Create a singleton instance+agent_manager = AgentManager()++[email protected]('/')+async def read_root():+ return FileResponse(os.path.join(STATIC_DIR, 'index.html'))++[email protected]('/agent/run')+async def run_agent(request: TaskRequest):+ try:+ # Create new agent if task is different or agent doesn't exist+ if not agent_manager.agent or agent_manager.task != request.task:+ agent_manager.create_agent(request.task)++ agent = agent_manager.get_agent()+ agent_manager.is_running = True++ # Run in background task to not block+ asyncio.create_task(agent.run())+ return {'status': 'running', 'task': request.task}+ except Exception as e:+ raise HTTPException(status_code=400, detail=str(e))++[email protected]('/agent/pause')+async def pause_agent():+ try:+ agent = agent_manager.get_agent()+ agent.pause()+ return {'status': 'paused'}+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e))++[email protected]('/agent/resume')+async def resume_agent():+ try:+ agent = agent_manager.get_agent()+ agent.resume()+ return {'status': 'resumed'}+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e))++[email protected]('/agent/stop')+async def stop_agent():+ try:+ agent = agent_manager.get_agent()+ agent.stop()+ agent_manager.is_running = False+ return {'status': 'stopped'}+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e))++[email protected]('/agent/status')+async def get_status():+ if not agent_manager.agent:+ return {'status': 'not_created'}++ agent = agent_manager.get_agent()+ if agent._stopped:+ status = 'stopped'+ elif agent._paused:+ status = 'paused'+ elif agent_manager.is_running:+ status = 'running'+ else:+ status = 'ready'++ return {'status': status, 'task': agent_manager.task}++[email protected]('/logs')+async def event_stream():+ async def generate():+ while True:+ if not log_queue.empty():+ with log_lock:+ while not log_queue.empty():+ log_entry = log_queue.get()+ yield {'event': 'log', 'data': log_entry}+ await asyncio.sleep(0.1)++ return EventSourceResponse(generate())+++if __name__ == '__main__':+ import uvicorn++ uvicorn.run(app, host='0.0.0.0', port=8000)diff --git a/examples/fastapi/static/index.html b/examples/fastapi/static/index.htmlnew file mode 100644index 000000000..3191734bc--- /dev/null+++ b/examples/fastapi/static/index.html@@ -0,0 +1,224 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Browser Agent Controller</title>+ <style>+ body {+ font-family: Arial, sans-serif;+ max-width: 800px;+ margin: 0 auto;+ padding: 20px;+ background-color: #f5f5f5;+ }+ .container {+ background-color: white;+ padding: 20px;+ border-radius: 8px;+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);+ }+ .control-panel {+ display: grid;+ gap: 10px;+ margin-top: 20px;+ }+ button {+ padding: 10px;+ border: none;+ border-radius: 4px;+ background-color: #007bff;+ color: white;+ cursor: pointer;+ transition: background-color 0.3s;+ }+ button:disabled {+ background-color: #cccccc;+ cursor: not-allowed;+ }+ button:hover:not(:disabled) {+ background-color: #0056b3;+ }+ #status {+ margin-top: 20px;+ padding: 10px;+ border-radius: 4px;+ }+ .status-running { background-color: #d4edda; color: #155724; }+ .status-paused { background-color: #fff3cd; color: #856404; }+ .status-stopped { background-color: #f8d7da; color: #721c24; }+ .status-not-created { background-color: #e2e3e5; color: #383d41; }+ .status-ready { background-color: #cce5ff; color: #004085; }+ textarea {+ width: 100%;+ padding: 10px;+ margin-bottom: 10px;+ border: 1px solid #ddd;+ border-radius: 4px;+ resize: vertical;+ }+ #logContainer {+ margin-top: 20px;+ padding: 10px;+ background-color: #f8f9fa;+ border-radius: 4px;+ border: 1px solid #ddd;+ height: 300px;+ overflow-y: auto;+ font-family: monospace;+ font-size: 14px;+ white-space: pre-wrap;+ }+ .log-entry {+ margin: 2px 0;+ padding: 2px 5px;+ }+ .button-group {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 10px;+ }+ </style>+</head>+<body>+ <div class="container">+ <h1>Browser Agent Controller</h1>++ <div class="control-panel">+ <textarea id="taskInput" rows="3" placeholder="Enter your task here..."></textarea>+ <div class="button-group">+ <button id="runBtn" onclick="runAgent()">Run Agent</button>+ <button id="pauseBtn" onclick="pauseAgent()" disabled>Pause</button>+ <button id="resumeBtn" onclick="resumeAgent()" disabled>Resume</button>+ <button id="stopBtn" onclick="stopAgent()" disabled>Stop</button>+ </div>+ </div>++ <div id="status" class="status-not-created">+ Status: Not Created+ </div>++ <div id="logContainer">+ <div id="logs"></div>+ </div>+ </div>++ <script>+ let statusCheckInterval;+ let eventSource;++ function setupLogging() {+ if (eventSource) {+ eventSource.close();+ }++ eventSource = new EventSource('/logs');+ const logsDiv = document.getElementById('logs');++ eventSource.addEventListener('log', function(event) {+ const logEntry = document.createElement('div');+ logEntry.className = 'log-entry';+ logEntry.textContent = event.data;+ logsDiv.appendChild(logEntry);+ logsDiv.scrollTop = logsDiv.scrollHeight;+ });++ eventSource.onerror = function(error) {+ console.error('EventSource failed:', error);+ eventSource.close();+ setTimeout(setupLogging, 5000); // Try to reconnect after 5 seconds+ };+ }++ async function runAgent() {+ const task = document.getElementById('taskInput').value;+ if (!task) {+ alert('Please enter a task');+ return;+ }++ try {+ const response = await fetch('/agent/run', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ task }),+ });++ if (response.ok) {+ startStatusCheck();+ document.getElementById('taskInput').disabled = true;+ }+ } catch (error) {+ console.error('Error:', error);+ alert('Failed to run agent');+ }+ }++ async function pauseAgent() {+ try {+ await fetch('/agent/pause', { method: 'POST' });+ } catch (error) {+ console.error('Error:', error);+ alert('Failed to pause agent');+ }+ }++ async function resumeAgent() {+ try {+ await fetch('/agent/resume', { method: 'POST' });+ } catch (error) {+ console.error('Error:', error);+ alert('Failed to resume agent');+ }+ }++ async function stopAgent() {+ try {+ await fetch('/agent/stop', { method: 'POST' });+ document.getElementById('taskInput').disabled = false;+ } catch (error) {+ console.error('Error:', error);+ alert('Failed to stop agent');+ }+ }++ async function checkStatus() {+ try {+ const response = await fetch('/agent/status');+ const data = await response.json();++ const statusDiv = document.getElementById('status');+ statusDiv.className = `status-${data.status}`;+ statusDiv.textContent = `Status: ${data.status.charAt(0).toUpperCase() + data.status.slice(1)}`;++ // Update buttons based on status+ document.getElementById('runBtn').disabled = data.status === 'running';+ document.getElementById('pauseBtn').disabled = data.status !== 'running';+ document.getElementById('resumeBtn').disabled = data.status !== 'paused';+ document.getElementById('stopBtn').disabled = data.status === 'stopped' || data.status === 'not_created';++ if (data.task) {+ statusDiv.textContent += `\nTask: ${data.task}`;+ }+ } catch (error) {+ console.error('Error checking status:', error);+ }+ }++ function startStatusCheck() {+ // Check status immediately+ checkStatus();+ // Then check every 2 seconds+ if (!statusCheckInterval) {+ statusCheckInterval = setInterval(checkStatus, 2000);+ }+ }++ // Initial setup+ setupLogging();+ checkStatus();+ </script>+</body>+</html>\ No newline at end of file