instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Annotate my code with docstrings | import json
import time
import re
import bs4
from typing import Any, BinaryIO, Dict, List, Union
from urllib.parse import parse_qs, urlparse, unquote
from .._base_converter import DocumentConverter, DocumentConverterResult
from .._stream_info import StreamInfo
# Optional YouTube transcription support
try:
# Suppr... | --- +++ @@ -35,6 +35,7 @@
class YouTubeConverter(DocumentConverter):
+ """Handle YouTube specially, focusing on the video title, description, and transcript."""
def accepts(
self,
@@ -42,6 +43,9 @@ stream_info: StreamInfo,
**kwargs: Any, # Options to pass to the converter
)... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_youtube_converter.py |
Turn comments into proper docstrings | import re
import markdownify
from typing import Any, Optional
from urllib.parse import quote, unquote, urlparse, urlunparse
class _CustomMarkdownify(markdownify.MarkdownConverter):
def __init__(self, **options: Any):
options["heading_style"] = options.get("heading_style", markdownify.ATX)
option... | --- +++ @@ -6,6 +6,14 @@
class _CustomMarkdownify(markdownify.MarkdownConverter):
+ """
+ A custom version of markdownify's MarkdownConverter. Changes include:
+
+ - Altering the default heading style to use '#', '##', etc.
+ - Removing javascript hyperlinks.
+ - Truncating images with large data:uri... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_markdownify.py |
Include argument descriptions in docstrings | from typing import Optional, List, Any
MISSING_DEPENDENCY_MESSAGE = """{converter} recognized the input as a potential {extension} file, but the dependencies needed to read {extension} files have not been installed. To resolve this error, include the optional dependency [{feature}] or [all] when installing MarkItDown.... | --- +++ @@ -9,21 +9,40 @@
class MarkItDownException(Exception):
+ """
+ Base exception class for MarkItDown.
+ """
pass
class MissingDependencyException(MarkItDownException):
+ """
+ Converters shipped with MarkItDown may depend on optional
+ dependencies. This exception is thrown when... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/_exceptions.py |
Add docstrings to incomplete code | # -*- encoding: utf-8 -*-
import sys
from .conf import settings
from .exceptions import NoRuleMatched
from .system import get_key
from .utils import get_alias
from . import logs, const
def read_actions():
while True:
key = get_key()
# Handle arrows, j/k (qwerty), and n/e (colemak)
if key... | --- +++ @@ -9,6 +9,7 @@
def read_actions():
+ """Yields actions for pressed keys."""
while True:
key = get_key()
@@ -24,8 +25,10 @@
class CommandSelector(object):
+ """Helper for selecting rule from rules list."""
def __init__(self, commands):
+ """:type commands: Iterable[th... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/ui.py |
Fully document this Python code with docstrings | import re
import base64
import binascii
from urllib.parse import parse_qs, urlparse
from typing import Any, BinaryIO
from bs4 import BeautifulSoup
from .._base_converter import DocumentConverter, DocumentConverterResult
from .._stream_info import StreamInfo
from ._markdownify import _CustomMarkdownify
ACCEPTED_MIME_T... | --- +++ @@ -21,6 +21,10 @@
class BingSerpConverter(DocumentConverter):
+ """
+ Handle Bing results pages (only the organic search results).
+ NOTE: It is better to use the Bing API
+ """
def accepts(
self,
@@ -28,6 +32,9 @@ stream_info: StreamInfo,
**kwargs: Any, # Opti... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_bing_serp_converter.py |
Generate consistent docstrings | from dataclasses import dataclass, asdict
from typing import Optional
@dataclass(kw_only=True, frozen=True)
class StreamInfo:
mimetype: Optional[str] = None
extension: Optional[str] = None
charset: Optional[str] = None
filename: Optional[
str
] = None # From local path, url, or Content-D... | --- +++ @@ -4,6 +4,9 @@
@dataclass(kw_only=True, frozen=True)
class StreamInfo:
+ """The StreamInfo class is used to store information about a file stream.
+ All fields can be None, and will depend on how the stream was opened.
+ """
mimetype: Optional[str] = None
extension: Optional[str] = None... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/_stream_info.py |
Help me write clear docstrings | import os
import zipfile
from defusedxml import minidom
from xml.dom.minidom import Document
from typing import BinaryIO, Any, Dict, List
from ._html_converter import HtmlConverter
from .._base_converter import DocumentConverterResult
from .._stream_info import StreamInfo
ACCEPTED_MIME_TYPE_PREFIXES = [
"applica... | --- +++ @@ -24,6 +24,9 @@
class EpubConverter(HtmlConverter):
+ """
+ Converts EPUB files to Markdown. Style information (e.g.m headings) and tables are preserved where possible.
+ """
def __init__(self):
super().__init__()
@@ -127,6 +130,7 @@ )
def _get_text_from_node(se... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_epub_converter.py |
Add docstrings following best practices | import sys
from typing import BinaryIO, Any
from ._html_converter import HtmlConverter
from .._base_converter import DocumentConverter, DocumentConverterResult
from .._exceptions import MissingDependencyException, MISSING_DEPENDENCY_MESSAGE
from .._stream_info import StreamInfo
# Try loading optional (but in this case... | --- +++ @@ -34,6 +34,9 @@
class XlsxConverter(DocumentConverter):
+ """
+ Converts XLSX files to Markdown, with each sheet presented as a separate Markdown table.
+ """
def __init__(self):
super().__init__()
@@ -93,6 +96,9 @@
class XlsConverter(DocumentConverter):
+ """
+ Converts... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_xlsx_converter.py |
Provide docstrings following PEP 257 |
import base64
from typing import Any, BinaryIO
from dataclasses import dataclass
from markitdown import StreamInfo
@dataclass
class OCRResult:
text: str
confidence: float | None = None
backend_used: str | None = None
error: str | None = None
class LLMVisionOCRService:
def __init__(
s... | --- +++ @@ -1,3 +1,7 @@+"""
+OCR Service Layer for MarkItDown
+Provides LLM Vision-based image text extraction.
+"""
import base64
from typing import Any, BinaryIO
@@ -8,6 +12,7 @@
@dataclass
class OCRResult:
+ """Result from OCR extraction."""
text: str
confidence: float | None = None
@@ -16,6 +2... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-ocr/src/markitdown_ocr/_ocr_service.py |
Add clean documentation to messy code | from typing import BinaryIO, Any
import json
from .._base_converter import DocumentConverter, DocumentConverterResult
from .._exceptions import FileConversionException
from .._stream_info import StreamInfo
CANDIDATE_MIME_TYPE_PREFIXES = [
"application/json",
]
ACCEPTED_FILE_EXTENSIONS = [".ipynb"]
class IpynbC... | --- +++ @@ -13,6 +13,7 @@
class IpynbConverter(DocumentConverter):
+ """Converts Jupyter Notebook (.ipynb) files to Markdown."""
def accepts(
self,
@@ -54,6 +55,7 @@ return self._convert(json.loads(notebook_content))
def _convert(self, notebook_content: dict) -> DocumentConverterRe... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_ipynb_converter.py |
Document my Python code with docstrings | from defusedxml import minidom
from xml.dom.minidom import Document, Element
from typing import BinaryIO, Any, Union
from bs4 import BeautifulSoup
from ._markdownify import _CustomMarkdownify
from .._stream_info import StreamInfo
from .._base_converter import DocumentConverter, DocumentConverterResult
PRECISE_MIME_TY... | --- +++ @@ -27,6 +27,7 @@
class RssConverter(DocumentConverter):
+ """Convert RSS / Atom type to markdown"""
def __init__(self):
super().__init__()
@@ -98,6 +99,10 @@ raise ValueError("Unknown feed type")
def _parse_atom_type(self, doc: Document) -> DocumentConverterResult:
+ ... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_rss_converter.py |
Add docstrings to existing functions | import mimetypes
import os
import re
import sys
import shutil
import traceback
import io
from dataclasses import dataclass
from importlib.metadata import entry_points
from typing import Any, List, Dict, Optional, Union, BinaryIO
from pathlib import Path
from urllib.parse import urlparse
from warnings import warn
import... | --- +++ @@ -63,6 +63,7 @@
def _load_plugins() -> Union[None, List[Any]]:
+ """Lazy load plugins, exiting early if already loaded."""
global _plugins
# Skip if we've already loaded plugins
@@ -83,12 +84,15 @@
@dataclass(kw_only=True, frozen=True)
class ConverterRegistration:
+ """A registration ... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/_markitdown.py |
Create documentation for each function signature | # -*- coding: utf-8 -*-
from defusedxml import ElementTree as ET
from .latex_dict import (
CHARS,
CHR,
CHR_BO,
CHR_DEFAULT,
POS,
POS_DEFAULT,
SUB,
SUP,
F,
F_DEFAULT,
T,
FUNC,
D,
D_DEFAULT,
RAD,
RAD_DEFAULT,
ARR,
LIM_FUNC,
LIM_TO,
LIM_UPP... | --- +++ @@ -1,5 +1,10 @@ # -*- coding: utf-8 -*-
+"""
+Office Math Markup Language (OMML)
+Adapted from https://github.com/xiilei/dwml/blob/master/dwml/omml.py
+On 25/03/2025
+"""
from defusedxml import ElementTree as ET
@@ -79,6 +84,9 @@ return None
def process_children_list(self, elm, includ... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converter_utils/docx/math/omml.py |
Provide docstrings following PEP 257 | import sys
import re
import os
from typing import BinaryIO, Any, List
from enum import Enum
from .._base_converter import DocumentConverter, DocumentConverterResult
from .._stream_info import StreamInfo
from .._exceptions import MissingDependencyException
# Try loading optional (but in this case, required) dependenci... | --- +++ @@ -53,6 +53,7 @@
class DocumentIntelligenceFileType(str, Enum):
+ """Enum of file types supported by the Document Intelligence Converter."""
# No OCR
DOCX = "docx"
@@ -68,6 +69,7 @@
def _get_mime_type_prefixes(types: List[DocumentIntelligenceFileType]) -> List[str]:
+ """Get the MIME ... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_doc_intel_converter.py |
Generate consistent docstrings | import zipfile
from io import BytesIO
from typing import BinaryIO
from xml.etree import ElementTree as ET
from bs4 import BeautifulSoup, Tag
from .math.omml import OMML_NS, oMath2Latex
MATH_ROOT_TEMPLATE = "".join(
(
"<w:document ",
'xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordpr... | --- +++ @@ -31,6 +31,15 @@
def _convert_omath_to_latex(tag: Tag) -> str:
+ """
+ Converts an OMML (Office Math Markup Language) tag to LaTeX format.
+
+ Args:
+ tag (Tag): A BeautifulSoup Tag object representing the OMML element.
+
+ Returns:
+ str: The LaTeX representation of the OMML ele... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converter_utils/docx/pre_process.py |
Write docstrings describing functionality | import io
from typing import Any, BinaryIO, Optional
from bs4 import BeautifulSoup
from .._base_converter import DocumentConverter, DocumentConverterResult
from .._stream_info import StreamInfo
from ._markdownify import _CustomMarkdownify
ACCEPTED_MIME_TYPE_PREFIXES = [
"text/html",
"application/xhtml",
]
AC... | --- +++ @@ -18,6 +18,7 @@
class HtmlConverter(DocumentConverter):
+ """Anything with content type text/html"""
def accepts(
self,
@@ -72,6 +73,11 @@ def convert_string(
self, html_content: str, *, url: Optional[str] = None, **kwargs
) -> DocumentConverterResult:
+ """
+ ... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_html_converter.py |
Add docstrings including usage examples | import re
import bs4
from typing import Any, BinaryIO
from .._base_converter import DocumentConverter, DocumentConverterResult
from .._stream_info import StreamInfo
from ._markdownify import _CustomMarkdownify
ACCEPTED_MIME_TYPE_PREFIXES = [
"text/html",
"application/xhtml",
]
ACCEPTED_FILE_EXTENSIONS = [
... | --- +++ @@ -18,6 +18,7 @@
class WikipediaConverter(DocumentConverter):
+ """Handle Wikipedia pages separately, focusing only on the main document content."""
def accepts(
self,
@@ -25,6 +26,9 @@ stream_info: StreamInfo,
**kwargs: Any, # Options to pass to the converter
) ->... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_wikipedia_converter.py |
Add docstrings following best practices |
import io
import sys
from typing import Any, BinaryIO, Optional
from markitdown.converters import HtmlConverter
from markitdown import DocumentConverter, DocumentConverterResult, StreamInfo
from markitdown._exceptions import (
MissingDependencyException,
MISSING_DEPENDENCY_MESSAGE,
)
from ._ocr_service import... | --- +++ @@ -1,3 +1,7 @@+"""
+Enhanced XLSX Converter with OCR support for embedded images.
+Extracts images from Excel spreadsheets and performs OCR while maintaining cell context.
+"""
import io
import sys
@@ -21,6 +25,10 @@
class XlsxConverterWithOCR(DocumentConverter):
+ """
+ Enhanced XLSX Converter w... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-ocr/src/markitdown_ocr/_xlsx_converter_with_ocr.py |
Help me add docstrings to my project | from typing import Any, BinaryIO, Optional
from ._stream_info import StreamInfo
class DocumentConverterResult:
def __init__(
self,
markdown: str,
*,
title: Optional[str] = None,
):
self.markdown = markdown
self.title = title
@property
def text_content(... | --- +++ @@ -3,6 +3,7 @@
class DocumentConverterResult:
+ """The result of converting a document to Markdown."""
def __init__(
self,
@@ -10,22 +11,36 @@ *,
title: Optional[str] = None,
):
+ """
+ Initialize the DocumentConverterResult.
+
+ The only requir... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/_base_converter.py |
Generate NumPy-style docstrings | import sys
from typing import Any, Union, BinaryIO
from .._stream_info import StreamInfo
from .._base_converter import DocumentConverter, DocumentConverterResult
from .._exceptions import MissingDependencyException, MISSING_DEPENDENCY_MESSAGE
# Try loading optional (but in this case, required) dependencies
# Save repo... | --- +++ @@ -22,6 +22,12 @@
class OutlookMsgConverter(DocumentConverter):
+ """Converts Outlook .msg files to markdown by extracting email metadata and content.
+
+ Uses the olefile package to parse the .msg file structure and extract:
+ - Email headers (From, To, Subject)
+ - Email body content
+ """... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_outlook_msg_converter.py |
Add verbose docstrings with examples | #!/usr/bin/env python
import random
from typing import List, Optional
def binary_search(arr: List[int], lb: int, ub: int, target: int) -> Optional[int]:
while lb <= ub:
mid = lb + (ub - lb) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
lb = mid + 1... | --- +++ @@ -5,6 +5,9 @@
def binary_search(arr: List[int], lb: int, ub: int, target: int) -> Optional[int]:
+ """
+ A Binary Search Example which has O(log n) time complexity.
+ """
while lb <= ub:
mid = lb + (ub - lb) // 2
if arr[mid] == target:
@@ -25,6 +28,10 @@
def main():
+ ... | https://raw.githubusercontent.com/bregman-arie/devops-exercises/HEAD/coding/python/binary_search.py |
Add docstrings to meet PEP guidelines |
class Utils:
@staticmethod
def get_key_info(key: str) -> tuple[str, int | None]:
# Complete mapping of key names to (code, virtualKeyCode)
# Based on standard Windows Virtual Key Codes
key_map = {
# Navigation keys
'Backspace': ('Backspace', 8),
'Tab': ('Tab', 9),
'Enter': ('Enter', 13),
'Esca... | --- +++ @@ -1,9 +1,22 @@+"""Utility functions for actor operations."""
class Utils:
+ """Utility functions for actor operations."""
@staticmethod
def get_key_info(key: str) -> tuple[str, int | None]:
+ """Get the code and windowsVirtualKeyCode for a key.
+
+ Args:
+ key: Key name (e.g., 'Enter', 'ArrowUp... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/actor/utils.py |
Create docstrings for API functions | from typing import Literal
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field
ProxyCountryCode = (
Literal[
'us', # United States
'uk', # United Kingdom
'fr', # France
'it', # Italy
'jp', # Japan
'au', # Australia
'de', # Germany
'fi', # Finland
'ca', # Canada
'in', ... | --- +++ @@ -26,6 +26,13 @@
# Requests
class CreateBrowserRequest(BaseModel):
+ """Request to create a cloud browser instance.
+
+ Args:
+ cloud_profile_id: The ID of the profile to use for the session
+ cloud_proxy_country_code: Country code for proxy location
+ cloud_timeout: The timeout for the session... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/cloud/views.py |
Write beginner-friendly docstrings | from __future__ import annotations
import json
from dataclasses import dataclass
from typing import Any, TypeVar, overload
import httpx
from openai import (
APIConnectionError,
APIError,
APIStatusError,
APITimeoutError,
AsyncOpenAI,
RateLimitError,
)
from pydantic import BaseModel
from browser_use.llm.base imp... | --- +++ @@ -27,6 +27,7 @@
@dataclass
class ChatDeepSeek(BaseChatModel):
+ """DeepSeek /chat/completions wrapper (OpenAI-compatible)."""
model: str = 'deepseek-chat'
@@ -86,6 +87,13 @@ stop: list[str] | None = None,
**kwargs: Any,
) -> ChatInvokeCompletion[T] | ChatInvokeCompletion[str]:
+ """
+ DeepSe... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/deepseek/chat.py |
Add docstrings to improve collaboration | from __future__ import annotations
import logging
from typing import Literal
from browser_use.agent.message_manager.views import (
HistoryItem,
)
from browser_use.agent.prompts import AgentMessagePrompt
from browser_use.agent.views import (
ActionResult,
AgentOutput,
AgentStepInfo,
MessageCompactionSettings,
Me... | --- +++ @@ -37,6 +37,7 @@
def _log_get_message_emoji(message: BaseMessage) -> str:
+ """Get emoji for a message type - used only for logging display"""
emoji_map = {
'UserMessage': '💬',
'SystemMessage': '🧠',
@@ -46,6 +47,7 @@
def _log_format_message_line(message: BaseMessage, content: str, is_last_mes... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/agent/message_manager/service.py |
Add concise docstrings to each method |
import asyncio
import json
import os
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar
from urllib.parse import urlparse
import anyio
from bubus import BaseEvent
from cdp_use.cdp.browser import DownloadProgressEvent as CDPDownloadProgressEvent
from cdp_use.cdp.browser import Dow... | --- +++ @@ -1,3 +1,4 @@+"""Downloads watchdog for monitoring and handling file downloads."""
import asyncio
import json
@@ -34,6 +35,7 @@
class DownloadsWatchdog(BaseWatchdog):
+ """Monitors downloads and handles file download events."""
# Events this watchdog listens to (for documentation)
LISTENS_TO: Cl... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/downloads_watchdog.py |
Generate docstrings with examples |
import asyncio
from typing import TYPE_CHECKING, Literal, Union
from cdp_use.client import logger
from typing_extensions import TypedDict
if TYPE_CHECKING:
from cdp_use.cdp.dom.commands import (
DescribeNodeParameters,
FocusParameters,
GetAttributesParameters,
GetBoxModelParameters,
PushNodesByBackendIdsT... | --- +++ @@ -1,3 +1,4 @@+"""Element class for element operations."""
import asyncio
from typing import TYPE_CHECKING, Literal, Union
@@ -30,12 +31,14 @@
class Position(TypedDict):
+ """2D position coordinates."""
x: float
y: float
class BoundingBox(TypedDict):
+ """Element bounding box with position a... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/actor/element.py |
Create docstrings for API functions | import asyncio
import gc
import inspect
import json
import logging
import re
import tempfile
import time
from collections.abc import Awaitable, Callable
from pathlib import Path
from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, cast
from urllib.parse import urlparse
if TYPE_CHECKING:
from browser_use.... | --- +++ @@ -85,6 +85,7 @@
def log_response(response: AgentOutput, registry=None, logger=None) -> None:
+ """Utility function to log the model's response."""
# Use module logger if no logger provided
if logger is None:
@@ -254,6 +255,7 @@ if llm_timeout is None:
def _get_model_timeout(llm_model: BaseCh... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/agent/service.py |
Create docstrings for reusable components |
import asyncio
import logging
import time
from functools import cached_property
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, Self, Union, cast, overload
from urllib.parse import urlparse, urlunparse
from uuid import UUID
import httpx
from bubus import EventBus
from cdp_use import CDPClient... | --- +++ @@ -1,3 +1,4 @@+"""Event-driven browser session with backwards compatibility."""
import asyncio
import logging
@@ -63,6 +64,11 @@
class Target(BaseModel):
+ """Browser target (page, iframe, worker) - the actual entity being controlled.
+
+ A target represents a browsing context with its own URL, title, ... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/session.py |
Add documentation for all methods |
import inspect
import os
from typing import Any, Literal
from bubus import BaseEvent
from bubus.models import T_EventResultType
from cdp_use.cdp.target import TargetID
from pydantic import BaseModel, Field, field_validator
from browser_use.browser.views import BrowserStateSummary
from browser_use.dom.views import En... | --- +++ @@ -1,3 +1,4 @@+"""Event definitions for browser communication."""
import inspect
import os
@@ -13,6 +14,19 @@
def _get_timeout(env_var: str, default: float) -> float | None:
+ """
+ Safely parse environment variable timeout values with robust error handling.
+
+ Args:
+ env_var: Environment variable n... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/events.py |
Add missing documentation to my Python functions | from __future__ import annotations
import json
import logging
from pathlib import Path
from typing import Any
import anyio
from browser_use.llm.messages import BaseMessage
logger = logging.getLogger(__name__)
async def save_conversation(
input_messages: list[BaseMessage],
response: Any,
target: str | Path,
en... | --- +++ @@ -18,6 +18,7 @@ target: str | Path,
encoding: str | None = None,
) -> None:
+ """Save conversation history to file asynchronously."""
target_path = Path(target)
# create folders if not exists
if target_path.parent:
@@ -30,6 +31,7 @@
async def _format_conversation(messages: list[BaseMessage], res... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/agent/message_manager/utils.py |
Document all public functions with docstrings | import os
from dataclasses import dataclass
from typing import Any, TypeVar, overload
import httpx
from openai import APIConnectionError, APIStatusError, RateLimitError
from openai import AsyncAzureOpenAI as AsyncAzureOpenAIClient
from openai.types.responses import Response
from openai.types.shared import ChatModel
fr... | --- +++ @@ -32,6 +32,16 @@
@dataclass
class ChatAzureOpenAI(ChatOpenAILike):
+ """
+ A class for to interact with any provider using the OpenAI API schema.
+
+ Args:
+ model (str): The name of the OpenAI model to use. Defaults to "not-provided".
+ api_key (Optional[str]): The API key to use. Defaults to "not... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/azure/chat.py |
Document my Python code with docstrings | # @file purpose: Serializes enhanced DOM trees to string format for LLM consumption
from typing import Any
from browser_use.dom.serializer.clickable_elements import ClickableElementDetector
from browser_use.dom.serializer.paint_order import PaintOrderRemover
from browser_use.dom.utils import cap_text_length
from brow... | --- +++ @@ -39,6 +39,7 @@
class DOMTreeSerializer:
+ """Serializes enhanced DOM trees to string format."""
# Configuration - elements that propagate bounds to their children
PROPAGATING_ELEMENTS = [
@@ -81,12 +82,14 @@ self.session_id = session_id
def _safe_parse_number(self, value_str: str, default: fl... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/dom/serializer/serializer.py |
Document functions with detailed explanations |
import base64
import logging
import os
from pathlib import Path
from typing import Any
import anyio
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclie... | --- +++ @@ -1,3 +1,8 @@+"""
+Gmail API Service for Browser Use
+Handles Gmail API authentication, email reading, and 2FA code extraction.
+This service provides a clean interface for agents to interact with Gmail.
+"""
import base64
import logging
@@ -18,6 +23,13 @@
class GmailService:
+ """
+ Gmail API service... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/integrations/gmail/service.py |
Create simple docstrings for beginners |
import re
def truncate_message_content(content: str, max_length: int = 10000) -> str:
if len(content) <= max_length:
return content
# Truncate and add marker
return content[:max_length] + f'\n\n[... truncated {len(content) - max_length} characters for history]'
def detect_token_limit_issue(
completion: str,
... | --- +++ @@ -1,8 +1,10 @@+"""Utility functions for code-use agent."""
import re
def truncate_message_content(content: str, max_length: int = 10000) -> str:
+ """Truncate message content to max_length characters for history."""
if len(content) <= max_length:
return content
# Truncate and add marker
@@ -15,... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/code_use/utils.py |
Add professional docstrings to my codebase |
import json
import re
from pathlib import Path
from browser_use.code_use.service import CodeAgent
from .views import CellType, NotebookExport
def export_to_ipynb(agent: CodeAgent, output_path: str | Path) -> Path:
output_path = Path(output_path)
# Create notebook structure
notebook = NotebookExport(
metadata... | --- +++ @@ -1,3 +1,4 @@+"""Export code-use session to Jupyter notebook format."""
import json
import re
@@ -9,6 +10,25 @@
def export_to_ipynb(agent: CodeAgent, output_path: str | Path) -> Path:
+ """
+ Export a NotebookSession to a Jupyter notebook (.ipynb) file.
+ Now includes JavaScript code blocks that were ... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/code_use/notebook_export.py |
Write docstrings describing each step | import logging
from dataclasses import dataclass
from typing import Any, Literal, TypeVar, overload
from groq import (
APIError,
APIResponseValidationError,
APIStatusError,
AsyncGroq,
NotGiven,
RateLimitError,
Timeout,
)
from groq.types.chat import ChatCompletion, ChatCompletionToolChoiceOptionParam, ChatComple... | --- +++ @@ -54,6 +54,9 @@
@dataclass
class ChatGroq(BaseChatModel):
+ """
+ A wrapper around AsyncGroq that implements the BaseLLM protocol.
+ """
# Model configuration
model: GroqVerifiedModels | str
@@ -146,6 +149,7 @@ raise ModelProviderError(message=str(e), model=self.name) from e
async def _invoke_... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/groq/chat.py |
Can you add docstrings to this Python file? |
import asyncio
import time
from typing import TYPE_CHECKING
from browser_use.browser.events import (
BrowserErrorEvent,
BrowserStateRequestEvent,
ScreenshotEvent,
TabCreatedEvent,
)
from browser_use.browser.watchdog_base import BaseWatchdog
from browser_use.dom.service import DomService
from browser_use.dom.views... | --- +++ @@ -1,3 +1,4 @@+"""DOM watchdog for browser DOM tree management using CDP."""
import asyncio
import time
@@ -23,6 +24,12 @@
class DOMWatchdog(BaseWatchdog):
+ """Handles DOM tree building, serialization, and element access via CDP.
+
+ This watchdog acts as a bridge between the event-driven browser sess... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/dom_watchdog.py |
Add docstrings to improve readability | import os
from typing import TYPE_CHECKING
from browser_use.logging_config import setup_logging
# Only set up logging if not in MCP mode or if explicitly requested
if os.environ.get('BROWSER_USE_SETUP_LOGGING', 'true').lower() != 'false':
from browser_use.config import CONFIG
# Get log file paths from config/envir... | --- +++ @@ -25,6 +25,7 @@
def _patched_del(self):
+ """Patched __del__ that handles closed event loops without throwing noisy red-herring errors like RuntimeError: Event loop is closed"""
try:
# Check if the event loop is closed before calling the original
if hasattr(self, '_loop') and self._loop and self._... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/__init__.py |
Help me add docstrings to my project |
import logging
import os
import httpx
from browser_use.browser.cloud.views import CloudBrowserAuthError, CloudBrowserError, CloudBrowserResponse, CreateBrowserRequest
from browser_use.sync.auth import CloudAuthConfig
logger = logging.getLogger(__name__)
class CloudBrowserClient:
def __init__(self, api_base_url:... | --- +++ @@ -1,3 +1,9 @@+"""Cloud browser service integration for browser-use.
+
+This module provides integration with the browser-use cloud browser service.
+When cloud_browser=True, it automatically creates a cloud browser instance
+and returns the CDP URL for connection.
+"""
import logging
import os
@@ -11,6 +1... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/cloud/cloud.py |
Create simple docstrings for beginners |
import base64
import logging
from datetime import datetime, timezone
from pathlib import Path
from typing import Literal
from browser_use.llm.messages import (
BaseMessage,
ContentPartImageParam,
ContentPartTextParam,
ImageURL,
SystemMessage,
UserMessage,
)
logger = logging.getLogger(__name__)
def _encode_im... | --- +++ @@ -1,3 +1,4 @@+"""Judge system for evaluating browser-use agent execution traces."""
import base64
import logging
@@ -18,6 +19,7 @@
def _encode_image(image_path: str) -> str | None:
+ """Encode image to base64 string."""
try:
path = Path(image_path)
if not path.exists():
@@ -30,6 +32,7 @@
d... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/agent/judge.py |
Add docstrings for utility scripts | import json
from dataclasses import dataclass
from os import getenv
from typing import TYPE_CHECKING, Any, TypeVar, overload
from pydantic import BaseModel
from browser_use.llm.aws.serializer import AWSBedrockMessageSerializer
from browser_use.llm.base import BaseChatModel
from browser_use.llm.exceptions import Model... | --- +++ @@ -20,6 +20,21 @@
@dataclass
class ChatAWSBedrock(BaseChatModel):
+ """
+ AWS Bedrock chat model supporting multiple providers (Anthropic, Meta, etc.).
+
+ This class provides access to various models via AWS Bedrock,
+ supporting both text generation and structured output via tool calling.
+
+ To use this ... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/aws/chat_bedrock.py |
Write clean docstrings for readability |
from __future__ import annotations
import asyncio
import os
import shutil
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar
import psutil
from bubus import BaseEvent
from pydantic import PrivateAttr
from browser_use.browser.events import (
BrowserKillEvent,
BrowserLaunchEven... | --- +++ @@ -1,3 +1,4 @@+"""Local browser watchdog for managing browser subprocess lifecycle."""
from __future__ import annotations
@@ -26,6 +27,7 @@
class LocalBrowserWatchdog(BaseWatchdog):
+ """Manages local browser subprocess lifecycle."""
# Events this watchdog listens to
LISTENS_TO: ClassVar[list[ty... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/local_browser_watchdog.py |
Write docstrings for data processing functions | import asyncio
from pydantic import BaseModel
from browser_use import Browser, ChatOpenAI
TASK = """
On the current wikipedia page, find the latest huge edit and tell me what is was about.
"""
class LatestEditFinder(BaseModel):
latest_edit: str
edit_time: str
edit_author: str
edit_summary: str
edit_url: str
... | --- +++ @@ -10,6 +10,7 @@
class LatestEditFinder(BaseModel):
+ """Find the latest huge edit on the current wikipedia page."""
latest_edit: str
edit_time: str
@@ -22,6 +23,9 @@
async def main():
+ """
+ Main function demonstrating mixed automation with Browser-Use and Playwright.
+ """
print('🚀 Mixed Au... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/actor/playground/mixed_automation.py |
Add docstrings explaining edge cases | import base64
import os
from datetime import datetime, timezone
from pathlib import Path
import anyio
from bubus import BaseEvent
from pydantic import Field, field_validator
from uuid_extensions import uuid7str
MAX_STRING_LENGTH = 500000 # 100K chars ~ 25k tokens should be enough
MAX_URL_LENGTH = 100000
MAX_TASK_LEN... | --- +++ @@ -33,6 +33,7 @@
@classmethod
def from_agent(cls, agent) -> 'UpdateAgentTaskEvent':
+ """Create an UpdateAgentTaskEvent from an Agent instance"""
if not hasattr(agent, '_task_start_time'):
raise ValueError('Agent must have _task_start_time attribute')
@@ -72,6 +73,7 @@ @field_validator('file_co... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/agent/cloud_events.py |
Generate NumPy-style docstrings |
import logging
from pydantic import BaseModel, Field
from browser_use.agent.views import ActionResult
from browser_use.tools.service import Tools
from .service import GmailService
logger = logging.getLogger(__name__)
# Global Gmail service instance - initialized when actions are registered
_gmail_service: GmailSe... | --- +++ @@ -1,3 +1,8 @@+"""
+Gmail Actions for Browser Use
+Defines agent actions for Gmail integration including 2FA code retrieval,
+email reading, and authentication management.
+"""
import logging
@@ -15,12 +20,20 @@
class GetRecentEmailsParams(BaseModel):
+ """Parameters for getting recent emails"""
k... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/integrations/gmail/actions.py |
Provide clean and structured docstrings | class ModelError(Exception):
pass
class ModelProviderError(ModelError):
def __init__(
self,
message: str,
status_code: int = 502,
model: str | None = None,
):
super().__init__(message)
self.message = message
self.status_code = status_code
self.model = model
class ModelRateLimitError(ModelProvide... | --- +++ @@ -3,6 +3,7 @@
class ModelProviderError(ModelError):
+ """Exception raised when a model provider returns an error."""
def __init__(
self,
@@ -17,6 +18,7 @@
class ModelRateLimitError(ModelProviderError):
+ """Exception raised when a model provider returns a rate limit error."""
def __init__(
... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/exceptions.py |
Add standardized docstrings across the file | import json
import logging
import re
from typing import TypeVar
from groq import APIStatusError
from pydantic import BaseModel
logger = logging.getLogger(__name__)
T = TypeVar('T', bound=BaseModel)
class ParseFailedGenerationError(Exception):
pass
def try_parse_groq_failed_generation(
error: APIStatusError,
o... | --- +++ @@ -19,6 +19,7 @@ error: APIStatusError,
output_format: type[T],
) -> T:
+ """Extract JSON from model output, handling both plain JSON and code-block-wrapped JSON."""
try:
content = error.body['error']['failed_generation'] # type: ignore
@@ -92,6 +93,7 @@
def _fix_control_characters_in_json(cont... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/groq/parser.py |
Create simple docstrings for beginners | import os
import sys
import tempfile
from collections.abc import Iterable
from enum import Enum
from functools import cache
from pathlib import Path
from typing import Annotated, Any, Literal, Self
from urllib.parse import urlparse
from pydantic import AfterValidator, AliasChoices, BaseModel, ConfigDict, Field, field_... | --- +++ @@ -16,6 +16,7 @@
def _get_enable_default_extensions_default() -> bool:
+ """Get the default value for enable_default_extensions from env var or True."""
env_val = os.getenv('BROWSER_USE_DISABLE_EXTENSIONS')
if env_val is not None:
# If DISABLE_EXTENSIONS is truthy, return False (extensions disabled)... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/profile.py |
Auto-generate documentation strings for this file |
from __future__ import annotations
import json
from enum import Enum
from pathlib import Path
from typing import Any
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
from uuid_extensions import uuid7str
from browser_use.tokens.views import UsageSummary
class CellType(str, Enum):
CODE = 'code'
MAR... | --- +++ @@ -1,3 +1,4 @@+"""Data models for code-use mode."""
from __future__ import annotations
@@ -13,12 +14,14 @@
class CellType(str, Enum):
+ """Type of notebook cell."""
CODE = 'code'
MARKDOWN = 'markdown'
class ExecutionStatus(str, Enum):
+ """Execution status of a cell."""
PENDING = 'pendi... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/code_use/views.py |
Generate docstrings for this script | # @file purpose: Concise evaluation serializer for DOM trees - optimized for LLM query writing
from browser_use.dom.utils import cap_text_length
from browser_use.dom.views import (
EnhancedDOMTreeNode,
NodeType,
SimplifiedNode,
)
# Critical attributes for query writing and form interaction
# NOTE: Removed 'id' an... | --- +++ @@ -110,9 +110,19 @@
class DOMEvalSerializer:
+ """Ultra-concise DOM serializer for quick LLM query writing."""
@staticmethod
def serialize_tree(node: SimplifiedNode | None, include_attributes: list[str], depth: int = 0) -> str:
+ """
+ Serialize complete DOM tree structure for LLM understanding.
+
... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/dom/serializer/eval_serializer.py |
Create docstrings for reusable components |
from __future__ import annotations
import base64
import hashlib
import json
from dataclasses import dataclass, field
from importlib import metadata as importlib_metadata
from pathlib import Path
from typing import ClassVar
from bubus import BaseEvent
from cdp_use.cdp.network.events import (
DataReceivedEvent,
Load... | --- +++ @@ -1,3 +1,9 @@+"""HAR Recording Watchdog for Browser-Use sessions.
+
+Captures HTTPS network activity via CDP Network domain and writes a HAR 1.2
+file on browser shutdown. Respects `record_har_content` (omit/embed/attach)
+and `record_har_mode` (full/minimal).
+"""
from __future__ import annotations
@@ -... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/har_recording_watchdog.py |
Write reusable docstrings |
from typing import TYPE_CHECKING, Any, ClassVar
from bubus import BaseEvent
from cdp_use.cdp.page import CaptureScreenshotParameters
from browser_use.browser.events import ScreenshotEvent
from browser_use.browser.views import BrowserError
from browser_use.browser.watchdog_base import BaseWatchdog
from browser_use.ob... | --- +++ @@ -1,3 +1,4 @@+"""Screenshot watchdog for handling screenshot requests using CDP."""
from typing import TYPE_CHECKING, Any, ClassVar
@@ -14,6 +15,7 @@
class ScreenshotWatchdog(BaseWatchdog):
+ """Handles screenshot requests using CDP."""
# Events this watchdog listens to
LISTENS_TO: ClassVar[lis... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/screenshot_watchdog.py |
Provide clean and structured docstrings | from browser_use.dom.views import EnhancedDOMTreeNode, NodeType
class ClickableElementDetector:
@staticmethod
def is_interactive(node: EnhancedDOMTreeNode) -> bool:
def has_form_control_descendant(element: EnhancedDOMTreeNode, max_depth: int = 2) -> bool:
if max_depth <= 0:
return False
for child in e... | --- +++ @@ -4,8 +4,10 @@ class ClickableElementDetector:
@staticmethod
def is_interactive(node: EnhancedDOMTreeNode) -> bool:
+ """Check if this node is clickable/interactive using enhanced scoring."""
def has_form_control_descendant(element: EnhancedDOMTreeNode, max_depth: int = 2) -> bool:
+ """Detect nes... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/dom/serializer/clickable_elements.py |
Create simple docstrings for beginners |
import asyncio
import base64
import io
import logging
import os
from PIL import Image, ImageDraw, ImageFont
from browser_use.dom.views import DOMSelectorMap, EnhancedDOMTreeNode
from browser_use.observability import observe_debug
from browser_use.utils import time_execution_async
logger = logging.getLogger(__name__... | --- +++ @@ -1,3 +1,8 @@+"""Python-based highlighting system for drawing bounding boxes on screenshots.
+
+This module replaces JavaScript-based highlighting with fast Python image processing
+to draw bounding boxes around interactive elements directly on screenshots.
+"""
import asyncio
import base64
@@ -29,6 +34,1... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/python_highlights.py |
Document this script properly |
import asyncio
import datetime
import html
import json
import logging
import re
import tempfile
import traceback
from pathlib import Path
from typing import Any
from uuid_extensions import uuid7str
from browser_use.browser import BrowserSession
from browser_use.browser.profile import BrowserProfile
from browser_use.... | --- +++ @@ -1,3 +1,4 @@+"""Code-use agent service - Jupyter notebook-like code execution for browser automation."""
import asyncio
import datetime
@@ -52,6 +53,12 @@
class CodeAgent:
+ """
+ Agent that executes Python code in a notebook-like environment for browser automation.
+
+ This agent provides a Jupyter ... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/code_use/service.py |
Create documentation strings for testing functions |
import re
from dataclasses import dataclass
from enum import Enum, auto
from typing import TYPE_CHECKING, Any
from browser_use.dom.serializer.html_serializer import HTMLSerializer
from browser_use.dom.service import DomService
from browser_use.dom.views import MarkdownChunk
if TYPE_CHECKING:
from browser_use.browse... | --- +++ @@ -1,3 +1,9 @@+"""
+Shared markdown extraction utilities for browser content processing.
+
+This module provides a unified interface for extracting clean markdown from browser content,
+used by both the tools service and page actor.
+"""
import re
from dataclasses import dataclass
@@ -19,6 +25,23 @@ targe... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/dom/markdown_extractor.py |
Annotate my code with docstrings |
import asyncio
import logging
import os
import random
from typing import Any, TypeVar, overload
import httpx
from pydantic import BaseModel
from browser_use.llm.base import BaseChatModel
from browser_use.llm.exceptions import ModelProviderError, ModelRateLimitError
from browser_use.llm.messages import BaseMessage
fr... | --- +++ @@ -1,3 +1,9 @@+"""
+ChatBrowserUse - Client for browser-use cloud API
+
+This wraps the BaseChatModel protocol and sends requests to the browser-use cloud API
+for optimized browser automation LLM inference.
+"""
import asyncio
import logging
@@ -23,6 +29,18 @@
class ChatBrowserUse(BaseChatModel):
+ ""... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/browser_use/chat.py |
Write docstrings describing functionality |
from cdp_use.cdp.domsnapshot.commands import CaptureSnapshotReturns
from cdp_use.cdp.domsnapshot.types import (
LayoutTreeSnapshot,
NodeTreeSnapshot,
RareBooleanData,
)
from browser_use.dom.views import DOMRect, EnhancedSnapshotNode
# Only the ESSENTIAL computed styles for interactivity and visibility detection
R... | --- +++ @@ -1,3 +1,9 @@+"""
+Enhanced snapshot processing for browser-use DOM tree extraction.
+
+This module provides stateless functions for parsing Chrome DevTools Protocol (CDP) DOMSnapshot data
+to extract visibility, clickability, cursor styles, and other layout information.
+"""
from cdp_use.cdp.domsnapshot.c... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/dom/enhanced_snapshot.py |
Write proper docstrings for these functions |
import asyncio
import inspect
import time
from collections.abc import Iterable
from typing import Any, ClassVar
from bubus import BaseEvent, EventBus
from pydantic import BaseModel, ConfigDict, Field
from browser_use.browser.session import BrowserSession
class BaseWatchdog(BaseModel):
model_config = ConfigDict(
... | --- +++ @@ -1,3 +1,4 @@+"""Base watchdog class for browser monitoring components."""
import asyncio
import inspect
@@ -12,6 +13,13 @@
class BaseWatchdog(BaseModel):
+ """Base class for all browser watchdogs.
+
+ Watchdogs monitor browser state and emit events based on changes.
+ They automatically register even... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdog_base.py |
Add docstrings following best practices |
from typing import TYPE_CHECKING, ClassVar
from bubus import BaseEvent
from browser_use.browser.events import BrowserConnectedEvent
from browser_use.browser.watchdog_base import BaseWatchdog
if TYPE_CHECKING:
pass
class PermissionsWatchdog(BaseWatchdog):
# Event contracts
LISTENS_TO: ClassVar[list[type[BaseEv... | --- +++ @@ -1,3 +1,4 @@+"""Permissions watchdog for granting browser permissions on connection."""
from typing import TYPE_CHECKING, ClassVar
@@ -11,6 +12,7 @@
class PermissionsWatchdog(BaseWatchdog):
+ """Grants browser permissions when browser connects."""
# Event contracts
LISTENS_TO: ClassVar[list[ty... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/permissions_watchdog.py |
Add minimal docstrings for each function | import hashlib
from dataclasses import asdict, dataclass, field
from enum import Enum
from typing import Any
from cdp_use.cdp.accessibility.commands import GetFullAXTreeReturns
from cdp_use.cdp.accessibility.types import AXPropertyName
from cdp_use.cdp.dom.commands import GetDocumentReturns
from cdp_use.cdp.dom.types ... | --- +++ @@ -163,6 +163,7 @@
class MatchLevel(Enum):
+ """Element matching strictness levels for history replay."""
EXACT = 1 # Full hash with all attributes (current behavior)
STABLE = 2 # Hash with dynamic classes filtered out
@@ -172,6 +173,10 @@
def filter_dynamic_classes(class_str: str | None) -> st... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/dom/views.py |
Replace inline comments with docstrings | from __future__ import annotations
from dataclasses import dataclass
from typing import Any, TypeVar, overload
import httpx
from openai import (
APIConnectionError,
APIError,
APIStatusError,
APITimeoutError,
AsyncOpenAI,
RateLimitError,
)
from openai.types.chat import ChatCompletion
from pydantic import BaseMod... | --- +++ @@ -26,6 +26,7 @@
@dataclass
class ChatCerebras(BaseChatModel):
+ """Cerebras inference wrapper (OpenAI-compatible)."""
model: str = 'llama3.1-8b'
@@ -93,6 +94,11 @@ output_format: type[T] | None = None,
**kwargs: Any,
) -> ChatInvokeCompletion[T] | ChatInvokeCompletion[str]:
+ """
+ Cerebras ... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/cerebras/chat.py |
Add docstrings that explain logic | from __future__ import annotations
import hashlib
import json
import logging
import re
import traceback
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Generic, Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError, create_model, model_validator
from typing_exte... | --- +++ @@ -32,6 +32,7 @@
class MessageCompactionSettings(BaseModel):
+ """Summarizes older history into a compact memory block to reduce prompt size."""
enabled: bool = True
compact_every_n_steps: int = 15
@@ -55,6 +56,7 @@
class AgentSettings(BaseModel):
+ """Configuration options for the Agent"""
u... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/agent/views.py |
Add docstrings that explain inputs and outputs |
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from cdp_use.cdp.input.commands import DispatchMouseEventParameters, SynthesizeScrollGestureParameters
from cdp_use.cdp.input.types import MouseButton
from browser_use.browser.session import BrowserSession
class Mouse:
def __init__(self, browser_session: 'Bro... | --- +++ @@ -1,3 +1,4 @@+"""Mouse class for mouse operations."""
from typing import TYPE_CHECKING
@@ -9,6 +10,7 @@
class Mouse:
+ """Mouse operations for a target."""
def __init__(self, browser_session: 'BrowserSession', session_id: str | None = None, target_id: str | None = None):
self._browser_session ... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/actor/mouse.py |
Add concise docstrings to each method |
from typing import Any, Protocol, TypeVar, overload, runtime_checkable
from pydantic import BaseModel
from browser_use.llm.messages import BaseMessage
from browser_use.llm.views import ChatInvokeCompletion
T = TypeVar('T', bound=BaseModel)
@runtime_checkable
class BaseChatModel(Protocol):
_verified_api_keys: boo... | --- +++ @@ -1,3 +1,8 @@+"""
+We have switched all of our code from langchain to openai.types.chat.chat_completion_message_param.
+
+For easier transition we have
+"""
from typing import Any, Protocol, TypeVar, overload, runtime_checkable
@@ -44,7 +49,11 @@ source_type: type,
handler: Any,
) -> Any:
+ """
+... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/base.py |
Add missing documentation to my Python functions | from dataclasses import dataclass, field
from typing import Any
from bubus import BaseEvent
from cdp_use.cdp.target import TargetID
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_serializer
from browser_use.dom.views import DOMInteractedElement, SerializedDOMState
# Known placeholder image da... | --- +++ @@ -15,6 +15,7 @@
# Pydantic
class TabInfo(BaseModel):
+ """Represents information about a browser tab"""
model_config = ConfigDict(
extra='forbid',
@@ -41,6 +42,7 @@
class PageInfo(BaseModel):
+ """Comprehensive page size and scroll information"""
# Current viewport dimensions
viewport_widt... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/views.py |
Add docstrings to existing functions | import json
from typing import overload
from anthropic.types import (
Base64ImageSourceParam,
CacheControlEphemeralParam,
ImageBlockParam,
MessageParam,
TextBlockParam,
ToolUseBlockParam,
URLImageSourceParam,
)
from browser_use.llm.messages import (
AssistantMessage,
BaseMessage,
ContentPartImageParam,
Con... | --- +++ @@ -25,13 +25,16 @@
class AnthropicMessageSerializer:
+ """Serializer for converting between custom message types and Anthropic message param types."""
@staticmethod
def _is_base64_image(url: str) -> bool:
+ """Check if the URL is a base64 encoded image."""
return url.startswith('data:image/')
... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/anthropic/serializer.py |
Add docstrings to make code maintainable | # @file purpose: Serializes enhanced DOM trees to HTML format including shadow roots
from browser_use.dom.views import EnhancedDOMTreeNode, NodeType
class HTMLSerializer:
def __init__(self, extract_links: bool = False):
self.extract_links = extract_links
def serialize(self, node: EnhancedDOMTreeNode, depth: in... | --- +++ @@ -4,11 +4,36 @@
class HTMLSerializer:
+ """Serializes enhanced DOM trees back to HTML format.
+
+ This serializer reconstructs HTML from the enhanced DOM tree, including:
+ - Shadow DOM content (both open and closed)
+ - Iframe content documents
+ - All attributes and text nodes
+ - Proper HTML structure
... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/dom/serializer/html_serializer.py |
Add docstrings to improve code quality | # @file purpose: Ultra-compact serializer optimized for code-use agents
# Focuses on minimal token usage while preserving essential interactive context
from browser_use.dom.utils import cap_text_length
from browser_use.dom.views import (
EnhancedDOMTreeNode,
NodeType,
SimplifiedNode,
)
# Minimal but sufficient att... | --- +++ @@ -56,9 +56,19 @@
class DOMCodeAgentSerializer:
+ """Optimized DOM serializer for code-use agents - balances token efficiency with context."""
@staticmethod
def serialize_tree(node: SimplifiedNode | None, include_attributes: list[str], depth: int = 0) -> str:
+ """
+ Serialize DOM tree with smart t... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/dom/serializer/code_use_serializer.py |
Annotate my code with docstrings | from collections import defaultdict
from dataclasses import dataclass
from browser_use.dom.views import SimplifiedNode
"""
Helper class for maintaining a union of rectangles (used for order of elements calculation)
"""
@dataclass(frozen=True, slots=True)
class Rect:
x1: float
y1: float
x2: float
y2: float
de... | --- +++ @@ -10,6 +10,7 @@
@dataclass(frozen=True, slots=True)
class Rect:
+ """Closed axis-aligned rectangle with (x1,y1) bottom-left, (x2,y2) top-right."""
x1: float
y1: float
@@ -32,6 +33,10 @@
class RectUnionPure:
+ """
+ Maintains a *disjoint* set of rectangles.
+ No external dependencies - fine for a ... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/dom/serializer/paint_order.py |
Improve documentation using docstrings | import asyncio
import logging
import time
from typing import TYPE_CHECKING, Any
from cdp_use.cdp.accessibility.commands import GetFullAXTreeReturns
from cdp_use.cdp.accessibility.types import AXNode
from cdp_use.cdp.dom.types import Node
from cdp_use.cdp.target import TargetID
from browser_use.dom.enhanced_snapshot i... | --- +++ @@ -33,6 +33,13 @@
class DomService:
+ """
+ Service for getting the DOM tree and other DOM-related information.
+
+ Either browser or page must be provided.
+
+ TODO: currently we start a new websocket connection PER STEP, we should definitely keep this persistent
+ """
logger: logging.Logger
@@ -61,... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/dom/service.py |
Help me add docstrings to my project |
import json
import shutil
import sys
from pathlib import Path
from typing import Any
from urllib import request
from urllib.error import URLError
import click
from InquirerPy import inquirer
from InquirerPy.base.control import Choice
from InquirerPy.utils import InquirerPyStyle
from rich.console import Console
from r... | --- +++ @@ -1,3 +1,9 @@+"""
+Standalone init command for browser-use template generation.
+
+This module provides a minimal command-line interface for generating
+browser-use templates without requiring heavy TUI dependencies.
+"""
import json
import shutil
@@ -27,6 +33,11 @@
def _fetch_template_list() -> dict[... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/init_cmd.py |
Replace inline comments with docstrings |
import json
import logging
import os
from datetime import datetime
from functools import cache
from pathlib import Path
from typing import Any
from uuid import uuid4
import psutil
from pydantic import BaseModel, ConfigDict, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
logger = logging.getLogg... | --- +++ @@ -1,3 +1,4 @@+"""Configuration system for browser-use with automatic migration support."""
import json
import logging
@@ -17,6 +18,7 @@
@cache
def is_running_in_docker() -> bool:
+ """Detect if we are running in a docker container, for the purpose of optimizing chrome launch flags (dev shm usage, gpu s... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/config.py |
Write docstrings for algorithm functions |
import asyncio
from dataclasses import dataclass
from typing import Any, ClassVar, Literal
from bubus import BaseEvent
from cdp_use.cdp.browseruse.events import CaptchaSolverFinishedEvent as CDPCaptchaSolverFinishedEvent
from cdp_use.cdp.browseruse.events import CaptchaSolverStartedEvent as CDPCaptchaSolverStartedEve... | --- +++ @@ -1,3 +1,13 @@+"""Captcha solver watchdog — monitors captcha events from the browser proxy.
+
+Listens for BrowserUse.captchaSolverStarted/Finished CDP events and exposes a
+wait_if_captcha_solving() method that the agent step loop uses to block until
+a captcha is resolved (with a configurable timeout).
+
+N... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/captcha_watchdog.py |
Generate NumPy-style docstrings |
from typing import TYPE_CHECKING, TypeVar
from pydantic import BaseModel
from browser_use import logger
from browser_use.actor.utils import get_key_info
from browser_use.dom.serializer.serializer import DOMTreeSerializer
from browser_use.dom.service import DomService
from browser_use.llm.messages import SystemMessag... | --- +++ @@ -1,3 +1,4 @@+"""Page class for page-level operations."""
from typing import TYPE_CHECKING, TypeVar
@@ -36,6 +37,7 @@
class Page:
+ """Page operations (tab or iframe)."""
def __init__(
self, browser_session: 'BrowserSession', target_id: str, session_id: str | None = None, llm: 'BaseChatModel |... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/actor/page.py |
Include argument descriptions in docstrings |
import asyncio
from typing import TYPE_CHECKING
from cdp_use.cdp.target import AttachedToTargetEvent, DetachedFromTargetEvent, SessionID, TargetID
from browser_use.utils import create_task_with_error_handling
if TYPE_CHECKING:
from browser_use.browser.session import BrowserSession, CDPSession, Target
class Sessi... | --- +++ @@ -1,3 +1,8 @@+"""Event-driven CDP session management.
+
+Manages CDP sessions by listening to Target.attachedToTarget and Target.detachedFromTarget
+events, ensuring the session pool always reflects the current browser state.
+"""
import asyncio
from typing import TYPE_CHECKING
@@ -11,6 +16,18 @@
clas... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/session_manager.py |
Generate helpful docstrings for debugging | import asyncio
import json
import logging
import random
import time
from dataclasses import dataclass, field
from typing import Any, Literal, TypeVar, overload
from google import genai
from google.auth.credentials import Credentials
from google.genai import types
from google.genai.types import MediaModality
from pydan... | --- +++ @@ -44,6 +44,44 @@
@dataclass
class ChatGoogle(BaseChatModel):
+ """
+ A wrapper around Google's Gemini chat model using the genai client.
+
+ This class accepts all genai.Client parameters while adding model,
+ temperature, and config parameters for the LLM interface.
+
+ Args:
+ model: The Gemini model to... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/google/chat.py |
Create documentation for each function signature |
from typing import TYPE_CHECKING
# Lightweight imports that are commonly used
from browser_use.llm.base import BaseChatModel
from browser_use.llm.messages import (
AssistantMessage,
BaseMessage,
SystemMessage,
UserMessage,
)
from browser_use.llm.messages import (
ContentPartImageParam as ContentImage,
)
from bro... | --- +++ @@ -1,3 +1,8 @@+"""
+We have switched all of our code from langchain to openai.types.chat.chat_completion_message_param.
+
+For easier transition we have
+"""
from typing import TYPE_CHECKING
@@ -96,6 +101,7 @@
def __getattr__(name: str):
+ """Lazy import mechanism for heavy chat model imports and mode... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/__init__.py |
Expand my code with proper documentation strings | # pyright: reportMissingImports=false
# Check for MCP mode early to prevent logging initialization
import sys
if '--mcp' in sys.argv:
import logging
import os
os.environ['BROWSER_USE_LOGGING_LEVEL'] = 'critical'
os.environ['BROWSER_USE_SETUP_LOGGING'] = 'false'
logging.disable(logging.CRITICAL)
# Special case:... | --- +++ @@ -229,6 +229,7 @@
def get_default_config() -> dict[str, Any]:
+ """Return default configuration dictionary using the new config system."""
# Load config from the new config system
config_data = CONFIG.load_config()
@@ -266,6 +267,7 @@
def load_user_config() -> dict[str, Any]:
+ """Load user conf... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/cli.py |
Add docstrings to improve readability |
import logging
from typing import Any
from browser_use.browser.session import BrowserSession
from browser_use.browser.views import BrowserStateSummary
logger = logging.getLogger(__name__)
async def format_browser_state_for_llm(
state: BrowserStateSummary,
namespace: dict[str, Any],
browser_session: BrowserSessi... | --- +++ @@ -1,3 +1,4 @@+"""Browser state formatting helpers for code-use agent."""
import logging
from typing import Any
@@ -13,6 +14,17 @@ namespace: dict[str, Any],
browser_session: BrowserSession,
) -> str:
+ """
+ Format browser state summary for LLM consumption in code-use mode.
+
+ Args:
+ state: Browser... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/code_use/formatting.py |
Help me write clear docstrings |
import asyncio
import json
import os
from pathlib import Path
from typing import Any, ClassVar
from bubus import BaseEvent
from cdp_use.cdp.network import Cookie
from pydantic import Field, PrivateAttr
from browser_use.browser.events import (
BrowserConnectedEvent,
BrowserStopEvent,
LoadStorageStateEvent,
SaveSt... | --- +++ @@ -1,3 +1,4 @@+"""Storage state watchdog for managing browser cookies and storage persistence."""
import asyncio
import json
@@ -22,6 +23,7 @@
class StorageStateWatchdog(BaseWatchdog):
+ """Monitors and persists browser storage state including cookies and localStorage."""
# Event contracts
LISTEN... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/storage_state_watchdog.py |
Add docstrings to incomplete code | import asyncio
import base64
import csv
import io
import os
import re
import shutil
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any
from pydantic import BaseModel, Field
UNSUPPORTED_BINARY_EXTENSIONS = {
'png',
'jpg',
'jpeg',
'g... | --- +++ @@ -38,6 +38,7 @@
def _build_filename_error_message(file_name: str, supported_extensions: list[str]) -> str:
+ """Build a specific error message explaining why the filename was rejected and how to fix it."""
base = os.path.basename(file_name)
# Check for binary/image extension
@@ -76,11 +77,13 @@
... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/filesystem/file_system.py |
Fill in missing docstrings in my code |
import asyncio
import json
import os
from cdp_use.cdp.input.commands import DispatchKeyEventParameters
from browser_use.actor.utils import get_key_info
from browser_use.browser.events import (
ClickCoordinateEvent,
ClickElementEvent,
GetDropdownOptionsEvent,
GoBackEvent,
GoForwardEvent,
RefreshEvent,
ScrollEv... | --- +++ @@ -1,3 +1,4 @@+"""Default browser action handlers using CDP."""
import asyncio
import json
@@ -38,6 +39,7 @@
class DefaultActionWatchdog(BaseWatchdog):
+ """Handles default browser actions like click, type, and scroll using CDP."""
async def _execute_click_with_download_detection(
self,
@@ -45,6... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/default_action_watchdog.py |
Insert docstrings into my code | import json
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, TypeVar, overload
import httpx
from anthropic import (
APIConnectionError,
APIStatusError,
AsyncAnthropic,
NotGiven,
RateLimitError,
omit,
)
from anthropic.types import CacheControlEphemeralParam, Message, T... | --- +++ @@ -31,6 +31,9 @@
@dataclass
class ChatAnthropic(BaseChatModel):
+ """
+ A wrapper around Anthropic's chat model.
+ """
# Model configuration
model: str | ModelParam
@@ -55,6 +58,7 @@ return 'anthropic'
def _get_client_params(self) -> dict[str, Any]:
+ """Prepare client parameters dictionary."""... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/anthropic/chat.py |
Write Python docstrings for this snippet |
import asyncio
from pathlib import Path
from typing import Any, ClassVar
from bubus import BaseEvent
from cdp_use.cdp.page.events import ScreencastFrameEvent
from pydantic import PrivateAttr
from uuid_extensions import uuid7str
from browser_use.browser.events import AgentFocusChangedEvent, BrowserConnectedEvent, Bro... | --- +++ @@ -1,3 +1,4 @@+"""Recording Watchdog for Browser Use Sessions."""
import asyncio
from pathlib import Path
@@ -16,6 +17,9 @@
class RecordingWatchdog(BaseWatchdog):
+ """
+ Manages video recording of a browser session using CDP screencasting.
+ """
LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [Brows... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/recording_watchdog.py |
Create documentation for each function signature | from typing import overload
from groq.types.chat import (
ChatCompletionAssistantMessageParam,
ChatCompletionContentPartImageParam,
ChatCompletionContentPartTextParam,
ChatCompletionMessageParam,
ChatCompletionMessageToolCallParam,
ChatCompletionSystemMessageParam,
ChatCompletionUserMessageParam,
)
from groq.ty... | --- +++ @@ -25,6 +25,7 @@
class GroqMessageSerializer:
+ """Serializer for converting between custom message types and OpenAI message param types."""
@staticmethod
def _serialize_content_part_text(part: ContentPartTextParam) -> ChatCompletionContentPartTextParam:
@@ -41,6 +42,7 @@ def _serialize_user_content... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/groq/serializer.py |
Add docstrings to existing functions |
import base64
import io
import logging
import math
from pathlib import Path
from typing import Optional
from browser_use.browser.profile import ViewportSize
try:
import imageio.v2 as iio # type: ignore[import-not-found]
import numpy as np # type: ignore[import-not-found]
from imageio.core.format import Format ... | --- +++ @@ -1,3 +1,4 @@+"""Video Recording Service for Browser Use Sessions."""
import base64
import io
@@ -22,14 +23,30 @@
def _get_padded_size(size: ViewportSize, macro_block_size: int = 16) -> ViewportSize:
+ """Calculates the dimensions padded to the nearest multiple of macro_block_size."""
width = int(ma... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/video_recorder.py |
Write docstrings for utility functions |
import asyncio
from typing import ClassVar
from bubus import BaseEvent
from pydantic import PrivateAttr
from browser_use.browser.events import TabCreatedEvent
from browser_use.browser.watchdog_base import BaseWatchdog
class PopupsWatchdog(BaseWatchdog):
# Events this watchdog listens to and emits
LISTENS_TO: Cl... | --- +++ @@ -1,3 +1,4 @@+"""Watchdog for handling JavaScript dialogs (alert, confirm, prompt) automatically."""
import asyncio
from typing import ClassVar
@@ -10,6 +11,7 @@
class PopupsWatchdog(BaseWatchdog):
+ """Handles JavaScript dialogs (alert, confirm, prompt) by automatically accepting them immediately."""... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/popups_watchdog.py |
Create structured documentation for my script |
from typing import TYPE_CHECKING, ClassVar
from bubus import BaseEvent
from cdp_use.cdp.target import TargetID
from pydantic import PrivateAttr
from browser_use.browser.events import (
AboutBlankDVDScreensaverShownEvent,
BrowserStopEvent,
BrowserStoppedEvent,
CloseTabEvent,
NavigateToUrlEvent,
TabClosedEvent,
... | --- +++ @@ -1,3 +1,4 @@+"""About:blank watchdog for managing about:blank tabs with DVD screensaver."""
from typing import TYPE_CHECKING, ClassVar
@@ -21,6 +22,7 @@
class AboutBlankWatchdog(BaseWatchdog):
+ """Ensures there's always exactly one about:blank tab with DVD screensaver."""
# Event contracts
LI... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/aboutblank_watchdog.py |
Add docstrings to clarify complex logic |
import asyncio
import time
from typing import TYPE_CHECKING, ClassVar
import psutil
from bubus import BaseEvent
from cdp_use.cdp.target import SessionID, TargetID
from cdp_use.cdp.target.events import TargetCrashedEvent
from pydantic import Field, PrivateAttr
from browser_use.browser.events import (
BrowserConnecte... | --- +++ @@ -1,3 +1,4 @@+"""Browser watchdog for monitoring crashes and network timeouts using CDP."""
import asyncio
import time
@@ -24,6 +25,7 @@
class NetworkRequestTracker:
+ """Tracks ongoing network requests."""
def __init__(self, request_id: str, start_time: float, url: str, method: str, resource_type... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/crash_watchdog.py |
Provide docstrings following PEP 257 | import importlib.resources
from datetime import datetime
from typing import TYPE_CHECKING, Literal, Optional
from browser_use.dom.views import NodeType, SimplifiedNode
from browser_use.llm.messages import ContentPartImageParam, ContentPartTextParam, ImageURL, SystemMessage, UserMessage
from browser_use.observability i... | --- +++ @@ -14,6 +14,7 @@
def _is_anthropic_4_5_model(model_name: str | None) -> bool:
+ """Check if the model is Claude Opus 4.5 or Haiku 4.5 (requires 4096+ token prompts for caching)."""
if not model_name:
return False
model_lower = model_name.lower()
@@ -56,6 +57,7 @@ self.system_message = SystemMessag... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/agent/prompts.py |
Generate docstrings with examples |
import re
from browser_use.agent.views import AgentHistoryList, DetectedVariable
from browser_use.dom.views import DOMInteractedElement
def detect_variables_in_history(history: AgentHistoryList) -> dict[str, DetectedVariable]:
detected: dict[str, DetectedVariable] = {}
detected_values: set[str] = set() # Track w... | --- +++ @@ -1,3 +1,4 @@+"""Detect variables in agent history for reuse"""
import re
@@ -6,6 +7,16 @@
def detect_variables_in_history(history: AgentHistoryList) -> dict[str, DetectedVariable]:
+ """
+ Analyze agent history and detect reusable variables.
+
+ Uses two strategies:
+ 1. Element attributes (id, name... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/agent/variable_detector.py |
Document this module using docstrings |
from typing import TYPE_CHECKING, ClassVar
from bubus import BaseEvent
from browser_use.browser.events import (
BrowserErrorEvent,
NavigateToUrlEvent,
NavigationCompleteEvent,
TabCreatedEvent,
)
from browser_use.browser.watchdog_base import BaseWatchdog
if TYPE_CHECKING:
pass
# Track if we've shown the glob w... | --- +++ @@ -1,3 +1,4 @@+"""Security watchdog for enforcing URL access policies."""
from typing import TYPE_CHECKING, ClassVar
@@ -19,6 +20,7 @@
class SecurityWatchdog(BaseWatchdog):
+ """Monitors and enforces security policies for URL access."""
# Event contracts
LISTENS_TO: ClassVar[list[type[BaseEvent]... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/browser/watchdogs/security_watchdog.py |
Add clean documentation to messy code | import base64
import json
import re
from typing import Any, overload
from browser_use.llm.messages import (
AssistantMessage,
BaseMessage,
ContentPartImageParam,
ContentPartRefusalParam,
ContentPartTextParam,
SystemMessage,
ToolCall,
UserMessage,
)
class AWSBedrockMessageSerializer:
@staticmethod
def _is_... | --- +++ @@ -16,19 +16,23 @@
class AWSBedrockMessageSerializer:
+ """Serializer for converting between custom message types and AWS Bedrock message format."""
@staticmethod
def _is_base64_image(url: str) -> bool:
+ """Check if the URL is a base64 encoded image."""
return url.startswith('data:image/')
@... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/aws/serializer.py |
Write docstrings for utility functions | from __future__ import annotations
from typing import TYPE_CHECKING, Any
from pydantic import BaseModel, ConfigDict, Field
from browser_use.llm.messages import (
BaseMessage,
)
if TYPE_CHECKING:
pass
class HistoryItem(BaseModel):
step_number: int | None = None
evaluation_previous_goal: str | None = None
mem... | --- +++ @@ -13,6 +13,7 @@
class HistoryItem(BaseModel):
+ """Represents a single agent history item with its data and string representation"""
step_number: int | None = None
evaluation_previous_goal: str | None = None
@@ -25,10 +26,12 @@ model_config = ConfigDict(arbitrary_types_allowed=True)
def model_p... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/agent/message_manager/views.py |
Add detailed docstrings explaining each function | import base64
from google.genai.types import Content, ContentListUnion, Part
from browser_use.llm.messages import (
AssistantMessage,
BaseMessage,
SystemMessage,
UserMessage,
)
class GoogleMessageSerializer:
@staticmethod
def serialize_messages(
messages: list[BaseMessage], include_system_in_user: bool = F... | --- +++ @@ -11,11 +11,28 @@
class GoogleMessageSerializer:
+ """Serializer for converting messages to Google Gemini format."""
@staticmethod
def serialize_messages(
messages: list[BaseMessage], include_system_in_user: bool = False
) -> tuple[ContentListUnion, str | None]:
+ """
+ Convert a list of Base... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/google/serializer.py |
Add standardized docstrings across the file | from __future__ import annotations
import base64
import io
import logging
import os
import platform
from typing import TYPE_CHECKING
from browser_use.agent.views import AgentHistoryList
from browser_use.browser.views import PLACEHOLDER_4PX_SCREENSHOT
from browser_use.config import CONFIG
if TYPE_CHECKING:
from PIL ... | --- +++ @@ -18,6 +18,7 @@
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 t... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/agent/gif.py |
Add structured docstrings to improve clarity |
import asyncio
import csv
import datetime
import json
import logging
import re
from pathlib import Path
from typing import Any
import requests
from browser_use.browser import BrowserSession
from browser_use.filesystem.file_system import FileSystem
from browser_use.llm.base import BaseChatModel
from browser_use.tools... | --- +++ @@ -1,3 +1,8 @@+"""Namespace initialization for code-use mode.
+
+This module creates a namespace with all browser tools available as functions,
+similar to a Jupyter notebook environment.
+"""
import asyncio
import csv
@@ -62,6 +67,16 @@
def _strip_js_comments(js_code: str) -> str:
+ """
+ Remove JavaS... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/code_use/namespace.py |
Add verbose docstrings with examples | import json
from collections.abc import Mapping
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, TypeVar, overload
from anthropic import (
APIConnectionError,
APIStatusError,
AsyncAnthropicBedrock,
RateLimitError,
omit,
)
from anthropic.types import CacheControlEphemeralParam, Message, Too... | --- +++ @@ -30,6 +30,13 @@
@dataclass
class ChatAnthropicBedrock(ChatAWSBedrock):
+ """
+ AWS Bedrock Anthropic Claude chat model.
+
+ This is a convenience class that provides Claude-specific defaults
+ for the AWS Bedrock service. It inherits all functionality from
+ ChatAWSBedrock but sets Anthropic Claude as the... | https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/aws/chat_anthropic.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.