from langchain_openai import AzureChatOpenAI
from browser_use import Agent
from browser_use import BrowserConfig
from browser_use.browser.context import BrowserContextConfig
import asyncio
import os
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"],
)
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"
]
)
config = BrowserContextConfig(
browser_window_size={'width': 1920, 'height': 1080}
)
async def main():
agent = Agent(
task="Find a one-way flight from Bali to Oman on 12 January 2025 on Google Flights. Return me the cheapest option.",
llm=llm,
use_vision=True,
save_conversation_path="logs/conversation.json"
)
result = await agent.run()
print(result)
asyncio.run(main())
produced error:
"""
RuntimeError Traceback (most recent call last)
Cell In[7], line 37
34 result = await agent.run()
35 print(result)
---> 37 asyncio.run(main())
File c:\Users\YINLADMIN\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py:186, in run(main, debug)
161 """Execute the coroutine and return the result.
162
163 This function runs the passed coroutine, taking care of
(...)
182 asyncio.run(main())
183 """
184 if events._get_running_loop() is not None:
185 # fail fast with short traceback
--> 186 raise RuntimeError(
187 "asyncio.run() cannot be called from a running event loop")
189 with Runner(debug=debug) as runner:
190 return runner.run(main)
RuntimeError: asyncio.run() cannot be called from a running event loop
"""
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The error "RuntimeError: asyncio.run() cannot be called from a running event loop" occurs because asyncio.run() is designed to be the entry point for an asyncio program and should only be called once. In your case, it seems you are trying to call asyncio.run() from within an already running asyncio context, possibly within a Jupyter Notebook or similar environment where an event loop is already active.
Here's a breakdown of the issue and how to resolve it, along with considerations based on the provided code and repository files:
Understanding the Problem
asyncio.run(main()): This function starts a new event loop, runs the main() coroutine within it, and then closes the loop.
Running Event Loop: When you execute code in an environment like a Jupyter Notebook or sometimes within test frameworks, an event loop might already be running in the background.
Conflict: asyncio.run() cannot create a new event loop when one is already active, hence the RuntimeError.
Solutions
Using asyncio.get_event_loop().run_until_complete() (Recommended for Jupyter/Interactive Environments)
If you are in a Jupyter Notebook, Google Colab or other interactive environments, you should use asyncio.get_event_loop().run_until_complete() to run your main() function. This avoids creating a new loop when one is already active.
python
import asyncio
import os
from langchain_openai import AzureChatOpenAI
from browser_use.agent.service import Agent
from browser_use.browser.browser import BrowserConfig
from browser_use.browser.context import BrowserContextConfig
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"],
)
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"
]
)
config = BrowserContextConfig(
browser_window_size={'width': 1920, 'height': 1080}
)
async def main():
agent = Agent(
task="Find a one-way flight from Bali to Oman on 12 January 2025 on Google Flights. Return me the cheapest option.",
llm=llm,
use_vision=True,
save_conversation_path="logs/conversation.json"
)
result = await agent.run()
print(result)
if __name__ == "__main__":
asyncio.get_event_loop().run_until_complete(main())
Using asyncio.run() in a Proper Script Environment
If you are running this code in a standard Python script, the asyncio.run(main()) approach is correct and should work fine. Ensure that you are running this as a regular .py file, and not within an interactive environment.
Testing with pytest (If applicable)
If you were running this in a pytest context, pytest-asyncio handles event loops. See the conftest.py and pytest.ini files for the configurations used by this repository. You should not run code like this directly with asyncio.run() in tests.
Additional Notes:
Browser Configuration: The code snippet includes custom configurations for the browser, such as headless=False, custom Chrome paths and user data directories. Ensure these configurations are appropriate for your system.
Environment Variables: The code relies on environment variables like AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_DEPLOYMENT_ID, and OPENAI_API_VERSION. Make sure these are properly set before running the code.
Agent Class: The provided code snippet uses the Agent class. Review the browser_use/agent/service.py file, this is where the Agent class is defined. Also ensure the correct usage of BrowserConfig and BrowserContextConfig as they relate to the browser_use library.
Vision Support: The use_vision=True argument in the Agent constructor indicates that the agent will use vision capabilities (likely for processing screenshots from the browser). Ensure that the llm supports vision, or disable vision if it is not needed.
Saving Conversations: You are saving the conversation to logs/conversation.json. Make sure the directory logs exists, or that the program has permission to create it.
Error Handling and Retries: The Agent class in browser_use/agent/service.py has built-in mechanisms for error handling and retries. If your task fails, it might be worth reviewing the logging output and making sure the Agent can recover from potential errors like rate limits, validation errors etc.
Revised Code
python
import asyncio
import os
from langchain_openai import AzureChatOpenAI
from browser_use.agent.service import Agent
from browser_use.browser.browser import BrowserConfig
from browser_use.browser.context import BrowserContextConfig
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"],
)
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"
]
)
config = BrowserContextConfig(
browser_window_size={'width': 1920, 'height': 1080}
)
async def main():
agent = Agent(
task="Find a one-way flight from Bali to Oman on 12 January 2025 on Google Flights. Return me the cheapest option.",
llm=llm,
use_vision=True,
save_conversation_path="logs/conversation.json"
)
result = await agent.run()
print(result)
if __name__ == "__main__":
asyncio.get_event_loop().run_until_complete(main())
Summary
The core issue is using asyncio.run() inside an environment with an active asyncio event loop. The provided solution replaces asyncio.run(main()) with asyncio.get_event_loop().run_until_complete(main()) which works in such environments. The rest of the analysis points to other aspects of your code that could help you achieve the desired outcome with browser-use.