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
Standardise and refactor agent script for clarity and modularity
Morris Lee15976d79e837
diff --git a/examples/use-cases/captcha.py b/examples/use-cases/captcha.pyindex b35d719d9..fcfe96813 100644--- a/examples/use-cases/captcha.py+++ b/examples/use-cases/captcha.py@@ -2,6 +2,8 @@Simple try of the agent.@dev You need to add OPENAI_API_KEY to your environment variables.+NOTE: captchas are hard. For this example it works. But e.g. for iframes it does not.+for this example it helps to zoom in."""import os@@ -14,22 +16,19 @@ from langchain_openai import ChatOpenAIfrom browser_use import Agentfrom dotenv import load_dotenv+# Load environment variablesload_dotenv()if not os.getenv('OPENAI_API_KEY'):raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')-# NOTE: captchas are hard. For this example it works. But e.g. for iframes it does not.-# for this example it helps to zoom in.-llm = ChatOpenAI(model='gpt-4o')-agent = Agent(- task='go to https://captcha.com/demos/features/captcha-demo.aspx and solve the captcha',- llm=llm,-)--async def main():- await agent.run()- input('Press Enter to exit')---asyncio.run(main())+ llm = ChatOpenAI(model='gpt-4o')+ agent = Agent(+ task='go to https://captcha.com/demos/features/captcha-demo.aspx and solve the captcha',+ llm=llm,+ )+ await agent.run()+ input('Press Enter to exit')++if __name__ == "__main__":+ asyncio.run(main())\ No newline at end of filediff --git a/examples/use-cases/check_appointment.py b/examples/use-cases/check_appointment.pyindex 12e50d12b..11f4bd8b7 100644--- a/examples/use-cases/check_appointment.py+++ b/examples/use-cases/check_appointment.py@@ -8,6 +8,7 @@ from pydantic import BaseModel, SecretStrfrom browser_use.agent.service import Agentfrom browser_use.controller.service import Controller+# Load environment variablesload_dotenv()if not os.getenv('OPENAI_API_KEY'):raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')@@ -16,15 +17,18 @@ controller = Controller()class WebpageInfo(BaseModel):+ """Model for webpage link."""link: str = 'https://appointment.mfa.gr/en/reservations/aero/ireland-grcon-dub/'@controller.action('Go to the webpage', param_model=WebpageInfo)def go_to_webpage(webpage_info: WebpageInfo):+ """Returns the webpage link."""return webpage_info.linkasync def main():+ """Main function to execute the agent task."""task = ('Go to the Greece MFA webpage via the link I provided you.''Check the visa appointment dates. If there is no available date in this month, check the next month.'@@ -34,8 +38,8 @@ async def main():model = ChatOpenAI(model='gpt-4o-mini', api_key=SecretStr(os.getenv('OPENAI_API_KEY', '')))agent = Agent(task, model, controller=controller, use_vision=True)- result = await agent.run()+ await agent.run()-if __name__ == '__main__':+if __name__ == "__main__":asyncio.run(main())diff --git a/examples/use-cases/find_and_apply_to_jobs.py b/examples/use-cases/find_and_apply_to_jobs.pyindex a08363ecb..14032eecf 100644--- a/examples/use-cases/find_and_apply_to_jobs.py+++ b/examples/use-cases/find_and_apply_to_jobs.py@@ -25,9 +25,8 @@ from browser_use import ActionResult, Agent, Controllerfrom browser_use.browser.context import BrowserContextfrom browser_use.browser.browser import Browser, BrowserConfig-load_dotenv()-# Validate required environment variables+load_dotenv()required_env_vars = ["AZURE_OPENAI_KEY", "AZURE_OPENAI_ENDPOINT"]for var in required_env_vars:if not os.getenv(var):@@ -102,7 +101,7 @@ async def upload_cv(index: int, browser: BrowserContext):try:await file_upload_el.set_input_files(path)- msg = f'Successfully uploaded file to index {index}'+ msg = f'Successfully uploaded file "{path}" to index {index}'logger.info(msg)return ActionResult(extracted_content=msg)except Exception as e:@@ -158,5 +157,5 @@ async def main():await asyncio.gather(*[agent.run() for agent in agents])-if __name__ == '__main__':- asyncio.run(main())+if __name__ == "__main__":+ asyncio.run(main())\ No newline at end of filediff --git a/examples/use-cases/online_coding_agent.py b/examples/use-cases/online_coding_agent.pyindex 830f1b1ca..ba98a2f38 100644--- a/examples/use-cases/online_coding_agent.py+++ b/examples/use-cases/online_coding_agent.py@@ -9,8 +9,8 @@ from dotenv import load_dotenvfrom browser_use import Agent, Browser+# Load environment variablesload_dotenv()-if not os.getenv('OPENAI_API_KEY'):raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')@@ -40,4 +40,5 @@ async def main():await executor.run()await coder.run()-asyncio.run(main())+if __name__ == "__main__":+ asyncio.run(main())\ No newline at end of filediff --git a/examples/use-cases/post-twitter.py b/examples/use-cases/post-twitter.pyindex b25f6169c..e19e02bfa 100644--- a/examples/use-cases/post-twitter.py+++ b/examples/use-cases/post-twitter.py@@ -20,18 +20,21 @@ Any issues, contact me on X @defichemist95import osimport sysfrom typing import Optional-from dataclasses import dataclass-from dotenv import load_dotenv--load_dotenv()+import asynciosys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))-import asyncio+from dataclasses import dataclass+from dotenv import load_dotenvfrom langchain_openai import ChatOpenAI+from browser_use.browser.browser import Browser, BrowserConfigfrom browser_use import Agent, Controller+# Load environment variables+load_dotenv()+if not os.getenv('OPENAI_API_KEY'):+ raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')# ============ Configuration Section ============@dataclass@@ -114,9 +117,9 @@ async def post_tweet(agent: Agent):print(f"Error posting tweet: {str(e)}")-def main():+async def main():agent = create_twitter_agent(config)- asyncio.run(post_tweet(agent))+ await agent.run()if __name__ == "__main__":- main()+ asyncio.run(main())\ No newline at end of filediff --git a/examples/use-cases/scrolling_page.py b/examples/use-cases/scrolling_page.pyindex 537d5909c..6f83ba365 100644--- a/examples/use-cases/scrolling_page.py+++ b/examples/use-cases/scrolling_page.py@@ -10,8 +10,8 @@ from dotenv import load_dotenvfrom browser_use.browser.browser import Browser, BrowserConfig+# Load environment variablesload_dotenv()-if not os.getenv('OPENAI_API_KEY'):raise ValueError('OPENAI_API_KEY is not set')@@ -36,5 +36,5 @@ async def main():await agent.run()-if __name__ == '__main__':+if __name__ == "__main__":asyncio.run(main())diff --git a/examples/use-cases/twitter_post_using_cookies.py b/examples/use-cases/twitter_post_using_cookies.pyindex 063c85543..0b556c8ee 100644--- a/examples/use-cases/twitter_post_using_cookies.py+++ b/examples/use-cases/twitter_post_using_cookies.py@@ -26,7 +26,7 @@ file_path = os.path.join(os.path.dirname(__file__), 'twitter_cookies.txt')context = BrowserContext(browser=browser, config=BrowserContextConfig(cookies_file=file_path))-async def run_search():+async def main():agent = Agent(browser_context=context,task=('go to https://x.com. write a new post with the text "browser-use ftw", and submit it'),@@ -37,5 +37,5 @@ async def run_search():input('Press Enter to close the browser...')-if __name__ == '__main__':- asyncio.run(run_search())+if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/use-cases/web_voyager_agent.py b/examples/use-cases/web_voyager_agent.pyindex 82ac55d54..9e2c0af93 100644--- a/examples/use-cases/web_voyager_agent.py+++ b/examples/use-cases/web_voyager_agent.py@@ -66,5 +66,5 @@ async def main():history.save_to_file('./tmp/history.json')-if __name__ == '__main__':+if __name__ == "__main__":asyncio.run(main())