async def main():
agent = Agent(
task="search 'openai' on google.com and describe the result page.",
llm=llm,
use_vision=True,
browser=browser,
save_conversation_path="logs/conversation.json",
)
result = await agent.run()
print(result)
asyncio.run(main())
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Based on the code provided and the repository context, I can help explain and improve your implementation. Your code is generally well-structured, but let me break down the key components and suggest some potential enhancements:
Your browser configuration looks good, but you might want to consider:
Adding wait_for_network_idle_page_load_time in the context config to ensure stable page loads
Consider adding error handling for Chrome instance connection
Agent Configuration:
python
agent = Agent(
task="search 'openai' on google.com and describe the result page.",
llm=llm,
use_vision=True,
browser=browser,
save_conversation_path="logs/conversation.json",
)
You might want to add these optional parameters for better control:
max_steps: to limit the number of steps (default is 100)
validate_output: for output validation
max_failures: for retry attempts (default is 3)
Here's an improved version of your code:
python
import os
import asyncio
from langchain_openai import AzureChatOpenAI
from browser_use import Agent, Browser, BrowserConfig
from browser_use.browser.context import BrowserContextConfig
from dotenv import load_dotenv
# Load environment variables
load_dotenv(r"C:\Users\YINL\OneDrive - Bird & Bird LLP\Desktop\jupyter notebooks\.env")
# Initialize Azure OpenAI
llm = AzureChatOpenAI(
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_ID"],
openai_api_version=os.environ["OPENAI_API_VERSION"],
)
# Enhanced context configuration
context_config = BrowserContextConfig(
browser_window_size={"width": 1280, "height": 720},
disable_security=True,
wait_for_network_idle_page_load_time=2.0, # Increased wait time for stable loads
minimum_wait_page_load_time=1.0,
)
# Enhanced browser configuration
browser = Browser(
config=BrowserConfig(
headless=False,
disable_security=True,
chrome_instance_path=r"C:\Program Files\Google\Chrome\Application\chrome.exe",
extra_chromium_args=[
r"--user-data-dir=C:\Users\YINL\AppData\Local\Google\Chrome\User Data",
"--disable-web-security",
"--disable-features=IsolateOrigins,site-per-process",
],
new_context_config=context_config,
)
)
async def main():
try:
# Create agent with enhanced configuration
agent = Agent(
task="search 'openai' on google.com and describe the result page.",
llm=llm,
use_vision=True,
browser=browser,
save_conversation_path="logs/conversation.json",
max_failures=5, # Increased retry attempts
validate_output=True, # Enable output validation
max_steps=50, # Limit maximum steps
generate_gif=True, # Generate visual history
)
# Run the agent and get results
result = await agent.run()
# Print final result
if result.is_done():
print("Task completed successfully!")
print("Final result:", result.final_result())
else:
print("Task did not complete successfully")
if result.errors():
print("Errors encountered:", result.errors())
except Exception as e:
print(f"An error occurred: {str(e)}")
finally:
# Ensure browser cleanup
await browser.close()
if __name__ == "__main__":
asyncio.run(main())
Key improvements made:
Added error handling and proper cleanup
Enhanced browser and context configuration for better stability
Added output validation and increased retry attempts
Added GIF generation for visual history
Improved result handling with error checking
Added proper browser cleanup in finally block
The code will now:
Handle connection errors more gracefully
Wait longer for network stability
Validate outputs for better reliability
Generate a visual history of the automation
Clean up resources properly
Provide better feedback about task completion and any errors
Remember that the save_conversation_path directory ("logs/") should exist before running the code, or you should create it programmatically:
python
# Add this before creating the agent
os.makedirs("logs", exist_ok=True)