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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
if __name__ == '__main__':
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify, send_from_directory
|
| 2 |
+
from flask_cors import CORS
|
| 3 |
+
import asyncio
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
from threading import Thread
|
| 7 |
+
import json
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
|
| 10 |
+
# Load environment variables
|
| 11 |
+
load_dotenv()
|
| 12 |
+
|
| 13 |
+
# Import browser-use components
|
| 14 |
+
try:
|
| 15 |
+
from langchain_openai import ChatOpenAI
|
| 16 |
+
from browser_use import Agent
|
| 17 |
+
except ImportError as e:
|
| 18 |
+
print(f"Import error: {e}")
|
| 19 |
+
print("Make sure to install browser-use and langchain-openai")
|
| 20 |
+
|
| 21 |
+
app = Flask(__name__, static_folder='static')
|
| 22 |
+
CORS(app) # Enable CORS for all routes
|
| 23 |
+
|
| 24 |
+
# Global variables for managing async operations
|
| 25 |
+
loop = None
|
| 26 |
+
thread = None
|
| 27 |
+
|
| 28 |
+
def start_background_loop(loop):
|
| 29 |
+
"""Start the asyncio event loop in a background thread"""
|
| 30 |
+
asyncio.set_event_loop(loop)
|
| 31 |
+
loop.run_forever()
|
| 32 |
+
|
| 33 |
+
def get_or_create_eventloop():
|
| 34 |
+
"""Get or create the asyncio event loop"""
|
| 35 |
+
global loop, thread
|
| 36 |
+
if loop is None:
|
| 37 |
+
loop = asyncio.new_event_loop()
|
| 38 |
+
thread = Thread(target=start_background_loop, args=(loop,))
|
| 39 |
+
thread.daemon = True
|
| 40 |
+
thread.start()
|
| 41 |
+
return loop
|
| 42 |
+
|
| 43 |
+
async def run_browser_task(task, model="gpt-4o-mini"):
|
| 44 |
+
"""Run a browser automation task using browser-use"""
|
| 45 |
+
try:
|
| 46 |
+
# Initialize the LLM
|
| 47 |
+
llm = ChatOpenAI(model=model, temperature=0.1)
|
| 48 |
+
|
| 49 |
+
# Create the agent
|
| 50 |
+
agent = Agent(task=task, llm=llm)
|
| 51 |
+
|
| 52 |
+
# Run the task
|
| 53 |
+
result = await agent.run()
|
| 54 |
+
|
| 55 |
+
return {
|
| 56 |
+
"success": True,
|
| 57 |
+
"result": str(result),
|
| 58 |
+
"task": task
|
| 59 |
+
}
|
| 60 |
+
except Exception as e:
|
| 61 |
+
return {
|
| 62 |
+
"success": False,
|
| 63 |
+
"error": str(e),
|
| 64 |
+
"task": task
|
| 65 |
+
}
|
| 66 |
|
| 67 |
@app.route('/')
|
| 68 |
+
def home():
|
| 69 |
+
"""Serve the HTML interface"""
|
| 70 |
+
return send_from_directory('static', 'index.html')
|
| 71 |
+
|
| 72 |
+
@app.route('/api')
|
| 73 |
+
def api_docs():
|
| 74 |
+
"""API documentation endpoint"""
|
| 75 |
+
return jsonify({
|
| 76 |
+
"message": "Browser-Use Server API",
|
| 77 |
+
"endpoints": {
|
| 78 |
+
"/": "Web interface",
|
| 79 |
+
"/api": "This API documentation",
|
| 80 |
+
"/health": "Health check",
|
| 81 |
+
"/run-task": "POST - Run a browser automation task",
|
| 82 |
+
"/status": "Get server status"
|
| 83 |
+
},
|
| 84 |
+
"usage": {
|
| 85 |
+
"run_task": {
|
| 86 |
+
"method": "POST",
|
| 87 |
+
"url": "/run-task",
|
| 88 |
+
"body": {
|
| 89 |
+
"task": "Description of the task to perform",
|
| 90 |
+
"model": "gpt-4o-mini (optional, default)"
|
| 91 |
+
},
|
| 92 |
+
"example": {
|
| 93 |
+
"task": "Go to google.com and search for 'Python programming'",
|
| 94 |
+
"model": "gpt-4o-mini"
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
})
|
| 99 |
+
|
| 100 |
+
@app.route('/health')
|
| 101 |
+
def health():
|
| 102 |
+
"""Health check endpoint"""
|
| 103 |
+
return jsonify({
|
| 104 |
+
"status": "healthy",
|
| 105 |
+
"service": "browser-use-server",
|
| 106 |
+
"version": "1.0.0"
|
| 107 |
+
})
|
| 108 |
+
|
| 109 |
+
@app.route('/status')
|
| 110 |
+
def status():
|
| 111 |
+
"""Get server status and configuration"""
|
| 112 |
+
return jsonify({
|
| 113 |
+
"status": "running",
|
| 114 |
+
"environment": {
|
| 115 |
+
"python_version": sys.version,
|
| 116 |
+
"has_openai_key": bool(os.getenv("OPENAI_API_KEY")),
|
| 117 |
+
"has_anthropic_key": bool(os.getenv("ANTHROPIC_API_KEY"))
|
| 118 |
+
},
|
| 119 |
+
"supported_models": [
|
| 120 |
+
"gpt-4o",
|
| 121 |
+
"gpt-4o-mini",
|
| 122 |
+
"gpt-4-turbo",
|
| 123 |
+
"claude-3-sonnet-20240229",
|
| 124 |
+
"claude-3-haiku-20240307"
|
| 125 |
+
]
|
| 126 |
+
})
|
| 127 |
+
|
| 128 |
+
@app.route('/run-task', methods=['POST'])
|
| 129 |
+
def run_task():
|
| 130 |
+
"""Run a browser automation task"""
|
| 131 |
+
try:
|
| 132 |
+
# Get request data
|
| 133 |
+
data = request.get_json()
|
| 134 |
+
|
| 135 |
+
if not data or 'task' not in data:
|
| 136 |
+
return jsonify({
|
| 137 |
+
"success": False,
|
| 138 |
+
"error": "Missing 'task' in request body"
|
| 139 |
+
}), 400
|
| 140 |
+
|
| 141 |
+
task = data['task']
|
| 142 |
+
model = data.get('model', 'gpt-4o-mini')
|
| 143 |
+
|
| 144 |
+
# Validate API keys
|
| 145 |
+
if not os.getenv("OPENAI_API_KEY") and not os.getenv("ANTHROPIC_API_KEY"):
|
| 146 |
+
return jsonify({
|
| 147 |
+
"success": False,
|
| 148 |
+
"error": "No API keys configured. Please set OPENAI_API_KEY or ANTHROPIC_API_KEY environment variable."
|
| 149 |
+
}), 500
|
| 150 |
+
|
| 151 |
+
# Get the event loop
|
| 152 |
+
loop = get_or_create_eventloop()
|
| 153 |
+
|
| 154 |
+
# Run the task asynchronously
|
| 155 |
+
future = asyncio.run_coroutine_threadsafe(
|
| 156 |
+
run_browser_task(task, model),
|
| 157 |
+
loop
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# Wait for the result (with timeout)
|
| 161 |
+
try:
|
| 162 |
+
result = future.result(timeout=300) # 5 minute timeout
|
| 163 |
+
return jsonify(result)
|
| 164 |
+
except asyncio.TimeoutError:
|
| 165 |
+
return jsonify({
|
| 166 |
+
"success": False,
|
| 167 |
+
"error": "Task timed out after 5 minutes"
|
| 168 |
+
}), 408
|
| 169 |
+
|
| 170 |
+
except Exception as e:
|
| 171 |
+
return jsonify({
|
| 172 |
+
"success": False,
|
| 173 |
+
"error": f"Server error: {str(e)}"
|
| 174 |
+
}), 500
|
| 175 |
|
| 176 |
if __name__ == '__main__':
|
| 177 |
+
print("Starting Browser-Use Server...")
|
| 178 |
+
print("Make sure you have set your API keys:")
|
| 179 |
+
print("- OPENAI_API_KEY for OpenAI models")
|
| 180 |
+
print("- ANTHROPIC_API_KEY for Anthropic models")
|
| 181 |
+
|
| 182 |
+
# Run the Flask app
|
| 183 |
+
app.run(host='0.0.0.0', port=7860, debug=False)
|
| 184 |
+
|