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
apply ruff safe fixes
Nick Sweetingfb6fa259a83a
diff --git a/browser_use/agent/gif.py b/browser_use/agent/gif.pyindex a2bd6705c..d93b587cc 100644--- a/browser_use/agent/gif.py+++ b/browser_use/agent/gif.py@@ -158,13 +158,13 @@ def _create_task_frame(# Draw task text with dynamic font size based on task lengthmargin = 140 # Increased marginmax_width = image.width - (2 * margin)-+# Dynamic font size calculation based on task length# Start with base font size (regular + 16)base_font_size = regular_font.size + 16min_font_size = max(regular_font.size - 10, 16) # Don't go below 16ptmax_font_size = base_font_size # Cap at the base font size-+# Calculate dynamic font size based on text length and complexity# Longer texts get progressively smaller fontstext_length = len(task)@@ -173,9 +173,9 @@ def _create_task_frame(font_size = max(base_font_size - int(10 * (text_length / 200)), min_font_size)else:font_size = base_font_size-+larger_font = ImageFont.truetype(regular_font.path, font_size)-+# Generate wrapped text with the calculated font sizewrapped_text = _wrap_text(task, larger_font, max_width)diff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.pyindex fa4100e35..b16438ef6 100644--- a/browser_use/agent/message_manager/views.py+++ b/browser_use/agent/message_manager/views.py@@ -8,7 +8,7 @@ from langchain_core.load import dumpd, loadfrom langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage, ToolMessagefrom pydantic import BaseModel, ConfigDict, Field, model_serializer, model_validator-filterwarnings("ignore", category=LangChainBetaWarning)+filterwarnings('ignore', category=LangChainBetaWarning)if TYPE_CHECKING:from browser_use.agent.views import AgentOutputdiff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex f4370cf84..699cb83c3 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -6,7 +6,6 @@ import inspectimport jsonimport loggingimport os-import platformimport reimport timefrom pathlib import Pathdiff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 2a20f8d98..ea1327d65 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -23,11 +23,11 @@ from browser_use.dom.views import SelectorMapToolCallingMethod = Literal['function_calling', 'json_mode', 'raw', 'auto']REQUIRED_LLM_API_ENV_VARS = {- "ChatOpenAI": ["OPENAI_API_KEY"],- "AzureOpenAI": ["AZURE_ENDPOINT", "AZURE_OPENAI_API_KEY"],- "ChatBedrockConverse": ["ANTHROPIC_API_KEY"],- "ChatAnthropic": ["ANTHROPIC_API_KEY"],- "ChatGoogleGenerativeAI": ["GEMINI_API_KEY"]+ 'ChatOpenAI': ['OPENAI_API_KEY'],+ 'AzureOpenAI': ['AZURE_ENDPOINT', 'AZURE_OPENAI_API_KEY'],+ 'ChatBedrockConverse': ['ANTHROPIC_API_KEY'],+ 'ChatAnthropic': ['ANTHROPIC_API_KEY'],+ 'ChatGoogleGenerativeAI': ['GEMINI_API_KEY'],}diff --git a/browser_use/browser/context.py b/browser_use/browser/context.pyindex a9fd857ac..7cbb3c3a0 100644--- a/browser_use/browser/context.py+++ b/browser_use/browser/context.py@@ -158,12 +158,7 @@ class BrowserContextConfig(BaseModel):class BrowserSession:-- def __init__(- self,- context: PlaywrightBrowserContext,- cached_state: BrowserState | None=None- ):+ def __init__(self, context: PlaywrightBrowserContext, cached_state: BrowserState | None = None):init_script = """(() => {if (!window.getEventListeners) {@@ -212,6 +207,7 @@ class BrowserSession:self.cached_state = cached_stateself.context.on('page', lambda page: page.add_init_script(init_script))+@dataclassclass BrowserContextState:"""@@ -1217,7 +1213,9 @@ class BrowserContext:return None@time_execution_async('--get_locate_element_by_text')- async def get_locate_element_by_text(self, text: str, nth: Optional[int] = 0, element_type: Optional[str] = None) -> Optional[ElementHandle]:+ async def get_locate_element_by_text(+ self, text: str, nth: Optional[int] = 0, element_type: Optional[str] = None+ ) -> Optional[ElementHandle]:"""Locates an element on the page using the provided text.If `nth` is provided, it returns the nth matching element (0-based).@@ -1226,7 +1224,7 @@ class BrowserContext:current_frame = await self.get_current_page()try:# handle also specific element type or use any type.- selector = f"{element_type or '*'}:text(\"{text}\")"+ selector = f'{element_type or "*"}:text("{text}")'elements = await current_frame.query_selector_all(selector)# considering only visible elementselements = [el for el in elements if await el.is_visible()]@@ -1574,4 +1572,4 @@ class BrowserContext:TimeoutError: If the element does not become visible within the specified timeout."""page = await self.get_current_page()- await page.wait_for_selector(selector, state="visible", timeout=timeout)+ await page.wait_for_selector(selector, state='visible', timeout=timeout)diff --git a/browser_use/browser/tests/screenshot_test.py b/browser_use/browser/tests/screenshot_test.pyindex b2911f857..b55fdf879 100644--- a/browser_use/browser/tests/screenshot_test.py+++ b/browser_use/browser/tests/screenshot_test.py@@ -31,5 +31,6 @@ async def test_take_full_page_screenshot():finally:await browser.close()+if __name__ == '__main__':asyncio.run(test_take_full_page_screenshot())diff --git a/browser_use/browser/views.py b/browser_use/browser/views.pyindex f6fc87bc0..73304bc42 100644--- a/browser_use/browser/views.py+++ b/browser_use/browser/views.py@@ -16,13 +16,17 @@ class TabInfo(BaseModel):title: strparent_page_id: Optional[int] = None # parent page that contains this popup or cross-origin iframe+class GroupTabsAction(BaseModel):- tab_ids: list[int]- title: str- color: Optional[str] = "blue"+ tab_ids: list[int]+ title: str+ color: Optional[str] = 'blue'+class UngroupTabsAction(BaseModel):- tab_ids: list[int]+ tab_ids: list[int]++@dataclassclass BrowserState(DOMState):url: strdiff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 1827fd7b6..9cf0b57f2 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -212,9 +212,7 @@ class Controller(Generic[Context]):async def click_element_by_text(params: ClickElementByTextAction, browser: BrowserContext):try:element_node = await browser.get_locate_element_by_text(- text=params.text,- nth=params.nth,- element_type=params.element_type+ text=params.text, nth=params.nth, element_type=params.element_type)if element_node:@@ -302,7 +300,9 @@ class Controller(Generic[Context]):@self.registry.action('Extract page content to retrieve specific information from the page, e.g. all company names, a specifc description, all information about, links with companies in structured format or simply links',)- async def extract_content(goal: str, should_strip_link_urls: bool, browser: BrowserContext, page_extraction_llm: BaseChatModel):+ async def extract_content(+ goal: str, should_strip_link_urls: bool, browser: BrowserContext, page_extraction_llm: BaseChatModel+ ):page = await browser.get_current_page()import markdownifydiff --git a/browser_use/controller/views.py b/browser_use/controller/views.pyindex e7d2ec86b..579b64ec5 100644--- a/browser_use/controller/views.py+++ b/browser_use/controller/views.py@@ -13,23 +13,28 @@ class GoToUrlAction(BaseModel):class WaitForElementAction(BaseModel):- selector: str- timeout: Optional[int] = 10000 # Timeout in milliseconds+ selector: str+ timeout: Optional[int] = 10000 # Timeout in milliseconds+class ClickElementAction(BaseModel):index: intxpath: Optional[str] = None-++class ClickElementByXpathAction(BaseModel):- xpath: str+ xpath: str+class ClickElementBySelectorAction(BaseModel):- css_selector: str-+ css_selector: str++class ClickElementByTextAction(BaseModel):- text: str- element_type: Optional[str]- nth: int = 0+ text: str+ element_type: Optional[str]+ nth: int = 0+class InputTextAction(BaseModel):index: int@@ -61,16 +66,19 @@ class ScrollAction(BaseModel):class SendKeysAction(BaseModel):keys: str+class GroupTabsAction(BaseModel):- tab_ids: list[int] = Field(..., description="List of tab IDs to group")- title: str = Field(..., description="Name for the tab group")- color: Optional[str] = Field(- "blue",- description="Color for the group (grey/blue/red/yellow/green/pink/purple/cyan)",- )+ tab_ids: list[int] = Field(..., description='List of tab IDs to group')+ title: str = Field(..., description='Name for the tab group')+ color: Optional[str] = Field(+ 'blue',+ description='Color for the group (grey/blue/red/yellow/green/pink/purple/cyan)',+ )+class UngroupTabsAction(BaseModel):- tab_ids: list[int] = Field(..., description="List of tab IDs to ungroup")+ tab_ids: list[int] = Field(..., description='List of tab IDs to ungroup')+class ExtractPageContentAction(BaseModel):value: strdiff --git a/browser_use/exceptions.py b/browser_use/exceptions.pyindex c3df4934a..2e01cf0cd 100644--- a/browser_use/exceptions.py+++ b/browser_use/exceptions.py@@ -1,5 +1,5 @@class LLMException(Exception):- def __init__(self, status_code, message):- self.status_code = status_code- self.message = message- super().__init__(f"Error {status_code}: {message}")+ def __init__(self, status_code, message):+ self.status_code = status_code+ self.message = message+ super().__init__(f'Error {status_code}: {message}')diff --git a/browser_use/utils.py b/browser_use/utils.pyindex f70491870..38485bf16 100644--- a/browser_use/utils.py+++ b/browser_use/utils.py@@ -82,7 +82,7 @@ class SignalHandler:if self.custom_exit_callback:self.custom_exit_callback()os._exit(0)-+self.original_sigint_handler = signal.signal(signal.SIGINT, windows_handler)else:# On Unix-like systems, use asyncio's signal handling for smoother experiencediff --git a/eval/grok.py b/eval/grok.pyindex e15f68446..4df613b6b 100644--- a/eval/grok.py+++ b/eval/grok.py@@ -13,13 +13,15 @@ api_key = os.getenv('GROK_API_KEY', '')if not api_key:raise ValueError('GROK_API_KEY is not set')+async def main():- agent = Agent(- task='Go to https://www.google.com and search for "python" and click on the first result',- use_vision=False,- llm=ChatOpenAI(model="grok-2-1212",base_url="https://api.x.ai/v1",api_key=SecretStr(api_key)),- )+ agent = Agent(+ task='Go to https://www.google.com and search for "python" and click on the first result',+ use_vision=False,+ llm=ChatOpenAI(model='grok-2-1212', base_url='https://api.x.ai/v1', api_key=SecretStr(api_key)),+ )++ await agent.run()- await agent.run()asyncio.run(main())diff --git a/examples/custom-functions/group_ungroup.py b/examples/custom-functions/group_ungroup.pyindex a7108c025..2349cb1bd 100644--- a/examples/custom-functions/group_ungroup.py+++ b/examples/custom-functions/group_ungroup.py@@ -1,4 +1,3 @@-import osimport sys@@ -13,7 +12,7 @@ from langchain_openai import ChatOpenAIfrom browser_use import Agent, Controllerfrom browser_use.browser.browser import Browser, BrowserConfigfrom browser_use.browser.context import BrowserContext-+# async def group_tabs(self, tab_ids: list[int] , title: str, color: str = "blue"):# """Reset the browser session# Call this when you don't want to kill the context but just kill the state@@ -23,7 +22,7 @@ from browser_use.browser.context import BrowserContext# js = f"""# chrome.tabs.group({{ tabIds: {tab_ids} }}, (groupId) => {{-# chrome.tabGroups.update(groupId, {{+# chrome.tabGroups.update(groupId, {{# title: "{title}",# color: "{color}"# }});@@ -45,7 +44,7 @@ from browser_use.browser.context import BrowserContext# }}# """-# await page.evaluate(js)+# await page.evaluate(js)# Initialize controller first@@ -57,52 +56,39 @@ browser = Browser()controller = Controller()- "Visually group browser tabs in Chrome",- param_model=GroupTabsAction,- requires_browser=True-)+[email protected]('Visually group browser tabs in Chrome', param_model=GroupTabsAction, requires_browser=True)async def group_tabs(params: GroupTabsAction, browser: BrowserContext):- try:- # Get tab IDs from params- tab_ids = params.tab_ids- title = params.title- color = params.color-- # Call the low-level implementation in BrowserContext- result = await browser.group_tabs(tab_ids, title, color='red')- return ActionResult(- extracted_content=result,- include_in_memory=True- )- except Exception as e:- return ActionResult(error=f"Failed to group tabs: {str(e)}")+ try:+ # Get tab IDs from params+ tab_ids = params.tab_ids+ title = params.title+ color = params.color++ # Call the low-level implementation in BrowserContext+ result = await browser.group_tabs(tab_ids, title, color='red')+ return ActionResult(extracted_content=result, include_in_memory=True)+ except Exception as e:+ return ActionResult(error=f'Failed to group tabs: {str(e)}')+# Register ungroup_tabs action- "Remove visual grouping from tabs in Chrome",- param_model=UngroupTabsAction,- requires_browser=True-)[email protected]('Remove visual grouping from tabs in Chrome', param_model=UngroupTabsAction, requires_browser=True)async def ungroup_tabs(params: UngroupTabsAction, browser: BrowserContext):- try:- # Get tab IDs from params- tab_ids = params.tab_ids-- # Call the low-level implementation in BrowserContext- result = await browser.ungroup_tabs(tab_ids)- return ActionResult(- extracted_content=result,- include_in_memory=True- )- except Exception as e:- return ActionResult(error=f"Failed to ungroup tabs: {str(e)}")-+ try:+ # Get tab IDs from params+ tab_ids = params.tab_ids++ # Call the low-level implementation in BrowserContext+ result = await browser.ungroup_tabs(tab_ids)+ return ActionResult(extracted_content=result, include_in_memory=True)+ except Exception as e:+ return ActionResult(error=f'Failed to ungroup tabs: {str(e)}')++async def main():task = 'Group tabs 1 and 2 into a "Research" group, then ungroup them.'--model = ChatOpenAI(model='gpt-4o')agent = Agent(task=task,@@ -119,4 +105,4 @@ async def main():if __name__ == '__main__':- asyncio.run(main())+ asyncio.run(main())diff --git a/examples/custom-functions/hover_element.py b/examples/custom-functions/hover_element.pyindex f8f3b2304..42bd4ed6d 100644--- a/examples/custom-functions/hover_element.py+++ b/examples/custom-functions/hover_element.py@@ -17,72 +17,80 @@ from browser_use.browser.context import BrowserContextclass HoverAction(BaseModel):- index: Optional[int] = None- xpath: Optional[str] = None+ index: Optional[int] = None+ xpath: Optional[str] = Noneselector: Optional[str] = None+browser = Browser(- config=BrowserConfig(- headless=False,- )+ config=BrowserConfig(+ headless=False,+ ))controller = Controller()+@controller.registry.action(- 'Hover over an element',- param_model=HoverAction, # Define this model with at least "index: int" field+ 'Hover over an element',+ param_model=HoverAction, # Define this model with at least "index: int" field)async def hover_element(params: HoverAction, browser: BrowserContext):- """- Hovers over the element specified by its index from the cached selector map or by XPath.- """- session = await browser.get_session()- state = session.cached_state-- if params.xpath:- # Use XPath to locate the element- element_handle = await browser.get_locate_element_by_xpath(params.xpath)- if element_handle is None:- raise Exception(f'Failed to locate element with XPath {params.xpath}')- elif params.selector:- # Use CSS selector to locate the element- element_handle = await browser.get_locate_element_by_css_selector(params.selector)- if element_handle is None:- raise Exception(f'Failed to locate element with CSS Selector {params.selector}')- elif params.index is not None:- # Use index to locate the element- if state is None or params.index not in state.selector_map:- raise Exception(f'Element index {params.index} does not exist - retry or use alternative actions')- element_node = state.selector_map[params.index]- element_handle = await browser.get_locate_element(element_node)- if element_handle is None:- raise Exception(f'Failed to locate element with index {params.index}')- else:- raise Exception('Either index or xpath must be provided')-- try:- await element_handle.hover()- msg = f'🖱️ Hovered over element at index {params.index}' if params.index is not None else f'🖱️ Hovered over element with XPath {params.xpath}'- return ActionResult(extracted_content=msg, include_in_memory=True)- except Exception as e:- err_msg = f'❌ Failed to hover over element: {str(e)}'- raise Exception(err_msg)+ """+ Hovers over the element specified by its index from the cached selector map or by XPath.+ """+ session = await browser.get_session()+ state = session.cached_state++ if params.xpath:+ # Use XPath to locate the element+ element_handle = await browser.get_locate_element_by_xpath(params.xpath)+ if element_handle is None:+ raise Exception(f'Failed to locate element with XPath {params.xpath}')+ elif params.selector:+ # Use CSS selector to locate the element+ element_handle = await browser.get_locate_element_by_css_selector(params.selector)+ if element_handle is None:+ raise Exception(f'Failed to locate element with CSS Selector {params.selector}')+ elif params.index is not None:+ # Use index to locate the element+ if state is None or params.index not in state.selector_map:+ raise Exception(f'Element index {params.index} does not exist - retry or use alternative actions')+ element_node = state.selector_map[params.index]+ element_handle = await browser.get_locate_element(element_node)+ if element_handle is None:+ raise Exception(f'Failed to locate element with index {params.index}')+ else:+ raise Exception('Either index or xpath must be provided')++ try:+ await element_handle.hover()+ msg = (+ f'🖱️ Hovered over element at index {params.index}'+ if params.index is not None+ else f'🖱️ Hovered over element with XPath {params.xpath}'+ )+ return ActionResult(extracted_content=msg, include_in_memory=True)+ except Exception as e:+ err_msg = f'❌ Failed to hover over element: {str(e)}'+ raise Exception(err_msg)+async def main():- task = 'Open https://testpages.eviltester.com/styled/csspseudo/css-hover.html and hover the element with the css selector #hoverdivpara, then click on "Can you click me?"'- # task = 'Open https://testpages.eviltester.com/styled/csspseudo/css-hover.html and hover the element with the xpath //*[@id="hoverdivpara"], then click on "Can you click me?"'- model = ChatOpenAI(model='gpt-4o')- agent = Agent(- task=task,- llm=model,- controller=controller,- browser=browser,- )+ task = 'Open https://testpages.eviltester.com/styled/csspseudo/css-hover.html and hover the element with the css selector #hoverdivpara, then click on "Can you click me?"'+ # task = 'Open https://testpages.eviltester.com/styled/csspseudo/css-hover.html and hover the element with the xpath //*[@id="hoverdivpara"], then click on "Can you click me?"'+ model = ChatOpenAI(model='gpt-4o')+ agent = Agent(+ task=task,+ llm=model,+ controller=controller,+ browser=browser,+ )++ await agent.run()+ await browser.close()- await agent.run()- await browser.close()+ input('Press Enter to close...')- input('Press Enter to close...')if __name__ == '__main__':- asyncio.run(main())+ asyncio.run(main())diff --git a/examples/features/click_fallback_options.py b/examples/features/click_fallback_options.pyindex ef8fb1f8a..8d0f52b88 100644--- a/examples/features/click_fallback_options.py+++ b/examples/features/click_fallback_options.py@@ -147,61 +147,65 @@ HTML_CONTENT = """"""+# aiohttp request handler to serve the HTML contentasync def handle_root(request):- return web.Response(text=HTML_CONTENT, content_type='text/html')+ return web.Response(text=HTML_CONTENT, content_type='text/html')+# Function to run the HTTP serverasync def run_http_server():- app = web.Application()- app.router.add_get("/", handle_root)- runner = web.AppRunner(app)- await runner.setup()- site = web.TCPSite(runner, "localhost", 8000)- await site.start()- print("HTTP server running on http://localhost:8000")- # Keep the server running indefinitely.- while True:- await asyncio.sleep(3600)+ app = web.Application()+ app.router.add_get('/', handle_root)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, 'localhost', 8000)+ await site.start()+ print('HTTP server running on http://localhost:8000')+ # Keep the server running indefinitely.+ while True:+ await asyncio.sleep(3600)+# Your agent tasks and other logicload_dotenv()controller = Controller()+async def main():- # Start the HTTP server in the background.- server_task = asyncio.create_task(run_http_server())-- # Example tasks for the agent.- xpath_task = 'Open http://localhost:8000/, click element with the xpath "/html/body/div/div[1]" and then click on Oranges'- css_selector_task = 'Open http://localhost:8000/, click element with the selector div.select-display and then click on apples'- text_task = 'Open http://localhost:8000/, click the third element with the text "Select a fruit" and then click on Apples, then click the second element with the text "Select a fruit" and then click on Oranges'- select_task = 'Open http://localhost:8000/, choose the car BMW'- button_task = 'Open http://localhost:8000/, click on the button'-- llm = ChatOpenAI(model='gpt-4o')- # llm = ChatGoogleGenerativeAI(- # model="gemini-2.0-flash-lite",- # )--- # Run different agent tasks.- for task in [xpath_task, css_selector_task, text_task, select_task, button_task]:- agent = Agent(- task=task,- llm=llm,- controller=controller,- )- await agent.run()-- # Wait for user input before shutting down.- input('Press Enter to close...')- # Cancel the server task once finished.- server_task.cancel()- try:- await server_task- except asyncio.CancelledError:- print("HTTP server stopped.")+ # Start the HTTP server in the background.+ server_task = asyncio.create_task(run_http_server())++ # Example tasks for the agent.+ xpath_task = 'Open http://localhost:8000/, click element with the xpath "/html/body/div/div[1]" and then click on Oranges'+ css_selector_task = 'Open http://localhost:8000/, click element with the selector div.select-display and then click on apples'+ text_task = 'Open http://localhost:8000/, click the third element with the text "Select a fruit" and then click on Apples, then click the second element with the text "Select a fruit" and then click on Oranges'+ select_task = 'Open http://localhost:8000/, choose the car BMW'+ button_task = 'Open http://localhost:8000/, click on the button'++ llm = ChatOpenAI(model='gpt-4o')+ # llm = ChatGoogleGenerativeAI(+ # model="gemini-2.0-flash-lite",+ # )++ # Run different agent tasks.+ for task in [xpath_task, css_selector_task, text_task, select_task, button_task]:+ agent = Agent(+ task=task,+ llm=llm,+ controller=controller,+ )+ await agent.run()++ # Wait for user input before shutting down.+ input('Press Enter to close...')+ # Cancel the server task once finished.+ server_task.cancel()+ try:+ await server_task+ except asyncio.CancelledError:+ print('HTTP server stopped.')+if __name__ == '__main__':- asyncio.run(main())+ asyncio.run(main())diff --git a/examples/features/custom_user_agent.py b/examples/features/custom_user_agent.pyindex 126d11b5e..fa5b1bb70 100644--- a/examples/features/custom_user_agent.py+++ b/examples/features/custom_user_agent.py@@ -49,7 +49,7 @@ llm = get_llm(args.provider)browser = Browser(config=BrowserConfig(- #browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ # browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',))diff --git a/examples/features/save_trace.py b/examples/features/save_trace.pyindex f2b4bb677..657a6ed81 100644--- a/examples/features/save_trace.py+++ b/examples/features/save_trace.py@@ -16,9 +16,7 @@ llm = ChatOpenAI(model='gpt-4o', temperature=0.0)async def main():browser = Browser()- async with await browser.new_context(- config=BrowserContextConfig(trace_path='./tmp/traces/')- ) as context:+ async with await browser.new_context(config=BrowserContextConfig(trace_path='./tmp/traces/')) as context:agent = Agent(task='Go to hackernews, then go to apple.com and return all titles of open tabs',llm=llm,diff --git a/examples/integrations/discord/discord_api.py b/examples/integrations/discord/discord_api.pyindex 32ee5c0b0..66a2640bf 100644--- a/examples/integrations/discord/discord_api.py+++ b/examples/integrations/discord/discord_api.py@@ -55,9 +55,7 @@ class DiscordBot(commands.Bot):intents.members = True # Enable members intent for user info# Initialize the bot with a command prefix and intents.- super().__init__(- command_prefix='!', intents=intents- ) # You may not need prefix, just here for flexibility+ super().__init__(command_prefix='!', intents=intents) # You may not need prefix, just here for flexibility# self.tree = app_commands.CommandTree(self) # Initialize command tree for slash commands.@@ -86,12 +84,8 @@ class DiscordBot(commands.Bot):print(f'Error sending start message: {e}')try:- agent_message = await self.run_agent(- message.content.replace(f'{self.prefix} ', '').strip()- )- await message.channel.send(- content=f'{agent_message}', reference=message, mention_author=True- )+ agent_message = await self.run_agent(message.content.replace(f'{self.prefix} ', '').strip())+ await message.channel.send(content=f'{agent_message}', reference=message, mention_author=True)except Exception as e:await message.channel.send(content=f'Error during task execution: {str(e)}',diff --git a/examples/integrations/slack/slack_api.py b/examples/integrations/slack/slack_api.pyindex 453209cae..956e2aa66 100644--- a/examples/integrations/slack/slack_api.py+++ b/examples/integrations/slack/slack_api.py@@ -18,96 +18,107 @@ logger = logging.getLogger('slack')app = FastAPI()+class SlackBot:- def __init__(self, llm: BaseChatModel, bot_token: str, signing_secret: str, ack: bool = False, browser_config: BrowserConfig = BrowserConfig(headless=True)):- if not bot_token or not signing_secret:- raise ValueError("Bot token and signing secret must be provided")-- self.llm = llm- self.ack = ack- self.browser_config = browser_config- self.client = AsyncWebClient(token=bot_token)- self.signature_verifier = SignatureVerifier(signing_secret)- self.processed_events = set()- logger.info("SlackBot initialized")-- async def handle_event(self, event, event_id):- try:- logger.info(f"Received event id: {event_id}")- if not event_id:- logger.warning("Event ID missing in event data")- return-- if event_id in self.processed_events:- logger.info(f"Event {event_id} already processed")- return- self.processed_events.add(event_id)-- if 'subtype' in event and event['subtype'] == 'bot_message':- return-- text = event.get('text')- user_id = event.get('user')- if text and text.startswith('$bu '):- task = text[len('$bu '):].strip()- if self.ack:- try:- await self.send_message(event['channel'], f'<@{user_id}> Starting browser use task...', thread_ts=event.get('ts'))- except Exception as e:- logger.error(f"Error sending start message: {e}")-- try:- agent_message = await self.run_agent(task)- await self.send_message(event['channel'], f'<@{user_id}> {agent_message}', thread_ts=event.get('ts'))- except Exception as e:- await self.send_message(event['channel'], f'Error during task execution: {str(e)}', thread_ts=event.get('ts'))- except Exception as e:- logger.error(f"Error in handle_event: {str(e)}")-- async def run_agent(self, task: str) -> str:- try:- browser = Browser(config=self.browser_config)- agent = Agent(task=task, llm=self.llm, browser=browser)- result = await agent.run()-- agent_message = None- if result.is_done():- agent_message = result.history[-1].result[0].extracted_content-- if agent_message is None:- agent_message = 'Oops! Something went wrong while running Browser-Use.'-- return agent_message-- except Exception as e:- logger.error(f"Error during task execution: {str(e)}")- return f'Error during task execution: {str(e)}'-- async def send_message(self, channel, text, thread_ts=None):- try:- await self.client.chat_postMessage(channel=channel, text=text, thread_ts=thread_ts)- except SlackApiError as e:- logger.error(f"Error sending message: {e.response['error']}")-[email protected]("/slack/events")+ def __init__(+ self,+ llm: BaseChatModel,+ bot_token: str,+ signing_secret: str,+ ack: bool = False,+ browser_config: BrowserConfig = BrowserConfig(headless=True),+ ):+ if not bot_token or not signing_secret:+ raise ValueError('Bot token and signing secret must be provided')++ self.llm = llm+ self.ack = ack+ self.browser_config = browser_config+ self.client = AsyncWebClient(token=bot_token)+ self.signature_verifier = SignatureVerifier(signing_secret)+ self.processed_events = set()+ logger.info('SlackBot initialized')++ async def handle_event(self, event, event_id):+ try:+ logger.info(f'Received event id: {event_id}')+ if not event_id:+ logger.warning('Event ID missing in event data')+ return++ if event_id in self.processed_events:+ logger.info(f'Event {event_id} already processed')+ return+ self.processed_events.add(event_id)++ if 'subtype' in event and event['subtype'] == 'bot_message':+ return++ text = event.get('text')+ user_id = event.get('user')+ if text and text.startswith('$bu '):+ task = text[len('$bu ') :].strip()+ if self.ack:+ try:+ await self.send_message(+ event['channel'], f'<@{user_id}> Starting browser use task...', thread_ts=event.get('ts')+ )+ except Exception as e:+ logger.error(f'Error sending start message: {e}')++ try:+ agent_message = await self.run_agent(task)+ await self.send_message(event['channel'], f'<@{user_id}> {agent_message}', thread_ts=event.get('ts'))+ except Exception as e:+ await self.send_message(event['channel'], f'Error during task execution: {str(e)}', thread_ts=event.get('ts'))+ except Exception as e:+ logger.error(f'Error in handle_event: {str(e)}')++ async def run_agent(self, task: str) -> str:+ try:+ browser = Browser(config=self.browser_config)+ agent = Agent(task=task, llm=self.llm, browser=browser)+ result = await agent.run()++ agent_message = None+ if result.is_done():+ agent_message = result.history[-1].result[0].extracted_content++ if agent_message is None:+ agent_message = 'Oops! Something went wrong while running Browser-Use.'++ return agent_message++ except Exception as e:+ logger.error(f'Error during task execution: {str(e)}')+ return f'Error during task execution: {str(e)}'++ async def send_message(self, channel, text, thread_ts=None):+ try:+ await self.client.chat_postMessage(channel=channel, text=text, thread_ts=thread_ts)+ except SlackApiError as e:+ logger.error(f'Error sending message: {e.response["error"]}')++[email protected]('/slack/events')async def slack_events(request: Request, slack_bot: SlackBot = Depends()):- try:- if not slack_bot.signature_verifier.is_valid_request(await request.body(), dict(request.headers)):- logger.warning("Request verification failed")- raise HTTPException(status_code=400, detail="Request verification failed")-- event_data = await request.json()- logger.info(f"Received event data: {event_data}")- if 'challenge' in event_data:- return {"challenge": event_data['challenge']}-- if 'event' in event_data:- try:- await slack_bot.handle_event(event_data.get('event'), event_data.get('event_id'))- except Exception as e:- logger.error(f"Error handling event: {str(e)}")-- return {}- except Exception as e:- logger.error(f"Error in slack_events: {str(e)}")- raise HTTPException(status_code=500, detail="Internal Server Error")+ try:+ if not slack_bot.signature_verifier.is_valid_request(await request.body(), dict(request.headers)):+ logger.warning('Request verification failed')+ raise HTTPException(status_code=400, detail='Request verification failed')++ event_data = await request.json()+ logger.info(f'Received event data: {event_data}')+ if 'challenge' in event_data:+ return {'challenge': event_data['challenge']}++ if 'event' in event_data:+ try:+ await slack_bot.handle_event(event_data.get('event'), event_data.get('event_id'))+ except Exception as e:+ logger.error(f'Error handling event: {str(e)}')++ return {}+ except Exception as e:+ logger.error(f'Error in slack_events: {str(e)}')+ raise HTTPException(status_code=500, detail='Internal Server Error')diff --git a/examples/models/azure_openai.py b/examples/models/azure_openai.pyindex 2c540adfa..dd2efc0bf 100644--- a/examples/models/azure_openai.py+++ b/examples/models/azure_openai.py@@ -24,26 +24,26 @@ azure_openai_api_key = os.getenv('AZURE_OPENAI_API_KEY')azure_openai_endpoint = os.getenv('AZURE_OPENAI_ENDPOINT')if not azure_openai_api_key or not azure_openai_endpoint:- raise ValueError('AZURE_OPENAI_API_KEY or AZURE_OPENAI_ENDPOINT is not set')+ raise ValueError('AZURE_OPENAI_API_KEY or AZURE_OPENAI_ENDPOINT is not set')# Initialize the Azure OpenAI clientllm = AzureChatOpenAI(- model_name='gpt-4o',- openai_api_key=azure_openai_api_key,- azure_endpoint=azure_openai_endpoint, # Corrected to use azure_endpoint instead of openai_api_base- deployment_name='gpt-4o', # Use deployment_name for Azure models- api_version='2024-08-01-preview' # Explicitly set the API version here+ model_name='gpt-4o',+ openai_api_key=azure_openai_api_key,+ azure_endpoint=azure_openai_endpoint, # Corrected to use azure_endpoint instead of openai_api_base+ deployment_name='gpt-4o', # Use deployment_name for Azure models+ api_version='2024-08-01-preview', # Explicitly set the API version here)agent = Agent(- task='Go to amazon.com, search for laptop, sort by best rating, and give me the price of the first result',- llm=llm,+ task='Go to amazon.com, search for laptop, sort by best rating, and give me the price of the first result',+ llm=llm,)async def main():- await agent.run(max_steps=10)- input('Press Enter to continue...')+ await agent.run(max_steps=10)+ input('Press Enter to continue...')asyncio.run(main())diff --git a/examples/models/bedrock_claude.py b/examples/models/bedrock_claude.pyindex c2bade20f..5d834994c 100644--- a/examples/models/bedrock_claude.py+++ b/examples/models/bedrock_claude.py@@ -19,19 +19,19 @@ from browser_use.controller.service import Controllerdef get_llm():- return ChatBedrockConverse(- model_id="us.anthropic.claude-3-5-sonnet-20241022-v2:0",- temperature=0.0,- max_tokens=None,- )+ return ChatBedrockConverse(+ model_id='us.anthropic.claude-3-5-sonnet-20241022-v2:0',+ temperature=0.0,+ max_tokens=None,+ )# Define the task for the agenttask = (- "Visit cnn.com, navigate to the 'World News' section, and identify the latest headline. "- "Open the first article and summarize its content in 3-4 sentences. "- "Additionally, analyze the sentiment of the article (positive, neutral, or negative) "- "and provide a confidence score for the sentiment. Present the result in a tabular format."+ "Visit cnn.com, navigate to the 'World News' section, and identify the latest headline. "+ 'Open the first article and summarize its content in 3-4 sentences. '+ 'Additionally, analyze the sentiment of the article (positive, neutral, or negative) '+ 'and provide a confidence score for the sentiment. Present the result in a tabular format.')parser = argparse.ArgumentParser()@@ -41,19 +41,23 @@ args = parser.parse_args()llm = get_llm()browser = Browser(- config=BrowserConfig(- # browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',- )+ config=BrowserConfig(+ # browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ ))agent = Agent(- task=args.query, llm=llm, controller=Controller(), browser=browser, validate_output=True,+ task=args.query,+ llm=llm,+ controller=Controller(),+ browser=browser,+ validate_output=True,)async def main():- await agent.run(max_steps=30)- await browser.close()+ await agent.run(max_steps=30)+ await browser.close()asyncio.run(main())diff --git a/examples/models/ollama.py b/examples/models/ollama.pyindex 792e73b67..dc297598d 100644--- a/examples/models/ollama.py+++ b/examples/models/ollama.py@@ -15,22 +15,22 @@ from browser_use.agent.views import AgentHistoryListasync def run_search() -> AgentHistoryList:- agent = Agent(- task="Search for a 'browser use' post on the r/LocalLLaMA subreddit and open it.",- llm=ChatOllama(- model="qwen2.5:32b-instruct-q4_K_M",- num_ctx=32000,- ),- )+ agent = Agent(+ task="Search for a 'browser use' post on the r/LocalLLaMA subreddit and open it.",+ llm=ChatOllama(+ model='qwen2.5:32b-instruct-q4_K_M',+ num_ctx=32000,+ ),+ )- result = await agent.run()- return result+ result = await agent.run()+ return resultasync def main():- result = await run_search()- print("\n\n", result)+ result = await run_search()+ print('\n\n', result)-if __name__ == "__main__":- asyncio.run(main())+if __name__ == '__main__':+ asyncio.run(main())diff --git a/examples/models/qwen.py b/examples/models/qwen.pyindex 9bddec952..0b621cdf0 100644--- a/examples/models/qwen.py+++ b/examples/models/qwen.py@@ -8,10 +8,7 @@ from browser_use import Agentasync def run_search():agent = Agent(task=(- '1. Go to https://www.reddit.com/r/LocalLLaMA'- "2. Search for 'browser use' in the search bar"- '3. Click search'- '4. Call done'+ "1. Go to https://www.reddit.com/r/LocalLLaMA2. Search for 'browser use' in the search bar3. Click search4. Call done"),llm=ChatOllama(# model='qwen2.5:32b-instruct-q4_K_M',diff --git a/examples/notebook/agent_browsing.ipynb b/examples/notebook/agent_browsing.ipynbindex 4d58a94eb..de5a9e97b 100644--- a/examples/notebook/agent_browsing.ipynb+++ b/examples/notebook/agent_browsing.ipynb@@ -1,760 +1,757 @@{- "nbformat": 4,- "nbformat_minor": 0,- "metadata": {- "colab": {- "provenance": []- },- "kernelspec": {- "name": "python3",- "display_name": "Python 3"- },- "language_info": {- "name": "python"- }+ "cells": [+ {+ "cell_type": "code",+ "execution_count": 2,+ "metadata": {+ "id": "ZRGlUb8O4fPV"+ },+ "outputs": [],+ "source": [+ "%pip install -U langgraph langchain_google_genai langchain_community langgraph-checkpoint-postgres openai langchain_groq"+ ]},- "cells": [- {- "cell_type": "code",- "execution_count": 2,- "metadata": {- "id": "ZRGlUb8O4fPV"- },- "outputs": [],- "source": [- "\n",- "%pip install -U langgraph langchain_google_genai langchain_community langgraph-checkpoint-postgres openai langchain_groq"- ]- },- {- "cell_type": "code",- "source": [- "%%capture --no-stderr\n",- "%pip install --upgrade --quiet playwright > /dev/null\n",- "%pip install --upgrade --quiet lxml browser-use langchain_openai"- ],- "metadata": {- "id": "cMfPUmHIxqTi"- },- "execution_count": 3,- "outputs": []- },- {- "cell_type": "code",- "source": [- "!playwright install"- ],- "metadata": {- "id": "kkZ7jVUOUV7Q"- },- "execution_count": null,- "outputs": []- },- {- "cell_type": "code",- "source": [- "!pip install \"anyio<4\""- ],- "metadata": {- "id": "-_T1MhnGUl2q"- },- "execution_count": null,- "outputs": []- },- {- "cell_type": "code",- "source": [- "# This import is required only for jupyter notebooks, since they have their own eventloop\n",- "import nest_asyncio\n",- "\n",- "nest_asyncio.apply()"- ],- "metadata": {- "id": "yARYirp1UhDR"- },- "execution_count": null,- "outputs": []- },- {- "cell_type": "code",- "source": [- "from langchain_openai import ChatOpenAI\n",- "from google.colab import userdata\n",- "\n",- "\n",- "llm = ChatOpenAI(model=\"gpt-4o-mini\", temperature=0, api_key=userdata.get('Open_api_key'))\n",- "\n",- "\n",- "\n"- ],- "metadata": {- "id": "jyVP10O_5Qck"- },- "execution_count": 4,- "outputs": []+ {+ "cell_type": "code",+ "execution_count": 3,+ "metadata": {+ "id": "cMfPUmHIxqTi"+ },+ "outputs": [],+ "source": [+ "%%capture --no-stderr\n",+ "%pip install --upgrade --quiet playwright > /dev/null\n",+ "%pip install --upgrade --quiet lxml browser-use langchain_openai"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "kkZ7jVUOUV7Q"+ },+ "outputs": [],+ "source": [+ "!playwright install"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "-_T1MhnGUl2q"+ },+ "outputs": [],+ "source": [+ "!pip install \"anyio<4\""+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {+ "id": "yARYirp1UhDR"+ },+ "outputs": [],+ "source": [+ "# This import is required only for jupyter notebooks, since they have their own eventloop\n",+ "import nest_asyncio\n",+ "\n",+ "nest_asyncio.apply()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "metadata": {+ "id": "jyVP10O_5Qck"+ },+ "outputs": [],+ "source": [+ "from google.colab import userdata\n",+ "from langchain_openai import ChatOpenAI\n",+ "\n",+ "llm = ChatOpenAI(model='gpt-4o-mini', temperature=0, api_key=userdata.get('Open_api_key'))"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 5,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "e9duizdv5cOH",+ "outputId": "a07b1702-d485-4641-c307-601e6ab34b9b"+ },+ "outputs": [{- "cell_type": "code",- "source": [- "llm.invoke(\"hi\")"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "e9duizdv5cOH",- "outputId": "a07b1702-d485-4641-c307-601e6ab34b9b"- },- "execution_count": 5,- "outputs": [- {- "output_type": "execute_result",- "data": {- "text/plain": [- "AIMessage(content='Hello! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 10, 'prompt_tokens': 8, 'total_tokens': 18, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_bd83329f63', 'finish_reason': 'stop', 'logprobs': None}, id='run-28a9088f-7539-412a-aa80-1663be40e74f-0', usage_metadata={'input_tokens': 8, 'output_tokens': 10, 'total_tokens': 18, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})"- ]- },- "metadata": {},- "execution_count": 5- }+ "data": {+ "text/plain": [+ "AIMessage(content='Hello! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 10, 'prompt_tokens': 8, 'total_tokens': 18, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_bd83329f63', 'finish_reason': 'stop', 'logprobs': None}, id='run-28a9088f-7539-412a-aa80-1663be40e74f-0', usage_metadata={'input_tokens': 8, 'output_tokens': 10, 'total_tokens': 18, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})"]+ },+ "execution_count": 5,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "llm.invoke('hi')"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 32,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "wS8ouhiVQ2dL",+ "outputId": "653879a8-b3ac-4178-edee-5cd834e3404a"+ },+ "outputs": [{- "cell_type": "code",- "source": [- "from browser_use import Agent, Browser\n",- "from browser_use import BrowserConfig\n",- "from langchain_openai import ChatOpenAI\n",- "import asyncio\n",- "\n",- "# Basic configuration for the browser\n",- "config = BrowserConfig(\n",- " headless=True, # Run in headless mode\n",- " # disable_security=True # Uncomment if you want to disable security\n",- ")\n",- "\n",- "# Initialize the browser with the specified configuration\n",- "browser = Browser(config=config)\n",- "\n",- "async def main():\n",- " # Initialize the agent with the task and language model\n",- " agent = Agent(\n",- " task=\"What is Langgraph\",\n",- " llm=llm, # Replace with your LLM configuration\n",- " browser=browser,\n",- " generate_gif=False # Disable GIF generation\n",- " )\n",- "\n",- " # Run the agent and get results asynchronously\n",- " result = await agent.run()\n",- "\n",- " # Process results token-wise\n",- " for action in result.action_results():\n",- " print(action.extracted_content,end=\"\\r\",flush=True)\n",- " print(\"\\n\\n\")\n",- " # if action.is_done:\n",- " # print(action.extracted_content)\n",- "\n",- " # Close the browser after completion\n",- " await browser.close()\n",- "\n",- "# Run the asynchronous main function\n",- "asyncio.run(main())\n"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "wS8ouhiVQ2dL",- "outputId": "653879a8-b3ac-4178-edee-5cd834e3404a"- },- "execution_count": 32,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "🔍 Searched for \"What is Langgraph?\" in Google\n",- "\n",- "\n",- "\n",- "\n",- "\n",- "📄 Extracted page as markdown\n",- ": \n",- "\n",- "\n",- "\n",- "\n",- "\n",- "## Controllable cognitive architecture for any task\n",- "\n",- "LangGraph's flexible framework supports diverse control flows – single agent,\n",- "multi-agent, hierarchical, sequential – and robustly handles realistic,\n",- "complex scenarios. \n",- " \n",- "Ensure reliability with easy-to-add moderation and quality loops that prevent\n",- "agents from veering off course. \n",- " \n",- "Use LangGraph Platform to templatize your cognitive architecture so that\n",- "tools, prompts, and models are easily configurable with LangGraph Platform\n",- "Assistants.\n",- "\n",- "[See the docs ](https://langchain-ai.github.io/langgraph/)\n",- "\n",- "## Designed for human-agent collaboration\n",- "\n",- "With built-in statefulness, LangGraph agents seamlessly collaborate with\n",- "humans by writing drafts for review and awaiting approval before acting.\n",- "Easily inspect the agent’s actions and \"time-travel\" to roll back and take a\n",- "different action to correct course.\n",- "\n",- "[Read a conceptual guide ](https://langchain-\n",- "ai.github.io/langgraph/concepts/agentic_concepts/#human-in-the-loop)\n",- "\n",- ".gif)\n",- "\n",- "\n",- "\n",- "## First class streaming support for better UX design\n",- "\n",- "Bridge user expectations and agent capabilities with native token-by-token\n",- "streaming and streaming of intermediate steps, helpful for showing agent\n",- "reasoning and actions back to the user as they happen. Use LangGraph\n",- "Platform's API to deliver dynamic and interactive user experiences.\n",- "\n",- "[Learn more ](https://langchain-ai.github.io/langgraph/how-tos/streaming-\n",- "tokens/)\n",- "\n",- "## Why choose LangGraph?\n",- "\n",- "### Control, moderate, and guide your agent’s actions.\n",- "\n",- "Prevent agents from veering off course and ensure reliability with easy-to-add\n",- "moderation and quality loops. Add human-in-the-loop to steer and approve agent\n",- "actions.\n",- "\n",- "### Expressive and customizable agent and multi-agent workflows.\n",- "\n",- "LangGraph’s low level abstractions offer the flexibility needed to create\n",- "sophisticated agents. Design diverse control flows – single, multi-agent,\n",- "hierarchical, sequential – all with one framework.\n",- "\n",- "### Persisted context for long-term interactions.\n",- "\n",- "With its stateful design, LangGraph stores conversation histories and session\n",- "data to maintain context over time and ensure smooth handoffs in agentic\n",- "systems.\n",- "\n",- "### First-class streaming support for better UX design.\n",- "\n",- "Bridge user expectations and agent capabilities with native token-by-token\n",- "streaming of intermediate steps, helpful for showing agent reasoning and\n",- "actions back to the user as they happen.\n",- "\n",- "## LangGraph Platform: \n",- "Deploy & develop agents at scale\n",- "\n",- "Craft agent-appropriate UXs using LangGraph Platform's APIs. Quickly deploy\n",- "and scale your agent with purpose-built infrastructure. Choose from multiple\n",- "deployment options.\n",- "\n",- "\n",- "\n",- "## Dynamic APIs for designing agent UXs.\n",- "\n",- "Craft personalized experiences with the long-term memory API to recall\n",- "information across conversation sessions. Expose, update, and rewind your\n",- "app's state for better user visibility, steering, and interaction. Kick off\n",- "long-running background jobs for research-style or multi-step work.\n",- "\n",- "[See the docs ](https://langchain-ai.github.io/langgraph/how-tos/streaming-\n",- "tokens/)\n",- "\n",- "\n",- "\n",- "## Fault-tolerant scalability.\n",- "\n",- "Handle large workloads gracefully with horizontally-scaling servers, task\n",- "queues, and built-in persistence. Enhance resilience with intelligent caching\n",- "and automated retries.\n",- "\n",- "[Learn more in the blog ](https://langchain-ai.github.io/langgraph/how-\n",- "tos/streaming-tokens/)\n",- "\n",- ".gif)\n",- "\n",- "## An end-to-end agent experience.\n",- "\n",- "Simplify prototyping, debugging, and sharing of agents in our visual LangGraph\n",- "Studio. Deploy your application with 1-click deploy with our SaaS offering or\n",- "within your own VPC. Then, monitor app performance with LangSmith.\n",- "\n",- "[Discover LangGraph Studio ](https://langchain-ai.github.io/langgraph/how-\n",- "tos/streaming-tokens/)\n",- "\n",- "\n",- "\n",- "## Introduction to LangGraph\n",- "\n",- "Learn the basics of LangGraph in this LangChain Academy Course. You'll learn\n",- "how to build agents that automate real-world tasks with LangGraph\n",- "orchestration.\n",- "\n",- "[Enroll for free](https://academy.langchain.com/courses/intro-to-\n",- "langgraph)[Book enterprise\n",- "training](https://airtable.com/appGjCAN6126Jm7K8/pagNAp7niHQzRH8zk/form)\n",- "\n",- "\n",- "\n",- "## Deploy agents at scale, monitor carefully, iterate boldly\n",- "\n",- "Design agent-driven user experiences with LangGraph Platform's APIs. Quickly\n",- "deploy and scale your application with infrastructure built for agents. Choose\n",- "from multiple deployment options.\n",- "\n",- "### Fault-tolerant scalability\n",- "\n",- "Handle large workloads gracefully with horizontally-scaling servers, task\n",- "queues, and built-in persistence. Enhance resilience with intelligent caching\n",- "and automated retries.\n",- "\n",- "### Dynamic APIs for designing agent experience\n",- "\n",- "Craft personalized user experiences with APIs featuring long-term memory to\n",- "recall information across conversation sessions. Track, update, and rewind\n",- "your app's state for easy human steering and interaction. Kick off long-\n",- "running background jobs for research-style or multi-step work.\n",- "\n",- "### Integrated developer experience\n",- "\n",- "Simplify prototyping, debugging, and sharing of agents in our visual LangGraph\n",- "Studio. Deploy your application with 1-click deploy with our SaaS offering or\n",- "within your own VPC. Then, monitor app performance with LangSmith.\n",- "\n",- "### Trusted by companies taking agency in AI innovation:\n",- "\n",- "LangGraph helps teams of all sizes, across all industries, from ambitious\n",- "startups to established enterprises.\n",- "\n",- "\n",- "\n",- "“LangChain is streets ahead with what they've put forward with LangGraph.\n",- "LangGraph sets the foundation for how we can build and scale AI workloads —\n",- "from conversational agents, complex task automation, to custom LLM-backed\n",- "experiences that 'just work'. The next chapter in building complex production-\n",- "ready features with LLMs is agentic, and with LangGraph and LangSmith,\n",- "LangChain delivers an out-of-the-box solution to iterate quickly, debug\n",- "immediately, and scale effortlessly.”\n",- "\n",- "\n",- "\n",- "Garrett Spong\n",- "\n",- "Principal SWE\n",- "\n",- "\n",- "\n",- "“LangGraph has been instrumental for our AI development. Its robust framework\n",- "for building stateful, multi-actor applications with LLMs has transformed how\n",- "we evaluate and optimize the performance of our AI guest-facing solutions.\n",- "LangGraph enables granular control over the agent's thought process, which has\n",- "empowered us to make data-driven and deliberate decisions to meet the diverse\n",- "needs of our guests.”\n",- "\n",- "\n",- "\n",- "Andres Torres\n",- "\n",- "Sr. Solutions Architect\n",- "\n",- "\n",- "\n",- "“It's easy to build the prototype of a coding agent, but deceptively hard to\n",- "improve its reliability. Replit wants to give a coding agent to millions of\n",- "users — reliability is our top priority, and will remain so for a long time.\n",- "LangGraph is giving us the control and ergonomics we need to build and ship\n",- "powerful coding agents.”\n",- "\n",- "“As Ally advances its exploration of Generative AI,\n",- "\n",- "%201.webp)\n",- "\n",- "Michele Catasta\n",- "\n",- "President\n",- "\n",- "\n",- "\n",- "“As Ally advances its exploration of Generative AI, our tech labs is excited\n",- "by LangGraph, the new library from LangChain, which is central to our\n",- "experiments with multi-actor agentic workflows. We are committed to deepening\n",- "our partnership with LangChain.”\n",- "\n",- "“As Ally advances its exploration of Generative AI,\n",- "\n",- "\n",- "\n",- "Sathish Muthukrishnan\n",- "\n",- "Chief Information, Data and Digital Officer\n",- "\n",- "\n",- "\n",- "“LangChain is streets ahead with what they've put forward with LangGraph.\n",- "LangGraph sets the foundation for how we can build and scale AI workloads —\n",- "from conversational agents, complex task automation, to custom LLM-backed\n",- "experiences that 'just work'. The next chapter in building complex production-\n",- "ready features with LLMs is agentic, and with LangGraph and LangSmith,\n",- "LangChain delivers an out-of-the-box solution to iterate quickly, debug\n",- "immediately, and scale effortlessly.”\n",- "\n",- "\n",- "\n",- "Garrett Spong\n",- "\n",- "Principal SWE\n",- "\n",- "\n",- "\n",- "“LangGraph has been instrumental for our AI development. Its robust framework\n",- "for building stateful, multi-actor applications with LLMs has transformed how\n",- "we evaluate and optimize the performance of our AI guest-facing solutions.\n",- "LangGraph enables granular control over the agent's thought process, which has\n",- "empowered us to make data-driven and deliberate decisions to meet the diverse\n",- "needs of our guests.”\n",- "\n",- "\n",- "\n",- "Andres Torres\n",- "\n",- "Sr. Solutions Architect\n",- "\n",- "\n",- "\n",- "“It's easy to build the prototype of a coding agent, but deceptively hard to\n",- "improve its reliability. Replit wants to give a coding agent to millions of\n",- "users — reliability is our top priority, and will remain so for a long time.\n",- "LangGraph is giving us the control and ergonomics we need to build and ship\n",- "powerful coding agents.”\n",- "\n",- "“As Ally advances its exploration of Generative AI,\n",- "\n",- "%201.webp)\n",- "\n",- "Michele Catasta\n",- "\n",- "President\n",- "\n",- "\n",- "\n",- "“As Ally advances its exploration of Generative AI, our tech labs is excited\n",- "by LangGraph, the new library from LangChain, which is central to our\n",- "experiments with multi-actor agentic workflows. We are committed to deepening\n",- "our partnership with LangChain.”\n",- "\n",- "“As Ally advances its exploration of Generative AI,\n",- "\n",- "\n",- "\n",- "Sathish Muthukrishnan\n",- "\n",- "Chief Information, Data and Digital Officer\n",- "\n",- "## LangGraph FAQs\n",- "\n",- "Do I need to use LangChain to use LangGraph? What’s the difference?\n",- "\n",- "No. LangGraph is an orchestration framework for complex agentic systems and is\n",- "more low-level and controllable than LangChain agents. LangChain provides a\n",- "standard interface to interact with models and other components, useful for\n",- "straight-forward chains and retrieval flows.\n",- "\n",- "How is LangGraph different from other agent frameworks?\n",- "\n",- "Other agentic frameworks can work for simple, generic tasks but fall short for\n",- "complex tasks bespoke to a company’s needs. LangGraph provides a more\n",- "expressive framework to handle companies’ unique tasks without restricting\n",- "users to a single black-box cognitive architecture.\n",- "\n",- "Does LangGraph impact the performance of my app?\n",- "\n",- "LangGraph will not add any overhead to your code and is specifically designed\n",- "with streaming workflows in mind.\n",- "\n",- "Is LangGraph open source? Is it free?\n",- "\n",- "Yes. LangGraph is an MIT-licensed open-source library and is free to use.\n",- "\n",- "How are LangGraph and LangGraph Platform different?\n",- "\n",- "LangGraph is a stateful, orchestration framework that brings added control to\n",- "agent workflows. LangGraph Platform is a service for deploying and scaling\n",- "LangGraph applications, with an opinionated API for building agent UXs, plus\n",- "an integrated developer studio.\n",- "\n",- "LangGraph (open source)\n",- "\n",- "LangGraph Platform\n",- "\n",- "Features\n",- "\n",- "Stateful orchestration framework for agentic applications\n",- "\n",- "Scalable infrastructure for deploying LangGraph applications \n",- "\n",- "Python and JavaScript\n",- "\n",- "Python and JavaScript \n",- "\n",- "None\n",- "\n",- "Yes - useful for retrieving & updating state or long-term memory, or creating\n",- "a configurable assistant \n",- "\n",- "Basic\n",- "\n",- "Dedicated mode for token-by-token messages \n",- "\n",- "Community contributed\n",- "\n",- "Supported out-of-the-box \n",- "\n",- "Self-managed\n",- "\n",- "Managed Postgres with efficient storage \n",- "\n",- "Self-managed\n",- "\n",- "\\- Cloud SaaS \n",- "\\- Free self-hosted \n",- "\\- Enterprise \n",- "(BYOC or paid self-hosted) \n",- "\n",- "Self-managed\n",- "\n",- "Auto-scaling of task queues and servers \n",- "\n",- "Self-managed\n",- "\n",- "Automated retries \n",- "\n",- "Simple threading\n",- "\n",- "Supports double-texting \n",- "\n",- "None\n",- "\n",- "Cron scheduling \n",- "\n",- "None\n",- "\n",- "Integrated with LangSmith for observability \n",- "\n",- "LangGraph Studio for Desktop\n",- "\n",- "LangGraph Studio for Desktop & Cloud \n",- "\n",- "What are my deployment options for LangGraph Platform?\n",- "\n",- "We currently have the following deployment options for LangGraph applications: \n",- " \n",- "**Self-Hosted Lite** : A free (up to 1M nodes executed), limited version of\n",- "LangGraph Platform that you can run locally or in a self-hosted manner. This\n",- "version requires a LangSmith API key and logs all usage to LangSmith. Fewer\n",- "features are available than in paid plans. \n",- "**Cloud SaaS:** Fully managed and hosted as part of LangSmith, with automatic\n",- "updates and zero maintenance. \n",- "**Bring Your Own Cloud (BYOC):** Deploy LangGraph Platform within your VPC,\n",- "provisioned and run as a service. Keep data in your environment while\n",- "outsourcing the management of the service. \n",- "**Self-Hosted Enterprise:** Deploy LangGraph entirely on your own\n",- "infrastructure.\n",- "\n",- "Is LangGraph Platform open source?\n",- "\n",- "No. LangGraph Platform is proprietary software. \n",- " \n",- "There is a free, self-hosted version of LangGraph Platform with access to\n",- "basic features. The Cloud SaaS deployment option is free while in beta, but\n",- "will eventually be a paid service. We will always give ample notice before\n",- "charging for a service and reward our early adopters with preferential\n",- "pricing. The Bring Your Own Cloud (BYOC) and Self-Hosted Enterprise options\n",- "are also paid services. [Contact our sales team](/contact-sales) to learn\n",- "more. \n",- " \n",- "For more information, see our [LangGraph Platform pricing page](/pricing-\n",- "langgraph-platform).\n",- "\n",- "## Ready to start shipping reliable GenAI apps faster?\n",- "\n",- "Get started with LangChain, LangSmith, and LangGraph to enhance your LLM app\n",- "development, from prototype to production.\n",- "\n",- "[Contact Us](/contact-sales)[Sign Up](https://smith.langchain.com/)\n",- "\n",- "\n",- "\n",- "\n",- "\n",- "LangGraph is a flexible framework designed for building and scaling agentic applications. It allows for complex task handling and human-agent collaboration, supporting various control flows such as single-agent, multi-agent, hierarchical, and sequential. Key features include:\n",- "\n",- "- **Statefulness**: LangGraph agents maintain context over time, enabling smooth interactions.\n",- "- **Streaming Support**: It provides native token-by-token streaming for better user experience.\n",- "- **Moderation and Quality Loops**: These features ensure agents remain reliable and on course.\n",- "- **Dynamic APIs**: LangGraph offers APIs for crafting personalized user experiences and managing long-term memory.\n",- "- **Deployment Options**: It supports various deployment methods, including self-hosted and cloud solutions.\n",- "\n",- "\n",- "\n",- "\n"- ]- }- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "🔍 Searched for \"What is Langgraph?\" in Google\n",+ "\n",+ "\n",+ "\n",+ "\n",+ "\n",+ "📄 Extracted page as markdown\n",+ ": \n",+ "\n",+ "\n",+ "\n",+ "\n",+ "\n",+ "## Controllable cognitive architecture for any task\n",+ "\n",+ "LangGraph's flexible framework supports diverse control flows – single agent,\n",+ "multi-agent, hierarchical, sequential – and robustly handles realistic,\n",+ "complex scenarios. \n",+ " \n",+ "Ensure reliability with easy-to-add moderation and quality loops that prevent\n",+ "agents from veering off course. \n",+ " \n",+ "Use LangGraph Platform to templatize your cognitive architecture so that\n",+ "tools, prompts, and models are easily configurable with LangGraph Platform\n",+ "Assistants.\n",+ "\n",+ "[See the docs ](https://langchain-ai.github.io/langgraph/)\n",+ "\n",+ "## Designed for human-agent collaboration\n",+ "\n",+ "With built-in statefulness, LangGraph agents seamlessly collaborate with\n",+ "humans by writing drafts for review and awaiting approval before acting.\n",+ "Easily inspect the agent’s actions and \"time-travel\" to roll back and take a\n",+ "different action to correct course.\n",+ "\n",+ "[Read a conceptual guide ](https://langchain-\n",+ "ai.github.io/langgraph/concepts/agentic_concepts/#human-in-the-loop)\n",+ "\n",+ ".gif)\n",+ "\n",+ "\n",+ "\n",+ "## First class streaming support for better UX design\n",+ "\n",+ "Bridge user expectations and agent capabilities with native token-by-token\n",+ "streaming and streaming of intermediate steps, helpful for showing agent\n",+ "reasoning and actions back to the user as they happen. Use LangGraph\n",+ "Platform's API to deliver dynamic and interactive user experiences.\n",+ "\n",+ "[Learn more ](https://langchain-ai.github.io/langgraph/how-tos/streaming-\n",+ "tokens/)\n",+ "\n",+ "## Why choose LangGraph?\n",+ "\n",+ "### Control, moderate, and guide your agent’s actions.\n",+ "\n",+ "Prevent agents from veering off course and ensure reliability with easy-to-add\n",+ "moderation and quality loops. Add human-in-the-loop to steer and approve agent\n",+ "actions.\n",+ "\n",+ "### Expressive and customizable agent and multi-agent workflows.\n",+ "\n",+ "LangGraph’s low level abstractions offer the flexibility needed to create\n",+ "sophisticated agents. Design diverse control flows – single, multi-agent,\n",+ "hierarchical, sequential – all with one framework.\n",+ "\n",+ "### Persisted context for long-term interactions.\n",+ "\n",+ "With its stateful design, LangGraph stores conversation histories and session\n",+ "data to maintain context over time and ensure smooth handoffs in agentic\n",+ "systems.\n",+ "\n",+ "### First-class streaming support for better UX design.\n",+ "\n",+ "Bridge user expectations and agent capabilities with native token-by-token\n",+ "streaming of intermediate steps, helpful for showing agent reasoning and\n",+ "actions back to the user as they happen.\n",+ "\n",+ "## LangGraph Platform: \n",+ "Deploy & develop agents at scale\n",+ "\n",+ "Craft agent-appropriate UXs using LangGraph Platform's APIs. Quickly deploy\n",+ "and scale your agent with purpose-built infrastructure. Choose from multiple\n",+ "deployment options.\n",+ "\n",+ "\n",+ "\n",+ "## Dynamic APIs for designing agent UXs.\n",+ "\n",+ "Craft personalized experiences with the long-term memory API to recall\n",+ "information across conversation sessions. Expose, update, and rewind your\n",+ "app's state for better user visibility, steering, and interaction. Kick off\n",+ "long-running background jobs for research-style or multi-step work.\n",+ "\n",+ "[See the docs ](https://langchain-ai.github.io/langgraph/how-tos/streaming-\n",+ "tokens/)\n",+ "\n",+ "\n",+ "\n",+ "## Fault-tolerant scalability.\n",+ "\n",+ "Handle large workloads gracefully with horizontally-scaling servers, task\n",+ "queues, and built-in persistence. Enhance resilience with intelligent caching\n",+ "and automated retries.\n",+ "\n",+ "[Learn more in the blog ](https://langchain-ai.github.io/langgraph/how-\n",+ "tos/streaming-tokens/)\n",+ "\n",+ ".gif)\n",+ "\n",+ "## An end-to-end agent experience.\n",+ "\n",+ "Simplify prototyping, debugging, and sharing of agents in our visual LangGraph\n",+ "Studio. Deploy your application with 1-click deploy with our SaaS offering or\n",+ "within your own VPC. Then, monitor app performance with LangSmith.\n",+ "\n",+ "[Discover LangGraph Studio ](https://langchain-ai.github.io/langgraph/how-\n",+ "tos/streaming-tokens/)\n",+ "\n",+ "\n",+ "\n",+ "## Introduction to LangGraph\n",+ "\n",+ "Learn the basics of LangGraph in this LangChain Academy Course. You'll learn\n",+ "how to build agents that automate real-world tasks with LangGraph\n",+ "orchestration.\n",+ "\n",+ "[Enroll for free](https://academy.langchain.com/courses/intro-to-\n",+ "langgraph)[Book enterprise\n",+ "training](https://airtable.com/appGjCAN6126Jm7K8/pagNAp7niHQzRH8zk/form)\n",+ "\n",+ "\n",+ "\n",+ "## Deploy agents at scale, monitor carefully, iterate boldly\n",+ "\n",+ "Design agent-driven user experiences with LangGraph Platform's APIs. Quickly\n",+ "deploy and scale your application with infrastructure built for agents. Choose\n",+ "from multiple deployment options.\n",+ "\n",+ "### Fault-tolerant scalability\n",+ "\n",+ "Handle large workloads gracefully with horizontally-scaling servers, task\n",+ "queues, and built-in persistence. Enhance resilience with intelligent caching\n",+ "and automated retries.\n",+ "\n",+ "### Dynamic APIs for designing agent experience\n",+ "\n",+ "Craft personalized user experiences with APIs featuring long-term memory to\n",+ "recall information across conversation sessions. Track, update, and rewind\n",+ "your app's state for easy human steering and interaction. Kick off long-\n",+ "running background jobs for research-style or multi-step work.\n",+ "\n",+ "### Integrated developer experience\n",+ "\n",+ "Simplify prototyping, debugging, and sharing of agents in our visual LangGraph\n",+ "Studio. Deploy your application with 1-click deploy with our SaaS offering or\n",+ "within your own VPC. Then, monitor app performance with LangSmith.\n",+ "\n",+ "### Trusted by companies taking agency in AI innovation:\n",+ "\n",+ "LangGraph helps teams of all sizes, across all industries, from ambitious\n",+ "startups to established enterprises.\n",+ "\n",+ "\n",+ "\n",+ "“LangChain is streets ahead with what they've put forward with LangGraph.\n",+ "LangGraph sets the foundation for how we can build and scale AI workloads —\n",+ "from conversational agents, complex task automation, to custom LLM-backed\n",+ "experiences that 'just work'. The next chapter in building complex production-\n",+ "ready features with LLMs is agentic, and with LangGraph and LangSmith,\n",+ "LangChain delivers an out-of-the-box solution to iterate quickly, debug\n",+ "immediately, and scale effortlessly.”\n",+ "\n",+ "\n",+ "\n",+ "Garrett Spong\n",+ "\n",+ "Principal SWE\n",+ "\n",+ "\n",+ "\n",+ "“LangGraph has been instrumental for our AI development. Its robust framework\n",+ "for building stateful, multi-actor applications with LLMs has transformed how\n",+ "we evaluate and optimize the performance of our AI guest-facing solutions.\n",+ "LangGraph enables granular control over the agent's thought process, which has\n",+ "empowered us to make data-driven and deliberate decisions to meet the diverse\n",+ "needs of our guests.”\n",+ "\n",+ "\n",+ "\n",+ "Andres Torres\n",+ "\n",+ "Sr. Solutions Architect\n",+ "\n",+ "\n",+ "\n",+ "“It's easy to build the prototype of a coding agent, but deceptively hard to\n",+ "improve its reliability. Replit wants to give a coding agent to millions of\n",+ "users — reliability is our top priority, and will remain so for a long time.\n",+ "LangGraph is giving us the control and ergonomics we need to build and ship\n",+ "powerful coding agents.”\n",+ "\n",+ "“As Ally advances its exploration of Generative AI,\n",+ "\n",+ "%201.webp)\n",+ "\n",+ "Michele Catasta\n",+ "\n",+ "President\n",+ "\n",+ "\n",+ "\n",+ "“As Ally advances its exploration of Generative AI, our tech labs is excited\n",+ "by LangGraph, the new library from LangChain, which is central to our\n",+ "experiments with multi-actor agentic workflows. We are committed to deepening\n",+ "our partnership with LangChain.”\n",+ "\n",+ "“As Ally advances its exploration of Generative AI,\n",+ "\n",+ "\n",+ "\n",+ "Sathish Muthukrishnan\n",+ "\n",+ "Chief Information, Data and Digital Officer\n",+ "\n",+ "\n",+ "\n",+ "“LangChain is streets ahead with what they've put forward with LangGraph.\n",+ "LangGraph sets the foundation for how we can build and scale AI workloads —\n",+ "from conversational agents, complex task automation, to custom LLM-backed\n",+ "experiences that 'just work'. The next chapter in building complex production-\n",+ "ready features with LLMs is agentic, and with LangGraph and LangSmith,\n",+ "LangChain delivers an out-of-the-box solution to iterate quickly, debug\n",+ "immediately, and scale effortlessly.”\n",+ "\n",+ "\n",+ "\n",+ "Garrett Spong\n",+ "\n",+ "Principal SWE\n",+ "\n",+ "\n",+ "\n",+ "“LangGraph has been instrumental for our AI development. Its robust framework\n",+ "for building stateful, multi-actor applications with LLMs has transformed how\n",+ "we evaluate and optimize the performance of our AI guest-facing solutions.\n",+ "LangGraph enables granular control over the agent's thought process, which has\n",+ "empowered us to make data-driven and deliberate decisions to meet the diverse\n",+ "needs of our guests.”\n",+ "\n",+ "\n",+ "\n",+ "Andres Torres\n",+ "\n",+ "Sr. Solutions Architect\n",+ "\n",+ "\n",+ "\n",+ "“It's easy to build the prototype of a coding agent, but deceptively hard to\n",+ "improve its reliability. Replit wants to give a coding agent to millions of\n",+ "users — reliability is our top priority, and will remain so for a long time.\n",+ "LangGraph is giving us the control and ergonomics we need to build and ship\n",+ "powerful coding agents.”\n",+ "\n",+ "“As Ally advances its exploration of Generative AI,\n",+ "\n",+ "%201.webp)\n",+ "\n",+ "Michele Catasta\n",+ "\n",+ "President\n",+ "\n",+ "\n",+ "\n",+ "“As Ally advances its exploration of Generative AI, our tech labs is excited\n",+ "by LangGraph, the new library from LangChain, which is central to our\n",+ "experiments with multi-actor agentic workflows. We are committed to deepening\n",+ "our partnership with LangChain.”\n",+ "\n",+ "“As Ally advances its exploration of Generative AI,\n",+ "\n",+ "\n",+ "\n",+ "Sathish Muthukrishnan\n",+ "\n",+ "Chief Information, Data and Digital Officer\n",+ "\n",+ "## LangGraph FAQs\n",+ "\n",+ "Do I need to use LangChain to use LangGraph? What’s the difference?\n",+ "\n",+ "No. LangGraph is an orchestration framework for complex agentic systems and is\n",+ "more low-level and controllable than LangChain agents. LangChain provides a\n",+ "standard interface to interact with models and other components, useful for\n",+ "straight-forward chains and retrieval flows.\n",+ "\n",+ "How is LangGraph different from other agent frameworks?\n",+ "\n",+ "Other agentic frameworks can work for simple, generic tasks but fall short for\n",+ "complex tasks bespoke to a company’s needs. LangGraph provides a more\n",+ "expressive framework to handle companies’ unique tasks without restricting\n",+ "users to a single black-box cognitive architecture.\n",+ "\n",+ "Does LangGraph impact the performance of my app?\n",+ "\n",+ "LangGraph will not add any overhead to your code and is specifically designed\n",+ "with streaming workflows in mind.\n",+ "\n",+ "Is LangGraph open source? Is it free?\n",+ "\n",+ "Yes. LangGraph is an MIT-licensed open-source library and is free to use.\n",+ "\n",+ "How are LangGraph and LangGraph Platform different?\n",+ "\n",+ "LangGraph is a stateful, orchestration framework that brings added control to\n",+ "agent workflows. LangGraph Platform is a service for deploying and scaling\n",+ "LangGraph applications, with an opinionated API for building agent UXs, plus\n",+ "an integrated developer studio.\n",+ "\n",+ "LangGraph (open source)\n",+ "\n",+ "LangGraph Platform\n",+ "\n",+ "Features\n",+ "\n",+ "Stateful orchestration framework for agentic applications\n",+ "\n",+ "Scalable infrastructure for deploying LangGraph applications \n",+ "\n",+ "Python and JavaScript\n",+ "\n",+ "Python and JavaScript \n",+ "\n",+ "None\n",+ "\n",+ "Yes - useful for retrieving & updating state or long-term memory, or creating\n",+ "a configurable assistant \n",+ "\n",+ "Basic\n",+ "\n",+ "Dedicated mode for token-by-token messages \n",+ "\n",+ "Community contributed\n",+ "\n",+ "Supported out-of-the-box \n",+ "\n",+ "Self-managed\n",+ "\n",+ "Managed Postgres with efficient storage \n",+ "\n",+ "Self-managed\n",+ "\n",+ "\\- Cloud SaaS \n",+ "\\- Free self-hosted \n",+ "\\- Enterprise \n",+ "(BYOC or paid self-hosted) \n",+ "\n",+ "Self-managed\n",+ "\n",+ "Auto-scaling of task queues and servers \n",+ "\n",+ "Self-managed\n",+ "\n",+ "Automated retries \n",+ "\n",+ "Simple threading\n",+ "\n",+ "Supports double-texting \n",+ "\n",+ "None\n",+ "\n",+ "Cron scheduling \n",+ "\n",+ "None\n",+ "\n",+ "Integrated with LangSmith for observability \n",+ "\n",+ "LangGraph Studio for Desktop\n",+ "\n",+ "LangGraph Studio for Desktop & Cloud \n",+ "\n",+ "What are my deployment options for LangGraph Platform?\n",+ "\n",+ "We currently have the following deployment options for LangGraph applications: \n",+ " \n",+ "**Self-Hosted Lite** : A free (up to 1M nodes executed), limited version of\n",+ "LangGraph Platform that you can run locally or in a self-hosted manner. This\n",+ "version requires a LangSmith API key and logs all usage to LangSmith. Fewer\n",+ "features are available than in paid plans. \n",+ "**Cloud SaaS:** Fully managed and hosted as part of LangSmith, with automatic\n",+ "updates and zero maintenance. \n",+ "**Bring Your Own Cloud (BYOC):** Deploy LangGraph Platform within your VPC,\n",+ "provisioned and run as a service. Keep data in your environment while\n",+ "outsourcing the management of the service. \n",+ "**Self-Hosted Enterprise:** Deploy LangGraph entirely on your own\n",+ "infrastructure.\n",+ "\n",+ "Is LangGraph Platform open source?\n",+ "\n",+ "No. LangGraph Platform is proprietary software. \n",+ " \n",+ "There is a free, self-hosted version of LangGraph Platform with access to\n",+ "basic features. The Cloud SaaS deployment option is free while in beta, but\n",+ "will eventually be a paid service. We will always give ample notice before\n",+ "charging for a service and reward our early adopters with preferential\n",+ "pricing. The Bring Your Own Cloud (BYOC) and Self-Hosted Enterprise options\n",+ "are also paid services. [Contact our sales team](/contact-sales) to learn\n",+ "more. \n",+ " \n",+ "For more information, see our [LangGraph Platform pricing page](/pricing-\n",+ "langgraph-platform).\n",+ "\n",+ "## Ready to start shipping reliable GenAI apps faster?\n",+ "\n",+ "Get started with LangChain, LangSmith, and LangGraph to enhance your LLM app\n",+ "development, from prototype to production.\n",+ "\n",+ "[Contact Us](/contact-sales)[Sign Up](https://smith.langchain.com/)\n",+ "\n",+ "\n",+ "\n",+ "\n",+ "\n",+ "LangGraph is a flexible framework designed for building and scaling agentic applications. It allows for complex task handling and human-agent collaboration, supporting various control flows such as single-agent, multi-agent, hierarchical, and sequential. Key features include:\n",+ "\n",+ "- **Statefulness**: LangGraph agents maintain context over time, enabling smooth interactions.\n",+ "- **Streaming Support**: It provides native token-by-token streaming for better user experience.\n",+ "- **Moderation and Quality Loops**: These features ensure agents remain reliable and on course.\n",+ "- **Dynamic APIs**: LangGraph offers APIs for crafting personalized user experiences and managing long-term memory.\n",+ "- **Deployment Options**: It supports various deployment methods, including self-hosted and cloud solutions.\n",+ "\n",+ "\n",+ "\n",+ "\n"+ ]+ }+ ],+ "source": [+ "import asyncio\n",+ "\n",+ "from langchain_openai import ChatOpenAI\n",+ "\n",+ "from browser_use import Agent, Browser, BrowserConfig\n",+ "\n",+ "# Basic configuration for the browser\n",+ "config = BrowserConfig(\n",+ "\theadless=True, # Run in headless mode\n",+ "\t# disable_security=True # Uncomment if you want to disable security\n",+ ")\n",+ "\n",+ "# Initialize the browser with the specified configuration\n",+ "browser = Browser(config=config)\n",+ "\n",+ "\n",+ "async def main():\n",+ "\t# Initialize the agent with the task and language model\n",+ "\tagent = Agent(\n",+ "\t\ttask='What is Langgraph',\n",+ "\t\tllm=llm, # Replace with your LLM configuration\n",+ "\t\tbrowser=browser,\n",+ "\t\tgenerate_gif=False, # Disable GIF generation\n",+ "\t)\n",+ "\n",+ "\t# Run the agent and get results asynchronously\n",+ "\tresult = await agent.run()\n",+ "\n",+ "\t# Process results token-wise\n",+ "\tfor action in result.action_results():\n",+ "\t\tprint(action.extracted_content, end='\\r', flush=True)\n",+ "\t\tprint('\\n\\n')\n",+ "\t\t# if action.is_done:\n",+ "\t\t# print(action.extracted_content)\n",+ "\n",+ "\t# Close the browser after completion\n",+ "\tawait browser.close()\n",+ "\n",+ "\n",+ "# Run the asynchronous main function\n",+ "asyncio.run(main())"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 11,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "TFK-fNoLDFcF",+ "outputId": "d78fbeae-c8f0-4c26-e0e3-7a0a683d3fc1"+ },+ "outputs": [{- "cell_type": "code",- "source": [- "from browser_use import Agent, Browser\n",- "from playwright.async_api import BrowserContext\n",- "from browser_use import BrowserConfig\n",- "from langchain_openai import ChatOpenAI\n",- "# from browser_use import Agent\n",- "import asyncio\n",- "# Basic configuration\n",- "config = BrowserConfig(\n",- " headless=True,\n",- "\n",- " # disable_security=True\n",- ")\n",- "# Reuse existing browser\n",- "browser = Browser(config=config)\n",- "# async def main():\n",- "agent = Agent(\n",- " task=\"what is langchain\",\n",- " llm=llm,\n",- " browser=browser,\n",- " generate_gif = False # Browser instance will be reused\n",- " )\n",- "\n",- "result = await agent.run()\n",- "print(result)\n",- "# Manually close the browser\n",- "# asyncio.run(main())\n",- "await browser.close()\n"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "TFK-fNoLDFcF",- "outputId": "d78fbeae-c8f0-4c26-e0e3-7a0a683d3fc1"- },- "execution_count": 11,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "AgentHistoryList(all_results=[ActionResult(is_done=False, extracted_content='🔍 Searched for \"What is LangChain?\" in Google', error=None, include_in_memory=True), ActionResult(is_done=False, extracted_content=\"📄 Extracted page as markdown\\n: # Filters and Topics\\n\\n[All](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&source=lnms&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ0pQJegQIEhAB)\\n\\n[Images](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&udm=2&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQtKgLegQIExAB)\\n\\n[Videos](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&udm=7&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQtKgLegQIERAB)\\n\\n[Forums](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&udm=18&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQs6gLegQIDxAB)\\n\\nWeb\\n\\n[Flights](/travel/flights?sca_esv=4c6b8dc13bab3e46&output=search&q=What+is+LangChain%3F&source=lnms&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&ved=1t:200715&ictx=111)\\n\\n[Finance](/finance?sca_esv=4c6b8dc13bab3e46&output=search&q=What+is+LangChain%3F&source=lnms&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ0pQJegQIDBAB)\\n\\nMore\\n\\n[Books](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&udm=36&source=lnms&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ0pQJegQINxAB)\\n\\n[News](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&tbm=nws&source=lnms&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ0pQJegQINhAB)\\n\\n[Shopping](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&udm=28&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&ved=1t:220175&ictx=111)\\n\\nTools\\n\\nAny time\\n\\nAny time\\n\\n[Past\\nhour](/search?q=What+is+LangChain%3F&sca_esv=4c6b8dc13bab3e46&udm=14&source=lnt&tbs=qdr:h&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQpwV6BAgGEAc)\\n\\n[Past 24\\nhours](/search?q=What+is+LangChain%3F&sca_esv=4c6b8dc13bab3e46&udm=14&source=lnt&tbs=qdr:d&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQpwV6BAgGEAg)\\n\\n[Past\\nweek](/search?q=What+is+LangChain%3F&sca_esv=4c6b8dc13bab3e46&udm=14&source=lnt&tbs=qdr:w&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQpwV6BAgGEAk)\\n\\n[Past\\nmonth](/search?q=What+is+LangChain%3F&sca_esv=4c6b8dc13bab3e46&udm=14&source=lnt&tbs=qdr:m&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQpwV6BAgGEAo)\\n\\n[Past\\nyear](/search?q=What+is+LangChain%3F&sca_esv=4c6b8dc13bab3e46&udm=14&source=lnt&tbs=qdr:y&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQpwV6BAgGEAs)\\n\\nCustom range...\\n\\nCustom date range\\n\\nFromTo\\n\\nGo\\n\\nAll results\\n\\nAll results\\n\\n[Verbatim](/search?q=What+is+LangChain%3F&sca_esv=4c6b8dc13bab3e46&udm=14&source=lnt&tbs=li:1&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQpwV6BAgGEBM)\\n\\n[ Advanced Search\\n](https://www.google.com/advanced_search?q=What+is+LangChain%3F&udm=14)\\n\\nCtrl+Shift+X to select\\n\\n\\n\\n# Search settings\\n\\n[Search CustomizationOff](/history/optout?hl=en)\\n\\n[SafeSearchBlurring\\non](/safesearch?prev=https://www.google.com/search?q%3DWhat%2Bis%2BLangChain?%26udm%3D14&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8JsIegQIChAH)\\n\\n[LanguageEnglish](/preferences?lang=1&hl=en&prev=https://www.google.com/search?q%3DWhat%2Bis%2BLangChain%253F%26sca_esv%3D4c6b8dc13bab3e46%26udm%3D14#languages)\\n\\n[Dark themeDevice\\ndefault](/setprefs?hl=en&prev=https://www.google.com/search?q%3DWhat%2Bis%2BLangChain?%26udm%3D14%26pccc%3D1&sig=0_jfSkJcafppJyKAIkCWZpHFXzfrs%3D&cs=2&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQqsEHegQIChAJ&ictx=1)\\n\\n[More\\nsettings](/preferences?hl=en&prev=https://www.google.com/search?q%3DWhat%2Bis%2BLangChain%253F%26sca_esv%3D4c6b8dc13bab3e46%26udm%3D14)\\n\\nSend feedback\\n\\n[Help](https://support.google.com/websearch/?p=dsrp_search_hc&hl=en) •\\n[Privacy](https://policies.google.com/privacy?hl=en&fg=1) •\\n[Terms](https://policies.google.com/terms?hl=en&fg=1)\\n\\n# Search Results\\n\\n[ \\nLangChainLangChainhttps://www.langchain.com](https://www.langchain.com/)\\n\\nLangChain\\n\\nhttps://www.langchain.com\\n\\n _LangChain_ is a composable framework to build with LLMs. LangGraph is the\\norchestration framework for controllable agentic workflows. Run.\\n\\n\\u200e[Docs](https://python.langchain.com/docs/introduction/) ·\\n\\u200e[Products](https://www.langchain.com/langchain) · \\u200e[LangChain\\nAcademy](https://academy.langchain.com/) · \\u200e[Join the LangChain\\nCommunity](https://www.langchain.com/join-community)\\n\\n[ \\nWhat is\\nLangChain?Amazon\\nWeb Serviceshttps://aws.amazon.com › ... › Generative\\nAI](https://aws.amazon.com/what-is/langchain/)\\n\\nAmazon Web Services\\n\\nhttps://aws.amazon.com › ... › Generative AI\\n\\nLangChain _provides AI developers with tools to connect language models with\\nexternal data sources_. It is open-source and supported by an active\\ncommunity.\\n\\n[ \\nWhat Is LangChain and How to Use It: A\\nGuideTechTargethttps://www.techtarget.com\\n› definition ›\\nLangChain](https://www.techtarget.com/searchenterpriseai/definition/LangChain)\\n\\nTechTarget\\n\\nhttps://www.techtarget.com › definition › LangChain\\n\\n _LangChain is an open source framework_ that enables software developers\\nworking with artificial intelligence (AI) and its machine learning subset to\\ncombine ...\\n\\n[ \\nIntroduction | 🦜️ LangChainLangChainhttps://python.langchain.com › docs › introduction](https://python.langchain.com/docs/introduction/)\\n\\nLangChain\\n\\nhttps://python.langchain.com › docs › introduction\\n\\n _LangChain_ is a framework for developing applications powered by large\\nlanguage models (LLMs). LangChain simplifies every stage of the LLM\\napplication lifecycle.\\n\\n\\u200e[Introduction](https://python.langchain.com/v0.1/docs/get_started/introduction/)\\n·\\n\\u200e[Langchain.agents...](https://api.python.langchain.com/en/latest/agents/langchain.agents.tool_calling_agent.base.create_tool_calling_agent.html)\\n· \\u200e[LangChain v0.3](https://python.langchain.com/docs/versions/v0_3/) ·\\n\\u200e[Langchain_core.tools.](https://api.python.langchain.com/en/latest/tools/langchain_core.tools.tool.html)\\n\\n[ \\nWhat Is\\nLangChain?IBMhttps://www.ibm.com\\n› think › topics › langchain](https://www.ibm.com/think/topics/langchain)\\n\\nIBM\\n\\nhttps://www.ibm.com › think › topics › langchain\\n\\nLangChain is essentially _a library of abstractions for Python and Javascript_\\n, representing common steps and concepts necessary to work with language\\nmodels.\\n\\n[ \\nWhat is\\nLangChain?YouTube\\n· IBM Technology287.6K+ views · 10 months\\nago](https://www.youtube.com/watch?v=1bUy-1hGZpI)\\n\\nYouTube · IBM Technology\\n\\n287.6K+ views · 10 months ago\\n\\nLang chain is _an open-source orchestration framework_ for the development of\\napplications that use large language models.\\n\\n[ \\nWhat is Langchain and why should I care as a\\ndeveloper?Medium\\n· Logan Kilpatrick370+ likes · 1 year ago](https://medium.com/around-the-\\nprompt/what-is-langchain-and-why-should-i-care-as-a-developer-b2d952c42b28)\\n\\nMedium · Logan Kilpatrick\\n\\n370+ likes · 1 year ago\\n\\n _Langchain_ makes creating agents using large language models simple through\\ntheir agents API. Developers can use OpenAI functions or other means ...\\n\\n[ \\nLangChainWikipediahttps://en.wikipedia.org\\n› wiki › LangChain](https://en.wikipedia.org/wiki/LangChain)\\n\\nWikipedia\\n\\nhttps://en.wikipedia.org › wiki › LangChain\\n\\nLangChain is a software framework that helps facilitate the integration of\\nlarge language models (LLMs) into applications.\\n\\n\\u200e[History](https://en.wikipedia.org/wiki/LangChain#History) ·\\n\\u200e[Capabilities](https://en.wikipedia.org/wiki/LangChain#Capabilities) ·\\n\\u200e[LangChain tools](https://en.wikipedia.org/wiki/LangChain#LangChain_tools)\\n\\n[ \\nWhat Is LangChain? A Complete Comprehensive\\nOverviewDataStaxhttps://www.datastax.com\\n› guides › what-is-langchain](https://www.datastax.com/guides/what-is-\\nlangchain)\\n\\nDataStax\\n\\nhttps://www.datastax.com › guides › what-is-langchain\\n\\nNov 9, 2023 — LangChain is _a Python framework designed to streamline AI\\napplication development_ , focusing on real-time data processing and\\nintegration with ...\\n\\n[ \\nWhat Is\\nLangChain?Google\\nCloudhttps://cloud.google.com › use-cases ›\\nlangchain](https://cloud.google.com/use-cases/langchain)\\n\\nGoogle Cloud\\n\\nhttps://cloud.google.com › use-cases › langchain\\n\\n _LangChain_ is a programming language platform that lets developers construct\\nand connect models to access, transform, and share data seamlessly.\\n\\n\\u200e[Langchain And Ai](https://cloud.google.com/use-\\ncases/langchain#:~:text=LangChain%20and%20AI) · \\u200e[How Does Langchain\\nWork?](https://cloud.google.com/use-\\ncases/langchain#:~:text=How%20does%20LangChain%20work%3F) · \\u200e[Key Features Of\\nLangchain](https://cloud.google.com/use-\\ncases/langchain#:~:text=Key%20features%20of%20LangChain)\\n\\n# Page Navigation\\n\\n| 1|\\n[2](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=10&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAE)|\\n[3](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=20&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAG)|\\n[4](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=30&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAI)|\\n[5](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=40&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAK)|\\n[6](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=50&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAM)|\\n[7](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=60&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAO)|\\n[8](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=70&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAQ)|\\n[9](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=80&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAS)|\\n[10](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=90&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAU)|\\n[Next](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=10&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8NMDegQICBAW) \\n---|---|---|---|---|---|---|---|---|---|---|--- \\n \\n# Footer Links\\n\\nWasco County, Oregon \\\\- From your IP address\\n\\n\\\\-\\n\\nUpdate location\\n\\nCan't update your locationLearn more\\n\\nUpdating location...\\n\\n[Help](https://support.google.com/websearch/?p=ws_results_help&hl=en&fg=1)Send\\nfeedback[Privacy](https://policies.google.com/privacy?hl=en&fg=1)[Terms](https://policies.google.com/terms?hl=en&fg=1)\\n\\n\\n\", error=None, include_in_memory=False), ActionResult(is_done=True, extracted_content='LangChain is a composable framework designed for building applications with large language models (LLMs). It simplifies the integration of language models with external data sources and is open-source, supported by an active community. LangChain provides tools for developers to streamline the application lifecycle of LLMs.', error=None, include_in_memory=False)], all_model_outputs=[{'search_google': {'query': 'What is LangChain?'}}, {'extract_content': {'include_links': True}}, {'done': {'text': 'LangChain is a composable framework designed for building applications with large language models (LLMs). It simplifies the integration of language models with external data sources and is open-source, supported by an active community. LangChain provides tools for developers to streamline the application lifecycle of LLMs.'}}])\n"- ]- }- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "AgentHistoryList(all_results=[ActionResult(is_done=False, extracted_content='🔍 Searched for \"What is LangChain?\" in Google', error=None, include_in_memory=True), ActionResult(is_done=False, extracted_content=\"📄 Extracted page as markdown\\n: # Filters and Topics\\n\\n[All](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&source=lnms&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ0pQJegQIEhAB)\\n\\n[Images](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&udm=2&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQtKgLegQIExAB)\\n\\n[Videos](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&udm=7&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQtKgLegQIERAB)\\n\\n[Forums](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&udm=18&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQs6gLegQIDxAB)\\n\\nWeb\\n\\n[Flights](/travel/flights?sca_esv=4c6b8dc13bab3e46&output=search&q=What+is+LangChain%3F&source=lnms&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&ved=1t:200715&ictx=111)\\n\\n[Finance](/finance?sca_esv=4c6b8dc13bab3e46&output=search&q=What+is+LangChain%3F&source=lnms&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ0pQJegQIDBAB)\\n\\nMore\\n\\n[Books](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&udm=36&source=lnms&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ0pQJegQINxAB)\\n\\n[News](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&tbm=nws&source=lnms&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ0pQJegQINhAB)\\n\\n[Shopping](/search?sca_esv=4c6b8dc13bab3e46&q=What+is+LangChain%3F&udm=28&fbs=AEQNm0Aa4sjWe7Rqy32pFwRj0UkWd8nbOJfsBGGB5IQQO6L3JyWp6w6_rxLPe8F8fpm5a55blYtaduielx1say4YCS0EIyvBb6VkaLhDZSOnSC94tp-\\nJuFEDkvqUl_u6quB-Is11hrT6R6Y6jGPIGI0MqGRIdRYfHHK4Fm5f9UNWxYphEnPjChpmH-\\nusjmkJN6Sk444PHRuqJvihdKgoqwGrUjYjqVvmxA&ved=1t:220175&ictx=111)\\n\\nTools\\n\\nAny time\\n\\nAny time\\n\\n[Past\\nhour](/search?q=What+is+LangChain%3F&sca_esv=4c6b8dc13bab3e46&udm=14&source=lnt&tbs=qdr:h&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQpwV6BAgGEAc)\\n\\n[Past 24\\nhours](/search?q=What+is+LangChain%3F&sca_esv=4c6b8dc13bab3e46&udm=14&source=lnt&tbs=qdr:d&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQpwV6BAgGEAg)\\n\\n[Past\\nweek](/search?q=What+is+LangChain%3F&sca_esv=4c6b8dc13bab3e46&udm=14&source=lnt&tbs=qdr:w&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQpwV6BAgGEAk)\\n\\n[Past\\nmonth](/search?q=What+is+LangChain%3F&sca_esv=4c6b8dc13bab3e46&udm=14&source=lnt&tbs=qdr:m&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQpwV6BAgGEAo)\\n\\n[Past\\nyear](/search?q=What+is+LangChain%3F&sca_esv=4c6b8dc13bab3e46&udm=14&source=lnt&tbs=qdr:y&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQpwV6BAgGEAs)\\n\\nCustom range...\\n\\nCustom date range\\n\\nFromTo\\n\\nGo\\n\\nAll results\\n\\nAll results\\n\\n[Verbatim](/search?q=What+is+LangChain%3F&sca_esv=4c6b8dc13bab3e46&udm=14&source=lnt&tbs=li:1&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQpwV6BAgGEBM)\\n\\n[ Advanced Search\\n](https://www.google.com/advanced_search?q=What+is+LangChain%3F&udm=14)\\n\\nCtrl+Shift+X to select\\n\\n\\n\\n# Search settings\\n\\n[Search CustomizationOff](/history/optout?hl=en)\\n\\n[SafeSearchBlurring\\non](/safesearch?prev=https://www.google.com/search?q%3DWhat%2Bis%2BLangChain?%26udm%3D14&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8JsIegQIChAH)\\n\\n[LanguageEnglish](/preferences?lang=1&hl=en&prev=https://www.google.com/search?q%3DWhat%2Bis%2BLangChain%253F%26sca_esv%3D4c6b8dc13bab3e46%26udm%3D14#languages)\\n\\n[Dark themeDevice\\ndefault](/setprefs?hl=en&prev=https://www.google.com/search?q%3DWhat%2Bis%2BLangChain?%26udm%3D14%26pccc%3D1&sig=0_jfSkJcafppJyKAIkCWZpHFXzfrs%3D&cs=2&sa=X&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQqsEHegQIChAJ&ictx=1)\\n\\n[More\\nsettings](/preferences?hl=en&prev=https://www.google.com/search?q%3DWhat%2Bis%2BLangChain%253F%26sca_esv%3D4c6b8dc13bab3e46%26udm%3D14)\\n\\nSend feedback\\n\\n[Help](https://support.google.com/websearch/?p=dsrp_search_hc&hl=en) •\\n[Privacy](https://policies.google.com/privacy?hl=en&fg=1) •\\n[Terms](https://policies.google.com/terms?hl=en&fg=1)\\n\\n# Search Results\\n\\n[ \\nLangChainLangChainhttps://www.langchain.com](https://www.langchain.com/)\\n\\nLangChain\\n\\nhttps://www.langchain.com\\n\\n _LangChain_ is a composable framework to build with LLMs. LangGraph is the\\norchestration framework for controllable agentic workflows. Run.\\n\\n\\u200e[Docs](https://python.langchain.com/docs/introduction/) ·\\n\\u200e[Products](https://www.langchain.com/langchain) · \\u200e[LangChain\\nAcademy](https://academy.langchain.com/) · \\u200e[Join the LangChain\\nCommunity](https://www.langchain.com/join-community)\\n\\n[ \\nWhat is\\nLangChain?Amazon\\nWeb Serviceshttps://aws.amazon.com › ... › Generative\\nAI](https://aws.amazon.com/what-is/langchain/)\\n\\nAmazon Web Services\\n\\nhttps://aws.amazon.com › ... › Generative AI\\n\\nLangChain _provides AI developers with tools to connect language models with\\nexternal data sources_. It is open-source and supported by an active\\ncommunity.\\n\\n[ \\nWhat Is LangChain and How to Use It: A\\nGuideTechTargethttps://www.techtarget.com\\n› definition ›\\nLangChain](https://www.techtarget.com/searchenterpriseai/definition/LangChain)\\n\\nTechTarget\\n\\nhttps://www.techtarget.com › definition › LangChain\\n\\n _LangChain is an open source framework_ that enables software developers\\nworking with artificial intelligence (AI) and its machine learning subset to\\ncombine ...\\n\\n[ \\nIntroduction | 🦜️ LangChainLangChainhttps://python.langchain.com › docs › introduction](https://python.langchain.com/docs/introduction/)\\n\\nLangChain\\n\\nhttps://python.langchain.com › docs › introduction\\n\\n _LangChain_ is a framework for developing applications powered by large\\nlanguage models (LLMs). LangChain simplifies every stage of the LLM\\napplication lifecycle.\\n\\n\\u200e[Introduction](https://python.langchain.com/v0.1/docs/get_started/introduction/)\\n·\\n\\u200e[Langchain.agents...](https://api.python.langchain.com/en/latest/agents/langchain.agents.tool_calling_agent.base.create_tool_calling_agent.html)\\n· \\u200e[LangChain v0.3](https://python.langchain.com/docs/versions/v0_3/) ·\\n\\u200e[Langchain_core.tools.](https://api.python.langchain.com/en/latest/tools/langchain_core.tools.tool.html)\\n\\n[ \\nWhat Is\\nLangChain?IBMhttps://www.ibm.com\\n› think › topics › langchain](https://www.ibm.com/think/topics/langchain)\\n\\nIBM\\n\\nhttps://www.ibm.com › think › topics › langchain\\n\\nLangChain is essentially _a library of abstractions for Python and Javascript_\\n, representing common steps and concepts necessary to work with language\\nmodels.\\n\\n[ \\nWhat is\\nLangChain?YouTube\\n· IBM Technology287.6K+ views · 10 months\\nago](https://www.youtube.com/watch?v=1bUy-1hGZpI)\\n\\nYouTube · IBM Technology\\n\\n287.6K+ views · 10 months ago\\n\\nLang chain is _an open-source orchestration framework_ for the development of\\napplications that use large language models.\\n\\n[ \\nWhat is Langchain and why should I care as a\\ndeveloper?Medium\\n· Logan Kilpatrick370+ likes · 1 year ago](https://medium.com/around-the-\\nprompt/what-is-langchain-and-why-should-i-care-as-a-developer-b2d952c42b28)\\n\\nMedium · Logan Kilpatrick\\n\\n370+ likes · 1 year ago\\n\\n _Langchain_ makes creating agents using large language models simple through\\ntheir agents API. Developers can use OpenAI functions or other means ...\\n\\n[ \\nLangChainWikipediahttps://en.wikipedia.org\\n› wiki › LangChain](https://en.wikipedia.org/wiki/LangChain)\\n\\nWikipedia\\n\\nhttps://en.wikipedia.org › wiki › LangChain\\n\\nLangChain is a software framework that helps facilitate the integration of\\nlarge language models (LLMs) into applications.\\n\\n\\u200e[History](https://en.wikipedia.org/wiki/LangChain#History) ·\\n\\u200e[Capabilities](https://en.wikipedia.org/wiki/LangChain#Capabilities) ·\\n\\u200e[LangChain tools](https://en.wikipedia.org/wiki/LangChain#LangChain_tools)\\n\\n[ \\nWhat Is LangChain? A Complete Comprehensive\\nOverviewDataStaxhttps://www.datastax.com\\n› guides › what-is-langchain](https://www.datastax.com/guides/what-is-\\nlangchain)\\n\\nDataStax\\n\\nhttps://www.datastax.com › guides › what-is-langchain\\n\\nNov 9, 2023 — LangChain is _a Python framework designed to streamline AI\\napplication development_ , focusing on real-time data processing and\\nintegration with ...\\n\\n[ \\nWhat Is\\nLangChain?Google\\nCloudhttps://cloud.google.com › use-cases ›\\nlangchain](https://cloud.google.com/use-cases/langchain)\\n\\nGoogle Cloud\\n\\nhttps://cloud.google.com › use-cases › langchain\\n\\n _LangChain_ is a programming language platform that lets developers construct\\nand connect models to access, transform, and share data seamlessly.\\n\\n\\u200e[Langchain And Ai](https://cloud.google.com/use-\\ncases/langchain#:~:text=LangChain%20and%20AI) · \\u200e[How Does Langchain\\nWork?](https://cloud.google.com/use-\\ncases/langchain#:~:text=How%20does%20LangChain%20work%3F) · \\u200e[Key Features Of\\nLangchain](https://cloud.google.com/use-\\ncases/langchain#:~:text=Key%20features%20of%20LangChain)\\n\\n# Page Navigation\\n\\n| 1|\\n[2](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=10&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAE)|\\n[3](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=20&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAG)|\\n[4](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=30&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAI)|\\n[5](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=40&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAK)|\\n[6](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=50&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAM)|\\n[7](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=60&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAO)|\\n[8](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=70&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAQ)|\\n[9](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=80&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAS)|\\n[10](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=90&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8tMDegQICBAU)|\\n[Next](/search?q=What+is+LangChain?&sca_esv=4c6b8dc13bab3e46&udm=14&ei=e8iJZ425Mabg0PEP6LmQGQ&start=10&sa=N&sstk=ATObxK4t7c6xZe8J3zQzlUfrNV-\\nBchujCI0GxH83wgy_vu9jEqYrHuTxd0wVBzubCa-bn_k1uK_Zn1BBIfr2yh6eyUzMdvUxFJ-\\nmCw&ved=2ahUKEwjN4oy74vuKAxUmMDQIHegcJAMQ8NMDegQICBAW) \\n---|---|---|---|---|---|---|---|---|---|---|--- \\n \\n# Footer Links\\n\\nWasco County, Oregon \\\\- From your IP address\\n\\n\\\\-\\n\\nUpdate location\\n\\nCan't update your locationLearn more\\n\\nUpdating location...\\n\\n[Help](https://support.google.com/websearch/?p=ws_results_help&hl=en&fg=1)Send\\nfeedback[Privacy](https://policies.google.com/privacy?hl=en&fg=1)[Terms](https://policies.google.com/terms?hl=en&fg=1)\\n\\n\\n\", error=None, include_in_memory=False), ActionResult(is_done=True, extracted_content='LangChain is a composable framework designed for building applications with large language models (LLMs). It simplifies the integration of language models with external data sources and is open-source, supported by an active community. LangChain provides tools for developers to streamline the application lifecycle of LLMs.', error=None, include_in_memory=False)], all_model_outputs=[{'search_google': {'query': 'What is LangChain?'}}, {'extract_content': {'include_links': True}}, {'done': {'text': 'LangChain is a composable framework designed for building applications with large language models (LLMs). It simplifies the integration of language models with external data sources and is open-source, supported by an active community. LangChain provides tools for developers to streamline the application lifecycle of LLMs.'}}])\n"+ ]+ }+ ],+ "source": [+ "# from browser_use import Agent\n",+ "import asyncio\n",+ "\n",+ "from langchain_openai import ChatOpenAI\n",+ "\n",+ "from browser_use import Browser, BrowserConfig\n",+ "\n",+ "# Basic configuration\n",+ "config = BrowserConfig(\n",+ "\theadless=True,\n",+ "\t# disable_security=True\n",+ ")\n",+ "# Reuse existing browser\n",+ "browser = Browser(config=config)\n",+ "# async def main():\n",+ "agent = Agent(\n",+ "\ttask='what is langchain',\n",+ "\tllm=llm,\n",+ "\tbrowser=browser,\n",+ "\tgenerate_gif=False, # Browser instance will be reused\n",+ ")\n",+ "\n",+ "result = await agent.run()\n",+ "print(result)\n",+ "# Manually close the browser\n",+ "# asyncio.run(main())\n",+ "await browser.close()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 27,+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"},+ "id": "nKGC936xODry",+ "outputId": "de70d715-c30a-4d5b-9d25-40bd79d410de"+ },+ "outputs": [{- "cell_type": "code",- "source": [- "# display(result.action_results())\n",- "for action in result.action_results():\n",- " if action.is_done:\n",- " print(action.extracted_content)\n",- ""- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "nKGC936xODry",- "outputId": "de70d715-c30a-4d5b-9d25-40bd79d410de"- },- "execution_count": 27,- "outputs": [- {- "output_type": "stream",- "name": "stdout",- "text": [- "LangChain is a composable framework designed for building applications with large language models (LLMs). It simplifies the integration of language models with external data sources and is open-source, supported by an active community. LangChain provides tools for developers to streamline the application lifecycle of LLMs.\n"- ]- }- ]+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "LangChain is a composable framework designed for building applications with large language models (LLMs). It simplifies the integration of language models with external data sources and is open-source, supported by an active community. LangChain provides tools for developers to streamline the application lifecycle of LLMs.\n"+ ]}- ]+ ],+ "source": [+ "# display(result.action_results())\n",+ "for action in result.action_results():\n",+ "\tif action.is_done:\n",+ "\t\tprint(action.extracted_content)"+ ]+ }+ ],+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"+ },+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 0}diff --git a/examples/ui/command_line.py b/examples/ui/command_line.pyindex 129d7c957..ea2d1a5ad 100644--- a/examples/ui/command_line.py+++ b/examples/ui/command_line.py@@ -11,6 +11,7 @@ Example 3: Using Anthropic's Claude Model with a Custom Querypython command_line.py --query "find latest Python tutorials on Medium" --provider anthropic"""+import argparseimport asyncioimport os@@ -27,70 +28,71 @@ from browser_use.controller.service import Controllerload_dotenv()+def get_llm(provider: str):if provider == 'anthropic':from langchain_anthropic import ChatAnthropic- api_key = os.getenv("ANTHROPIC_API_KEY")++ api_key = os.getenv('ANTHROPIC_API_KEY')if not api_key:- raise ValueError("Error: ANTHROPIC_API_KEY is not set. Please provide a valid API key.")+ raise ValueError('Error: ANTHROPIC_API_KEY is not set. Please provide a valid API key.')- return ChatAnthropic(- model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None, temperature=0.0- )+ return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None, temperature=0.0)elif provider == 'openai':from langchain_openai import ChatOpenAI- api_key = os.getenv("OPENAI_API_KEY")++ api_key = os.getenv('OPENAI_API_KEY')if not api_key:- raise ValueError("Error: OPENAI_API_KEY is not set. Please provide a valid API key.")+ raise ValueError('Error: OPENAI_API_KEY is not set. Please provide a valid API key.')return ChatOpenAI(model='gpt-4o', temperature=0.0)else:raise ValueError(f'Unsupported provider: {provider}')+def parse_arguments():- """Parse command-line arguments."""- parser = argparse.ArgumentParser(description="Automate browser tasks using an LLM agent.")- parser.add_argument(- '--query',- type=str,- help='The query to process',- default='go to reddit and search for posts about browser-use'- )- parser.add_argument(- '--provider',- type=str,- choices=['openai', 'anthropic'],- default='openai',- help='The model provider to use (default: openai)',- )- return parser.parse_args()+ """Parse command-line arguments."""+ parser = argparse.ArgumentParser(description='Automate browser tasks using an LLM agent.')+ parser.add_argument(+ '--query', type=str, help='The query to process', default='go to reddit and search for posts about browser-use'+ )+ parser.add_argument(+ '--provider',+ type=str,+ choices=['openai', 'anthropic'],+ default='openai',+ help='The model provider to use (default: openai)',+ )+ return parser.parse_args()+def initialize_agent(query: str, provider: str):- """Initialize the browser agent with the given query and provider."""- llm = get_llm(provider)- controller = Controller()- browser = Browser(config=BrowserConfig())-- return Agent(- task=query,- llm=llm,- controller=controller,- browser=browser,- use_vision=True,- max_actions_per_step=1,- ), browser+ """Initialize the browser agent with the given query and provider."""+ llm = get_llm(provider)+ controller = Controller()+ browser = Browser(config=BrowserConfig())++ return Agent(+ task=query,+ llm=llm,+ controller=controller,+ browser=browser,+ use_vision=True,+ max_actions_per_step=1,+ ), browser+async def main():- """Main async function to run the agent."""- args = parse_arguments()- agent, browser = initialize_agent(args.query, args.provider)+ """Main async function to run the agent."""+ args = parse_arguments()+ agent, browser = initialize_agent(args.query, args.provider)- await agent.run(max_steps=25)+ await agent.run(max_steps=25)- input('Press Enter to close the browser...')- await browser.close()+ input('Press Enter to close the browser...')+ await browser.close()-if __name__ == "__main__":- asyncio.run(main())+if __name__ == '__main__':+ asyncio.run(main())diff --git a/examples/ui/gradio_demo.py b/examples/ui/gradio_demo.pyindex 8b0babf78..aa3915eb3 100644--- a/examples/ui/gradio_demo.py+++ b/examples/ui/gradio_demo.py@@ -85,9 +85,7 @@ def create_ui():placeholder='E.g., Find flights from New York to London for next week',lines=3,)- model = gr.Dropdown(- choices=['gpt-4', 'gpt-3.5-turbo'], label='Model', value='gpt-4'- )+ model = gr.Dropdown(choices=['gpt-4', 'gpt-3.5-turbo'], label='Model', value='gpt-4')headless = gr.Checkbox(label='Run Headless', value=True)submit_btn = gr.Button('Run Task')diff --git a/examples/ui/streamlit_demo.py b/examples/ui/streamlit_demo.pyindex 123366af6..39960b0c9 100644--- a/examples/ui/streamlit_demo.py+++ b/examples/ui/streamlit_demo.py@@ -23,62 +23,65 @@ from browser_use.controller.service import Controllerload_dotenv()if os.name == 'nt':- asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())-+ asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())++# Function to get the LLM based on providerdef get_llm(provider: str):- if provider == 'anthropic':- from langchain_anthropic import ChatAnthropic- api_key = os.getenv("ANTHROPIC_API_KEY")- if not api_key:- st.error("Error: ANTHROPIC_API_KEY is not set. Please provide a valid API key.")- st.stop()-- return ChatAnthropic(- model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None, temperature=0.0- )- elif provider == 'openai':- from langchain_openai import ChatOpenAI- api_key = os.getenv("OPENAI_API_KEY")- if not api_key:- st.error("Error: OPENAI_API_KEY is not set. Please provide a valid API key.")- st.stop()-- return ChatOpenAI(model='gpt-4o', temperature=0.0)- else:- st.error(f'Unsupported provider: {provider}')- st.stop()+ if provider == 'anthropic':+ from langchain_anthropic import ChatAnthropic++ api_key = os.getenv('ANTHROPIC_API_KEY')+ if not api_key:+ st.error('Error: ANTHROPIC_API_KEY is not set. Please provide a valid API key.')+ st.stop()++ return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None, temperature=0.0)+ elif provider == 'openai':+ from langchain_openai import ChatOpenAI++ api_key = os.getenv('OPENAI_API_KEY')+ if not api_key:+ st.error('Error: OPENAI_API_KEY is not set. Please provide a valid API key.')+ st.stop()++ return ChatOpenAI(model='gpt-4o', temperature=0.0)+ else:+ st.error(f'Unsupported provider: {provider}')+ st.stop()+# Function to initialize the agentdef initialize_agent(query: str, provider: str):- llm = get_llm(provider)- controller = Controller()- browser = Browser(config=BrowserConfig())-- return Agent(- task=query,- llm=llm,- controller=controller,- browser=browser,- use_vision=True,- max_actions_per_step=1,- ), browser+ llm = get_llm(provider)+ controller = Controller()+ browser = Browser(config=BrowserConfig())++ return Agent(+ task=query,+ llm=llm,+ controller=controller,+ browser=browser,+ use_vision=True,+ max_actions_per_step=1,+ ), browser+# Streamlit UI-st.title("Automated Browser Agent with LLMs 🤖")+st.title('Automated Browser Agent with LLMs 🤖')-query = st.text_input("Enter your query:", "go to reddit and search for posts about browser-use")-provider = st.radio("Select LLM Provider:", ["openai", "anthropic"], index=0)+query = st.text_input('Enter your query:', 'go to reddit and search for posts about browser-use')+provider = st.radio('Select LLM Provider:', ['openai', 'anthropic'], index=0)-if st.button("Run Agent"):- st.write("Initializing agent...")- agent, browser = initialize_agent(query, provider)+if st.button('Run Agent'):+ st.write('Initializing agent...')+ agent, browser = initialize_agent(query, provider)- async def run_agent():- with st.spinner("Running automation..."):- await agent.run(max_steps=25)- st.success("Task completed! 🎉")+ async def run_agent():+ with st.spinner('Running automation...'):+ await agent.run(max_steps=25)+ st.success('Task completed! 🎉')- asyncio.run(run_agent())+ asyncio.run(run_agent())- st.button("Close Browser", on_click=lambda: asyncio.run(browser.close()))+ st.button('Close Browser', on_click=lambda: asyncio.run(browser.close()))diff --git a/examples/use-cases/captcha.py b/examples/use-cases/captcha.pyindex 180693cd8..4091c8d74 100644--- a/examples/use-cases/captcha.py+++ b/examples/use-cases/captcha.py@@ -23,16 +23,18 @@ from browser_use import Agent# 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.')+ raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')+async def main():- llm = ChatOpenAI(model='gpt-4o')- agent = Agent(+ 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')+ await agent.run()+ input('Press Enter to exit')+-if __name__ == "__main__":- asyncio.run(main())+if __name__ == '__main__':+ asyncio.run(main())diff --git a/examples/use-cases/check_appointment.py b/examples/use-cases/check_appointment.pyindex 8e010f014..4696baf7f 100644--- a/examples/use-cases/check_appointment.py+++ b/examples/use-cases/check_appointment.py@@ -13,13 +13,14 @@ from 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.')+ raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')controller = Controller()class WebpageInfo(BaseModel):"""Model for webpage link."""+link: str = 'https://appointment.mfa.gr/en/reservations/aero/ireland-grcon-dub/'@@ -43,5 +44,5 @@ async def main():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 ba2eeb180..bec4ccc97 100644--- a/examples/use-cases/find_and_apply_to_jobs.py+++ b/examples/use-cases/find_and_apply_to_jobs.py@@ -26,10 +26,10 @@ from browser_use.browser.context import BrowserContext# Validate required environment variablesload_dotenv()-required_env_vars = ["AZURE_OPENAI_KEY", "AZURE_OPENAI_ENDPOINT"]+required_env_vars = ['AZURE_OPENAI_KEY', 'AZURE_OPENAI_ENDPOINT']for var in required_env_vars:- if not os.getenv(var):- raise ValueError(f"{var} is not set. Please add it to your environment variables.")+ if not os.getenv(var):+ raise ValueError(f'{var} is not set. Please add it to your environment variables.')logger = logging.getLogger(__name__)# full screen mode@@ -156,5 +156,5 @@ async def main():await asyncio.gather(*[agent.run() for agent in agents])-if __name__ == "__main__":+if __name__ == '__main__':asyncio.run(main())diff --git a/examples/use-cases/online_coding_agent.py b/examples/use-cases/online_coding_agent.pyindex 3b723c182..e0b9f11e6 100644--- a/examples/use-cases/online_coding_agent.py+++ b/examples/use-cases/online_coding_agent.py@@ -14,33 +14,35 @@ from 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.')+ raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')+async def main():- browser = Browser()- async with await browser.new_context() as context:- model = ChatOpenAI(model='gpt-4o')-- # Initialize browser agent- agent1 = Agent(- task='Open an online code editor programiz.',- llm=model,- browser_context=context,- )- executor = Agent(- task='Executor. Execute the code written by the coder and suggest some updates if there are errors.',- llm=model,- browser_context=context,- )-- coder = Agent(- task='Coder. Your job is to write and complete code. You are an expert coder. Code a simple calculator. Write the code on the coding interface after agent1 has opened the link.',- llm=model,- browser_context=context,- )- await agent1.run()- await executor.run()- await coder.run()--if __name__ == "__main__":- asyncio.run(main())+ browser = Browser()+ async with await browser.new_context() as context:+ model = ChatOpenAI(model='gpt-4o')++ # Initialize browser agent+ agent1 = Agent(+ task='Open an online code editor programiz.',+ llm=model,+ browser_context=context,+ )+ executor = Agent(+ task='Executor. Execute the code written by the coder and suggest some updates if there are errors.',+ llm=model,+ browser_context=context,+ )++ coder = Agent(+ task='Coder. Your job is to write and complete code. You are an expert coder. Code a simple calculator. Write the code on the coding interface after agent1 has opened the link.',+ llm=model,+ browser_context=context,+ )+ await agent1.run()+ await executor.run()+ await coder.run()+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/examples/use-cases/post-twitter.py b/examples/use-cases/post-twitter.pyindex 7a46d7b60..a90f02404 100644--- a/examples/use-cases/post-twitter.py+++ b/examples/use-cases/post-twitter.py@@ -36,53 +36,53 @@ from 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. Please add it to your environment variables.')+ raise ValueError('OPENAI_API_KEY is not set. Please add it to your environment variables.')+# ============ Configuration Section ============@dataclassclass TwitterConfig:- """Configuration for Twitter posting"""+ """Configuration for Twitter posting"""- openai_api_key: str- chrome_path: str- target_user: str # Twitter handle without @- message: str- reply_url: str- headless: bool = False- model: str = "gpt-4o-mini"- base_url: str = "https://x.com/home"+ openai_api_key: str+ chrome_path: str+ target_user: str # Twitter handle without @+ message: str+ reply_url: str+ headless: bool = False+ model: str = 'gpt-4o-mini'+ base_url: str = 'https://x.com/home'# Customize these settingsconfig = TwitterConfig(- openai_api_key=os.getenv("OPENAI_API_KEY"),- chrome_path="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", # This is for MacOS (Chrome)- target_user="XXXXX",- message="XXXXX",- reply_url="XXXXX",- headless=False,+ openai_api_key=os.getenv('OPENAI_API_KEY'),+ chrome_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', # This is for MacOS (Chrome)+ target_user='XXXXX',+ message='XXXXX',+ reply_url='XXXXX',+ headless=False,)def create_twitter_agent(config: TwitterConfig) -> Agent:+ llm = ChatOpenAI(model=config.model, api_key=config.openai_api_key)- llm = ChatOpenAI(model=config.model, api_key=config.openai_api_key)-- browser = Browser(- config=BrowserConfig(- headless=config.headless,- browser_binary_path=config.chrome_path,- )- )+ browser = Browser(+ config=BrowserConfig(+ headless=config.headless,+ browser_binary_path=config.chrome_path,+ )+ )- controller = Controller()+ controller = Controller()- # Construct the full message with tag- full_message = f"@{config.target_user} {config.message}"+ # Construct the full message with tag+ full_message = f'@{config.target_user} {config.message}'- # Create the agent with detailed instructions- return Agent(- task=f"""Navigate to Twitter and create a post and reply to a tweet.+ # Create the agent with detailed instructions+ return Agent(+ task=f"""Navigate to Twitter and create a post and reply to a tweet.Here are the specific steps:@@ -103,25 +103,25 @@ def create_twitter_agent(config: TwitterConfig) -> Agent:- Verify the post button is clickable before clicking- Do not click on the '+' button which will add another tweet""",- llm=llm,- controller=controller,- browser=browser,- )+ llm=llm,+ controller=controller,+ browser=browser,+ )async def post_tweet(agent: Agent):-- try:- await agent.run(max_steps=100)- agent.create_history_gif()- print("Tweet posted successfully!")- except Exception as e:- print(f"Error posting tweet: {str(e)}")+ try:+ await agent.run(max_steps=100)+ agent.create_history_gif()+ print('Tweet posted successfully!')+ except Exception as e:+ print(f'Error posting tweet: {str(e)}')async def main():- agent = create_twitter_agent(config)- await agent.run()+ agent = create_twitter_agent(config)+ await agent.run()+-if __name__ == "__main__":- asyncio.run(main())+if __name__ == '__main__':+ asyncio.run(main())diff --git a/examples/use-cases/scrolling_page.py b/examples/use-cases/scrolling_page.pyindex 6ad0cfc6e..4e649b062 100644--- a/examples/use-cases/scrolling_page.py+++ b/examples/use-cases/scrolling_page.py@@ -38,5 +38,5 @@ async def main():await agent.run()-if __name__ == "__main__":+if __name__ == '__main__':asyncio.run(main())diff --git a/examples/use-cases/shopping.py b/examples/use-cases/shopping.pyindex 1b55a9d0a..4ba67ac99 100644--- a/examples/use-cases/shopping.py+++ b/examples/use-cases/shopping.py@@ -7,7 +7,7 @@ load_dotenv()import asyncio-task="""+task = """### Prompt for Shopping Agent – Migros Online Grocery Order**Objective:**@@ -107,15 +107,17 @@ At this stage, check the basket on the top right (indicates the price) and checkbrowser = Browser()agent = Agent(- task=task,- llm=ChatOpenAI(model="gpt-4o"),- browser=browser,- )+ task=task,+ llm=ChatOpenAI(model='gpt-4o'),+ browser=browser,+)+async def main():- await agent.run()- input("Press Enter to close the browser...")- await browser.close()+ await agent.run()+ input('Press Enter to close the browser...')+ await browser.close()+if __name__ == '__main__':- asyncio.run(main())+ asyncio.run(main())diff --git a/examples/use-cases/twitter_post_using_cookies.py b/examples/use-cases/twitter_post_using_cookies.pyindex 33a99d411..73a46a8b8 100644--- a/examples/use-cases/twitter_post_using_cookies.py+++ b/examples/use-cases/twitter_post_using_cookies.py@@ -39,5 +39,5 @@ async def main():input('Press Enter to close the browser...')-if __name__ == "__main__":+if __name__ == '__main__':asyncio.run(main())diff --git a/examples/use-cases/web_voyager_agent.py b/examples/use-cases/web_voyager_agent.pyindex 17859487b..723fa8b0b 100644--- a/examples/use-cases/web_voyager_agent.py+++ b/examples/use-cases/web_voyager_agent.py@@ -18,10 +18,10 @@ from browser_use.browser.browser import Browser, BrowserConfig, BrowserContextCoload_dotenv()# Validate required environment variables-required_env_vars = ["AZURE_OPENAI_KEY", "AZURE_OPENAI_ENDPOINT"]+required_env_vars = ['AZURE_OPENAI_KEY', 'AZURE_OPENAI_ENDPOINT']for var in required_env_vars:- if not os.getenv(var):- raise ValueError(f"{var} is not set. Please add it to your environment variables.")+ if not os.getenv(var):+ raise ValueError(f'{var} is not set. Please add it to your environment variables.')browser = Browser(config=BrowserConfig(@@ -68,5 +68,5 @@ async def main():history.save_to_file('./tmp/history.json')-if __name__ == "__main__":+if __name__ == '__main__':asyncio.run(main())diff --git a/tests/test_agent_actions.py b/tests/test_agent_actions.pyindex 14d8dbacc..6a2c049d6 100644--- a/tests/test_agent_actions.py+++ b/tests/test_agent_actions.py@@ -104,15 +104,11 @@ async def test_error_recovery(llm, context):actions_names = history.action_names()actions = history.model_actions()- assert (- 'go_to_url' in actions_names or 'open_tab' in actions_names- ), f'{actions_names} does not contain go_to_url or open_tab'+ assert 'go_to_url' in actions_names or 'open_tab' in actions_names, f'{actions_names} does not contain go_to_url or open_tab'for action in actions:if 'go_to_url' in action:assert 'url' in action['go_to_url'], 'url is not in go_to_url'- assert action['go_to_url']['url'].endswith(- 'google.com'- ), 'url does not end with google.com'+ assert action['go_to_url']['url'].endswith('google.com'), 'url does not end with google.com'breakdiff --git a/tests/test_browser.py b/tests/test_browser.pyindex b3e41b175..f6ef59533 100644--- a/tests/test_browser.py+++ b/tests/test_browser.py@@ -11,308 +11,377 @@ from browser_use.browser.context import BrowserContext, BrowserContextConfig@pytest.mark.asyncioasync def test_builtin_browser_launch(monkeypatch):- """- Test that the standard browser is launched correctly:- When no remote (cdp or wss) or chrome instance is provided, the Browser class uses _setup_builtin_browser.- This test monkeypatches async_playwright to return dummy objects, and asserts that get_playwright_browser returns the expected DummyBrowser.- """- class DummyBrowser:- pass- class DummyChromium:- async def launch(self, headless, args, proxy=None):- return DummyBrowser()- class DummyPlaywright:- def __init__(self):- self.chromium = DummyChromium()- async def stop(self):- pass- class DummyAsyncPlaywrightContext:- async def start(self):- return DummyPlaywright()- monkeypatch.setattr("browser_use.browser.browser.async_playwright", lambda: DummyAsyncPlaywrightContext())- config = BrowserConfig(headless=True, disable_security=False, extra_browser_args=["--test"])- browser_obj = Browser(config=config)- result_browser = await browser_obj.get_playwright_browser()- assert isinstance(result_browser, DummyBrowser), "Expected DummyBrowser from _setup_builtin_browser"- await browser_obj.close()+ """+ Test that the standard browser is launched correctly:+ When no remote (cdp or wss) or chrome instance is provided, the Browser class uses _setup_builtin_browser.+ This test monkeypatches async_playwright to return dummy objects, and asserts that get_playwright_browser returns the expected DummyBrowser.+ """++ class DummyBrowser:+ pass++ class DummyChromium:+ async def launch(self, headless, args, proxy=None):+ return DummyBrowser()++ class DummyPlaywright:+ def __init__(self):+ self.chromium = DummyChromium()++ async def stop(self):+ pass++ class DummyAsyncPlaywrightContext:+ async def start(self):+ return DummyPlaywright()++ monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())+ config = BrowserConfig(headless=True, disable_security=False, extra_browser_args=['--test'])+ browser_obj = Browser(config=config)+ result_browser = await browser_obj.get_playwright_browser()+ assert isinstance(result_browser, DummyBrowser), 'Expected DummyBrowser from _setup_builtin_browser'+ await browser_obj.close()+@pytest.mark.asyncioasync def test_cdp_browser_launch(monkeypatch):- """- Test that when a CDP URL is provided in the configuration, the Browser uses _setup_cdp- and returns the expected DummyBrowser.- """- class DummyBrowser:- pass- class DummyChromium:- async def connect_over_cdp(self, endpoint_url, timeout=20000):- assert endpoint_url == "ws://dummy-cdp-url", "The endpoint URL should match the configuration."- return DummyBrowser()- class DummyPlaywright:- def __init__(self):- self.chromium = DummyChromium()- async def stop(self):- pass- class DummyAsyncPlaywrightContext:- async def start(self):- return DummyPlaywright()- monkeypatch.setattr("browser_use.browser.browser.async_playwright", lambda: DummyAsyncPlaywrightContext())- config = BrowserConfig(cdp_url="ws://dummy-cdp-url")- browser_obj = Browser(config=config)- result_browser = await browser_obj.get_playwright_browser()- assert isinstance(result_browser, DummyBrowser), "Expected DummyBrowser from _setup_cdp"- await browser_obj.close()+ """+ Test that when a CDP URL is provided in the configuration, the Browser uses _setup_cdp+ and returns the expected DummyBrowser.+ """++ class DummyBrowser:+ pass++ class DummyChromium:+ async def connect_over_cdp(self, endpoint_url, timeout=20000):+ assert endpoint_url == 'ws://dummy-cdp-url', 'The endpoint URL should match the configuration.'+ return DummyBrowser()++ class DummyPlaywright:+ def __init__(self):+ self.chromium = DummyChromium()++ async def stop(self):+ pass++ class DummyAsyncPlaywrightContext:+ async def start(self):+ return DummyPlaywright()++ monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())+ config = BrowserConfig(cdp_url='ws://dummy-cdp-url')+ browser_obj = Browser(config=config)+ result_browser = await browser_obj.get_playwright_browser()+ assert isinstance(result_browser, DummyBrowser), 'Expected DummyBrowser from _setup_cdp'+ await browser_obj.close()+@pytest.mark.asyncioasync def test_wss_browser_launch(monkeypatch):- """- Test that when a WSS URL is provided in the configuration,- the Browser uses setup_wss and returns the expected DummyBrowser.- """- class DummyBrowser:- pass- class DummyChromium:- async def connect(self, wss_url):- assert wss_url == "ws://dummy-wss-url", "WSS URL should match the configuration."- return DummyBrowser()- class DummyPlaywright:- def __init__(self):- self.chromium = DummyChromium()- async def stop(self):- pass- class DummyAsyncPlaywrightContext:- async def start(self):- return DummyPlaywright()- monkeypatch.setattr("browser_use.browser.browser.async_playwright", lambda: DummyAsyncPlaywrightContext())- config = BrowserConfig(wss_url="ws://dummy-wss-url")- browser_obj = Browser(config=config)- result_browser = await browser_obj.get_playwright_browser()- assert isinstance(result_browser, DummyBrowser), "Expected DummyBrowser from _setup_wss"- await browser_obj.close()+ """+ Test that when a WSS URL is provided in the configuration,+ the Browser uses setup_wss and returns the expected DummyBrowser.+ """++ class DummyBrowser:+ pass++ class DummyChromium:+ async def connect(self, wss_url):+ assert wss_url == 'ws://dummy-wss-url', 'WSS URL should match the configuration.'+ return DummyBrowser()++ class DummyPlaywright:+ def __init__(self):+ self.chromium = DummyChromium()++ async def stop(self):+ pass++ class DummyAsyncPlaywrightContext:+ async def start(self):+ return DummyPlaywright()++ monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())+ config = BrowserConfig(wss_url='ws://dummy-wss-url')+ browser_obj = Browser(config=config)+ result_browser = await browser_obj.get_playwright_browser()+ assert isinstance(result_browser, DummyBrowser), 'Expected DummyBrowser from _setup_wss'+ await browser_obj.close()+@pytest.mark.asyncioasync def test_user_provided_browser_launch(monkeypatch):- """- Test that when a browser_binary_path is provided the Browser class uses- _setup_user_provided_browser branch and returns the expected DummyBrowser object- by reusing an existing Chrome instance.- """- # Dummy response for requests.get when checking chrome debugging endpoint.- class DummyResponse:- status_code = 200- def dummy_get(url, timeout):- if url == "http://localhost:9222/json/version":- return DummyResponse()- raise requests.ConnectionError("Connection failed")- monkeypatch.setattr(requests, "get", dummy_get)- class DummyBrowser:- pass- class DummyChromium:- async def connect_over_cdp(self, endpoint_url, timeout=20000):- assert endpoint_url == "http://localhost:9222", "Endpoint URL must be 'http://localhost:9222'"- return DummyBrowser()- class DummyPlaywright:- def __init__(self):- self.chromium = DummyChromium()- async def stop(self):- pass- class DummyAsyncPlaywrightContext:- async def start(self):- return DummyPlaywright()- monkeypatch.setattr("browser_use.browser.browser.async_playwright", lambda: DummyAsyncPlaywrightContext())- config = BrowserConfig(browser_binary_path="dummy/chrome", extra_browser_args=["--dummy-arg"])- browser_obj = Browser(config=config)- result_browser = await browser_obj.get_playwright_browser()- assert isinstance(result_browser, DummyBrowser), "Expected DummyBrowser from _setup_user_provided_browser"- await browser_obj.close()+ """+ Test that when a browser_binary_path is provided the Browser class uses+ _setup_user_provided_browser branch and returns the expected DummyBrowser object+ by reusing an existing Chrome instance.+ """++ # Dummy response for requests.get when checking chrome debugging endpoint.+ class DummyResponse:+ status_code = 200++ def dummy_get(url, timeout):+ if url == 'http://localhost:9222/json/version':+ return DummyResponse()+ raise requests.ConnectionError('Connection failed')++ monkeypatch.setattr(requests, 'get', dummy_get)++ class DummyBrowser:+ pass++ class DummyChromium:+ async def connect_over_cdp(self, endpoint_url, timeout=20000):+ assert endpoint_url == 'http://localhost:9222', "Endpoint URL must be 'http://localhost:9222'"+ return DummyBrowser()++ class DummyPlaywright:+ def __init__(self):+ self.chromium = DummyChromium()++ async def stop(self):+ pass++ class DummyAsyncPlaywrightContext:+ async def start(self):+ return DummyPlaywright()++ monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())+ config = BrowserConfig(browser_binary_path='dummy/chrome', extra_browser_args=['--dummy-arg'])+ browser_obj = Browser(config=config)+ result_browser = await browser_obj.get_playwright_browser()+ assert isinstance(result_browser, DummyBrowser), 'Expected DummyBrowser from _setup_user_provided_browser'+ await browser_obj.close()+@pytest.mark.asyncioasync def test_builtin_browser_disable_security_args(monkeypatch):- """- Test that the standard browser launch includes disable-security arguments when disable_security is True.- This verifies that _setup_builtin_browser correctly appends the security disabling arguments along with- the base arguments and any extra arguments provided.- """- # These are the base arguments defined in _setup_builtin_browser.- base_args = [- '--no-sandbox',- '--disable-blink-features=AutomationControlled',- '--disable-infobars',- '--disable-background-timer-throttling',- '--disable-popup-blocking',- '--disable-backgrounding-occluded-windows',- '--disable-renderer-backgrounding',- '--disable-window-activation',- '--disable-focus-on-load',- '--no-first-run',- '--no-default-browser-check',- '--no-startup-window',- '--window-position=0,0',- ]- # When disable_security is True, these arguments should be added.- disable_security_args = [- '--disable-web-security',- '--disable-site-isolation-trials',- '--disable-features=IsolateOrigins,site-per-process'- ]- # Additional arbitrary argument for testing extra args- extra_args = ["--dummy-extra"]- class DummyBrowser:- pass- class DummyChromium:- async def launch(self, headless, args, proxy=None):- # Expected args is the base args plus disable security args and the extra args.- expected_args = base_args + disable_security_args + extra_args- assert headless is True, "Expected headless to be True"- assert args == expected_args, f"Expected args {expected_args}, but got {args}"- assert proxy is None, "Expected proxy to be None"- return DummyBrowser()- class DummyPlaywright:- def __init__(self):- self.chromium = DummyChromium()- async def stop(self):- pass- class DummyAsyncPlaywrightContext:- async def start(self):- return DummyPlaywright()- monkeypatch.setattr("browser_use.browser.browser.async_playwright", lambda: DummyAsyncPlaywrightContext())- config = BrowserConfig(headless=True, disable_security=True, extra_browser_args=extra_args)- browser_obj = Browser(config=config)- result_browser = await browser_obj.get_playwright_browser()- assert isinstance(result_browser, DummyBrowser), "Expected DummyBrowser from _setup_builtin_browser with disable_security active"- await browser_obj.close()+ """+ Test that the standard browser launch includes disable-security arguments when disable_security is True.+ This verifies that _setup_builtin_browser correctly appends the security disabling arguments along with+ the base arguments and any extra arguments provided.+ """+ # These are the base arguments defined in _setup_builtin_browser.+ base_args = [+ '--no-sandbox',+ '--disable-blink-features=AutomationControlled',+ '--disable-infobars',+ '--disable-background-timer-throttling',+ '--disable-popup-blocking',+ '--disable-backgrounding-occluded-windows',+ '--disable-renderer-backgrounding',+ '--disable-window-activation',+ '--disable-focus-on-load',+ '--no-first-run',+ '--no-default-browser-check',+ '--no-startup-window',+ '--window-position=0,0',+ ]+ # When disable_security is True, these arguments should be added.+ disable_security_args = [+ '--disable-web-security',+ '--disable-site-isolation-trials',+ '--disable-features=IsolateOrigins,site-per-process',+ ]+ # Additional arbitrary argument for testing extra args+ extra_args = ['--dummy-extra']++ class DummyBrowser:+ pass++ class DummyChromium:+ async def launch(self, headless, args, proxy=None):+ # Expected args is the base args plus disable security args and the extra args.+ expected_args = base_args + disable_security_args + extra_args+ assert headless is True, 'Expected headless to be True'+ assert args == expected_args, f'Expected args {expected_args}, but got {args}'+ assert proxy is None, 'Expected proxy to be None'+ return DummyBrowser()++ class DummyPlaywright:+ def __init__(self):+ self.chromium = DummyChromium()++ async def stop(self):+ pass++ class DummyAsyncPlaywrightContext:+ async def start(self):+ return DummyPlaywright()++ monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())+ config = BrowserConfig(headless=True, disable_security=True, extra_browser_args=extra_args)+ browser_obj = Browser(config=config)+ result_browser = await browser_obj.get_playwright_browser()+ assert isinstance(result_browser, DummyBrowser), (+ 'Expected DummyBrowser from _setup_builtin_browser with disable_security active'+ )+ await browser_obj.close()+@pytest.mark.asyncioasync def test_new_context_creation():- """- Test that the new_context method returns a BrowserContext with the correct attributes.- This verifies that the BrowserContext is initialized with the provided Browser instance and configuration.- """- config = BrowserConfig()- browser_obj = Browser(config=config)- custom_context_config = BrowserContextConfig()- context = await browser_obj.new_context(custom_context_config)- assert isinstance(context, BrowserContext), "Expected new_context to return an instance of BrowserContext"- assert context.browser is browser_obj, "Expected the context's browser attribute to be the Browser instance"- assert context.config == custom_context_config, "Expected the context's config attribute to be the provided config"- await browser_obj.close()+ """+ Test that the new_context method returns a BrowserContext with the correct attributes.+ This verifies that the BrowserContext is initialized with the provided Browser instance and configuration.+ """+ config = BrowserConfig()+ browser_obj = Browser(config=config)+ custom_context_config = BrowserContextConfig()+ context = await browser_obj.new_context(custom_context_config)+ assert isinstance(context, BrowserContext), 'Expected new_context to return an instance of BrowserContext'+ assert context.browser is browser_obj, "Expected the context's browser attribute to be the Browser instance"+ assert context.config == custom_context_config, "Expected the context's config attribute to be the provided config"+ await browser_obj.close()+@pytest.mark.asyncioasync def test_user_provided_browser_launch_failure(monkeypatch):- """- Test that when a Chrome instance cannot be started or connected to,- the Browser._setup_user_provided_browser branch eventually raises a RuntimeError.- We simulate failure by:- - Forcing requests.get to always raise a ConnectionError (so no existing instance is found).- - Monkeypatching subprocess.Popen to do nothing.- - Replacing asyncio.sleep to avoid delays.- - Having the dummy playwright's connect_over_cdp method always raise an Exception.- """- def dummy_get(url, timeout):- raise requests.ConnectionError("Simulated connection failure")- monkeypatch.setattr(requests, "get", dummy_get)- monkeypatch.setattr(subprocess, "Popen", lambda args, stdout, stderr: None)- async def fake_sleep(seconds):- return- monkeypatch.setattr(asyncio, "sleep", fake_sleep)- class DummyChromium:- async def connect_over_cdp(self, endpoint_url, timeout=20000):- raise Exception("Connection failed simulation")- class DummyPlaywright:- def __init__(self):- self.chromium = DummyChromium()- async def stop(self):- pass- class DummyAsyncPlaywrightContext:- async def start(self):- return DummyPlaywright()- monkeypatch.setattr("browser_use.browser.browser.async_playwright", lambda: DummyAsyncPlaywrightContext())- config = BrowserConfig(browser_binary_path="dummy/chrome", extra_browser_args=["--dummy-arg"])- browser_obj = Browser(config=config)- with pytest.raises(RuntimeError, match="To start chrome in Debug mode"):- await browser_obj.get_playwright_browser()- await browser_obj.close()+ """+ Test that when a Chrome instance cannot be started or connected to,+ the Browser._setup_user_provided_browser branch eventually raises a RuntimeError.+ We simulate failure by:+ - Forcing requests.get to always raise a ConnectionError (so no existing instance is found).+ - Monkeypatching subprocess.Popen to do nothing.+ - Replacing asyncio.sleep to avoid delays.+ - Having the dummy playwright's connect_over_cdp method always raise an Exception.+ """++ def dummy_get(url, timeout):+ raise requests.ConnectionError('Simulated connection failure')++ monkeypatch.setattr(requests, 'get', dummy_get)+ monkeypatch.setattr(subprocess, 'Popen', lambda args, stdout, stderr: None)++ async def fake_sleep(seconds):+ return++ monkeypatch.setattr(asyncio, 'sleep', fake_sleep)++ class DummyChromium:+ async def connect_over_cdp(self, endpoint_url, timeout=20000):+ raise Exception('Connection failed simulation')++ class DummyPlaywright:+ def __init__(self):+ self.chromium = DummyChromium()++ async def stop(self):+ pass++ class DummyAsyncPlaywrightContext:+ async def start(self):+ return DummyPlaywright()++ monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())+ config = BrowserConfig(browser_binary_path='dummy/chrome', extra_browser_args=['--dummy-arg'])+ browser_obj = Browser(config=config)+ with pytest.raises(RuntimeError, match='To start chrome in Debug mode'):+ await browser_obj.get_playwright_browser()+ await browser_obj.close()+@pytest.mark.asyncioasync def test_get_playwright_browser_caching(monkeypatch):- """- Test that get_playwright_browser returns a cached browser instance.- On the first call, the browser is initialized; on subsequent calls,- the same instance is returned.- """- class DummyBrowser:- pass- class DummyChromium:- async def launch(self, headless, args, proxy=None):- return DummyBrowser()- class DummyPlaywright:- def __init__(self):- self.chromium = DummyChromium()- async def stop(self):- pass- class DummyAsyncPlaywrightContext:- async def start(self):- return DummyPlaywright()- monkeypatch.setattr("browser_use.browser.browser.async_playwright", lambda: DummyAsyncPlaywrightContext())- config = BrowserConfig(headless=True, disable_security=False, extra_browser_args=["--test"])- browser_obj = Browser(config=config)- first_browser = await browser_obj.get_playwright_browser()- second_browser = await browser_obj.get_playwright_browser()- assert first_browser is second_browser, "Expected the browser to be cached and reused across calls."- await browser_obj.close()+ """+ Test that get_playwright_browser returns a cached browser instance.+ On the first call, the browser is initialized; on subsequent calls,+ the same instance is returned.+ """++ class DummyBrowser:+ pass++ class DummyChromium:+ async def launch(self, headless, args, proxy=None):+ return DummyBrowser()++ class DummyPlaywright:+ def __init__(self):+ self.chromium = DummyChromium()++ async def stop(self):+ pass++ class DummyAsyncPlaywrightContext:+ async def start(self):+ return DummyPlaywright()++ monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())+ config = BrowserConfig(headless=True, disable_security=False, extra_browser_args=['--test'])+ browser_obj = Browser(config=config)+ first_browser = await browser_obj.get_playwright_browser()+ second_browser = await browser_obj.get_playwright_browser()+ assert first_browser is second_browser, 'Expected the browser to be cached and reused across calls.'+ await browser_obj.close()+@pytest.mark.asyncioasync def test_close_error_handling(monkeypatch):- """- Test that the close method properly handles exceptions thrown by- playwright_browser.close() and playwright.stop(), ensuring that the- browser's attributes are set to None even if errors occur.- """- class DummyBrowserWithError:- async def close(self):- raise Exception("Close error simulation")- class DummyPlaywrightWithError:- async def stop(self):- raise Exception("Stop error simulation")- config = BrowserConfig()- browser_obj = Browser(config=config)- browser_obj.playwright_browser = DummyBrowserWithError()- browser_obj.playwright = DummyPlaywrightWithError()- await browser_obj.close()- assert browser_obj.playwright_browser is None, "Expected playwright_browser to be None after close"- assert browser_obj.playwright is None, "Expected playwright to be None after close"+ """+ Test that the close method properly handles exceptions thrown by+ playwright_browser.close() and playwright.stop(), ensuring that the+ browser's attributes are set to None even if errors occur.+ """++ class DummyBrowserWithError:+ async def close(self):+ raise Exception('Close error simulation')++ class DummyPlaywrightWithError:+ async def stop(self):+ raise Exception('Stop error simulation')++ config = BrowserConfig()+ browser_obj = Browser(config=config)+ browser_obj.playwright_browser = DummyBrowserWithError()+ browser_obj.playwright = DummyPlaywrightWithError()+ await browser_obj.close()+ assert browser_obj.playwright_browser is None, 'Expected playwright_browser to be None after close'+ assert browser_obj.playwright is None, 'Expected playwright to be None after close'+@pytest.mark.asyncioasync def test_standard_browser_launch_with_proxy(monkeypatch):- """- Test that when a proxy is provided in the BrowserConfig, the _setup_builtin_browser method- correctly passes the proxy parameter to the playwright.chromium.launch method.- This test sets up a dummy async_playwright context and verifies that the dummy proxy is received.- """- class DummyBrowser:- pass- # Create a dummy proxy settings instance.- dummy_proxy = ProxySettings(server="http://dummy.proxy")- class DummyChromium:- async def launch(self, headless, args, proxy=None):- # Assert that the proxy passed equals the dummy proxy provided in the configuration.- assert proxy == dummy_proxy, f"Expected proxy {dummy_proxy} but got {proxy}"- # We can also verify some base parameters if needed (headless, args) but our focus is proxy.- return DummyBrowser()- class DummyPlaywright:- def __init__(self):- self.chromium = DummyChromium()- async def stop(self):- pass- class DummyAsyncPlaywrightContext:- async def start(self):- return DummyPlaywright()- # Monkeypatch async_playwright to return our dummy async playwright context.- monkeypatch.setattr("browser_use.browser.browser.async_playwright", lambda: DummyAsyncPlaywrightContext())- # Create a BrowserConfig with the dummy proxy.- config = BrowserConfig(headless=False, disable_security=False, proxy=dummy_proxy)- browser_obj = Browser(config=config)- # Call get_playwright_browser and verify that the returned browser is as expected.- result_browser = await browser_obj.get_playwright_browser()- assert isinstance(result_browser, DummyBrowser), "Expected DummyBrowser from _setup_builtin_browser with proxy provided"- await browser_obj.close()+ """+ Test that when a proxy is provided in the BrowserConfig, the _setup_builtin_browser method+ correctly passes the proxy parameter to the playwright.chromium.launch method.+ This test sets up a dummy async_playwright context and verifies that the dummy proxy is received.+ """++ class DummyBrowser:+ pass++ # Create a dummy proxy settings instance.+ dummy_proxy = ProxySettings(server='http://dummy.proxy')++ class DummyChromium:+ async def launch(self, headless, args, proxy=None):+ # Assert that the proxy passed equals the dummy proxy provided in the configuration.+ assert proxy == dummy_proxy, f'Expected proxy {dummy_proxy} but got {proxy}'+ # We can also verify some base parameters if needed (headless, args) but our focus is proxy.+ return DummyBrowser()++ class DummyPlaywright:+ def __init__(self):+ self.chromium = DummyChromium()++ async def stop(self):+ pass++ class DummyAsyncPlaywrightContext:+ async def start(self):+ return DummyPlaywright()++ # Monkeypatch async_playwright to return our dummy async playwright context.+ monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())+ # Create a BrowserConfig with the dummy proxy.+ config = BrowserConfig(headless=False, disable_security=False, proxy=dummy_proxy)+ browser_obj = Browser(config=config)+ # Call get_playwright_browser and verify that the returned browser is as expected.+ result_browser = await browser_obj.get_playwright_browser()+ assert isinstance(result_browser, DummyBrowser), 'Expected DummyBrowser from _setup_builtin_browser with proxy provided'+ await browser_obj.close()diff --git a/tests/test_context.py b/tests/test_context.pyindex 0f1b26db6..9d59951e4 100644--- a/tests/test_context.py+++ b/tests/test_context.py@@ -9,319 +9,354 @@ from browser_use.dom.views import DOMElementNodedef test_is_url_allowed():- """- Test the _is_url_allowed method to verify that it correctly checks URLs against- the allowed domains configuration.- Scenario 1: When allowed_domains is None, all URLs should be allowed.- Scenario 2: When allowed_domains is a list, only URLs matching the allowed domain(s) are allowed.- Scenario 3: When the URL is malformed, it should return False.- """- # Create a dummy Browser mock. Only the 'config' attribute is needed for _is_url_allowed.- dummy_browser = Mock()- # Set an empty config for dummy_browser; it won't be used in _is_url_allowed.- dummy_browser.config = Mock()- # Scenario 1: allowed_domains is None, any URL should be allowed.- config1 = BrowserContextConfig(allowed_domains=None)- context1 = BrowserContext(browser=dummy_browser, config=config1)- assert context1._is_url_allowed("http://anydomain.com") is True- assert context1._is_url_allowed("https://anotherdomain.org/path") is True- # Scenario 2: allowed_domains is provided.- allowed = ["example.com", "mysite.org"]- config2 = BrowserContextConfig(allowed_domains=allowed)- context2 = BrowserContext(browser=dummy_browser, config=config2)- # URL exactly matching- assert context2._is_url_allowed("http://example.com") is True- # URL with subdomain (should be allowed)- assert context2._is_url_allowed("http://sub.example.com/path") is True- # URL with different domain (should not be allowed)- assert context2._is_url_allowed("http://notexample.com") is False- # URL that matches second allowed domain- assert context2._is_url_allowed("https://mysite.org/page") is True- # URL with port number, still allowed (port is stripped)- assert context2._is_url_allowed("http://example.com:8080") is True- # Scenario 3: Malformed URL or empty domain- # urlparse will return an empty netloc for some malformed URLs.- assert context2._is_url_allowed("notaurl") is False+ """+ Test the _is_url_allowed method to verify that it correctly checks URLs against+ the allowed domains configuration.+ Scenario 1: When allowed_domains is None, all URLs should be allowed.+ Scenario 2: When allowed_domains is a list, only URLs matching the allowed domain(s) are allowed.+ Scenario 3: When the URL is malformed, it should return False.+ """+ # Create a dummy Browser mock. Only the 'config' attribute is needed for _is_url_allowed.+ dummy_browser = Mock()+ # Set an empty config for dummy_browser; it won't be used in _is_url_allowed.+ dummy_browser.config = Mock()+ # Scenario 1: allowed_domains is None, any URL should be allowed.+ config1 = BrowserContextConfig(allowed_domains=None)+ context1 = BrowserContext(browser=dummy_browser, config=config1)+ assert context1._is_url_allowed('http://anydomain.com') is True+ assert context1._is_url_allowed('https://anotherdomain.org/path') is True+ # Scenario 2: allowed_domains is provided.+ allowed = ['example.com', 'mysite.org']+ config2 = BrowserContextConfig(allowed_domains=allowed)+ context2 = BrowserContext(browser=dummy_browser, config=config2)+ # URL exactly matching+ assert context2._is_url_allowed('http://example.com') is True+ # URL with subdomain (should be allowed)+ assert context2._is_url_allowed('http://sub.example.com/path') is True+ # URL with different domain (should not be allowed)+ assert context2._is_url_allowed('http://notexample.com') is False+ # URL that matches second allowed domain+ assert context2._is_url_allowed('https://mysite.org/page') is True+ # URL with port number, still allowed (port is stripped)+ assert context2._is_url_allowed('http://example.com:8080') is True+ # Scenario 3: Malformed URL or empty domain+ # urlparse will return an empty netloc for some malformed URLs.+ assert context2._is_url_allowed('notaurl') is False++def test_convert_simple_xpath_to_css_selector():- """- Test the _convert_simple_xpath_to_css_selector method of BrowserContext.- This verifies that simple XPath expressions (with and without indices) are correctly converted to CSS selectors.- """- # Test empty xpath returns empty string- assert BrowserContext._convert_simple_xpath_to_css_selector('') == ''- # Test a simple xpath without indices- xpath = "/html/body/div/span"- expected = "html > body > div > span"- result = BrowserContext._convert_simple_xpath_to_css_selector(xpath)- assert result == expected- # Test xpath with an index on one element: [2] should translate to :nth-of-type(2)- xpath = "/html/body/div[2]/span"- expected = "html > body > div:nth-of-type(2) > span"- result = BrowserContext._convert_simple_xpath_to_css_selector(xpath)- assert result == expected- # Test xpath with indices on multiple elements:- # For "li[3]" -> li:nth-of-type(3) and for "a[1]" -> a:nth-of-type(1)- xpath = "/ul/li[3]/a[1]"- expected = "ul > li:nth-of-type(3) > a:nth-of-type(1)"- result = BrowserContext._convert_simple_xpath_to_css_selector(xpath)- assert result == expected+ """+ Test the _convert_simple_xpath_to_css_selector method of BrowserContext.+ This verifies that simple XPath expressions (with and without indices) are correctly converted to CSS selectors.+ """+ # Test empty xpath returns empty string+ assert BrowserContext._convert_simple_xpath_to_css_selector('') == ''+ # Test a simple xpath without indices+ xpath = '/html/body/div/span'+ expected = 'html > body > div > span'+ result = BrowserContext._convert_simple_xpath_to_css_selector(xpath)+ assert result == expected+ # Test xpath with an index on one element: [2] should translate to :nth-of-type(2)+ xpath = '/html/body/div[2]/span'+ expected = 'html > body > div:nth-of-type(2) > span'+ result = BrowserContext._convert_simple_xpath_to_css_selector(xpath)+ assert result == expected+ # Test xpath with indices on multiple elements:+ # For "li[3]" -> li:nth-of-type(3) and for "a[1]" -> a:nth-of-type(1)+ xpath = '/ul/li[3]/a[1]'+ expected = 'ul > li:nth-of-type(3) > a:nth-of-type(1)'+ result = BrowserContext._convert_simple_xpath_to_css_selector(xpath)+ assert result == expected++def test_get_initial_state():- """- Test the _get_initial_state method to verify it returns the correct initial BrowserState.- The test checks that when a dummy page with a URL is provided,- the returned state contains that URL and other default values.- """- # Create a dummy browser since only its existence is needed.- dummy_browser = Mock()- dummy_browser.config = Mock()- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- # Define a dummy page with a 'url' attribute.- class DummyPage:- url = "http://dummy.com"- dummy_page = DummyPage()- # Call _get_initial_state with a page: URL should be set from page.url.- state_with_page = context._get_initial_state(page=dummy_page)- assert state_with_page.url == dummy_page.url- # Verify that the element_tree is initialized with tag 'root'- assert state_with_page.element_tree.tag_name == 'root'- # Call _get_initial_state without a page: URL should be empty.- state_without_page = context._get_initial_state()- assert state_without_page.url == ""+ """+ Test the _get_initial_state method to verify it returns the correct initial BrowserState.+ The test checks that when a dummy page with a URL is provided,+ the returned state contains that URL and other default values.+ """+ # Create a dummy browser since only its existence is needed.+ dummy_browser = Mock()+ dummy_browser.config = Mock()+ context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())++ # Define a dummy page with a 'url' attribute.+ class DummyPage:+ url = 'http://dummy.com'++ dummy_page = DummyPage()+ # Call _get_initial_state with a page: URL should be set from page.url.+ state_with_page = context._get_initial_state(page=dummy_page)+ assert state_with_page.url == dummy_page.url+ # Verify that the element_tree is initialized with tag 'root'+ assert state_with_page.element_tree.tag_name == 'root'+ # Call _get_initial_state without a page: URL should be empty.+ state_without_page = context._get_initial_state()+ assert state_without_page.url == ''++@pytest.mark.asyncioasync def test_execute_javascript():- """- Test the execute_javascript method by mocking the current page's evaluate function.- This ensures that when execute_javascript is called, it correctly returns the value- from the page's evaluate method.- """- # Define a dummy page with an async evaluate method.- class DummyPage:- async def evaluate(self, script):- return "dummy_result"- # Create a dummy session object with a dummy current_page.- dummy_session = type("DummySession", (), {})()- dummy_session.current_page = DummyPage()- # Create a dummy browser mock with a minimal config.- dummy_browser = Mock()- dummy_browser.config = Mock()- # Initialize the BrowserContext with the dummy browser and config.- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- # Manually set the session to our dummy session.- context.session = dummy_session- # Call execute_javascript and verify it returns the expected result.- result = await context.execute_javascript("return 1+1")- assert result == "dummy_result"+ """+ Test the execute_javascript method by mocking the current page's evaluate function.+ This ensures that when execute_javascript is called, it correctly returns the value+ from the page's evaluate method.+ """++ # Define a dummy page with an async evaluate method.+ class DummyPage:+ async def evaluate(self, script):+ return 'dummy_result'++ # Create a dummy session object with a dummy current_page.+ dummy_session = type('DummySession', (), {})()+ dummy_session.current_page = DummyPage()+ # Create a dummy browser mock with a minimal config.+ dummy_browser = Mock()+ dummy_browser.config = Mock()+ # Initialize the BrowserContext with the dummy browser and config.+ context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())+ # Manually set the session to our dummy session.+ context.session = dummy_session+ # Call execute_javascript and verify it returns the expected result.+ result = await context.execute_javascript('return 1+1')+ assert result == 'dummy_result'++@pytest.mark.asyncioasync def test_enhanced_css_selector_for_element():- """- Test the _enhanced_css_selector_for_element method to verify that- it returns the correct CSS selector string for a dummy DOMElementNode.- The test checks that:- - The provided xpath is correctly converted (handling indices),- - Class attributes are appended as CSS classes,- - Standard and dynamic attributes (including ones with special characters)- are correctly added to the selector.- """- # Create a dummy DOMElementNode instance with a complex set of attributes.- dummy_element = DOMElementNode(- tag_name="div",- is_visible=True,- parent=None,- xpath="/html/body/div[2]",- attributes={- "class": "foo bar",- "id": "my-id",- "placeholder": 'some "quoted" text',- "data-testid": "123"- },- children=[]- )- # Call the method with include_dynamic_attributes=True.- actual_selector = BrowserContext._enhanced_css_selector_for_element(dummy_element, include_dynamic_attributes=True)- # Expected conversion:- # 1. The xpath "/html/body/div[2]" converts to "html > body > div:nth-of-type(2)".- # 2. The class attribute "foo bar" appends ".foo.bar".- # 3. The "id" attribute is added as [id="my-id"].- # 4. The "placeholder" attribute contains quotes; it is added as- # [placeholder*="some \"quoted\" text"].- # 5. The dynamic attribute "data-testid" is added as [data-testid="123"].- expected_selector = 'html > body > div:nth-of-type(2).foo.bar[id="my-id"][placeholder*="some \\"quoted\\" text"][data-testid="123"]'- assert actual_selector == expected_selector, f"Expected {expected_selector}, but got {actual_selector}"+ """+ Test the _enhanced_css_selector_for_element method to verify that+ it returns the correct CSS selector string for a dummy DOMElementNode.+ The test checks that:+ - The provided xpath is correctly converted (handling indices),+ - Class attributes are appended as CSS classes,+ - Standard and dynamic attributes (including ones with special characters)+ are correctly added to the selector.+ """+ # Create a dummy DOMElementNode instance with a complex set of attributes.+ dummy_element = DOMElementNode(+ tag_name='div',+ is_visible=True,+ parent=None,+ xpath='/html/body/div[2]',+ attributes={'class': 'foo bar', 'id': 'my-id', 'placeholder': 'some "quoted" text', 'data-testid': '123'},+ children=[],+ )+ # Call the method with include_dynamic_attributes=True.+ actual_selector = BrowserContext._enhanced_css_selector_for_element(dummy_element, include_dynamic_attributes=True)+ # Expected conversion:+ # 1. The xpath "/html/body/div[2]" converts to "html > body > div:nth-of-type(2)".+ # 2. The class attribute "foo bar" appends ".foo.bar".+ # 3. The "id" attribute is added as [id="my-id"].+ # 4. The "placeholder" attribute contains quotes; it is added as+ # [placeholder*="some \"quoted\" text"].+ # 5. The dynamic attribute "data-testid" is added as [data-testid="123"].+ expected_selector = (+ 'html > body > div:nth-of-type(2).foo.bar[id="my-id"][placeholder*="some \\"quoted\\" text"][data-testid="123"]'+ )+ assert actual_selector == expected_selector, f'Expected {expected_selector}, but got {actual_selector}'++@pytest.mark.asyncioasync def test_get_scroll_info():- """- Test the get_scroll_info method by mocking the page's evaluate method.- This dummy page returns preset values for window.scrollY, window.innerHeight,- and document.documentElement.scrollHeight. The test then verifies that the- computed scroll information (pixels_above and pixels_below) match the expected values.- """- # Define a dummy page with an async evaluate method returning preset values.- class DummyPage:- async def evaluate(self, script):- if "window.scrollY" in script:- return 100 # scrollY- elif "window.innerHeight" in script:- return 500 # innerHeight- elif "document.documentElement.scrollHeight" in script:- return 1200 # total scrollable height- return None- # Create a dummy session with a dummy current_page.- dummy_session = type("DummySession", (), {})()- dummy_session.current_page = DummyPage()- # We also need a dummy context attribute but it won't be used in this test.- dummy_session.context = type("DummyContext", (), {})()- # Create a dummy browser mock.- dummy_browser = Mock()- dummy_browser.config = Mock()- # Initialize BrowserContext with the dummy browser and config.- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- # Manually set the session to our dummy session.- context.session = dummy_session- # Call get_scroll_info on the dummy page.- pixels_above, pixels_below = await context.get_scroll_info(dummy_session.current_page)- # Expected calculations:- # pixels_above = scrollY = 100- # pixels_below = total_height - (scrollY + innerHeight) = 1200 - (100 + 500) = 600- assert pixels_above == 100, f"Expected 100 pixels above, got {pixels_above}"- assert pixels_below == 600, f"Expected 600 pixels below, got {pixels_below}"+ """+ Test the get_scroll_info method by mocking the page's evaluate method.+ This dummy page returns preset values for window.scrollY, window.innerHeight,+ and document.documentElement.scrollHeight. The test then verifies that the+ computed scroll information (pixels_above and pixels_below) match the expected values.+ """++ # Define a dummy page with an async evaluate method returning preset values.+ class DummyPage:+ async def evaluate(self, script):+ if 'window.scrollY' in script:+ return 100 # scrollY+ elif 'window.innerHeight' in script:+ return 500 # innerHeight+ elif 'document.documentElement.scrollHeight' in script:+ return 1200 # total scrollable height+ return None++ # Create a dummy session with a dummy current_page.+ dummy_session = type('DummySession', (), {})()+ dummy_session.current_page = DummyPage()+ # We also need a dummy context attribute but it won't be used in this test.+ dummy_session.context = type('DummyContext', (), {})()+ # Create a dummy browser mock.+ dummy_browser = Mock()+ dummy_browser.config = Mock()+ # Initialize BrowserContext with the dummy browser and config.+ context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())+ # Manually set the session to our dummy session.+ context.session = dummy_session+ # Call get_scroll_info on the dummy page.+ pixels_above, pixels_below = await context.get_scroll_info(dummy_session.current_page)+ # Expected calculations:+ # pixels_above = scrollY = 100+ # pixels_below = total_height - (scrollY + innerHeight) = 1200 - (100 + 500) = 600+ assert pixels_above == 100, f'Expected 100 pixels above, got {pixels_above}'+ assert pixels_below == 600, f'Expected 600 pixels below, got {pixels_below}'++@pytest.mark.asyncioasync def test_reset_context():- """- Test the reset_context method to ensure it correctly closes all existing tabs,- resets the cached state, and creates a new page.- """- # Dummy Page with close and wait_for_load_state methods.- class DummyPage:- def __init__(self, url="http://dummy.com"):- self.url = url- self.closed = False- async def close(self):- self.closed = True- async def wait_for_load_state(self):- pass- # Dummy Context that holds pages and can create a new page.- class DummyContext:- def __init__(self):- self.pages = []- async def new_page(self):- new_page = DummyPage(url="")- self.pages.append(new_page)- return new_page- # Create a dummy session with a context containing two pages.- dummy_session = type("DummySession", (), {})()- dummy_context = DummyContext()- page1 = DummyPage(url="http://page1.com")- page2 = DummyPage(url="http://page2.com")- dummy_context.pages.extend([page1, page2])- dummy_session.context = dummy_context- dummy_session.current_page = page1- dummy_session.cached_state = None- # Create a dummy browser mock.- dummy_browser = Mock()- dummy_browser.config = Mock()- # Initialize BrowserContext using our dummy_browser and config,- # and manually set its session to our dummy session.- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- context.session = dummy_session- # Confirm session has 2 pages before reset.- assert len(dummy_session.context.pages) == 2- # Call reset_context which should close existing pages,- # reset the cached state, and create a new page as current_page.- await context.reset_context()- # Verify that initial pages were closed.- assert page1.closed is True- assert page2.closed is True- # Check that a new page is created and set as current_page.- assert dummy_session.current_page is not None- new_page = dummy_session.current_page- # New page URL should be empty as per _get_initial_state.- assert new_page.url == ""- # Verify that cached_state is reset to an initial BrowserState.- state = dummy_session.cached_state- assert isinstance(state, BrowserState)- assert state.url == ""- assert state.element_tree.tag_name == 'root'+ """+ Test the reset_context method to ensure it correctly closes all existing tabs,+ resets the cached state, and creates a new page.+ """++ # Dummy Page with close and wait_for_load_state methods.+ class DummyPage:+ def __init__(self, url='http://dummy.com'):+ self.url = url+ self.closed = False++ async def close(self):+ self.closed = True++ async def wait_for_load_state(self):+ pass++ # Dummy Context that holds pages and can create a new page.+ class DummyContext:+ def __init__(self):+ self.pages = []++ async def new_page(self):+ new_page = DummyPage(url='')+ self.pages.append(new_page)+ return new_page++ # Create a dummy session with a context containing two pages.+ dummy_session = type('DummySession', (), {})()+ dummy_context = DummyContext()+ page1 = DummyPage(url='http://page1.com')+ page2 = DummyPage(url='http://page2.com')+ dummy_context.pages.extend([page1, page2])+ dummy_session.context = dummy_context+ dummy_session.current_page = page1+ dummy_session.cached_state = None+ # Create a dummy browser mock.+ dummy_browser = Mock()+ dummy_browser.config = Mock()+ # Initialize BrowserContext using our dummy_browser and config,+ # and manually set its session to our dummy session.+ context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())+ context.session = dummy_session+ # Confirm session has 2 pages before reset.+ assert len(dummy_session.context.pages) == 2+ # Call reset_context which should close existing pages,+ # reset the cached state, and create a new page as current_page.+ await context.reset_context()+ # Verify that initial pages were closed.+ assert page1.closed is True+ assert page2.closed is True+ # Check that a new page is created and set as current_page.+ assert dummy_session.current_page is not None+ new_page = dummy_session.current_page+ # New page URL should be empty as per _get_initial_state.+ assert new_page.url == ''+ # Verify that cached_state is reset to an initial BrowserState.+ state = dummy_session.cached_state+ assert isinstance(state, BrowserState)+ assert state.url == ''+ assert state.element_tree.tag_name == 'root'++@pytest.mark.asyncioasync def test_take_screenshot():- """- Test the take_screenshot method to verify that it returns a base64 encoded screenshot string.- A dummy page with a mocked screenshot method is used, returning a predefined byte string.- """- class DummyPage:- async def screenshot(self, full_page, animations):- # Verify that parameters are forwarded correctly.- assert full_page is True, "full_page parameter was not correctly passed"- assert animations == 'disabled', "animations parameter was not correctly passed"- # Return a test byte string.- return b'test'- # Create a dummy session with the DummyPage as the current_page.- dummy_session = type("DummySession", (), {})()- dummy_session.current_page = DummyPage()- dummy_session.context = None # Not used in this test- # Create a dummy browser mock.- dummy_browser = Mock()- dummy_browser.config = Mock()- # Initialize the BrowserContext with the dummy browser and config.- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- # Manually set the session to our dummy session.- context.session = dummy_session- # Call take_screenshot and check that it returns the expected base64 encoded string.- result = await context.take_screenshot(full_page=True)- expected = base64.b64encode(b'test').decode('utf-8')- assert result == expected, f"Expected {expected}, but got {result}"+ """+ Test the take_screenshot method to verify that it returns a base64 encoded screenshot string.+ A dummy page with a mocked screenshot method is used, returning a predefined byte string.+ """++ class DummyPage:+ async def screenshot(self, full_page, animations):+ # Verify that parameters are forwarded correctly.+ assert full_page is True, 'full_page parameter was not correctly passed'+ assert animations == 'disabled', 'animations parameter was not correctly passed'+ # Return a test byte string.+ return b'test'++ # Create a dummy session with the DummyPage as the current_page.+ dummy_session = type('DummySession', (), {})()+ dummy_session.current_page = DummyPage()+ dummy_session.context = None # Not used in this test+ # Create a dummy browser mock.+ dummy_browser = Mock()+ dummy_browser.config = Mock()+ # Initialize the BrowserContext with the dummy browser and config.+ context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())+ # Manually set the session to our dummy session.+ context.session = dummy_session+ # Call take_screenshot and check that it returns the expected base64 encoded string.+ result = await context.take_screenshot(full_page=True)+ expected = base64.b64encode(b'test').decode('utf-8')+ assert result == expected, f'Expected {expected}, but got {result}'++@pytest.mark.asyncioasync def test_refresh_page_behavior():- """- Test the refresh_page method of BrowserContext to verify that it correctly reloads the current page- and waits for the page's load state. This is done by creating a dummy page that flags when its- reload and wait_for_load_state methods are called.- """- class DummyPage:- def __init__(self):- self.reload_called = False- self.wait_for_load_state_called = False- async def reload(self):- self.reload_called = True- async def wait_for_load_state(self):- self.wait_for_load_state_called = True- # Create a dummy session with the dummy page as the current_page.- dummy_page = DummyPage()- dummy_session = type("DummySession", (), {})()- dummy_session.current_page = dummy_page- dummy_session.context = None # Not required for this test- # Create a dummy browser mock- dummy_browser = Mock()- dummy_browser.config = Mock()- # Initialize BrowserContext with the dummy browser and config,- # and manually set its session to our dummy session.- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- context.session = dummy_session- # Call refresh_page and verify that reload and wait_for_load_state were called.- await context.refresh_page()- assert dummy_page.reload_called is True, "Expected the page to call reload()"- assert dummy_page.wait_for_load_state_called is True, "Expected the page to call wait_for_load_state()"+ """+ Test the refresh_page method of BrowserContext to verify that it correctly reloads the current page+ and waits for the page's load state. This is done by creating a dummy page that flags when its+ reload and wait_for_load_state methods are called.+ """++ class DummyPage:+ def __init__(self):+ self.reload_called = False+ self.wait_for_load_state_called = False++ async def reload(self):+ self.reload_called = True++ async def wait_for_load_state(self):+ self.wait_for_load_state_called = True++ # Create a dummy session with the dummy page as the current_page.+ dummy_page = DummyPage()+ dummy_session = type('DummySession', (), {})()+ dummy_session.current_page = dummy_page+ dummy_session.context = None # Not required for this test+ # Create a dummy browser mock+ dummy_browser = Mock()+ dummy_browser.config = Mock()+ # Initialize BrowserContext with the dummy browser and config,+ # and manually set its session to our dummy session.+ context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())+ context.session = dummy_session+ # Call refresh_page and verify that reload and wait_for_load_state were called.+ await context.refresh_page()+ assert dummy_page.reload_called is True, 'Expected the page to call reload()'+ assert dummy_page.wait_for_load_state_called is True, 'Expected the page to call wait_for_load_state()'++@pytest.mark.asyncioasync def test_remove_highlights_failure():- """- Test the remove_highlights method to ensure that if the page.evaluate call fails,- the exception is caught and does not propagate (i.e. the method handles errors gracefully).- """- # Dummy page that always raises an exception when evaluate is called.- class DummyPage:- async def evaluate(self, script):- raise Exception("dummy error")- # Create a dummy session with the DummyPage as current_page.- dummy_session = type("DummySession", (), {})()- dummy_session.current_page = DummyPage()- dummy_session.context = None # Not used in this test- # Create a dummy browser mock.- dummy_browser = Mock()- dummy_browser.config = Mock()- # Initialize BrowserContext with the dummy browser and configuration.- context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())- context.session = dummy_session- # Call remove_highlights and verify that no exception is raised.- try:- await context.remove_highlights()- except Exception as e:- pytest.fail(f"remove_highlights raised an exception: {e}")+ """+ Test the remove_highlights method to ensure that if the page.evaluate call fails,+ the exception is caught and does not propagate (i.e. the method handles errors gracefully).+ """++ # Dummy page that always raises an exception when evaluate is called.+ class DummyPage:+ async def evaluate(self, script):+ raise Exception('dummy error')++ # Create a dummy session with the DummyPage as current_page.+ dummy_session = type('DummySession', (), {})()+ dummy_session.current_page = DummyPage()+ dummy_session.context = None # Not used in this test+ # Create a dummy browser mock.+ dummy_browser = Mock()+ dummy_browser.config = Mock()+ # Initialize BrowserContext with the dummy browser and configuration.+ context = BrowserContext(browser=dummy_browser, config=BrowserContextConfig())+ context.session = dummy_session+ # Call remove_highlights and verify that no exception is raised.+ try:+ await context.remove_highlights()+ except Exception as e:+ pytest.fail(f'remove_highlights raised an exception: {e}')diff --git a/tests/test_dropdown.py b/tests/test_dropdown.pyindex 927bc5434..a6af88a5e 100644--- a/tests/test_dropdown.py+++ b/tests/test_dropdown.py@@ -1,6 +1,7 @@"""Test dropdown interaction functionality."""+import pytestfrom browser_use.agent.service import Agent@@ -9,31 +10,31 @@ from browser_use.agent.views import AgentHistoryList@pytest.mark.asyncioasync def test_dropdown(llm, browser_context):- """Test selecting an option from a dropdown menu."""- agent = Agent(- task=(- 'go to https://codepen.io/geheimschriftstift/pen/mPLvQz and first get all options for the dropdown and then select the 5th option'- ),- llm=llm,- browser_context=browser_context,- )-- try:- history: AgentHistoryList = await agent.run(20)- result = history.final_result()-- # Verify dropdown interaction- assert result is not None- assert 'Duck' in result, "Expected 5th option 'Duck' to be selected"-- # Verify dropdown state- element = await browser_context.get_element_by_selector('select')- assert element is not None, "Dropdown element should exist"-- value = await element.evaluate('el => el.value')- assert value == '5', "Dropdown should have 5th option selected"-- except Exception as e:- pytest.fail(f"Dropdown test failed: {str(e)}")- finally:- await browser_context.close()+ """Test selecting an option from a dropdown menu."""+ agent = Agent(+ task=(+ 'go to https://codepen.io/geheimschriftstift/pen/mPLvQz and first get all options for the dropdown and then select the 5th option'+ ),+ llm=llm,+ browser_context=browser_context,+ )++ try:+ history: AgentHistoryList = await agent.run(20)+ result = history.final_result()++ # Verify dropdown interaction+ assert result is not None+ assert 'Duck' in result, "Expected 5th option 'Duck' to be selected"++ # Verify dropdown state+ element = await browser_context.get_element_by_selector('select')+ assert element is not None, 'Dropdown element should exist'++ value = await element.evaluate('el => el.value')+ assert value == '5', 'Dropdown should have 5th option selected'++ except Exception as e:+ pytest.fail(f'Dropdown test failed: {str(e)}')+ finally:+ await browser_context.close()diff --git a/tests/test_dropdown_complex.py b/tests/test_dropdown_complex.pyindex 26066445f..ffa2efdab 100644--- a/tests/test_dropdown_complex.py+++ b/tests/test_dropdown_complex.py@@ -1,6 +1,7 @@"""Test complex dropdown interaction functionality."""+import pytestfrom browser_use.agent.service import Agent@@ -9,35 +10,35 @@ from browser_use.agent.views import AgentHistoryList@pytest.mark.asyncioasync def test_dropdown_complex(llm, browser_context):- """Test selecting an option from a complex dropdown menu."""- agent = Agent(- task=(- 'go to https://codepen.io/shyam-king/pen/pvzpByJ and first get all options for the dropdown and then select the json option'- ),- llm=llm,- browser_context=browser_context,- )-- try:- history: AgentHistoryList = await agent.run(20)- result = history.final_result()-- # Verify dropdown interaction- assert result is not None- assert 'json' in result.lower(), "Expected 'json' option to be selected"-- # Verify dropdown state- element = await browser_context.get_element_by_selector('.select-selected')- assert element is not None, "Custom dropdown element should exist"-- text = await element.text_content()- assert 'json' in text.lower(), "Dropdown should display json option"-- # Verify the selected option's effect- code_element = await browser_context.get_element_by_selector('pre code')- assert code_element is not None, "Code element should be visible when JSON is selected"-- except Exception as e:- pytest.fail(f"Complex dropdown test failed: {str(e)}")- finally:- await browser_context.close()+ """Test selecting an option from a complex dropdown menu."""+ agent = Agent(+ task=(+ 'go to https://codepen.io/shyam-king/pen/pvzpByJ and first get all options for the dropdown and then select the json option'+ ),+ llm=llm,+ browser_context=browser_context,+ )++ try:+ history: AgentHistoryList = await agent.run(20)+ result = history.final_result()++ # Verify dropdown interaction+ assert result is not None+ assert 'json' in result.lower(), "Expected 'json' option to be selected"++ # Verify dropdown state+ element = await browser_context.get_element_by_selector('.select-selected')+ assert element is not None, 'Custom dropdown element should exist'++ text = await element.text_content()+ assert 'json' in text.lower(), 'Dropdown should display json option'++ # Verify the selected option's effect+ code_element = await browser_context.get_element_by_selector('pre code')+ assert code_element is not None, 'Code element should be visible when JSON is selected'++ except Exception as e:+ pytest.fail(f'Complex dropdown test failed: {str(e)}')+ finally:+ await browser_context.close()diff --git a/tests/test_dropdown_error.py b/tests/test_dropdown_error.pyindex 4f23bc932..fe1a28d6d 100644--- a/tests/test_dropdown_error.py+++ b/tests/test_dropdown_error.py@@ -20,9 +20,7 @@ llm = ChatOpenAI(model='gpt-4o')# browser = Browser(config=BrowserConfig(headless=False))agent = Agent(- task=(- 'go to https://codepen.io/shyam-king/pen/emOyjKm and select number "4" and return the output of "selected value"'- ),+ task=('go to https://codepen.io/shyam-king/pen/emOyjKm and select number "4" and return the output of "selected value"'),llm=llm,browser_context=BrowserContext(browser=Browser(config=BrowserConfig(headless=False, disable_security=True)),diff --git a/tests/test_gif_path.py b/tests/test_gif_path.pyindex a85171481..d9e327695 100644--- a/tests/test_gif_path.py+++ b/tests/test_gif_path.py@@ -19,24 +19,22 @@ from browser_use import Agent, AgentHistoryListllm = ChatOpenAI(model='gpt-4o')agent = Agent(- task=(- 'go to google.com and search for text "hi there"'- ),+ task=('go to google.com and search for text "hi there"'),llm=llm,browser_context=BrowserContext(browser=Browser(config=BrowserConfig(headless=False, disable_security=True)),),- generate_gif="./google.gif"+ generate_gif='./google.gif',)async def test_gif_path():- if os.path.exists("./google.gif"):- os.unlink("./google.gif")+ if os.path.exists('./google.gif'):+ os.unlink('./google.gif')history: AgentHistoryList = await agent.run(20)result = history.final_result()assert result is not None- assert os.path.exists("./google.gif"), "google.gif was not created"+ assert os.path.exists('./google.gif'), 'google.gif was not created'diff --git a/tests/test_mind2web.py b/tests/test_mind2web.pyindex 1bbd3c907..756f18568 100644--- a/tests/test_mind2web.py+++ b/tests/test_mind2web.py@@ -83,7 +83,7 @@ async def test_random_samples(test_cases: List[Dict[str, Any]], llm, context, vasamples = random.sample(test_cases, 1)for i, case in enumerate(samples, 1):- task = f"Go to {case['website']}.com and {case['confirmed_task']}"+ task = f'Go to {case["website"]}.com and {case["confirmed_task"]}'logger.info(f'--- Random Sample {i}/{len(samples)} ---')logger.info(f'Task: {task}\n')diff --git a/tests/test_wait_for_element.py b/tests/test_wait_for_element.pyindex a716e05b0..4ffe51cff 100644--- a/tests/test_wait_for_element.py+++ b/tests/test_wait_for_element.py@@ -4,7 +4,7 @@ import sysproject_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))if project_root not in sys.path:- sys.path.insert(0, project_root)+ sys.path.insert(0, project_root)import pytestfrom dotenv import load_dotenv@@ -24,43 +24,45 @@ load_dotenv()llm = ChatOpenAI(model='gpt-4o')controller = Controller()+@pytest.mark.skip(reason='this is for local testing only')async def test_wait_for_element():- """Test 'Wait for element' action."""-- initial_actions = [- {'open_tab': {'url': 'https://pypi.org/'}},- # Uncomment the line below to include the wait action in initial actions.- # {'wait_for_element': {'selector': '#search', 'timeout': 30}},- ]-- # Set up the browser context.- context = BrowserContext(- browser=Browser(config=BrowserConfig(headless=False, disable_security=True)),- )-- # Create the agent with the task.- agent = Agent(- task="Wait for element '#search' to be visible with a timeout of 30 seconds.",- llm=llm,- browser_context=context,- initial_actions=initial_actions,- controller=controller- )-- # Run the agent for a few steps to trigger navigation and then the wait action.- history = await agent.run(max_steps=3)- action_names = history.action_names()-- # Ensure that the wait_for_element action was executed.- assert 'wait_for_element' in action_names, "Expected wait_for_element action to be executed."-- # Verify that the #search element is visible by querying the page.- page = await context.get_current_page()- header_handle = await page.query_selector("#search")- assert header_handle is not None, "Expected to find a #search element on the page."- is_visible = await header_handle.is_visible()- assert is_visible, "Expected the #search element to be visible."-+ """Test 'Wait for element' action."""++ initial_actions = [+ {'open_tab': {'url': 'https://pypi.org/'}},+ # Uncomment the line below to include the wait action in initial actions.+ # {'wait_for_element': {'selector': '#search', 'timeout': 30}},+ ]++ # Set up the browser context.+ context = BrowserContext(+ browser=Browser(config=BrowserConfig(headless=False, disable_security=True)),+ )++ # Create the agent with the task.+ agent = Agent(+ task="Wait for element '#search' to be visible with a timeout of 30 seconds.",+ llm=llm,+ browser_context=context,+ initial_actions=initial_actions,+ controller=controller,+ )++ # Run the agent for a few steps to trigger navigation and then the wait action.+ history = await agent.run(max_steps=3)+ action_names = history.action_names()++ # Ensure that the wait_for_element action was executed.+ assert 'wait_for_element' in action_names, 'Expected wait_for_element action to be executed.'++ # Verify that the #search element is visible by querying the page.+ page = await context.get_current_page()+ header_handle = await page.query_selector('#search')+ assert header_handle is not None, 'Expected to find a #search element on the page.'+ is_visible = await header_handle.is_visible()+ assert is_visible, 'Expected the #search element to be visible.'++if __name__ == '__main__':- asyncio.run(test_wait_for_element())+ asyncio.run(test_wait_for_element())