Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Merge Azure OpenAI into gradio_demo. Default uses regular OpenAI. Use Azure OpenAI by setting AZURE_ENDPOINT env variable or see gradio_demo.py comment.

wwwc698b407a6979
diff --git a/examples/ui/gradio_demo.py b/examples/ui/gradio_demo.py
index 6d05d48db..765a60412 100644
--- a/examples/ui/gradio_demo.py
+++ b/examples/ui/gradio_demo.py
@@ -1,3 +1,12 @@
+"""
+This script creates a Gradio interface to run browser tasks using OpenAI models.
+By default, it uses regular OpenAI. To use Azure OpenAI, set the AZURE_ENDPOINT environment variable:
+
+- AZURE_ENDPOINT: Your Azure OpenAI endpoint URL
+
+The script will automatically detect this variable and switch to using Azure OpenAI if it is set.
+"""
+
import asyncio
import os
from dataclasses import dataclass
@@ -12,6 +21,14 @@ from rich.text import Text
from browser_use import Agent
+# Conditionally import AzureChatOpenAI or ChatOpenAI based on the presence of the AZURE_ENDPOINT environment variable
+if os.getenv("AZURE_ENDPOINT"):
+ from langchain_openai import AzureChatOpenAI as ChatOpenAI # Use Azure if environment variable is set
+else:
+ from langchain_openai import ChatOpenAI # Use regular OpenAI otherwise
+
+from browser_use import Agent
+
load_dotenv()
@@ -49,26 +66,48 @@ def parse_agent_history(history_str: str) -> None:
async def run_browser_task(
- task: str,
- api_key: str,
- model: str = 'gpt-4o',
- headless: bool = True,
+ task: str,
+ api_key: str,
+ model: str = 'gpt-4',
+ headless: bool = True,
) -> str:
- if not api_key.strip():
- return 'Please provide an API key'
-
- os.environ['OPENAI_API_KEY'] = api_key
-
- try:
- agent = Agent(
- task=task,
- llm=ChatOpenAI(model='gpt-4o'),
- )
- result = await agent.run()
- # TODO: The result cloud be parsed better
- return result
- except Exception as e:
- return f'Error: {str(e)}'
+ if not api_key.strip():
+ return 'Please provide an API key'
+
+ azure_endpoint = os.getenv("AZURE_ENDPOINT")
+
+ if azure_endpoint:
+ os.environ['AZURE_API_KEY'] = api_key
+ os.environ['AZURE_ENDPOINT'] = azure_endpoint
+ os.environ['OPENAI_API_VERSION'] = '2024-08-01-preview' # Set the API version globally for Azure OpenAI
+
+ try:
+ agent = Agent(
+ task=task,
+ llm=ChatOpenAI(
+ model_name=model,
+ openai_api_key=api_key,
+ azure_endpoint=azure_endpoint,
+ deployment_name=model,
+ api_version='2024-08-01-preview' # Explicitly set the API version
+ ),
+ )
+ except Exception as e:
+ return f'Error: {str(e)}'
+ else:
+ os.environ['OPENAI_API_KEY'] = api_key
+
+ try:
+ agent = Agent(
+ task=task,
+ llm=ChatOpenAI(model=model),
+ )
+ except Exception as e:
+ return f'Error: {str(e)}'
+
+ result = await agent.run()
+ return result
+
def create_ui():
@@ -84,7 +123,7 @@ def create_ui():
lines=3,
)
model = gr.Dropdown(
- choices=['gpt-4', 'gpt-3.5-turbo'], label='Model', value='gpt-4'
+ choices=['gpt-4o', 'gpt-4', 'gpt-3.5-turbo'], # Added gpt-4o
)
headless = gr.Checkbox(label='Run Headless', value=True)
submit_btn = gr.Button('Run Task')
diff --git a/examples/ui/gradio_demo_azure_openai.py b/examples/ui/gradio_demo_azure_openai.py
deleted file mode 100644
index 9c3cf0e18..000000000
--- a/examples/ui/gradio_demo_azure_openai.py
+++ /dev/null
@@ -1,118 +0,0 @@
-import asyncio
-import os
-from dataclasses import dataclass
-from typing import List, Optional
-
-import gradio as gr
-from dotenv import load_dotenv
-from langchain_openai import AzureChatOpenAI # Updated import
-from rich.console import Console
-from rich.panel import Panel
-from rich.text import Text
-
-from browser_use import Agent
-
-load_dotenv()
-
-@dataclass
-class ActionResult:
- is_done: bool
- extracted_content: Optional[str]
- error: Optional[str]
- include_in_memory: bool
-
-
-@dataclass
-class AgentHistoryList:
- all_results: List[ActionResult]
- all_model_outputs: List[dict]
-
-
-def parse_agent_history(history_str: str) -> None:
- console = Console()
-
- # Split the content into sections based on ActionResult entries
- sections = history_str.split('ActionResult(')
-
- for i, section in enumerate(sections[1:], 1): # Skip first empty section
- # Extract relevant information
- content = ''
- if 'extracted_content=' in section:
- content = section.split('extracted_content=')[1].split(',')[0].strip("'")
-
- if content:
- header = Text(f'Step {i}', style='bold blue')
- panel = Panel(content, title=header, border_style='blue')
- console.print(panel)
- console.print()
-
-
-async def run_browser_task(
- task: str,
- api_key: str,
- endpoint: str,
- model: str = 'gpt-4o',
- headless: bool = True,
-) -> str:
- if not api_key.strip() or not endpoint.strip():
- return 'Please provide both API key and endpoint'
-
- # Set environment variables for Azure
- os.environ['AZURE_API_KEY'] = api_key
- os.environ['AZURE_ENDPOINT'] = endpoint
- os.environ['OPENAI_API_VERSION'] = '2024-08-01-preview' # Set the API version globally
-
- try:
- agent = Agent(
- task=task,
- llm=AzureChatOpenAI(
- model_name=model,
- openai_api_key=api_key,
- azure_endpoint=endpoint, # Corrected to use azure_endpoint instead of openai_api_base
- deployment_name=model, # Use deployment_name for Azure models
- api_version='2024-08-01-preview' # Explicitly set the API version here
- ),
- )
- result = await agent.run()
- # TODO: The result could be parsed better
- return result
- except Exception as e:
- return f'Error: {str(e)}'
-
-
-def create_ui():
- with gr.Blocks(title='Browser Use GUI') as interface:
- gr.Markdown('# Browser Use Task Automation')
-
- with gr.Row():
- with gr.Column():
- api_key = gr.Textbox(label='Azure OpenAI API Key', placeholder='sk-...', type='password')
- endpoint = gr.Textbox(label='Azure Endpoint', placeholder='https://<your-endpoint>.openai.azure.com/', type='text')
- task = gr.Textbox(
- label='Task Description',
- placeholder='E.g., Find flights from New York to London for next week',
- lines=3,
- )
- model = gr.Dropdown(
- choices=['gpt-4o', 'o1', 'gpt-4', 'gpt-3.5-turbo'], # Added gpt-4o and o1
- label='Model',
- value='gpt-4' # Default value can be gpt-4 or any other
- )
- headless = gr.Checkbox(label='Run Headless', value=True)
- submit_btn = gr.Button('Run Task')
-
- with gr.Column():
- output = gr.Textbox(label='Output', lines=10, interactive=False)
-
- submit_btn.click(
- fn=lambda *args: asyncio.run(run_browser_task(*args)),
- inputs=[task, api_key, endpoint, model, headless],
- outputs=output,
- )
-
- return interface
-
-
-if __name__ == '__main__':
- demo = create_ui()
- demo.launch()