code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def decode_unicode_escapes_to_utf8(text: str) -> str: """Handle decoding any unicode escape sequences embedded in a string (needed to render non-ASCII languages like chinese or arabic in the GIF overlay text)""" if r'\u' not in text: # doesn't have any escape sequences that need to be decoded return text try: ...
Handle decoding any unicode escape sequences embedded in a string (needed to render non-ASCII languages like chinese or arabic in the GIF overlay text)
decode_unicode_escapes_to_utf8
python
browser-use/browser-use
browser_use/agent/gif.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/gif.py
MIT
def _create_task_frame( task: str, first_screenshot: str, title_font: ImageFont.FreeTypeFont, regular_font: ImageFont.FreeTypeFont, logo: Image.Image | None = None, line_spacing: float = 1.5, ) -> Image.Image: """Create initial frame showing the task.""" from PIL import Image, ImageDraw, ImageFont img_data = ...
Create initial frame showing the task.
_create_task_frame
python
browser-use/browser-use
browser_use/agent/gif.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/gif.py
MIT
def _add_overlay_to_image( image: Image.Image, step_number: int, goal_text: str, regular_font: ImageFont.FreeTypeFont, title_font: ImageFont.FreeTypeFont, margin: int, logo: Image.Image | None = None, display_step: bool = True, text_color: tuple[int, int, int, int] = (255, 255, 255, 255), text_box_color: tupl...
Add step number and goal overlay to an image.
_add_overlay_to_image
python
browser-use/browser-use
browser_use/agent/gif.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/gif.py
MIT
def _wrap_text(text: str, font: ImageFont.FreeTypeFont, max_width: int) -> str: """ Wrap text to fit within a given width. Args: text: Text to wrap font: Font to use for text max_width: Maximum width in pixels Returns: Wrapped text with newlines """ text = decode_unicode_escapes_to_utf8(text...
Wrap text to fit within a given width. Args: text: Text to wrap font: Font to use for text max_width: Maximum width in pixels Returns: Wrapped text with newlines
_wrap_text
python
browser-use/browser-use
browser_use/agent/gif.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/gif.py
MIT
def _load_prompt_template(self) -> None: """Load the prompt template from the markdown file.""" try: # This works both in development and when installed as a package with importlib.resources.files('browser_use.agent').joinpath('system_prompt.md').open('r') as f: self.prompt_template = f.read() except Ex...
Load the prompt template from the markdown file.
_load_prompt_template
python
browser-use/browser-use
browser_use/agent/prompts.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/prompts.py
MIT
def get_system_message( self, is_planner_reasoning: bool, extended_planner_system_prompt: str | None = None ) -> SystemMessage | HumanMessage: """Get the system message for the planner. Args: is_planner_reasoning: If True, return as HumanMessage for chain-of-thought extended_planner_system_prompt: O...
Get the system message for the planner. Args: is_planner_reasoning: If True, return as HumanMessage for chain-of-thought extended_planner_system_prompt: Optional text to append to the base prompt Returns: SystemMessage or HumanMessage depending on is_planner_reasoning
get_system_message
python
browser-use/browser-use
browser_use/agent/prompts.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/prompts.py
MIT
def _set_browser_use_version_and_source(self, source_override: str | None = None) -> None: """Get the version from pyproject.toml and determine the source of the browser-use package""" # Use the helper function for version detection version = get_browser_use_version() # Determine source try: package_root ...
Get the version from pyproject.toml and determine the source of the browser-use package
_set_browser_use_version_and_source
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
def _setup_action_models(self) -> None: """Setup dynamic action models from controller's registry""" # Initially only include actions with no filters self.ActionModel = self.controller.registry.create_action_model() # Create output model with the dynamic actions self.AgentOutput = AgentOutput.type_with_custom...
Setup dynamic action models from controller's registry
_setup_action_models
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
async def _test_tool_calling_method_async(self, method: str) -> tuple[str, bool]: """Test if a specific tool calling method works with the current LLM (async version).""" # Run the synchronous test in a thread pool to avoid blocking loop = asyncio.get_event_loop() result = await loop.run_in_executor(None, self....
Test if a specific tool calling method works with the current LLM (async version).
_test_tool_calling_method_async
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
def _get_known_tool_calling_method(self) -> str | None: """Get known tool calling method for common model/library combinations.""" # Fast path for known combinations model_lower = self.model_name.lower() # OpenAI models if self.chat_model_library == 'ChatOpenAI': if any(m in model_lower for m in ['gpt-4',...
Get known tool calling method for common model/library combinations.
_get_known_tool_calling_method
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
def add_new_task(self, new_task: str) -> None: """Add a new task to the agent, keeping the same task_id as tasks are continuous""" # Simply delegate to message manager - no need for new task_id or events # The task continues with new instructions, it doesn't end and start a new one self.task = new_task self._...
Add a new task to the agent, keeping the same task_id as tasks are continuous
add_new_task
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
async def _raise_if_stopped_or_paused(self) -> None: """Utility function that raises an InterruptedError if the agent is stopped or paused.""" if self.register_external_agent_status_raise_error_callback: if await self.register_external_agent_status_raise_error_callback(): raise InterruptedError if self.s...
Utility function that raises an InterruptedError if the agent is stopped or paused.
_raise_if_stopped_or_paused
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
def _convert_input_messages(self, input_messages: list[BaseMessage]) -> list[BaseMessage]: """Convert input messages to the correct format""" if is_model_without_tool_support(self.model_name): return convert_input_messages(input_messages, self.model_name) else: return input_messages
Convert input messages to the correct format
_convert_input_messages
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
async def get_next_action(self, input_messages: list[BaseMessage]) -> AgentOutput: """Get next action from LLM based on current state""" input_messages = self._convert_input_messages(input_messages) if self.tool_calling_method == 'raw': self._log_llm_call_info(input_messages, self.tool_calling_method) try:...
Get next action from LLM based on current state
get_next_action
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
def _log_agent_event(self, max_steps: int, agent_run_error: str | None = None) -> None: """Sent the agent event for this run to telemetry""" # Prepare action_history data correctly action_history_data = [] for item in self.state.history.history: if item.model_output and item.model_output.action: # Conve...
Sent the agent event for this run to telemetry
_log_agent_event
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
async def take_step(self) -> tuple[bool, bool]: """Take a step Returns: Tuple[bool, bool]: (is_done, is_valid) """ await self.step() if self.state.history.is_done(): if self.settings.validate_output: if not await self._validate_output(): return True, False await self.log_completion() i...
Take a step Returns: Tuple[bool, bool]: (is_done, is_valid)
take_step
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
async def rerun_history( self, history: AgentHistoryList, max_retries: int = 3, skip_failures: bool = True, delay_between_actions: float = 2.0, ) -> list[ActionResult]: """ Rerun a saved history of actions with error handling and retry logic. Args: history: The history to replay max_retries: M...
Rerun a saved history of actions with error handling and retry logic. Args: history: The history to replay max_retries: Maximum number of retries per action skip_failures: Whether to skip failed actions or stop execution delay_between_actions: Delay between actions in seconds Returns: List ...
rerun_history
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
async def _execute_history_step(self, history_item: AgentHistory, delay: float) -> list[ActionResult]: """Execute a single step from history with element validation""" state = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=False) if not state or not history_item.model_output: rais...
Execute a single step from history with element validation
_execute_history_step
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
async def _update_action_indices( self, historical_element: DOMHistoryElement | None, action: ActionModel, # Type this properly based on your action model browser_state_summary: BrowserStateSummary, ) -> ActionModel | None: """ Update action indices based on current page state. Returns updated action or...
Update action indices based on current page state. Returns updated action or None if element cannot be found.
_update_action_indices
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
async def load_and_rerun(self, history_file: str | Path | None = None, **kwargs) -> list[ActionResult]: """ Load history from file and rerun it. Args: history_file: Path to the history file **kwargs: Additional arguments passed to rerun_history """ if not history_file: history_file = 'AgentHistory...
Load history from file and rerun it. Args: history_file: Path to the history file **kwargs: Additional arguments passed to rerun_history
load_and_rerun
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
def _convert_initial_actions(self, actions: list[dict[str, dict[str, Any]]]) -> list[ActionModel]: """Convert dictionary-based actions to ActionModel instances""" converted_actions = [] action_model = self.ActionModel for action_dict in actions: # Each action_dict should have a single key-value pair actio...
Convert dictionary-based actions to ActionModel instances
_convert_initial_actions
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
def _verify_and_setup_llm(self) -> bool: """ Verify that the LLM API keys are setup and the LLM API is responding properly. Also handles tool calling method detection if in auto mode. """ self.tool_calling_method = self._set_tool_calling_method() # Skip verification if already done if getattr(self.llm, '...
Verify that the LLM API keys are setup and the LLM API is responding properly. Also handles tool calling method detection if in auto mode.
_verify_and_setup_llm
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
async def _run_planner(self) -> str | None: """Run the planner to analyze state and suggest next steps""" # Skip planning if no planner_llm is set if not self.settings.planner_llm: return None # Get current state to filter actions by page page = await self.browser_session.get_current_page() # Get all s...
Run the planner to analyze state and suggest next steps
_run_planner
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
async def _update_action_models_for_page(self, page) -> None: """Update action models with page-specific actions""" # Create new action model with current page's filtered actions self.ActionModel = self.controller.registry.create_action_model(page=page) # Update output model with the new actions self.AgentOut...
Update action models with page-specific actions
_update_action_models_for_page
python
browser-use/browser-use
browser_use/agent/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/service.py
MIT
def total_duration_seconds(self) -> float: """Get total duration of all steps in seconds""" total = 0.0 for h in self.history: if h.metadata: total += h.metadata.duration_seconds return total
Get total duration of all steps in seconds
total_duration_seconds
python
browser-use/browser-use
browser_use/agent/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/views.py
MIT
def save_to_file(self, filepath: str | Path) -> None: """Save history to JSON file with proper serialization""" try: Path(filepath).parent.mkdir(parents=True, exist_ok=True) data = self.model_dump() with open(filepath, 'w', encoding='utf-8') as f: json.dump(data, f, indent=2) except Exception as e: ...
Save history to JSON file with proper serialization
save_to_file
python
browser-use/browser-use
browser_use/agent/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/views.py
MIT
def model_dump(self, **kwargs) -> dict[str, Any]: """Custom serialization that properly uses AgentHistory's model_dump""" return { 'history': [h.model_dump(**kwargs) for h in self.history], }
Custom serialization that properly uses AgentHistory's model_dump
model_dump
python
browser-use/browser-use
browser_use/agent/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/views.py
MIT
def errors(self) -> list[str | None]: """Get all errors from history, with None for steps without errors""" errors = [] for h in self.history: step_errors = [r.error for r in h.result if r.error] # each step can have only one error errors.append(step_errors[0] if step_errors else None) return errors
Get all errors from history, with None for steps without errors
errors
python
browser-use/browser-use
browser_use/agent/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/views.py
MIT
def is_done(self) -> bool: """Check if the agent is done""" if self.history and len(self.history[-1].result) > 0: last_result = self.history[-1].result[-1] return last_result.is_done is True return False
Check if the agent is done
is_done
python
browser-use/browser-use
browser_use/agent/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/views.py
MIT
def is_successful(self) -> bool | None: """Check if the agent completed successfully - the agent decides in the last step if it was successful or not. None if not done yet.""" if self.history and len(self.history[-1].result) > 0: last_result = self.history[-1].result[-1] if last_result.is_done is True: re...
Check if the agent completed successfully - the agent decides in the last step if it was successful or not. None if not done yet.
is_successful
python
browser-use/browser-use
browser_use/agent/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/views.py
MIT
def action_names(self) -> list[str]: """Get all action names from history""" action_names = [] for action in self.model_actions(): actions = list(action.keys()) if actions: action_names.append(actions[0]) return action_names
Get all action names from history
action_names
python
browser-use/browser-use
browser_use/agent/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/views.py
MIT
def extracted_content(self) -> list[str]: """Get all extracted content from history""" content = [] for h in self.history: content.extend([r.extracted_content for r in h.result if r.extracted_content]) return content
Get all extracted content from history
extracted_content
python
browser-use/browser-use
browser_use/agent/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/views.py
MIT
def model_actions_filtered(self, include: list[str] | None = None) -> list[dict]: """Get all model actions from history as JSON""" if include is None: include = [] outputs = self.model_actions() result = [] for o in outputs: for i in include: if i == list(o.keys())[0]: result.append(o) return...
Get all model actions from history as JSON
model_actions_filtered
python
browser-use/browser-use
browser_use/agent/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/views.py
MIT
def format_error(error: Exception, include_trace: bool = False) -> str: """Format error message based on error type and optionally include trace""" message = '' if isinstance(error, ValidationError): return f'{AgentError.VALIDATION_ERROR}\nDetails: {str(error)}' if isinstance(error, RateLimitError): retur...
Format error message based on error type and optionally include trace
format_error
python
browser-use/browser-use
browser_use/agent/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/views.py
MIT
def vector_store_config_dict(self) -> dict[str, Any]: """ Returns the vector store configuration dictionary for Mem0, tailored to the selected provider. """ provider_specific_config = {'embedding_model_dims': self.embedder_dims} # --- Default collection_name handling --- if self.vector_store_collection_n...
Returns the vector store configuration dictionary for Mem0, tailored to the selected provider.
vector_store_config_dict
python
browser-use/browser-use
browser_use/agent/memory/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/memory/views.py
MIT
def full_config_dict(self) -> dict[str, dict[str, Any]]: """Returns the complete configuration dictionary for Mem0.""" return { 'embedder': self.embedder_config_dict, 'llm': self.llm_config_dict, 'vector_store': self.vector_store_config_dict, }
Returns the complete configuration dictionary for Mem0.
full_config_dict
python
browser-use/browser-use
browser_use/agent/memory/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/memory/views.py
MIT
def _log_extract_text_from_list_content(content: list) -> str: """Extract text from list content structure - used only for logging display""" text_content = '' for item in content: if isinstance(item, dict) and 'text' in item: text_content += item['text'] return text_content
Extract text from list content structure - used only for logging display
_log_extract_text_from_list_content
python
browser-use/browser-use
browser_use/agent/message_manager/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/service.py
MIT
def _log_format_agent_output_content(tool_call: dict) -> str: """Format AgentOutput tool call into readable content - used only for logging display""" try: args = tool_call.get('args', {}) action_info = '' # Get action name if 'action' in args and args['action']: first_action = args['action'][0] if isinst...
Format AgentOutput tool call into readable content - used only for logging display
_log_format_agent_output_content
python
browser-use/browser-use
browser_use/agent/message_manager/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/service.py
MIT
def _log_extract_message_content(message: BaseMessage, is_last_message: bool, metadata: MessageMetadata | None = None) -> str: """Extract content from a message for logging display only""" try: message_type = message.__class__.__name__ if is_last_message and message_type == 'HumanMessage' and isinstance(message....
Extract content from a message for logging display only
_log_extract_message_content
python
browser-use/browser-use
browser_use/agent/message_manager/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/service.py
MIT
def _init_messages(self) -> None: """Initialize the message history with system message, context, task, and other initial messages""" self._add_message_with_tokens(self.system_prompt, message_type='init') if self.settings.message_context: context_message = HumanMessage(content='Context for the task' + self.se...
Initialize the message history with system message, context, task, and other initial messages
_init_messages
python
browser-use/browser-use
browser_use/agent/message_manager/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/service.py
MIT
def add_state_message( self, browser_state_summary: BrowserStateSummary, result: list[ActionResult] | None = None, step_info: AgentStepInfo | None = None, use_vision=True, ) -> None: """Add browser state as human message""" # if keep in memory, add to directly to history and add state without result i...
Add browser state as human message
add_state_message
python
browser-use/browser-use
browser_use/agent/message_manager/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/service.py
MIT
def add_model_output(self, model_output: AgentOutput) -> None: """Add model output as AI message""" tool_calls = [ { 'name': 'AgentOutput', 'args': model_output.model_dump(mode='json', exclude_unset=True), 'id': str(self.state.tool_id), 'type': 'tool_call', } ] msg = AIMessage( content...
Add model output as AI message
add_model_output
python
browser-use/browser-use
browser_use/agent/message_manager/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/service.py
MIT
def get_messages(self) -> list[BaseMessage]: """Get current message list, potentially trimmed to max tokens""" msg = [m.message for m in self.state.history.messages] # Log message history for debugging logger.debug(self._log_history_lines()) return msg
Get current message list, potentially trimmed to max tokens
get_messages
python
browser-use/browser-use
browser_use/agent/message_manager/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/service.py
MIT
def _add_message_with_tokens( self, message: BaseMessage, position: int | None = None, message_type: str | None = None ) -> None: """Add message with token count metadata position: None for last, -1 for second last, etc. """ # filter out sensitive data from the message if self.settings.sensitive_data: ...
Add message with token count metadata position: None for last, -1 for second last, etc.
_add_message_with_tokens
python
browser-use/browser-use
browser_use/agent/message_manager/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/service.py
MIT
def _filter_sensitive_data(self, message: BaseMessage) -> BaseMessage: """Filter out sensitive data from the message""" def replace_sensitive(value: str) -> str: if not self.settings.sensitive_data: return value # Collect all sensitive values, immediately converting old format to new format sensitive...
Filter out sensitive data from the message
_filter_sensitive_data
python
browser-use/browser-use
browser_use/agent/message_manager/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/service.py
MIT
def _count_tokens(self, message: BaseMessage) -> int: """Count tokens in a message using the model's tokenizer""" tokens = 0 if isinstance(message.content, list): for item in message.content: if 'image_url' in item: tokens += self.settings.image_tokens elif isinstance(item, dict) and 'text' in ite...
Count tokens in a message using the model's tokenizer
_count_tokens
python
browser-use/browser-use
browser_use/agent/message_manager/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/service.py
MIT
def test_initial_messages(message_manager: MessageManager): """Test that message manager initializes with system and task messages""" messages = message_manager.get_messages() assert len(messages) == 2 assert isinstance(messages[0], SystemMessage) assert isinstance(messages[1], HumanMessage) assert 'Test task' in...
Test that message manager initializes with system and task messages
test_initial_messages
python
browser-use/browser-use
browser_use/agent/message_manager/tests.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/tests.py
MIT
def test_add_state_with_memory_result(message_manager: MessageManager): """Test adding state with result that should be included in memory""" state = BrowserStateSummary( url='https://test.com', title='Test Page', element_tree=DOMElementNode( tag_name='div', attributes={}, children=[], is_visible=Tr...
Test adding state with result that should be included in memory
test_add_state_with_memory_result
python
browser-use/browser-use
browser_use/agent/message_manager/tests.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/tests.py
MIT
def test_add_state_with_non_memory_result(message_manager: MessageManager): """Test adding state with result that should not be included in memory""" state = BrowserStateSummary( url='https://test.com', title='Test Page', element_tree=DOMElementNode( tag_name='div', attributes={}, children=[], is_vi...
Test adding state with result that should not be included in memory
test_add_state_with_non_memory_result
python
browser-use/browser-use
browser_use/agent/message_manager/tests.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/tests.py
MIT
def test_token_overflow_handling_with_real_flow(message_manager: MessageManager, max_tokens): """Test handling of token overflow in a realistic message flow""" # Set more realistic token limit message_manager.settings.max_input_tokens = max_tokens # Create a long sequence of interactions for i in range(200): # S...
Test handling of token overflow in a realistic message flow
test_token_overflow_handling_with_real_flow
python
browser-use/browser-use
browser_use/agent/message_manager/tests.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/tests.py
MIT
def extract_json_from_model_output(content: str) -> dict: """Extract JSON from model output, handling both plain JSON and code-block-wrapped JSON.""" try: # If content is wrapped in code blocks, extract just the JSON part if '```' in content: # Find the JSON content between code blocks content = content.spl...
Extract JSON from model output, handling both plain JSON and code-block-wrapped JSON.
extract_json_from_model_output
python
browser-use/browser-use
browser_use/agent/message_manager/utils.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/utils.py
MIT
def convert_input_messages(input_messages: list[BaseMessage], model_name: str | None) -> list[BaseMessage]: """Convert input messages to a format that is compatible with the planner model""" if model_name is None: return input_messages # TODO: use the auto-detected tool calling method from Agent._set_tool_calling...
Convert input messages to a format that is compatible with the planner model
convert_input_messages
python
browser-use/browser-use
browser_use/agent/message_manager/utils.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/utils.py
MIT
def _convert_messages_for_non_function_calling_models(input_messages: list[BaseMessage]) -> list[BaseMessage]: """Convert messages for non-function-calling models""" output_messages = [] for message in input_messages: if isinstance(message, HumanMessage): output_messages.append(message) elif isinstance(messag...
Convert messages for non-function-calling models
_convert_messages_for_non_function_calling_models
python
browser-use/browser-use
browser_use/agent/message_manager/utils.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/utils.py
MIT
def _merge_successive_messages(messages: list[BaseMessage], class_to_merge: type[BaseMessage]) -> list[BaseMessage]: """Some models like deepseek-reasoner dont allow multiple human messages in a row. This function merges them into one.""" merged_messages = [] streak = 0 for message in messages: if isinstance(mess...
Some models like deepseek-reasoner dont allow multiple human messages in a row. This function merges them into one.
_merge_successive_messages
python
browser-use/browser-use
browser_use/agent/message_manager/utils.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/utils.py
MIT
def to_json(self, original_dump): """ Returns the JSON representation of the model. It uses langchain's `dumps` function to serialize the `message` property before encoding the overall dict with json.dumps. """ data = original_dump(self) # NOTE: We override the message field to use langchain JSON serial...
Returns the JSON representation of the model. It uses langchain's `dumps` function to serialize the `message` property before encoding the overall dict with json.dumps.
to_json
python
browser-use/browser-use
browser_use/agent/message_manager/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/views.py
MIT
def validate( cls, value: Any, *, strict: bool | None = None, from_attributes: bool | None = None, context: Any | None = None, ) -> Any: """ Custom validator that uses langchain's `loads` function to parse the message if it is provided as a JSON string. """ if isinstance(value, dict) and 'message...
Custom validator that uses langchain's `loads` function to parse the message if it is provided as a JSON string.
validate
python
browser-use/browser-use
browser_use/agent/message_manager/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/views.py
MIT
def add_message(self, message: BaseMessage, metadata: MessageMetadata, position: int | None = None) -> None: """Add message with metadata to history""" if position is None: self.messages.append(ManagedMessage(message=message, metadata=metadata)) else: self.messages.insert(position, ManagedMessage(message=me...
Add message with metadata to history
add_message
python
browser-use/browser-use
browser_use/agent/message_manager/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/views.py
MIT
def remove_last_state_message(self) -> None: """Remove last state message from history""" if len(self.messages) > 2 and isinstance(self.messages[-1].message, HumanMessage): self.current_tokens -= self.messages[-1].metadata.tokens self.messages.pop()
Remove last state message from history
remove_last_state_message
python
browser-use/browser-use
browser_use/agent/message_manager/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/agent/message_manager/views.py
MIT
def get_window_adjustments() -> tuple[int, int]: """Returns recommended x, y offsets for window positioning""" if sys.platform == 'darwin': # macOS return -4, 24 # macOS has a small title bar, no border elif sys.platform == 'win32': # Windows return -8, 0 # Windows has a border on the left else: # Linux ...
Returns recommended x, y offsets for window positioning
get_window_adjustments
python
browser-use/browser-use
browser_use/browser/profile.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/profile.py
MIT
def validate_url(url: str, schemes: Iterable[str] = ()) -> str: """Validate URL format and optionally check for specific schemes.""" parsed_url = urlparse(url) if not parsed_url.netloc: raise ValueError(f'Invalid URL format: {url}') if schemes and parsed_url.scheme and parsed_url.scheme.lower() not in schemes: ...
Validate URL format and optionally check for specific schemes.
validate_url
python
browser-use/browser-use
browser_use/browser/profile.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/profile.py
MIT
def validate_float_range(value: float, min_val: float, max_val: float) -> float: """Validate that float is within specified range.""" if not min_val <= value <= max_val: raise ValueError(f'Value {value} outside of range {min_val}-{max_val}') return value
Validate that float is within specified range.
validate_float_range
python
browser-use/browser-use
browser_use/browser/profile.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/profile.py
MIT
def validate_cli_arg(arg: str) -> str: """Validate that arg is a valid CLI argument.""" if not arg.startswith('--'): raise ValueError(f'Invalid CLI argument: {arg} (should start with --, e.g. --some-key="some value here")') return arg
Validate that arg is a valid CLI argument.
validate_cli_arg
python
browser-use/browser-use
browser_use/browser/profile.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/profile.py
MIT
def args_as_dict(args: list[str]) -> dict[str, str]: """Return the extra launch CLI args as a dictionary.""" args_dict = {} for arg in args: key, value, *_ = [*arg.split('=', 1), '', '', ''] args_dict[key.strip().lstrip('-')] = value.strip() return args_dict
Return the extra launch CLI args as a dictionary.
args_as_dict
python
browser-use/browser-use
browser_use/browser/profile.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/profile.py
MIT
def detect_display_configuration(self) -> None: """ Detect the system display size and initialize the display-related config defaults: screen, window_size, window_position, viewport, no_viewport, device_scale_factor """ display_size = get_display_size() has_screen_available = bool(display_size) s...
Detect the system display size and initialize the display-related config defaults: screen, window_size, window_position, viewport, no_viewport, device_scale_factor
detect_display_configuration
python
browser-use/browser-use
browser_use/browser/profile.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/profile.py
MIT
def apply_session_overrides_to_profile(self) -> Self: """Apply any extra **kwargs passed to BrowserSession(...) as session-specific config overrides on top of browser_profile""" session_own_fields = type(self).model_fields.keys() # get all the extra kwarg overrides passed to BrowserSession(...) that are actually...
Apply any extra **kwargs passed to BrowserSession(...) as session-specific config overrides on top of browser_profile
apply_session_overrides_to_profile
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
def _connection_str(self) -> str: """Get a logging-ready string describing the connection method e.g. browser=playwright+google-chrome-canary (local)""" binary_name = ( Path(self.browser_profile.executable_path).name.lower().replace(' ', '-').replace('.exe', '') if self.browser_profile.executable_path else...
Get a logging-ready string describing the connection method e.g. browser=playwright+google-chrome-canary (local)
_connection_str
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def close(self) -> None: """Deprecated: Provides backwards-compatibility with old method Browser().close() and playwright BrowserContext.close()""" await self.stop()
Deprecated: Provides backwards-compatibility with old method Browser().close() and playwright BrowserContext.close()
close
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def new_context(self, **kwargs): """Deprecated: Provides backwards-compatibility with old class method Browser().new_context().""" # TODO: remove this after >=0.3.0 return self
Deprecated: Provides backwards-compatibility with old class method Browser().new_context().
new_context
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
def __eq__(self, other: object) -> bool: """Check if two BrowserSession instances are using the same browser.""" if not isinstance(other, BrowserSession): return False # Two sessions are considered equal if they're connected to the same browser # All three connection identifiers must match return self.br...
Check if two BrowserSession instances are using the same browser.
__eq__
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
def _kill_child_processes(self) -> None: """Kill any child processes that might be related to the browser""" if not self.browser_profile.keep_alive and self.browser_pid: try: browser_proc = psutil.Process(self.browser_pid) try: browser_proc.terminate() browser_proc.wait( timeout=5 )...
Kill any child processes that might be related to the browser
_kill_child_processes
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def _recreate_playwright_instance(self) -> None: """Force recreation of the playwright instance when it's detected to be invalid""" global GLOBAL_PLAYWRIGHT_API_OBJECT global GLOBAL_PATCHRIGHT_API_OBJECT global GLOBAL_PLAYWRIGHT_EVENT_LOOP global GLOBAL_PATCHRIGHT_EVENT_LOOP try: current_loop = as...
Force recreation of the playwright instance when it's detected to be invalid
_recreate_playwright_instance
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
def _set_browser_keep_alive(self, keep_alive: bool | None) -> None: """set the keep_alive flag on the browser_profile, defaulting to True if keep_alive is None""" if self.browser_profile.keep_alive is None: self.browser_profile.keep_alive = keep_alive
set the keep_alive flag on the browser_profile, defaulting to True if keep_alive is None
_set_browser_keep_alive
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
def is_connected(self) -> bool: """ Check if the browser session has valid, connected browser and context objects. Returns False if any of the following conditions are met: - No browser_context exists - Browser exists but is disconnected - Browser_context's browser exists but is disconnected - Browser_con...
Check if the browser session has valid, connected browser and context objects. Returns False if any of the following conditions are met: - No browser_context exists - Browser exists but is disconnected - Browser_context's browser exists but is disconnected - Browser_context itself is closed/unusable
is_connected
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def get_current_page(self) -> Page: """Get the current page + ensure it's not None / closed""" if not self.initialized: await self.start() # get-or-create the browser_context if it's not already set up if not self.browser_context: await self.start() assert self.browser_context, 'BrowserContext ...
Get the current page + ensure it's not None / closed
get_current_page
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def save_cookies(self, *args, **kwargs) -> None: """ Old name for the new save_storage_state() function. """ await self.save_storage_state(*args, **kwargs)
Old name for the new save_storage_state() function.
save_cookies
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def load_cookies_from_file(self, *args, **kwargs) -> None: """ Old name for the new load_storage_state() function. """ await self.load_storage_state(*args, **kwargs)
Old name for the new load_storage_state() function.
load_cookies_from_file
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
def _is_url_allowed(self, url: str) -> bool: """ Check if a URL is allowed based on the whitelist configuration. SECURITY CRITICAL. Supports optional glob patterns and schemes in allowed_domains: - *.example.com will match sub.example.com and example.com - *google.com will match google.com, agoogle.com, and ...
Check if a URL is allowed based on the whitelist configuration. SECURITY CRITICAL. Supports optional glob patterns and schemes in allowed_domains: - *.example.com will match sub.example.com and example.com - *google.com will match google.com, agoogle.com, and www.google.com - http*://example.com will match ...
_is_url_allowed
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def navigate_to(self, url: str): """Navigate the agent's current tab to a URL""" if not self._is_url_allowed(url): raise BrowserError(f'Navigation to non-allowed URL: {url}') page = await self.get_current_page() await page.goto(url) await page.wait_for_load_state()
Navigate the agent's current tab to a URL
navigate_to
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def get_page_html(self) -> str: """Get the HTML content of the agent's current page""" page = await self.get_current_page() return await page.content()
Get the HTML content of the agent's current page
get_page_html
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def get_page_structure(self) -> str: """Get a debug view of the page structure including iframes""" debug_script = """(() => { function getPageStructure(element = document, depth = 0, maxDepth = 10) { if (depth >= maxDepth) return ''; const indent = ' '.repeat(depth); let structure = ''; ...
Get a debug view of the page structure including iframes
get_page_structure
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def get_state_summary(self, cache_clickable_elements_hashes: bool) -> BrowserStateSummary: """Get a summary of the current browser state This method builds a BrowserStateSummary object that captures the current state of the browser, including url, title, tabs, screenshot, and DOM tree. Parameters: ---...
Get a summary of the current browser state This method builds a BrowserStateSummary object that captures the current state of the browser, including url, title, tabs, screenshot, and DOM tree. Parameters: ----------- cache_clickable_elements_hashes: bool If True, cache the clickable elements hashes for t...
get_state_summary
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def _get_unique_filename(directory: str, filename: str) -> str: """Generate a unique filename for downloads by appending (1), (2), etc., if a file already exists.""" base, ext = os.path.splitext(filename) counter = 1 new_filename = filename while os.path.exists(os.path.join(directory, new_filename)): ...
Generate a unique filename for downloads by appending (1), (2), etc., if a file already exists.
_get_unique_filename
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
def _convert_simple_xpath_to_css_selector(xpath: str) -> str: """Converts simple XPath expressions to CSS selectors.""" if not xpath: return '' # Remove leading slash if present xpath = xpath.lstrip('/') # Split into parts parts = xpath.split('/') css_parts = [] for part in parts: if not part: ...
Converts simple XPath expressions to CSS selectors.
_convert_simple_xpath_to_css_selector
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
def _enhanced_css_selector_for_element(cls, element: DOMElementNode, include_dynamic_attributes: bool = True) -> str: """ Creates a CSS selector for a DOM element, handling various edge cases and special characters. Args: element: The DOM element to create a selector for Returns: A valid CSS selector ...
Creates a CSS selector for a DOM element, handling various edge cases and special characters. Args: element: The DOM element to create a selector for Returns: A valid CSS selector string
_enhanced_css_selector_for_element
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def _is_visible(self, element: ElementHandle) -> bool: """ Checks if an element is visible on the page. We use our own implementation instead of relying solely on Playwright's is_visible() because of edge cases with CSS frameworks like Tailwind. When elements use Tailwind's 'hidden' class, the computed ...
Checks if an element is visible on the page. We use our own implementation instead of relying solely on Playwright's is_visible() because of edge cases with CSS frameworks like Tailwind. When elements use Tailwind's 'hidden' class, the computed style may return display as '' (empty string) instead of 'none', c...
_is_visible
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def get_scroll_info(self, page: Page) -> tuple[int, int]: """Get scroll position information for the current page.""" scroll_y = await page.evaluate('window.scrollY') viewport_height = await page.evaluate('window.innerHeight') total_height = await page.evaluate('document.documentElement.scrollHeight') p...
Get scroll position information for the current page.
get_scroll_info
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def _show_dvd_screensaver_loading_animation(self, page: Page) -> None: """ Injects a DVD screensaver-style bouncing logo loading animation overlay into the given Playwright Page. This is used to visually indicate that the browser is setting up or waiting. """ if os.environ.get('IS_IN_EVALS', 'false').lo...
Injects a DVD screensaver-style bouncing logo loading animation overlay into the given Playwright Page. This is used to visually indicate that the browser is setting up or waiting.
_show_dvd_screensaver_loading_animation
python
browser-use/browser-use
browser_use/browser/session.py
https://github.com/browser-use/browser-use/blob/master/browser_use/browser/session.py
MIT
async def get_dropdown_options(index: int, browser_session: BrowserSession) -> ActionResult: """Get all options from a native dropdown""" page = await browser_session.get_current_page() selector_map = await browser_session.get_selector_map() dom_element = selector_map[index] try: # Frame-aware appro...
Get all options from a native dropdown
get_dropdown_options
python
browser-use/browser-use
browser_use/controller/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/service.py
MIT
async def select_dropdown_option( index: int, text: str, browser_session: BrowserSession, ) -> ActionResult: """Select dropdown option by the text of the option you want to select""" page = await browser_session.get_current_page() selector_map = await browser_session.get_selector_map() dom_elemen...
Select dropdown option by the text of the option you want to select
select_dropdown_option
python
browser-use/browser-use
browser_use/controller/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/service.py
MIT
async def get_drag_elements( page: Page, source_selector: str, target_selector: str, ) -> tuple[ElementHandle | None, ElementHandle | None]: """Get source and target elements with appropriate error handling.""" source_element = None target_element = None try: # page.locator() auto-d...
Get source and target elements with appropriate error handling.
get_drag_elements
python
browser-use/browser-use
browser_use/controller/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/service.py
MIT
async def get_element_coordinates( source_element: ElementHandle, target_element: ElementHandle, source_position: Position | None, target_position: Position | None, ) -> tuple[tuple[int, int] | None, tuple[int, int] | None]: """Get coordinates from elements with appropriate error handling.""" ...
Get coordinates from elements with appropriate error handling.
get_element_coordinates
python
browser-use/browser-use
browser_use/controller/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/service.py
MIT
async def execute_drag_operation( page: Page, source_x: int, source_y: int, target_x: int, target_y: int, steps: int, delay_ms: int, ) -> tuple[bool, str]: """Execute the drag operation with comprehensive error handling.""" try: # Try to move to source position try: ...
Execute the drag operation with comprehensive error handling.
execute_drag_operation
python
browser-use/browser-use
browser_use/controller/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/service.py
MIT
def _get_special_param_types(self) -> dict[str, type]: """Get the expected types for special parameters from SpecialActionParameters""" # Manually define the expected types to avoid issues with Optional handling. # we should try to reduce this list to 0 if possible, give as few standardized objects to all the act...
Get the expected types for special parameters from SpecialActionParameters
_get_special_param_types
python
browser-use/browser-use
browser_use/controller/registry/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/registry/service.py
MIT
def _normalize_action_function_signature( self, func: Callable, description: str, param_model: type[BaseModel] | None = None, ) -> tuple[Callable, type[BaseModel]]: """ Normalize action function to accept only kwargs. Returns: - Normalized function that accepts (*_, params: ParamModel, **special_para...
Normalize action function to accept only kwargs. Returns: - Normalized function that accepts (*_, params: ParamModel, **special_params) - The param model to use for registration
_normalize_action_function_signature
python
browser-use/browser-use
browser_use/controller/registry/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/registry/service.py
MIT
async def normalized_wrapper(*args, params: BaseModel | None = None, **kwargs): """Normalized action that only accepts kwargs""" # Validate no positional args if args: raise TypeError(f'{func.__name__}() does not accept positional arguments, only keyword arguments are allowed') # Prepare arguments for ...
Normalized action that only accepts kwargs
normalized_wrapper
python
browser-use/browser-use
browser_use/controller/registry/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/registry/service.py
MIT
def _create_param_model(self, function: Callable) -> type[BaseModel]: """Creates a Pydantic model from function signature""" sig = signature(function) special_param_names = set(SpecialActionParameters.model_fields.keys()) params = { name: (param.annotation, ... if param.default == param.empty else param.defa...
Creates a Pydantic model from function signature
_create_param_model
python
browser-use/browser-use
browser_use/controller/registry/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/registry/service.py
MIT
async def execute_action( self, action_name: str, params: dict, browser_session: BrowserSession | None = None, page_extraction_llm: BaseChatModel | None = None, sensitive_data: dict[str, str | dict[str, str]] | None = None, available_file_paths: list[str] | None = None, # context: Context | None = Non...
Execute a registered action with simplified parameter handling
execute_action
python
browser-use/browser-use
browser_use/controller/registry/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/registry/service.py
MIT
def _replace_sensitive_data(self, params: BaseModel, sensitive_data: dict[str, Any], current_url: str = None) -> BaseModel: """ Replaces sensitive data placeholders in params with actual values. Args: params: The parameter object containing <secret>placeholder</secret> tags sensitive_data: Dictionary of se...
Replaces sensitive data placeholders in params with actual values. Args: params: The parameter object containing <secret>placeholder</secret> tags sensitive_data: Dictionary of sensitive data, either in old format {key: value} or new format {domain_pattern: {key: value}} current_url: Optional cu...
_replace_sensitive_data
python
browser-use/browser-use
browser_use/controller/registry/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/registry/service.py
MIT
def create_action_model(self, include_actions: list[str] | None = None, page=None) -> type[ActionModel]: """Creates a Pydantic model from registered actions, used by LLM APIs that support tool calling & enforce a schema""" # Filter actions based on page if provided: # if page is None, only include actions with...
Creates a Pydantic model from registered actions, used by LLM APIs that support tool calling & enforce a schema
create_action_model
python
browser-use/browser-use
browser_use/controller/registry/service.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/registry/service.py
MIT
def prompt_description(self) -> str: """Get a description of the action for the prompt""" skip_keys = ['title'] s = f'{self.description}: \n' s += '{' + str(self.name) + ': ' s += str( { k: {sub_k: sub_v for sub_k, sub_v in v.items() if sub_k not in skip_keys} for k, v in self.param_model.model_jso...
Get a description of the action for the prompt
prompt_description
python
browser-use/browser-use
browser_use/controller/registry/views.py
https://github.com/browser-use/browser-use/blob/master/browser_use/controller/registry/views.py
MIT