instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings explaining edge cases
# region - Content parts from typing import Literal, Union from pydantic import BaseModel def _truncate(text: str, max_length: int = 50) -> str: if len(text) <= max_length: return text return text[: max_length - 3] + '...' def _format_image_url(url: str, max_length: int = 50) -> str: if url.startswith('data:...
--- +++ @@ -1,3 +1,6 @@+""" +This implementation is based on the OpenAI types, while removing all the parts that are not needed for Browser Use. +""" # region - Content parts from typing import Literal, Union @@ -6,12 +9,14 @@ def _truncate(text: str, max_length: int = 50) -> str: + """Truncate text to max_leng...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/messages.py
Write docstrings for data processing functions
from browser_use.mcp.client import MCPClient from browser_use.mcp.controller import MCPToolWrapper __all__ = ['MCPClient', 'MCPToolWrapper', 'BrowserUseServer'] # type: ignore def __getattr__(name): if name == 'BrowserUseServer': from browser_use.mcp.server import BrowserUseServer return BrowserUseServer ra...
--- +++ @@ -1,3 +1,7 @@+"""MCP (Model Context Protocol) support for browser-use. + +This module provides integration with MCP servers and clients for browser automation. +""" from browser_use.mcp.client import MCPClient from browser_use.mcp.controller import MCPToolWrapper @@ -6,8 +10,9 @@ def __getattr__(name)...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/mcp/__init__.py
Can you add docstrings to this Python file?
import logging from dataclasses import dataclass, field from typing import Any, TypeVar, overload 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 from browser_u...
--- +++ @@ -31,6 +31,7 @@ _clean_model: str = field(default='', init=False, repr=False) def __post_init__(self) -> None: + """Resolve provider info from the model string via litellm.""" try: from litellm import get_llm_provider @@ -60,6 +61,7 @@ @staticmethod def _parse_usage(response: Any) -> ChatI...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/litellm/chat.py
Replace inline comments with docstrings
from __future__ import annotations from typing import Any from pydantic import BaseModel from browser_use.llm.schema import SchemaOptimizer class MistralSchemaOptimizer: UNSUPPORTED_KEYWORDS = {'minLength', 'maxLength', 'pattern', 'format'} @classmethod def create_mistral_compatible_schema(cls, model: type[B...
--- +++ @@ -1,3 +1,4 @@+"""Schema optimizer for Mistral-compatible JSON schemas.""" from __future__ import annotations @@ -9,11 +10,16 @@ class MistralSchemaOptimizer: + """Create JSON schemas that avoid Mistral's unsupported keywords.""" UNSUPPORTED_KEYWORDS = {'minLength', 'maxLength', 'pattern', 'format...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/mistral/schema.py
Add standardized docstrings across the file
import asyncio import logging from typing import Any from pydantic import Field, create_model from browser_use.agent.views import ActionResult from browser_use.tools.registry.service import Registry logger = logging.getLogger(__name__) try: from mcp import ClientSession, StdioServerParameters from mcp.client.std...
--- +++ @@ -1,3 +1,8 @@+"""MCP (Model Context Protocol) tool wrapper for browser-use. + +This module provides integration between MCP tools and browser-use's action registry system. +MCP tools are dynamically discovered and registered as browser-use actions. +""" import asyncio import logging @@ -22,8 +27,16 @@ ...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/mcp/controller.py
Add concise docstrings to each method
import asyncio import logging import time from typing import Any from pydantic import BaseModel, ConfigDict, Field, create_model from browser_use.agent.views import ActionResult from browser_use.telemetry import MCPClientTelemetryEvent, ProductTelemetry from browser_use.tools.registry.service import Registry from br...
--- +++ @@ -1,3 +1,26 @@+"""MCP (Model Context Protocol) client integration for browser-use. + +This module provides integration between external MCP servers and browser-use's action registry. +MCP tools are dynamically discovered and registered as browser-use actions. + +Example usage: + from browser_use import Too...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/mcp/client.py
Add structured docstrings to improve clarity
import os from typing import TYPE_CHECKING from browser_use.llm.azure.chat import ChatAzureOpenAI from browser_use.llm.browser_use.chat import ChatBrowserUse from browser_use.llm.cerebras.chat import ChatCerebras from browser_use.llm.google.chat import ChatGoogle from browser_use.llm.mistral.chat import ChatMistral f...
--- +++ @@ -1,3 +1,15 @@+""" +Convenient access to LLM models. + +Usage: + from browser_use import llm + + # Simple model access + model = llm.azure_gpt_4_1_mini + model = llm.openai_gpt_4o + model = llm.google_gemini_2_5_pro + model = llm.bu_latest # or bu_1_0, bu_2_0 +""" import os from typing ...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/models.py
Provide clean and structured docstrings
import ast import asyncio import base64 import dataclasses import enum import inspect import json import os import sys import textwrap from collections.abc import Callable, Coroutine from functools import wraps from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar, Union, cast, get_args, get_origin im...
--- +++ @@ -33,6 +33,7 @@ def get_terminal_width() -> int: + """Get terminal width, default to 80 if unable to detect""" try: return os.get_terminal_size().columns except (AttributeError, OSError): @@ -40,12 +41,14 @@ async def _call_callback(callback: Callable[..., Any], *args: Any) -> None: + """Call a...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/sandbox/sandbox.py
Add documentation for all methods
import asyncio import json from dataclasses import dataclass from typing import Any, TypeVar, overload import oci from oci.generative_ai_inference import GenerativeAiInferenceClient from oci.generative_ai_inference.models import ( BaseChatRequest, ChatDetails, CohereChatRequest, GenericChatRequest, OnDemandServi...
--- +++ @@ -1,3 +1,9 @@+""" +OCI Raw API chat model integration for browser-use. + +This module provides direct integration with Oracle Cloud Infrastructure's +Generative AI service using raw API calls without Langchain dependencies. +""" import asyncio import json @@ -28,6 +34,27 @@ @dataclass class ChatOCIRaw(...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/oci_raw/chat.py
Document helper functions with docstrings
import base64 from pathlib import Path import anyio from browser_use.observability import observe_debug class ScreenshotService: def __init__(self, agent_directory: str | Path): self.agent_directory = Path(agent_directory) if isinstance(agent_directory, str) else agent_directory # Create screenshots subdire...
--- +++ @@ -1,3 +1,6 @@+""" +Screenshot storage service for browser-use agents. +""" import base64 from pathlib import Path @@ -8,8 +11,10 @@ class ScreenshotService: + """Simple screenshot storage service that saves screenshots to disk""" def __init__(self, agent_directory: str | Path): + """Initialize wi...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/screenshots/service.py
Include argument descriptions in docstrings
from collections.abc import Mapping from dataclasses import dataclass from typing import Any, TypeVar, overload import httpx from ollama import AsyncClient as OllamaAsyncClient from ollama import Options from pydantic import BaseModel from browser_use.llm.base import BaseChatModel from browser_use.llm.exceptions impo...
--- +++ @@ -18,6 +18,9 @@ @dataclass class ChatOllama(BaseChatModel): + """ + A wrapper around Ollama's chat model. + """ model: str @@ -37,6 +40,7 @@ return 'ollama' def _get_client_params(self) -> dict[str, Any]: + """Prepare client parameters dictionary.""" return { 'host': self.host, 'tim...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/ollama/chat.py
Generate descriptive docstrings automatically
# @file purpose: Observability module for browser-use that handles optional lmnr integration with debug mode support import logging import os from collections.abc import Callable from functools import wraps from typing import Any, Literal, TypeVar, cast logger = logging.getLogger(__name__) from dotenv import load_dot...
--- +++ @@ -1,4 +1,16 @@ # @file purpose: Observability module for browser-use that handles optional lmnr integration with debug mode support +""" +Observability module for browser-use + +This module provides observability decorators that optionally integrate with lmnr (Laminar) for tracing. +If lmnr is not installed, ...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/observability.py
Add docstrings for utility scripts
import json from enum import Enum from typing import Any from pydantic import BaseModel class SandboxError(Exception): pass class SSEEventType(str, Enum): BROWSER_CREATED = 'browser_created' INSTANCE_CREATED = 'instance_created' INSTANCE_READY = 'instance_ready' LOG = 'log' RESULT = 'result' ERROR = 'erro...
--- +++ @@ -1,3 +1,4 @@+"""Type-safe event models for sandbox execution SSE streaming""" import json from enum import Enum @@ -11,6 +12,7 @@ class SSEEventType(str, Enum): + """Event types for Server-Sent Events""" BROWSER_CREATED = 'browser_created' INSTANCE_CREATED = 'instance_created' @@ -22,6 +24,7 @@...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/sandbox/views.py
Create Google-style docstrings for my code
from oci.generative_ai_inference.models import ImageContent, ImageUrl, Message, TextContent from browser_use.llm.messages import ( AssistantMessage, BaseMessage, ContentPartImageParam, SystemMessage, UserMessage, ) class OCIRawMessageSerializer: @staticmethod def _is_base64_image(url: str) -> bool: return...
--- +++ @@ -1,3 +1,9 @@+""" +Message serializer for OCI Raw API integration. + +This module handles the conversion between browser-use message formats +and the OCI Raw API message format using proper OCI SDK models. +""" from oci.generative_ai_inference.models import ImageContent, ImageUrl, Message, TextContent @@...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/oci_raw/serializer.py
Add docstrings for production code
from browser_use.dom.service import EnhancedDOMTreeNode def get_click_description(node: EnhancedDOMTreeNode) -> str: parts = [] # Tag name parts.append(node.tag_name) # Add type for inputs if node.tag_name == 'input' and node.attributes.get('type'): input_type = node.attributes['type'] parts.append(f'type...
--- +++ @@ -1,8 +1,10 @@+"""Utility functions for browser tools.""" from browser_use.dom.service import EnhancedDOMTreeNode def get_click_description(node: EnhancedDOMTreeNode) -> str: + """Get a brief description of the clicked element for memory.""" parts = [] # Tag name @@ -77,4 +79,4 @@ if node.attr...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/tools/utils.py
Document this script properly
from openai.types.chat import ChatCompletionMessageParam from browser_use.llm.messages import BaseMessage from browser_use.llm.openai.serializer import OpenAIMessageSerializer class OpenRouterMessageSerializer: @staticmethod def serialize_messages(messages: list[BaseMessage]) -> list[ChatCompletionMessageParam]: ...
--- +++ @@ -5,8 +5,22 @@ class OpenRouterMessageSerializer: + """ + Serializer for converting between custom message types and OpenRouter message formats. + + OpenRouter uses the OpenAI-compatible API, so we can reuse the OpenAI serializer. + """ @staticmethod def serialize_messages(messages: list[BaseMessage...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/openrouter/serializer.py
Add docstrings for production code
import logging from typing import Any from pydantic import BaseModel, ConfigDict, Field, create_model logger = logging.getLogger(__name__) # Keywords that indicate composition/reference patterns we don't support _UNSUPPORTED_KEYWORDS = frozenset( { '$ref', 'allOf', 'anyOf', 'oneOf', 'not', '$defs', '...
--- +++ @@ -1,3 +1,4 @@+"""Converts a JSON Schema dict to a runtime Pydantic model for structured extraction.""" import logging from typing import Any @@ -39,12 +40,17 @@ def _check_unsupported(schema: dict) -> None: + """Raise ValueError if the schema uses unsupported composition keywords.""" for kw in _UNSU...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/tools/extraction/schema_utils.py
Add missing documentation to my Python functions
import asyncio import json import os import shutil import time from datetime import datetime import httpx from pydantic import BaseModel from uuid_extensions import uuid7str from browser_use.config import CONFIG # Temporary user ID for pre-auth events (matches cloud backend) TEMP_USER_ID = '99999999-9999-9999-9999-...
--- +++ @@ -1,3 +1,6 @@+""" +OAuth2 Device Authorization Grant flow client for browser-use. +""" import asyncio import json @@ -17,6 +20,7 @@ def get_or_create_device_id() -> str: + """Get or create a persistent device ID for this installation.""" device_id_path = CONFIG.BROWSER_USE_CONFIG_DIR / 'device_id' ...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/sync/auth.py
Write proper docstrings for these functions
from typing import Any from browser_use_sdk.types.parameter_schema import ParameterSchema from browser_use_sdk.types.skill_response import SkillResponse from pydantic import BaseModel, ConfigDict, Field class MissingCookieException(Exception): def __init__(self, cookie_name: str, cookie_description: str): self....
--- +++ @@ -1,3 +1,4 @@+"""Skills views - wraps SDK types with helper methods""" from typing import Any @@ -7,6 +8,12 @@ class MissingCookieException(Exception): + """Raised when a required cookie is missing for skill execution + + Attributes: + cookie_name: The name of the missing cookie parameter + cookie_...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skills/views.py
Add documentation for all methods
import asyncio import logging import os import platform import re import signal import time from collections.abc import Callable, Coroutine from fnmatch import fnmatch from functools import cache, wraps from pathlib import Path from sys import stderr from typing import Any, ParamSpec, TypeVar from urllib.parse import u...
--- +++ @@ -32,6 +32,7 @@ def _get_openai_bad_request_error() -> type | None: + """Lazy loader for OpenAI BadRequestError.""" global _openai_bad_request_error if _openai_bad_request_error is None: try: @@ -44,6 +45,7 @@ def _get_groq_bad_request_error() -> type | None: + """Lazy loader for Groq BadReques...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/utils.py
Document helper functions with docstrings
from typing import Any from pydantic import BaseModel, ConfigDict, Field class ExtractionResult(BaseModel): model_config = ConfigDict(extra='forbid') data: dict[str, Any] = Field(description='The validated extraction payload') schema_used: dict[str, Any] = Field(description='The JSON Schema that was enforced')...
--- +++ @@ -1,3 +1,4 @@+"""Pydantic models for the extraction subsystem.""" from typing import Any @@ -5,6 +6,7 @@ class ExtractionResult(BaseModel): + """Metadata about a structured extraction, stored in ActionResult.metadata.""" model_config = ConfigDict(extra='forbid') @@ -12,4 +14,4 @@ schema_used: ...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/tools/extraction/views.py
Help me add docstrings to my project
import logging from dataclasses import dataclass, field from typing import Any from browser_use.browser.session import BrowserSession from browser_use.skill_cli.python_session import PythonSession logger = logging.getLogger(__name__) @dataclass class SessionInfo: name: str browser_mode: str headed: bool profi...
--- +++ @@ -1,3 +1,4 @@+"""Session registry - manages BrowserSession instances.""" import logging from dataclasses import dataclass, field @@ -11,6 +12,7 @@ @dataclass class SessionInfo: + """Information about a browser session.""" name: str browser_mode: str @@ -21,6 +23,11 @@ class SessionRegistry: +...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/sessions.py
Document this code for team use
import logging from typing import Any, Literal logger = logging.getLogger(__name__) COMMANDS = {'setup'} async def handle( action: str, params: dict[str, Any], ) -> dict[str, Any]: assert action == 'setup' mode: Literal['local', 'remote', 'full'] = params.get('mode', 'local') yes: bool = params.get('yes', Fa...
--- +++ @@ -1,3 +1,8 @@+"""Setup command - configure browser-use for first-time use. + +Handles dependency installation and configuration with mode-based +setup (local/remote/full) and optional automatic fixes. +""" import logging from typing import Any, Literal @@ -11,6 +16,7 @@ action: str, params: dict[str, A...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/commands/setup.py
Add docstrings following best practices
import logging import os from datetime import datetime, timedelta from pathlib import Path from typing import Any import anyio import httpx from dotenv import load_dotenv from browser_use.llm.base import BaseChatModel from browser_use.llm.views import ChatInvokeUsage from browser_use.tokens.custom_pricing import CUS...
--- +++ @@ -1,3 +1,9 @@+""" +Token cost service that tracks LLM token usage and costs. + +Fetches pricing data from LiteLLM repository and caches it for 1 day. +Automatically tracks token usage when LLMs are registered and invoked. +""" import logging import os @@ -40,6 +46,7 @@ class TokenCost: + """Service fo...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/tokens/service.py
Add docstrings for utility scripts
from typing import overload from openai.types.chat import ( ChatCompletionAssistantMessageParam, ChatCompletionContentPartImageParam, ChatCompletionContentPartRefusalParam, ChatCompletionContentPartTextParam, ChatCompletionMessageFunctionToolCallParam, ChatCompletionMessageParam, ChatCompletionSystemMessagePara...
--- +++ @@ -26,6 +26,7 @@ class OpenAIMessageSerializer: + """Serializer for converting between custom message types and OpenAI message param types.""" @staticmethod def _serialize_content_part_text(part: ContentPartTextParam) -> ChatCompletionContentPartTextParam: @@ -46,6 +47,7 @@ def _serialize_user_conte...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/openai/serializer.py
Write reusable docstrings
import argparse import json import logging import sys import tempfile from pathlib import Path from typing import Any, Literal from browser_use.skill_cli.commands.utils import get_sdk_client logger = logging.getLogger(__name__) ProfileMode = Literal['real', 'remote'] class ProfileModeError(Exception): pass d...
--- +++ @@ -1,3 +1,8 @@+"""Profile management command handlers. + +Unified profile management that works with both local Chrome profiles and cloud profiles. +The behavior is determined by the browser mode (-b real or -b remote). +""" import argparse import json @@ -16,11 +21,23 @@ class ProfileModeError(Excepti...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/commands/profile.py
Help me add docstrings to my project
import json import os from collections.abc import Mapping from dataclasses import dataclass, field from typing import Any, Literal, TypeAlias, TypeVar, overload import httpx from openai import APIConnectionError, APIStatusError, AsyncOpenAI, RateLimitError from openai.types.chat.chat_completion import ChatCompletion f...
--- +++ @@ -268,6 +268,41 @@ @dataclass class ChatVercel(BaseChatModel): + """ + A wrapper around Vercel AI Gateway's API, which provides OpenAI-compatible access + to various LLM models with features like rate limiting, caching, and monitoring. + + Examples: + ```python + from browser_use import Agent, Cha...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/vercel/chat.py
Generate consistent documentation across files
import asyncio import base64 import json import sys import tempfile from contextlib import asynccontextmanager from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from cdp_use import CDPClient from browser_use.browser.session import BrowserSession STA...
--- +++ @@ -1,3 +1,21 @@+"""Serverless CLI for browser-use - runs commands directly without a session server. + +Each command reconnects to the browser via CDP WebSocket URL saved to a state file. +The browser process stays alive between commands; only the Python process exits. + +Two-tier reconnection: + Tier 1 (Ligh...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/direct.py
Create docstrings for each class method
import asyncio import base64 import logging from pathlib import Path from typing import Any from browser_use.skill_cli.sessions import SessionInfo logger = logging.getLogger(__name__) COMMANDS = { 'open', 'click', 'type', 'input', 'scroll', 'back', 'screenshot', 'state', 'switch', 'close-tab', 'keys', '...
--- +++ @@ -1,3 +1,4 @@+"""Browser control commands.""" import asyncio import base64 @@ -34,6 +35,7 @@ async def _execute_js(session: SessionInfo, js: str) -> Any: + """Execute JavaScript in the browser via CDP.""" bs = session.browser_session # Get or create a CDP session for the focused target cdp_sessi...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/commands/browser.py
Create documentation strings for testing functions
from datetime import datetime from typing import Any, TypeVar from pydantic import BaseModel, Field from browser_use.llm.views import ChatInvokeUsage T = TypeVar('T', bound=BaseModel) class TokenUsageEntry(BaseModel): model: str timestamp: datetime usage: ChatInvokeUsage class TokenCostCalculated(BaseModel):...
--- +++ @@ -9,6 +9,7 @@ class TokenUsageEntry(BaseModel): + """Single token usage entry""" model: str timestamp: datetime @@ -16,6 +17,7 @@ class TokenCostCalculated(BaseModel): + """Token cost""" new_prompt_tokens: int new_prompt_cost: float @@ -45,6 +47,7 @@ class ModelPricing(BaseModel): + ""...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/tokens/views.py
Generate consistent docstrings
import json import os import sys from pathlib import Path class APIKeyRequired(Exception): pass def get_config_path() -> Path: if sys.platform == 'win32': base = Path(os.environ.get('APPDATA', Path.home())) else: base = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config')) return base / 'browse...
--- +++ @@ -1,3 +1,4 @@+"""API key management for browser-use CLI.""" import json import os @@ -6,11 +7,13 @@ class APIKeyRequired(Exception): + """Raised when API key is required but not provided.""" pass def get_config_path() -> Path: + """Get browser-use config file path.""" if sys.platform == 'wi...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/api_key.py
Generate missing documentation strings
from abc import ABC, abstractmethod from collections.abc import Sequence from dataclasses import asdict, dataclass from typing import Any, Literal from browser_use.config import is_running_in_docker @dataclass class BaseTelemetryEvent(ABC): @property @abstractmethod def name(self) -> str: pass @property def ...
--- +++ @@ -60,6 +60,7 @@ @dataclass class MCPClientTelemetryEvent(BaseTelemetryEvent): + """Telemetry event for MCP client usage""" server_name: str command: str @@ -75,6 +76,7 @@ @dataclass class MCPServerTelemetryEvent(BaseTelemetryEvent): + """Telemetry event for MCP server usage""" version: str a...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/telemetry/views.py
Write docstrings describing functionality
import base64 import json from typing import Any, overload from ollama._types import Image, Message from browser_use.llm.messages import ( AssistantMessage, BaseMessage, SystemMessage, ToolCall, UserMessage, ) class OllamaMessageSerializer: @staticmethod def _extract_text_content(content: Any) -> str: if ...
--- +++ @@ -14,9 +14,11 @@ class OllamaMessageSerializer: + """Serializer for converting between custom message types and Ollama message types.""" @staticmethod def _extract_text_content(content: Any) -> str: + """Extract text content from message content, ignoring images.""" if content is None: retur...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/ollama/serializer.py
Create docstrings for reusable components
import logging import os from typing import Any, Literal from browser_use_sdk import AsyncBrowserUse from browser_use_sdk.types.execute_skill_response import ExecuteSkillResponse from browser_use_sdk.types.skill_list_response import SkillListResponse from cdp_use.cdp.network import Cookie from pydantic import BaseMod...
--- +++ @@ -1,3 +1,4 @@+"""Skills service for fetching and executing skills from the Browser Use API""" import logging import os @@ -18,8 +19,15 @@ class SkillService: + """Service for managing and executing skills from the Browser Use API""" def __init__(self, skill_ids: list[str | Literal['*']], api_key: ...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skills/service.py
Document this code for team use
from collections.abc import Iterable, Mapping from dataclasses import dataclass, field from typing import Any, Literal, TypeVar, overload import httpx from openai import APIConnectionError, APIStatusError, AsyncOpenAI, RateLimitError from openai.types.chat import ChatCompletionContentPartTextParam from openai.types.ch...
--- +++ @@ -23,6 +23,12 @@ @dataclass class ChatOpenAI(BaseChatModel): + """ + A wrapper around AsyncOpenAI that implements the BaseLLM protocol. + + This class accepts all AsyncOpenAI parameters while adding model + and temperature parameters for the LLM interface (if temperature it not `None`). + """ # Model c...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/openai/chat.py
Add professional docstrings to my codebase
import asyncio import logging from pathlib import Path from typing import Any from browser_use.skill_cli.sessions import SessionInfo logger = logging.getLogger(__name__) async def handle(session: SessionInfo, params: dict[str, Any]) -> Any: python_session = session.python_session browser_session = session.browse...
--- +++ @@ -1,3 +1,4 @@+"""Python execution command handler.""" import asyncio import logging @@ -10,6 +11,14 @@ async def handle(session: SessionInfo, params: dict[str, Any]) -> Any: + """Handle python command. + + Supports: + - python "<code>" - Execute Python code + - python --file script.py - Execute Python...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/commands/python_exec.py
Write Python docstrings for this snippet
import logging import os import sys from pathlib import Path from dotenv import load_dotenv load_dotenv() from browser_use.config import CONFIG def addLoggingLevel(levelName, levelNum, methodName=None): if not methodName: methodName = levelName.lower() if hasattr(logging, levelName): raise AttributeError(f'...
--- +++ @@ -11,6 +11,30 @@ def addLoggingLevel(levelName, levelNum, methodName=None): + """ + Comprehensively adds a new logging level to the `logging` module and the + currently configured logging class. + + `levelName` becomes an attribute of the `logging` module with the value + `levelNum`. `methodName` becomes ...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/logging_config.py
Create docstrings for each class method
import asyncio import functools import inspect import logging import re from collections.abc import Callable from inspect import Parameter, iscoroutinefunction, signature from types import UnionType from typing import Any, Generic, Optional, TypeVar, Union, get_args, get_origin import pyotp from pydantic import BaseMo...
--- +++ @@ -30,6 +30,7 @@ class Registry(Generic[Context]): + """Service for registering and managing actions""" def __init__(self, exclude_actions: list[str] | None = None): self.registry = ActionRegistry() @@ -38,6 +39,11 @@ self.exclude_actions = list(exclude_actions) if exclude_actions is not None else...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/tools/registry/service.py
Generate missing documentation strings
from datetime import datetime, timezone from browser_use_sdk import BrowserUse _client: BrowserUse | None = None def get_sdk_client() -> BrowserUse: global _client if _client is None: from browser_use.skill_cli.api_key import require_api_key api_key = require_api_key('Cloud API') _client = BrowserUse(api_...
--- +++ @@ -1,3 +1,4 @@+"""Shared utilities for CLI command handlers.""" from datetime import datetime, timezone @@ -7,6 +8,7 @@ def get_sdk_client() -> BrowserUse: + """Get authenticated SDK client (singleton).""" global _client if _client is None: from browser_use.skill_cli.api_key import require_api_...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/commands/utils.py
Provide docstrings following PEP 257
import asyncio import io import traceback from contextlib import redirect_stderr, redirect_stdout from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Any, Literal if TYPE_CHECKING: from browser_use.browser.session import BrowserSession @dataclass class ExecutionResul...
--- +++ @@ -1,3 +1,4 @@+"""Jupyter-like persistent Python execution for browser-use CLI.""" import asyncio import io @@ -13,6 +14,7 @@ @dataclass class ExecutionResult: + """Result of Python code execution.""" success: bool output: str = '' @@ -21,12 +23,18 @@ @dataclass class PythonSession: + """Jupyte...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/python_session.py
Include argument descriptions in docstrings
from typing import overload from openai.types.responses.easy_input_message_param import EasyInputMessageParam from openai.types.responses.response_input_image_param import ResponseInputImageParam from openai.types.responses.response_input_message_content_list_param import ( ResponseInputMessageContentListParam, ) fr...
--- +++ @@ -1,3 +1,4 @@+"""Serializer for converting messages to OpenAI Responses API input format.""" from typing import overload @@ -20,6 +21,7 @@ class ResponsesAPIMessageSerializer: + """Serializer for converting between custom message types and OpenAI Responses API input format.""" @staticmethod def...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/openai/responses_serializer.py
Generate docstrings for each module
import asyncio import json import logging import os import re import shutil import signal from pathlib import Path from typing import Any logger = logging.getLogger(__name__) # Pattern to extract tunnel URL from cloudflared output _URL_PATTERN = re.compile(r'(https://\S+\.trycloudflare\.com)') # Directory for tunne...
--- +++ @@ -1,3 +1,15 @@+"""Cloudflared tunnel binary management. + +This module manages the cloudflared binary for tunnel support. +Cloudflared must be installed via install.sh or manually by the user. + +Tunnels are managed independently of browser sessions - they are purely +a network utility for exposing local port...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/tunnel.py
Add docstrings for internal functions
__all__ = ['main'] def __getattr__(name: str): if name == 'main': from browser_use.skill_cli.main import main return main raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
--- +++ @@ -1,10 +1,24 @@+"""Browser-use CLI package. + +This package provides a fast command-line interface for browser automation. +The CLI uses a session server architecture for persistent browser sessions. + +Usage: + browser-use open https://example.com + browser-use click 5 + browser-use type "Hello Worl...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/__init__.py
Write reusable docstrings
from collections.abc import Callable from typing import TYPE_CHECKING, Any from pydantic import BaseModel, ConfigDict from browser_use.browser import BrowserSession from browser_use.filesystem.file_system import FileSystem from browser_use.llm.base import BaseChatModel if TYPE_CHECKING: pass class RegisteredActio...
--- +++ @@ -12,6 +12,7 @@ class RegisteredAction(BaseModel): + """Model for a registered action""" name: str description: str @@ -28,6 +29,7 @@ model_config = ConfigDict(arbitrary_types_allowed=True) def prompt_description(self) -> str: + """Get a description of the action for the prompt in unstructured...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/tools/registry/views.py
Add docstrings to meet PEP guidelines
import logging from typing import Any logger = logging.getLogger(__name__) COMMANDS = {'doctor'} async def handle() -> dict[str, Any]: checks: dict[str, dict[str, Any]] = {} # 1. Package installation checks['package'] = _check_package() # 2. Browser availability checks['browser'] = _check_browser() # 3. A...
--- +++ @@ -1,3 +1,8 @@+"""Doctor command - check installation and dependencies. + +Validates that browser-use is properly installed and all dependencies +are available. Provides helpful diagnostic information and fixes. +""" import logging from typing import Any @@ -8,6 +13,7 @@ async def handle() -> dict[str,...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/commands/doctor.py
Add docstrings to improve collaboration
import asyncio import json import logging import os from typing import Generic, TypeVar import anyio try: from lmnr import Laminar # type: ignore except ImportError: Laminar = None # type: ignore from pydantic import BaseModel from browser_use.agent.views import ActionModel, ActionResult from browser_use.browser...
--- +++ @@ -75,6 +75,7 @@ def _detect_sensitive_key_name(text: str, sensitive_data: dict[str, str | dict[str, str]] | None) -> str | None: + """Detect which sensitive key name corresponds to the given text value.""" if not sensitive_data or not text: return None @@ -230,6 +231,7 @@ css_scope: str | None, ...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/tools/service.py
Add docstrings to meet PEP guidelines
import json from dataclasses import asdict, dataclass, field from typing import Any @dataclass class Request: id: str action: str session: str params: dict[str, Any] = field(default_factory=dict) def to_json(self) -> str: return json.dumps(asdict(self)) @classmethod def from_json(cls, data: str) -> 'Requ...
--- +++ @@ -1,3 +1,7 @@+"""Wire protocol for CLI↔Server communication. + +Uses JSON over Unix sockets (or TCP on Windows) with newline-delimited messages. +""" import json from dataclasses import asdict, dataclass, field @@ -6,6 +10,7 @@ @dataclass class Request: + """Command request from CLI to server.""" i...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/protocol.py
Write docstrings describing functionality
import os import sys # Set environment variables BEFORE any browser_use imports to prevent early logging os.environ['BROWSER_USE_LOGGING_LEVEL'] = 'critical' os.environ['BROWSER_USE_SETUP_LOGGING'] = 'false' import asyncio import json import logging import time from pathlib import Path from typing import Any from b...
--- +++ @@ -1,3 +1,27 @@+"""MCP Server for browser-use - exposes browser automation capabilities via Model Context Protocol. + +This server provides tools for: +- Running autonomous browser tasks with an AI agent +- Direct browser control (navigation, clicking, typing, etc.) +- Content extraction from web pages +- File...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/mcp/server.py
Expand my code with proper documentation strings
from typing import Any from pydantic import BaseModel, Field, create_model from browser_use.skills.views import ParameterSchema def convert_parameters_to_pydantic(parameters: list[ParameterSchema], model_name: str = 'SkillParameters') -> type[BaseModel]: if not parameters: # Return empty model if no parameters ...
--- +++ @@ -1,3 +1,4 @@+"""Utilities for skill schema conversion""" from typing import Any @@ -7,6 +8,15 @@ def convert_parameters_to_pydantic(parameters: list[ParameterSchema], model_name: str = 'SkillParameters') -> type[BaseModel]: + """Convert a list of ParameterSchema to a pydantic model for structured ou...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skills/utils.py
Generate docstrings with examples
from typing import Generic, TypeVar, Union from pydantic import BaseModel T = TypeVar('T', bound=Union[BaseModel, str]) class ChatInvokeUsage(BaseModel): prompt_tokens: int """The number of tokens in the prompt (this includes the cached tokens as well. When calculating the cost, subtract the cached tokens from t...
--- +++ @@ -6,6 +6,9 @@ class ChatInvokeUsage(BaseModel): + """ + Usage information for a chat model invocation. + """ prompt_tokens: int """The number of tokens in the prompt (this includes the cached tokens as well. When calculating the cost, subtract the cached tokens from the prompt tokens)""" @@ -27,6 +3...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/views.py
Document classes and their methods
import argparse import json import logging import sys from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any from browser_use_sdk.types.session_item_view import SessionItemView from browser_use_sdk.types.session_view import SessionView from browser_use_sdk.types.share_view import Share...
--- +++ @@ -1,3 +1,9 @@+"""Cloud session SDK wrappers and CLI handlers. + +This module provides: +- SDK wrapper functions for the Browser-Use Cloud Session API +- CLI command handlers for `browser-use session <command>` +""" import argparse import json @@ -19,6 +25,20 @@ def create_session(**kwargs: Any) -> Ses...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/commands/cloud_session.py
Generate docstrings with parameter types
#!/usr/bin/env python3 import argparse import asyncio import hashlib import json import os import socket import subprocess import sys import tempfile import time from pathlib import Path # ============================================================================= # Early command interception (before heavy imports)...
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +"""Fast CLI for browser-use. STDLIB ONLY - must start in <50ms. + +This is the main entry point for the browser-use CLI. It uses only stdlib +imports to ensure fast startup, delegating heavy operations to the session +server which loads once and stays running. +""" im...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/main.py
Generate docstrings for exported functions
import argparse import json import logging import sys from typing import Any from browser_use_sdk.types.task_created_response import TaskCreatedResponse from browser_use_sdk.types.task_item_view import TaskItemView from browser_use_sdk.types.task_log_file_response import TaskLogFileResponse from browser_use_sdk.types...
--- +++ @@ -1,3 +1,9 @@+"""Cloud task SDK wrappers and CLI handlers. + +This module provides: +- SDK wrapper functions for the Browser-Use Cloud Task API +- CLI command handlers for `browser-use task <command>` +""" import argparse import json @@ -16,6 +22,7 @@ def _filter_none(kwargs: dict[str, Any]) -> dict[s...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/commands/cloud_task.py
Generate missing documentation strings
import json from pathlib import Path from typing import Literal CONFIG_PATH = Path.home() / '.browser-use' / 'install-config.json' ModeType = Literal['chromium', 'real', 'remote'] # Local modes (both require Chromium to be installed) LOCAL_MODES: set[str] = {'chromium', 'real'} def get_config() -> dict: if not C...
--- +++ @@ -1,3 +1,12 @@+"""Install configuration - tracks which browser modes are available. + +This module manages the installation configuration that determines which browser +modes (chromium, real, remote) are available based on how browser-use was installed. + +Config file: ~/.browser-use/install-config.json + +Wh...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/install_config.py
Turn comments into proper docstrings
import logging import httpx from bubus import BaseEvent from browser_use.config import CONFIG from browser_use.sync.auth import TEMP_USER_ID, DeviceAuthClient logger = logging.getLogger(__name__) class CloudSync: def __init__(self, base_url: str | None = None, allow_session_events_for_auth: bool = False): # B...
--- +++ @@ -1,3 +1,6 @@+""" +Cloud sync service for sending events to the Browser Use cloud. +""" import logging @@ -11,6 +14,7 @@ class CloudSync: + """Service for syncing events to the Browser Use cloud""" def __init__(self, base_url: str | None = None, allow_session_events_for_auth: bool = False): # ...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/sync/service.py
Generate docstrings for exported functions
import logging from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from browser_use.skill_cli.sessions import SessionRegistry logger = logging.getLogger(__name__) COMMANDS = {'sessions', 'close'} async def handle(action: str, session_name: str, registry: 'SessionRegistry', params: dict[str, Any]) -> Any: if...
--- +++ @@ -1,3 +1,4 @@+"""Session management command handlers.""" import logging from typing import TYPE_CHECKING, Any @@ -11,6 +12,7 @@ async def handle(action: str, session_name: str, registry: 'SessionRegistry', params: dict[str, Any]) -> Any: + """Handle session management command.""" if action == 'sessi...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/commands/session.py
Help me comply with documentation standards
from typing import Any from pydantic import BaseModel class SchemaOptimizer: @staticmethod def create_optimized_json_schema( model: type[BaseModel], *, remove_min_items: bool = False, remove_defaults: bool = False, ) -> dict[str, Any]: # Generate original schema original_schema = model.model_json_sch...
--- +++ @@ -1,3 +1,6 @@+""" +Utilities for creating optimized Pydantic schemas for LLM usage. +""" from typing import Any @@ -12,6 +15,18 @@ remove_min_items: bool = False, remove_defaults: bool = False, ) -> dict[str, Any]: + """ + Create the most optimized schema by flattening all $ref/$defs while prese...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/schema.py
Add well-formatted docstrings
from collections.abc import Mapping from dataclasses import dataclass from typing import Any, TypeVar, overload import httpx from openai import APIConnectionError, APIStatusError, AsyncOpenAI, RateLimitError from openai.types.chat.chat_completion import ChatCompletion from openai.types.shared_params.response_format_js...
--- +++ @@ -23,6 +23,12 @@ @dataclass class ChatOpenRouter(BaseChatModel): + """ + A wrapper around OpenRouter's chat API, which provides access to various LLM models + through a unified OpenAI-compatible interface. + + This class implements the BaseChatModel protocol for OpenRouter's API. + """ # Model configur...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/openrouter/chat.py
Write proper docstrings for these functions
from openai.types.chat import ChatCompletionMessageParam from browser_use.llm.messages import BaseMessage from browser_use.llm.openai.serializer import OpenAIMessageSerializer class VercelMessageSerializer: @staticmethod def serialize_messages(messages: list[BaseMessage]) -> list[ChatCompletionMessageParam]: # ...
--- +++ @@ -5,8 +5,22 @@ class VercelMessageSerializer: + """ + Serializer for converting between custom message types and Vercel AI Gateway message formats. + + Vercel AI Gateway uses the OpenAI-compatible API, so we can reuse the OpenAI serializer. + """ @staticmethod def serialize_messages(messages: list[B...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/llm/vercel/serializer.py
Add docstrings that explain logic
import logging import os from typing import Any from browser_use.skill_cli.api_key import APIKeyRequired, require_api_key from browser_use.skill_cli.sessions import SessionInfo logger = logging.getLogger(__name__) # Cloud-only flags that only work in remote mode CLOUD_ONLY_FLAGS = [ 'session_id', 'proxy_country',...
--- +++ @@ -1,3 +1,4 @@+"""Agent task command handler.""" import logging import os @@ -29,6 +30,12 @@ async def handle(session: SessionInfo, params: dict[str, Any]) -> Any: + """Handle agent run command. + + Routes based on browser mode: + - Remote mode (--browser remote): Uses Cloud API with US proxy by defaul...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/commands/agent.py
Add docstrings with type hints explained
import logging import os from dotenv import load_dotenv from posthog import Posthog from uuid_extensions import uuid7str from browser_use.telemetry.views import BaseTelemetryEvent from browser_use.utils import singleton load_dotenv() from browser_use.config import CONFIG logger = logging.getLogger(__name__) POST...
--- +++ @@ -22,6 +22,11 @@ @singleton class ProductTelemetry: + """ + Service for capturing anonymized telemetry data. + + If the environment variable `ANONYMIZED_TELEMETRY=False`, anonymized telemetry will be disabled. + """ USER_ID_PATH = str(CONFIG.BROWSER_USE_CONFIG_DIR / 'device_id') PROJECT_API_KEY = 'ph...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/telemetry/service.py
Add docstrings for better understanding
import argparse import asyncio import json import logging import os import signal import sys from pathlib import Path from typing import IO import portalocker # Configure logging before imports logging.basicConfig( level=logging.INFO, format='%(asctime)s [%(levelname)s] %(name)s: %(message)s', handlers=[logging.S...
--- +++ @@ -1,3 +1,9 @@+"""Session server - keeps BrowserSession instances alive. + +This server runs as a background process, managing browser sessions and +handling commands from the CLI. It uses Unix sockets (or TCP on Windows) +for IPC communication. +""" import argparse import asyncio @@ -21,6 +27,7 @@ cla...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/server.py
Create docstrings for reusable components
import hashlib import os import platform import signal import subprocess import sys import tempfile from pathlib import Path from typing import IO import portalocker def get_socket_path(session: str) -> str: if sys.platform == 'win32': # Windows: use TCP on deterministic port (49152-65535) # Use 127.0.0.1 expl...
--- +++ @@ -1,3 +1,4 @@+"""Platform utilities for CLI and server.""" import hashlib import os @@ -13,6 +14,11 @@ def get_socket_path(session: str) -> str: + """Get socket path for session. + + On Windows, returns a TCP address (tcp://127.0.0.1:PORT). + On Unix, returns a Unix socket path. + """ if sys.platfor...
https://raw.githubusercontent.com/browser-use/browser-use/HEAD/browser_use/skill_cli/utils.py
Document my Python code with docstrings
import json import hashlib import os import tempfile import zipfile import shutil import copy from dataclasses import dataclass from pathlib import Path from typing import Optional, Dict, List, Any, Callable, Set from datetime import datetime, timezone import re import pathspec import yaml from packaging import vers...
--- +++ @@ -1,3 +1,10 @@+""" +Extension Manager for Spec Kit + +Handles installation, removal, and management of Spec Kit extensions. +Extensions are modular packages that add commands and functionality to spec-kit +without bloating the core framework. +""" import json import hashlib @@ -20,18 +27,33 @@ class E...
https://raw.githubusercontent.com/github/spec-kit/HEAD/src/specify_cli/extensions.py
Help me write clear docstrings
from pathlib import Path from typing import Dict, List, Any import yaml class CommandRegistrar: # Agent configurations with directory, format, and argument placeholder AGENT_CONFIGS = { "claude": { "dir": ".claude/commands", "format": "markdown", "args": "$ARGUME...
--- +++ @@ -1,3 +1,10 @@+""" +Agent Command Registrar for Spec Kit + +Shared infrastructure for registering commands with AI agents. +Used by both the extension system and the preset system to write +command files into agent-specific directories in the correct format. +""" from pathlib import Path from typing impor...
https://raw.githubusercontent.com/github/spec-kit/HEAD/src/specify_cli/agents.py
Generate descriptive docstrings automatically
import copy import json import hashlib import os import tempfile import zipfile import shutil from dataclasses import dataclass from pathlib import Path from typing import Optional, Dict, List, Any from datetime import datetime, timezone import re import yaml from packaging import version as pkg_version from packagin...
--- +++ @@ -1,3 +1,11 @@+""" +Preset Manager for Spec Kit + +Handles installation, removal, and management of Spec Kit presets. +Presets are self-contained, versioned collections of templates +(artifact, command, and script templates) that can be installed to +customize the Spec-Driven Development workflow. +""" imp...
https://raw.githubusercontent.com/github/spec-kit/HEAD/src/specify_cli/presets.py
Create documentation strings for testing functions
#!/usr/bin/env python3 # /// script # requires-python = ">=3.11" # dependencies = [ # "typer", # "rich", # "platformdirs", # "readchar", # "httpx", # "json5", # ] # /// import os import subprocess import sys import zipfile import tempfile import shutil import shlex import json import json5 impo...
--- +++ @@ -10,6 +10,20 @@ # "json5", # ] # /// +""" +Specify CLI - Setup tool for Specify projects + +Usage: + uvx specify-cli.py init <project-name> + uvx specify-cli.py init . + uvx specify-cli.py init --here + +Or install globally: + uv tool install --from specify-cli.py specify-cli + specify i...
https://raw.githubusercontent.com/github/spec-kit/HEAD/src/specify_cli/__init__.py
Add docstrings that explain logic
#!/usr/bin/python from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import range import struct,sys,os import gd from io import StringIO from random import randint,shuffle from time import time # image width/height (square) N = 32 def insertPa...
--- +++ @@ -1,5 +1,28 @@ #!/usr/bin/python +""" + Bulletproof Jpegs Generator + Copyright (C) 2012 Damien "virtualabs" Cauquil + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation;...
https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/HEAD/Upload Insecure Files/Picture Compression/createBulletproofJPG.py
Improve my code by adding docstrings
from enum import Enum class QueryStatus(Enum): CLAIMED = "Claimed" # Username Detected AVAILABLE = "Available" # Username Not Detected UNKNOWN = "Unknown" # Error Occurred While Trying To Detect Username ILLEGAL = "Illegal" # Username Not Allowable For This Site WAF = "WAF" ...
--- +++ @@ -1,7 +1,15 @@+"""Sherlock Result Module + +This module defines various objects for recording the results of queries. +""" from enum import Enum class QueryStatus(Enum): + """Query Status Enumeration. + + Describes status of query about a given username. + """ CLAIMED = "Claimed" # Use...
https://raw.githubusercontent.com/sherlock-project/sherlock/HEAD/sherlock_project/result.py
Please document this code using docstrings
#! /usr/bin/env python3 import sys try: from sherlock_project.__init__ import import_error_test_var # noqa: F401 except ImportError: print("Did you run Sherlock with `python3 sherlock/sherlock.py ...`?") print("This is an outdated method. Please see https://sherlockproject.xyz/installation for up to date...
--- +++ @@ -1,5 +1,11 @@ #! /usr/bin/env python3 +""" +Sherlock: Find Usernames Across Social Networks Module + +This module contains the main logic to search for usernames at social +networks. +""" import sys @@ -41,12 +47,42 @@ class SherlockFuturesSession(FuturesSession): def request(self, method, url,...
https://raw.githubusercontent.com/sherlock-project/sherlock/HEAD/sherlock_project/sherlock.py
Add clean documentation to messy code
from sherlock_project.result import QueryStatus from colorama import Fore, Style import webbrowser # Global variable to count the number of results. globvar = 0 class QueryNotify: def __init__(self, result=None): self.result = result # return def start(self, message=None): # retu...
--- +++ @@ -1,3 +1,8 @@+"""Sherlock Notify Module + +This module defines the objects for notifying the caller about the +results of queries. +""" from sherlock_project.result import QueryStatus from colorama import Fore, Style import webbrowser @@ -7,34 +12,125 @@ class QueryNotify: + """Query Notify Object. ...
https://raw.githubusercontent.com/sherlock-project/sherlock/HEAD/sherlock_project/notify.py
Write reusable docstrings
from importlib.metadata import version as pkg_version, PackageNotFoundError import pathlib import tomli def get_version() -> str: try: return pkg_version("sherlock_project") except PackageNotFoundError: pyproject_path: pathlib.Path = pathlib.Path(__file__).resolve().parent.parent / "pyproject...
--- +++ @@ -1,3 +1,9 @@+""" Sherlock Module + +This module contains the main logic to search for usernames at social +networks. + +""" from importlib.metadata import version as pkg_version, PackageNotFoundError import pathlib @@ -5,6 +11,7 @@ def get_version() -> str: + """Fetch the version number of the ins...
https://raw.githubusercontent.com/sherlock-project/sherlock/HEAD/sherlock_project/__init__.py
Generate docstrings for exported functions
import json import requests import secrets MANIFEST_URL = "https://raw.githubusercontent.com/sherlock-project/sherlock/master/sherlock_project/resources/data.json" EXCLUSIONS_URL = "https://raw.githubusercontent.com/sherlock-project/sherlock/refs/heads/exclusions/false_positive_exclusions.txt" class SiteInformation:...
--- +++ @@ -1,3 +1,8 @@+"""Sherlock Sites Information Module + +This module supports storing information about websites. +This is the raw data that will be used to search for usernames. +""" import json import requests import secrets @@ -9,6 +14,42 @@ class SiteInformation: def __init__(self, name, url_home, ur...
https://raw.githubusercontent.com/sherlock-project/sherlock/HEAD/sherlock_project/sites.py
Add docstrings to make code maintainable
from __future__ import annotations import collections.abc as c import hashlib import typing as t from collections.abc import MutableMapping from datetime import datetime from datetime import timezone from itsdangerous import BadSignature from itsdangerous import URLSafeTimedSerializer from werkzeug.datastructures imp...
--- +++ @@ -22,9 +22,11 @@ class SessionMixin(MutableMapping[str, t.Any]): + """Expands a basic dictionary with session attributes.""" @property def permanent(self) -> bool: + """This reflects the ``'_permanent'`` key in the dict.""" return self.get("_permanent", False) # type: ignor...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/sessions.py
Document helper functions with docstrings
from __future__ import annotations import os import typing as t from datetime import timedelta from .cli import AppGroup from .globals import current_app from .helpers import send_from_directory from .sansio.blueprints import Blueprint as SansioBlueprint from .sansio.blueprints import BlueprintSetupState as Blueprint...
--- +++ @@ -53,6 +53,22 @@ self.cli.name = self.name def get_send_file_max_age(self, filename: str | None) -> int | None: + """Used by :func:`send_file` to determine the ``max_age`` cache + value for a given file path if it wasn't passed. + + By default, this returns :data:`SEND_FILE...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/blueprints.py
Add concise docstrings to each method
from __future__ import annotations import typing as t from jinja2.loaders import BaseLoader from werkzeug.routing import RequestRedirect from .blueprints import Blueprint from .globals import _cv_app from .sansio.app import App if t.TYPE_CHECKING: from .sansio.scaffold import Scaffold from .wrappers import ...
--- +++ @@ -15,9 +15,15 @@ class UnexpectedUnicodeError(AssertionError, UnicodeError): + """Raised in places where we want some better error reporting for + unexpected unicode or binary data. + """ class DebugFilesKeyError(KeyError, AssertionError): + """Raised from request.files during debugging. ...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/debughelpers.py
Write docstrings that follow conventions
from __future__ import annotations import ast import collections.abc as cabc import importlib.metadata import inspect import os import platform import re import sys import traceback import typing as t from functools import update_wrapper from operator import itemgetter from types import ModuleType import click from c...
--- +++ @@ -35,9 +35,13 @@ class NoAppException(click.UsageError): + """Raised if an application cannot be found or loaded.""" def find_best_app(module: ModuleType) -> Flask: + """Given a module instance this tries to find the best possible + application in the module or raises an exception. + """ ...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/cli.py
Include argument descriptions in docstrings
from __future__ import annotations import importlib.util import os import sys import typing as t from datetime import datetime from functools import cache from functools import update_wrapper from types import TracebackType import werkzeug.utils from werkzeug.exceptions import abort as _wz_abort from werkzeug.utils i...
--- +++ @@ -26,11 +26,20 @@ def get_debug_flag() -> bool: + """Get whether debug mode should be enabled for the app, indicated by the + :envvar:`FLASK_DEBUG` environment variable. The default is ``False``. + """ val = os.environ.get("FLASK_DEBUG") return bool(val and val.lower() not in {"0", "fal...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/helpers.py
Fully document this Python code with docstrings
from __future__ import annotations import typing as t from . import typing as ft from .globals import current_app from .globals import request F = t.TypeVar("F", bound=t.Callable[..., t.Any]) http_method_funcs = frozenset( ["get", "post", "head", "options", "delete", "put", "trace", "patch"] ) class View: ...
--- +++ @@ -14,6 +14,36 @@ class View: + """Subclass this class and override :meth:`dispatch_request` to + create a generic class-based view. Call :meth:`as_view` to create a + view function that creates an instance of the class with the given + arguments and calls its ``dispatch_request`` method with a...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/views.py
Can you add docstrings to this Python file?
from __future__ import annotations import importlib.util import os import pathlib import sys import typing as t from collections import defaultdict from functools import update_wrapper from jinja2 import BaseLoader from jinja2 import FileSystemLoader from werkzeug.exceptions import default_exceptions from werkzeug.ex...
--- +++ @@ -50,6 +50,22 @@ class Scaffold: + """Common behavior shared between :class:`~flask.Flask` and + :class:`~flask.blueprints.Blueprint`. + + :param import_name: The import name of the module where this object + is defined. Usually :attr:`__name__` should be used. + :param static_folder: P...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/sansio/scaffold.py
Help me document legacy Python code
from __future__ import annotations import logging import os import sys import typing as t from datetime import timedelta from itertools import chain from werkzeug.exceptions import Aborter from werkzeug.exceptions import BadRequest from werkzeug.exceptions import BadRequestKeyError from werkzeug.routing import BuildE...
--- +++ @@ -57,6 +57,101 @@ class App(Scaffold): + """The flask object implements a WSGI application and acts as the central + object. It is passed the name of the module or package of the + application. Once it is created it will act as a central registry for + the view functions, the URL rules, temp...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/sansio/app.py
Add docstrings to clarify complex logic
from __future__ import annotations import os import typing as t from collections import defaultdict from functools import update_wrapper from .. import typing as ft from .scaffold import _endpoint_from_view_func from .scaffold import _sentinel from .scaffold import Scaffold from .scaffold import setupmethod if t.TYP...
--- +++ @@ -32,6 +32,11 @@ class BlueprintSetupState: + """Temporary holder object for registering a blueprint with the + application. An instance of this class is created by the + :meth:`~flask.Blueprint.make_setup_state` method and later passed + to all register callback functions. + """ de...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/sansio/blueprints.py
Add docstrings to make code maintainable
from __future__ import annotations import dataclasses import decimal import json import typing as t import uuid import weakref from datetime import date from werkzeug.http import http_date if t.TYPE_CHECKING: # pragma: no cover from werkzeug.sansio.response import Response from ..sansio.app import App cl...
--- +++ @@ -17,20 +17,59 @@ class JSONProvider: + """A standard set of JSON operations for an application. Subclasses + of this can be used to customize JSON behavior or use different + JSON libraries. + + To implement a provider for a specific library, subclass this base + class and implement at lea...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/json/provider.py
Replace inline comments with docstrings
from __future__ import annotations import logging import sys import typing as t from werkzeug.local import LocalProxy from .globals import request if t.TYPE_CHECKING: # pragma: no cover from .sansio.app import App @LocalProxy def wsgi_errors_stream() -> t.TextIO: if request: return request.enviro...
--- +++ @@ -14,6 +14,14 @@ @LocalProxy def wsgi_errors_stream() -> t.TextIO: + """Find the most appropriate error stream for the application. If a request + is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``. + + If you configure your own :class:`logging.StreamHandler`, you may want to + use...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/logging.py
Create Google-style docstrings for my code
from __future__ import annotations import collections.abc as cabc import inspect import os import sys import typing as t import weakref from datetime import timedelta from functools import update_wrapper from inspect import iscoroutinefunction from itertools import chain from types import TracebackType from urllib.par...
--- +++ @@ -107,6 +107,101 @@ class Flask(App): + """The flask object implements a WSGI application and acts as the central + object. It is passed the name of the module or package of the + application. Once it is created it will act as a central registry for + the view functions, the URL rules, templ...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/app.py
Write docstrings for backend logic
from __future__ import annotations import typing as t from base64 import b64decode from base64 import b64encode from datetime import datetime from uuid import UUID from markupsafe import Markup from werkzeug.http import http_date from werkzeug.http import parse_date from ..json import dumps from ..json import loads...
--- +++ @@ -1,3 +1,45 @@+""" +Tagged JSON +~~~~~~~~~~~ + +A compact representation for lossless serialization of non-standard JSON +types. :class:`~flask.sessions.SecureCookieSessionInterface` uses this +to serialize the session data, but it may be useful in other places. It +can be extended to support other types. + +...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/json/tag.py
Add detailed documentation for each class
from __future__ import annotations import contextvars import typing as t from functools import update_wrapper from types import TracebackType from werkzeug.exceptions import HTTPException from werkzeug.routing import MapAdapter from . import typing as ft from .globals import _cv_app from .helpers import _CollectErro...
--- +++ @@ -28,6 +28,24 @@ class _AppCtxGlobals: + """A plain object. Used as a namespace for storing data during an + application context. + + Creating an app context automatically creates this object, which is + made available as the :data:`.g` proxy. + + .. describe:: 'key' in g + + Check w...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/ctx.py
Create docstrings for API functions
from __future__ import annotations import errno import json import os import types import typing as t from werkzeug.utils import import_string if t.TYPE_CHECKING: import typing_extensions as te from .sansio.app import App T = t.TypeVar("T") class ConfigAttribute(t.Generic[T]): def __init__( ...
--- +++ @@ -18,6 +18,7 @@ class ConfigAttribute(t.Generic[T]): + """Makes an attribute forward to the config""" def __init__( self, name: str, get_converter: t.Callable[[t.Any], T] | None = None @@ -47,6 +48,48 @@ class Config(dict): # type: ignore[type-arg] + """Works exactly like a dict...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/config.py
Write docstrings for data processing functions
from __future__ import annotations import typing as t from jinja2 import BaseLoader from jinja2 import Environment as BaseEnvironment from jinja2 import Template from jinja2 import TemplateNotFound from .ctx import AppContext from .globals import app_ctx from .helpers import stream_with_context from .signals import ...
--- +++ @@ -19,6 +19,9 @@ def _default_template_ctx_processor() -> dict[str, t.Any]: + """Default template context processor. Replaces the ``request`` and ``g`` + proxies with their concrete objects for faster access. + """ ctx = app_ctx._get_current_object() rv: dict[str, t.Any] = {"g": ctx.g} ...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/templating.py
Add detailed documentation for each class
from __future__ import annotations import json as _json import typing as t from ..globals import current_app from .provider import _default if t.TYPE_CHECKING: # pragma: no cover from ..wrappers import Response def dumps(obj: t.Any, **kwargs: t.Any) -> str: if current_app: return current_app.json....
--- +++ @@ -11,6 +11,32 @@ def dumps(obj: t.Any, **kwargs: t.Any) -> str: + """Serialize data as JSON. + + If :data:`~flask.current_app` is available, it will use its + :meth:`app.json.dumps() <flask.json.provider.JSONProvider.dumps>` + method, otherwise it will use :func:`json.dumps`. + + :param obj...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/json/__init__.py
Add docstrings with type hints explained
from __future__ import annotations import typing as t from werkzeug.exceptions import BadRequest from werkzeug.exceptions import HTTPException from werkzeug.wrappers import Request as RequestBase from werkzeug.wrappers import Response as ResponseBase from . import json from .globals import current_app from .helpers ...
--- +++ @@ -16,6 +16,17 @@ class Request(RequestBase): + """The request object used by default in Flask. Remembers the + matched endpoint and view arguments. + + It is what ends up as :class:`~flask.request`. If you want to replace + the request object used you can subclass this and set + :attr:`~f...
https://raw.githubusercontent.com/pallets/flask/HEAD/src/flask/wrappers.py
Write docstrings describing functionality
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
--- +++ @@ -63,6 +63,7 @@ system: Optional[str] = None, tools: Optional[str] = None, ) -> tuple[list[int], list[int]]: + r"""Return a single pair of token ids representing prompt and response respectively.""" encoded_messages = self._encode(tokenizer, messages, system, tools) ...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/data/template.py
Write docstrings for this repository
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
--- +++ @@ -37,6 +37,7 @@ @dataclass class RayArguments: + r"""Arguments pertaining to the Ray training.""" ray_num_workers: int = field( default=1, @@ -64,6 +65,7 @@ @dataclass class Fp8Arguments: + r"""Arguments pertaining to the FP8 training.""" fp8: bool = field( default=...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/hparams/training_args.py
Can you add docstrings to this Python file?
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
--- +++ @@ -27,6 +27,7 @@ @dataclass class DatasetProcessor(ABC): + r"""A class for data processors.""" template: "Template" tokenizer: "PreTrainedTokenizer" @@ -35,19 +36,23 @@ @abstractmethod def preprocess_dataset(self, examples: dict[str, list[Any]]) -> dict[str, list[Any]]: + r"...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/data/processor/processor_utils.py
Generate docstrings for each module
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
--- +++ @@ -34,6 +34,7 @@ include_recompute: bool = False, include_flashattn: bool = False, ) -> int: + r"""Calculate the FLOPs of model per forward/backward pass.""" config = AutoConfig.from_pretrained(model_name_or_path) hidden_size = getattr(config, "hidden_size", None) vocab_size = getat...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/scripts/stat_utils/cal_mfu.py
Add docstrings including usage examples
# Copyright 2025 the ROLL team and the LlamaFactory team. # # This code is modified from the ROLL library. # https://github.com/alibaba/ROLL/blob/main/mcore_adapter/tools/convert.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
--- +++ @@ -35,6 +35,15 @@ fp16: bool = False, convert_model_max_length: int | None = None, ): + """Convert megatron checkpoint to HuggingFace format. + + Args: + checkpoint_path: Path to the checkpoint to convert + output_path: Path to save the converted checkpoint + bf16: Use bflo...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/scripts/megatron_merge.py
Add detailed docstrings explaining each function
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
--- +++ @@ -30,10 +30,12 @@ @dataclass class PairwiseDataCollatorWithPadding(MultiModalDataCollatorForSeq2Seq): + r"""Data collator for pairwise data.""" train_on_prompt: bool = False def __call__(self, features: list[dict[str, Any]]) -> dict[str, torch.Tensor]: + r"""Pad batched data to the ...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/scripts/stat_utils/cal_ppl.py
Write docstrings for utility functions
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's Transformers library. # https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/models/llava/modeling_llava.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not u...
--- +++ @@ -62,6 +62,16 @@ language_model_keys: Optional[list[str]] = None, lora_conflict_keys: Optional[list[str]] = None, ): + r"""Register a new composite model. + + Args: + model_type: model type + projector_key: multi_modal_projector + vision_model_keys: vision_tower + l...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/model/model_utils/visual.py
Generate docstrings for exported functions
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
--- +++ @@ -55,6 +55,10 @@ def _get_init_kwargs(model_args: "ModelArguments") -> dict[str, Any]: + r"""Get arguments to load config/tokenizer/model. + + Note: including inplace operation of model_args. + """ skip_check_imports() model_args.model_name_or_path = try_download_model_from_other_hub(mo...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/model/loader.py
Add docstrings that explain logic
# Copyright 2025 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
--- +++ @@ -26,6 +26,7 @@ def find_all_linear_modules(model: "PreTrainedModel", freeze_vision_tower: bool) -> list[str]: + r"""Find all available modules to apply LoRA, GaLore or APOLLO.""" model_type = getattr(model.config, "model_type", None) forbidden_modules = {"lm_head"} if model_type == "cha...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/model/model_utils/misc.py