instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Write docstrings for backend logic
from __future__ import annotations import re from typing import Iterable from ._loop import loop_last from .cells import cell_len, chop_cells re_word = re.compile(r"\s*\S+\s*") def words(text: str) -> Iterable[tuple[int, int, str]]: position = 0 word_match = re_word.match(text, position) while word_mat...
--- +++ @@ -10,6 +10,10 @@ def words(text: str) -> Iterable[tuple[int, int, str]]: + """Yields each word from the text as a tuple + containing (start_index, end_index, word). A "word" in this context may + include the actual word and any whitespace to the right. + """ position = 0 word_match =...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/_wrap.py
Write Python docstrings for this snippet
__all__ = ["decimal"] from typing import Iterable, List, Optional, Tuple def _to_str( size: int, suffixes: Iterable[str], base: int, *, precision: Optional[int] = 1, separator: Optional[str] = " ", ) -> str: if size == 1: return "1 byte" elif size < base: return f"{si...
--- +++ @@ -1,3 +1,14 @@+"""Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2 + +The functions declared in this module should cover the different +use cases needed to generate a string representation of a file size +using several different units. Since there are many standar...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/filesize.py
Create docstrings for all classes and functions
import sys from typing import TYPE_CHECKING, Optional, Union, Literal from .jupyter import JupyterMixin from .segment import Segment from .style import Style from ._emoji_codes import EMOJI from ._emoji_replace import _emoji_replace if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderResult E...
--- +++ @@ -16,6 +16,7 @@ class NoEmoji(Exception): + """No emoji by that name.""" class Emoji(JupyterMixin): @@ -29,6 +30,15 @@ style: Union[str, Style] = "none", variant: Optional[EmojiVariant] = None, ) -> None: + """A single emoji character. + + Args: + nam...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/emoji.py
Generate docstrings for each module
from typing import Literal, Optional, Tuple from ._loop import loop_last from .console import Console, ConsoleOptions, RenderableType, RenderResult from .control import Control from .segment import ControlType, Segment from .style import StyleType from .text import Text VerticalOverflowMethod = Literal["crop", "ellip...
--- +++ @@ -11,6 +11,12 @@ class LiveRender: + """Creates a renderable that may be updated. + + Args: + renderable (RenderableType): Any renderable object. + style (StyleType, optional): An optional style to apply to the renderable. Defaults to "". + """ def __init__( self, @@...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/live_render.py
Include argument descriptions in docstrings
import logging from datetime import datetime from logging import Handler, LogRecord from pathlib import Path from types import ModuleType from typing import ClassVar, Iterable, List, Optional, Type, Union from rich._null_file import NullFile from . import get_console from ._log_render import FormatTimeCallable, LogRe...
--- +++ @@ -16,6 +16,39 @@ class RichHandler(Handler): + """A logging handler that renders output with Rich. The time / level / message and file are displayed in columns. + The level is color coded, and the message is syntax highlighted. + + Note: + Be careful when enabling console markup in log mes...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/logging.py
Add docstrings to clarify complex logic
from typing import TYPE_CHECKING, List, Optional, Union, cast from ._spinners import SPINNERS from .measure import Measurement from .table import Table from .text import Text if TYPE_CHECKING: from .console import Console, ConsoleOptions, RenderableType, RenderResult from .style import StyleType class Spinn...
--- +++ @@ -11,6 +11,17 @@ class Spinner: + """A spinner animation. + + Args: + name (str): Name of spinner (run python -m rich.spinner). + text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to "". + style (StyleType, opt...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/spinner.py
Add detailed docstrings explaining each function
import configparser from typing import IO, Dict, List, Mapping, Optional from .default_styles import DEFAULT_STYLES from .style import Style, StyleType class Theme: styles: Dict[str, Style] def __init__( self, styles: Optional[Mapping[str, StyleType]] = None, inherit: bool = True ): sel...
--- +++ @@ -6,6 +6,12 @@ class Theme: + """A container for style information, used by :class:`~rich.console.Console`. + + Args: + styles (Dict[str, Style], optional): A mapping of style names on to styles. Defaults to None for a theme with no styles. + inherit (bool, optional): Inherit default s...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/theme.py
Write docstrings describing each step
import sys from functools import lru_cache from operator import attrgetter from pickle import dumps, loads from random import randint from typing import Any, Dict, Iterable, List, Optional, Type, Union, cast from . import errors from .color import Color, ColorParseError, ColorSystem, blend_rgb from .repr import Result...
--- +++ @@ -19,6 +19,7 @@ class _Bit: + """A descriptor to get/set a style attribute bit.""" __slots__ = ["bit"] @@ -33,6 +34,31 @@ @rich_repr class Style: + """A terminal style. + + A terminal style consists of a color (`color`), a background color (`bgcolor`), and a number of attributes, such...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/style.py
Document this module using docstrings
import re from functools import partial, reduce from math import gcd from operator import itemgetter from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Pattern, Tuple, Union, ) from ._loop import loop_last from ._pick import pick_b...
--- +++ @@ -45,6 +45,7 @@ class Span(NamedTuple): + """A marked up region in some text.""" start: int """Span start index.""" @@ -60,6 +61,7 @@ return self.end > self.start def split(self, offset: int) -> Tuple["Span", Optional["Span"]]: + """Split a span in to 2 from a given of...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/text.py
Help me write clear docstrings
import inspect import linecache import os import sys from dataclasses import dataclass, field from itertools import islice from traceback import walk_tb from types import ModuleType, TracebackType from typing import ( Any, Callable, Dict, Iterable, List, Optional, Sequence, Set, Tupl...
--- +++ @@ -56,6 +56,15 @@ def _iter_syntax_lines( start: SyntaxPosition, end: SyntaxPosition ) -> Iterable[Tuple[int, int, int]]: + """Yield start and end positions per line. + + Args: + start: Start position. + end: End position. + + Returns: + Iterable of (LINE, COLUMN1, COLUMN2)....
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/traceback.py
Turn comments into proper docstrings
from dataclasses import dataclass, field, replace from typing import ( TYPE_CHECKING, Dict, Iterable, List, NamedTuple, Optional, Sequence, Tuple, Union, ) from . import box, errors from ._loop import loop_first_last, loop_last from ._pick import pick_bool from ._ratio import ratio_...
--- +++ @@ -37,6 +37,34 @@ @dataclass class Column: + """Defines a column within a ~Table. + + Args: + title (Union[str, Text], optional): The title of the table rendered at the top. Defaults to None. + caption (Union[str, Text], optional): The table caption rendered below. Defaults to None. + ...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/table.py
Create docstrings for API functions
from types import TracebackType from typing import Optional, Type from .console import Console, RenderableType from .jupyter import JupyterMixin from .live import Live from .spinner import Spinner from .style import StyleType class Status(JupyterMixin): def __init__( self, status: RenderableType...
--- +++ @@ -9,6 +9,16 @@ class Status(JupyterMixin): + """Displays a status indicator with a 'spinner' animation. + + Args: + status (RenderableType): A status renderable (str or Text typically). + console (Console, optional): Console instance to use, or None for global console. Defaults to None...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/status.py
Add docstrings to improve collaboration
from __future__ import annotations import os.path import re import sys import textwrap from abc import ABC, abstractmethod from pathlib import Path from typing import ( Any, Dict, Iterable, List, NamedTuple, Optional, Sequence, Set, Tuple, Type, Union, ) from pygments.lexer...
--- +++ @@ -122,17 +122,21 @@ class SyntaxTheme(ABC): + """Base class for a syntax theme.""" @abstractmethod def get_style_for_token(self, token_type: TokenType) -> Style: + """Get a style for a given Pygments token.""" raise NotImplementedError # pragma: no cover @abstractmet...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/syntax.py
Generate descriptive docstrings automatically
from typing import Iterator, List, Optional, Tuple from ._loop import loop_first, loop_last from .console import Console, ConsoleOptions, RenderableType, RenderResult from .jupyter import JupyterMixin from .measure import Measurement from .segment import Segment from .style import Style, StyleStack, StyleType from .st...
--- +++ @@ -12,6 +12,20 @@ class Tree(JupyterMixin): + """A renderable for a tree structure. + + Attributes: + ASCII_GUIDES (GuideType): Guide lines used when Console.ascii_only is True. + TREE_GUIDES (List[GuideType, GuideType, GuideType]): Default guide lines. + + Args: + label (Rend...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/tree.py
Help me document legacy Python code
from abc import ABC, abstractmethod from contextlib import asynccontextmanager from typing import List, Optional from pydantic import BaseModel, Field, model_validator from app.llm import LLM from app.logger import logger from app.sandbox.client import SANDBOX_CLIENT from app.schema import ROLE_TYPE, AgentState, Memo...
--- +++ @@ -11,6 +11,11 @@ class BaseAgent(BaseModel, ABC): + """Abstract base class for managing agent state and execution. + + Provides foundational functionality for state transitions, memory management, + and a step-based execution loop. Subclasses must implement the `step` method. + """ # Co...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/agent/base.py
Write docstrings that follow conventions
from abc import ABC, abstractmethod from itertools import islice from operator import itemgetter from threading import RLock from typing import ( TYPE_CHECKING, Dict, Iterable, List, NamedTuple, Optional, Sequence, Tuple, Union, ) from ._ratio import ratio_resolve from .align import...
--- +++ @@ -30,6 +30,7 @@ class LayoutRender(NamedTuple): + """An individual layout render.""" region: Region render: List[List[Segment]] @@ -40,12 +41,15 @@ class LayoutError(Exception): + """Layout related error.""" class NoSplitter(LayoutError): + """Requested splitter does not exis...
https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/layout.py
Include argument descriptions in docstrings
import time from daytona import ( CreateSandboxFromImageParams, Daytona, DaytonaConfig, Resources, Sandbox, SandboxState, SessionExecuteRequest, ) from app.config import config from app.utils.logger import logger # load_dotenv() daytona_settings = config.daytona logger.info("Initializing...
--- +++ @@ -43,6 +43,7 @@ async def get_or_start_sandbox(sandbox_id: str): + """Retrieve a sandbox by ID, check its state, and start it if needed.""" logger.info(f"Getting or starting sandbox with ID: {sandbox_id}") @@ -77,6 +78,7 @@ def start_supervisord_session(sandbox: Sandbox): + """Start sup...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/daytona/sandbox.py
Generate descriptive docstrings automatically
from abc import ABC, abstractmethod from typing import Optional from pydantic import Field from app.agent.base import BaseAgent from app.llm import LLM from app.schema import AgentState, Memory class ReActAgent(BaseAgent, ABC): name: str description: Optional[str] = None system_prompt: Optional[str] = ...
--- +++ @@ -24,12 +24,15 @@ @abstractmethod async def think(self) -> bool: + """Process current state and decide next action""" @abstractmethod async def act(self) -> str: + """Execute decided actions""" async def step(self) -> str: + """Execute a single step: think an...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/agent/react.py
Can you add docstrings to this Python file?
import json import threading import tomllib from pathlib import Path from typing import Dict, List, Optional from pydantic import BaseModel, Field def get_project_root() -> Path: return Path(__file__).resolve().parent.parent PROJECT_ROOT = get_project_root() WORKSPACE_ROOT = PROJECT_ROOT / "workspace" class ...
--- +++ @@ -8,6 +8,7 @@ def get_project_root() -> Path: + """Get the project root directory""" return Path(__file__).resolve().parent.parent @@ -91,6 +92,7 @@ class SandboxSettings(BaseModel): + """Configuration for the execution sandbox""" use_sandbox: bool = Field(False, description="Whe...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/config.py
Document helper functions with docstrings
from typing import Any, Dict, List, Optional, Tuple from pydantic import Field from app.agent.toolcall import ToolCallAgent from app.logger import logger from app.prompt.mcp import MULTIMEDIA_RESPONSE_PROMPT, NEXT_STEP_PROMPT, SYSTEM_PROMPT from app.schema import AgentState, Message from app.tool.base import ToolResu...
--- +++ @@ -11,6 +11,11 @@ class MCPAgent(ToolCallAgent): + """Agent for interacting with MCP (Model Context Protocol) servers. + + This agent connects to an MCP server using either SSE or stdio transport + and makes the server's tools available through the agent's tool interface. + """ name: str...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/agent/mcp.py
Create documentation strings for testing functions
class ToolError(Exception): def __init__(self, message): self.message = message class OpenManusError(Exception): class TokenLimitExceeded(OpenManusError):
--- +++ @@ -1,10 +1,13 @@ class ToolError(Exception): + """Raised when a tool encounters an error.""" def __init__(self, message): self.message = message class OpenManusError(Exception): + """Base exception for all OpenManus errors""" -class TokenLimitExceeded(OpenManusError):+class Token...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/exceptions.py
Help me add docstrings to my project
from typing import Dict, List, Optional from pydantic import Field, model_validator from app.agent.browser import BrowserContextHelper from app.agent.toolcall import ToolCallAgent from app.config import config from app.daytona.sandbox import create_sandbox, delete_sandbox from app.daytona.tool_base import SandboxTool...
--- +++ @@ -19,6 +19,7 @@ class SandboxManus(ToolCallAgent): + """A versatile general-purpose agent with support for both local and MCP tools.""" name: str = "SandboxManus" description: str = "A versatile agent that can solve various tasks using multiple sandbox-tools including MCP-based tools" @@ -5...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/agent/sandbox_agent.py
Write docstrings describing functionality
import json from typing import TYPE_CHECKING, Optional from pydantic import Field, model_validator from app.agent.toolcall import ToolCallAgent from app.logger import logger from app.prompt.browser import NEXT_STEP_PROMPT, SYSTEM_PROMPT from app.schema import Message, ToolChoice from app.tool import BrowserUseTool, T...
--- +++ @@ -45,6 +45,7 @@ return None async def format_next_step_prompt(self) -> str: + """Gets browser state and formats the browser prompt.""" browser_state = await self.get_browser_state() url_info, tabs_info, content_above_info, content_below_info = "", "", "", "" ...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/agent/browser.py
Document functions with clear intent
import asyncio import json from typing import Any, List, Optional, Union from pydantic import Field from app.agent.react import ReActAgent from app.exceptions import TokenLimitExceeded from app.logger import logger from app.prompt.toolcall import NEXT_STEP_PROMPT, SYSTEM_PROMPT from app.schema import TOOL_CHOICE_TYPE...
--- +++ @@ -16,6 +16,7 @@ class ToolCallAgent(ReActAgent): + """Base agent class for handling tool/function calls with enhanced abstraction""" name: str = "toolcall" description: str = "an agent that can execute tool calls." @@ -36,6 +37,7 @@ max_observe: Optional[Union[int, bool]] = None ...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/agent/toolcall.py
Add minimal docstrings for each function
from dataclasses import dataclass, field from datetime import datetime from typing import Any, ClassVar, Dict, Optional from daytona import Daytona, DaytonaConfig, Sandbox, SandboxState from pydantic import Field from app.config import config from app.daytona.sandbox import create_sandbox, start_supervisord_session f...
--- +++ @@ -24,6 +24,9 @@ @dataclass class ThreadMessage: + """ + Represents a message to be added to a thread. + """ type: str content: Dict[str, Any] @@ -34,6 +37,7 @@ ) def to_dict(self) -> Dict[str, Any]: + """Convert the message to a dictionary for API calls""" re...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/daytona/tool_base.py
Add docstrings that explain logic
from typing import Dict, List, Optional from pydantic import Field, model_validator from app.agent.browser import BrowserContextHelper from app.agent.toolcall import ToolCallAgent from app.config import config from app.logger import logger from app.prompt.manus import NEXT_STEP_PROMPT, SYSTEM_PROMPT from app.tool imp...
--- +++ @@ -16,6 +16,7 @@ class Manus(ToolCallAgent): + """A versatile general-purpose agent with support for both local and MCP tools.""" name: str = "Manus" description: str = "A versatile agent that can solve various tasks using multiple tools including MCP-based tools" @@ -51,17 +52,20 @@ @...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/agent/manus.py
Write docstrings for data processing functions
import asyncio import base64 import json from typing import Generic, Optional, TypeVar from browser_use import Browser as BrowserUseBrowser from browser_use import BrowserConfig from browser_use.browser.context import BrowserContext, BrowserContextConfig from browser_use.dom.service import DomService from pydantic imp...
--- +++ @@ -139,6 +139,7 @@ return v async def _ensure_browser_initialized(self) -> BrowserContext: + """Ensure browser and context are initialized.""" if self.browser is None: browser_config_kwargs = {"headless": False, "disable_security": True} @@ -200,6 +201,25 @@ ...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/browser_use_tool.py
Add structured docstrings to improve clarity
import asyncio import os from typing import Optional from app.exceptions import ToolError from app.tool.base import BaseTool, CLIResult _BASH_DESCRIPTION = """Execute a bash command in the terminal. * Long running commands: For commands that may run indefinitely, it should be run in the background and the output sho...
--- +++ @@ -14,6 +14,7 @@ class _BashSession: + """A session of a bash shell.""" _started: bool _process: asyncio.subprocess.Process @@ -44,6 +45,7 @@ self._started = True def stop(self): + """Terminate the bash shell.""" if not self._started: raise ToolErr...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/bash.py
Generate missing documentation strings
from abc import ABC, abstractmethod from typing import Dict, List, Optional, Union from pydantic import BaseModel from app.agent.base import BaseAgent class BaseFlow(BaseModel, ABC): agents: Dict[str, BaseAgent] tools: Optional[List] = None primary_agent_key: Optional[str] = None class Config: ...
--- +++ @@ -7,6 +7,7 @@ class BaseFlow(BaseModel, ABC): + """Base class for execution flows supporting multiple agents""" agents: Dict[str, BaseAgent] tools: Optional[List] = None @@ -40,13 +41,17 @@ @property def primary_agent(self) -> Optional[BaseAgent]: + """Get the primary agen...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/flow/base.py
Add docstrings for production code
import json from abc import ABC, abstractmethod from typing import Any, Dict, Optional, Union from pydantic import BaseModel, Field from app.utils.logger import logger # class BaseTool(ABC, BaseModel): # name: str # description: str # parameters: Optional[dict] = None # class Config: # arbi...
--- +++ @@ -36,6 +36,7 @@ class ToolResult(BaseModel): + """Represents the result of a tool execution.""" output: Any = Field(default=None) error: Optional[str] = Field(default=None) @@ -69,11 +70,26 @@ return f"Error: {self.error}" if self.error else self.output def replace(self, **kw...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/base.py
Generate docstrings for script automation
import math from typing import Dict, List, Optional, Union import tiktoken from openai import ( APIError, AsyncAzureOpenAI, AsyncOpenAI, AuthenticationError, OpenAIError, RateLimitError, ) from openai.types.chat import ChatCompletion, ChatCompletionMessage from tenacity import ( retry, ...
--- +++ @@ -58,9 +58,20 @@ self.tokenizer = tokenizer def count_text(self, text: str) -> int: + """Calculate tokens for a text string""" return 0 if not text else len(self.tokenizer.encode(text)) def count_image(self, image_item: dict) -> int: + """ + Calculate tokens...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/llm.py
Add detailed documentation for each class
import json import time from enum import Enum from typing import Dict, List, Optional, Union from pydantic import Field from app.agent.base import BaseAgent from app.flow.base import BaseFlow from app.llm import LLM from app.logger import logger from app.schema import AgentState, Message, ToolChoice from app.tool imp...
--- +++ @@ -14,6 +14,7 @@ class PlanStepStatus(str, Enum): + """Enum class defining possible statuses of a plan step""" NOT_STARTED = "not_started" IN_PROGRESS = "in_progress" @@ -22,14 +23,17 @@ @classmethod def get_all_statuses(cls) -> list[str]: + """Return a list of all possible...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/flow/planning.py
Replace inline comments with docstrings
import asyncio from typing import List, Union from urllib.parse import urlparse from app.logger import logger from app.tool.base import BaseTool, ToolResult class Crawl4aiTool(BaseTool): name: str = "crawl4ai" description: str = """Web crawler that extracts clean, AI-ready content from web pages. Feat...
--- +++ @@ -1,3 +1,9 @@+""" +Crawl4AI Web Crawler Tool for OpenManus + +This tool integrates Crawl4AI, a high-performance web crawler designed for LLMs and AI agents, +providing fast, precise, and AI-ready data extraction with clean Markdown generation. +""" import asyncio from typing import List, Union @@ -8,6 +14...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/crawl4ai.py
Provide docstrings following PEP 257
import asyncio from pathlib import Path from typing import Optional, Protocol, Tuple, Union, runtime_checkable from app.config import SandboxSettings from app.exceptions import ToolError from app.sandbox.client import SANDBOX_CLIENT PathLike = Union[str, Path] @runtime_checkable class FileOperator(Protocol): ...
--- +++ @@ -1,3 +1,4 @@+"""File operation interfaces and implementations for local and sandbox environments.""" import asyncio from pathlib import Path @@ -13,50 +14,62 @@ @runtime_checkable class FileOperator(Protocol): + """Interface for file operations in different environments.""" async def read_fi...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/file_operators.py
Improve documentation using docstrings
import asyncio import base64 import logging import os import time from typing import Dict, Literal, Optional import aiohttp from pydantic import Field from app.daytona.tool_base import Sandbox, SandboxToolsBase from app.tool.base import ToolResult KEYBOARD_KEYS = [ "a", "b", "c", "d", "e", "...
--- +++ @@ -100,6 +100,7 @@ class ComputerUseTool(SandboxToolsBase): + """Computer automation tool for controlling the desktop environment.""" name: str = "computer_use" description: str = _COMPUTER_USE_DESCRIPTION @@ -181,6 +182,7 @@ api_base_url: Optional[str] = Field(default=None, exclude=True...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/computer_use_tool.py
Help me write clear docstrings
from contextlib import AsyncExitStack from typing import Dict, List, Optional from mcp import ClientSession, StdioServerParameters from mcp.client.sse import sse_client from mcp.client.stdio import stdio_client from mcp.types import ListToolsResult, TextContent from app.logger import logger from app.tool.base import ...
--- +++ @@ -12,12 +12,14 @@ class MCPClientTool(BaseTool): + """Represents a tool proxy that can be called on the MCP server from the client side.""" session: Optional[ClientSession] = None server_id: str = "" # Add server identifier original_name: str = "" async def execute(self, **kwar...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/mcp.py
Add docstrings that explain purpose and usage
import base64 import mimetypes import os from io import BytesIO from typing import Optional from PIL import Image from pydantic import Field from app.daytona.tool_base import Sandbox, SandboxToolsBase, ThreadMessage from app.tool.base import ToolResult # 最大文件大小(原图10MB,压缩后5MB) MAX_IMAGE_SIZE = 10 * 1024 * 1024 MAX_C...
--- +++ @@ -59,11 +59,13 @@ def __init__( self, sandbox: Optional[Sandbox] = None, thread_id: Optional[str] = None, **data ): + """Initialize with optional sandbox and thread_id.""" super().__init__(**data) if sandbox is not None: self._sandbox = sandbox de...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/sandbox/sb_vision_tool.py
Add docstrings that explain inputs and outputs
from typing import Any, List, Optional, Type, Union, get_args, get_origin from pydantic import BaseModel, Field from app.tool import BaseTool class CreateChatCompletion(BaseTool): name: str = "create_chat_completion" description: str = ( "Creates a structured completion with specified output formatt...
--- +++ @@ -24,11 +24,13 @@ required: List[str] = Field(default_factory=lambda: ["response"]) def __init__(self, response_type: Optional[Type] = str): + """Initialize with a specific response type.""" super().__init__() self.response_type = response_type self.parameters = se...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/create_chat_completion.py
Generate docstrings for exported functions
import logging import sys logging.basicConfig(level=logging.INFO, handlers=[logging.StreamHandler(sys.stderr)]) import argparse import asyncio import atexit import json from inspect import Parameter, Signature from typing import Any, Dict, Optional from mcp.server.fastmcp import FastMCP from app.logger import logg...
--- +++ @@ -22,6 +22,7 @@ class MCPServer: + """MCP Server implementation with tool registration and management.""" def __init__(self, name: str = "openmanus"): self.server = FastMCP(name) @@ -34,6 +35,7 @@ self.tools["terminate"] = Terminate() def register_tool(self, tool: BaseToo...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/mcp/server.py
Document helper functions with docstrings
import asyncio import time from typing import Any, Dict, Optional, TypeVar from uuid import uuid4 from app.daytona.tool_base import Sandbox, SandboxToolsBase from app.tool.base import ToolResult from app.utils.logger import logger Context = TypeVar("Context") _SHELL_DESCRIPTION = """\ Execute a shell command in the ...
--- +++ @@ -19,6 +19,9 @@ class SandboxShellTool(SandboxToolsBase): + """Tool for executing tasks in a Daytona sandbox with browser-use capabilities. + Uses sessions for maintaining state between commands and provides comprehensive process management. + """ name: str = "sandbox_shell" descripti...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/sandbox/sb_shell_tool.py
Create docstrings for all classes and functions
from typing import List, Optional, Tuple import requests from bs4 import BeautifulSoup from app.logger import logger from app.tool.search.base import SearchItem, WebSearchEngine ABSTRACT_MAX_LENGTH = 300 USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68...
--- +++ @@ -39,11 +39,22 @@ session: Optional[requests.Session] = None def __init__(self, **data): + """Initialize the BingSearch tool with a requests session.""" super().__init__(**data) self.session = requests.Session() self.session.headers.update(HEADERS) def _sear...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/search/bing_search.py
Add well-formatted docstrings
from typing import Any, Dict, List from app.exceptions import ToolError from app.logger import logger from app.tool.base import BaseTool, ToolFailure, ToolResult class ToolCollection: class Config: arbitrary_types_allowed = True def __init__(self, *tools: BaseTool): self.tools = tools ...
--- +++ @@ -1,3 +1,4 @@+"""Collection classes for managing multiple tools.""" from typing import Any, Dict, List from app.exceptions import ToolError @@ -6,6 +7,7 @@ class ToolCollection: + """A collection of defined tools.""" class Config: arbitrary_types_allowed = True @@ -33,6 +35,7 @@ ...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/tool_collection.py
Add minimal docstrings for each function
import asyncio import uuid from contextlib import asynccontextmanager from typing import Dict, Optional, Set import docker from docker.errors import APIError, ImageNotFound from app.config import SandboxSettings from app.logger import logger from app.sandbox.core.sandbox import DockerSandbox class SandboxManager: ...
--- +++ @@ -12,6 +12,19 @@ class SandboxManager: + """Docker sandbox manager. + + Manages multiple DockerSandbox instances lifecycle including creation, + monitoring, and cleanup. Provides concurrent access control and automatic + cleanup mechanisms for sandbox resources. + + Attributes: + max...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/sandbox/core/manager.py
Document all public functions with docstrings
class SandboxError(Exception): class SandboxTimeoutError(SandboxError): class SandboxResourceError(SandboxError):
--- +++ @@ -1,9 +1,17 @@+"""Exception classes for the sandbox system. + +This module defines custom exceptions used throughout the sandbox system to +handle various error conditions in a structured way. +""" class SandboxError(Exception): + """Base exception for sandbox-related errors.""" class SandboxTime...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/sandbox/core/exceptions.py
Add docstrings including usage examples
import asyncio import io import os import tarfile import tempfile import uuid from typing import Dict, Optional import docker from docker.errors import NotFound from docker.models.containers import Container from app.config import SandboxSettings from app.sandbox.core.exceptions import SandboxTimeoutError from app.sa...
--- +++ @@ -16,12 +16,30 @@ class DockerSandbox: + """Docker sandbox environment. + + Provides a containerized execution environment with resource limits, + file operations, and command execution capabilities. + + Attributes: + config: Sandbox configuration. + volume_bindings: Volume mappi...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/sandbox/core/sandbox.py
Help me comply with documentation standards
import os # Files to exclude from operations EXCLUDED_FILES = { ".DS_Store", ".gitignore", "package-lock.json", "postcss.config.js", "postcss.config.mjs", "jsconfig.json", "components.json", "tsconfig.tsbuildinfo", "tsconfig.json", } # Directories to exclude from operations EXCLUD...
--- +++ @@ -34,6 +34,14 @@ def should_exclude_file(rel_path: str) -> bool: + """Check if a file should be excluded based on path, name, or extension + + Args: + rel_path: Relative path of the file to check + + Returns: + True if the file should be excluded, False otherwise + """ # Che...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/utils/files_utils.py
Help me comply with documentation standards
from abc import ABC, abstractmethod from typing import Dict, Optional, Protocol from app.config import SandboxSettings from app.sandbox.core.sandbox import DockerSandbox class SandboxFileOperations(Protocol): async def copy_from(self, container_path: str, local_path: str) -> None: ... async def cop...
--- +++ @@ -6,21 +6,49 @@ class SandboxFileOperations(Protocol): + """Protocol for sandbox file operations.""" async def copy_from(self, container_path: str, local_path: str) -> None: + """Copies file from container to local. + + Args: + container_path: File path in container. + ...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/sandbox/client.py
Document this code for team use
import asyncio from typing import Any, Dict, List, Optional import requests from bs4 import BeautifulSoup from pydantic import BaseModel, ConfigDict, Field, model_validator from tenacity import retry, stop_after_attempt, wait_exponential from app.config import config from app.logger import logger from app.tool.base i...
--- +++ @@ -20,6 +20,7 @@ class SearchResult(BaseModel): + """Represents a single search result returned by a search engine.""" model_config = ConfigDict(arbitrary_types_allowed=True) @@ -35,10 +36,12 @@ ) def __str__(self) -> str: + """String representation of a search result.""" ...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/web_search.py
Help me write clear docstrings
from collections import defaultdict from pathlib import Path from typing import Any, DefaultDict, List, Literal, Optional, get_args from app.config import config from app.exceptions import ToolError from app.tool import BaseTool from app.tool.base import CLIResult, ToolResult from app.tool.file_operators import ( ...
--- +++ @@ -1,3 +1,4 @@+"""File and directory manipulation tool with sandbox support.""" from collections import defaultdict from pathlib import Path @@ -50,12 +51,14 @@ def maybe_truncate( content: str, truncate_after: Optional[int] = MAX_RESPONSE_LEN ) -> str: + """Truncate content and append a notice if...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/str_replace_editor.py
Write docstrings for utility functions
from typing import Any, AsyncIterable, ClassVar, Dict, List, Literal from pydantic import BaseModel from app.agent.manus import Manus class ResponseFormat(BaseModel): status: Literal["input_required", "completed", "error"] = "input_required" message: str class A2AManus(Manus): async def invoke(self, ...
--- +++ @@ -6,6 +6,7 @@ class ResponseFormat(BaseModel): + """Respond to the user in this format.""" status: Literal["input_required", "completed", "error"] = "input_required" message: str @@ -18,6 +19,7 @@ return self.get_agent_response(config, response) async def stream(self, query: ...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/protocol/a2a/app/agent.py
Turn comments into proper docstrings
# tool/planning.py from typing import Dict, List, Literal, Optional from app.exceptions import ToolError from app.tool.base import BaseTool, ToolResult _PLANNING_TOOL_DESCRIPTION = """ A planning tool that allows the agent to create and manage plans for solving complex tasks. The tool provides functionality for crea...
--- +++ @@ -12,6 +12,10 @@ class PlanningTool(BaseTool): + """ + A planning tool that allows the agent to create and manage plans for solving complex tasks. + The tool provides functionality for creating plans, updating plan steps, and tracking progress. + """ name: str = "planning" descript...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/planning.py
Write docstrings that follow conventions
import asyncio import re import socket from typing import Dict, Optional, Tuple, Union import docker from docker import APIClient from docker.errors import APIError from docker.models.containers import Container class DockerSession: def __init__(self, container_id: str) -> None: self.api = APIClient() ...
--- +++ @@ -1,3 +1,9 @@+""" +Asynchronous Docker Terminal + +This module provides asynchronous terminal functionality for Docker containers, +allowing interactive command execution with timeout control. +""" import asyncio import re @@ -12,12 +18,26 @@ class DockerSession: def __init__(self, container_id: st...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/sandbox/core/terminal.py
Document this code for team use
#!/usr/bin/env python import argparse import asyncio import sys from app.agent.mcp import MCPAgent from app.config import config from app.logger import logger class MCPRunner: def __init__(self): self.root_path = config.root_path self.server_reference = config.mcp_config.server_reference ...
--- +++ @@ -9,6 +9,7 @@ class MCPRunner: + """Runner class for MCP Agent with proper path handling and configuration.""" def __init__(self): self.root_path = config.root_path @@ -20,6 +21,7 @@ connection_type: str, server_url: str | None = None, ) -> None: + """Initia...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/run_mcp.py
Add docstrings to my Python code
import asyncio from typing import Optional, TypeVar from pydantic import Field from app.daytona.tool_base import Sandbox, SandboxToolsBase from app.tool.base import ToolResult from app.utils.files_utils import clean_path, should_exclude_file from app.utils.logger import logger Context = TypeVar("Context") _FILES_D...
--- +++ @@ -78,17 +78,21 @@ def __init__( self, sandbox: Optional[Sandbox] = None, thread_id: Optional[str] = None, **data ): + """Initialize with optional sandbox and thread_id.""" super().__init__(**data) if sandbox is not None: self._sandbox = sandbox de...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/sandbox/sb_files_tool.py
Add verbose docstrings with examples
import multiprocessing import sys from io import StringIO from typing import Dict from app.tool.base import BaseTool class PythonExecute(BaseTool): name: str = "python_execute" description: str = "Executes Python code string. Note: Only print outputs are visible, function return values are not captured. Use...
--- +++ @@ -7,6 +7,7 @@ class PythonExecute(BaseTool): + """A tool for executing Python code with timeout and safety restrictions.""" name: str = "python_execute" description: str = "Executes Python code string. Note: Only print outputs are visible, function return values are not captured. Use print ...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/python_execute.py
Create docstrings for API functions
from enum import Enum from typing import Any, List, Literal, Optional, Union from pydantic import BaseModel, Field class Role(str, Enum): SYSTEM = "system" USER = "user" ASSISTANT = "assistant" TOOL = "tool" ROLE_VALUES = tuple(role.value for role in Role) ROLE_TYPE = Literal[ROLE_VALUES] # type:...
--- +++ @@ -5,6 +5,7 @@ class Role(str, Enum): + """Message role options""" SYSTEM = "system" USER = "user" @@ -17,6 +18,7 @@ class ToolChoice(str, Enum): + """Tool choice options""" NONE = "none" AUTO = "auto" @@ -28,6 +30,7 @@ class AgentState(str, Enum): + """Agent execut...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/schema.py
Generate missing documentation strings
import base64 import io import json import traceback from typing import Optional # Add this import for Optional from PIL import Image from pydantic import Field from app.daytona.tool_base import ( # Ensure Sandbox is imported correctly Sandbox, SandboxToolsBase, ThreadMessage, ) from app.tool.base impor...
--- +++ @@ -34,6 +34,7 @@ # noinspection PyArgumentList class SandboxBrowserTool(SandboxToolsBase): + """Tool for executing tasks in a Daytona sandbox with browser-use capabilities.""" name: str = "sandbox_browser" description: str = _BROWSER_DESCRIPTION @@ -129,6 +130,7 @@ def __init__( ...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/sandbox/sb_browser_tool.py
Add docstrings for production code
from typing import List, Optional from pydantic import BaseModel, Field class SearchItem(BaseModel): title: str = Field(description="The title of the search result") url: str = Field(description="The URL of the search result") description: Optional[str] = Field( default=None, description="A desc...
--- +++ @@ -4,6 +4,7 @@ class SearchItem(BaseModel): + """Represents a single search result item""" title: str = Field(description="The title of the search result") url: str = Field(description="The URL of the search result") @@ -12,14 +13,28 @@ ) def __str__(self) -> str: + """Stri...
https://raw.githubusercontent.com/FoundationAgents/OpenManus/HEAD/app/tool/search/base.py
Fill in missing docstrings in my code
import os import shutil import sys import webbrowser from collections.abc import Callable from platform import system from rich import box from rich.console import Console from rich.panel import Panel from rich.prompt import Prompt from rich.table import Table from rich.text import Text from rich.theme import Theme fr...
--- +++ @@ -42,6 +42,7 @@ def validate_input(ip, val_range: list) -> int | None: + """Return the integer if it is in val_range, else None.""" if not val_range: return None try: @@ -54,6 +55,7 @@ def _show_inline_help(): + """Quick help available from any menu level.""" console.prin...
https://raw.githubusercontent.com/Z4nzu/hackingtool/HEAD/core.py
Document this module using docstrings
#!/usr/bin/env python3 import os import sys import shutil import subprocess from pathlib import Path # ── Python version check (must be before any other local import) ────────────── if sys.version_info < (3, 10): print( f"[ERROR] Python 3.10 or newer is required.\n" f"You are running Python {sys.ve...
--- +++ @@ -50,6 +50,7 @@ # ── OS compatibility check ───────────────────────────────────────────────────── def check_os_compatibility(): + """Print detected OS info and exit on unsupported systems.""" info = CURRENT_OS console.print( f"[dim]Detected: OS={info.system} | distro={info.distro_id o...
https://raw.githubusercontent.com/Z4nzu/hackingtool/HEAD/install.py
Create structured documentation for my script
#!/usr/bin/env python3 import sys # ── Python version guard (must be before any other local import) ─────────────── if sys.version_info < (3, 10): print( f"[ERROR] Python 3.10 or newer is required.\n" f"You are running Python {sys.version_info.major}.{sys.version_info.minor}.\n" f"Upgrade w...
--- +++ @@ -178,6 +178,7 @@ def _sys_info() -> dict: + """Collect live system info for the header panel.""" info: dict = {} # OS pretty name @@ -327,6 +328,7 @@ # ── Search ───────────────────────────────────────────────────────────────────── def _collect_all_tools() -> list[tuple]: + """Walk a...
https://raw.githubusercontent.com/Z4nzu/hackingtool/HEAD/hackingtool.py
Add missing documentation to my Python functions
import json import logging from pathlib import Path from typing import Any from constants import USER_CONFIG_FILE, USER_TOOLS_DIR, DEFAULT_CONFIG logger = logging.getLogger(__name__) def load() -> dict[str, Any]: if USER_CONFIG_FILE.exists(): try: on_disk = json.loads(USER_CONFIG_FILE.read_t...
--- +++ @@ -9,6 +9,7 @@ def load() -> dict[str, Any]: + """Load config from disk, merging with defaults for any missing keys.""" if USER_CONFIG_FILE.exists(): try: on_disk = json.loads(USER_CONFIG_FILE.read_text()) @@ -19,11 +20,17 @@ def save(cfg: dict[str, Any]) -> None: + """...
https://raw.githubusercontent.com/Z4nzu/hackingtool/HEAD/config.py
Add docstrings to my Python code
import platform import shutil from dataclasses import dataclass, field from pathlib import Path @dataclass class OSInfo: system: str # "linux", "macos", "windows", "unknown" distro_id: str = "" # "kali", "ubuntu", "arch", "fedora", etc. distro_like: str = "" # "debia...
--- +++ @@ -18,6 +18,10 @@ def detect() -> OSInfo: + """ + Fully detect the current OS, distro, and available package manager. + Never asks the user — entirely automatic. + """ import os system_raw = platform.system() @@ -104,6 +108,7 @@ def install_packages(packages: list[str], os_info:...
https://raw.githubusercontent.com/Z4nzu/hackingtool/HEAD/os_detect.py
Generate docstrings with examples
import black from gpt_engineer.core.files_dict import FilesDict class Linting: def __init__(self): # Dictionary to hold linting methods for different file types self.linters = {".py": self.lint_python} import black def lint_python(self, content, config): try: # Try t...
--- +++ @@ -11,6 +11,10 @@ import black def lint_python(self, content, config): + """Lint Python files using the `black` library, handling all exceptions silently and logging them. + This function attempts to format the code and returns the formatted code if successful. + If any error oc...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/linting.py
Add docstrings to incomplete code
from gpt_engineer.benchmark.bench_config import BenchConfig from gpt_engineer.benchmark.benchmarks.apps.load import load_apps from gpt_engineer.benchmark.benchmarks.gptme.load import load_gptme from gpt_engineer.benchmark.benchmarks.mbpp.load import load_mbpp from gpt_engineer.benchmark.types import Benchmark BENCHMAR...
--- +++ @@ -1,3 +1,14 @@+""" +Module for loading benchmarks. + +This module provides a central point to access different benchmarks by name. +It maps benchmark names to their respective loading functions. + +Functions +--------- +get_benchmark : function + Retrieves a Benchmark object by name. Raises ValueError if t...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/benchmark/benchmarks/load.py
Add docstrings for utility scripts
import logging from collections import Counter from typing import List RETAIN = "retain" ADD = "add" REMOVE = "remove" class Hunk: def __init__( self, start_line_pre_edit, hunk_len_pre_edit, start_line_post_edit, hunk_len_post_edit, lines, ) -> None: ...
--- +++ @@ -1,3 +1,36 @@+""" +File Overview: + +This Python module is designed for processing and analyzing diffs in source code files. Diffs represent the changes between two versions of a file, which are crucial in version control systems for tracking file modifications. The module focuses on the detailed examination...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/diff.py
Write docstrings for backend logic
# list all folders in benchmark folder # for each folder, run the benchmark import contextlib import json import os import subprocess from datetime import datetime from itertools import islice from pathlib import Path from typing import Iterable, Union from tabulate import tabulate from typer import run def main( ...
--- +++ @@ -1,3 +1,7 @@+""" +This module provides functionality to run benchmarks on different folders within +the 'benchmark' directory, wait for their completion, and generate a report. +""" # list all folders in benchmark folder # for each folder, run the benchmark @@ -18,6 +22,15 @@ def main( n_benchmarks:...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/scripts/legacy_benchmark.py
Can you add docstrings to this Python file?
from __future__ import annotations import json import logging import os from pathlib import Path from typing import Any, List, Optional, Union import backoff import openai import pyperclip from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from langchain.chat_models.base import BaseCha...
--- +++ @@ -1,3 +1,17 @@+""" +AI Module + +This module provides an AI class that interfaces with language models to perform various tasks such as +starting a conversation, advancing the conversation, and handling message serialization. It also includes +backoff strategies for handling rate limit errors from the OpenAI ...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/ai.py
Create docstrings for API functions
import importlib import os.path import sys from typing import Annotated, Optional import typer from langchain.globals import set_llm_cache from langchain_community.cache import SQLiteCache from gpt_engineer.applications.cli.main import load_env_if_needed from gpt_engineer.benchmark.bench_config import BenchConfig f...
--- +++ @@ -1,3 +1,24 @@+""" +Main entry point for the benchmarking tool. + +This module provides a command-line interface for running benchmarks using Typer. +It allows users to specify the path to an agent, the benchmark(s) to run, and other +options such as verbosity. + +Functions +--------- +get_agent : function + ...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/benchmark/__main__.py
Add docstrings for internal functions
import json import random import tempfile from dataclasses import dataclass, field from datetime import datetime from pathlib import Path from typing import Optional, Tuple from dataclasses_json import dataclass_json from termcolor import colored from gpt_engineer.core.default.disk_memory import DiskMemory from gpt...
--- +++ @@ -1,3 +1,31 @@+""" +The `learning` module is designed to facilitate the collection and storage of user feedback on the outputs generated by the GPT Engineer tool. It provides mechanisms for obtaining user consent, capturing user reviews, and storing this information for future analysis and enhancement of the ...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/applications/cli/learning.py
Expand my code with proper documentation strings
from pathlib import Path from subprocess import TimeoutExpired from typing import Union from datasets import Dataset, DatasetDict, load_dataset, load_from_disk from gpt_engineer.benchmark.bench_config import MbppConfig from gpt_engineer.benchmark.benchmarks.mbpp.problem import Problem from gpt_engineer.benchmark.type...
--- +++ @@ -1,3 +1,15 @@+""" +Module for loading MBPP evaluation tasks. + +This module provides functionality to load tasks for evaluating GPT-based models +on smaller, more focused tasks. It defines a set of tasks with predefined prompts +and assertions to benchmark the performance of AI models. + +Functions +--------...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/benchmark/benchmarks/mbpp/load.py
Add minimal docstrings for each function
import logging import re from typing import Dict, Tuple from regex import regex from gpt_engineer.core.diff import ADD, REMOVE, RETAIN, Diff, Hunk from gpt_engineer.core.files_dict import FilesDict, file_to_lines_dict # Initialize a logger for this module logger = logging.getLogger(__name__) def chat_to_files_di...
--- +++ @@ -1,3 +1,25 @@+""" +This Python script provides functionalities for parsing chat transcripts that contain file paths and code blocks, +applying diffs to these files, and parsing unified git diff format strings. The script is designed to work within +a larger system that involves processing and manipulating co...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/chat_to_files.py
Generate docstrings for this script
from platform import platform from sys import version_info from typing import List, Union from langchain.schema import AIMessage, HumanMessage, SystemMessage from gpt_engineer.core.ai import AI from gpt_engineer.core.base_execution_env import BaseExecutionEnv from gpt_engineer.core.base_memory import BaseMemory from ...
--- +++ @@ -20,6 +20,16 @@ def get_platform_info() -> str: + """ + Returns a string containing the OS and Python version information. + + This function is used for self-healing by providing information about the current + operating system and Python version. It assumes that the Python version in the + ...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/tools/custom_steps.py
Add docstrings to incomplete code
from gpt_engineer.benchmark.bench_config import GptmeConfig from gpt_engineer.benchmark.types import Benchmark, Task from gpt_engineer.core.files_dict import FilesDict from gpt_engineer.core.prompt import Prompt def load_gptme(config: GptmeConfig) -> Benchmark: return Benchmark( name="gptme", task...
--- +++ @@ -1,3 +1,15 @@+""" +Module for loading GPT-Me evaluation tasks. + +This module provides functionality to load tasks for evaluating GPT-based models +on smaller, more focused tasks. It defines a set of tasks with predefined prompts +and assertions to benchmark the performance of AI models. + +Functions +------...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/benchmark/benchmarks/gptme/load.py
Add docstrings that explain logic
from typing import Tuple from gpt_engineer.applications.cli.learning import ( Learning, Review, extract_learning, human_review_input, ) from gpt_engineer.core.default.disk_memory import DiskMemory from gpt_engineer.core.prompt import Prompt def send_learning(learning: Learning): import ruddersta...
--- +++ @@ -1,3 +1,26 @@+""" +Module `collect` - Data Handling and RudderStack Integration + +This module provides functionalities to handle and send learning data to RudderStack +for the purpose of analysis and to improve the gpt-engineer system. The data is sent +only when the user gives consent to share. + +Function...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/applications/cli/collect.py
Add docstrings to incomplete code
from pathlib import Path from subprocess import TimeoutExpired from typing import Union from datasets import Dataset, DatasetDict, load_dataset, load_from_disk from gpt_engineer.benchmark.bench_config import AppsConfig from gpt_engineer.benchmark.benchmarks.apps.problem import Problem from gpt_engineer.benchmark.type...
--- +++ @@ -1,3 +1,15 @@+""" +Module for loading APPS evaluation tasks. + +This module provides functionality to load tasks for evaluating GPT-based models +on smaller, more focused tasks. It defines a set of tasks with predefined prompts +and assertions to benchmark the performance of AI models. + +Functions +--------...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/benchmark/benchmarks/apps/load.py
Create structured documentation for my script
from typing import Callable, Optional, TypeVar # from gpt_engineer.core.default.git_version_manager import GitVersionManager from gpt_engineer.core.ai import AI from gpt_engineer.core.base_agent import BaseAgent from gpt_engineer.core.base_execution_env import BaseExecutionEnv from gpt_engineer.core.base_memory impor...
--- +++ @@ -1,3 +1,8 @@+""" +This module provides the CliAgent class which manages the lifecycle of code generation and improvement +using an AI model. It includes functionalities to initialize code generation, improve existing code, +and process the code through various steps defined in the step bundle. +""" from t...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/applications/cli/cli_agent.py
Generate consistent docstrings
import tempfile from typing import Optional from gpt_engineer.core.ai import AI from gpt_engineer.core.base_agent import BaseAgent from gpt_engineer.core.base_execution_env import BaseExecutionEnv from gpt_engineer.core.base_memory import BaseMemory from gpt_engineer.core.default.disk_execution_env import DiskExecut...
--- +++ @@ -1,3 +1,11 @@+""" +Module for defining a simple agent that uses AI to manage code generation and improvement. + +This module provides a class that represents an agent capable of initializing and improving +a codebase using AI. It handles interactions with the AI model, memory, and execution +environment to g...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/default/simple_agent.py
Add clean documentation to messy code
from collections import OrderedDict from pathlib import Path from typing import Union # class Code(MutableMapping[str | Path, str]): # ToDo: implement as mutable mapping, potentially holding a dict instead of being a dict. class FilesDict(dict): def __setitem__(self, key: Union[str, Path], value: str): i...
--- +++ @@ -1,3 +1,14 @@+""" +FilesDict Module + +This module provides a FilesDict class which is a dictionary-based container for managing code files. +It extends the standard dictionary to enforce string keys and values, representing filenames and their +corresponding code content. It also provides methods to format ...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/files_dict.py
Add docstrings for utility scripts
import difflib import json import logging import os import platform import subprocess import sys from pathlib import Path import openai import typer from dotenv import load_dotenv from langchain.globals import set_llm_cache from langchain_community.cache import SQLiteCache from termcolor import colored from gpt_en...
--- +++ @@ -1,3 +1,29 @@+""" +Entrypoint for the CLI tool. + +This module serves as the entry point for a command-line interface (CLI) tool. +It is designed to interact with OpenAI's language models. +The module provides functionality to: +- Load necessary environment variables, +- Configure various parameters for the ...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/applications/cli/main.py
Write docstrings including parameters and return values
import fnmatch import os import subprocess from pathlib import Path from typing import Any, Dict, Generator, List, Union import toml from gpt_engineer.core.default.disk_memory import DiskMemory from gpt_engineer.core.default.paths import metadata_path from gpt_engineer.core.files_dict import FilesDict from gpt_engi...
--- +++ @@ -1,3 +1,21 @@+""" +file_selector.py + +This module offers interactive file selection for projects. Leveraging a terminal-based, +tree-structured display, users can navigate and select files for editing or processing. +It integrates with system editors for direct file modification and supports saving +selecti...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/applications/cli/file_selector.py
Generate docstrings for exported functions
from abc import ABC, abstractmethod from gpt_engineer.core.files_dict import FilesDict from gpt_engineer.core.prompt import Prompt class BaseAgent(ABC): @abstractmethod def init(self, prompt: Prompt) -> FilesDict: pass @abstractmethod def improve(self, files_dict: FilesDict, prompt: Prompt)...
--- +++ @@ -1,3 +1,13 @@+""" +Base Agent Module + +This module provides an abstract base class for an agent that interacts with code. It defines the interface +for agents capable of initializing and improving code based on a given prompt. Implementations of this class +are expected to provide concrete methods for these...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/base_agent.py
Replace inline comments with docstrings
import base64 import json import shutil from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterator, Optional, Union from gpt_engineer.core.base_memory import BaseMemory from gpt_engineer.tools.supported_languages import SUPPORTED_LANGUAGES # This class represents a simple databas...
--- +++ @@ -1,3 +1,24 @@+""" +Disk Memory Module +================== + +This module provides a simple file-based key-value database system, where keys are +represented as filenames and values are the contents of these files. The `DiskMemory` class +is responsible for the CRUD operations on the database. + +Attributes +...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/default/disk_memory.py
Create documentation strings for testing functions
import subprocess import time from pathlib import Path from typing import Optional, Tuple, Union from gpt_engineer.core.base_execution_env import BaseExecutionEnv from gpt_engineer.core.default.file_store import FileStore from gpt_engineer.core.files_dict import FilesDict class DiskExecutionEnv(BaseExecutionEnv): ...
--- +++ @@ -1,3 +1,26 @@+""" +Module for managing the execution environment on the local disk. + +This module provides a class that handles the execution of code stored on the local +file system. It includes methods for uploading files to the execution environment, +running commands, and capturing the output. + +Classe...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/default/disk_execution_env.py
Add docstrings to make code maintainable
# list all folders in benchmark folder # for each folder, run the benchmark import os import shutil from pathlib import Path from typer import run def main(): benchmarks = Path("benchmark") for benchmark in benchmarks.iterdir(): if benchmark.is_dir(): print(f"Cleaning {benchmark}") ...
--- +++ @@ -1,3 +1,7 @@+""" +This module provides functionality to clean up benchmark directories by removing +all files and folders except for 'prompt' and 'main_prompt'. +""" # list all folders in benchmark folder # for each folder, run the benchmark @@ -11,6 +15,11 @@ def main(): + """ + Main function ...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/scripts/clean_benchmarks.py
Fill in missing docstrings in my code
import time from typing import List import yaml from gpt_engineer.benchmark.types import Assertable, Benchmark, TaskResult from gpt_engineer.core.base_agent import BaseAgent from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv def run( agent: BaseAgent, benchmark: Benchmark, verbos...
--- +++ @@ -1,3 +1,17 @@+""" +Module for running benchmarks. + +This module defines functions to run benchmarks using a given agent and to print +the results of the benchmark tasks. + +Functions +--------- +run : function + Runs the benchmark tasks using the provided agent and returns a list of TaskResult objects. +...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/benchmark/run.py
Add detailed documentation for each class
import json import typer from termcolor import colored app = typer.Typer() def pretty_print_conversation(messages): role_to_color = { "system": "red", "user": "green", "assistant": "blue", "function": "magenta", } formatted_messages = [] for message in messages: ...
--- +++ @@ -1,3 +1,7 @@+""" +This module provides functionality to print a conversation with messages +colored according to the role of the speaker. +""" import json @@ -9,6 +13,15 @@ def pretty_print_conversation(messages): + """ + Prints a conversation with messages formatted and colored by role. + + ...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/scripts/print_chat.py
Write docstrings describing functionality
import os from pathlib import Path META_DATA_REL_PATH = ".gpteng" MEMORY_REL_PATH = os.path.join(META_DATA_REL_PATH, "memory") CODE_GEN_LOG_FILE = "all_output.txt" IMPROVE_LOG_FILE = "improve.txt" DIFF_LOG_FILE = "diff_errors.txt" DEBUG_LOG_FILE = "debug_log_file.txt" ENTRYPOINT_FILE = "run.sh" ENTRYPOINT_LOG_FILE = ...
--- +++ @@ -1,3 +1,41 @@+""" +Module defining file system paths used by the application. + +This module contains definitions of file system paths that are used throughout the +application to locate and manage various files and directories, such as logs, memory, +and preprompts. + +Constants +--------- +META_DATA_REL_PA...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/default/paths.py
Generate docstrings for each module
import base64 import io import logging import math from dataclasses import dataclass from typing import List, Union import tiktoken from langchain.schema import AIMessage, HumanMessage, SystemMessage from PIL import Image # workaround for function moved in: # https://github.com/langchain-ai/langchain/blob/535db7260...
--- +++ @@ -30,6 +30,26 @@ @dataclass class TokenUsage: + """ + Dataclass representing token usage statistics for a conversation step. + + Attributes + ---------- + step_name : str + The name of the conversation step. + in_step_prompt_tokens : int + The number of prompt tokens used in...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/token_usage.py
Write docstrings for algorithm functions
import inspect import io import re import sys import traceback from pathlib import Path from typing import List, MutableMapping, Union from langchain.schema import HumanMessage, SystemMessage from termcolor import colored from gpt_engineer.core.ai import AI from gpt_engineer.core.base_execution_env import BaseExecu...
--- +++ @@ -1,3 +1,34 @@+""" +Module for defining the steps involved in generating and improving code using AI. + +This module provides functions that represent different steps in the process of generating +and improving code using an AI model. These steps include generating code from a prompt, +creating an entrypoint ...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/default/steps.py
Create docstrings for reusable components
from abc import ABC, abstractmethod from subprocess import Popen from typing import Optional, Tuple from gpt_engineer.core.files_dict import FilesDict class BaseExecutionEnv(ABC): @abstractmethod def run(self, command: str, timeout: Optional[int] = None) -> Tuple[str, str, int]: raise NotImplemented...
--- +++ @@ -6,19 +6,37 @@ class BaseExecutionEnv(ABC): + """ + Abstract base class for an execution environment capable of running code. + + This class defines the interface for execution environments that can execute commands, + handle processes, and manage file uploads and downloads. + """ @...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/base_execution_env.py
Create docstrings for all classes and functions
from dataclasses import asdict, dataclass, field from pathlib import Path import tomlkit default_config_filename = "gpt-engineer.toml" example_config = """ [run] build = "npm run build" test = "npm run test" lint = "quick-lint-js" [paths] base = "./frontend" # base directory to operate in (for monorepos) src = "./...
--- +++ @@ -1,3 +1,8 @@+""" +Functions for reading and writing the `gpt-engineer.toml` configuration file. + +The `gpt-engineer.toml` file is a TOML file that contains project-specific configuration used by the GPT Engineer CLI and gptengineer.app. +""" from dataclasses import asdict, dataclass, field from pathlib im...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/project_config.py
Generate documentation strings for clarity
from dataclasses import dataclass from subprocess import Popen from typing import Callable, Dict, Optional from gpt_engineer.core.base_execution_env import BaseExecutionEnv from gpt_engineer.core.files_dict import FilesDict from gpt_engineer.core.prompt import Prompt @dataclass class Assertable: files: FilesDic...
--- +++ @@ -1,3 +1,25 @@+""" +Module defining types used in benchmarking. + +This module contains dataclass definitions for various types used throughout the +benchmarking process, such as Assertable, Task, Benchmark, and TaskResult. + +Classes: + Assertable: + Represents an object that can be asserted agains...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/benchmark/types.py
Write Python docstrings for this snippet
from abc import ABC, abstractmethod from pathlib import Path from typing import Union from gpt_engineer.core.files_dict import FilesDict class BaseVersionManager(ABC): @abstractmethod def __init__(self, path: Union[str, Path]): pass @abstractmethod def snapshot(self, files_dict: FilesDict) ...
--- +++ @@ -1,3 +1,10 @@+""" +Version Manager Module + +This module provides an abstract base class for a version manager that handles the creation of snapshots +for code. Implementations of this class are expected to provide methods to create a snapshot of the given +code and return a reference to it. +""" from abc i...
https://raw.githubusercontent.com/AntonOsika/gpt-engineer/HEAD/gpt_engineer/core/version_manager.py
Generate consistent documentation across files
import math import inspect from dataclasses import dataclass import torch import torch.nn as nn from torch.nn import functional as F class LayerNorm(nn.Module): def __init__(self, ndim, bias): super().__init__() self.weight = nn.Parameter(torch.ones(ndim)) self.bias = nn.Parameter(torch....
--- +++ @@ -1,3 +1,11 @@+""" +Full definition of a GPT Language Model, all of it in this single file. +References: +1) the official GPT-2 TensorFlow implementation released by OpenAI: +https://github.com/openai/gpt-2/blob/master/src/model.py +2) huggingface/transformers PyTorch implementation: +https://github.com/huggi...
https://raw.githubusercontent.com/karpathy/nanoGPT/HEAD/model.py
Fill in missing docstrings in my code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import math import os import random from collections.abc import Iterator from pathlib import Path from typing import Any from urllib.parse import urlsplit import numpy as np import torch import torch.distributed as...
--- +++ @@ -35,8 +35,31 @@ class InfiniteDataLoader(dataloader.DataLoader): + """DataLoader that reuses workers for infinite iteration. + + This dataloader extends the PyTorch DataLoader to provide infinite recycling of workers, which improves efficiency + for training loops that need to iterate through th...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/data/build.py
Document this code for team use
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import platform import re import threading from pathlib import Path from typing import Any, Callable import cv2 import numpy as np import torch from ultralytics.cfg import get_cfg, get_save_dir from ultralytics.da...
--- +++ @@ -1,4 +1,37 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Run prediction on images, videos, directories, globs, YouTube, webcam, streams, etc. + +Usage - sources: + $ yolo mode=predict model=yolo26n.pt source=0 # webcam + ...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/engine/predictor.py
Write beginner-friendly docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import shutil import threading import time from http import HTTPStatus from pathlib import Path from typing import Any from urllib.parse import parse_qs, urlparse from ultralytics import __version__ from ultralytic...
--- +++ @@ -19,8 +19,42 @@ class HUBTrainingSession: + """HUB training session for Ultralytics HUB YOLO models. + + This class encapsulates the functionality for interacting with Ultralytics HUB during model training, including + model creation, metrics tracking, and checkpoint uploading. + + Attributes...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/hub/session.py
Generate consistent documentation across files
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations from pathlib import Path from ultralytics.engine.model import Model from ultralytics.utils.torch_utils import model_info from .predict import Predictor, SAM2Predictor, SAM3Predictor class SAM(Model): def __...
--- +++ @@ -1,4 +1,18 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +SAM model interface. + +This module provides an interface to the Segment Anything Model (SAM) from Ultralytics, designed for real-time image +segmentation tasks. The SAM model allows for promptable segmentation with unpar...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/ultralytics/models/sam/model.py
Fill in missing docstrings in my code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from __future__ import annotations import os import re import shutil import subprocess import sys import tempfile import time from pathlib import Path import yaml from bs4 import BeautifulSoup from minijinja import Environment, load_from_path try: ...
--- +++ @@ -1,4 +1,24 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Automates building and post-processing of MkDocs documentation, especially for multilingual projects. + +This script streamlines generating localized documentation and updating HTML links for correct formatting. + +Key Fe...
https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/docs/build_docs.py