Skip to content

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

checkpoint before checking out main

MagellaX90f7cba3be9d
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 626fa9469..085068d8d 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -472,7 +472,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):
self._last_known_downloads: list[str] = []
self.logger.info('📁 Initialized download tracking for agent')
- # Pause event is now managed in AgentState - no separate attribute needed
+ # Event-based pause control (kept out of AgentState for serialization)
+ self._pause_event = asyncio.Event()
+ self._pause_event.set()
@property
def logger(self) -> logging.Logger:
@@ -1226,7 +1228,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# Use the consolidated pause state management
if self.state.paused:
self.logger.debug(f'⏸️ Step {step}: Agent paused, waiting to resume...')
- await self.state.wait_until_resumed()
+ await self._pause_event.wait()
signal_handler.reset()
# Check if we should stop due to too many failures
@@ -1617,7 +1619,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
print(
'\n\n⏸️ Got [Ctrl+C], paused the agent and left the browser open.\n\tPress [Enter] to resume or [Ctrl+C] again to quit.'
)
- self.state.pause()
+ self.state.paused = True
+ self._pause_event.clear()
# Task paused
@@ -1628,7 +1631,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):
"""Resume the agent"""
print('----------------------------------------------------------------------')
print('▶️ Got Enter, resuming agent execution where it left off...\n')
- self.state.resume()
+ self.state.paused = False
+ self._pause_event.set()
# Task resumed
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index c67e4c427..1c3507bc0 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -83,37 +83,13 @@ class AgentState(BaseModel):
last_plan: str | None = None
last_model_output: AgentOutput | None = None
- # Consolidated pause/resume state management
- # The pause_event serves as the single source of truth for pause state
- # When set: agent is running, when cleared: agent is paused
- pause_event: asyncio.Event = Field(default_factory=lambda: asyncio.Event(), exclude=True, repr=False)
+ # Pause/resume state (kept serialisable for checkpointing)
+ paused: bool = False
stopped: bool = False
message_manager_state: MessageManagerState = Field(default_factory=MessageManagerState)
file_system_state: FileSystemState | None = None
- def __init__(self, **data):
- super().__init__(**data)
- # Ensure pause_event is initially set (not paused)
- if not self.pause_event.is_set():
- self.pause_event.set()
-
- @property
- def paused(self) -> bool:
- """Check if agent is paused by examining the pause event"""
- return not self.pause_event.is_set()
-
- def pause(self) -> None:
- """Pause the agent by clearing the pause event"""
- self.pause_event.clear()
-
- def resume(self) -> None:
- """Resume the agent by setting the pause event"""
- self.pause_event.set()
-
- async def wait_until_resumed(self) -> None:
- """Wait until the agent is resumed"""
- await self.pause_event.wait()
@dataclass
diff --git a/examples/models/langchain/chat.py b/examples/models/langchain/chat.py
index 5313189e5..08502c4bf 100644
--- a/examples/models/langchain/chat.py
+++ b/examples/models/langchain/chat.py
@@ -27,6 +27,9 @@ class ChatLangchain(BaseChatModel):
# The LangChain model to wrap
chat: 'LangChainBaseChatModel'
+ # Option to disable structured output when using incompatible APIs
+ disable_structured_output: bool = False
+
@property
def model(self) -> str:
return self.name
@@ -105,7 +108,7 @@ class ChatLangchain(BaseChatModel):
Args:
messages: List of browser-use chat messages
- output_format: Optional Pydantic model class for structured output (not supported in basic LangChain integration)
+ output_format: Optional Pydantic model class for structured output
Returns:
Either a string response or an instance of output_format
@@ -139,24 +142,56 @@ class ChatLangchain(BaseChatModel):
else:
# Use LangChain's structured output capability
- try:
- structured_chat = self.chat.with_structured_output(output_format)
- parsed_object = await structured_chat.ainvoke(langchain_messages)
+ structured_output_success = False
+ response = None
+
+ # First, try to use structured output if not disabled
+ if not self.disable_structured_output:
+ try:
+ # For LangChain OpenAI models, disable json_schema mode if it's causing issues
+ if hasattr(self.chat, 'model_kwargs'):
+ # Temporarily modify model kwargs to use json_mode instead of json_schema
+ original_kwargs = getattr(self.chat, 'model_kwargs', {})
+ self.chat.model_kwargs = {**original_kwargs}
+
+ # Check if this is a ChatOpenAI model with structured output issues
+ if self.chat.__class__.__name__ == 'ChatOpenAI':
+ # Use method="function_calling" instead of default "json_mode"
+ structured_chat = self.chat.with_structured_output(output_format, method='function_calling')
+ else:
+ structured_chat = self.chat.with_structured_output(output_format)
+ else:
+ structured_chat = self.chat.with_structured_output(output_format)
- # For structured output, usage metadata is typically not available
- # in the parsed object since it's a Pydantic model, not an AIMessage
- usage = None
+ parsed_object = await structured_chat.ainvoke(langchain_messages)
+ structured_output_success = True
- # Type cast since LangChain's with_structured_output returns the correct type
- return ChatInvokeCompletion(
- completion=parsed_object, # type: ignore
- usage=usage,
- )
- except AttributeError:
- # Fall back to manual parsing if with_structured_output is not available
+ # For structured output, usage metadata is typically not available
+ # in the parsed object since it's a Pydantic model, not an AIMessage
+ usage = None
+
+ # Type cast since LangChain's with_structured_output returns the correct type
+ return ChatInvokeCompletion(
+ completion=parsed_object, # type: ignore
+ usage=usage,
+ )
+ except Exception as e:
+ # If structured output fails, fall back to manual parsing
+ # This handles cases where the API doesn't support json_schema
+ if 'json_schema' in str(e) or 'response_format' in str(e):
+ # Fall through to manual parsing
+ pass
+ else:
+ # Re-raise other errors
+ raise
+
+ # Fall back to manual parsing if structured output failed or was disabled
+ if not structured_output_success:
response = await self.chat.ainvoke(langchain_messages) # type: ignore
- if not isinstance(response, 'LangChainAIMessage'):
+ from langchain_core.messages import AIMessage as LangChainAIMessage # type: ignore
+
+ if not isinstance(response, LangChainAIMessage):
raise ModelProviderError(
message=f'Response is not an AIMessage: {type(response)}',
model=self.name,
@@ -168,7 +203,15 @@ class ChatLangchain(BaseChatModel):
if isinstance(content, str):
import json
- parsed_data = json.loads(content)
+ # Try to extract JSON from the content
+ # Handle cases where the model returns markdown code blocks
+ content_str = str(content).strip()
+ if content_str.startswith('```json') and content_str.endswith('```'):
+ content_str = content_str[7:-3].strip()
+ elif content_str.startswith('```') and content_str.endswith('```'):
+ content_str = content_str[3:-3].strip()
+
+ parsed_data = json.loads(content_str)
if isinstance(parsed_data, dict):
parsed_object = output_format(**parsed_data)
else:
@@ -177,7 +220,7 @@ class ChatLangchain(BaseChatModel):
raise ValueError('Content is not a string and structured output not supported')
except Exception as e:
raise ModelProviderError(
- message=f'Failed to parse response as {output_format.__name__}: {e}',
+ message=f'Failed to parse response as {output_format.__name__}: {e}. Consider using disable_structured_output=True for APIs that do not support structured output.',
model=self.name,
) from e
@@ -187,6 +230,9 @@ class ChatLangchain(BaseChatModel):
usage=usage,
)
+ except ModelProviderError:
+ # Re-raise our own errors
+ raise
except Exception as e:
# Convert any LangChain errors to browser-use ModelProviderError
raise ModelProviderError(
diff --git a/examples/use-cases/shopping.py b/examples/use-cases/shopping.py
index fda19db13..e6404a1a3 100644
--- a/examples/use-cases/shopping.py
+++ b/examples/use-cases/shopping.py
@@ -107,7 +107,7 @@ At this stage, check the basket on the top right (indicates the price) and check
- **Total cost**.
- **Chosen delivery time**.
-**Important:** Ensure efficiency and accuracy throughout the process."""
+**Important:** Ensure efficiency and accuracy throughout the process."""""""
browser_session = BrowserSession()