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_match is not None:
start, end = word_match.span()
word = word_match.group(0)
yield start, end, word
word_match = re_word.match(text, end)
def divide_line(text: str, width: int, fold: bool = True) -> list[int]:
break_positions: list[int] = [] # offsets to insert the breaks at
append = break_positions.append
cell_offset = 0
_cell_len = cell_len
for start, _end, word in words(text):
word_length = _cell_len(word.rstrip())
remaining_space = width - cell_offset
word_fits_remaining_space = remaining_space >= word_length
if word_fits_remaining_space:
# Simplest case - the word fits within the remaining width for this line.
cell_offset += _cell_len(word)
else:
# Not enough space remaining for this word on the current line.
if word_length > width:
# The word doesn't fit on any line, so we can't simply
# place it on the next line...
if fold:
# Fold the word across multiple lines.
folded_word = chop_cells(word, width=width)
for last, line in loop_last(folded_word):
if start:
append(start)
if last:
cell_offset = _cell_len(line)
else:
start += len(line)
else:
# Folding isn't allowed, so crop the word.
if start:
append(start)
cell_offset = _cell_len(word)
elif cell_offset and start:
# The word doesn't fit within the remaining space on the current
# line, but it *can* fit on to the next (empty) line.
append(start)
cell_offset = _cell_len(word)
return break_positions
if __name__ == "__main__": # pragma: no cover
from .console import Console
console = Console(width=10)
console.print("12345 abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ 12345")
print(chop_cells("abcdefghijklmnopqrstuvwxyz", 10))
console = Console(width=20)
console.rule()
console.print("TextualはPythonの高速アプリケーション開発フレームワークです")
console.rule()
console.print("アプリケーションは1670万色を使用でき") | --- +++ @@ -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 = re_word.match(text, position)
while word_match is not None:
@@ -20,6 +24,18 @@
def divide_line(text: str, width: int, fold: bool = True) -> list[int]:
+ """Given a string of text, and a width (measured in cells), return a list
+ of cell offsets which the string should be split at in order for it to fit
+ within the given width.
+
+ Args:
+ text: The text to examine.
+ width: The available cell width.
+ fold: If True, words longer than `width` will be folded onto a new line.
+
+ Returns:
+ A list of indices to break the line at.
+ """
break_positions: list[int] = [] # offsets to insert the breaks at
append = break_positions.append
cell_offset = 0
@@ -74,4 +90,4 @@ console.print("TextualはPythonの高速アプリケーション開発フレームワークです")
console.rule()
- console.print("アプリケーションは1670万色を使用でき")+ console.print("アプリケーションは1670万色を使用でき")
| 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"{size:,} bytes"
for i, suffix in enumerate(suffixes, 2): # noqa: B007
unit = base**i
if size < unit:
break
return "{:,.{precision}f}{separator}{}".format(
(base * size / unit),
suffix,
precision=precision,
separator=separator,
)
def pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]:
for i, suffix in enumerate(suffixes):
unit = base**i
if size < unit * base:
break
return unit, suffix
def decimal(
size: int,
*,
precision: Optional[int] = 1,
separator: Optional[str] = " ",
) -> str:
return _to_str(
size,
("kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"),
1000,
precision=precision,
separator=separator,
) | --- +++ @@ -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 standards regarding
+file size units, three different functions have been implemented.
+
+See Also:
+ * `Wikipedia: Binary prefix <https://en.wikipedia.org/wiki/Binary_prefix>`_
+
+"""
__all__ = ["decimal"]
@@ -30,6 +41,7 @@
def pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]:
+ """Pick a suffix and base for the given size."""
for i, suffix in enumerate(suffixes):
unit = base**i
if size < unit * base:
@@ -43,10 +55,34 @@ precision: Optional[int] = 1,
separator: Optional[str] = " ",
) -> str:
+ """Convert a filesize in to a string (powers of 1000, SI prefixes).
+
+ In this convention, ``1000 B = 1 kB``.
+
+ This is typically the format used to advertise the storage
+ capacity of USB flash drives and the like (*256 MB* meaning
+ actually a storage capacity of more than *256 000 000 B*),
+ or used by **Mac OS X** since v10.6 to report file sizes.
+
+ Arguments:
+ int (size): A file size.
+ int (precision): The number of decimal places to include (default = 1).
+ str (separator): The string to separate the value from the units (default = " ").
+
+ Returns:
+ `str`: A string containing a abbreviated file size and units.
+
+ Example:
+ >>> filesize.decimal(30000)
+ '30.0 kB'
+ >>> filesize.decimal(30000, precision=2, separator="")
+ '30.00kB'
+
+ """
return _to_str(
size,
("kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"),
1000,
precision=precision,
separator=separator,
- )+ )
| 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
EmojiVariant = Literal["emoji", "text"]
class NoEmoji(Exception):
class Emoji(JupyterMixin):
__slots__ = ["name", "style", "_char", "variant"]
VARIANTS = {"text": "\uFE0E", "emoji": "\uFE0F"}
def __init__(
self,
name: str,
style: Union[str, Style] = "none",
variant: Optional[EmojiVariant] = None,
) -> None:
self.name = name
self.style = style
self.variant = variant
try:
self._char = EMOJI[name]
except KeyError:
raise NoEmoji(f"No emoji called {name!r}")
if variant is not None:
self._char += self.VARIANTS.get(variant, "")
@classmethod
def replace(cls, text: str) -> str:
return _emoji_replace(text)
def __repr__(self) -> str:
return f"<emoji {self.name!r}>"
def __str__(self) -> str:
return self._char
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> "RenderResult":
yield Segment(self._char, console.get_style(self.style))
if __name__ == "__main__": # pragma: no cover
import sys
from rich.columns import Columns
from rich.console import Console
console = Console(record=True)
columns = Columns(
(f":{name}: {name}" for name in sorted(EMOJI.keys()) if "\u200D" not in name),
column_first=True,
)
console.print(columns)
if len(sys.argv) > 1:
console.save_html(sys.argv[1]) | --- +++ @@ -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:
+ name (str): Name of emoji.
+ style (Union[str, Style], optional): Optional style. Defaults to None.
+
+ Raises:
+ NoEmoji: If the emoji doesn't exist.
+ """
self.name = name
self.style = style
self.variant = variant
@@ -41,6 +51,14 @@
@classmethod
def replace(cls, text: str) -> str:
+ """Replace emoji markup with corresponding unicode characters.
+
+ Args:
+ text (str): A string with emojis codes, e.g. "Hello :smiley:!"
+
+ Returns:
+ str: A string with emoji codes replaces with actual emoji.
+ """
return _emoji_replace(text)
def __repr__(self) -> str:
@@ -70,4 +88,4 @@
console.print(columns)
if len(sys.argv) > 1:
- console.save_html(sys.argv[1])+ console.save_html(sys.argv[1])
| 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", "ellipsis", "visible"]
class LiveRender:
def __init__(
self,
renderable: RenderableType,
style: StyleType = "",
vertical_overflow: VerticalOverflowMethod = "ellipsis",
) -> None:
self.renderable = renderable
self.style = style
self.vertical_overflow = vertical_overflow
self._shape: Optional[Tuple[int, int]] = None
@property
def last_render_height(self) -> int:
if self._shape is None:
return 0
return self._shape[1]
def set_renderable(self, renderable: RenderableType) -> None:
self.renderable = renderable
def position_cursor(self) -> Control:
if self._shape is not None:
_, height = self._shape
return Control(
ControlType.CARRIAGE_RETURN,
(ControlType.ERASE_IN_LINE, 2),
*(
(
(ControlType.CURSOR_UP, 1),
(ControlType.ERASE_IN_LINE, 2),
)
* (height - 1)
)
)
return Control()
def restore_cursor(self) -> Control:
if self._shape is not None:
_, height = self._shape
return Control(
ControlType.CARRIAGE_RETURN,
*((ControlType.CURSOR_UP, 1), (ControlType.ERASE_IN_LINE, 2)) * height
)
return Control()
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
renderable = self.renderable
style = console.get_style(self.style)
lines = console.render_lines(renderable, options, style=style, pad=False)
shape = Segment.get_shape(lines)
_, height = shape
if height > options.size.height:
if self.vertical_overflow == "crop":
lines = lines[: options.size.height]
shape = Segment.get_shape(lines)
elif self.vertical_overflow == "ellipsis":
lines = lines[: (options.size.height - 1)]
overflow_text = Text(
"...",
overflow="crop",
justify="center",
end="",
style="live.ellipsis",
)
lines.append(list(console.render(overflow_text)))
shape = Segment.get_shape(lines)
self._shape = shape
new_line = Segment.line()
for last, line in loop_last(lines):
yield from line
if not last:
yield new_line | --- +++ @@ -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,
@@ -25,14 +31,29 @@
@property
def last_render_height(self) -> int:
+ """The number of lines in the last render (may be 0 if nothing was rendered).
+
+ Returns:
+ Height in lines
+ """
if self._shape is None:
return 0
return self._shape[1]
def set_renderable(self, renderable: RenderableType) -> None:
+ """Set a new renderable.
+
+ Args:
+ renderable (RenderableType): Any renderable object, including str.
+ """
self.renderable = renderable
def position_cursor(self) -> Control:
+ """Get control codes to move cursor to beginning of live render.
+
+ Returns:
+ Control: A control instance that may be printed.
+ """
if self._shape is not None:
_, height = self._shape
return Control(
@@ -49,6 +70,11 @@ return Control()
def restore_cursor(self) -> Control:
+ """Get control codes to clear the render and restore the cursor to its previous position.
+
+ Returns:
+ Control: A Control instance that may be printed.
+ """
if self._shape is not None:
_, height = self._shape
return Control(
@@ -87,4 +113,4 @@ for last, line in loop_last(lines):
yield from line
if not last:
- yield new_line+ yield new_line
| 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, LogRender
from .console import Console, ConsoleRenderable
from .highlighter import Highlighter, ReprHighlighter
from .text import Text
from .traceback import Traceback
class RichHandler(Handler):
KEYWORDS: ClassVar[Optional[List[str]]] = [
"GET",
"POST",
"HEAD",
"PUT",
"DELETE",
"OPTIONS",
"TRACE",
"PATCH",
]
HIGHLIGHTER_CLASS: ClassVar[Type[Highlighter]] = ReprHighlighter
def __init__(
self,
level: Union[int, str] = logging.NOTSET,
console: Optional[Console] = None,
*,
show_time: bool = True,
omit_repeated_times: bool = True,
show_level: bool = True,
show_path: bool = True,
enable_link_path: bool = True,
highlighter: Optional[Highlighter] = None,
markup: bool = False,
rich_tracebacks: bool = False,
tracebacks_width: Optional[int] = None,
tracebacks_code_width: Optional[int] = 88,
tracebacks_extra_lines: int = 3,
tracebacks_theme: Optional[str] = None,
tracebacks_word_wrap: bool = True,
tracebacks_show_locals: bool = False,
tracebacks_suppress: Iterable[Union[str, ModuleType]] = (),
tracebacks_max_frames: int = 100,
locals_max_length: int = 10,
locals_max_string: int = 80,
log_time_format: Union[str, FormatTimeCallable] = "[%x %X]",
keywords: Optional[List[str]] = None,
) -> None:
super().__init__(level=level)
self.console = console or get_console()
self.highlighter = highlighter or self.HIGHLIGHTER_CLASS()
self._log_render = LogRender(
show_time=show_time,
show_level=show_level,
show_path=show_path,
time_format=log_time_format,
omit_repeated_times=omit_repeated_times,
level_width=None,
)
self.enable_link_path = enable_link_path
self.markup = markup
self.rich_tracebacks = rich_tracebacks
self.tracebacks_width = tracebacks_width
self.tracebacks_extra_lines = tracebacks_extra_lines
self.tracebacks_theme = tracebacks_theme
self.tracebacks_word_wrap = tracebacks_word_wrap
self.tracebacks_show_locals = tracebacks_show_locals
self.tracebacks_suppress = tracebacks_suppress
self.tracebacks_max_frames = tracebacks_max_frames
self.tracebacks_code_width = tracebacks_code_width
self.locals_max_length = locals_max_length
self.locals_max_string = locals_max_string
self.keywords = keywords
def get_level_text(self, record: LogRecord) -> Text:
level_name = record.levelname
level_text = Text.styled(
level_name.ljust(8), f"logging.level.{level_name.lower()}"
)
return level_text
def emit(self, record: LogRecord) -> None:
message = self.format(record)
traceback = None
if (
self.rich_tracebacks
and record.exc_info
and record.exc_info != (None, None, None)
):
exc_type, exc_value, exc_traceback = record.exc_info
assert exc_type is not None
assert exc_value is not None
traceback = Traceback.from_exception(
exc_type,
exc_value,
exc_traceback,
width=self.tracebacks_width,
code_width=self.tracebacks_code_width,
extra_lines=self.tracebacks_extra_lines,
theme=self.tracebacks_theme,
word_wrap=self.tracebacks_word_wrap,
show_locals=self.tracebacks_show_locals,
locals_max_length=self.locals_max_length,
locals_max_string=self.locals_max_string,
suppress=self.tracebacks_suppress,
max_frames=self.tracebacks_max_frames,
)
message = record.getMessage()
if self.formatter:
record.message = record.getMessage()
formatter = self.formatter
if hasattr(formatter, "usesTime") and formatter.usesTime():
record.asctime = formatter.formatTime(record, formatter.datefmt)
message = formatter.formatMessage(record)
message_renderable = self.render_message(record, message)
log_renderable = self.render(
record=record, traceback=traceback, message_renderable=message_renderable
)
if isinstance(self.console.file, NullFile):
# Handles pythonw, where stdout/stderr are null, and we return NullFile
# instance from Console.file. In this case, we still want to make a log record
# even though we won't be writing anything to a file.
self.handleError(record)
else:
try:
self.console.print(log_renderable)
except Exception:
self.handleError(record)
def render_message(self, record: LogRecord, message: str) -> "ConsoleRenderable":
use_markup = getattr(record, "markup", self.markup)
message_text = Text.from_markup(message) if use_markup else Text(message)
highlighter = getattr(record, "highlighter", self.highlighter)
if highlighter:
message_text = highlighter(message_text)
if self.keywords is None:
self.keywords = self.KEYWORDS
if self.keywords:
message_text.highlight_words(self.keywords, "logging.keyword")
return message_text
def render(
self,
*,
record: LogRecord,
traceback: Optional[Traceback],
message_renderable: "ConsoleRenderable",
) -> "ConsoleRenderable":
path = Path(record.pathname).name
level = self.get_level_text(record)
time_format = None if self.formatter is None else self.formatter.datefmt
log_time = datetime.fromtimestamp(record.created)
log_renderable = self._log_render(
self.console,
[message_renderable] if not traceback else [message_renderable, traceback],
log_time=log_time,
time_format=time_format,
level=level,
path=path,
line_no=record.lineno,
link_path=record.pathname if self.enable_link_path else None,
)
return log_renderable
if __name__ == "__main__": # pragma: no cover
from time import sleep
FORMAT = "%(message)s"
# FORMAT = "%(asctime)-15s - %(levelname)s - %(message)s"
logging.basicConfig(
level="NOTSET",
format=FORMAT,
datefmt="[%X]",
handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)],
)
log = logging.getLogger("rich")
log.info("Server starting...")
log.info("Listening on http://127.0.0.1:8080")
sleep(1)
log.info("GET /index.html 200 1298")
log.info("GET /imgs/backgrounds/back1.jpg 200 54386")
log.info("GET /css/styles.css 200 54386")
log.warning("GET /favicon.ico 404 242")
sleep(1)
log.debug(
"JSONRPC request\n--> %r\n<-- %r",
{
"version": "1.1",
"method": "confirmFruitPurchase",
"params": [["apple", "orange", "mangoes", "pomelo"], 1.123],
"id": "194521489",
},
{"version": "1.1", "result": True, "error": None, "id": "194521489"},
)
log.debug(
"Loading configuration file /adasd/asdasd/qeqwe/qwrqwrqwr/sdgsdgsdg/werwerwer/dfgerert/ertertert/ertetert/werwerwer"
)
log.error("Unable to find 'pomelo' in database!")
log.info("POST /jsonrpc/ 200 65532")
log.info("POST /admin/ 401 42234")
log.warning("password was rejected for admin site.")
def divide() -> None:
number = 1
divisor = 0
foos = ["foo"] * 100
log.debug("in divide")
try:
number / divisor
except:
log.exception("An error of some kind occurred!")
divide()
sleep(1)
log.critical("Out of memory!")
log.info("Server exited with code=-1")
log.info("[bold]EXITING...[/bold]", extra=dict(markup=True)) | --- +++ @@ -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 messages if you have configured logging for libraries not
+ under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.
+
+ Args:
+ level (Union[int, str], optional): Log level. Defaults to logging.NOTSET.
+ console (:class:`~rich.console.Console`, optional): Optional console instance to write logs.
+ Default will use a global console instance writing to stdout.
+ show_time (bool, optional): Show a column for the time. Defaults to True.
+ omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True.
+ show_level (bool, optional): Show a column for the level. Defaults to True.
+ show_path (bool, optional): Show the path to the original log call. Defaults to True.
+ enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True.
+ highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.
+ markup (bool, optional): Enable console markup in log messages. Defaults to False.
+ rich_tracebacks (bool, optional): Enable rich tracebacks with syntax highlighting and formatting. Defaults to False.
+ tracebacks_width (Optional[int], optional): Number of characters used to render tracebacks, or None for full width. Defaults to None.
+ tracebacks_code_width (int, optional): Number of code characters used to render tracebacks, or None for full width. Defaults to 88.
+ tracebacks_extra_lines (int, optional): Additional lines of code to render tracebacks, or None for full width. Defaults to None.
+ tracebacks_theme (str, optional): Override pygments theme used in traceback.
+ tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to True.
+ tracebacks_show_locals (bool, optional): Enable display of locals in tracebacks. Defaults to False.
+ tracebacks_suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
+ tracebacks_max_frames (int, optional): Optional maximum number of frames returned by traceback.
+ locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
+ Defaults to 10.
+ locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
+ log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%x %X] ".
+ keywords (List[str], optional): List of words to highlight instead of ``RichHandler.KEYWORDS``.
+ """
KEYWORDS: ClassVar[Optional[List[str]]] = [
"GET",
@@ -82,6 +115,14 @@ self.keywords = keywords
def get_level_text(self, record: LogRecord) -> Text:
+ """Get the level name from the record.
+
+ Args:
+ record (LogRecord): LogRecord instance.
+
+ Returns:
+ Text: A tuple of the style and level name.
+ """
level_name = record.levelname
level_text = Text.styled(
level_name.ljust(8), f"logging.level.{level_name.lower()}"
@@ -89,6 +130,7 @@ return level_text
def emit(self, record: LogRecord) -> None:
+ """Invoked by logging."""
message = self.format(record)
traceback = None
if (
@@ -138,6 +180,15 @@ self.handleError(record)
def render_message(self, record: LogRecord, message: str) -> "ConsoleRenderable":
+ """Render message text in to Text.
+
+ Args:
+ record (LogRecord): logging Record.
+ message (str): String containing log message.
+
+ Returns:
+ ConsoleRenderable: Renderable to display log message.
+ """
use_markup = getattr(record, "markup", self.markup)
message_text = Text.from_markup(message) if use_markup else Text(message)
@@ -160,6 +211,16 @@ traceback: Optional[Traceback],
message_renderable: "ConsoleRenderable",
) -> "ConsoleRenderable":
+ """Render log for display.
+
+ Args:
+ record (LogRecord): logging Record.
+ traceback (Optional[Traceback]): Traceback instance or None for no Traceback.
+ message_renderable (ConsoleRenderable): Renderable (typically Text) containing log message contents.
+
+ Returns:
+ ConsoleRenderable: Renderable to display log.
+ """
path = Path(record.pathname).name
level = self.get_level_text(record)
time_format = None if self.formatter is None else self.formatter.datefmt
@@ -233,4 +294,4 @@ sleep(1)
log.critical("Out of memory!")
log.info("Server exited with code=-1")
- log.info("[bold]EXITING...[/bold]", extra=dict(markup=True))+ log.info("[bold]EXITING...[/bold]", extra=dict(markup=True))
| 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 Spinner:
def __init__(
self,
name: str,
text: "RenderableType" = "",
*,
style: Optional["StyleType"] = None,
speed: float = 1.0,
) -> None:
try:
spinner = SPINNERS[name]
except KeyError:
raise KeyError(f"no spinner called {name!r}")
self.text: "Union[RenderableType, Text]" = (
Text.from_markup(text) if isinstance(text, str) else text
)
self.name = name
self.frames = cast(List[str], spinner["frames"])[:]
self.interval = cast(float, spinner["interval"])
self.start_time: Optional[float] = None
self.style = style
self.speed = speed
self.frame_no_offset: float = 0.0
self._update_speed = 0.0
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> "RenderResult":
yield self.render(console.get_time())
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> Measurement:
text = self.render(0)
return Measurement.get(console, options, text)
def render(self, time: float) -> "RenderableType":
if self.start_time is None:
self.start_time = time
frame_no = ((time - self.start_time) * self.speed) / (
self.interval / 1000.0
) + self.frame_no_offset
frame = Text(
self.frames[int(frame_no) % len(self.frames)], style=self.style or ""
)
if self._update_speed:
self.frame_no_offset = frame_no
self.start_time = time
self.speed = self._update_speed
self._update_speed = 0.0
if not self.text:
return frame
elif isinstance(self.text, (str, Text)):
return Text.assemble(frame, " ", self.text)
else:
table = Table.grid(padding=1)
table.add_row(frame, self.text)
return table
def update(
self,
*,
text: "RenderableType" = "",
style: Optional["StyleType"] = None,
speed: Optional[float] = None,
) -> None:
if text:
self.text = Text.from_markup(text) if isinstance(text, str) else text
if style:
self.style = style
if speed:
self._update_speed = speed
if __name__ == "__main__": # pragma: no cover
from time import sleep
from .console import Group
from .live import Live
all_spinners = Group(
*[
Spinner(spinner_name, text=Text(repr(spinner_name), style="green"))
for spinner_name in sorted(SPINNERS.keys())
]
)
with Live(all_spinners, refresh_per_second=20) as live:
while True:
sleep(0.1) | --- +++ @@ -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, optional): Style for spinner animation. Defaults to None.
+ speed (float, optional): Speed factor for animation. Defaults to 1.0.
+
+ Raises:
+ KeyError: If name isn't one of the supported spinner animations.
+ """
def __init__(
self,
@@ -48,6 +59,14 @@ return Measurement.get(console, options, text)
def render(self, time: float) -> "RenderableType":
+ """Render the spinner for a given time.
+
+ Args:
+ time (float): Time in seconds.
+
+ Returns:
+ RenderableType: A renderable containing animation frame.
+ """
if self.start_time is None:
self.start_time = time
@@ -80,6 +99,13 @@ style: Optional["StyleType"] = None,
speed: Optional[float] = None,
) -> None:
+ """Updates attributes of a spinner after it has been started.
+
+ Args:
+ text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to "".
+ style (StyleType, optional): Style for spinner animation. Defaults to None.
+ speed (float, optional): Speed factor for animation. Defaults to None.
+ """
if text:
self.text = Text.from_markup(text) if isinstance(text, str) else text
if style:
@@ -103,4 +129,4 @@
with Live(all_spinners, refresh_per_second=20) as live:
while True:
- sleep(0.1)+ sleep(0.1)
| 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
):
self.styles = DEFAULT_STYLES.copy() if inherit else {}
if styles is not None:
self.styles.update(
{
name: style if isinstance(style, Style) else Style.parse(style)
for name, style in styles.items()
}
)
@property
def config(self) -> str:
config = "[styles]\n" + "\n".join(
f"{name} = {style}" for name, style in sorted(self.styles.items())
)
return config
@classmethod
def from_file(
cls, config_file: IO[str], source: Optional[str] = None, inherit: bool = True
) -> "Theme":
config = configparser.ConfigParser()
config.read_file(config_file, source=source)
styles = {name: Style.parse(value) for name, value in config.items("styles")}
theme = Theme(styles, inherit=inherit)
return theme
@classmethod
def read(
cls, path: str, inherit: bool = True, encoding: Optional[str] = None
) -> "Theme":
with open(path, encoding=encoding) as config_file:
return cls.from_file(config_file, source=path, inherit=inherit)
class ThemeStackError(Exception):
class ThemeStack:
def __init__(self, theme: Theme) -> None:
self._entries: List[Dict[str, Style]] = [theme.styles]
self.get = self._entries[-1].get
def push_theme(self, theme: Theme, inherit: bool = True) -> None:
styles: Dict[str, Style]
styles = (
{**self._entries[-1], **theme.styles} if inherit else theme.styles.copy()
)
self._entries.append(styles)
self.get = self._entries[-1].get
def pop_theme(self) -> None:
if len(self._entries) == 1:
raise ThemeStackError("Unable to pop base theme")
self._entries.pop()
self.get = self._entries[-1].get
if __name__ == "__main__": # pragma: no cover
theme = Theme()
print(theme.config) | --- +++ @@ -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 styles. Defaults to True.
+ """
styles: Dict[str, Style]
@@ -23,6 +29,7 @@
@property
def config(self) -> str:
+ """Get contents of a config file for this theme."""
config = "[styles]\n" + "\n".join(
f"{name} = {style}" for name, style in sorted(self.styles.items())
)
@@ -32,6 +39,16 @@ def from_file(
cls, config_file: IO[str], source: Optional[str] = None, inherit: bool = True
) -> "Theme":
+ """Load a theme from a text mode file.
+
+ Args:
+ config_file (IO[str]): An open conf file.
+ source (str, optional): The filename of the open file. Defaults to None.
+ inherit (bool, optional): Inherit default styles. Defaults to True.
+
+ Returns:
+ Theme: A New theme instance.
+ """
config = configparser.ConfigParser()
config.read_file(config_file, source=source)
styles = {name: Style.parse(value) for name, value in config.items("styles")}
@@ -42,20 +59,42 @@ def read(
cls, path: str, inherit: bool = True, encoding: Optional[str] = None
) -> "Theme":
+ """Read a theme from a path.
+
+ Args:
+ path (str): Path to a config file readable by Python configparser module.
+ inherit (bool, optional): Inherit default styles. Defaults to True.
+ encoding (str, optional): Encoding of the config file. Defaults to None.
+
+ Returns:
+ Theme: A new theme instance.
+ """
with open(path, encoding=encoding) as config_file:
return cls.from_file(config_file, source=path, inherit=inherit)
class ThemeStackError(Exception):
+ """Base exception for errors related to the theme stack."""
class ThemeStack:
+ """A stack of themes.
+
+ Args:
+ theme (Theme): A theme instance
+ """
def __init__(self, theme: Theme) -> None:
self._entries: List[Dict[str, Style]] = [theme.styles]
self.get = self._entries[-1].get
def push_theme(self, theme: Theme, inherit: bool = True) -> None:
+ """Push a theme on the top of the stack.
+
+ Args:
+ theme (Theme): A Theme instance.
+ inherit (boolean, optional): Inherit styles from current top of stack.
+ """
styles: Dict[str, Style]
styles = (
{**self._entries[-1], **theme.styles} if inherit else theme.styles.copy()
@@ -64,6 +103,7 @@ self.get = self._entries[-1].get
def pop_theme(self) -> None:
+ """Pop (and discard) the top-most theme."""
if len(self._entries) == 1:
raise ThemeStackError("Unable to pop base theme")
self._entries.pop()
@@ -72,4 +112,4 @@
if __name__ == "__main__": # pragma: no cover
theme = Theme()
- print(theme.config)+ print(theme.config)
| 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, rich_repr
from .terminal_theme import DEFAULT_TERMINAL_THEME, TerminalTheme
_hash_getter = attrgetter(
"_color", "_bgcolor", "_attributes", "_set_attributes", "_link", "_meta"
)
# Style instances and style definitions are often interchangeable
StyleType = Union[str, "Style"]
class _Bit:
__slots__ = ["bit"]
def __init__(self, bit_no: int) -> None:
self.bit = 1 << bit_no
def __get__(self, obj: "Style", objtype: Type["Style"]) -> Optional[bool]:
if obj._set_attributes & self.bit:
return obj._attributes & self.bit != 0
return None
@rich_repr
class Style:
_color: Optional[Color]
_bgcolor: Optional[Color]
_attributes: int
_set_attributes: int
_hash: Optional[int]
_null: bool
_meta: Optional[bytes]
__slots__ = [
"_color",
"_bgcolor",
"_attributes",
"_set_attributes",
"_link",
"_link_id",
"_ansi",
"_style_definition",
"_hash",
"_null",
"_meta",
]
# maps bits on to SGR parameter
_style_map = {
0: "1",
1: "2",
2: "3",
3: "4",
4: "5",
5: "6",
6: "7",
7: "8",
8: "9",
9: "21",
10: "51",
11: "52",
12: "53",
}
STYLE_ATTRIBUTES = {
"dim": "dim",
"d": "dim",
"bold": "bold",
"b": "bold",
"italic": "italic",
"i": "italic",
"underline": "underline",
"u": "underline",
"blink": "blink",
"blink2": "blink2",
"reverse": "reverse",
"r": "reverse",
"conceal": "conceal",
"c": "conceal",
"strike": "strike",
"s": "strike",
"underline2": "underline2",
"uu": "underline2",
"frame": "frame",
"encircle": "encircle",
"overline": "overline",
"o": "overline",
}
def __init__(
self,
*,
color: Optional[Union[Color, str]] = None,
bgcolor: Optional[Union[Color, str]] = None,
bold: Optional[bool] = None,
dim: Optional[bool] = None,
italic: Optional[bool] = None,
underline: Optional[bool] = None,
blink: Optional[bool] = None,
blink2: Optional[bool] = None,
reverse: Optional[bool] = None,
conceal: Optional[bool] = None,
strike: Optional[bool] = None,
underline2: Optional[bool] = None,
frame: Optional[bool] = None,
encircle: Optional[bool] = None,
overline: Optional[bool] = None,
link: Optional[str] = None,
meta: Optional[Dict[str, Any]] = None,
):
self._ansi: Optional[str] = None
self._style_definition: Optional[str] = None
def _make_color(color: Union[Color, str]) -> Color:
return color if isinstance(color, Color) else Color.parse(color)
self._color = None if color is None else _make_color(color)
self._bgcolor = None if bgcolor is None else _make_color(bgcolor)
self._set_attributes = sum(
(
bold is not None,
dim is not None and 2,
italic is not None and 4,
underline is not None and 8,
blink is not None and 16,
blink2 is not None and 32,
reverse is not None and 64,
conceal is not None and 128,
strike is not None and 256,
underline2 is not None and 512,
frame is not None and 1024,
encircle is not None and 2048,
overline is not None and 4096,
)
)
self._attributes = (
sum(
(
bold and 1 or 0,
dim and 2 or 0,
italic and 4 or 0,
underline and 8 or 0,
blink and 16 or 0,
blink2 and 32 or 0,
reverse and 64 or 0,
conceal and 128 or 0,
strike and 256 or 0,
underline2 and 512 or 0,
frame and 1024 or 0,
encircle and 2048 or 0,
overline and 4096 or 0,
)
)
if self._set_attributes
else 0
)
self._link = link
self._meta = None if meta is None else dumps(meta)
self._link_id = (
f"{randint(0, 999999)}{hash(self._meta)}" if (link or meta) else ""
)
self._hash: Optional[int] = None
self._null = not (self._set_attributes or color or bgcolor or link or meta)
@classmethod
def null(cls) -> "Style":
return NULL_STYLE
@classmethod
def from_color(
cls, color: Optional[Color] = None, bgcolor: Optional[Color] = None
) -> "Style":
style: Style = cls.__new__(Style)
style._ansi = None
style._style_definition = None
style._color = color
style._bgcolor = bgcolor
style._set_attributes = 0
style._attributes = 0
style._link = None
style._link_id = ""
style._meta = None
style._null = not (color or bgcolor)
style._hash = None
return style
@classmethod
def from_meta(cls, meta: Optional[Dict[str, Any]]) -> "Style":
style: Style = cls.__new__(Style)
style._ansi = None
style._style_definition = None
style._color = None
style._bgcolor = None
style._set_attributes = 0
style._attributes = 0
style._link = None
style._meta = dumps(meta)
style._link_id = f"{randint(0, 999999)}{hash(style._meta)}"
style._hash = None
style._null = not (meta)
return style
@classmethod
def on(cls, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> "Style":
meta = {} if meta is None else meta
meta.update({f"@{key}": value for key, value in handlers.items()})
return cls.from_meta(meta)
bold = _Bit(0)
dim = _Bit(1)
italic = _Bit(2)
underline = _Bit(3)
blink = _Bit(4)
blink2 = _Bit(5)
reverse = _Bit(6)
conceal = _Bit(7)
strike = _Bit(8)
underline2 = _Bit(9)
frame = _Bit(10)
encircle = _Bit(11)
overline = _Bit(12)
@property
def link_id(self) -> str:
return self._link_id
def __str__(self) -> str:
if self._style_definition is None:
attributes: List[str] = []
append = attributes.append
bits = self._set_attributes
if bits & 0b0000000001111:
if bits & 1:
append("bold" if self.bold else "not bold")
if bits & (1 << 1):
append("dim" if self.dim else "not dim")
if bits & (1 << 2):
append("italic" if self.italic else "not italic")
if bits & (1 << 3):
append("underline" if self.underline else "not underline")
if bits & 0b0000111110000:
if bits & (1 << 4):
append("blink" if self.blink else "not blink")
if bits & (1 << 5):
append("blink2" if self.blink2 else "not blink2")
if bits & (1 << 6):
append("reverse" if self.reverse else "not reverse")
if bits & (1 << 7):
append("conceal" if self.conceal else "not conceal")
if bits & (1 << 8):
append("strike" if self.strike else "not strike")
if bits & 0b1111000000000:
if bits & (1 << 9):
append("underline2" if self.underline2 else "not underline2")
if bits & (1 << 10):
append("frame" if self.frame else "not frame")
if bits & (1 << 11):
append("encircle" if self.encircle else "not encircle")
if bits & (1 << 12):
append("overline" if self.overline else "not overline")
if self._color is not None:
append(self._color.name)
if self._bgcolor is not None:
append("on")
append(self._bgcolor.name)
if self._link:
append("link")
append(self._link)
self._style_definition = " ".join(attributes) or "none"
return self._style_definition
def __bool__(self) -> bool:
return not self._null
def _make_ansi_codes(self, color_system: ColorSystem) -> str:
if self._ansi is None:
sgr: List[str] = []
append = sgr.append
_style_map = self._style_map
attributes = self._attributes & self._set_attributes
if attributes:
if attributes & 1:
append(_style_map[0])
if attributes & 2:
append(_style_map[1])
if attributes & 4:
append(_style_map[2])
if attributes & 8:
append(_style_map[3])
if attributes & 0b0000111110000:
for bit in range(4, 9):
if attributes & (1 << bit):
append(_style_map[bit])
if attributes & 0b1111000000000:
for bit in range(9, 13):
if attributes & (1 << bit):
append(_style_map[bit])
if self._color is not None:
sgr.extend(self._color.downgrade(color_system).get_ansi_codes())
if self._bgcolor is not None:
sgr.extend(
self._bgcolor.downgrade(color_system).get_ansi_codes(
foreground=False
)
)
self._ansi = ";".join(sgr)
return self._ansi
@classmethod
@lru_cache(maxsize=1024)
def normalize(cls, style: str) -> str:
try:
return str(cls.parse(style))
except errors.StyleSyntaxError:
return style.strip().lower()
@classmethod
def pick_first(cls, *values: Optional[StyleType]) -> StyleType:
for value in values:
if value is not None:
return value
raise ValueError("expected at least one non-None style")
def __rich_repr__(self) -> Result:
yield "color", self.color, None
yield "bgcolor", self.bgcolor, None
yield "bold", self.bold, None,
yield "dim", self.dim, None,
yield "italic", self.italic, None
yield "underline", self.underline, None,
yield "blink", self.blink, None
yield "blink2", self.blink2, None
yield "reverse", self.reverse, None
yield "conceal", self.conceal, None
yield "strike", self.strike, None
yield "underline2", self.underline2, None
yield "frame", self.frame, None
yield "encircle", self.encircle, None
yield "link", self.link, None
if self._meta:
yield "meta", self.meta
def __eq__(self, other: Any) -> bool:
if not isinstance(other, Style):
return NotImplemented
return self.__hash__() == other.__hash__()
def __ne__(self, other: Any) -> bool:
if not isinstance(other, Style):
return NotImplemented
return self.__hash__() != other.__hash__()
def __hash__(self) -> int:
if self._hash is not None:
return self._hash
self._hash = hash(_hash_getter(self))
return self._hash
@property
def color(self) -> Optional[Color]:
return self._color
@property
def bgcolor(self) -> Optional[Color]:
return self._bgcolor
@property
def link(self) -> Optional[str]:
return self._link
@property
def transparent_background(self) -> bool:
return self.bgcolor is None or self.bgcolor.is_default
@property
def background_style(self) -> "Style":
return Style(bgcolor=self.bgcolor)
@property
def meta(self) -> Dict[str, Any]:
return {} if self._meta is None else cast(Dict[str, Any], loads(self._meta))
@property
def without_color(self) -> "Style":
if self._null:
return NULL_STYLE
style: Style = self.__new__(Style)
style._ansi = None
style._style_definition = None
style._color = None
style._bgcolor = None
style._attributes = self._attributes
style._set_attributes = self._set_attributes
style._link = self._link
style._link_id = f"{randint(0, 999999)}" if self._link else ""
style._null = False
style._meta = None
style._hash = None
return style
@classmethod
@lru_cache(maxsize=4096)
def parse(cls, style_definition: str) -> "Style":
if style_definition.strip() == "none" or not style_definition:
return cls.null()
STYLE_ATTRIBUTES = cls.STYLE_ATTRIBUTES
color: Optional[str] = None
bgcolor: Optional[str] = None
attributes: Dict[str, Optional[Any]] = {}
link: Optional[str] = None
words = iter(style_definition.split())
for original_word in words:
word = original_word.lower()
if word == "on":
word = next(words, "")
if not word:
raise errors.StyleSyntaxError("color expected after 'on'")
try:
Color.parse(word)
except ColorParseError as error:
raise errors.StyleSyntaxError(
f"unable to parse {word!r} as background color; {error}"
) from None
bgcolor = word
elif word == "not":
word = next(words, "")
attribute = STYLE_ATTRIBUTES.get(word)
if attribute is None:
raise errors.StyleSyntaxError(
f"expected style attribute after 'not', found {word!r}"
)
attributes[attribute] = False
elif word == "link":
word = next(words, "")
if not word:
raise errors.StyleSyntaxError("URL expected after 'link'")
link = word
elif word in STYLE_ATTRIBUTES:
attributes[STYLE_ATTRIBUTES[word]] = True
else:
try:
Color.parse(word)
except ColorParseError as error:
raise errors.StyleSyntaxError(
f"unable to parse {word!r} as color; {error}"
) from None
color = word
style = Style(color=color, bgcolor=bgcolor, link=link, **attributes)
return style
@lru_cache(maxsize=1024)
def get_html_style(self, theme: Optional[TerminalTheme] = None) -> str:
theme = theme or DEFAULT_TERMINAL_THEME
css: List[str] = []
append = css.append
color = self.color
bgcolor = self.bgcolor
if self.reverse:
color, bgcolor = bgcolor, color
if self.dim:
foreground_color = (
theme.foreground_color if color is None else color.get_truecolor(theme)
)
color = Color.from_triplet(
blend_rgb(foreground_color, theme.background_color, 0.5)
)
if color is not None:
theme_color = color.get_truecolor(theme)
append(f"color: {theme_color.hex}")
append(f"text-decoration-color: {theme_color.hex}")
if bgcolor is not None:
theme_color = bgcolor.get_truecolor(theme, foreground=False)
append(f"background-color: {theme_color.hex}")
if self.bold:
append("font-weight: bold")
if self.italic:
append("font-style: italic")
if self.underline:
append("text-decoration: underline")
if self.strike:
append("text-decoration: line-through")
if self.overline:
append("text-decoration: overline")
return "; ".join(css)
@classmethod
def combine(cls, styles: Iterable["Style"]) -> "Style":
iter_styles = iter(styles)
return sum(iter_styles, next(iter_styles))
@classmethod
def chain(cls, *styles: "Style") -> "Style":
iter_styles = iter(styles)
return sum(iter_styles, next(iter_styles))
def copy(self) -> "Style":
if self._null:
return NULL_STYLE
style: Style = self.__new__(Style)
style._ansi = self._ansi
style._style_definition = self._style_definition
style._color = self._color
style._bgcolor = self._bgcolor
style._attributes = self._attributes
style._set_attributes = self._set_attributes
style._link = self._link
style._link_id = f"{randint(0, 999999)}" if self._link else ""
style._hash = self._hash
style._null = False
style._meta = self._meta
return style
@lru_cache(maxsize=128)
def clear_meta_and_links(self) -> "Style":
if self._null:
return NULL_STYLE
style: Style = self.__new__(Style)
style._ansi = self._ansi
style._style_definition = self._style_definition
style._color = self._color
style._bgcolor = self._bgcolor
style._attributes = self._attributes
style._set_attributes = self._set_attributes
style._link = None
style._link_id = ""
style._hash = None
style._null = False
style._meta = None
return style
def update_link(self, link: Optional[str] = None) -> "Style":
style: Style = self.__new__(Style)
style._ansi = self._ansi
style._style_definition = self._style_definition
style._color = self._color
style._bgcolor = self._bgcolor
style._attributes = self._attributes
style._set_attributes = self._set_attributes
style._link = link
style._link_id = f"{randint(0, 999999)}" if link else ""
style._hash = None
style._null = False
style._meta = self._meta
return style
def render(
self,
text: str = "",
*,
color_system: Optional[ColorSystem] = ColorSystem.TRUECOLOR,
legacy_windows: bool = False,
) -> str:
if not text or color_system is None:
return text
attrs = self._ansi or self._make_ansi_codes(color_system)
rendered = f"\x1b[{attrs}m{text}\x1b[0m" if attrs else text
if self._link and not legacy_windows:
rendered = (
f"\x1b]8;id={self._link_id};{self._link}\x1b\\{rendered}\x1b]8;;\x1b\\"
)
return rendered
def test(self, text: Optional[str] = None) -> None:
text = text or str(self)
sys.stdout.write(f"{self.render(text)}\n")
@lru_cache(maxsize=1024)
def _add(self, style: Optional["Style"]) -> "Style":
if style is None or style._null:
return self
if self._null:
return style
new_style: Style = self.__new__(Style)
new_style._ansi = None
new_style._style_definition = None
new_style._color = style._color or self._color
new_style._bgcolor = style._bgcolor or self._bgcolor
new_style._attributes = (self._attributes & ~style._set_attributes) | (
style._attributes & style._set_attributes
)
new_style._set_attributes = self._set_attributes | style._set_attributes
new_style._link = style._link or self._link
new_style._link_id = style._link_id or self._link_id
new_style._null = style._null
if self._meta and style._meta:
new_style._meta = dumps({**self.meta, **style.meta})
else:
new_style._meta = self._meta or style._meta
new_style._hash = None
return new_style
def __add__(self, style: Optional["Style"]) -> "Style":
combined_style = self._add(style)
return combined_style.copy() if combined_style.link else combined_style
NULL_STYLE = Style()
class StyleStack:
__slots__ = ["_stack"]
def __init__(self, default_style: "Style") -> None:
self._stack: List[Style] = [default_style]
def __repr__(self) -> str:
return f"<stylestack {self._stack!r}>"
@property
def current(self) -> Style:
return self._stack[-1]
def push(self, style: Style) -> None:
self._stack.append(self._stack[-1] + style)
def pop(self) -> Style:
self._stack.pop()
return self._stack[-1] | --- +++ @@ -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
+ as bold, italic etc. The attributes have 3 states: they can either be on
+ (``True``), off (``False``), or not set (``None``).
+
+ Args:
+ color (Union[Color, str], optional): Color of terminal text. Defaults to None.
+ bgcolor (Union[Color, str], optional): Color of terminal background. Defaults to None.
+ bold (bool, optional): Enable bold text. Defaults to None.
+ dim (bool, optional): Enable dim text. Defaults to None.
+ italic (bool, optional): Enable italic text. Defaults to None.
+ underline (bool, optional): Enable underlined text. Defaults to None.
+ blink (bool, optional): Enabled blinking text. Defaults to None.
+ blink2 (bool, optional): Enable fast blinking text. Defaults to None.
+ reverse (bool, optional): Enabled reverse text. Defaults to None.
+ conceal (bool, optional): Enable concealed text. Defaults to None.
+ strike (bool, optional): Enable strikethrough text. Defaults to None.
+ underline2 (bool, optional): Enable doubly underlined text. Defaults to None.
+ frame (bool, optional): Enable framed text. Defaults to None.
+ encircle (bool, optional): Enable encircled text. Defaults to None.
+ overline (bool, optional): Enable overlined text. Defaults to None.
+ link (str, link): Link URL. Defaults to None.
+
+ """
_color: Optional[Color]
_bgcolor: Optional[Color]
@@ -176,12 +202,19 @@
@classmethod
def null(cls) -> "Style":
+ """Create an 'null' style, equivalent to Style(), but more performant."""
return NULL_STYLE
@classmethod
def from_color(
cls, color: Optional[Color] = None, bgcolor: Optional[Color] = None
) -> "Style":
+ """Create a new style with colors and no attributes.
+
+ Returns:
+ color (Optional[Color]): A (foreground) color, or None for no color. Defaults to None.
+ bgcolor (Optional[Color]): A (background) color, or None for no color. Defaults to None.
+ """
style: Style = cls.__new__(Style)
style._ansi = None
style._style_definition = None
@@ -198,6 +231,11 @@
@classmethod
def from_meta(cls, meta: Optional[Dict[str, Any]]) -> "Style":
+ """Create a new style with meta data.
+
+ Returns:
+ meta (Optional[Dict[str, Any]]): A dictionary of meta data. Defaults to None.
+ """
style: Style = cls.__new__(Style)
style._ansi = None
style._style_definition = None
@@ -214,6 +252,18 @@
@classmethod
def on(cls, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> "Style":
+ """Create a blank style with meta information.
+
+ Example:
+ style = Style.on(click=self.on_click)
+
+ Args:
+ meta (Optional[Dict[str, Any]], optional): An optional dict of meta information.
+ **handlers (Any): Keyword arguments are translated in to handlers.
+
+ Returns:
+ Style: A Style with meta information attached.
+ """
meta = {} if meta is None else meta
meta.update({f"@{key}": value for key, value in handlers.items()})
return cls.from_meta(meta)
@@ -234,9 +284,11 @@
@property
def link_id(self) -> str:
+ """Get a link id, used in ansi code for links."""
return self._link_id
def __str__(self) -> str:
+ """Re-generate style definition from attributes."""
if self._style_definition is None:
attributes: List[str] = []
append = attributes.append
@@ -282,9 +334,18 @@ return self._style_definition
def __bool__(self) -> bool:
+ """A Style is false if it has no attributes, colors, or links."""
return not self._null
def _make_ansi_codes(self, color_system: ColorSystem) -> str:
+ """Generate ANSI codes for this style.
+
+ Args:
+ color_system (ColorSystem): Color system.
+
+ Returns:
+ str: String containing codes.
+ """
if self._ansi is None:
sgr: List[str] = []
@@ -322,6 +383,15 @@ @classmethod
@lru_cache(maxsize=1024)
def normalize(cls, style: str) -> str:
+ """Normalize a style definition so that styles with the same effect have the same string
+ representation.
+
+ Args:
+ style (str): A style definition.
+
+ Returns:
+ str: Normal form of style definition.
+ """
try:
return str(cls.parse(style))
except errors.StyleSyntaxError:
@@ -329,6 +399,7 @@
@classmethod
def pick_first(cls, *values: Optional[StyleType]) -> StyleType:
+ """Pick first non-None style."""
for value in values:
if value is not None:
return value
@@ -371,30 +442,37 @@
@property
def color(self) -> Optional[Color]:
+ """The foreground color or None if it is not set."""
return self._color
@property
def bgcolor(self) -> Optional[Color]:
+ """The background color or None if it is not set."""
return self._bgcolor
@property
def link(self) -> Optional[str]:
+ """Link text, if set."""
return self._link
@property
def transparent_background(self) -> bool:
+ """Check if the style specified a transparent background."""
return self.bgcolor is None or self.bgcolor.is_default
@property
def background_style(self) -> "Style":
+ """A Style with background only."""
return Style(bgcolor=self.bgcolor)
@property
def meta(self) -> Dict[str, Any]:
+ """Get meta information (can not be changed after construction)."""
return {} if self._meta is None else cast(Dict[str, Any], loads(self._meta))
@property
def without_color(self) -> "Style":
+ """Get a copy of the style with color removed."""
if self._null:
return NULL_STYLE
style: Style = self.__new__(Style)
@@ -414,6 +492,17 @@ @classmethod
@lru_cache(maxsize=4096)
def parse(cls, style_definition: str) -> "Style":
+ """Parse a style definition.
+
+ Args:
+ style_definition (str): A string containing a style.
+
+ Raises:
+ errors.StyleSyntaxError: If the style definition syntax is invalid.
+
+ Returns:
+ `Style`: A Style instance.
+ """
if style_definition.strip() == "none" or not style_definition:
return cls.null()
@@ -469,6 +558,7 @@
@lru_cache(maxsize=1024)
def get_html_style(self, theme: Optional[TerminalTheme] = None) -> str:
+ """Get a CSS style rule."""
theme = theme or DEFAULT_TERMINAL_THEME
css: List[str] = []
append = css.append
@@ -505,15 +595,36 @@
@classmethod
def combine(cls, styles: Iterable["Style"]) -> "Style":
+ """Combine styles and get result.
+
+ Args:
+ styles (Iterable[Style]): Styles to combine.
+
+ Returns:
+ Style: A new style instance.
+ """
iter_styles = iter(styles)
return sum(iter_styles, next(iter_styles))
@classmethod
def chain(cls, *styles: "Style") -> "Style":
+ """Combine styles from positional argument in to a single style.
+
+ Args:
+ *styles (Iterable[Style]): Styles to combine.
+
+ Returns:
+ Style: A new style instance.
+ """
iter_styles = iter(styles)
return sum(iter_styles, next(iter_styles))
def copy(self) -> "Style":
+ """Get a copy of this style.
+
+ Returns:
+ Style: A new Style instance with identical attributes.
+ """
if self._null:
return NULL_STYLE
style: Style = self.__new__(Style)
@@ -532,6 +643,11 @@
@lru_cache(maxsize=128)
def clear_meta_and_links(self) -> "Style":
+ """Get a copy of this style with link and meta information removed.
+
+ Returns:
+ Style: New style object.
+ """
if self._null:
return NULL_STYLE
style: Style = self.__new__(Style)
@@ -549,6 +665,14 @@ return style
def update_link(self, link: Optional[str] = None) -> "Style":
+ """Get a copy with a different value for link.
+
+ Args:
+ link (str, optional): New value for link. Defaults to None.
+
+ Returns:
+ Style: A new Style instance.
+ """
style: Style = self.__new__(Style)
style._ansi = self._ansi
style._style_definition = self._style_definition
@@ -570,6 +694,15 @@ color_system: Optional[ColorSystem] = ColorSystem.TRUECOLOR,
legacy_windows: bool = False,
) -> str:
+ """Render the ANSI codes for the style.
+
+ Args:
+ text (str, optional): A string to style. Defaults to "".
+ color_system (Optional[ColorSystem], optional): Color system to render to. Defaults to ColorSystem.TRUECOLOR.
+
+ Returns:
+ str: A string containing ANSI style codes.
+ """
if not text or color_system is None:
return text
attrs = self._ansi or self._make_ansi_codes(color_system)
@@ -581,6 +714,14 @@ return rendered
def test(self, text: Optional[str] = None) -> None:
+ """Write text with style directly to terminal.
+
+ This method is for testing purposes only.
+
+ Args:
+ text (Optional[str], optional): Text to style or None for style name.
+
+ """
text = text or str(self)
sys.stdout.write(f"{self.render(text)}\n")
@@ -618,6 +759,7 @@
class StyleStack:
+ """A stack of styles."""
__slots__ = ["_stack"]
@@ -629,11 +771,22 @@
@property
def current(self) -> Style:
+ """Get the Style at the top of the stack."""
return self._stack[-1]
def push(self, style: Style) -> None:
+ """Push a new style on to the stack.
+
+ Args:
+ style (Style): New style to combine with current style.
+ """
self._stack.append(self._stack[-1] + style)
def pop(self) -> Style:
+ """Pop last style and discard.
+
+ Returns:
+ Style: New current style (also available as stack.current)
+ """
self._stack.pop()
- return self._stack[-1]+ return self._stack[-1]
| 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_bool
from ._wrap import divide_line
from .align import AlignMethod
from .cells import cell_len, set_cell_size
from .containers import Lines
from .control import strip_control_codes
from .emoji import EmojiVariant
from .jupyter import JupyterMixin
from .measure import Measurement
from .segment import Segment
from .style import Style, StyleType
if TYPE_CHECKING: # pragma: no cover
from .console import Console, ConsoleOptions, JustifyMethod, OverflowMethod
DEFAULT_JUSTIFY: "JustifyMethod" = "default"
DEFAULT_OVERFLOW: "OverflowMethod" = "fold"
_re_whitespace = re.compile(r"\s+$")
TextType = Union[str, "Text"]
"""A plain string or a :class:`Text` instance."""
GetStyleCallable = Callable[[str], Optional[StyleType]]
class Span(NamedTuple):
start: int
"""Span start index."""
end: int
"""Span end index."""
style: Union[str, Style]
"""Style associated with the span."""
def __repr__(self) -> str:
return f"Span({self.start}, {self.end}, {self.style!r})"
def __bool__(self) -> bool:
return self.end > self.start
def split(self, offset: int) -> Tuple["Span", Optional["Span"]]:
if offset < self.start:
return self, None
if offset >= self.end:
return self, None
start, end, style = self
span1 = Span(start, min(end, offset), style)
span2 = Span(span1.end, end, style)
return span1, span2
def move(self, offset: int) -> "Span":
start, end, style = self
return Span(start + offset, end + offset, style)
def right_crop(self, offset: int) -> "Span":
start, end, style = self
if offset >= end:
return self
return Span(start, min(offset, end), style)
def extend(self, cells: int) -> "Span":
if cells:
start, end, style = self
return Span(start, end + cells, style)
else:
return self
class Text(JupyterMixin):
__slots__ = [
"_text",
"style",
"justify",
"overflow",
"no_wrap",
"end",
"tab_size",
"_spans",
"_length",
]
def __init__(
self,
text: str = "",
style: Union[str, Style] = "",
*,
justify: Optional["JustifyMethod"] = None,
overflow: Optional["OverflowMethod"] = None,
no_wrap: Optional[bool] = None,
end: str = "\n",
tab_size: Optional[int] = None,
spans: Optional[List[Span]] = None,
) -> None:
sanitized_text = strip_control_codes(text)
self._text = [sanitized_text]
self.style = style
self.justify: Optional["JustifyMethod"] = justify
self.overflow: Optional["OverflowMethod"] = overflow
self.no_wrap = no_wrap
self.end = end
self.tab_size = tab_size
self._spans: List[Span] = spans or []
self._length: int = len(sanitized_text)
def __len__(self) -> int:
return self._length
def __bool__(self) -> bool:
return bool(self._length)
def __str__(self) -> str:
return self.plain
def __repr__(self) -> str:
return f"<text {self.plain!r} {self._spans!r} {self.style!r}>"
def __add__(self, other: Any) -> "Text":
if isinstance(other, (str, Text)):
result = self.copy()
result.append(other)
return result
return NotImplemented
def __eq__(self, other: object) -> bool:
if not isinstance(other, Text):
return NotImplemented
return self.plain == other.plain and self._spans == other._spans
def __contains__(self, other: object) -> bool:
if isinstance(other, str):
return other in self.plain
elif isinstance(other, Text):
return other.plain in self.plain
return False
def __getitem__(self, slice: Union[int, slice]) -> "Text":
def get_text_at(offset: int) -> "Text":
_Span = Span
text = Text(
self.plain[offset],
spans=[
_Span(0, 1, style)
for start, end, style in self._spans
if end > offset >= start
],
end="",
)
return text
if isinstance(slice, int):
return get_text_at(slice)
else:
start, stop, step = slice.indices(len(self.plain))
if step == 1:
lines = self.divide([start, stop])
return lines[1]
else:
# This would be a bit of work to implement efficiently
# For now, its not required
raise TypeError("slices with step!=1 are not supported")
@property
def cell_len(self) -> int:
return cell_len(self.plain)
@property
def markup(self) -> str:
from .markup import escape
output: List[str] = []
plain = self.plain
markup_spans = [
(0, False, self.style),
*((span.start, False, span.style) for span in self._spans),
*((span.end, True, span.style) for span in self._spans),
(len(plain), True, self.style),
]
markup_spans.sort(key=itemgetter(0, 1))
position = 0
append = output.append
for offset, closing, style in markup_spans:
if offset > position:
append(escape(plain[position:offset]))
position = offset
if style:
append(f"[/{style}]" if closing else f"[{style}]")
markup = "".join(output)
return markup
@classmethod
def from_markup(
cls,
text: str,
*,
style: Union[str, Style] = "",
emoji: bool = True,
emoji_variant: Optional[EmojiVariant] = None,
justify: Optional["JustifyMethod"] = None,
overflow: Optional["OverflowMethod"] = None,
end: str = "\n",
) -> "Text":
from .markup import render
rendered_text = render(text, style, emoji=emoji, emoji_variant=emoji_variant)
rendered_text.justify = justify
rendered_text.overflow = overflow
rendered_text.end = end
return rendered_text
@classmethod
def from_ansi(
cls,
text: str,
*,
style: Union[str, Style] = "",
justify: Optional["JustifyMethod"] = None,
overflow: Optional["OverflowMethod"] = None,
no_wrap: Optional[bool] = None,
end: str = "\n",
tab_size: Optional[int] = 8,
) -> "Text":
from .ansi import AnsiDecoder
joiner = Text(
"\n",
justify=justify,
overflow=overflow,
no_wrap=no_wrap,
end=end,
tab_size=tab_size,
style=style,
)
decoder = AnsiDecoder()
result = joiner.join(line for line in decoder.decode(text))
return result
@classmethod
def styled(
cls,
text: str,
style: StyleType = "",
*,
justify: Optional["JustifyMethod"] = None,
overflow: Optional["OverflowMethod"] = None,
) -> "Text":
styled_text = cls(text, justify=justify, overflow=overflow)
styled_text.stylize(style)
return styled_text
@classmethod
def assemble(
cls,
*parts: Union[str, "Text", Tuple[str, StyleType]],
style: Union[str, Style] = "",
justify: Optional["JustifyMethod"] = None,
overflow: Optional["OverflowMethod"] = None,
no_wrap: Optional[bool] = None,
end: str = "\n",
tab_size: int = 8,
meta: Optional[Dict[str, Any]] = None,
) -> "Text":
text = cls(
style=style,
justify=justify,
overflow=overflow,
no_wrap=no_wrap,
end=end,
tab_size=tab_size,
)
append = text.append
_Text = Text
for part in parts:
if isinstance(part, (_Text, str)):
append(part)
else:
append(*part)
if meta:
text.apply_meta(meta)
return text
@property
def plain(self) -> str:
if len(self._text) != 1:
self._text[:] = ["".join(self._text)]
return self._text[0]
@plain.setter
def plain(self, new_text: str) -> None:
if new_text != self.plain:
sanitized_text = strip_control_codes(new_text)
self._text[:] = [sanitized_text]
old_length = self._length
self._length = len(sanitized_text)
if old_length > self._length:
self._trim_spans()
@property
def spans(self) -> List[Span]:
return self._spans
@spans.setter
def spans(self, spans: List[Span]) -> None:
self._spans = spans[:]
def blank_copy(self, plain: str = "") -> "Text":
copy_self = Text(
plain,
style=self.style,
justify=self.justify,
overflow=self.overflow,
no_wrap=self.no_wrap,
end=self.end,
tab_size=self.tab_size,
)
return copy_self
def copy(self) -> "Text":
copy_self = Text(
self.plain,
style=self.style,
justify=self.justify,
overflow=self.overflow,
no_wrap=self.no_wrap,
end=self.end,
tab_size=self.tab_size,
)
copy_self._spans[:] = self._spans
return copy_self
def stylize(
self,
style: Union[str, Style],
start: int = 0,
end: Optional[int] = None,
) -> None:
if style:
length = len(self)
if start < 0:
start = length + start
if end is None:
end = length
if end < 0:
end = length + end
if start >= length or end <= start:
# Span not in text or not valid
return
self._spans.append(Span(start, min(length, end), style))
def stylize_before(
self,
style: Union[str, Style],
start: int = 0,
end: Optional[int] = None,
) -> None:
if style:
length = len(self)
if start < 0:
start = length + start
if end is None:
end = length
if end < 0:
end = length + end
if start >= length or end <= start:
# Span not in text or not valid
return
self._spans.insert(0, Span(start, min(length, end), style))
def apply_meta(
self, meta: Dict[str, Any], start: int = 0, end: Optional[int] = None
) -> None:
style = Style.from_meta(meta)
self.stylize(style, start=start, end=end)
def on(self, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> "Text":
meta = {} if meta is None else meta
meta.update({f"@{key}": value for key, value in handlers.items()})
self.stylize(Style.from_meta(meta))
return self
def remove_suffix(self, suffix: str) -> None:
if self.plain.endswith(suffix):
self.right_crop(len(suffix))
def get_style_at_offset(self, console: "Console", offset: int) -> Style:
# TODO: This is a little inefficient, it is only used by full justify
if offset < 0:
offset = len(self) + offset
get_style = console.get_style
style = get_style(self.style).copy()
for start, end, span_style in self._spans:
if end > offset >= start:
style += get_style(span_style, default="")
return style
def extend_style(self, spaces: int) -> None:
if spaces <= 0:
return
spans = self.spans
new_spaces = " " * spaces
if spans:
end_offset = len(self)
self._spans[:] = [
span.extend(spaces) if span.end >= end_offset else span
for span in spans
]
self._text.append(new_spaces)
self._length += spaces
else:
self.plain += new_spaces
def highlight_regex(
self,
re_highlight: Union[Pattern[str], str],
style: Optional[Union[GetStyleCallable, StyleType]] = None,
*,
style_prefix: str = "",
) -> int:
count = 0
append_span = self._spans.append
_Span = Span
plain = self.plain
if isinstance(re_highlight, str):
re_highlight = re.compile(re_highlight)
for match in re_highlight.finditer(plain):
get_span = match.span
if style:
start, end = get_span()
match_style = style(plain[start:end]) if callable(style) else style
if match_style is not None and end > start:
append_span(_Span(start, end, match_style))
count += 1
for name in match.groupdict().keys():
start, end = get_span(name)
if start != -1 and end > start:
append_span(_Span(start, end, f"{style_prefix}{name}"))
return count
def highlight_words(
self,
words: Iterable[str],
style: Union[str, Style],
*,
case_sensitive: bool = True,
) -> int:
re_words = "|".join(re.escape(word) for word in words)
add_span = self._spans.append
count = 0
_Span = Span
for match in re.finditer(
re_words, self.plain, flags=0 if case_sensitive else re.IGNORECASE
):
start, end = match.span(0)
add_span(_Span(start, end, style))
count += 1
return count
def rstrip(self) -> None:
self.plain = self.plain.rstrip()
def rstrip_end(self, size: int) -> None:
text_length = len(self)
if text_length > size:
excess = text_length - size
whitespace_match = _re_whitespace.search(self.plain)
if whitespace_match is not None:
whitespace_count = len(whitespace_match.group(0))
self.right_crop(min(whitespace_count, excess))
def set_length(self, new_length: int) -> None:
length = len(self)
if length != new_length:
if length < new_length:
self.pad_right(new_length - length)
else:
self.right_crop(length - new_length)
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> Iterable[Segment]:
tab_size: int = console.tab_size if self.tab_size is None else self.tab_size
justify = self.justify or options.justify or DEFAULT_JUSTIFY
overflow = self.overflow or options.overflow or DEFAULT_OVERFLOW
lines = self.wrap(
console,
options.max_width,
justify=justify,
overflow=overflow,
tab_size=tab_size or 8,
no_wrap=pick_bool(self.no_wrap, options.no_wrap, False),
)
all_lines = Text("\n").join(lines)
yield from all_lines.render(console, end=self.end)
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> Measurement:
text = self.plain
lines = text.splitlines()
max_text_width = max(cell_len(line) for line in lines) if lines else 0
words = text.split()
min_text_width = (
max(cell_len(word) for word in words) if words else max_text_width
)
return Measurement(min_text_width, max_text_width)
def render(self, console: "Console", end: str = "") -> Iterable["Segment"]:
_Segment = Segment
text = self.plain
if not self._spans:
yield Segment(text)
if end:
yield _Segment(end)
return
get_style = partial(console.get_style, default=Style.null())
enumerated_spans = list(enumerate(self._spans, 1))
style_map = {index: get_style(span.style) for index, span in enumerated_spans}
style_map[0] = get_style(self.style)
spans = [
(0, False, 0),
*((span.start, False, index) for index, span in enumerated_spans),
*((span.end, True, index) for index, span in enumerated_spans),
(len(text), True, 0),
]
spans.sort(key=itemgetter(0, 1))
stack: List[int] = []
stack_append = stack.append
stack_pop = stack.remove
style_cache: Dict[Tuple[Style, ...], Style] = {}
style_cache_get = style_cache.get
combine = Style.combine
def get_current_style() -> Style:
styles = tuple(style_map[_style_id] for _style_id in sorted(stack))
cached_style = style_cache_get(styles)
if cached_style is not None:
return cached_style
current_style = combine(styles)
style_cache[styles] = current_style
return current_style
for (offset, leaving, style_id), (next_offset, _, _) in zip(spans, spans[1:]):
if leaving:
stack_pop(style_id)
else:
stack_append(style_id)
if next_offset > offset:
yield _Segment(text[offset:next_offset], get_current_style())
if end:
yield _Segment(end)
def join(self, lines: Iterable["Text"]) -> "Text":
new_text = self.blank_copy()
def iter_text() -> Iterable["Text"]:
if self.plain:
for last, line in loop_last(lines):
yield line
if not last:
yield self
else:
yield from lines
extend_text = new_text._text.extend
append_span = new_text._spans.append
extend_spans = new_text._spans.extend
offset = 0
_Span = Span
for text in iter_text():
extend_text(text._text)
if text.style:
append_span(_Span(offset, offset + len(text), text.style))
extend_spans(
_Span(offset + start, offset + end, style)
for start, end, style in text._spans
)
offset += len(text)
new_text._length = offset
return new_text
def expand_tabs(self, tab_size: Optional[int] = None) -> None:
if "\t" not in self.plain:
return
if tab_size is None:
tab_size = self.tab_size
if tab_size is None:
tab_size = 8
new_text: List[Text] = []
append = new_text.append
for line in self.split("\n", include_separator=True):
if "\t" not in line.plain:
append(line)
else:
cell_position = 0
parts = line.split("\t", include_separator=True)
for part in parts:
if part.plain.endswith("\t"):
part._text[-1] = part._text[-1][:-1] + " "
cell_position += part.cell_len
tab_remainder = cell_position % tab_size
if tab_remainder:
spaces = tab_size - tab_remainder
part.extend_style(spaces)
cell_position += spaces
else:
cell_position += part.cell_len
append(part)
result = Text("").join(new_text)
self._text = [result.plain]
self._length = len(self.plain)
self._spans[:] = result._spans
def truncate(
self,
max_width: int,
*,
overflow: Optional["OverflowMethod"] = None,
pad: bool = False,
) -> None:
_overflow = overflow or self.overflow or DEFAULT_OVERFLOW
if _overflow != "ignore":
length = cell_len(self.plain)
if length > max_width:
if _overflow == "ellipsis":
self.plain = set_cell_size(self.plain, max_width - 1) + "…"
else:
self.plain = set_cell_size(self.plain, max_width)
if pad and length < max_width:
spaces = max_width - length
self._text = [f"{self.plain}{' ' * spaces}"]
self._length = len(self.plain)
def _trim_spans(self) -> None:
max_offset = len(self.plain)
_Span = Span
self._spans[:] = [
(
span
if span.end < max_offset
else _Span(span.start, min(max_offset, span.end), span.style)
)
for span in self._spans
if span.start < max_offset
]
def pad(self, count: int, character: str = " ") -> None:
assert len(character) == 1, "Character must be a string of length 1"
if count:
pad_characters = character * count
self.plain = f"{pad_characters}{self.plain}{pad_characters}"
_Span = Span
self._spans[:] = [
_Span(start + count, end + count, style)
for start, end, style in self._spans
]
def pad_left(self, count: int, character: str = " ") -> None:
assert len(character) == 1, "Character must be a string of length 1"
if count:
self.plain = f"{character * count}{self.plain}"
_Span = Span
self._spans[:] = [
_Span(start + count, end + count, style)
for start, end, style in self._spans
]
def pad_right(self, count: int, character: str = " ") -> None:
assert len(character) == 1, "Character must be a string of length 1"
if count:
self.plain = f"{self.plain}{character * count}"
def align(self, align: AlignMethod, width: int, character: str = " ") -> None:
self.truncate(width)
excess_space = width - cell_len(self.plain)
if excess_space:
if align == "left":
self.pad_right(excess_space, character)
elif align == "center":
left = excess_space // 2
self.pad_left(left, character)
self.pad_right(excess_space - left, character)
else:
self.pad_left(excess_space, character)
def append(
self, text: Union["Text", str], style: Optional[Union[str, "Style"]] = None
) -> "Text":
if not isinstance(text, (str, Text)):
raise TypeError("Only str or Text can be appended to Text")
if len(text):
if isinstance(text, str):
sanitized_text = strip_control_codes(text)
self._text.append(sanitized_text)
offset = len(self)
text_length = len(sanitized_text)
if style:
self._spans.append(Span(offset, offset + text_length, style))
self._length += text_length
elif isinstance(text, Text):
_Span = Span
if style is not None:
raise ValueError(
"style must not be set when appending Text instance"
)
text_length = self._length
if text.style:
self._spans.append(
_Span(text_length, text_length + len(text), text.style)
)
self._text.append(text.plain)
self._spans.extend(
_Span(start + text_length, end + text_length, style)
for start, end, style in text._spans.copy()
)
self._length += len(text)
return self
def append_text(self, text: "Text") -> "Text":
_Span = Span
text_length = self._length
if text.style:
self._spans.append(_Span(text_length, text_length + len(text), text.style))
self._text.append(text.plain)
self._spans.extend(
_Span(start + text_length, end + text_length, style)
for start, end, style in text._spans.copy()
)
self._length += len(text)
return self
def append_tokens(
self, tokens: Iterable[Tuple[str, Optional[StyleType]]]
) -> "Text":
append_text = self._text.append
append_span = self._spans.append
_Span = Span
offset = len(self)
for content, style in tokens:
content = strip_control_codes(content)
append_text(content)
if style:
append_span(_Span(offset, offset + len(content), style))
offset += len(content)
self._length = offset
return self
def copy_styles(self, text: "Text") -> None:
self._spans.extend(text._spans)
def split(
self,
separator: str = "\n",
*,
include_separator: bool = False,
allow_blank: bool = False,
) -> Lines:
assert separator, "separator must not be empty"
text = self.plain
if separator not in text:
return Lines([self.copy()])
if include_separator:
lines = self.divide(
match.end() for match in re.finditer(re.escape(separator), text)
)
else:
def flatten_spans() -> Iterable[int]:
for match in re.finditer(re.escape(separator), text):
start, end = match.span()
yield start
yield end
lines = Lines(
line for line in self.divide(flatten_spans()) if line.plain != separator
)
if not allow_blank and text.endswith(separator):
lines.pop()
return lines
def divide(self, offsets: Iterable[int]) -> Lines:
_offsets = list(offsets)
if not _offsets:
return Lines([self.copy()])
text = self.plain
text_length = len(text)
divide_offsets = [0, *_offsets, text_length]
line_ranges = list(zip(divide_offsets, divide_offsets[1:]))
style = self.style
justify = self.justify
overflow = self.overflow
_Text = Text
new_lines = Lines(
_Text(
text[start:end],
style=style,
justify=justify,
overflow=overflow,
)
for start, end in line_ranges
)
if not self._spans:
return new_lines
_line_appends = [line._spans.append for line in new_lines._lines]
line_count = len(line_ranges)
_Span = Span
for span_start, span_end, style in self._spans:
lower_bound = 0
upper_bound = line_count
start_line_no = (lower_bound + upper_bound) // 2
while True:
line_start, line_end = line_ranges[start_line_no]
if span_start < line_start:
upper_bound = start_line_no - 1
elif span_start > line_end:
lower_bound = start_line_no + 1
else:
break
start_line_no = (lower_bound + upper_bound) // 2
if span_end < line_end:
end_line_no = start_line_no
else:
end_line_no = lower_bound = start_line_no
upper_bound = line_count
while True:
line_start, line_end = line_ranges[end_line_no]
if span_end < line_start:
upper_bound = end_line_no - 1
elif span_end > line_end:
lower_bound = end_line_no + 1
else:
break
end_line_no = (lower_bound + upper_bound) // 2
for line_no in range(start_line_no, end_line_no + 1):
line_start, line_end = line_ranges[line_no]
new_start = max(0, span_start - line_start)
new_end = min(span_end - line_start, line_end - line_start)
if new_end > new_start:
_line_appends[line_no](_Span(new_start, new_end, style))
return new_lines
def right_crop(self, amount: int = 1) -> None:
max_offset = len(self.plain) - amount
_Span = Span
self._spans[:] = [
(
span
if span.end < max_offset
else _Span(span.start, min(max_offset, span.end), span.style)
)
for span in self._spans
if span.start < max_offset
]
self._text = [self.plain[:-amount]]
self._length -= amount
def wrap(
self,
console: "Console",
width: int,
*,
justify: Optional["JustifyMethod"] = None,
overflow: Optional["OverflowMethod"] = None,
tab_size: int = 8,
no_wrap: Optional[bool] = None,
) -> Lines:
wrap_justify = justify or self.justify or DEFAULT_JUSTIFY
wrap_overflow = overflow or self.overflow or DEFAULT_OVERFLOW
no_wrap = pick_bool(no_wrap, self.no_wrap, False) or overflow == "ignore"
lines = Lines()
for line in self.split(allow_blank=True):
if "\t" in line:
line.expand_tabs(tab_size)
if no_wrap:
if overflow == "ignore":
lines.append(line)
continue
new_lines = Lines([line])
else:
offsets = divide_line(str(line), width, fold=wrap_overflow == "fold")
new_lines = line.divide(offsets)
for line in new_lines:
line.rstrip_end(width)
if wrap_justify:
new_lines.justify(
console, width, justify=wrap_justify, overflow=wrap_overflow
)
for line in new_lines:
line.truncate(width, overflow=wrap_overflow)
lines.extend(new_lines)
return lines
def fit(self, width: int) -> Lines:
lines: Lines = Lines()
append = lines.append
for line in self.split():
line.set_length(width)
append(line)
return lines
def detect_indentation(self) -> int:
_indentations = {
len(match.group(1))
for match in re.finditer(r"^( *)(.*)$", self.plain, flags=re.MULTILINE)
}
try:
indentation = (
reduce(gcd, [indent for indent in _indentations if not indent % 2]) or 1
)
except TypeError:
indentation = 1
return indentation
def with_indent_guides(
self,
indent_size: Optional[int] = None,
*,
character: str = "│",
style: StyleType = "dim green",
) -> "Text":
_indent_size = self.detect_indentation() if indent_size is None else indent_size
text = self.copy()
text.expand_tabs()
indent_line = f"{character}{' ' * (_indent_size - 1)}"
re_indent = re.compile(r"^( *)(.*)$")
new_lines: List[Text] = []
add_line = new_lines.append
blank_lines = 0
for line in text.split(allow_blank=True):
match = re_indent.match(line.plain)
if not match or not match.group(2):
blank_lines += 1
continue
indent = match.group(1)
full_indents, remaining_space = divmod(len(indent), _indent_size)
new_indent = f"{indent_line * full_indents}{' ' * remaining_space}"
line.plain = new_indent + line.plain[len(new_indent) :]
line.stylize(style, 0, len(new_indent))
if blank_lines:
new_lines.extend([Text(new_indent, style=style)] * blank_lines)
blank_lines = 0
add_line(line)
if blank_lines:
new_lines.extend([Text("", style=style)] * blank_lines)
new_text = text.blank_copy("\n").join(new_lines)
return new_text
if __name__ == "__main__": # pragma: no cover
from rich.console import Console
text = Text(
"""\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n"""
)
text.highlight_words(["Lorem"], "bold")
text.highlight_words(["ipsum"], "italic")
console = Console()
console.rule("justify='left'")
console.print(text, style="red")
console.print()
console.rule("justify='center'")
console.print(text, style="green", justify="center")
console.print()
console.rule("justify='right'")
console.print(text, style="blue", justify="right")
console.print()
console.rule("justify='full'")
console.print(text, style="magenta", justify="full")
console.print() | --- +++ @@ -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 offset."""
if offset < self.start:
return self, None
@@ -72,16 +74,40 @@ return span1, span2
def move(self, offset: int) -> "Span":
+ """Move start and end by a given offset.
+
+ Args:
+ offset (int): Number of characters to add to start and end.
+
+ Returns:
+ TextSpan: A new TextSpan with adjusted position.
+ """
start, end, style = self
return Span(start + offset, end + offset, style)
def right_crop(self, offset: int) -> "Span":
+ """Crop the span at the given offset.
+
+ Args:
+ offset (int): A value between start and end.
+
+ Returns:
+ Span: A new (possibly smaller) span.
+ """
start, end, style = self
if offset >= end:
return self
return Span(start, min(offset, end), style)
def extend(self, cells: int) -> "Span":
+ """Extend the span by the given number of cells.
+
+ Args:
+ cells (int): Additional space to add to end of span.
+
+ Returns:
+ Span: A span.
+ """
if cells:
start, end, style = self
return Span(start, end + cells, style)
@@ -90,6 +116,18 @@
class Text(JupyterMixin):
+ """Text with color / style.
+
+ Args:
+ text (str, optional): Default unstyled text. Defaults to "".
+ style (Union[str, Style], optional): Base style for text. Defaults to "".
+ justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
+ overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
+ no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.
+ end (str, optional): Character to end text with. Defaults to "\\\\n".
+ tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None.
+ spans (List[Span], optional). A list of predefined style spans. Defaults to None.
+ """
__slots__ = [
"_text",
@@ -185,10 +223,16 @@
@property
def cell_len(self) -> int:
+ """Get the number of cells required to render this text."""
return cell_len(self.plain)
@property
def markup(self) -> str:
+ """Get console markup to render this Text.
+
+ Returns:
+ str: A string potentially creating markup tags.
+ """
from .markup import escape
output: List[str] = []
@@ -224,6 +268,20 @@ overflow: Optional["OverflowMethod"] = None,
end: str = "\n",
) -> "Text":
+ """Create Text instance from markup.
+
+ Args:
+ text (str): A string containing console markup.
+ style (Union[str, Style], optional): Base style for text. Defaults to "".
+ emoji (bool, optional): Also render emoji code. Defaults to True.
+ emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None.
+ justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
+ overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
+ end (str, optional): Character to end text with. Defaults to "\\\\n".
+
+ Returns:
+ Text: A Text instance with markup rendered.
+ """
from .markup import render
rendered_text = render(text, style, emoji=emoji, emoji_variant=emoji_variant)
@@ -244,6 +302,17 @@ end: str = "\n",
tab_size: Optional[int] = 8,
) -> "Text":
+ """Create a Text object from a string containing ANSI escape codes.
+
+ Args:
+ text (str): A string containing escape codes.
+ style (Union[str, Style], optional): Base style for text. Defaults to "".
+ justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
+ overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
+ no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.
+ end (str, optional): Character to end text with. Defaults to "\\\\n".
+ tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None.
+ """
from .ansi import AnsiDecoder
joiner = Text(
@@ -268,6 +337,18 @@ justify: Optional["JustifyMethod"] = None,
overflow: Optional["OverflowMethod"] = None,
) -> "Text":
+ """Construct a Text instance with a pre-applied styled. A style applied in this way won't be used
+ to pad the text when it is justified.
+
+ Args:
+ text (str): A string containing console markup.
+ style (Union[str, Style]): Style to apply to the text. Defaults to "".
+ justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
+ overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
+
+ Returns:
+ Text: A text instance with a style applied to the entire string.
+ """
styled_text = cls(text, justify=justify, overflow=overflow)
styled_text.stylize(style)
return styled_text
@@ -284,6 +365,21 @@ tab_size: int = 8,
meta: Optional[Dict[str, Any]] = None,
) -> "Text":
+ """Construct a text instance by combining a sequence of strings with optional styles.
+ The positional arguments should be either strings, or a tuple of string + style.
+
+ Args:
+ style (Union[str, Style], optional): Base style for text. Defaults to "".
+ justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
+ overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
+ no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.
+ end (str, optional): Character to end text with. Defaults to "\\\\n".
+ tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None.
+ meta (Dict[str, Any], optional). Meta data to apply to text, or None for no meta data. Default to None
+
+ Returns:
+ Text: A new text instance.
+ """
text = cls(
style=style,
justify=justify,
@@ -305,12 +401,14 @@
@property
def plain(self) -> str:
+ """Get the text as a single string."""
if len(self._text) != 1:
self._text[:] = ["".join(self._text)]
return self._text[0]
@plain.setter
def plain(self, new_text: str) -> None:
+ """Set the text to a new value."""
if new_text != self.plain:
sanitized_text = strip_control_codes(new_text)
self._text[:] = [sanitized_text]
@@ -321,13 +419,16 @@
@property
def spans(self) -> List[Span]:
+ """Get a reference to the internal list of spans."""
return self._spans
@spans.setter
def spans(self, spans: List[Span]) -> None:
+ """Set spans."""
self._spans = spans[:]
def blank_copy(self, plain: str = "") -> "Text":
+ """Return a new Text instance with copied metadata (but not the string or spans)."""
copy_self = Text(
plain,
style=self.style,
@@ -340,6 +441,7 @@ return copy_self
def copy(self) -> "Text":
+ """Return a copy of this instance."""
copy_self = Text(
self.plain,
style=self.style,
@@ -358,6 +460,13 @@ start: int = 0,
end: Optional[int] = None,
) -> None:
+ """Apply a style to the text, or a portion of the text.
+
+ Args:
+ style (Union[str, Style]): Style instance or style definition to apply.
+ start (int): Start offset (negative indexing is supported). Defaults to 0.
+ end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.
+ """
if style:
length = len(self)
if start < 0:
@@ -377,6 +486,13 @@ start: int = 0,
end: Optional[int] = None,
) -> None:
+ """Apply a style to the text, or a portion of the text. Styles will be applied before other styles already present.
+
+ Args:
+ style (Union[str, Style]): Style instance or style definition to apply.
+ start (int): Start offset (negative indexing is supported). Defaults to 0.
+ end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.
+ """
if style:
length = len(self)
if start < 0:
@@ -393,20 +509,56 @@ def apply_meta(
self, meta: Dict[str, Any], start: int = 0, end: Optional[int] = None
) -> None:
+ """Apply metadata to the text, or a portion of the text.
+
+ Args:
+ meta (Dict[str, Any]): A dict of meta information.
+ start (int): Start offset (negative indexing is supported). Defaults to 0.
+ end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.
+
+ """
style = Style.from_meta(meta)
self.stylize(style, start=start, end=end)
def on(self, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> "Text":
+ """Apply event handlers (used by Textual project).
+
+ Example:
+ >>> from rich.text import Text
+ >>> text = Text("hello world")
+ >>> text.on(click="view.toggle('world')")
+
+ Args:
+ meta (Dict[str, Any]): Mapping of meta information.
+ **handlers: Keyword args are prefixed with "@" to defined handlers.
+
+ Returns:
+ Text: Self is returned to method may be chained.
+ """
meta = {} if meta is None else meta
meta.update({f"@{key}": value for key, value in handlers.items()})
self.stylize(Style.from_meta(meta))
return self
def remove_suffix(self, suffix: str) -> None:
+ """Remove a suffix if it exists.
+
+ Args:
+ suffix (str): Suffix to remove.
+ """
if self.plain.endswith(suffix):
self.right_crop(len(suffix))
def get_style_at_offset(self, console: "Console", offset: int) -> Style:
+ """Get the style of a character at give offset.
+
+ Args:
+ console (~Console): Console where text will be rendered.
+ offset (int): Offset in to text (negative indexing supported)
+
+ Returns:
+ Style: A Style instance.
+ """
# TODO: This is a little inefficient, it is only used by full justify
if offset < 0:
offset = len(self) + offset
@@ -418,6 +570,11 @@ return style
def extend_style(self, spaces: int) -> None:
+ """Extend the Text given number of spaces where the spaces have the same style as the last character.
+
+ Args:
+ spaces (int): Number of spaces to add to the Text.
+ """
if spaces <= 0:
return
spans = self.spans
@@ -440,6 +597,18 @@ *,
style_prefix: str = "",
) -> int:
+ """Highlight text with a regular expression, where group names are
+ translated to styles.
+
+ Args:
+ re_highlight (Union[re.Pattern, str]): A regular expression object or string.
+ style (Union[GetStyleCallable, StyleType]): Optional style to apply to whole match, or a callable
+ which accepts the matched text and returns a style. Defaults to None.
+ style_prefix (str, optional): Optional prefix to add to style group names.
+
+ Returns:
+ int: Number of regex matches
+ """
count = 0
append_span = self._spans.append
_Span = Span
@@ -468,6 +637,16 @@ *,
case_sensitive: bool = True,
) -> int:
+ """Highlight words with a style.
+
+ Args:
+ words (Iterable[str]): Words to highlight.
+ style (Union[str, Style]): Style to apply.
+ case_sensitive (bool, optional): Enable case sensitive matching. Defaults to True.
+
+ Returns:
+ int: Number of words highlighted.
+ """
re_words = "|".join(re.escape(word) for word in words)
add_span = self._spans.append
count = 0
@@ -481,9 +660,15 @@ return count
def rstrip(self) -> None:
+ """Strip whitespace from end of text."""
self.plain = self.plain.rstrip()
def rstrip_end(self, size: int) -> None:
+ """Remove whitespace beyond a certain width at the end of the text.
+
+ Args:
+ size (int): The desired size of the text.
+ """
text_length = len(self)
if text_length > size:
excess = text_length - size
@@ -493,6 +678,7 @@ self.right_crop(min(whitespace_count, excess))
def set_length(self, new_length: int) -> None:
+ """Set new length of the text, clipping or padding is required."""
length = len(self)
if length != new_length:
if length < new_length:
@@ -531,6 +717,15 @@ return Measurement(min_text_width, max_text_width)
def render(self, console: "Console", end: str = "") -> Iterable["Segment"]:
+ """Render the text as Segments.
+
+ Args:
+ console (Console): Console instance.
+ end (Optional[str], optional): Optional end character.
+
+ Returns:
+ Iterable[Segment]: Result of render that may be written to the console.
+ """
_Segment = Segment
text = self.plain
if not self._spans:
@@ -561,6 +756,7 @@ combine = Style.combine
def get_current_style() -> Style:
+ """Construct current style from stack."""
styles = tuple(style_map[_style_id] for _style_id in sorted(stack))
cached_style = style_cache_get(styles)
if cached_style is not None:
@@ -580,6 +776,14 @@ yield _Segment(end)
def join(self, lines: Iterable["Text"]) -> "Text":
+ """Join text together with this instance as the separator.
+
+ Args:
+ lines (Iterable[Text]): An iterable of Text instances to join.
+
+ Returns:
+ Text: A new text instance containing join text.
+ """
new_text = self.blank_copy()
@@ -611,6 +815,12 @@ return new_text
def expand_tabs(self, tab_size: Optional[int] = None) -> None:
+ """Converts tabs to spaces.
+
+ Args:
+ tab_size (int, optional): Size of tabs. Defaults to 8.
+
+ """
if "\t" not in self.plain:
return
if tab_size is None:
@@ -653,6 +863,13 @@ overflow: Optional["OverflowMethod"] = None,
pad: bool = False,
) -> None:
+ """Truncate text if it is longer that a given width.
+
+ Args:
+ max_width (int): Maximum number of characters in text.
+ overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None, to use self.overflow.
+ pad (bool, optional): Pad with spaces if the length is less than max_width. Defaults to False.
+ """
_overflow = overflow or self.overflow or DEFAULT_OVERFLOW
if _overflow != "ignore":
length = cell_len(self.plain)
@@ -667,6 +884,7 @@ self._length = len(self.plain)
def _trim_spans(self) -> None:
+ """Remove or modify any spans that are over the end of the text."""
max_offset = len(self.plain)
_Span = Span
self._spans[:] = [
@@ -680,6 +898,12 @@ ]
def pad(self, count: int, character: str = " ") -> None:
+ """Pad left and right with a given number of characters.
+
+ Args:
+ count (int): Width of padding.
+ character (str): The character to pad with. Must be a string of length 1.
+ """
assert len(character) == 1, "Character must be a string of length 1"
if count:
pad_characters = character * count
@@ -691,6 +915,12 @@ ]
def pad_left(self, count: int, character: str = " ") -> None:
+ """Pad the left with a given character.
+
+ Args:
+ count (int): Number of characters to pad.
+ character (str, optional): Character to pad with. Defaults to " ".
+ """
assert len(character) == 1, "Character must be a string of length 1"
if count:
self.plain = f"{character * count}{self.plain}"
@@ -701,11 +931,24 @@ ]
def pad_right(self, count: int, character: str = " ") -> None:
+ """Pad the right with a given character.
+
+ Args:
+ count (int): Number of characters to pad.
+ character (str, optional): Character to pad with. Defaults to " ".
+ """
assert len(character) == 1, "Character must be a string of length 1"
if count:
self.plain = f"{self.plain}{character * count}"
def align(self, align: AlignMethod, width: int, character: str = " ") -> None:
+ """Align text to a given width.
+
+ Args:
+ align (AlignMethod): One of "left", "center", or "right".
+ width (int): Desired width.
+ character (str, optional): Character to pad with. Defaults to " ".
+ """
self.truncate(width)
excess_space = width - cell_len(self.plain)
if excess_space:
@@ -721,6 +964,15 @@ def append(
self, text: Union["Text", str], style: Optional[Union[str, "Style"]] = None
) -> "Text":
+ """Add text with an optional style.
+
+ Args:
+ text (Union[Text, str]): A str or Text to append.
+ style (str, optional): A style name. Defaults to None.
+
+ Returns:
+ Text: Returns self for chaining.
+ """
if not isinstance(text, (str, Text)):
raise TypeError("Only str or Text can be appended to Text")
@@ -754,6 +1006,15 @@ return self
def append_text(self, text: "Text") -> "Text":
+ """Append another Text instance. This method is more performant than Text.append, but
+ only works for Text.
+
+ Args:
+ text (Text): The Text instance to append to this instance.
+
+ Returns:
+ Text: Returns self for chaining.
+ """
_Span = Span
text_length = self._length
if text.style:
@@ -769,6 +1030,14 @@ def append_tokens(
self, tokens: Iterable[Tuple[str, Optional[StyleType]]]
) -> "Text":
+ """Append iterable of str and style. Style may be a Style instance or a str style definition.
+
+ Args:
+ tokens (Iterable[Tuple[str, Optional[StyleType]]]): An iterable of tuples containing str content and style.
+
+ Returns:
+ Text: Returns self for chaining.
+ """
append_text = self._text.append
append_span = self._spans.append
_Span = Span
@@ -783,6 +1052,11 @@ return self
def copy_styles(self, text: "Text") -> None:
+ """Copy styles from another Text instance.
+
+ Args:
+ text (Text): A Text instance to copy styles from, must be the same length.
+ """
self._spans.extend(text._spans)
def split(
@@ -792,6 +1066,16 @@ include_separator: bool = False,
allow_blank: bool = False,
) -> Lines:
+ """Split rich text in to lines, preserving styles.
+
+ Args:
+ separator (str, optional): String to split on. Defaults to "\\\\n".
+ include_separator (bool, optional): Include the separator in the lines. Defaults to False.
+ allow_blank (bool, optional): Return a blank line if the text ends with a separator. Defaults to False.
+
+ Returns:
+ List[RichText]: A list of rich text, one per line of the original.
+ """
assert separator, "separator must not be empty"
text = self.plain
@@ -820,6 +1104,14 @@ return lines
def divide(self, offsets: Iterable[int]) -> Lines:
+ """Divide text into a number of lines at given offsets.
+
+ Args:
+ offsets (Iterable[int]): Offsets used to divide text.
+
+ Returns:
+ Lines: New RichText instances between offsets.
+ """
_offsets = list(offsets)
if not _offsets:
@@ -891,6 +1183,7 @@ return new_lines
def right_crop(self, amount: int = 1) -> None:
+ """Remove a number of characters from the end of the text."""
max_offset = len(self.plain) - amount
_Span = Span
self._spans[:] = [
@@ -915,6 +1208,19 @@ tab_size: int = 8,
no_wrap: Optional[bool] = None,
) -> Lines:
+ """Word wrap the text.
+
+ Args:
+ console (Console): Console instance.
+ width (int): Number of cells available per line.
+ justify (str, optional): Justify method: "default", "left", "center", "full", "right". Defaults to "default".
+ overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None.
+ tab_size (int, optional): Default tab size. Defaults to 8.
+ no_wrap (bool, optional): Disable wrapping, Defaults to False.
+
+ Returns:
+ Lines: Number of lines.
+ """
wrap_justify = justify or self.justify or DEFAULT_JUSTIFY
wrap_overflow = overflow or self.overflow or DEFAULT_OVERFLOW
@@ -944,6 +1250,14 @@ return lines
def fit(self, width: int) -> Lines:
+ """Fit the text in to given width by chopping in to lines.
+
+ Args:
+ width (int): Maximum characters in a line.
+
+ Returns:
+ Lines: Lines container.
+ """
lines: Lines = Lines()
append = lines.append
for line in self.split():
@@ -952,6 +1266,11 @@ return lines
def detect_indentation(self) -> int:
+ """Auto-detect indentation of code.
+
+ Returns:
+ int: Number of spaces used to indent code.
+ """
_indentations = {
len(match.group(1))
@@ -974,6 +1293,16 @@ character: str = "│",
style: StyleType = "dim green",
) -> "Text":
+ """Adds indent guide lines to text.
+
+ Args:
+ indent_size (Optional[int]): Size of indentation, or None to auto detect. Defaults to None.
+ character (str, optional): Character to use for indentation. Defaults to "│".
+ style (Union[Style, str], optional): Style of indent guides.
+
+ Returns:
+ Text: New text with indentation guides.
+ """
_indent_size = self.detect_indentation() if indent_size is None else indent_size
@@ -1031,4 +1360,4 @@
console.rule("justify='full'")
console.print(text, style="magenta", justify="full")
- console.print()+ console.print()
| 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,
Tuple,
Type,
Union,
)
from pygments.lexers import guess_lexer_for_filename
from pygments.token import Comment, Keyword, Name, Number, Operator, String
from pygments.token import Text as TextToken
from pygments.token import Token
from pygments.util import ClassNotFound
from . import pretty
from ._loop import loop_first_last, loop_last
from .columns import Columns
from .console import (
Console,
ConsoleOptions,
ConsoleRenderable,
OverflowMethod,
Group,
RenderResult,
group,
)
from .constrain import Constrain
from .highlighter import RegexHighlighter, ReprHighlighter
from .panel import Panel
from .scope import render_scope
from .style import Style
from .syntax import Syntax, SyntaxPosition
from .text import Text
from .theme import Theme
WINDOWS = sys.platform == "win32"
LOCALS_MAX_LENGTH = 10
LOCALS_MAX_STRING = 80
def _iter_syntax_lines(
start: SyntaxPosition, end: SyntaxPosition
) -> Iterable[Tuple[int, int, int]]:
line1, column1 = start
line2, column2 = end
if line1 == line2:
yield line1, column1, column2
else:
for first, last, line_no in loop_first_last(range(line1, line2 + 1)):
if first:
yield line_no, column1, -1
elif last:
yield line_no, 0, column2
else:
yield line_no, 0, -1
def install(
*,
console: Optional[Console] = None,
width: Optional[int] = 100,
code_width: Optional[int] = 88,
extra_lines: int = 3,
theme: Optional[str] = None,
word_wrap: bool = False,
show_locals: bool = False,
locals_max_length: int = LOCALS_MAX_LENGTH,
locals_max_string: int = LOCALS_MAX_STRING,
locals_max_depth: Optional[int] = None,
locals_hide_dunder: bool = True,
locals_hide_sunder: Optional[bool] = None,
locals_overflow: Optional[OverflowMethod] = None,
indent_guides: bool = True,
suppress: Iterable[Union[str, ModuleType]] = (),
max_frames: int = 100,
) -> Callable[[Type[BaseException], BaseException, Optional[TracebackType]], Any]:
traceback_console = Console(stderr=True) if console is None else console
locals_hide_sunder = (
True
if (traceback_console.is_jupyter and locals_hide_sunder is None)
else locals_hide_sunder
)
def excepthook(
type_: Type[BaseException],
value: BaseException,
traceback: Optional[TracebackType],
) -> None:
exception_traceback = Traceback.from_exception(
type_,
value,
traceback,
width=width,
code_width=code_width,
extra_lines=extra_lines,
theme=theme,
word_wrap=word_wrap,
show_locals=show_locals,
locals_max_length=locals_max_length,
locals_max_string=locals_max_string,
locals_max_depth=locals_max_depth,
locals_hide_dunder=locals_hide_dunder,
locals_hide_sunder=bool(locals_hide_sunder),
locals_overflow=locals_overflow,
indent_guides=indent_guides,
suppress=suppress,
max_frames=max_frames,
)
traceback_console.print(exception_traceback)
def ipy_excepthook_closure(ip: Any) -> None: # pragma: no cover
tb_data = {} # store information about showtraceback call
default_showtraceback = ip.showtraceback # keep reference of default traceback
def ipy_show_traceback(*args: Any, **kwargs: Any) -> None:
nonlocal tb_data
tb_data = kwargs
default_showtraceback(*args, **kwargs)
def ipy_display_traceback(
*args: Any, is_syntax: bool = False, **kwargs: Any
) -> None:
nonlocal tb_data
exc_tuple = ip._get_exc_info()
# do not display trace on syntax error
tb: Optional[TracebackType] = None if is_syntax else exc_tuple[2]
# determine correct tb_offset
compiled = tb_data.get("running_compiled_code", False)
tb_offset = tb_data.get("tb_offset")
if tb_offset is None:
tb_offset = 1 if compiled else 0
# remove ipython internal frames from trace with tb_offset
for _ in range(tb_offset):
if tb is None:
break
tb = tb.tb_next
excepthook(exc_tuple[0], exc_tuple[1], tb)
tb_data = {} # clear data upon usage
# replace _showtraceback instead of showtraceback to allow ipython features such as debugging to work
# this is also what the ipython docs recommends to modify when subclassing InteractiveShell
ip._showtraceback = ipy_display_traceback
# add wrapper to capture tb_data
ip.showtraceback = ipy_show_traceback
ip.showsyntaxerror = lambda *args, **kwargs: ipy_display_traceback(
*args, is_syntax=True, **kwargs
)
try: # pragma: no cover
# if within ipython, use customized traceback
ip = get_ipython() # type: ignore[name-defined]
ipy_excepthook_closure(ip)
return sys.excepthook
except Exception:
# otherwise use default system hook
old_excepthook = sys.excepthook
sys.excepthook = excepthook
return old_excepthook
@dataclass
class Frame:
filename: str
lineno: int
name: str
line: str = ""
locals: Optional[Dict[str, pretty.Node]] = None
last_instruction: Optional[Tuple[Tuple[int, int], Tuple[int, int]]] = None
@dataclass
class _SyntaxError:
offset: int
filename: str
line: str
lineno: int
msg: str
notes: List[str] = field(default_factory=list)
@dataclass
class Stack:
exc_type: str
exc_value: str
syntax_error: Optional[_SyntaxError] = None
is_cause: bool = False
frames: List[Frame] = field(default_factory=list)
notes: List[str] = field(default_factory=list)
is_group: bool = False
exceptions: List["Trace"] = field(default_factory=list)
@dataclass
class Trace:
stacks: List[Stack]
class PathHighlighter(RegexHighlighter):
highlights = [r"(?P<dim>.*/)(?P<bold>.+)"]
class Traceback:
LEXERS = {
"": "text",
".py": "python",
".pxd": "cython",
".pyx": "cython",
".pxi": "pyrex",
}
def __init__(
self,
trace: Optional[Trace] = None,
*,
width: Optional[int] = 100,
code_width: Optional[int] = 88,
extra_lines: int = 3,
theme: Optional[str] = None,
word_wrap: bool = False,
show_locals: bool = False,
locals_max_length: int = LOCALS_MAX_LENGTH,
locals_max_string: int = LOCALS_MAX_STRING,
locals_max_depth: Optional[int] = None,
locals_hide_dunder: bool = True,
locals_hide_sunder: bool = False,
locals_overlow: Optional[OverflowMethod] = None,
indent_guides: bool = True,
suppress: Iterable[Union[str, ModuleType]] = (),
max_frames: int = 100,
):
if trace is None:
exc_type, exc_value, traceback = sys.exc_info()
if exc_type is None or exc_value is None or traceback is None:
raise ValueError(
"Value for 'trace' required if not called in except: block"
)
trace = self.extract(
exc_type, exc_value, traceback, show_locals=show_locals
)
self.trace = trace
self.width = width
self.code_width = code_width
self.extra_lines = extra_lines
self.theme = Syntax.get_theme(theme or "ansi_dark")
self.word_wrap = word_wrap
self.show_locals = show_locals
self.indent_guides = indent_guides
self.locals_max_length = locals_max_length
self.locals_max_string = locals_max_string
self.locals_max_depth = locals_max_depth
self.locals_hide_dunder = locals_hide_dunder
self.locals_hide_sunder = locals_hide_sunder
self.locals_overflow = locals_overlow
self.suppress: Sequence[str] = []
for suppress_entity in suppress:
if not isinstance(suppress_entity, str):
assert (
suppress_entity.__file__ is not None
), f"{suppress_entity!r} must be a module with '__file__' attribute"
path = os.path.dirname(suppress_entity.__file__)
else:
path = suppress_entity
path = os.path.normpath(os.path.abspath(path))
self.suppress.append(path)
self.max_frames = max(4, max_frames) if max_frames > 0 else 0
@classmethod
def from_exception(
cls,
exc_type: Type[Any],
exc_value: BaseException,
traceback: Optional[TracebackType],
*,
width: Optional[int] = 100,
code_width: Optional[int] = 88,
extra_lines: int = 3,
theme: Optional[str] = None,
word_wrap: bool = False,
show_locals: bool = False,
locals_max_length: int = LOCALS_MAX_LENGTH,
locals_max_string: int = LOCALS_MAX_STRING,
locals_max_depth: Optional[int] = None,
locals_hide_dunder: bool = True,
locals_hide_sunder: bool = False,
locals_overflow: Optional[OverflowMethod] = None,
indent_guides: bool = True,
suppress: Iterable[Union[str, ModuleType]] = (),
max_frames: int = 100,
) -> "Traceback":
rich_traceback = cls.extract(
exc_type,
exc_value,
traceback,
show_locals=show_locals,
locals_max_length=locals_max_length,
locals_max_string=locals_max_string,
locals_max_depth=locals_max_depth,
locals_hide_dunder=locals_hide_dunder,
locals_hide_sunder=locals_hide_sunder,
)
return cls(
rich_traceback,
width=width,
code_width=code_width,
extra_lines=extra_lines,
theme=theme,
word_wrap=word_wrap,
show_locals=show_locals,
indent_guides=indent_guides,
locals_max_length=locals_max_length,
locals_max_string=locals_max_string,
locals_max_depth=locals_max_depth,
locals_hide_dunder=locals_hide_dunder,
locals_hide_sunder=locals_hide_sunder,
locals_overlow=locals_overflow,
suppress=suppress,
max_frames=max_frames,
)
@classmethod
def extract(
cls,
exc_type: Type[BaseException],
exc_value: BaseException,
traceback: Optional[TracebackType],
*,
show_locals: bool = False,
locals_max_length: int = LOCALS_MAX_LENGTH,
locals_max_string: int = LOCALS_MAX_STRING,
locals_max_depth: Optional[int] = None,
locals_hide_dunder: bool = True,
locals_hide_sunder: bool = False,
_visited_exceptions: Optional[Set[BaseException]] = None,
) -> Trace:
stacks: List[Stack] = []
is_cause = False
from rich import _IMPORT_CWD
notes: List[str] = getattr(exc_value, "__notes__", None) or []
grouped_exceptions: Set[BaseException] = (
set() if _visited_exceptions is None else _visited_exceptions
)
def safe_str(_object: Any) -> str:
try:
return str(_object)
except Exception:
return "<exception str() failed>"
while True:
stack = Stack(
exc_type=safe_str(exc_type.__name__),
exc_value=safe_str(exc_value),
is_cause=is_cause,
notes=notes,
)
if sys.version_info >= (3, 11):
if isinstance(exc_value, (BaseExceptionGroup, ExceptionGroup)):
stack.is_group = True
for exception in exc_value.exceptions:
if exception in grouped_exceptions:
continue
grouped_exceptions.add(exception)
stack.exceptions.append(
Traceback.extract(
type(exception),
exception,
exception.__traceback__,
show_locals=show_locals,
locals_max_length=locals_max_length,
locals_hide_dunder=locals_hide_dunder,
locals_hide_sunder=locals_hide_sunder,
_visited_exceptions=grouped_exceptions,
)
)
if isinstance(exc_value, SyntaxError):
stack.syntax_error = _SyntaxError(
offset=exc_value.offset or 0,
filename=exc_value.filename or "?",
lineno=exc_value.lineno or 0,
line=exc_value.text or "",
msg=exc_value.msg,
notes=notes,
)
stacks.append(stack)
append = stack.frames.append
def get_locals(
iter_locals: Iterable[Tuple[str, object]],
) -> Iterable[Tuple[str, object]]:
if not (locals_hide_dunder or locals_hide_sunder):
yield from iter_locals
return
for key, value in iter_locals:
if locals_hide_dunder and key.startswith("__"):
continue
if locals_hide_sunder and key.startswith("_"):
continue
yield key, value
for frame_summary, line_no in walk_tb(traceback):
filename = frame_summary.f_code.co_filename
last_instruction: Optional[Tuple[Tuple[int, int], Tuple[int, int]]]
last_instruction = None
if sys.version_info >= (3, 11):
instruction_index = frame_summary.f_lasti // 2
instruction_position = next(
islice(
frame_summary.f_code.co_positions(),
instruction_index,
instruction_index + 1,
)
)
(
start_line,
end_line,
start_column,
end_column,
) = instruction_position
if (
start_line is not None
and end_line is not None
and start_column is not None
and end_column is not None
):
last_instruction = (
(start_line, start_column),
(end_line, end_column),
)
if filename and not filename.startswith("<"):
if not os.path.isabs(filename):
filename = os.path.join(_IMPORT_CWD, filename)
if frame_summary.f_locals.get("_rich_traceback_omit", False):
continue
frame = Frame(
filename=filename or "?",
lineno=line_no,
name=frame_summary.f_code.co_name,
locals=(
{
key: pretty.traverse(
value,
max_length=locals_max_length,
max_string=locals_max_string,
max_depth=locals_max_depth,
)
for key, value in get_locals(frame_summary.f_locals.items())
if not (inspect.isfunction(value) or inspect.isclass(value))
}
if show_locals
else None
),
last_instruction=last_instruction,
)
append(frame)
if frame_summary.f_locals.get("_rich_traceback_guard", False):
del stack.frames[:]
if not grouped_exceptions:
cause = getattr(exc_value, "__cause__", None)
if cause is not None and cause is not exc_value:
exc_type = cause.__class__
exc_value = cause
# __traceback__ can be None, e.g. for exceptions raised by the
# 'multiprocessing' module
traceback = cause.__traceback__
is_cause = True
continue
cause = exc_value.__context__
if cause is not None and not getattr(
exc_value, "__suppress_context__", False
):
exc_type = cause.__class__
exc_value = cause
traceback = cause.__traceback__
is_cause = False
continue
# No cover, code is reached but coverage doesn't recognize it.
break # pragma: no cover
trace = Trace(stacks=stacks)
return trace
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
theme = self.theme
background_style = theme.get_background_style()
token_style = theme.get_style_for_token
traceback_theme = Theme(
{
"pretty": token_style(TextToken),
"pygments.text": token_style(Token),
"pygments.string": token_style(String),
"pygments.function": token_style(Name.Function),
"pygments.number": token_style(Number),
"repr.indent": token_style(Comment) + Style(dim=True),
"repr.str": token_style(String),
"repr.brace": token_style(TextToken) + Style(bold=True),
"repr.number": token_style(Number),
"repr.bool_true": token_style(Keyword.Constant),
"repr.bool_false": token_style(Keyword.Constant),
"repr.none": token_style(Keyword.Constant),
"scope.border": token_style(String.Delimiter),
"scope.equals": token_style(Operator),
"scope.key": token_style(Name),
"scope.key.special": token_style(Name.Constant) + Style(dim=True),
},
inherit=False,
)
highlighter = ReprHighlighter()
@group()
def render_stack(stack: Stack, last: bool) -> RenderResult:
if stack.frames:
stack_renderable: ConsoleRenderable = Panel(
self._render_stack(stack),
title="[traceback.title]Traceback [dim](most recent call last)",
style=background_style,
border_style="traceback.border",
expand=True,
padding=(0, 1),
)
stack_renderable = Constrain(stack_renderable, self.width)
with console.use_theme(traceback_theme):
yield stack_renderable
if stack.syntax_error is not None:
with console.use_theme(traceback_theme):
yield Constrain(
Panel(
self._render_syntax_error(stack.syntax_error),
style=background_style,
border_style="traceback.border.syntax_error",
expand=True,
padding=(0, 1),
width=self.width,
),
self.width,
)
yield Text.assemble(
(f"{stack.exc_type}: ", "traceback.exc_type"),
highlighter(stack.syntax_error.msg),
)
elif stack.exc_value:
yield Text.assemble(
(f"{stack.exc_type}: ", "traceback.exc_type"),
highlighter(stack.exc_value),
)
else:
yield Text.assemble((f"{stack.exc_type}", "traceback.exc_type"))
for note in stack.notes:
yield Text.assemble(("[NOTE] ", "traceback.note"), highlighter(note))
if stack.is_group:
for group_no, group_exception in enumerate(stack.exceptions, 1):
grouped_exceptions: List[Group] = []
for group_last, group_stack in loop_last(group_exception.stacks):
grouped_exceptions.append(render_stack(group_stack, group_last))
yield ""
yield Constrain(
Panel(
Group(*grouped_exceptions),
title=f"Sub-exception #{group_no}",
border_style="traceback.group.border",
),
self.width,
)
if not last:
if stack.is_cause:
yield Text.from_markup(
"\n[i]The above exception was the direct cause of the following exception:\n",
)
else:
yield Text.from_markup(
"\n[i]During handling of the above exception, another exception occurred:\n",
)
for last, stack in loop_last(reversed(self.trace.stacks)):
yield render_stack(stack, last)
@group()
def _render_syntax_error(self, syntax_error: _SyntaxError) -> RenderResult:
highlighter = ReprHighlighter()
path_highlighter = PathHighlighter()
if syntax_error.filename != "<stdin>":
if os.path.exists(syntax_error.filename):
text = Text.assemble(
(f" {syntax_error.filename}", "pygments.string"),
(":", "pygments.text"),
(str(syntax_error.lineno), "pygments.number"),
style="pygments.text",
)
yield path_highlighter(text)
syntax_error_text = highlighter(syntax_error.line.rstrip())
syntax_error_text.no_wrap = True
offset = min(syntax_error.offset - 1, len(syntax_error_text))
syntax_error_text.stylize("bold underline", offset, offset)
syntax_error_text += Text.from_markup(
"\n" + " " * offset + "[traceback.offset]▲[/]",
style="pygments.text",
)
yield syntax_error_text
@classmethod
def _guess_lexer(cls, filename: str, code: str) -> str:
ext = os.path.splitext(filename)[-1]
if not ext:
# No extension, look at first line to see if it is a hashbang
# Note, this is an educated guess and not a guarantee
# If it fails, the only downside is that the code is highlighted strangely
new_line_index = code.index("\n")
first_line = code[:new_line_index] if new_line_index != -1 else code
if first_line.startswith("#!") and "python" in first_line.lower():
return "python"
try:
return cls.LEXERS.get(ext) or guess_lexer_for_filename(filename, code).name
except ClassNotFound:
return "text"
@group()
def _render_stack(self, stack: Stack) -> RenderResult:
path_highlighter = PathHighlighter()
theme = self.theme
def render_locals(frame: Frame) -> Iterable[ConsoleRenderable]:
if frame.locals:
yield render_scope(
frame.locals,
title="locals",
indent_guides=self.indent_guides,
max_length=self.locals_max_length,
max_string=self.locals_max_string,
max_depth=self.locals_max_depth,
overflow=self.locals_overflow,
)
exclude_frames: Optional[range] = None
if self.max_frames != 0:
exclude_frames = range(
self.max_frames // 2,
len(stack.frames) - self.max_frames // 2,
)
excluded = False
for frame_index, frame in enumerate(stack.frames):
if exclude_frames and frame_index in exclude_frames:
excluded = True
continue
if excluded:
assert exclude_frames is not None
yield Text(
f"\n... {len(exclude_frames)} frames hidden ...",
justify="center",
style="traceback.error",
)
excluded = False
first = frame_index == 0
frame_filename = frame.filename
suppressed = any(frame_filename.startswith(path) for path in self.suppress)
if os.path.exists(frame.filename):
text = Text.assemble(
path_highlighter(Text(frame.filename, style="pygments.string")),
(":", "pygments.text"),
(str(frame.lineno), "pygments.number"),
" in ",
(frame.name, "pygments.function"),
style="pygments.text",
)
else:
text = Text.assemble(
"in ",
(frame.name, "pygments.function"),
(":", "pygments.text"),
(str(frame.lineno), "pygments.number"),
style="pygments.text",
)
if not frame.filename.startswith("<") and not first:
yield ""
yield text
if frame.filename.startswith("<"):
yield from render_locals(frame)
continue
if not suppressed:
try:
code_lines = linecache.getlines(frame.filename)
code = "".join(code_lines)
if not code:
# code may be an empty string if the file doesn't exist, OR
# if the traceback filename is generated dynamically
continue
lexer_name = self._guess_lexer(frame.filename, code)
syntax = Syntax(
code,
lexer_name,
theme=theme,
line_numbers=True,
line_range=(
frame.lineno - self.extra_lines,
frame.lineno + self.extra_lines,
),
highlight_lines={frame.lineno},
word_wrap=self.word_wrap,
code_width=self.code_width,
indent_guides=self.indent_guides,
dedent=False,
)
yield ""
except Exception as error:
yield Text.assemble(
(f"\n{error}", "traceback.error"),
)
else:
if frame.last_instruction is not None:
start, end = frame.last_instruction
# Stylize a line at a time
# So that indentation isn't underlined (which looks bad)
for line1, column1, column2 in _iter_syntax_lines(start, end):
try:
if column1 == 0:
line = code_lines[line1 - 1]
column1 = len(line) - len(line.lstrip())
if column2 == -1:
column2 = len(code_lines[line1 - 1])
except IndexError:
# Being defensive here
# If last_instruction reports a line out-of-bounds, we don't want to crash
continue
syntax.stylize_range(
style="traceback.error_range",
start=(line1, column1),
end=(line1, column2),
)
yield (
Columns(
[
syntax,
*render_locals(frame),
],
padding=1,
)
if frame.locals
else syntax
)
if __name__ == "__main__": # pragma: no cover
install(show_locals=True)
import sys
def bar(
a: Any,
) -> None: # 这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑
one = 1
print(one / a)
def foo(a: Any) -> None:
_rich_traceback_guard = True
zed = {
"characters": {
"Paul Atreides",
"Vladimir Harkonnen",
"Thufir Hawat",
"Duncan Idaho",
},
"atomic_types": (None, False, True),
}
bar(a)
def error() -> None:
foo(0)
error() | --- +++ @@ -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).
+ """
line1, column1 = start
line2, column2 = end
@@ -91,6 +100,34 @@ suppress: Iterable[Union[str, ModuleType]] = (),
max_frames: int = 100,
) -> Callable[[Type[BaseException], BaseException, Optional[TracebackType]], Any]:
+ """Install a rich traceback handler.
+
+ Once installed, any tracebacks will be printed with syntax highlighting and rich formatting.
+
+
+ Args:
+ console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance.
+ width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100.
+ code_width (Optional[int], optional): Code width (in characters) of traceback. Defaults to 88.
+ extra_lines (int, optional): Extra lines of code. Defaults to 3.
+ theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick
+ a theme appropriate for the platform.
+ word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
+ show_locals (bool, optional): Enable display of local variables. Defaults to False.
+ locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
+ Defaults to 10.
+ locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
+ locals_max_depth (int, optional): Maximum depths of locals before truncating, or None to disable. Defaults to None.
+ locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
+ locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
+ locals_overflow (OverflowMethod, optional): How to handle overflowing locals, or None to disable. Defaults to None.
+ indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
+ suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
+
+ Returns:
+ Callable: The previous exception handler that was replaced.
+
+ """
traceback_console = Console(stderr=True) if console is None else console
locals_hide_sunder = (
@@ -131,6 +168,7 @@ default_showtraceback = ip.showtraceback # keep reference of default traceback
def ipy_show_traceback(*args: Any, **kwargs: Any) -> None:
+ """wrap the default ip.showtraceback to store info for ip._showtraceback"""
nonlocal tb_data
tb_data = kwargs
default_showtraceback(*args, **kwargs)
@@ -138,6 +176,7 @@ def ipy_display_traceback(
*args: Any, is_syntax: bool = False, **kwargs: Any
) -> None:
+ """Internally called traceback from ip._showtraceback"""
nonlocal tb_data
exc_tuple = ip._get_exc_info()
@@ -221,6 +260,29 @@
class Traceback:
+ """A Console renderable that renders a traceback.
+
+ Args:
+ trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses
+ the last exception.
+ width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
+ code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88.
+ extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
+ theme (str, optional): Override pygments theme used in traceback.
+ word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
+ show_locals (bool, optional): Enable display of local variables. Defaults to False.
+ indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
+ locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
+ Defaults to 10.
+ locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
+ locals_max_depth (int, optional): Maximum depths of locals before truncating, or None to disable. Defaults to None.
+ locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
+ locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
+ locals_overflow (OverflowMethod, optional): How to handle overflowing locals, or None to disable. Defaults to None.
+ suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
+ max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
+
+ """
LEXERS = {
"": "text",
@@ -310,6 +372,32 @@ suppress: Iterable[Union[str, ModuleType]] = (),
max_frames: int = 100,
) -> "Traceback":
+ """Create a traceback from exception info
+
+ Args:
+ exc_type (Type[BaseException]): Exception type.
+ exc_value (BaseException): Exception value.
+ traceback (TracebackType): Python Traceback object.
+ width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
+ code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88.
+ extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
+ theme (str, optional): Override pygments theme used in traceback.
+ word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
+ show_locals (bool, optional): Enable display of local variables. Defaults to False.
+ indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
+ locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
+ Defaults to 10.
+ locals_max_depth (int, optional): Maximum depths of locals before truncating, or None to disable. Defaults to None.
+ locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
+ locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
+ locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
+ locals_overflow (OverflowMethod, optional): How to handle overflowing locals, or None to disable. Defaults to None.
+ suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
+ max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
+
+ Returns:
+ Traceback: A Traceback instance that may be printed.
+ """
rich_traceback = cls.extract(
exc_type,
exc_value,
@@ -356,6 +444,23 @@ locals_hide_sunder: bool = False,
_visited_exceptions: Optional[Set[BaseException]] = None,
) -> Trace:
+ """Extract traceback information.
+
+ Args:
+ exc_type (Type[BaseException]): Exception type.
+ exc_value (BaseException): Exception value.
+ traceback (TracebackType): Python Traceback object.
+ show_locals (bool, optional): Enable display of local variables. Defaults to False.
+ locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
+ Defaults to 10.
+ locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
+ locals_max_depth (int, optional): Maximum depths of locals before truncating, or None to disable. Defaults to None.
+ locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
+ locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
+
+ Returns:
+ Trace: A Trace instance which you can use to construct a `Traceback`.
+ """
stacks: List[Stack] = []
is_cause = False
@@ -369,6 +474,7 @@ )
def safe_str(_object: Any) -> str:
+ """Don't allow exceptions from __str__ to propagate."""
try:
return str(_object)
except Exception:
@@ -418,6 +524,7 @@ def get_locals(
iter_locals: Iterable[Tuple[str, object]],
) -> Iterable[Tuple[str, object]]:
+ """Extract locals from an iterator of key pairs."""
if not (locals_hide_dunder or locals_hide_sunder):
yield from iter_locals
return
@@ -814,4 +921,4 @@ def error() -> None:
foo(0)
- error()+ error()
| 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_distribute, ratio_reduce
from .align import VerticalAlignMethod
from .jupyter import JupyterMixin
from .measure import Measurement
from .padding import Padding, PaddingDimensions
from .protocol import is_renderable
from .segment import Segment
from .style import Style, StyleType
from .text import Text, TextType
if TYPE_CHECKING:
from .console import (
Console,
ConsoleOptions,
JustifyMethod,
OverflowMethod,
RenderableType,
RenderResult,
)
@dataclass
class Column:
header: "RenderableType" = ""
"""RenderableType: Renderable for the header (typically a string)"""
footer: "RenderableType" = ""
"""RenderableType: Renderable for the footer (typically a string)"""
header_style: StyleType = ""
"""StyleType: The style of the header."""
footer_style: StyleType = ""
"""StyleType: The style of the footer."""
style: StyleType = ""
"""StyleType: The style of the column."""
justify: "JustifyMethod" = "left"
"""str: How to justify text within the column ("left", "center", "right", or "full")"""
vertical: "VerticalAlignMethod" = "top"
"""str: How to vertically align content ("top", "middle", or "bottom")"""
overflow: "OverflowMethod" = "ellipsis"
"""str: Overflow method."""
width: Optional[int] = None
"""Optional[int]: Width of the column, or ``None`` (default) to auto calculate width."""
min_width: Optional[int] = None
"""Optional[int]: Minimum width of column, or ``None`` for no minimum. Defaults to None."""
max_width: Optional[int] = None
"""Optional[int]: Maximum width of column, or ``None`` for no maximum. Defaults to None."""
ratio: Optional[int] = None
"""Optional[int]: Ratio to use when calculating column width, or ``None`` (default) to adapt to column contents."""
no_wrap: bool = False
"""bool: Prevent wrapping of text within the column. Defaults to ``False``."""
highlight: bool = False
"""bool: Apply highlighter to column. Defaults to ``False``."""
_index: int = 0
"""Index of column."""
_cells: List["RenderableType"] = field(default_factory=list)
def copy(self) -> "Column":
return replace(self, _cells=[])
@property
def cells(self) -> Iterable["RenderableType"]:
yield from self._cells
@property
def flexible(self) -> bool:
return self.ratio is not None
@dataclass
class Row:
style: Optional[StyleType] = None
"""Style to apply to row."""
end_section: bool = False
"""Indicated end of section, which will force a line beneath the row."""
class _Cell(NamedTuple):
style: StyleType
"""Style to apply to cell."""
renderable: "RenderableType"
"""Cell renderable."""
vertical: VerticalAlignMethod
"""Cell vertical alignment."""
class Table(JupyterMixin):
columns: List[Column]
rows: List[Row]
def __init__(
self,
*headers: Union[Column, str],
title: Optional[TextType] = None,
caption: Optional[TextType] = None,
width: Optional[int] = None,
min_width: Optional[int] = None,
box: Optional[box.Box] = box.HEAVY_HEAD,
safe_box: Optional[bool] = None,
padding: PaddingDimensions = (0, 1),
collapse_padding: bool = False,
pad_edge: bool = True,
expand: bool = False,
show_header: bool = True,
show_footer: bool = False,
show_edge: bool = True,
show_lines: bool = False,
leading: int = 0,
style: StyleType = "none",
row_styles: Optional[Iterable[StyleType]] = None,
header_style: Optional[StyleType] = "table.header",
footer_style: Optional[StyleType] = "table.footer",
border_style: Optional[StyleType] = None,
title_style: Optional[StyleType] = None,
caption_style: Optional[StyleType] = None,
title_justify: "JustifyMethod" = "center",
caption_justify: "JustifyMethod" = "center",
highlight: bool = False,
) -> None:
self.columns: List[Column] = []
self.rows: List[Row] = []
self.title = title
self.caption = caption
self.width = width
self.min_width = min_width
self.box = box
self.safe_box = safe_box
self._padding = Padding.unpack(padding)
self.pad_edge = pad_edge
self._expand = expand
self.show_header = show_header
self.show_footer = show_footer
self.show_edge = show_edge
self.show_lines = show_lines
self.leading = leading
self.collapse_padding = collapse_padding
self.style = style
self.header_style = header_style or ""
self.footer_style = footer_style or ""
self.border_style = border_style
self.title_style = title_style
self.caption_style = caption_style
self.title_justify: "JustifyMethod" = title_justify
self.caption_justify: "JustifyMethod" = caption_justify
self.highlight = highlight
self.row_styles: Sequence[StyleType] = list(row_styles or [])
append_column = self.columns.append
for header in headers:
if isinstance(header, str):
self.add_column(header=header)
else:
header._index = len(self.columns)
append_column(header)
@classmethod
def grid(
cls,
*headers: Union[Column, str],
padding: PaddingDimensions = 0,
collapse_padding: bool = True,
pad_edge: bool = False,
expand: bool = False,
) -> "Table":
return cls(
*headers,
box=None,
padding=padding,
collapse_padding=collapse_padding,
show_header=False,
show_footer=False,
show_edge=False,
pad_edge=pad_edge,
expand=expand,
)
@property
def expand(self) -> bool:
return self._expand or self.width is not None
@expand.setter
def expand(self, expand: bool) -> None:
self._expand = expand
@property
def _extra_width(self) -> int:
width = 0
if self.box and self.show_edge:
width += 2
if self.box:
width += len(self.columns) - 1
return width
@property
def row_count(self) -> int:
return len(self.rows)
def get_row_style(self, console: "Console", index: int) -> StyleType:
style = Style.null()
if self.row_styles:
style += console.get_style(self.row_styles[index % len(self.row_styles)])
row_style = self.rows[index].style
if row_style is not None:
style += console.get_style(row_style)
return style
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> Measurement:
max_width = options.max_width
if self.width is not None:
max_width = self.width
if max_width < 0:
return Measurement(0, 0)
extra_width = self._extra_width
max_width = sum(
self._calculate_column_widths(
console, options.update_width(max_width - extra_width)
)
)
_measure_column = self._measure_column
measurements = [
_measure_column(console, options.update_width(max_width), column)
for column in self.columns
]
minimum_width = (
sum(measurement.minimum for measurement in measurements) + extra_width
)
maximum_width = (
sum(measurement.maximum for measurement in measurements) + extra_width
if (self.width is None)
else self.width
)
measurement = Measurement(minimum_width, maximum_width)
measurement = measurement.clamp(self.min_width)
return measurement
@property
def padding(self) -> Tuple[int, int, int, int]:
return self._padding
@padding.setter
def padding(self, padding: PaddingDimensions) -> "Table":
self._padding = Padding.unpack(padding)
return self
def add_column(
self,
header: "RenderableType" = "",
footer: "RenderableType" = "",
*,
header_style: Optional[StyleType] = None,
highlight: Optional[bool] = None,
footer_style: Optional[StyleType] = None,
style: Optional[StyleType] = None,
justify: "JustifyMethod" = "left",
vertical: "VerticalAlignMethod" = "top",
overflow: "OverflowMethod" = "ellipsis",
width: Optional[int] = None,
min_width: Optional[int] = None,
max_width: Optional[int] = None,
ratio: Optional[int] = None,
no_wrap: bool = False,
) -> None:
column = Column(
_index=len(self.columns),
header=header,
footer=footer,
header_style=header_style or "",
highlight=highlight if highlight is not None else self.highlight,
footer_style=footer_style or "",
style=style or "",
justify=justify,
vertical=vertical,
overflow=overflow,
width=width,
min_width=min_width,
max_width=max_width,
ratio=ratio,
no_wrap=no_wrap,
)
self.columns.append(column)
def add_row(
self,
*renderables: Optional["RenderableType"],
style: Optional[StyleType] = None,
end_section: bool = False,
) -> None:
def add_cell(column: Column, renderable: "RenderableType") -> None:
column._cells.append(renderable)
cell_renderables: List[Optional["RenderableType"]] = list(renderables)
columns = self.columns
if len(cell_renderables) < len(columns):
cell_renderables = [
*cell_renderables,
*[None] * (len(columns) - len(cell_renderables)),
]
for index, renderable in enumerate(cell_renderables):
if index == len(columns):
column = Column(_index=index, highlight=self.highlight)
for _ in self.rows:
add_cell(column, Text(""))
self.columns.append(column)
else:
column = columns[index]
if renderable is None:
add_cell(column, "")
elif is_renderable(renderable):
add_cell(column, renderable)
else:
raise errors.NotRenderableError(
f"unable to render {type(renderable).__name__}; a string or other renderable object is required"
)
self.rows.append(Row(style=style, end_section=end_section))
def add_section(self) -> None:
if self.rows:
self.rows[-1].end_section = True
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> "RenderResult":
if not self.columns:
yield Segment("\n")
return
max_width = options.max_width
if self.width is not None:
max_width = self.width
extra_width = self._extra_width
widths = self._calculate_column_widths(
console, options.update_width(max_width - extra_width)
)
table_width = sum(widths) + extra_width
render_options = options.update(
width=table_width, highlight=self.highlight, height=None
)
def render_annotation(
text: TextType, style: StyleType, justify: "JustifyMethod" = "center"
) -> "RenderResult":
render_text = (
console.render_str(text, style=style, highlight=False)
if isinstance(text, str)
else text
)
return console.render(
render_text, options=render_options.update(justify=justify)
)
if self.title:
yield from render_annotation(
self.title,
style=Style.pick_first(self.title_style, "table.title"),
justify=self.title_justify,
)
yield from self._render(console, render_options, widths)
if self.caption:
yield from render_annotation(
self.caption,
style=Style.pick_first(self.caption_style, "table.caption"),
justify=self.caption_justify,
)
def _calculate_column_widths(
self, console: "Console", options: "ConsoleOptions"
) -> List[int]:
max_width = options.max_width
columns = self.columns
width_ranges = [
self._measure_column(console, options, column) for column in columns
]
widths = [_range.maximum or 1 for _range in width_ranges]
get_padding_width = self._get_padding_width
extra_width = self._extra_width
if self.expand:
ratios = [col.ratio or 0 for col in columns if col.flexible]
if any(ratios):
fixed_widths = [
0 if column.flexible else _range.maximum
for _range, column in zip(width_ranges, columns)
]
flex_minimum = [
(column.width or 1) + get_padding_width(column._index)
for column in columns
if column.flexible
]
flexible_width = max_width - sum(fixed_widths)
flex_widths = ratio_distribute(flexible_width, ratios, flex_minimum)
iter_flex_widths = iter(flex_widths)
for index, column in enumerate(columns):
if column.flexible:
widths[index] = fixed_widths[index] + next(iter_flex_widths)
table_width = sum(widths)
if table_width > max_width:
widths = self._collapse_widths(
widths,
[(column.width is None and not column.no_wrap) for column in columns],
max_width,
)
table_width = sum(widths)
# last resort, reduce columns evenly
if table_width > max_width:
excess_width = table_width - max_width
widths = ratio_reduce(excess_width, [1] * len(widths), widths, widths)
table_width = sum(widths)
width_ranges = [
self._measure_column(console, options.update_width(width), column)
for width, column in zip(widths, columns)
]
widths = [_range.maximum or 0 for _range in width_ranges]
if (table_width < max_width and self.expand) or (
self.min_width is not None and table_width < (self.min_width - extra_width)
):
_max_width = (
max_width
if self.min_width is None
else min(self.min_width - extra_width, max_width)
)
pad_widths = ratio_distribute(_max_width - table_width, widths)
widths = [_width + pad for _width, pad in zip(widths, pad_widths)]
return widths
@classmethod
def _collapse_widths(
cls, widths: List[int], wrapable: List[bool], max_width: int
) -> List[int]:
total_width = sum(widths)
excess_width = total_width - max_width
if any(wrapable):
while total_width and excess_width > 0:
max_column = max(
width for width, allow_wrap in zip(widths, wrapable) if allow_wrap
)
second_max_column = max(
width if allow_wrap and width != max_column else 0
for width, allow_wrap in zip(widths, wrapable)
)
column_difference = max_column - second_max_column
ratios = [
(1 if (width == max_column and allow_wrap) else 0)
for width, allow_wrap in zip(widths, wrapable)
]
if not any(ratios) or not column_difference:
break
max_reduce = [min(excess_width, column_difference)] * len(widths)
widths = ratio_reduce(excess_width, ratios, max_reduce, widths)
total_width = sum(widths)
excess_width = total_width - max_width
return widths
def _get_cells(
self, console: "Console", column_index: int, column: Column
) -> Iterable[_Cell]:
collapse_padding = self.collapse_padding
pad_edge = self.pad_edge
padding = self.padding
any_padding = any(padding)
first_column = column_index == 0
last_column = column_index == len(self.columns) - 1
_padding_cache: Dict[Tuple[bool, bool], Tuple[int, int, int, int]] = {}
def get_padding(first_row: bool, last_row: bool) -> Tuple[int, int, int, int]:
cached = _padding_cache.get((first_row, last_row))
if cached:
return cached
top, right, bottom, left = padding
if collapse_padding:
if not first_column:
left = max(0, left - right)
if not last_row:
bottom = max(0, top - bottom)
if not pad_edge:
if first_column:
left = 0
if last_column:
right = 0
if first_row:
top = 0
if last_row:
bottom = 0
_padding = (top, right, bottom, left)
_padding_cache[(first_row, last_row)] = _padding
return _padding
raw_cells: List[Tuple[StyleType, "RenderableType"]] = []
_append = raw_cells.append
get_style = console.get_style
if self.show_header:
header_style = get_style(self.header_style or "") + get_style(
column.header_style
)
_append((header_style, column.header))
cell_style = get_style(column.style or "")
for cell in column.cells:
_append((cell_style, cell))
if self.show_footer:
footer_style = get_style(self.footer_style or "") + get_style(
column.footer_style
)
_append((footer_style, column.footer))
if any_padding:
_Padding = Padding
for first, last, (style, renderable) in loop_first_last(raw_cells):
yield _Cell(
style,
_Padding(renderable, get_padding(first, last)),
getattr(renderable, "vertical", None) or column.vertical,
)
else:
for style, renderable in raw_cells:
yield _Cell(
style,
renderable,
getattr(renderable, "vertical", None) or column.vertical,
)
def _get_padding_width(self, column_index: int) -> int:
_, pad_right, _, pad_left = self.padding
if self.collapse_padding:
pad_left = 0
pad_right = abs(pad_left - pad_right)
if not self.pad_edge:
if column_index == 0:
pad_left = 0
if column_index == len(self.columns) - 1:
pad_right = 0
return pad_left + pad_right
def _measure_column(
self,
console: "Console",
options: "ConsoleOptions",
column: Column,
) -> Measurement:
max_width = options.max_width
if max_width < 1:
return Measurement(0, 0)
padding_width = self._get_padding_width(column._index)
if column.width is not None:
# Fixed width column
return Measurement(
column.width + padding_width, column.width + padding_width
).with_maximum(max_width)
# Flexible column, we need to measure contents
min_widths: List[int] = []
max_widths: List[int] = []
append_min = min_widths.append
append_max = max_widths.append
get_render_width = Measurement.get
for cell in self._get_cells(console, column._index, column):
_min, _max = get_render_width(console, options, cell.renderable)
append_min(_min)
append_max(_max)
measurement = Measurement(
max(min_widths) if min_widths else 1,
max(max_widths) if max_widths else max_width,
).with_maximum(max_width)
measurement = measurement.clamp(
None if column.min_width is None else column.min_width + padding_width,
None if column.max_width is None else column.max_width + padding_width,
)
return measurement
def _render(
self, console: "Console", options: "ConsoleOptions", widths: List[int]
) -> "RenderResult":
table_style = console.get_style(self.style or "")
border_style = table_style + console.get_style(self.border_style or "")
_column_cells = (
self._get_cells(console, column_index, column)
for column_index, column in enumerate(self.columns)
)
row_cells: List[Tuple[_Cell, ...]] = list(zip(*_column_cells))
_box = (
self.box.substitute(
options, safe=pick_bool(self.safe_box, console.safe_box)
)
if self.box
else None
)
_box = _box.get_plain_headed_box() if _box and not self.show_header else _box
new_line = Segment.line()
columns = self.columns
show_header = self.show_header
show_footer = self.show_footer
show_edge = self.show_edge
show_lines = self.show_lines
leading = self.leading
_Segment = Segment
if _box:
box_segments = [
(
_Segment(_box.head_left, border_style),
_Segment(_box.head_right, border_style),
_Segment(_box.head_vertical, border_style),
),
(
_Segment(_box.mid_left, border_style),
_Segment(_box.mid_right, border_style),
_Segment(_box.mid_vertical, border_style),
),
(
_Segment(_box.foot_left, border_style),
_Segment(_box.foot_right, border_style),
_Segment(_box.foot_vertical, border_style),
),
]
if show_edge:
yield _Segment(_box.get_top(widths), border_style)
yield new_line
else:
box_segments = []
get_row_style = self.get_row_style
get_style = console.get_style
for index, (first, last, row_cell) in enumerate(loop_first_last(row_cells)):
header_row = first and show_header
footer_row = last and show_footer
row = (
self.rows[index - show_header]
if (not header_row and not footer_row)
else None
)
max_height = 1
cells: List[List[List[Segment]]] = []
if header_row or footer_row:
row_style = Style.null()
else:
row_style = get_style(
get_row_style(console, index - 1 if show_header else index)
)
for width, cell, column in zip(widths, row_cell, columns):
render_options = options.update(
width=width,
justify=column.justify,
no_wrap=column.no_wrap,
overflow=column.overflow,
height=None,
highlight=column.highlight,
)
lines = console.render_lines(
cell.renderable,
render_options,
style=get_style(cell.style) + row_style,
)
max_height = max(max_height, len(lines))
cells.append(lines)
row_height = max(len(cell) for cell in cells)
def align_cell(
cell: List[List[Segment]],
vertical: "VerticalAlignMethod",
width: int,
style: Style,
) -> List[List[Segment]]:
if header_row:
vertical = "bottom"
elif footer_row:
vertical = "top"
if vertical == "top":
return _Segment.align_top(cell, width, row_height, style)
elif vertical == "middle":
return _Segment.align_middle(cell, width, row_height, style)
return _Segment.align_bottom(cell, width, row_height, style)
cells[:] = [
_Segment.set_shape(
align_cell(
cell,
_cell.vertical,
width,
get_style(_cell.style) + row_style,
),
width,
max_height,
)
for width, _cell, cell, column in zip(widths, row_cell, cells, columns)
]
if _box:
if last and show_footer:
yield _Segment(
_box.get_row(widths, "foot", edge=show_edge), border_style
)
yield new_line
left, right, _divider = box_segments[0 if first else (2 if last else 1)]
# If the column divider is whitespace also style it with the row background
divider = (
_divider
if _divider.text.strip()
else _Segment(
_divider.text, row_style.background_style + _divider.style
)
)
for line_no in range(max_height):
if show_edge:
yield left
for last_cell, rendered_cell in loop_last(cells):
yield from rendered_cell[line_no]
if not last_cell:
yield divider
if show_edge:
yield right
yield new_line
else:
for line_no in range(max_height):
for rendered_cell in cells:
yield from rendered_cell[line_no]
yield new_line
if _box and first and show_header:
yield _Segment(
_box.get_row(widths, "head", edge=show_edge), border_style
)
yield new_line
end_section = row and row.end_section
if _box and (show_lines or leading or end_section):
if (
not last
and not (show_footer and index >= len(row_cells) - 2)
and not (show_header and header_row)
):
if leading:
yield _Segment(
_box.get_row(widths, "mid", edge=show_edge) * leading,
border_style,
)
else:
yield _Segment(
_box.get_row(widths, "row", edge=show_edge), border_style
)
yield new_line
if _box and show_edge:
yield _Segment(_box.get_bottom(widths), border_style)
yield new_line
if __name__ == "__main__": # pragma: no cover
from rich.console import Console
from rich.highlighter import ReprHighlighter
from ._timer import timer
with timer("Table render"):
table = Table(
title="Star Wars Movies",
caption="Rich example table",
caption_justify="right",
)
table.add_column(
"Released", header_style="bright_cyan", style="cyan", no_wrap=True
)
table.add_column("Title", style="magenta")
table.add_column("Box Office", justify="right", style="green")
table.add_row(
"Dec 20, 2019",
"Star Wars: The Rise of Skywalker",
"$952,110,690",
)
table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347")
table.add_row(
"Dec 15, 2017",
"Star Wars Ep. V111: The Last Jedi",
"$1,332,539,889",
style="on black",
end_section=True,
)
table.add_row(
"Dec 16, 2016",
"Rogue One: A Star Wars Story",
"$1,332,439,889",
)
def header(text: str) -> None:
console.print()
console.rule(highlight(text))
console.print()
console = Console()
highlight = ReprHighlighter()
header("Example Table")
console.print(table, justify="center")
table.expand = True
header("expand=True")
console.print(table)
table.width = 50
header("width=50")
console.print(table, justify="center")
table.width = None
table.expand = False
table.row_styles = ["dim", "none"]
header("row_styles=['dim', 'none']")
console.print(table, justify="center")
table.width = None
table.expand = False
table.row_styles = ["dim", "none"]
table.leading = 1
header("leading=1, row_styles=['dim', 'none']")
console.print(table, justify="center")
table.width = None
table.expand = False
table.row_styles = ["dim", "none"]
table.show_lines = True
table.leading = 0
header("show_lines=True, row_styles=['dim', 'none']")
console.print(table, justify="center") | --- +++ @@ -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.
+ width (int, optional): The width in characters of the table, or ``None`` to automatically fit. Defaults to None.
+ min_width (Optional[int], optional): The minimum width of the table, or ``None`` for no minimum. Defaults to None.
+ box (box.Box, optional): One of the constants in box.py used to draw the edges (see :ref:`appendix_box`), or ``None`` for no box lines. Defaults to box.HEAVY_HEAD.
+ safe_box (Optional[bool], optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True.
+ padding (PaddingDimensions, optional): Padding for cells (top, right, bottom, left). Defaults to (0, 1).
+ collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to False.
+ pad_edge (bool, optional): Enable padding of edge cells. Defaults to True.
+ show_header (bool, optional): Show a header row. Defaults to True.
+ show_footer (bool, optional): Show a footer row. Defaults to False.
+ show_edge (bool, optional): Draw a box around the outside of the table. Defaults to True.
+ show_lines (bool, optional): Draw lines between every row. Defaults to False.
+ leading (int, optional): Number of blank lines between rows (precludes ``show_lines``). Defaults to 0.
+ style (Union[str, Style], optional): Default style for the table. Defaults to "none".
+ row_styles (List[Union, str], optional): Optional list of row styles, if more than one style is given then the styles will alternate. Defaults to None.
+ header_style (Union[str, Style], optional): Style of the header. Defaults to "table.header".
+ footer_style (Union[str, Style], optional): Style of the footer. Defaults to "table.footer".
+ border_style (Union[str, Style], optional): Style of the border. Defaults to None.
+ title_style (Union[str, Style], optional): Style of the title. Defaults to None.
+ caption_style (Union[str, Style], optional): Style of the caption. Defaults to None.
+ title_justify (str, optional): Justify method for title. Defaults to "center".
+ caption_justify (str, optional): Justify method for caption. Defaults to "center".
+ highlight (bool, optional): Highlight cell contents (if str). Defaults to False.
+ """
header: "RenderableType" = ""
"""RenderableType: Renderable for the header (typically a string)"""
@@ -86,19 +114,23 @@ _cells: List["RenderableType"] = field(default_factory=list)
def copy(self) -> "Column":
+ """Return a copy of this Column."""
return replace(self, _cells=[])
@property
def cells(self) -> Iterable["RenderableType"]:
+ """Get all cells in the column, not including header."""
yield from self._cells
@property
def flexible(self) -> bool:
+ """Check if this column is flexible."""
return self.ratio is not None
@dataclass
class Row:
+ """Information regarding a row."""
style: Optional[StyleType] = None
"""Style to apply to row."""
@@ -108,6 +140,7 @@
class _Cell(NamedTuple):
+ """A single cell in a table."""
style: StyleType
"""Style to apply to cell."""
@@ -118,6 +151,36 @@
class Table(JupyterMixin):
+ """A console renderable to draw a table.
+
+ Args:
+ *headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance.
+ 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.
+ width (int, optional): The width in characters of the table, or ``None`` to automatically fit. Defaults to None.
+ min_width (Optional[int], optional): The minimum width of the table, or ``None`` for no minimum. Defaults to None.
+ box (box.Box, optional): One of the constants in box.py used to draw the edges (see :ref:`appendix_box`), or ``None`` for no box lines. Defaults to box.HEAVY_HEAD.
+ safe_box (Optional[bool], optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True.
+ padding (PaddingDimensions, optional): Padding for cells (top, right, bottom, left). Defaults to (0, 1).
+ collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to False.
+ pad_edge (bool, optional): Enable padding of edge cells. Defaults to True.
+ expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False.
+ show_header (bool, optional): Show a header row. Defaults to True.
+ show_footer (bool, optional): Show a footer row. Defaults to False.
+ show_edge (bool, optional): Draw a box around the outside of the table. Defaults to True.
+ show_lines (bool, optional): Draw lines between every row. Defaults to False.
+ leading (int, optional): Number of blank lines between rows (precludes ``show_lines``). Defaults to 0.
+ style (Union[str, Style], optional): Default style for the table. Defaults to "none".
+ row_styles (List[Union, str], optional): Optional list of row styles, if more than one style is given then the styles will alternate. Defaults to None.
+ header_style (Union[str, Style], optional): Style of the header. Defaults to "table.header".
+ footer_style (Union[str, Style], optional): Style of the footer. Defaults to "table.footer".
+ border_style (Union[str, Style], optional): Style of the border. Defaults to None.
+ title_style (Union[str, Style], optional): Style of the title. Defaults to None.
+ caption_style (Union[str, Style], optional): Style of the caption. Defaults to None.
+ title_justify (str, optional): Justify method for title. Defaults to "center".
+ caption_justify (str, optional): Justify method for caption. Defaults to "center".
+ highlight (bool, optional): Highlight cell contents (if str). Defaults to False.
+ """
columns: List[Column]
rows: List[Row]
@@ -195,6 +258,18 @@ pad_edge: bool = False,
expand: bool = False,
) -> "Table":
+ """Get a table with no lines, headers, or footer.
+
+ Args:
+ *headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance.
+ padding (PaddingDimensions, optional): Get padding around cells. Defaults to 0.
+ collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to True.
+ pad_edge (bool, optional): Enable padding around edges of table. Defaults to False.
+ expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False.
+
+ Returns:
+ Table: A table instance.
+ """
return cls(
*headers,
box=None,
@@ -209,14 +284,17 @@
@property
def expand(self) -> bool:
+ """Setting a non-None self.width implies expand."""
return self._expand or self.width is not None
@expand.setter
def expand(self, expand: bool) -> None:
+ """Set expand."""
self._expand = expand
@property
def _extra_width(self) -> int:
+ """Get extra width to add to cell content."""
width = 0
if self.box and self.show_edge:
width += 2
@@ -226,9 +304,11 @@
@property
def row_count(self) -> int:
+ """Get the current number of rows."""
return len(self.rows)
def get_row_style(self, console: "Console", index: int) -> StyleType:
+ """Get the current row style."""
style = Style.null()
if self.row_styles:
style += console.get_style(self.row_styles[index % len(self.row_styles)])
@@ -272,10 +352,12 @@
@property
def padding(self) -> Tuple[int, int, int, int]:
+ """Get cell padding."""
return self._padding
@padding.setter
def padding(self, padding: PaddingDimensions) -> "Table":
+ """Set cell padding."""
self._padding = Padding.unpack(padding)
return self
@@ -297,6 +379,26 @@ ratio: Optional[int] = None,
no_wrap: bool = False,
) -> None:
+ """Add a column to the table.
+
+ Args:
+ header (RenderableType, optional): Text or renderable for the header.
+ Defaults to "".
+ footer (RenderableType, optional): Text or renderable for the footer.
+ Defaults to "".
+ header_style (Union[str, Style], optional): Style for the header, or None for default. Defaults to None.
+ highlight (bool, optional): Whether to highlight the text. The default of None uses the value of the table (self) object.
+ footer_style (Union[str, Style], optional): Style for the footer, or None for default. Defaults to None.
+ style (Union[str, Style], optional): Style for the column cells, or None for default. Defaults to None.
+ justify (JustifyMethod, optional): Alignment for cells. Defaults to "left".
+ vertical (VerticalAlignMethod, optional): Vertical alignment, one of "top", "middle", or "bottom". Defaults to "top".
+ overflow (OverflowMethod): Overflow method: "crop", "fold", "ellipsis". Defaults to "ellipsis".
+ width (int, optional): Desired width of column in characters, or None to fit to contents. Defaults to None.
+ min_width (Optional[int], optional): Minimum width of column, or ``None`` for no minimum. Defaults to None.
+ max_width (Optional[int], optional): Maximum width of column, or ``None`` for no maximum. Defaults to None.
+ ratio (int, optional): Flexible ratio for the column (requires ``Table.expand`` or ``Table.width``). Defaults to None.
+ no_wrap (bool, optional): Set to ``True`` to disable wrapping of this column.
+ """
column = Column(
_index=len(self.columns),
@@ -323,6 +425,17 @@ style: Optional[StyleType] = None,
end_section: bool = False,
) -> None:
+ """Add a row of renderables.
+
+ Args:
+ *renderables (None or renderable): Each cell in a row must be a renderable object (including str),
+ or ``None`` for a blank cell.
+ style (StyleType, optional): An optional style to apply to the entire row. Defaults to None.
+ end_section (bool, optional): End a section and draw a line. Defaults to False.
+
+ Raises:
+ errors.NotRenderableError: If you add something that can't be rendered.
+ """
def add_cell(column: Column, renderable: "RenderableType") -> None:
column._cells.append(renderable)
@@ -354,6 +467,7 @@ self.rows.append(Row(style=style, end_section=end_section))
def add_section(self) -> None:
+ """Add a new section (draw a line after current row)."""
if self.rows:
self.rows[-1].end_section = True
@@ -409,6 +523,7 @@ def _calculate_column_widths(
self, console: "Console", options: "ConsoleOptions"
) -> List[int]:
+ """Calculate the widths of each column, including padding, not including borders."""
max_width = options.max_width
columns = self.columns
width_ranges = [
@@ -474,6 +589,16 @@ def _collapse_widths(
cls, widths: List[int], wrapable: List[bool], max_width: int
) -> List[int]:
+ """Reduce widths so that the total is under max_width.
+
+ Args:
+ widths (List[int]): List of widths.
+ wrapable (List[bool]): List of booleans that indicate if a column may shrink.
+ max_width (int): Maximum width to reduce to.
+
+ Returns:
+ List[int]: A new list of widths.
+ """
total_width = sum(widths)
excess_width = total_width - max_width
if any(wrapable):
@@ -502,6 +627,7 @@ def _get_cells(
self, console: "Console", column_index: int, column: Column
) -> Iterable[_Cell]:
+ """Get all the cells with padding and optional header."""
collapse_padding = self.collapse_padding
pad_edge = self.pad_edge
@@ -572,6 +698,7 @@ )
def _get_padding_width(self, column_index: int) -> int:
+ """Get extra width from padding."""
_, pad_right, _, pad_left = self.padding
if self.collapse_padding:
@@ -592,6 +719,7 @@ options: "ConsoleOptions",
column: Column,
) -> Measurement:
+ """Get the minimum and maximum width of the column."""
max_width = options.max_width
if max_width < 1:
@@ -884,4 +1012,4 @@ table.show_lines = True
table.leading = 0
header("show_lines=True, row_styles=['dim', 'none']")
- console.print(table, justify="center")+ console.print(table, justify="center")
| 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,
*,
console: Optional[Console] = None,
spinner: str = "dots",
spinner_style: StyleType = "status.spinner",
speed: float = 1.0,
refresh_per_second: float = 12.5,
):
self.status = status
self.spinner_style = spinner_style
self.speed = speed
self._spinner = Spinner(spinner, text=status, style=spinner_style, speed=speed)
self._live = Live(
self.renderable,
console=console,
refresh_per_second=refresh_per_second,
transient=True,
)
@property
def renderable(self) -> Spinner:
return self._spinner
@property
def console(self) -> "Console":
return self._live.console
def update(
self,
status: Optional[RenderableType] = None,
*,
spinner: Optional[str] = None,
spinner_style: Optional[StyleType] = None,
speed: Optional[float] = None,
) -> None:
if status is not None:
self.status = status
if spinner_style is not None:
self.spinner_style = spinner_style
if speed is not None:
self.speed = speed
if spinner is not None:
self._spinner = Spinner(
spinner, text=self.status, style=self.spinner_style, speed=self.speed
)
self._live.update(self.renderable, refresh=True)
else:
self._spinner.update(
text=self.status, style=self.spinner_style, speed=self.speed
)
def start(self) -> None:
self._live.start()
def stop(self) -> None:
self._live.stop()
def __rich__(self) -> RenderableType:
return self.renderable
def __enter__(self) -> "Status":
self.start()
return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
self.stop()
if __name__ == "__main__": # pragma: no cover
from time import sleep
from .console import Console
console = Console()
with console.status("[magenta]Covid detector booting up") as status:
sleep(3)
console.log("Importing advanced AI")
sleep(3)
console.log("Advanced Covid AI Ready")
sleep(3)
status.update(status="[bold blue] Scanning for Covid", spinner="earth")
sleep(3)
console.log("Found 10,000,000,000 copies of Covid32.exe")
sleep(3)
status.update(
status="[bold red]Moving Covid32.exe to Trash",
spinner="bouncingBall",
spinner_style="yellow",
)
sleep(5)
console.print("[bold green]Covid deleted successfully") | --- +++ @@ -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.
+ spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots".
+ spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner".
+ speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.
+ refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.
+ """
def __init__(
self,
@@ -37,6 +47,7 @@
@property
def console(self) -> "Console":
+ """Get the Console used by the Status objects."""
return self._live.console
def update(
@@ -47,6 +58,14 @@ spinner_style: Optional[StyleType] = None,
speed: Optional[float] = None,
) -> None:
+ """Update status.
+
+ Args:
+ status (Optional[RenderableType], optional): New status renderable or None for no change. Defaults to None.
+ spinner (Optional[str], optional): New spinner or None for no change. Defaults to None.
+ spinner_style (Optional[StyleType], optional): New spinner style or None for no change. Defaults to None.
+ speed (Optional[float], optional): Speed factor for spinner animation or None for no change. Defaults to None.
+ """
if status is not None:
self.status = status
if spinner_style is not None:
@@ -64,9 +83,11 @@ )
def start(self) -> None:
+ """Start the status animation."""
self._live.start()
def stop(self) -> None:
+ """Stop the spinner animation."""
self._live.stop()
def __rich__(self) -> RenderableType:
@@ -107,4 +128,4 @@ spinner_style="yellow",
)
sleep(5)
- console.print("[bold green]Covid deleted successfully")+ console.print("[bold green]Covid deleted successfully")
| 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 import Lexer
from pygments.lexers import get_lexer_by_name, guess_lexer_for_filename
from pygments.style import Style as PygmentsStyle
from pygments.styles import get_style_by_name
from pygments.token import (
Comment,
Error,
Generic,
Keyword,
Name,
Number,
Operator,
String,
Token,
Whitespace,
)
from pygments.util import ClassNotFound
from rich.containers import Lines
from rich.padding import Padding, PaddingDimensions
from ._loop import loop_first
from .cells import cell_len
from .color import Color, blend_rgb
from .console import Console, ConsoleOptions, JustifyMethod, RenderResult
from .jupyter import JupyterMixin
from .measure import Measurement
from .segment import Segment, Segments
from .style import Style, StyleType
from .text import Text
TokenType = Tuple[str, ...]
WINDOWS = sys.platform == "win32"
DEFAULT_THEME = "monokai"
# The following styles are based on https://github.com/pygments/pygments/blob/master/pygments/formatters/terminal.py
# A few modifications were made
ANSI_LIGHT: Dict[TokenType, Style] = {
Token: Style(),
Whitespace: Style(color="white"),
Comment: Style(dim=True),
Comment.Preproc: Style(color="cyan"),
Keyword: Style(color="blue"),
Keyword.Type: Style(color="cyan"),
Operator.Word: Style(color="magenta"),
Name.Builtin: Style(color="cyan"),
Name.Function: Style(color="green"),
Name.Namespace: Style(color="cyan", underline=True),
Name.Class: Style(color="green", underline=True),
Name.Exception: Style(color="cyan"),
Name.Decorator: Style(color="magenta", bold=True),
Name.Variable: Style(color="red"),
Name.Constant: Style(color="red"),
Name.Attribute: Style(color="cyan"),
Name.Tag: Style(color="bright_blue"),
String: Style(color="yellow"),
Number: Style(color="blue"),
Generic.Deleted: Style(color="bright_red"),
Generic.Inserted: Style(color="green"),
Generic.Heading: Style(bold=True),
Generic.Subheading: Style(color="magenta", bold=True),
Generic.Prompt: Style(bold=True),
Generic.Error: Style(color="bright_red"),
Error: Style(color="red", underline=True),
}
ANSI_DARK: Dict[TokenType, Style] = {
Token: Style(),
Whitespace: Style(color="bright_black"),
Comment: Style(dim=True),
Comment.Preproc: Style(color="bright_cyan"),
Keyword: Style(color="bright_blue"),
Keyword.Type: Style(color="bright_cyan"),
Operator.Word: Style(color="bright_magenta"),
Name.Builtin: Style(color="bright_cyan"),
Name.Function: Style(color="bright_green"),
Name.Namespace: Style(color="bright_cyan", underline=True),
Name.Class: Style(color="bright_green", underline=True),
Name.Exception: Style(color="bright_cyan"),
Name.Decorator: Style(color="bright_magenta", bold=True),
Name.Variable: Style(color="bright_red"),
Name.Constant: Style(color="bright_red"),
Name.Attribute: Style(color="bright_cyan"),
Name.Tag: Style(color="bright_blue"),
String: Style(color="yellow"),
Number: Style(color="bright_blue"),
Generic.Deleted: Style(color="bright_red"),
Generic.Inserted: Style(color="bright_green"),
Generic.Heading: Style(bold=True),
Generic.Subheading: Style(color="bright_magenta", bold=True),
Generic.Prompt: Style(bold=True),
Generic.Error: Style(color="bright_red"),
Error: Style(color="red", underline=True),
}
RICH_SYNTAX_THEMES = {"ansi_light": ANSI_LIGHT, "ansi_dark": ANSI_DARK}
NUMBERS_COLUMN_DEFAULT_PADDING = 2
class SyntaxTheme(ABC):
@abstractmethod
def get_style_for_token(self, token_type: TokenType) -> Style:
raise NotImplementedError # pragma: no cover
@abstractmethod
def get_background_style(self) -> Style:
raise NotImplementedError # pragma: no cover
class PygmentsSyntaxTheme(SyntaxTheme):
def __init__(self, theme: Union[str, Type[PygmentsStyle]]) -> None:
self._style_cache: Dict[TokenType, Style] = {}
if isinstance(theme, str):
try:
self._pygments_style_class = get_style_by_name(theme)
except ClassNotFound:
self._pygments_style_class = get_style_by_name("default")
else:
self._pygments_style_class = theme
self._background_color = self._pygments_style_class.background_color
self._background_style = Style(bgcolor=self._background_color)
def get_style_for_token(self, token_type: TokenType) -> Style:
try:
return self._style_cache[token_type]
except KeyError:
try:
pygments_style = self._pygments_style_class.style_for_token(token_type)
except KeyError:
style = Style.null()
else:
color = pygments_style["color"]
bgcolor = pygments_style["bgcolor"]
style = Style(
color="#" + color if color else "#000000",
bgcolor="#" + bgcolor if bgcolor else self._background_color,
bold=pygments_style["bold"],
italic=pygments_style["italic"],
underline=pygments_style["underline"],
)
self._style_cache[token_type] = style
return style
def get_background_style(self) -> Style:
return self._background_style
class ANSISyntaxTheme(SyntaxTheme):
def __init__(self, style_map: Dict[TokenType, Style]) -> None:
self.style_map = style_map
self._missing_style = Style.null()
self._background_style = Style.null()
self._style_cache: Dict[TokenType, Style] = {}
def get_style_for_token(self, token_type: TokenType) -> Style:
try:
return self._style_cache[token_type]
except KeyError:
# Styles form a hierarchy
# We need to go from most to least specific
# e.g. ("foo", "bar", "baz") to ("foo", "bar") to ("foo",)
get_style = self.style_map.get
token = tuple(token_type)
style = self._missing_style
while token:
_style = get_style(token)
if _style is not None:
style = _style
break
token = token[:-1]
self._style_cache[token_type] = style
return style
def get_background_style(self) -> Style:
return self._background_style
SyntaxPosition = Tuple[int, int]
class _SyntaxHighlightRange(NamedTuple):
style: StyleType
start: SyntaxPosition
end: SyntaxPosition
style_before: bool = False
class PaddingProperty:
def __get__(self, obj: Syntax, objtype: Type[Syntax]) -> Tuple[int, int, int, int]:
return obj._padding
def __set__(self, obj: Syntax, padding: PaddingDimensions) -> None:
obj._padding = Padding.unpack(padding)
class Syntax(JupyterMixin):
_pygments_style_class: Type[PygmentsStyle]
_theme: SyntaxTheme
@classmethod
def get_theme(cls, name: Union[str, SyntaxTheme]) -> SyntaxTheme:
if isinstance(name, SyntaxTheme):
return name
theme: SyntaxTheme
if name in RICH_SYNTAX_THEMES:
theme = ANSISyntaxTheme(RICH_SYNTAX_THEMES[name])
else:
theme = PygmentsSyntaxTheme(name)
return theme
def __init__(
self,
code: str,
lexer: Union[Lexer, str],
*,
theme: Union[str, SyntaxTheme] = DEFAULT_THEME,
dedent: bool = False,
line_numbers: bool = False,
start_line: int = 1,
line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,
highlight_lines: Optional[Set[int]] = None,
code_width: Optional[int] = None,
tab_size: int = 4,
word_wrap: bool = False,
background_color: Optional[str] = None,
indent_guides: bool = False,
padding: PaddingDimensions = 0,
) -> None:
self.code = code
self._lexer = lexer
self.dedent = dedent
self.line_numbers = line_numbers
self.start_line = start_line
self.line_range = line_range
self.highlight_lines = highlight_lines or set()
self.code_width = code_width
self.tab_size = tab_size
self.word_wrap = word_wrap
self.background_color = background_color
self.background_style = (
Style(bgcolor=background_color) if background_color else Style()
)
self.indent_guides = indent_guides
self._padding = Padding.unpack(padding)
self._theme = self.get_theme(theme)
self._stylized_ranges: List[_SyntaxHighlightRange] = []
padding = PaddingProperty()
@classmethod
def from_path(
cls,
path: str,
encoding: str = "utf-8",
lexer: Optional[Union[Lexer, str]] = None,
theme: Union[str, SyntaxTheme] = DEFAULT_THEME,
dedent: bool = False,
line_numbers: bool = False,
line_range: Optional[Tuple[int, int]] = None,
start_line: int = 1,
highlight_lines: Optional[Set[int]] = None,
code_width: Optional[int] = None,
tab_size: int = 4,
word_wrap: bool = False,
background_color: Optional[str] = None,
indent_guides: bool = False,
padding: PaddingDimensions = 0,
) -> "Syntax":
code = Path(path).read_text(encoding=encoding)
if not lexer:
lexer = cls.guess_lexer(path, code=code)
return cls(
code,
lexer,
theme=theme,
dedent=dedent,
line_numbers=line_numbers,
line_range=line_range,
start_line=start_line,
highlight_lines=highlight_lines,
code_width=code_width,
tab_size=tab_size,
word_wrap=word_wrap,
background_color=background_color,
indent_guides=indent_guides,
padding=padding,
)
@classmethod
def guess_lexer(cls, path: str, code: Optional[str] = None) -> str:
lexer: Optional[Lexer] = None
lexer_name = "default"
if code:
try:
lexer = guess_lexer_for_filename(path, code)
except ClassNotFound:
pass
if not lexer:
try:
_, ext = os.path.splitext(path)
if ext:
extension = ext.lstrip(".").lower()
lexer = get_lexer_by_name(extension)
except ClassNotFound:
pass
if lexer:
if lexer.aliases:
lexer_name = lexer.aliases[0]
else:
lexer_name = lexer.name
return lexer_name
def _get_base_style(self) -> Style:
default_style = self._theme.get_background_style() + self.background_style
return default_style
def _get_token_color(self, token_type: TokenType) -> Optional[Color]:
style = self._theme.get_style_for_token(token_type)
return style.color
@property
def lexer(self) -> Optional[Lexer]:
if isinstance(self._lexer, Lexer):
return self._lexer
try:
return get_lexer_by_name(
self._lexer,
stripnl=False,
ensurenl=True,
tabsize=self.tab_size,
)
except ClassNotFound:
return None
@property
def default_lexer(self) -> Lexer:
return get_lexer_by_name(
"text",
stripnl=False,
ensurenl=True,
tabsize=self.tab_size,
)
def highlight(
self,
code: str,
line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,
) -> Text:
base_style = self._get_base_style()
justify: JustifyMethod = (
"default" if base_style.transparent_background else "left"
)
text = Text(
justify=justify,
style=base_style,
tab_size=self.tab_size,
no_wrap=not self.word_wrap,
)
_get_theme_style = self._theme.get_style_for_token
lexer = self.lexer or self.default_lexer
if lexer is None:
text.append(code)
else:
if line_range:
# More complicated path to only stylize a portion of the code
# This speeds up further operations as there are less spans to process
line_start, line_end = line_range
def line_tokenize() -> Iterable[Tuple[Any, str]]:
assert lexer # required to make MyPy happy - we know lexer is not None at this point
for token_type, token in lexer.get_tokens(code):
while token:
line_token, new_line, token = token.partition("\n")
yield token_type, line_token + new_line
def tokens_to_spans() -> Iterable[Tuple[str, Optional[Style]]]:
tokens = iter(line_tokenize())
line_no = 0
_line_start = line_start - 1 if line_start else 0
# Skip over tokens until line start
while line_no < _line_start:
try:
_token_type, token = next(tokens)
except StopIteration:
break
yield (token, None)
if token.endswith("\n"):
line_no += 1
# Generate spans until line end
for token_type, token in tokens:
yield (token, _get_theme_style(token_type))
if token.endswith("\n"):
line_no += 1
if line_end and line_no >= line_end:
break
text.append_tokens(tokens_to_spans())
else:
text.append_tokens(
(token, _get_theme_style(token_type))
for token_type, token in lexer.get_tokens(code)
)
if self.background_color is not None:
text.stylize(f"on {self.background_color}")
if self._stylized_ranges:
self._apply_stylized_ranges(text)
return text
def stylize_range(
self,
style: StyleType,
start: SyntaxPosition,
end: SyntaxPosition,
style_before: bool = False,
) -> None:
self._stylized_ranges.append(
_SyntaxHighlightRange(style, start, end, style_before)
)
def _get_line_numbers_color(self, blend: float = 0.3) -> Color:
background_style = self._theme.get_background_style() + self.background_style
background_color = background_style.bgcolor
if background_color is None or background_color.is_system_defined:
return Color.default()
foreground_color = self._get_token_color(Token.Text)
if foreground_color is None or foreground_color.is_system_defined:
return foreground_color or Color.default()
new_color = blend_rgb(
background_color.get_truecolor(),
foreground_color.get_truecolor(),
cross_fade=blend,
)
return Color.from_triplet(new_color)
@property
def _numbers_column_width(self) -> int:
column_width = 0
if self.line_numbers:
column_width = (
len(str(self.start_line + self.code.count("\n")))
+ NUMBERS_COLUMN_DEFAULT_PADDING
)
return column_width
def _get_number_styles(self, console: Console) -> Tuple[Style, Style, Style]:
background_style = self._get_base_style()
if background_style.transparent_background:
return Style.null(), Style(dim=True), Style.null()
if console.color_system in ("256", "truecolor"):
number_style = Style.chain(
background_style,
self._theme.get_style_for_token(Token.Text),
Style(color=self._get_line_numbers_color()),
self.background_style,
)
highlight_number_style = Style.chain(
background_style,
self._theme.get_style_for_token(Token.Text),
Style(bold=True, color=self._get_line_numbers_color(0.9)),
self.background_style,
)
else:
number_style = background_style + Style(dim=True)
highlight_number_style = background_style + Style(dim=False)
return background_style, number_style, highlight_number_style
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> "Measurement":
_, right, _, left = self.padding
padding = left + right
if self.code_width is not None:
width = self.code_width + self._numbers_column_width + padding + 1
return Measurement(self._numbers_column_width, width)
lines = self.code.splitlines()
width = (
self._numbers_column_width
+ padding
+ (max(cell_len(line) for line in lines) if lines else 0)
)
if self.line_numbers:
width += 1
return Measurement(self._numbers_column_width, width)
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
segments = Segments(self._get_syntax(console, options))
if any(self.padding):
yield Padding(segments, style=self._get_base_style(), pad=self.padding)
else:
yield segments
def _get_syntax(
self,
console: Console,
options: ConsoleOptions,
) -> Iterable[Segment]:
transparent_background = self._get_base_style().transparent_background
_pad_top, pad_right, _pad_bottom, pad_left = self.padding
horizontal_padding = pad_left + pad_right
code_width = (
(
(options.max_width - self._numbers_column_width - 1)
if self.line_numbers
else options.max_width
)
- horizontal_padding
if self.code_width is None
else self.code_width
)
code_width = max(0, code_width)
ends_on_nl, processed_code = self._process_code(self.code)
text = self.highlight(processed_code, self.line_range)
if not self.line_numbers and not self.word_wrap and not self.line_range:
if not ends_on_nl:
text.remove_suffix("\n")
# Simple case of just rendering text
style = (
self._get_base_style()
+ self._theme.get_style_for_token(Comment)
+ Style(dim=True)
+ self.background_style
)
if self.indent_guides and not options.ascii_only:
text = text.with_indent_guides(self.tab_size, style=style)
text.overflow = "crop"
if style.transparent_background:
yield from console.render(
text, options=options.update(width=code_width)
)
else:
syntax_lines = console.render_lines(
text,
options.update(width=code_width, height=None, justify="left"),
style=self.background_style,
pad=True,
new_lines=True,
)
for syntax_line in syntax_lines:
yield from syntax_line
return
start_line, end_line = self.line_range or (None, None)
line_offset = 0
if start_line:
line_offset = max(0, start_line - 1)
lines: Union[List[Text], Lines] = text.split("\n", allow_blank=ends_on_nl)
if self.line_range:
if line_offset > len(lines):
return
lines = lines[line_offset:end_line]
if self.indent_guides and not options.ascii_only:
style = (
self._get_base_style()
+ self._theme.get_style_for_token(Comment)
+ Style(dim=True)
+ self.background_style
)
lines = (
Text("\n")
.join(lines)
.with_indent_guides(self.tab_size, style=style + Style(italic=False))
.split("\n", allow_blank=True)
)
numbers_column_width = self._numbers_column_width
render_options = options.update(width=code_width)
highlight_line = self.highlight_lines.__contains__
_Segment = Segment
new_line = _Segment("\n")
line_pointer = "> " if options.legacy_windows else "❱ "
(
background_style,
number_style,
highlight_number_style,
) = self._get_number_styles(console)
for line_no, line in enumerate(lines, self.start_line + line_offset):
if self.word_wrap:
wrapped_lines = console.render_lines(
line,
render_options.update(height=None, justify="left"),
style=background_style,
pad=not transparent_background,
)
else:
segments = list(line.render(console, end=""))
if options.no_wrap:
wrapped_lines = [segments]
else:
wrapped_lines = [
_Segment.adjust_line_length(
segments,
render_options.max_width,
style=background_style,
pad=not transparent_background,
)
]
if self.line_numbers:
wrapped_line_left_pad = _Segment(
" " * numbers_column_width + " ", background_style
)
for first, wrapped_line in loop_first(wrapped_lines):
if first:
line_column = str(line_no).rjust(numbers_column_width - 2) + " "
if highlight_line(line_no):
yield _Segment(line_pointer, Style(color="red"))
yield _Segment(line_column, highlight_number_style)
else:
yield _Segment(" ", highlight_number_style)
yield _Segment(line_column, number_style)
else:
yield wrapped_line_left_pad
yield from wrapped_line
yield new_line
else:
for wrapped_line in wrapped_lines:
yield from wrapped_line
yield new_line
def _apply_stylized_ranges(self, text: Text) -> None:
code = text.plain
newlines_offsets = [
# Let's add outer boundaries at each side of the list:
0,
# N.B. using "\n" here is much faster than using metacharacters such as "^" or "\Z":
*[
match.start() + 1
for match in re.finditer("\n", code, flags=re.MULTILINE)
],
len(code) + 1,
]
for stylized_range in self._stylized_ranges:
start = _get_code_index_for_syntax_position(
newlines_offsets, stylized_range.start
)
end = _get_code_index_for_syntax_position(
newlines_offsets, stylized_range.end
)
if start is not None and end is not None:
if stylized_range.style_before:
text.stylize_before(stylized_range.style, start, end)
else:
text.stylize(stylized_range.style, start, end)
def _process_code(self, code: str) -> Tuple[bool, str]:
ends_on_nl = code.endswith("\n")
processed_code = code if ends_on_nl else code + "\n"
processed_code = (
textwrap.dedent(processed_code) if self.dedent else processed_code
)
processed_code = processed_code.expandtabs(self.tab_size)
return ends_on_nl, processed_code
def _get_code_index_for_syntax_position(
newlines_offsets: Sequence[int], position: SyntaxPosition
) -> Optional[int]:
lines_count = len(newlines_offsets)
line_number, column_index = position
if line_number > lines_count or len(newlines_offsets) < (line_number + 1):
return None # `line_number` is out of range
line_index = line_number - 1
line_length = newlines_offsets[line_index + 1] - newlines_offsets[line_index] - 1
# If `column_index` is out of range: let's silently clamp it:
column_index = min(line_length, column_index)
return newlines_offsets[line_index] + column_index
if __name__ == "__main__": # pragma: no cover
import argparse
import sys
parser = argparse.ArgumentParser(
description="Render syntax to the console with Rich"
)
parser.add_argument(
"path",
metavar="PATH",
help="path to file, or - for stdin",
)
parser.add_argument(
"-c",
"--force-color",
dest="force_color",
action="store_true",
default=None,
help="force color for non-terminals",
)
parser.add_argument(
"-i",
"--indent-guides",
dest="indent_guides",
action="store_true",
default=False,
help="display indent guides",
)
parser.add_argument(
"-l",
"--line-numbers",
dest="line_numbers",
action="store_true",
help="render line numbers",
)
parser.add_argument(
"-w",
"--width",
type=int,
dest="width",
default=None,
help="width of output (default will auto-detect)",
)
parser.add_argument(
"-r",
"--wrap",
dest="word_wrap",
action="store_true",
default=False,
help="word wrap long lines",
)
parser.add_argument(
"-s",
"--soft-wrap",
action="store_true",
dest="soft_wrap",
default=False,
help="enable soft wrapping mode",
)
parser.add_argument(
"-t", "--theme", dest="theme", default="monokai", help="pygments theme"
)
parser.add_argument(
"-b",
"--background-color",
dest="background_color",
default=None,
help="Override background color",
)
parser.add_argument(
"-x",
"--lexer",
default=None,
dest="lexer_name",
help="Lexer name",
)
parser.add_argument(
"-p", "--padding", type=int, default=0, dest="padding", help="Padding"
)
parser.add_argument(
"--highlight-line",
type=int,
default=None,
dest="highlight_line",
help="The line number (not index!) to highlight",
)
args = parser.parse_args()
from rich.console import Console
console = Console(force_terminal=args.force_color, width=args.width)
if args.path == "-":
code = sys.stdin.read()
syntax = Syntax(
code=code,
lexer=args.lexer_name,
line_numbers=args.line_numbers,
word_wrap=args.word_wrap,
theme=args.theme,
background_color=args.background_color,
indent_guides=args.indent_guides,
padding=args.padding,
highlight_lines={args.highlight_line},
)
else:
syntax = Syntax.from_path(
args.path,
lexer=args.lexer_name,
line_numbers=args.line_numbers,
word_wrap=args.word_wrap,
theme=args.theme,
background_color=args.background_color,
indent_guides=args.indent_guides,
padding=args.padding,
highlight_lines={args.highlight_line},
)
console.print(syntax, soft_wrap=args.soft_wrap) | --- +++ @@ -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
@abstractmethod
def get_background_style(self) -> Style:
+ """Get the background color."""
raise NotImplementedError # pragma: no cover
class PygmentsSyntaxTheme(SyntaxTheme):
+ """Syntax theme that delegates to Pygments theme."""
def __init__(self, theme: Union[str, Type[PygmentsStyle]]) -> None:
self._style_cache: Dict[TokenType, Style] = {}
@@ -148,6 +152,7 @@ self._background_style = Style(bgcolor=self._background_color)
def get_style_for_token(self, token_type: TokenType) -> Style:
+ """Get a style from a Pygments class."""
try:
return self._style_cache[token_type]
except KeyError:
@@ -173,6 +178,7 @@
class ANSISyntaxTheme(SyntaxTheme):
+ """Syntax theme to use standard colors."""
def __init__(self, style_map: Dict[TokenType, Style]) -> None:
self.style_map = style_map
@@ -181,6 +187,7 @@ self._style_cache: Dict[TokenType, Style] = {}
def get_style_for_token(self, token_type: TokenType) -> Style:
+ """Look up style in the style map."""
try:
return self._style_cache[token_type]
except KeyError:
@@ -207,6 +214,11 @@
class _SyntaxHighlightRange(NamedTuple):
+ """
+ A range to highlight in a Syntax object.
+ `start` and `end` are 2-integers tuples, where the first integer is the line number
+ (starting from 1) and the second integer is the column index (starting from 0).
+ """
style: StyleType
start: SyntaxPosition
@@ -215,8 +227,10 @@
class PaddingProperty:
+ """Descriptor to get and set padding."""
def __get__(self, obj: Syntax, objtype: Type[Syntax]) -> Tuple[int, int, int, int]:
+ """Space around the Syntax."""
return obj._padding
def __set__(self, obj: Syntax, padding: PaddingDimensions) -> None:
@@ -224,12 +238,32 @@
class Syntax(JupyterMixin):
+ """Construct a Syntax object to render syntax highlighted code.
+
+ Args:
+ code (str): Code to highlight.
+ lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/)
+ theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "monokai".
+ dedent (bool, optional): Enable stripping of initial whitespace. Defaults to False.
+ line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
+ start_line (int, optional): Starting number for line numbers. Defaults to 1.
+ line_range (Tuple[int | None, int | None], optional): If given should be a tuple of the start and end line to render.
+ A value of None in the tuple indicates the range is open in that direction.
+ highlight_lines (Set[int]): A set of line numbers to highlight.
+ code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
+ tab_size (int, optional): Size of tabs. Defaults to 4.
+ word_wrap (bool, optional): Enable word wrapping.
+ background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.
+ indent_guides (bool, optional): Show indent guides. Defaults to False.
+ padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).
+ """
_pygments_style_class: Type[PygmentsStyle]
_theme: SyntaxTheme
@classmethod
def get_theme(cls, name: Union[str, SyntaxTheme]) -> SyntaxTheme:
+ """Get a syntax theme instance."""
if isinstance(name, SyntaxTheme):
return name
theme: SyntaxTheme
@@ -298,6 +332,28 @@ indent_guides: bool = False,
padding: PaddingDimensions = 0,
) -> "Syntax":
+ """Construct a Syntax object from a file.
+
+ Args:
+ path (str): Path to file to highlight.
+ encoding (str): Encoding of file.
+ lexer (str | Lexer, optional): Lexer to use. If None, lexer will be auto-detected from path/file content.
+ theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "emacs".
+ dedent (bool, optional): Enable stripping of initial whitespace. Defaults to True.
+ line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
+ start_line (int, optional): Starting number for line numbers. Defaults to 1.
+ line_range (Tuple[int, int], optional): If given should be a tuple of the start and end line to render.
+ highlight_lines (Set[int]): A set of line numbers to highlight.
+ code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
+ tab_size (int, optional): Size of tabs. Defaults to 4.
+ word_wrap (bool, optional): Enable word wrapping of code.
+ background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.
+ indent_guides (bool, optional): Show indent guides. Defaults to False.
+ padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).
+
+ Returns:
+ [Syntax]: A Syntax object that may be printed to the console
+ """
code = Path(path).read_text(encoding=encoding)
if not lexer:
@@ -322,6 +378,21 @@
@classmethod
def guess_lexer(cls, path: str, code: Optional[str] = None) -> str:
+ """Guess the alias of the Pygments lexer to use based on a path and an optional string of code.
+ If code is supplied, it will use a combination of the code and the filename to determine the
+ best lexer to use. For example, if the file is ``index.html`` and the file contains Django
+ templating syntax, then "html+django" will be returned. If the file is ``index.html``, and no
+ templating language is used, the "html" lexer will be used. If no string of code
+ is supplied, the lexer will be chosen based on the file extension..
+
+ Args:
+ path (AnyStr): The path to the file containing the code you wish to know the lexer for.
+ code (str, optional): Optional string of code that will be used as a fallback if no lexer
+ is found for the supplied path.
+
+ Returns:
+ str: The name of the Pygments lexer that best matches the supplied path/code.
+ """
lexer: Optional[Lexer] = None
lexer_name = "default"
if code:
@@ -348,15 +419,28 @@ return lexer_name
def _get_base_style(self) -> Style:
+ """Get the base style."""
default_style = self._theme.get_background_style() + self.background_style
return default_style
def _get_token_color(self, token_type: TokenType) -> Optional[Color]:
+ """Get a color (if any) for the given token.
+
+ Args:
+ token_type (TokenType): A token type tuple from Pygments.
+
+ Returns:
+ Optional[Color]: Color from theme, or None for no color.
+ """
style = self._theme.get_style_for_token(token_type)
return style.color
@property
def lexer(self) -> Optional[Lexer]:
+ """The lexer for this syntax, or None if no lexer was found.
+
+ Tries to find the lexer by name if a string was passed to the constructor.
+ """
if isinstance(self._lexer, Lexer):
return self._lexer
@@ -372,6 +456,7 @@
@property
def default_lexer(self) -> Lexer:
+ """A Pygments Lexer to use if one is not specified or invalid."""
return get_lexer_by_name(
"text",
stripnl=False,
@@ -384,6 +469,15 @@ code: str,
line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,
) -> Text:
+ """Highlight code and return a Text instance.
+
+ Args:
+ code (str): Code to highlight.
+ line_range(Tuple[int, int], optional): Optional line range to highlight.
+
+ Returns:
+ Text: A text instance containing highlighted syntax.
+ """
base_style = self._get_base_style()
justify: JustifyMethod = (
@@ -409,6 +503,7 @@ line_start, line_end = line_range
def line_tokenize() -> Iterable[Tuple[Any, str]]:
+ """Split tokens to one per line."""
assert lexer # required to make MyPy happy - we know lexer is not None at this point
for token_type, token in lexer.get_tokens(code):
@@ -417,6 +512,7 @@ yield token_type, line_token + new_line
def tokens_to_spans() -> Iterable[Tuple[str, Optional[Style]]]:
+ """Convert tokens to spans."""
tokens = iter(line_tokenize())
line_no = 0
_line_start = line_start - 1 if line_start else 0
@@ -460,6 +556,16 @@ end: SyntaxPosition,
style_before: bool = False,
) -> None:
+ """
+ Adds a custom style on a part of the code, that will be applied to the syntax display when it's rendered.
+ Line numbers are 1-based, while column indexes are 0-based.
+
+ Args:
+ style (StyleType): The style to apply.
+ start (Tuple[int, int]): The start of the range, in the form `[line number, column index]`.
+ end (Tuple[int, int]): The end of the range, in the form `[line number, column index]`.
+ style_before (bool): Apply the style before any existing styles.
+ """
self._stylized_ranges.append(
_SyntaxHighlightRange(style, start, end, style_before)
)
@@ -481,6 +587,7 @@
@property
def _numbers_column_width(self) -> int:
+ """Get the number of characters used to render the numbers column."""
column_width = 0
if self.line_numbers:
column_width = (
@@ -490,6 +597,7 @@ return column_width
def _get_number_styles(self, console: Console) -> Tuple[Style, Style, Style]:
+ """Get background, number, and highlight styles for line numbers."""
background_style = self._get_base_style()
if background_style.transparent_background:
return Style.null(), Style(dim=True), Style.null()
@@ -543,6 +651,9 @@ console: Console,
options: ConsoleOptions,
) -> Iterable[Segment]:
+ """
+ Get the Segments for the Syntax object, excluding any vertical/horizontal padding
+ """
transparent_background = self._get_base_style().transparent_background
_pad_top, pad_right, _pad_bottom, pad_left = self.padding
horizontal_padding = pad_left + pad_right
@@ -674,6 +785,13 @@ yield new_line
def _apply_stylized_ranges(self, text: Text) -> None:
+ """
+ Apply stylized ranges to a text instance,
+ using the given code to determine the right portion to apply the style to.
+
+ Args:
+ text (Text): Text instance to apply the style to.
+ """
code = text.plain
newlines_offsets = [
# Let's add outer boundaries at each side of the list:
@@ -700,6 +818,17 @@ text.stylize(stylized_range.style, start, end)
def _process_code(self, code: str) -> Tuple[bool, str]:
+ """
+ Applies various processing to a raw code string
+ (normalises it so it always ends with a line return, dedents it if necessary, etc.)
+
+ Args:
+ code (str): The raw code string to process
+
+ Returns:
+ Tuple[bool, str]: the boolean indicates whether the raw code ends with a line return,
+ while the string is the processed code.
+ """
ends_on_nl = code.endswith("\n")
processed_code = code if ends_on_nl else code + "\n"
processed_code = (
@@ -712,6 +841,18 @@ def _get_code_index_for_syntax_position(
newlines_offsets: Sequence[int], position: SyntaxPosition
) -> Optional[int]:
+ """
+ Returns the index of the code string for the given positions.
+
+ Args:
+ newlines_offsets (Sequence[int]): The offset of each newline character found in the code snippet.
+ position (SyntaxPosition): The position to search for.
+
+ Returns:
+ Optional[int]: The index of the code string for this position, or `None`
+ if the given position's line number is out of range (if it's the column that is out of range
+ we silently clamp its value so that it reaches the end of the line)
+ """
lines_count = len(newlines_offsets)
line_number, column_index = position
@@ -841,4 +982,4 @@ padding=args.padding,
highlight_lines={args.highlight_line},
)
- console.print(syntax, soft_wrap=args.soft_wrap)+ console.print(syntax, soft_wrap=args.soft_wrap)
| 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 .styled import Styled
GuideType = Tuple[str, str, str, str]
class Tree(JupyterMixin):
ASCII_GUIDES = (" ", "| ", "+-- ", "`-- ")
TREE_GUIDES = [
(" ", "│ ", "├── ", "└── "),
(" ", "┃ ", "┣━━ ", "┗━━ "),
(" ", "║ ", "╠══ ", "╚══ "),
]
def __init__(
self,
label: RenderableType,
*,
style: StyleType = "tree",
guide_style: StyleType = "tree.line",
expanded: bool = True,
highlight: bool = False,
hide_root: bool = False,
) -> None:
self.label = label
self.style = style
self.guide_style = guide_style
self.children: List[Tree] = []
self.expanded = expanded
self.highlight = highlight
self.hide_root = hide_root
def add(
self,
label: RenderableType,
*,
style: Optional[StyleType] = None,
guide_style: Optional[StyleType] = None,
expanded: bool = True,
highlight: Optional[bool] = False,
) -> "Tree":
node = Tree(
label,
style=self.style if style is None else style,
guide_style=self.guide_style if guide_style is None else guide_style,
expanded=expanded,
highlight=self.highlight if highlight is None else highlight,
)
self.children.append(node)
return node
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> "RenderResult":
stack: List[Iterator[Tuple[bool, Tree]]] = []
pop = stack.pop
push = stack.append
new_line = Segment.line()
get_style = console.get_style
null_style = Style.null()
guide_style = get_style(self.guide_style, default="") or null_style
SPACE, CONTINUE, FORK, END = range(4)
_Segment = Segment
def make_guide(index: int, style: Style) -> Segment:
if options.ascii_only:
line = self.ASCII_GUIDES[index]
else:
guide = 1 if style.bold else (2 if style.underline2 else 0)
line = self.TREE_GUIDES[0 if options.legacy_windows else guide][index]
return _Segment(line, style)
levels: List[Segment] = [make_guide(CONTINUE, guide_style)]
push(iter(loop_last([self])))
guide_style_stack = StyleStack(get_style(self.guide_style))
style_stack = StyleStack(get_style(self.style))
remove_guide_styles = Style(bold=False, underline2=False)
depth = 0
while stack:
stack_node = pop()
try:
last, node = next(stack_node)
except StopIteration:
levels.pop()
if levels:
guide_style = levels[-1].style or null_style
levels[-1] = make_guide(FORK, guide_style)
guide_style_stack.pop()
style_stack.pop()
continue
push(stack_node)
if last:
levels[-1] = make_guide(END, levels[-1].style or null_style)
guide_style = guide_style_stack.current + get_style(node.guide_style)
style = style_stack.current + get_style(node.style)
prefix = levels[(2 if self.hide_root else 1) :]
renderable_lines = console.render_lines(
Styled(node.label, style),
options.update(
width=options.max_width
- sum(level.cell_length for level in prefix),
highlight=self.highlight,
height=None,
),
pad=options.justify is not None,
)
if not (depth == 0 and self.hide_root):
for first, line in loop_first(renderable_lines):
if prefix:
yield from _Segment.apply_style(
prefix,
style.background_style,
post_style=remove_guide_styles,
)
yield from line
yield new_line
if first and prefix:
prefix[-1] = make_guide(
SPACE if last else CONTINUE, prefix[-1].style or null_style
)
if node.expanded and node.children:
levels[-1] = make_guide(
SPACE if last else CONTINUE, levels[-1].style or null_style
)
levels.append(
make_guide(END if len(node.children) == 1 else FORK, guide_style)
)
style_stack.push(get_style(node.style))
guide_style_stack.push(get_style(node.guide_style))
push(iter(loop_last(node.children)))
depth += 1
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> "Measurement":
stack: List[Iterator[Tree]] = [iter([self])]
pop = stack.pop
push = stack.append
minimum = 0
maximum = 0
measure = Measurement.get
level = 0
while stack:
iter_tree = pop()
try:
tree = next(iter_tree)
except StopIteration:
level -= 1
continue
push(iter_tree)
min_measure, max_measure = measure(console, options, tree.label)
indent = level * 4
minimum = max(min_measure + indent, minimum)
maximum = max(max_measure + indent, maximum)
if tree.expanded and tree.children:
push(iter(tree.children))
level += 1
return Measurement(minimum, maximum)
if __name__ == "__main__": # pragma: no cover
from rich.console import Group
from rich.markdown import Markdown
from rich.panel import Panel
from rich.syntax import Syntax
from rich.table import Table
table = Table(row_styles=["", "dim"])
table.add_column("Released", style="cyan", no_wrap=True)
table.add_column("Title", style="magenta")
table.add_column("Box Office", justify="right", style="green")
table.add_row("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$952,110,690")
table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347")
table.add_row("Dec 15, 2017", "Star Wars Ep. V111: The Last Jedi", "$1,332,539,889")
table.add_row("Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889")
code = """\
class Segment(NamedTuple):
text: str = ""
style: Optional[Style] = None
is_control: bool = False
"""
syntax = Syntax(code, "python", theme="monokai", line_numbers=True)
markdown = Markdown(
"""\
### example.md
> Hello, World!
>
> Markdown _all_ the things
"""
)
root = Tree("🌲 [b green]Rich Tree", highlight=True, hide_root=True)
node = root.add(":file_folder: Renderables", guide_style="red")
simple_node = node.add(":file_folder: [bold yellow]Atomic", guide_style="uu green")
simple_node.add(Group("📄 Syntax", syntax))
simple_node.add(Group("📄 Markdown", Panel(markdown, border_style="green")))
containers_node = node.add(
":file_folder: [bold magenta]Containers", guide_style="bold magenta"
)
containers_node.expanded = True
panel = Panel.fit("Just a panel", border_style="red")
containers_node.add(Group("📄 Panels", panel))
containers_node.add(Group("📄 [b magenta]Table", table))
console = Console()
console.print(root) | --- +++ @@ -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 (RenderableType): The renderable or str for the tree label.
+ style (StyleType, optional): Style of this tree. Defaults to "tree".
+ guide_style (StyleType, optional): Style of the guide lines. Defaults to "tree.line".
+ expanded (bool, optional): Also display children. Defaults to True.
+ highlight (bool, optional): Highlight renderable (if str). Defaults to False.
+ hide_root (bool, optional): Hide the root node. Defaults to False.
+ """
ASCII_GUIDES = (" ", "| ", "+-- ", "`-- ")
TREE_GUIDES = [
@@ -47,6 +61,18 @@ expanded: bool = True,
highlight: Optional[bool] = False,
) -> "Tree":
+ """Add a child tree.
+
+ Args:
+ label (RenderableType): The renderable or str for the tree label.
+ style (StyleType, optional): Style of this tree. Defaults to "tree".
+ guide_style (StyleType, optional): Style of the guide lines. Defaults to "tree.line".
+ expanded (bool, optional): Also display children. Defaults to True.
+ highlight (Optional[bool], optional): Highlight renderable (if str). Defaults to False.
+
+ Returns:
+ Tree: A new child Tree, which may be further modified.
+ """
node = Tree(
label,
style=self.style if style is None else style,
@@ -73,6 +99,7 @@ _Segment = Segment
def make_guide(index: int, style: Style) -> Segment:
+ """Make a Segment for a level of the guide lines."""
if options.ascii_only:
line = self.ASCII_GUIDES[index]
else:
@@ -227,4 +254,4 @@
console = Console()
- console.print(root)+ console.print(root)
| 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, Memory, Message
class BaseAgent(BaseModel, ABC):
# Core attributes
name: str = Field(..., description="Unique name of the agent")
description: Optional[str] = Field(None, description="Optional agent description")
# Prompts
system_prompt: Optional[str] = Field(
None, description="System-level instruction prompt"
)
next_step_prompt: Optional[str] = Field(
None, description="Prompt for determining next action"
)
# Dependencies
llm: LLM = Field(default_factory=LLM, description="Language model instance")
memory: Memory = Field(default_factory=Memory, description="Agent's memory store")
state: AgentState = Field(
default=AgentState.IDLE, description="Current agent state"
)
# Execution control
max_steps: int = Field(default=10, description="Maximum steps before termination")
current_step: int = Field(default=0, description="Current step in execution")
duplicate_threshold: int = 2
class Config:
arbitrary_types_allowed = True
extra = "allow" # Allow extra fields for flexibility in subclasses
@model_validator(mode="after")
def initialize_agent(self) -> "BaseAgent":
if self.llm is None or not isinstance(self.llm, LLM):
self.llm = LLM(config_name=self.name.lower())
if not isinstance(self.memory, Memory):
self.memory = Memory()
return self
@asynccontextmanager
async def state_context(self, new_state: AgentState):
if not isinstance(new_state, AgentState):
raise ValueError(f"Invalid state: {new_state}")
previous_state = self.state
self.state = new_state
try:
yield
except Exception as e:
self.state = AgentState.ERROR # Transition to ERROR on failure
raise e
finally:
self.state = previous_state # Revert to previous state
def update_memory(
self,
role: ROLE_TYPE, # type: ignore
content: str,
base64_image: Optional[str] = None,
**kwargs,
) -> None:
message_map = {
"user": Message.user_message,
"system": Message.system_message,
"assistant": Message.assistant_message,
"tool": lambda content, **kw: Message.tool_message(content, **kw),
}
if role not in message_map:
raise ValueError(f"Unsupported message role: {role}")
# Create message with appropriate parameters based on role
kwargs = {"base64_image": base64_image, **(kwargs if role == "tool" else {})}
self.memory.add_message(message_map[role](content, **kwargs))
async def run(self, request: Optional[str] = None) -> str:
if self.state != AgentState.IDLE:
raise RuntimeError(f"Cannot run agent from state: {self.state}")
if request:
self.update_memory("user", request)
results: List[str] = []
async with self.state_context(AgentState.RUNNING):
while (
self.current_step < self.max_steps and self.state != AgentState.FINISHED
):
self.current_step += 1
logger.info(f"Executing step {self.current_step}/{self.max_steps}")
step_result = await self.step()
# Check for stuck state
if self.is_stuck():
self.handle_stuck_state()
results.append(f"Step {self.current_step}: {step_result}")
if self.current_step >= self.max_steps:
self.current_step = 0
self.state = AgentState.IDLE
results.append(f"Terminated: Reached max steps ({self.max_steps})")
await SANDBOX_CLIENT.cleanup()
return "\n".join(results) if results else "No steps executed"
@abstractmethod
async def step(self) -> str:
def handle_stuck_state(self):
stuck_prompt = "\
Observed duplicate responses. Consider new strategies and avoid repeating ineffective paths already attempted."
self.next_step_prompt = f"{stuck_prompt}\n{self.next_step_prompt}"
logger.warning(f"Agent detected stuck state. Added prompt: {stuck_prompt}")
def is_stuck(self) -> bool:
if len(self.memory.messages) < 2:
return False
last_message = self.memory.messages[-1]
if not last_message.content:
return False
# Count identical content occurrences
duplicate_count = sum(
1
for msg in reversed(self.memory.messages[:-1])
if msg.role == "assistant" and msg.content == last_message.content
)
return duplicate_count >= self.duplicate_threshold
@property
def messages(self) -> List[Message]:
return self.memory.messages
@messages.setter
def messages(self, value: List[Message]):
self.memory.messages = value | --- +++ @@ -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.
+ """
# Core attributes
name: str = Field(..., description="Unique name of the agent")
@@ -43,6 +48,7 @@
@model_validator(mode="after")
def initialize_agent(self) -> "BaseAgent":
+ """Initialize agent with default settings if not provided."""
if self.llm is None or not isinstance(self.llm, LLM):
self.llm = LLM(config_name=self.name.lower())
if not isinstance(self.memory, Memory):
@@ -51,6 +57,17 @@
@asynccontextmanager
async def state_context(self, new_state: AgentState):
+ """Context manager for safe agent state transitions.
+
+ Args:
+ new_state: The state to transition to during the context.
+
+ Yields:
+ None: Allows execution within the new state.
+
+ Raises:
+ ValueError: If the new_state is invalid.
+ """
if not isinstance(new_state, AgentState):
raise ValueError(f"Invalid state: {new_state}")
@@ -71,6 +88,17 @@ base64_image: Optional[str] = None,
**kwargs,
) -> None:
+ """Add a message to the agent's memory.
+
+ Args:
+ role: The role of the message sender (user, system, assistant, tool).
+ content: The message content.
+ base64_image: Optional base64 encoded image.
+ **kwargs: Additional arguments (e.g., tool_call_id for tool messages).
+
+ Raises:
+ ValueError: If the role is unsupported.
+ """
message_map = {
"user": Message.user_message,
"system": Message.system_message,
@@ -86,6 +114,17 @@ self.memory.add_message(message_map[role](content, **kwargs))
async def run(self, request: Optional[str] = None) -> str:
+ """Execute the agent's main loop asynchronously.
+
+ Args:
+ request: Optional initial user request to process.
+
+ Returns:
+ A string summarizing the execution results.
+
+ Raises:
+ RuntimeError: If the agent is not in IDLE state at start.
+ """
if self.state != AgentState.IDLE:
raise RuntimeError(f"Cannot run agent from state: {self.state}")
@@ -116,14 +155,20 @@
@abstractmethod
async def step(self) -> str:
+ """Execute a single step in the agent's workflow.
+
+ Must be implemented by subclasses to define specific behavior.
+ """
def handle_stuck_state(self):
+ """Handle stuck state by adding a prompt to change strategy"""
stuck_prompt = "\
Observed duplicate responses. Consider new strategies and avoid repeating ineffective paths already attempted."
self.next_step_prompt = f"{stuck_prompt}\n{self.next_step_prompt}"
logger.warning(f"Agent detected stuck state. Added prompt: {stuck_prompt}")
def is_stuck(self) -> bool:
+ """Check if the agent is stuck in a loop by detecting duplicate content"""
if len(self.memory.messages) < 2:
return False
@@ -142,8 +187,10 @@
@property
def messages(self) -> List[Message]:
+ """Retrieve a list of messages from the agent's memory."""
return self.memory.messages
@messages.setter
def messages(self, value: List[Message]):
- self.memory.messages = value+ """Set the list of messages in the agent's memory."""
+ self.memory.messages = value
| 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 Align
from .console import Console, ConsoleOptions, RenderableType, RenderResult
from .highlighter import ReprHighlighter
from .panel import Panel
from .pretty import Pretty
from .region import Region
from .repr import Result, rich_repr
from .segment import Segment
from .style import StyleType
if TYPE_CHECKING:
from rich.tree import Tree
class LayoutRender(NamedTuple):
region: Region
render: List[List[Segment]]
RegionMap = Dict["Layout", Region]
RenderMap = Dict["Layout", LayoutRender]
class LayoutError(Exception):
class NoSplitter(LayoutError):
class _Placeholder:
highlighter = ReprHighlighter()
def __init__(self, layout: "Layout", style: StyleType = "") -> None:
self.layout = layout
self.style = style
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
width = options.max_width
height = options.height or options.size.height
layout = self.layout
title = (
f"{layout.name!r} ({width} x {height})"
if layout.name
else f"({width} x {height})"
)
yield Panel(
Align.center(Pretty(layout), vertical="middle"),
style=self.style,
title=self.highlighter(title),
border_style="blue",
height=height,
)
class Splitter(ABC):
name: str = ""
@abstractmethod
def get_tree_icon(self) -> str:
@abstractmethod
def divide(
self, children: Sequence["Layout"], region: Region
) -> Iterable[Tuple["Layout", Region]]:
class RowSplitter(Splitter):
name = "row"
def get_tree_icon(self) -> str:
return "[layout.tree.row]⬌"
def divide(
self, children: Sequence["Layout"], region: Region
) -> Iterable[Tuple["Layout", Region]]:
x, y, width, height = region
render_widths = ratio_resolve(width, children)
offset = 0
_Region = Region
for child, child_width in zip(children, render_widths):
yield child, _Region(x + offset, y, child_width, height)
offset += child_width
class ColumnSplitter(Splitter):
name = "column"
def get_tree_icon(self) -> str:
return "[layout.tree.column]⬍"
def divide(
self, children: Sequence["Layout"], region: Region
) -> Iterable[Tuple["Layout", Region]]:
x, y, width, height = region
render_heights = ratio_resolve(height, children)
offset = 0
_Region = Region
for child, child_height in zip(children, render_heights):
yield child, _Region(x, y + offset, width, child_height)
offset += child_height
@rich_repr
class Layout:
splitters = {"row": RowSplitter, "column": ColumnSplitter}
def __init__(
self,
renderable: Optional[RenderableType] = None,
*,
name: Optional[str] = None,
size: Optional[int] = None,
minimum_size: int = 1,
ratio: int = 1,
visible: bool = True,
) -> None:
self._renderable = renderable or _Placeholder(self)
self.size = size
self.minimum_size = minimum_size
self.ratio = ratio
self.name = name
self.visible = visible
self.splitter: Splitter = self.splitters["column"]()
self._children: List[Layout] = []
self._render_map: RenderMap = {}
self._lock = RLock()
def __rich_repr__(self) -> Result:
yield "name", self.name, None
yield "size", self.size, None
yield "minimum_size", self.minimum_size, 1
yield "ratio", self.ratio, 1
@property
def renderable(self) -> RenderableType:
return self if self._children else self._renderable
@property
def children(self) -> List["Layout"]:
return [child for child in self._children if child.visible]
@property
def map(self) -> RenderMap:
return self._render_map
def get(self, name: str) -> Optional["Layout"]:
if self.name == name:
return self
else:
for child in self._children:
named_layout = child.get(name)
if named_layout is not None:
return named_layout
return None
def __getitem__(self, name: str) -> "Layout":
layout = self.get(name)
if layout is None:
raise KeyError(f"No layout with name {name!r}")
return layout
@property
def tree(self) -> "Tree":
from rich.styled import Styled
from rich.table import Table
from rich.tree import Tree
def summary(layout: "Layout") -> Table:
icon = layout.splitter.get_tree_icon()
table = Table.grid(padding=(0, 1, 0, 0))
text: RenderableType = (
Pretty(layout) if layout.visible else Styled(Pretty(layout), "dim")
)
table.add_row(icon, text)
_summary = table
return _summary
layout = self
tree = Tree(
summary(layout),
guide_style=f"layout.tree.{layout.splitter.name}",
highlight=True,
)
def recurse(tree: "Tree", layout: "Layout") -> None:
for child in layout._children:
recurse(
tree.add(
summary(child),
guide_style=f"layout.tree.{child.splitter.name}",
),
child,
)
recurse(tree, self)
return tree
def split(
self,
*layouts: Union["Layout", RenderableType],
splitter: Union[Splitter, str] = "column",
) -> None:
_layouts = [
layout if isinstance(layout, Layout) else Layout(layout)
for layout in layouts
]
try:
self.splitter = (
splitter
if isinstance(splitter, Splitter)
else self.splitters[splitter]()
)
except KeyError:
raise NoSplitter(f"No splitter called {splitter!r}")
self._children[:] = _layouts
def add_split(self, *layouts: Union["Layout", RenderableType]) -> None:
_layouts = (
layout if isinstance(layout, Layout) else Layout(layout)
for layout in layouts
)
self._children.extend(_layouts)
def split_row(self, *layouts: Union["Layout", RenderableType]) -> None:
self.split(*layouts, splitter="row")
def split_column(self, *layouts: Union["Layout", RenderableType]) -> None:
self.split(*layouts, splitter="column")
def unsplit(self) -> None:
del self._children[:]
def update(self, renderable: RenderableType) -> None:
with self._lock:
self._renderable = renderable
def refresh_screen(self, console: "Console", layout_name: str) -> None:
with self._lock:
layout = self[layout_name]
region, _lines = self._render_map[layout]
(x, y, width, height) = region
lines = console.render_lines(
layout, console.options.update_dimensions(width, height)
)
self._render_map[layout] = LayoutRender(region, lines)
console.update_screen_lines(lines, x, y)
def _make_region_map(self, width: int, height: int) -> RegionMap:
stack: List[Tuple[Layout, Region]] = [(self, Region(0, 0, width, height))]
push = stack.append
pop = stack.pop
layout_regions: List[Tuple[Layout, Region]] = []
append_layout_region = layout_regions.append
while stack:
append_layout_region(pop())
layout, region = layout_regions[-1]
children = layout.children
if children:
for child_and_region in layout.splitter.divide(children, region):
push(child_and_region)
region_map = {
layout: region
for layout, region in sorted(layout_regions, key=itemgetter(1))
}
return region_map
def render(self, console: Console, options: ConsoleOptions) -> RenderMap:
render_width = options.max_width
render_height = options.height or console.height
region_map = self._make_region_map(render_width, render_height)
layout_regions = [
(layout, region)
for layout, region in region_map.items()
if not layout.children
]
render_map: Dict["Layout", "LayoutRender"] = {}
render_lines = console.render_lines
update_dimensions = options.update_dimensions
for layout, region in layout_regions:
lines = render_lines(
layout.renderable, update_dimensions(region.width, region.height)
)
render_map[layout] = LayoutRender(region, lines)
return render_map
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
with self._lock:
width = options.max_width or console.width
height = options.height or console.height
render_map = self.render(console, options.update_dimensions(width, height))
self._render_map = render_map
layout_lines: List[List[Segment]] = [[] for _ in range(height)]
_islice = islice
for region, lines in render_map.values():
_x, y, _layout_width, layout_height = region
for row, line in zip(
_islice(layout_lines, y, y + layout_height), lines
):
row.extend(line)
new_line = Segment.line()
for layout_row in layout_lines:
yield from layout_row
yield new_line
if __name__ == "__main__":
from rich.console import Console
console = Console()
layout = Layout()
layout.split_column(
Layout(name="header", size=3),
Layout(ratio=1, name="main"),
Layout(size=10, name="footer"),
)
layout["main"].split_row(Layout(name="side"), Layout(name="body", ratio=2))
layout["body"].split_row(Layout(name="content", ratio=2), Layout(name="s2"))
layout["s2"].split_column(
Layout(name="top"), Layout(name="middle"), Layout(name="bottom")
)
layout["side"].split_column(Layout(layout.tree, name="left1"), Layout(name="left2"))
layout["content"].update("foo")
console.print(layout) | --- +++ @@ -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 exist."""
class _Placeholder:
+ """An internal renderable used as a Layout placeholder."""
highlighter = ReprHighlighter()
@@ -74,19 +78,28 @@
class Splitter(ABC):
+ """Base class for a splitter."""
name: str = ""
@abstractmethod
def get_tree_icon(self) -> str:
+ """Get the icon (emoji) used in layout.tree"""
@abstractmethod
def divide(
self, children: Sequence["Layout"], region: Region
) -> Iterable[Tuple["Layout", Region]]:
+ """Divide a region amongst several child layouts.
+
+ Args:
+ children (Sequence(Layout)): A number of child layouts.
+ region (Region): A rectangular region to divide.
+ """
class RowSplitter(Splitter):
+ """Split a layout region in to rows."""
name = "row"
@@ -106,6 +119,7 @@
class ColumnSplitter(Splitter):
+ """Split a layout region in to columns."""
name = "column"
@@ -126,6 +140,16 @@
@rich_repr
class Layout:
+ """A renderable to divide a fixed height in to rows or columns.
+
+ Args:
+ renderable (RenderableType, optional): Renderable content, or None for placeholder. Defaults to None.
+ name (str, optional): Optional identifier for Layout. Defaults to None.
+ size (int, optional): Optional fixed size of layout. Defaults to None.
+ minimum_size (int, optional): Minimum size of layout. Defaults to 1.
+ ratio (int, optional): Optional ratio for flexible layout. Defaults to 1.
+ visible (bool, optional): Visibility of layout. Defaults to True.
+ """
splitters = {"row": RowSplitter, "column": ColumnSplitter}
@@ -158,17 +182,28 @@
@property
def renderable(self) -> RenderableType:
+ """Layout renderable."""
return self if self._children else self._renderable
@property
def children(self) -> List["Layout"]:
+ """Gets (visible) layout children."""
return [child for child in self._children if child.visible]
@property
def map(self) -> RenderMap:
+ """Get a map of the last render."""
return self._render_map
def get(self, name: str) -> Optional["Layout"]:
+ """Get a named layout, or None if it doesn't exist.
+
+ Args:
+ name (str): Name of layout.
+
+ Returns:
+ Optional[Layout]: Layout instance or None if no layout was found.
+ """
if self.name == name:
return self
else:
@@ -186,6 +221,7 @@
@property
def tree(self) -> "Tree":
+ """Get a tree renderable to show layout structure."""
from rich.styled import Styled
from rich.table import Table
from rich.tree import Tree
@@ -227,6 +263,12 @@ *layouts: Union["Layout", RenderableType],
splitter: Union[Splitter, str] = "column",
) -> None:
+ """Split the layout in to multiple sub-layouts.
+
+ Args:
+ *layouts (Layout): Positional arguments should be (sub) Layout instances.
+ splitter (Union[Splitter, str]): Splitter instance or name of splitter.
+ """
_layouts = [
layout if isinstance(layout, Layout) else Layout(layout)
for layout in layouts
@@ -242,6 +284,12 @@ self._children[:] = _layouts
def add_split(self, *layouts: Union["Layout", RenderableType]) -> None:
+ """Add a new layout(s) to existing split.
+
+ Args:
+ *layouts (Union[Layout, RenderableType]): Positional arguments should be renderables or (sub) Layout instances.
+
+ """
_layouts = (
layout if isinstance(layout, Layout) else Layout(layout)
for layout in layouts
@@ -249,19 +297,41 @@ self._children.extend(_layouts)
def split_row(self, *layouts: Union["Layout", RenderableType]) -> None:
+ """Split the layout in to a row (layouts side by side).
+
+ Args:
+ *layouts (Layout): Positional arguments should be (sub) Layout instances.
+ """
self.split(*layouts, splitter="row")
def split_column(self, *layouts: Union["Layout", RenderableType]) -> None:
+ """Split the layout in to a column (layouts stacked on top of each other).
+
+ Args:
+ *layouts (Layout): Positional arguments should be (sub) Layout instances.
+ """
self.split(*layouts, splitter="column")
def unsplit(self) -> None:
+ """Reset splits to initial state."""
del self._children[:]
def update(self, renderable: RenderableType) -> None:
+ """Update renderable.
+
+ Args:
+ renderable (RenderableType): New renderable object.
+ """
with self._lock:
self._renderable = renderable
def refresh_screen(self, console: "Console", layout_name: str) -> None:
+ """Refresh a sub-layout.
+
+ Args:
+ console (Console): Console instance where Layout is to be rendered.
+ layout_name (str): Name of layout.
+ """
with self._lock:
layout = self[layout_name]
region, _lines = self._render_map[layout]
@@ -273,6 +343,7 @@ console.update_screen_lines(lines, x, y)
def _make_region_map(self, width: int, height: int) -> RegionMap:
+ """Create a dict that maps layout on to Region."""
stack: List[Tuple[Layout, Region]] = [(self, Region(0, 0, width, height))]
push = stack.append
pop = stack.pop
@@ -293,6 +364,15 @@ return region_map
def render(self, console: Console, options: ConsoleOptions) -> RenderMap:
+ """Render the sub_layouts.
+
+ Args:
+ console (Console): Console instance.
+ options (ConsoleOptions): Console options.
+
+ Returns:
+ RenderMap: A dict that maps Layout on to a tuple of Region, lines
+ """
render_width = options.max_width
render_height = options.height or console.height
region_map = self._make_region_map(render_width, render_height)
@@ -359,4 +439,4 @@
layout["content"].update("foo")
- console.print(layout)+ console.print(layout)
| 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 Daytona sandbox configuration")
daytona_config = DaytonaConfig(
api_key=daytona_settings.daytona_api_key,
server_url=daytona_settings.daytona_server_url,
target=daytona_settings.daytona_target,
)
if daytona_config.api_key:
logger.info("Daytona API key configured successfully")
else:
logger.warning("No Daytona API key found in environment variables")
if daytona_config.server_url:
logger.info(f"Daytona server URL set to: {daytona_config.server_url}")
else:
logger.warning("No Daytona server URL found in environment variables")
if daytona_config.target:
logger.info(f"Daytona target set to: {daytona_config.target}")
else:
logger.warning("No Daytona target found in environment variables")
daytona = Daytona(daytona_config)
logger.info("Daytona client initialized")
async def get_or_start_sandbox(sandbox_id: str):
logger.info(f"Getting or starting sandbox with ID: {sandbox_id}")
try:
sandbox = daytona.get(sandbox_id)
# Check if sandbox needs to be started
if (
sandbox.state == SandboxState.ARCHIVED
or sandbox.state == SandboxState.STOPPED
):
logger.info(f"Sandbox is in {sandbox.state} state. Starting...")
try:
daytona.start(sandbox)
# Wait a moment for the sandbox to initialize
# sleep(5)
# Refresh sandbox state after starting
sandbox = daytona.get(sandbox_id)
# Start supervisord in a session when restarting
start_supervisord_session(sandbox)
except Exception as e:
logger.error(f"Error starting sandbox: {e}")
raise e
logger.info(f"Sandbox {sandbox_id} is ready")
return sandbox
except Exception as e:
logger.error(f"Error retrieving or starting sandbox: {str(e)}")
raise e
def start_supervisord_session(sandbox: Sandbox):
session_id = "supervisord-session"
try:
logger.info(f"Creating session {session_id} for supervisord")
sandbox.process.create_session(session_id)
# Execute supervisord command
sandbox.process.execute_session_command(
session_id,
SessionExecuteRequest(
command="exec /usr/bin/supervisord -n -c /etc/supervisor/conf.d/supervisord.conf",
var_async=True,
),
)
time.sleep(25) # Wait a bit to ensure supervisord starts properly
logger.info(f"Supervisord started in session {session_id}")
except Exception as e:
logger.error(f"Error starting supervisord session: {str(e)}")
raise e
def create_sandbox(password: str, project_id: str = None):
logger.info("Creating new Daytona sandbox environment")
logger.info("Configuring sandbox with browser-use image and environment variables")
labels = None
if project_id:
logger.info(f"Using sandbox_id as label: {project_id}")
labels = {"id": project_id}
params = CreateSandboxFromImageParams(
image=daytona_settings.sandbox_image_name,
public=True,
labels=labels,
env_vars={
"CHROME_PERSISTENT_SESSION": "true",
"RESOLUTION": "1024x768x24",
"RESOLUTION_WIDTH": "1024",
"RESOLUTION_HEIGHT": "768",
"VNC_PASSWORD": password,
"ANONYMIZED_TELEMETRY": "false",
"CHROME_PATH": "",
"CHROME_USER_DATA": "",
"CHROME_DEBUGGING_PORT": "9222",
"CHROME_DEBUGGING_HOST": "localhost",
"CHROME_CDP": "",
},
resources=Resources(
cpu=2,
memory=4,
disk=5,
),
auto_stop_interval=15,
auto_archive_interval=24 * 60,
)
# Create the sandbox
sandbox = daytona.create(params)
logger.info(f"Sandbox created with ID: {sandbox.id}")
# Start supervisord in a session for new sandbox
start_supervisord_session(sandbox)
logger.info(f"Sandbox environment successfully initialized")
return sandbox
async def delete_sandbox(sandbox_id: str):
logger.info(f"Deleting sandbox with ID: {sandbox_id}")
try:
# Get the sandbox
sandbox = daytona.get(sandbox_id)
# Delete the sandbox
daytona.delete(sandbox)
logger.info(f"Successfully deleted sandbox {sandbox_id}")
return True
except Exception as e:
logger.error(f"Error deleting sandbox {sandbox_id}: {str(e)}")
raise e | --- +++ @@ -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 supervisord in a session."""
session_id = "supervisord-session"
try:
logger.info(f"Creating session {session_id} for supervisord")
@@ -98,6 +100,7 @@
def create_sandbox(password: str, project_id: str = None):
+ """Create a new sandbox with all required services configured and running."""
logger.info("Creating new Daytona sandbox environment")
logger.info("Configuring sandbox with browser-use image and environment variables")
@@ -145,6 +148,7 @@
async def delete_sandbox(sandbox_id: str):
+ """Delete a sandbox by its ID."""
logger.info(f"Deleting sandbox with ID: {sandbox_id}")
try:
@@ -158,4 +162,4 @@ return True
except Exception as e:
logger.error(f"Error deleting sandbox {sandbox_id}: {str(e)}")
- raise e+ raise e
| 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] = None
next_step_prompt: Optional[str] = None
llm: Optional[LLM] = Field(default_factory=LLM)
memory: Memory = Field(default_factory=Memory)
state: AgentState = AgentState.IDLE
max_steps: int = 10
current_step: int = 0
@abstractmethod
async def think(self) -> bool:
@abstractmethod
async def act(self) -> str:
async def step(self) -> str:
should_act = await self.think()
if not should_act:
return "Thinking complete - no action needed"
return await self.act() | --- +++ @@ -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 and act."""
should_act = await self.think()
if not should_act:
return "Thinking complete - no action needed"
- return await self.act()+ return await self.act()
| 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 LLMSettings(BaseModel):
model: str = Field(..., description="Model name")
base_url: str = Field(..., description="API base URL")
api_key: str = Field(..., description="API key")
max_tokens: int = Field(4096, description="Maximum number of tokens per request")
max_input_tokens: Optional[int] = Field(
None,
description="Maximum input tokens to use across all requests (None for unlimited)",
)
temperature: float = Field(1.0, description="Sampling temperature")
api_type: str = Field(..., description="Azure, Openai, or Ollama")
api_version: str = Field(..., description="Azure Openai version if AzureOpenai")
class ProxySettings(BaseModel):
server: str = Field(None, description="Proxy server address")
username: Optional[str] = Field(None, description="Proxy username")
password: Optional[str] = Field(None, description="Proxy password")
class SearchSettings(BaseModel):
engine: str = Field(default="Google", description="Search engine the llm to use")
fallback_engines: List[str] = Field(
default_factory=lambda: ["DuckDuckGo", "Baidu", "Bing"],
description="Fallback search engines to try if the primary engine fails",
)
retry_delay: int = Field(
default=60,
description="Seconds to wait before retrying all engines again after they all fail",
)
max_retries: int = Field(
default=3,
description="Maximum number of times to retry all engines when all fail",
)
lang: str = Field(
default="en",
description="Language code for search results (e.g., en, zh, fr)",
)
country: str = Field(
default="us",
description="Country code for search results (e.g., us, cn, uk)",
)
class RunflowSettings(BaseModel):
use_data_analysis_agent: bool = Field(
default=False, description="Enable data analysis agent in run flow"
)
class BrowserSettings(BaseModel):
headless: bool = Field(False, description="Whether to run browser in headless mode")
disable_security: bool = Field(
True, description="Disable browser security features"
)
extra_chromium_args: List[str] = Field(
default_factory=list, description="Extra arguments to pass to the browser"
)
chrome_instance_path: Optional[str] = Field(
None, description="Path to a Chrome instance to use"
)
wss_url: Optional[str] = Field(
None, description="Connect to a browser instance via WebSocket"
)
cdp_url: Optional[str] = Field(
None, description="Connect to a browser instance via CDP"
)
proxy: Optional[ProxySettings] = Field(
None, description="Proxy settings for the browser"
)
max_content_length: int = Field(
2000, description="Maximum length for content retrieval operations"
)
class SandboxSettings(BaseModel):
use_sandbox: bool = Field(False, description="Whether to use the sandbox")
image: str = Field("python:3.12-slim", description="Base image")
work_dir: str = Field("/workspace", description="Container working directory")
memory_limit: str = Field("512m", description="Memory limit")
cpu_limit: float = Field(1.0, description="CPU limit")
timeout: int = Field(300, description="Default command timeout (seconds)")
network_enabled: bool = Field(
False, description="Whether network access is allowed"
)
class DaytonaSettings(BaseModel):
daytona_api_key: str
daytona_server_url: Optional[str] = Field(
"https://app.daytona.io/api", description=""
)
daytona_target: Optional[str] = Field("us", description="enum ['eu', 'us']")
sandbox_image_name: Optional[str] = Field("whitezxj/sandbox:0.1.0", description="")
sandbox_entrypoint: Optional[str] = Field(
"/usr/bin/supervisord -n -c /etc/supervisor/conf.d/supervisord.conf",
description="",
)
# sandbox_id: Optional[str] = Field(
# None, description="ID of the daytona sandbox to use, if any"
# )
VNC_password: Optional[str] = Field(
"123456", description="VNC password for the vnc service in sandbox"
)
class MCPServerConfig(BaseModel):
type: str = Field(..., description="Server connection type (sse or stdio)")
url: Optional[str] = Field(None, description="Server URL for SSE connections")
command: Optional[str] = Field(None, description="Command for stdio connections")
args: List[str] = Field(
default_factory=list, description="Arguments for stdio command"
)
class MCPSettings(BaseModel):
server_reference: str = Field(
"app.mcp.server", description="Module reference for the MCP server"
)
servers: Dict[str, MCPServerConfig] = Field(
default_factory=dict, description="MCP server configurations"
)
@classmethod
def load_server_config(cls) -> Dict[str, MCPServerConfig]:
config_path = PROJECT_ROOT / "config" / "mcp.json"
try:
config_file = config_path if config_path.exists() else None
if not config_file:
return {}
with config_file.open() as f:
data = json.load(f)
servers = {}
for server_id, server_config in data.get("mcpServers", {}).items():
servers[server_id] = MCPServerConfig(
type=server_config["type"],
url=server_config.get("url"),
command=server_config.get("command"),
args=server_config.get("args", []),
)
return servers
except Exception as e:
raise ValueError(f"Failed to load MCP server config: {e}")
class AppConfig(BaseModel):
llm: Dict[str, LLMSettings]
sandbox: Optional[SandboxSettings] = Field(
None, description="Sandbox configuration"
)
browser_config: Optional[BrowserSettings] = Field(
None, description="Browser configuration"
)
search_config: Optional[SearchSettings] = Field(
None, description="Search configuration"
)
mcp_config: Optional[MCPSettings] = Field(None, description="MCP configuration")
run_flow_config: Optional[RunflowSettings] = Field(
None, description="Run flow configuration"
)
daytona_config: Optional[DaytonaSettings] = Field(
None, description="Daytona configuration"
)
class Config:
arbitrary_types_allowed = True
class Config:
_instance = None
_lock = threading.Lock()
_initialized = False
def __new__(cls):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
if not self._initialized:
with self._lock:
if not self._initialized:
self._config = None
self._load_initial_config()
self._initialized = True
@staticmethod
def _get_config_path() -> Path:
root = PROJECT_ROOT
config_path = root / "config" / "config.toml"
if config_path.exists():
return config_path
example_path = root / "config" / "config.example.toml"
if example_path.exists():
return example_path
raise FileNotFoundError("No configuration file found in config directory")
def _load_config(self) -> dict:
config_path = self._get_config_path()
with config_path.open("rb") as f:
return tomllib.load(f)
def _load_initial_config(self):
raw_config = self._load_config()
base_llm = raw_config.get("llm", {})
llm_overrides = {
k: v for k, v in raw_config.get("llm", {}).items() if isinstance(v, dict)
}
default_settings = {
"model": base_llm.get("model"),
"base_url": base_llm.get("base_url"),
"api_key": base_llm.get("api_key"),
"max_tokens": base_llm.get("max_tokens", 4096),
"max_input_tokens": base_llm.get("max_input_tokens"),
"temperature": base_llm.get("temperature", 1.0),
"api_type": base_llm.get("api_type", ""),
"api_version": base_llm.get("api_version", ""),
}
# handle browser config.
browser_config = raw_config.get("browser", {})
browser_settings = None
if browser_config:
# handle proxy settings.
proxy_config = browser_config.get("proxy", {})
proxy_settings = None
if proxy_config and proxy_config.get("server"):
proxy_settings = ProxySettings(
**{
k: v
for k, v in proxy_config.items()
if k in ["server", "username", "password"] and v
}
)
# filter valid browser config parameters.
valid_browser_params = {
k: v
for k, v in browser_config.items()
if k in BrowserSettings.__annotations__ and v is not None
}
# if there is proxy settings, add it to the parameters.
if proxy_settings:
valid_browser_params["proxy"] = proxy_settings
# only create BrowserSettings when there are valid parameters.
if valid_browser_params:
browser_settings = BrowserSettings(**valid_browser_params)
search_config = raw_config.get("search", {})
search_settings = None
if search_config:
search_settings = SearchSettings(**search_config)
sandbox_config = raw_config.get("sandbox", {})
if sandbox_config:
sandbox_settings = SandboxSettings(**sandbox_config)
else:
sandbox_settings = SandboxSettings()
daytona_config = raw_config.get("daytona", {})
if daytona_config:
daytona_settings = DaytonaSettings(**daytona_config)
else:
daytona_settings = DaytonaSettings()
mcp_config = raw_config.get("mcp", {})
mcp_settings = None
if mcp_config:
# Load server configurations from JSON
mcp_config["servers"] = MCPSettings.load_server_config()
mcp_settings = MCPSettings(**mcp_config)
else:
mcp_settings = MCPSettings(servers=MCPSettings.load_server_config())
run_flow_config = raw_config.get("runflow")
if run_flow_config:
run_flow_settings = RunflowSettings(**run_flow_config)
else:
run_flow_settings = RunflowSettings()
config_dict = {
"llm": {
"default": default_settings,
**{
name: {**default_settings, **override_config}
for name, override_config in llm_overrides.items()
},
},
"sandbox": sandbox_settings,
"browser_config": browser_settings,
"search_config": search_settings,
"mcp_config": mcp_settings,
"run_flow_config": run_flow_settings,
"daytona_config": daytona_settings,
}
self._config = AppConfig(**config_dict)
@property
def llm(self) -> Dict[str, LLMSettings]:
return self._config.llm
@property
def sandbox(self) -> SandboxSettings:
return self._config.sandbox
@property
def daytona(self) -> DaytonaSettings:
return self._config.daytona_config
@property
def browser_config(self) -> Optional[BrowserSettings]:
return self._config.browser_config
@property
def search_config(self) -> Optional[SearchSettings]:
return self._config.search_config
@property
def mcp_config(self) -> MCPSettings:
return self._config.mcp_config
@property
def run_flow_config(self) -> RunflowSettings:
return self._config.run_flow_config
@property
def workspace_root(self) -> Path:
return WORKSPACE_ROOT
@property
def root_path(self) -> Path:
return PROJECT_ROOT
config = Config() | --- +++ @@ -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="Whether to use the sandbox")
image: str = Field("python:3.12-slim", description="Base image")
@@ -123,6 +125,7 @@
class MCPServerConfig(BaseModel):
+ """Configuration for a single MCP server"""
type: str = Field(..., description="Server connection type (sse or stdio)")
url: Optional[str] = Field(None, description="Server URL for SSE connections")
@@ -133,6 +136,7 @@
class MCPSettings(BaseModel):
+ """Configuration for MCP (Model Context Protocol)"""
server_reference: str = Field(
"app.mcp.server", description="Module reference for the MCP server"
@@ -143,6 +147,7 @@
@classmethod
def load_server_config(cls) -> Dict[str, MCPServerConfig]:
+ """Load MCP server configuration from JSON file"""
config_path = PROJECT_ROOT / "config" / "mcp.json"
try:
@@ -345,19 +350,23 @@
@property
def mcp_config(self) -> MCPSettings:
+ """Get the MCP configuration"""
return self._config.mcp_config
@property
def run_flow_config(self) -> RunflowSettings:
+ """Get the Run Flow configuration"""
return self._config.run_flow_config
@property
def workspace_root(self) -> Path:
+ """Get the workspace root directory"""
return WORKSPACE_ROOT
@property
def root_path(self) -> Path:
+ """Get the root path of the application"""
return PROJECT_ROOT
-config = Config()+config = Config()
| 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 ToolResult
from app.tool.mcp import MCPClients
class MCPAgent(ToolCallAgent):
name: str = "mcp_agent"
description: str = "An agent that connects to an MCP server and uses its tools."
system_prompt: str = SYSTEM_PROMPT
next_step_prompt: str = NEXT_STEP_PROMPT
# Initialize MCP tool collection
mcp_clients: MCPClients = Field(default_factory=MCPClients)
available_tools: MCPClients = None # Will be set in initialize()
max_steps: int = 20
connection_type: str = "stdio" # "stdio" or "sse"
# Track tool schemas to detect changes
tool_schemas: Dict[str, Dict[str, Any]] = Field(default_factory=dict)
_refresh_tools_interval: int = 5 # Refresh tools every N steps
# Special tool names that should trigger termination
special_tool_names: List[str] = Field(default_factory=lambda: ["terminate"])
async def initialize(
self,
connection_type: Optional[str] = None,
server_url: Optional[str] = None,
command: Optional[str] = None,
args: Optional[List[str]] = None,
) -> None:
if connection_type:
self.connection_type = connection_type
# Connect to the MCP server based on connection type
if self.connection_type == "sse":
if not server_url:
raise ValueError("Server URL is required for SSE connection")
await self.mcp_clients.connect_sse(server_url=server_url)
elif self.connection_type == "stdio":
if not command:
raise ValueError("Command is required for stdio connection")
await self.mcp_clients.connect_stdio(command=command, args=args or [])
else:
raise ValueError(f"Unsupported connection type: {self.connection_type}")
# Set available_tools to our MCP instance
self.available_tools = self.mcp_clients
# Store initial tool schemas
await self._refresh_tools()
# Add system message about available tools
tool_names = list(self.mcp_clients.tool_map.keys())
tools_info = ", ".join(tool_names)
# Add system prompt and available tools information
self.memory.add_message(
Message.system_message(
f"{self.system_prompt}\n\nAvailable MCP tools: {tools_info}"
)
)
async def _refresh_tools(self) -> Tuple[List[str], List[str]]:
if not self.mcp_clients.sessions:
return [], []
# Get current tool schemas directly from the server
response = await self.mcp_clients.list_tools()
current_tools = {tool.name: tool.inputSchema for tool in response.tools}
# Determine added, removed, and changed tools
current_names = set(current_tools.keys())
previous_names = set(self.tool_schemas.keys())
added_tools = list(current_names - previous_names)
removed_tools = list(previous_names - current_names)
# Check for schema changes in existing tools
changed_tools = []
for name in current_names.intersection(previous_names):
if current_tools[name] != self.tool_schemas.get(name):
changed_tools.append(name)
# Update stored schemas
self.tool_schemas = current_tools
# Log and notify about changes
if added_tools:
logger.info(f"Added MCP tools: {added_tools}")
self.memory.add_message(
Message.system_message(f"New tools available: {', '.join(added_tools)}")
)
if removed_tools:
logger.info(f"Removed MCP tools: {removed_tools}")
self.memory.add_message(
Message.system_message(
f"Tools no longer available: {', '.join(removed_tools)}"
)
)
if changed_tools:
logger.info(f"Changed MCP tools: {changed_tools}")
return added_tools, removed_tools
async def think(self) -> bool:
# Check MCP session and tools availability
if not self.mcp_clients.sessions or not self.mcp_clients.tool_map:
logger.info("MCP service is no longer available, ending interaction")
self.state = AgentState.FINISHED
return False
# Refresh tools periodically
if self.current_step % self._refresh_tools_interval == 0:
await self._refresh_tools()
# All tools removed indicates shutdown
if not self.mcp_clients.tool_map:
logger.info("MCP service has shut down, ending interaction")
self.state = AgentState.FINISHED
return False
# Use the parent class's think method
return await super().think()
async def _handle_special_tool(self, name: str, result: Any, **kwargs) -> None:
# First process with parent handler
await super()._handle_special_tool(name, result, **kwargs)
# Handle multimedia responses
if isinstance(result, ToolResult) and result.base64_image:
self.memory.add_message(
Message.system_message(
MULTIMEDIA_RESPONSE_PROMPT.format(tool_name=name)
)
)
def _should_finish_execution(self, name: str, **kwargs) -> bool:
# Terminate if the tool name is 'terminate'
return name.lower() == "terminate"
async def cleanup(self) -> None:
if self.mcp_clients.sessions:
await self.mcp_clients.disconnect()
logger.info("MCP connection closed")
async def run(self, request: Optional[str] = None) -> str:
try:
result = await super().run(request)
return result
finally:
# Ensure cleanup happens even if there's an error
await self.cleanup() | --- +++ @@ -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 = "mcp_agent"
description: str = "An agent that connects to an MCP server and uses its tools."
@@ -39,6 +44,14 @@ command: Optional[str] = None,
args: Optional[List[str]] = None,
) -> None:
+ """Initialize the MCP connection.
+
+ Args:
+ connection_type: Type of connection to use ("stdio" or "sse")
+ server_url: URL of the MCP server (for SSE connection)
+ command: Command to run (for stdio connection)
+ args: Arguments for the command (for stdio connection)
+ """
if connection_type:
self.connection_type = connection_type
@@ -72,6 +85,11 @@ )
async def _refresh_tools(self) -> Tuple[List[str], List[str]]:
+ """Refresh the list of available tools from the MCP server.
+
+ Returns:
+ A tuple of (added_tools, removed_tools)
+ """
if not self.mcp_clients.sessions:
return [], []
@@ -114,6 +132,7 @@ return added_tools, removed_tools
async def think(self) -> bool:
+ """Process current state and decide next action."""
# Check MCP session and tools availability
if not self.mcp_clients.sessions or not self.mcp_clients.tool_map:
logger.info("MCP service is no longer available, ending interaction")
@@ -133,6 +152,7 @@ return await super().think()
async def _handle_special_tool(self, name: str, result: Any, **kwargs) -> None:
+ """Handle special tool execution and state changes"""
# First process with parent handler
await super()._handle_special_tool(name, result, **kwargs)
@@ -145,18 +165,21 @@ )
def _should_finish_execution(self, name: str, **kwargs) -> bool:
+ """Determine if tool execution should finish the agent"""
# Terminate if the tool name is 'terminate'
return name.lower() == "terminate"
async def cleanup(self) -> None:
+ """Clean up MCP connection when done."""
if self.mcp_clients.sessions:
await self.mcp_clients.disconnect()
logger.info("MCP connection closed")
async def run(self, request: Optional[str] = None) -> str:
+ """Run the agent with cleanup when done."""
try:
result = await super().run(request)
return result
finally:
# Ensure cleanup happens even if there's an error
- await self.cleanup()+ await self.cleanup()
| 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 TokenLimitExceeded(OpenManusError):
+ """Exception raised when the token limit is exceeded"""
| 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 SandboxToolsBase
from app.logger import logger
from app.prompt.manus import NEXT_STEP_PROMPT, SYSTEM_PROMPT
from app.tool import Terminate, ToolCollection
from app.tool.ask_human import AskHuman
from app.tool.mcp import MCPClients, MCPClientTool
from app.tool.sandbox.sb_browser_tool import SandboxBrowserTool
from app.tool.sandbox.sb_files_tool import SandboxFilesTool
from app.tool.sandbox.sb_shell_tool import SandboxShellTool
from app.tool.sandbox.sb_vision_tool import SandboxVisionTool
class SandboxManus(ToolCallAgent):
name: str = "SandboxManus"
description: str = "A versatile agent that can solve various tasks using multiple sandbox-tools including MCP-based tools"
system_prompt: str = SYSTEM_PROMPT.format(directory=config.workspace_root)
next_step_prompt: str = NEXT_STEP_PROMPT
max_observe: int = 10000
max_steps: int = 20
# MCP clients for remote tool access
mcp_clients: MCPClients = Field(default_factory=MCPClients)
# Add general-purpose tools to the tool collection
available_tools: ToolCollection = Field(
default_factory=lambda: ToolCollection(
# PythonExecute(),
# BrowserUseTool(),
# StrReplaceEditor(),
AskHuman(),
Terminate(),
)
)
special_tool_names: list[str] = Field(default_factory=lambda: [Terminate().name])
browser_context_helper: Optional[BrowserContextHelper] = None
# Track connected MCP servers
connected_servers: Dict[str, str] = Field(
default_factory=dict
) # server_id -> url/command
_initialized: bool = False
sandbox_link: Optional[dict[str, dict[str, str]]] = Field(default_factory=dict)
@model_validator(mode="after")
def initialize_helper(self) -> "SandboxManus":
self.browser_context_helper = BrowserContextHelper(self)
return self
@classmethod
async def create(cls, **kwargs) -> "SandboxManus":
instance = cls(**kwargs)
await instance.initialize_mcp_servers()
await instance.initialize_sandbox_tools()
instance._initialized = True
return instance
async def initialize_sandbox_tools(
self,
password: str = config.daytona.VNC_password,
) -> None:
try:
# 创建新沙箱
if password:
sandbox = create_sandbox(password=password)
self.sandbox = sandbox
else:
raise ValueError("password must be provided")
vnc_link = sandbox.get_preview_link(6080)
website_link = sandbox.get_preview_link(8080)
vnc_url = vnc_link.url if hasattr(vnc_link, "url") else str(vnc_link)
website_url = (
website_link.url if hasattr(website_link, "url") else str(website_link)
)
# Get the actual sandbox_id from the created sandbox
actual_sandbox_id = sandbox.id if hasattr(sandbox, "id") else "new_sandbox"
if not self.sandbox_link:
self.sandbox_link = {}
self.sandbox_link[actual_sandbox_id] = {
"vnc": vnc_url,
"website": website_url,
}
logger.info(f"VNC URL: {vnc_url}")
logger.info(f"Website URL: {website_url}")
SandboxToolsBase._urls_printed = True
sb_tools = [
SandboxBrowserTool(sandbox),
SandboxFilesTool(sandbox),
SandboxShellTool(sandbox),
SandboxVisionTool(sandbox),
]
self.available_tools.add_tools(*sb_tools)
except Exception as e:
logger.error(f"Error initializing sandbox tools: {e}")
raise
async def initialize_mcp_servers(self) -> None:
for server_id, server_config in config.mcp_config.servers.items():
try:
if server_config.type == "sse":
if server_config.url:
await self.connect_mcp_server(server_config.url, server_id)
logger.info(
f"Connected to MCP server {server_id} at {server_config.url}"
)
elif server_config.type == "stdio":
if server_config.command:
await self.connect_mcp_server(
server_config.command,
server_id,
use_stdio=True,
stdio_args=server_config.args,
)
logger.info(
f"Connected to MCP server {server_id} using command {server_config.command}"
)
except Exception as e:
logger.error(f"Failed to connect to MCP server {server_id}: {e}")
async def connect_mcp_server(
self,
server_url: str,
server_id: str = "",
use_stdio: bool = False,
stdio_args: List[str] = None,
) -> None:
if use_stdio:
await self.mcp_clients.connect_stdio(
server_url, stdio_args or [], server_id
)
self.connected_servers[server_id or server_url] = server_url
else:
await self.mcp_clients.connect_sse(server_url, server_id)
self.connected_servers[server_id or server_url] = server_url
# Update available tools with only the new tools from this server
new_tools = [
tool for tool in self.mcp_clients.tools if tool.server_id == server_id
]
self.available_tools.add_tools(*new_tools)
async def disconnect_mcp_server(self, server_id: str = "") -> None:
await self.mcp_clients.disconnect(server_id)
if server_id:
self.connected_servers.pop(server_id, None)
else:
self.connected_servers.clear()
# Rebuild available tools without the disconnected server's tools
base_tools = [
tool
for tool in self.available_tools.tools
if not isinstance(tool, MCPClientTool)
]
self.available_tools = ToolCollection(*base_tools)
self.available_tools.add_tools(*self.mcp_clients.tools)
async def delete_sandbox(self, sandbox_id: str) -> None:
try:
await delete_sandbox(sandbox_id)
logger.info(f"Sandbox {sandbox_id} deleted successfully")
if sandbox_id in self.sandbox_link:
del self.sandbox_link[sandbox_id]
except Exception as e:
logger.error(f"Error deleting sandbox {sandbox_id}: {e}")
raise e
async def cleanup(self):
if self.browser_context_helper:
await self.browser_context_helper.cleanup_browser()
# Disconnect from all MCP servers only if we were initialized
if self._initialized:
await self.disconnect_mcp_server()
await self.delete_sandbox(self.sandbox.id if self.sandbox else "unknown")
self._initialized = False
async def think(self) -> bool:
if not self._initialized:
await self.initialize_mcp_servers()
self._initialized = True
original_prompt = self.next_step_prompt
recent_messages = self.memory.messages[-3:] if self.memory.messages else []
browser_in_use = any(
tc.function.name == SandboxBrowserTool().name
for msg in recent_messages
if msg.tool_calls
for tc in msg.tool_calls
)
if browser_in_use:
self.next_step_prompt = (
await self.browser_context_helper.format_next_step_prompt()
)
result = await super().think()
# Restore original prompt
self.next_step_prompt = original_prompt
return result | --- +++ @@ -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"
@@ -55,11 +56,13 @@
@model_validator(mode="after")
def initialize_helper(self) -> "SandboxManus":
+ """Initialize basic components synchronously."""
self.browser_context_helper = BrowserContextHelper(self)
return self
@classmethod
async def create(cls, **kwargs) -> "SandboxManus":
+ """Factory method to create and properly initialize a Manus instance."""
instance = cls(**kwargs)
await instance.initialize_mcp_servers()
await instance.initialize_sandbox_tools()
@@ -108,6 +111,7 @@ raise
async def initialize_mcp_servers(self) -> None:
+ """Initialize connections to configured MCP servers."""
for server_id, server_config in config.mcp_config.servers.items():
try:
if server_config.type == "sse":
@@ -137,6 +141,7 @@ use_stdio: bool = False,
stdio_args: List[str] = None,
) -> None:
+ """Connect to an MCP server and add its tools."""
if use_stdio:
await self.mcp_clients.connect_stdio(
server_url, stdio_args or [], server_id
@@ -153,6 +158,7 @@ self.available_tools.add_tools(*new_tools)
async def disconnect_mcp_server(self, server_id: str = "") -> None:
+ """Disconnect from an MCP server and remove its tools."""
await self.mcp_clients.disconnect(server_id)
if server_id:
self.connected_servers.pop(server_id, None)
@@ -169,6 +175,7 @@ self.available_tools.add_tools(*self.mcp_clients.tools)
async def delete_sandbox(self, sandbox_id: str) -> None:
+ """Delete a sandbox by ID."""
try:
await delete_sandbox(sandbox_id)
logger.info(f"Sandbox {sandbox_id} deleted successfully")
@@ -179,6 +186,7 @@ raise e
async def cleanup(self):
+ """Clean up Manus agent resources."""
if self.browser_context_helper:
await self.browser_context_helper.cleanup_browser()
# Disconnect from all MCP servers only if we were initialized
@@ -188,6 +196,7 @@ self._initialized = False
async def think(self) -> bool:
+ """Process current state and decide next actions with appropriate context."""
if not self._initialized:
await self.initialize_mcp_servers()
self._initialized = True
@@ -211,4 +220,4 @@ # Restore original prompt
self.next_step_prompt = original_prompt
- return result+ return result
| 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, Terminate, ToolCollection
from app.tool.sandbox.sb_browser_tool import SandboxBrowserTool
# Avoid circular import if BrowserAgent needs BrowserContextHelper
if TYPE_CHECKING:
from app.agent.base import BaseAgent # Or wherever memory is defined
class BrowserContextHelper:
def __init__(self, agent: "BaseAgent"):
self.agent = agent
self._current_base64_image: Optional[str] = None
async def get_browser_state(self) -> Optional[dict]:
browser_tool = self.agent.available_tools.get_tool(BrowserUseTool().name)
if not browser_tool:
browser_tool = self.agent.available_tools.get_tool(
SandboxBrowserTool().name
)
if not browser_tool or not hasattr(browser_tool, "get_current_state"):
logger.warning("BrowserUseTool not found or doesn't have get_current_state")
return None
try:
result = await browser_tool.get_current_state()
if result.error:
logger.debug(f"Browser state error: {result.error}")
return None
if hasattr(result, "base64_image") and result.base64_image:
self._current_base64_image = result.base64_image
else:
self._current_base64_image = None
return json.loads(result.output)
except Exception as e:
logger.debug(f"Failed to get browser state: {str(e)}")
return None
async def format_next_step_prompt(self) -> str:
browser_state = await self.get_browser_state()
url_info, tabs_info, content_above_info, content_below_info = "", "", "", ""
results_info = "" # Or get from agent if needed elsewhere
if browser_state and not browser_state.get("error"):
url_info = f"\n URL: {browser_state.get('url', 'N/A')}\n Title: {browser_state.get('title', 'N/A')}"
tabs = browser_state.get("tabs", [])
if tabs:
tabs_info = f"\n {len(tabs)} tab(s) available"
pixels_above = browser_state.get("pixels_above", 0)
pixels_below = browser_state.get("pixels_below", 0)
if pixels_above > 0:
content_above_info = f" ({pixels_above} pixels)"
if pixels_below > 0:
content_below_info = f" ({pixels_below} pixels)"
if self._current_base64_image:
image_message = Message.user_message(
content="Current browser screenshot:",
base64_image=self._current_base64_image,
)
self.agent.memory.add_message(image_message)
self._current_base64_image = None # Consume the image after adding
return NEXT_STEP_PROMPT.format(
url_placeholder=url_info,
tabs_placeholder=tabs_info,
content_above_placeholder=content_above_info,
content_below_placeholder=content_below_info,
results_placeholder=results_info,
)
async def cleanup_browser(self):
browser_tool = self.agent.available_tools.get_tool(BrowserUseTool().name)
if browser_tool and hasattr(browser_tool, "cleanup"):
await browser_tool.cleanup()
class BrowserAgent(ToolCallAgent):
name: str = "browser"
description: str = "A browser agent that can control a browser to accomplish tasks"
system_prompt: str = SYSTEM_PROMPT
next_step_prompt: str = NEXT_STEP_PROMPT
max_observe: int = 10000
max_steps: int = 20
# Configure the available tools
available_tools: ToolCollection = Field(
default_factory=lambda: ToolCollection(BrowserUseTool(), Terminate())
)
# Use Auto for tool choice to allow both tool usage and free-form responses
tool_choices: ToolChoice = ToolChoice.AUTO
special_tool_names: list[str] = Field(default_factory=lambda: [Terminate().name])
browser_context_helper: Optional[BrowserContextHelper] = None
@model_validator(mode="after")
def initialize_helper(self) -> "BrowserAgent":
self.browser_context_helper = BrowserContextHelper(self)
return self
async def think(self) -> bool:
self.next_step_prompt = (
await self.browser_context_helper.format_next_step_prompt()
)
return await super().think()
async def cleanup(self):
await self.browser_context_helper.cleanup_browser() | --- +++ @@ -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 = "", "", "", ""
results_info = "" # Or get from agent if needed elsewhere
@@ -84,6 +85,12 @@
class BrowserAgent(ToolCallAgent):
+ """
+ A browser agent that uses the browser_use library to control a browser.
+
+ This agent can navigate web pages, interact with elements, fill forms,
+ extract content, and perform other browser-based actions to accomplish tasks.
+ """
name: str = "browser"
description: str = "A browser agent that can control a browser to accomplish tasks"
@@ -111,10 +118,12 @@ return self
async def think(self) -> bool:
+ """Process current state and decide next actions using tools, with browser state info added"""
self.next_step_prompt = (
await self.browser_context_helper.format_next_step_prompt()
)
return await super().think()
async def cleanup(self):
- await self.browser_context_helper.cleanup_browser()+ """Clean up browser agent resources by calling parent cleanup."""
+ await self.browser_context_helper.cleanup_browser()
| 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, AgentState, Message, ToolCall, ToolChoice
from app.tool import CreateChatCompletion, Terminate, ToolCollection
TOOL_CALL_REQUIRED = "Tool calls required but none provided"
class ToolCallAgent(ReActAgent):
name: str = "toolcall"
description: str = "an agent that can execute tool calls."
system_prompt: str = SYSTEM_PROMPT
next_step_prompt: str = NEXT_STEP_PROMPT
available_tools: ToolCollection = ToolCollection(
CreateChatCompletion(), Terminate()
)
tool_choices: TOOL_CHOICE_TYPE = ToolChoice.AUTO # type: ignore
special_tool_names: List[str] = Field(default_factory=lambda: [Terminate().name])
tool_calls: List[ToolCall] = Field(default_factory=list)
_current_base64_image: Optional[str] = None
max_steps: int = 30
max_observe: Optional[Union[int, bool]] = None
async def think(self) -> bool:
if self.next_step_prompt:
user_msg = Message.user_message(self.next_step_prompt)
self.messages += [user_msg]
try:
# Get response with tool options
response = await self.llm.ask_tool(
messages=self.messages,
system_msgs=(
[Message.system_message(self.system_prompt)]
if self.system_prompt
else None
),
tools=self.available_tools.to_params(),
tool_choice=self.tool_choices,
)
except ValueError:
raise
except Exception as e:
# Check if this is a RetryError containing TokenLimitExceeded
if hasattr(e, "__cause__") and isinstance(e.__cause__, TokenLimitExceeded):
token_limit_error = e.__cause__
logger.error(
f"🚨 Token limit error (from RetryError): {token_limit_error}"
)
self.memory.add_message(
Message.assistant_message(
f"Maximum token limit reached, cannot continue execution: {str(token_limit_error)}"
)
)
self.state = AgentState.FINISHED
return False
raise
self.tool_calls = tool_calls = (
response.tool_calls if response and response.tool_calls else []
)
content = response.content if response and response.content else ""
# Log response info
logger.info(f"✨ {self.name}'s thoughts: {content}")
logger.info(
f"🛠️ {self.name} selected {len(tool_calls) if tool_calls else 0} tools to use"
)
if tool_calls:
logger.info(
f"🧰 Tools being prepared: {[call.function.name for call in tool_calls]}"
)
logger.info(f"🔧 Tool arguments: {tool_calls[0].function.arguments}")
try:
if response is None:
raise RuntimeError("No response received from the LLM")
# Handle different tool_choices modes
if self.tool_choices == ToolChoice.NONE:
if tool_calls:
logger.warning(
f"🤔 Hmm, {self.name} tried to use tools when they weren't available!"
)
if content:
self.memory.add_message(Message.assistant_message(content))
return True
return False
# Create and add assistant message
assistant_msg = (
Message.from_tool_calls(content=content, tool_calls=self.tool_calls)
if self.tool_calls
else Message.assistant_message(content)
)
self.memory.add_message(assistant_msg)
if self.tool_choices == ToolChoice.REQUIRED and not self.tool_calls:
return True # Will be handled in act()
# For 'auto' mode, continue with content if no commands but content exists
if self.tool_choices == ToolChoice.AUTO and not self.tool_calls:
return bool(content)
return bool(self.tool_calls)
except Exception as e:
logger.error(f"🚨 Oops! The {self.name}'s thinking process hit a snag: {e}")
self.memory.add_message(
Message.assistant_message(
f"Error encountered while processing: {str(e)}"
)
)
return False
async def act(self) -> str:
if not self.tool_calls:
if self.tool_choices == ToolChoice.REQUIRED:
raise ValueError(TOOL_CALL_REQUIRED)
# Return last message content if no tool calls
return self.messages[-1].content or "No content or commands to execute"
results = []
for command in self.tool_calls:
# Reset base64_image for each tool call
self._current_base64_image = None
result = await self.execute_tool(command)
if self.max_observe:
result = result[: self.max_observe]
logger.info(
f"🎯 Tool '{command.function.name}' completed its mission! Result: {result}"
)
# Add tool response to memory
tool_msg = Message.tool_message(
content=result,
tool_call_id=command.id,
name=command.function.name,
base64_image=self._current_base64_image,
)
self.memory.add_message(tool_msg)
results.append(result)
return "\n\n".join(results)
async def execute_tool(self, command: ToolCall) -> str:
if not command or not command.function or not command.function.name:
return "Error: Invalid command format"
name = command.function.name
if name not in self.available_tools.tool_map:
return f"Error: Unknown tool '{name}'"
try:
# Parse arguments
args = json.loads(command.function.arguments or "{}")
# Execute the tool
logger.info(f"🔧 Activating tool: '{name}'...")
result = await self.available_tools.execute(name=name, tool_input=args)
# Handle special tools
await self._handle_special_tool(name=name, result=result)
# Check if result is a ToolResult with base64_image
if hasattr(result, "base64_image") and result.base64_image:
# Store the base64_image for later use in tool_message
self._current_base64_image = result.base64_image
# Format result for display (standard case)
observation = (
f"Observed output of cmd `{name}` executed:\n{str(result)}"
if result
else f"Cmd `{name}` completed with no output"
)
return observation
except json.JSONDecodeError:
error_msg = f"Error parsing arguments for {name}: Invalid JSON format"
logger.error(
f"📝 Oops! The arguments for '{name}' don't make sense - invalid JSON, arguments:{command.function.arguments}"
)
return f"Error: {error_msg}"
except Exception as e:
error_msg = f"⚠️ Tool '{name}' encountered a problem: {str(e)}"
logger.exception(error_msg)
return f"Error: {error_msg}"
async def _handle_special_tool(self, name: str, result: Any, **kwargs):
if not self._is_special_tool(name):
return
if self._should_finish_execution(name=name, result=result, **kwargs):
# Set agent state to finished
logger.info(f"🏁 Special tool '{name}' has completed the task!")
self.state = AgentState.FINISHED
@staticmethod
def _should_finish_execution(**kwargs) -> bool:
return True
def _is_special_tool(self, name: str) -> bool:
return name.lower() in [n.lower() for n in self.special_tool_names]
async def cleanup(self):
logger.info(f"🧹 Cleaning up resources for agent '{self.name}'...")
for tool_name, tool_instance in self.available_tools.tool_map.items():
if hasattr(tool_instance, "cleanup") and asyncio.iscoroutinefunction(
tool_instance.cleanup
):
try:
logger.debug(f"🧼 Cleaning up tool: {tool_name}")
await tool_instance.cleanup()
except Exception as e:
logger.error(
f"🚨 Error cleaning up tool '{tool_name}': {e}", exc_info=True
)
logger.info(f"✨ Cleanup complete for agent '{self.name}'.")
async def run(self, request: Optional[str] = None) -> str:
try:
return await super().run(request)
finally:
await self.cleanup() | --- +++ @@ -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
async def think(self) -> bool:
+ """Process current state and decide next actions using tools"""
if self.next_step_prompt:
user_msg = Message.user_message(self.next_step_prompt)
self.messages += [user_msg]
@@ -127,6 +129,7 @@ return False
async def act(self) -> str:
+ """Execute tool calls and handle their results"""
if not self.tool_calls:
if self.tool_choices == ToolChoice.REQUIRED:
raise ValueError(TOOL_CALL_REQUIRED)
@@ -161,6 +164,7 @@ return "\n\n".join(results)
async def execute_tool(self, command: ToolCall) -> str:
+ """Execute a single tool call with robust error handling"""
if not command or not command.function or not command.function.name:
return "Error: Invalid command format"
@@ -204,6 +208,7 @@ return f"Error: {error_msg}"
async def _handle_special_tool(self, name: str, result: Any, **kwargs):
+ """Handle special tool execution and state changes"""
if not self._is_special_tool(name):
return
@@ -214,12 +219,15 @@
@staticmethod
def _should_finish_execution(**kwargs) -> bool:
+ """Determine if tool execution should finish the agent"""
return True
def _is_special_tool(self, name: str) -> bool:
+ """Check if tool name is in special tools list"""
return name.lower() in [n.lower() for n in self.special_tool_names]
async def cleanup(self):
+ """Clean up resources used by the agent's tools."""
logger.info(f"🧹 Cleaning up resources for agent '{self.name}'...")
for tool_name, tool_instance in self.available_tools.tool_map.items():
if hasattr(tool_instance, "cleanup") and asyncio.iscoroutinefunction(
@@ -235,7 +243,8 @@ logger.info(f"✨ Cleanup complete for agent '{self.name}'.")
async def run(self, request: Optional[str] = None) -> str:
+ """Run the agent with cleanup when done."""
try:
return await super().run(request)
finally:
- await self.cleanup()+ await self.cleanup()
| 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
from app.tool.base import BaseTool
from app.utils.files_utils import clean_path
from app.utils.logger import logger
# load_dotenv()
daytona_settings = config.daytona
daytona_config = DaytonaConfig(
api_key=daytona_settings.daytona_api_key,
server_url=daytona_settings.daytona_server_url,
target=daytona_settings.daytona_target,
)
daytona = Daytona(daytona_config)
@dataclass
class ThreadMessage:
type: str
content: Dict[str, Any]
is_llm_message: bool = False
metadata: Optional[Dict[str, Any]] = None
timestamp: Optional[float] = field(
default_factory=lambda: datetime.now().timestamp()
)
def to_dict(self) -> Dict[str, Any]:
return {
"type": self.type,
"content": self.content,
"is_llm_message": self.is_llm_message,
"metadata": self.metadata or {},
"timestamp": self.timestamp,
}
class SandboxToolsBase(BaseTool):
# Class variable to track if sandbox URLs have been printed
_urls_printed: ClassVar[bool] = False
# Required fields
project_id: Optional[str] = None
# thread_manager: Optional[ThreadManager] = None
# Private fields (not part of the model schema)
_sandbox: Optional[Sandbox] = None
_sandbox_id: Optional[str] = None
_sandbox_pass: Optional[str] = None
workspace_path: str = Field(default="/workspace", exclude=True)
_sessions: dict[str, str] = {}
class Config:
arbitrary_types_allowed = True # Allow non-pydantic types like ThreadManager
underscore_attrs_are_private = True
async def _ensure_sandbox(self) -> Sandbox:
if self._sandbox is None:
# Get or start the sandbox
try:
self._sandbox = create_sandbox(password=config.daytona.VNC_password)
# Log URLs if not already printed
if not SandboxToolsBase._urls_printed:
vnc_link = self._sandbox.get_preview_link(6080)
website_link = self._sandbox.get_preview_link(8080)
vnc_url = (
vnc_link.url if hasattr(vnc_link, "url") else str(vnc_link)
)
website_url = (
website_link.url
if hasattr(website_link, "url")
else str(website_link)
)
print("\033[95m***")
print(f"VNC URL: {vnc_url}")
print(f"Website URL: {website_url}")
print("***\033[0m")
SandboxToolsBase._urls_printed = True
except Exception as e:
logger.error(f"Error retrieving or starting sandbox: {str(e)}")
raise e
else:
if (
self._sandbox.state == SandboxState.ARCHIVED
or self._sandbox.state == SandboxState.STOPPED
):
logger.info(f"Sandbox is in {self._sandbox.state} state. Starting...")
try:
daytona.start(self._sandbox)
# Wait a moment for the sandbox to initialize
# sleep(5)
# Refresh sandbox state after starting
# Start supervisord in a session when restarting
start_supervisord_session(self._sandbox)
except Exception as e:
logger.error(f"Error starting sandbox: {e}")
raise e
return self._sandbox
@property
def sandbox(self) -> Sandbox:
if self._sandbox is None:
raise RuntimeError("Sandbox not initialized. Call _ensure_sandbox() first.")
return self._sandbox
@property
def sandbox_id(self) -> str:
if self._sandbox_id is None:
raise RuntimeError(
"Sandbox ID not initialized. Call _ensure_sandbox() first."
)
return self._sandbox_id
def clean_path(self, path: str) -> str:
cleaned_path = clean_path(path, self.workspace_path)
logger.debug(f"Cleaned path: {path} -> {cleaned_path}")
return cleaned_path | --- +++ @@ -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"""
return {
"type": self.type,
"content": self.content,
@@ -44,6 +48,7 @@
class SandboxToolsBase(BaseTool):
+ """Base class for all sandbox tools that provides project-based sandbox access."""
# Class variable to track if sandbox URLs have been printed
_urls_printed: ClassVar[bool] = False
@@ -64,6 +69,7 @@ underscore_attrs_are_private = True
async def _ensure_sandbox(self) -> Sandbox:
+ """Ensure we have a valid sandbox instance, retrieving it from the project if needed."""
if self._sandbox is None:
# Get or start the sandbox
try:
@@ -111,12 +117,14 @@
@property
def sandbox(self) -> Sandbox:
+ """Get the sandbox instance, ensuring it exists."""
if self._sandbox is None:
raise RuntimeError("Sandbox not initialized. Call _ensure_sandbox() first.")
return self._sandbox
@property
def sandbox_id(self) -> str:
+ """Get the sandbox ID, ensuring it exists."""
if self._sandbox_id is None:
raise RuntimeError(
"Sandbox ID not initialized. Call _ensure_sandbox() first."
@@ -124,6 +132,7 @@ return self._sandbox_id
def clean_path(self, path: str) -> str:
+ """Clean and normalize a path to be relative to /workspace."""
cleaned_path = clean_path(path, self.workspace_path)
logger.debug(f"Cleaned path: {path} -> {cleaned_path}")
- return cleaned_path+ return cleaned_path
| 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 import Terminate, ToolCollection
from app.tool.ask_human import AskHuman
from app.tool.browser_use_tool import BrowserUseTool
from app.tool.mcp import MCPClients, MCPClientTool
from app.tool.python_execute import PythonExecute
from app.tool.str_replace_editor import StrReplaceEditor
class Manus(ToolCallAgent):
name: str = "Manus"
description: str = "A versatile agent that can solve various tasks using multiple tools including MCP-based tools"
system_prompt: str = SYSTEM_PROMPT.format(directory=config.workspace_root)
next_step_prompt: str = NEXT_STEP_PROMPT
max_observe: int = 10000
max_steps: int = 20
# MCP clients for remote tool access
mcp_clients: MCPClients = Field(default_factory=MCPClients)
# Add general-purpose tools to the tool collection
available_tools: ToolCollection = Field(
default_factory=lambda: ToolCollection(
PythonExecute(),
BrowserUseTool(),
StrReplaceEditor(),
AskHuman(),
Terminate(),
)
)
special_tool_names: list[str] = Field(default_factory=lambda: [Terminate().name])
browser_context_helper: Optional[BrowserContextHelper] = None
# Track connected MCP servers
connected_servers: Dict[str, str] = Field(
default_factory=dict
) # server_id -> url/command
_initialized: bool = False
@model_validator(mode="after")
def initialize_helper(self) -> "Manus":
self.browser_context_helper = BrowserContextHelper(self)
return self
@classmethod
async def create(cls, **kwargs) -> "Manus":
instance = cls(**kwargs)
await instance.initialize_mcp_servers()
instance._initialized = True
return instance
async def initialize_mcp_servers(self) -> None:
for server_id, server_config in config.mcp_config.servers.items():
try:
if server_config.type == "sse":
if server_config.url:
await self.connect_mcp_server(server_config.url, server_id)
logger.info(
f"Connected to MCP server {server_id} at {server_config.url}"
)
elif server_config.type == "stdio":
if server_config.command:
await self.connect_mcp_server(
server_config.command,
server_id,
use_stdio=True,
stdio_args=server_config.args,
)
logger.info(
f"Connected to MCP server {server_id} using command {server_config.command}"
)
except Exception as e:
logger.error(f"Failed to connect to MCP server {server_id}: {e}")
async def connect_mcp_server(
self,
server_url: str,
server_id: str = "",
use_stdio: bool = False,
stdio_args: List[str] = None,
) -> None:
if use_stdio:
await self.mcp_clients.connect_stdio(
server_url, stdio_args or [], server_id
)
self.connected_servers[server_id or server_url] = server_url
else:
await self.mcp_clients.connect_sse(server_url, server_id)
self.connected_servers[server_id or server_url] = server_url
# Update available tools with only the new tools from this server
new_tools = [
tool for tool in self.mcp_clients.tools if tool.server_id == server_id
]
self.available_tools.add_tools(*new_tools)
async def disconnect_mcp_server(self, server_id: str = "") -> None:
await self.mcp_clients.disconnect(server_id)
if server_id:
self.connected_servers.pop(server_id, None)
else:
self.connected_servers.clear()
# Rebuild available tools without the disconnected server's tools
base_tools = [
tool
for tool in self.available_tools.tools
if not isinstance(tool, MCPClientTool)
]
self.available_tools = ToolCollection(*base_tools)
self.available_tools.add_tools(*self.mcp_clients.tools)
async def cleanup(self):
if self.browser_context_helper:
await self.browser_context_helper.cleanup_browser()
# Disconnect from all MCP servers only if we were initialized
if self._initialized:
await self.disconnect_mcp_server()
self._initialized = False
async def think(self) -> bool:
if not self._initialized:
await self.initialize_mcp_servers()
self._initialized = True
original_prompt = self.next_step_prompt
recent_messages = self.memory.messages[-3:] if self.memory.messages else []
browser_in_use = any(
tc.function.name == BrowserUseTool().name
for msg in recent_messages
if msg.tool_calls
for tc in msg.tool_calls
)
if browser_in_use:
self.next_step_prompt = (
await self.browser_context_helper.format_next_step_prompt()
)
result = await super().think()
# Restore original prompt
self.next_step_prompt = original_prompt
return result | --- +++ @@ -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 @@
@model_validator(mode="after")
def initialize_helper(self) -> "Manus":
+ """Initialize basic components synchronously."""
self.browser_context_helper = BrowserContextHelper(self)
return self
@classmethod
async def create(cls, **kwargs) -> "Manus":
+ """Factory method to create and properly initialize a Manus instance."""
instance = cls(**kwargs)
await instance.initialize_mcp_servers()
instance._initialized = True
return instance
async def initialize_mcp_servers(self) -> None:
+ """Initialize connections to configured MCP servers."""
for server_id, server_config in config.mcp_config.servers.items():
try:
if server_config.type == "sse":
@@ -91,6 +95,7 @@ use_stdio: bool = False,
stdio_args: List[str] = None,
) -> None:
+ """Connect to an MCP server and add its tools."""
if use_stdio:
await self.mcp_clients.connect_stdio(
server_url, stdio_args or [], server_id
@@ -107,6 +112,7 @@ self.available_tools.add_tools(*new_tools)
async def disconnect_mcp_server(self, server_id: str = "") -> None:
+ """Disconnect from an MCP server and remove its tools."""
await self.mcp_clients.disconnect(server_id)
if server_id:
self.connected_servers.pop(server_id, None)
@@ -123,6 +129,7 @@ self.available_tools.add_tools(*self.mcp_clients.tools)
async def cleanup(self):
+ """Clean up Manus agent resources."""
if self.browser_context_helper:
await self.browser_context_helper.cleanup_browser()
# Disconnect from all MCP servers only if we were initialized
@@ -131,6 +138,7 @@ self._initialized = False
async def think(self) -> bool:
+ """Process current state and decide next actions with appropriate context."""
if not self._initialized:
await self.initialize_mcp_servers()
self._initialized = True
@@ -154,4 +162,4 @@ # Restore original prompt
self.next_step_prompt = original_prompt
- return result+ return result
| 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 import Field, field_validator
from pydantic_core.core_schema import ValidationInfo
from app.config import config
from app.llm import LLM
from app.tool.base import BaseTool, ToolResult
from app.tool.web_search import WebSearch
_BROWSER_DESCRIPTION = """\
A powerful browser automation tool that allows interaction with web pages through various actions.
* This tool provides commands for controlling a browser session, navigating web pages, and extracting information
* It maintains state across calls, keeping the browser session alive until explicitly closed
* Use this when you need to browse websites, fill forms, click buttons, extract content, or perform web searches
* Each action requires specific parameters as defined in the tool's dependencies
Key capabilities include:
* Navigation: Go to specific URLs, go back, search the web, or refresh pages
* Interaction: Click elements, input text, select from dropdowns, send keyboard commands
* Scrolling: Scroll up/down by pixel amount or scroll to specific text
* Content extraction: Extract and analyze content from web pages based on specific goals
* Tab management: Switch between tabs, open new tabs, or close tabs
Note: When using element indices, refer to the numbered elements shown in the current browser state.
"""
Context = TypeVar("Context")
class BrowserUseTool(BaseTool, Generic[Context]):
name: str = "browser_use"
description: str = _BROWSER_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": [
"go_to_url",
"click_element",
"input_text",
"scroll_down",
"scroll_up",
"scroll_to_text",
"send_keys",
"get_dropdown_options",
"select_dropdown_option",
"go_back",
"web_search",
"wait",
"extract_content",
"switch_tab",
"open_tab",
"close_tab",
],
"description": "The browser action to perform",
},
"url": {
"type": "string",
"description": "URL for 'go_to_url' or 'open_tab' actions",
},
"index": {
"type": "integer",
"description": "Element index for 'click_element', 'input_text', 'get_dropdown_options', or 'select_dropdown_option' actions",
},
"text": {
"type": "string",
"description": "Text for 'input_text', 'scroll_to_text', or 'select_dropdown_option' actions",
},
"scroll_amount": {
"type": "integer",
"description": "Pixels to scroll (positive for down, negative for up) for 'scroll_down' or 'scroll_up' actions",
},
"tab_id": {
"type": "integer",
"description": "Tab ID for 'switch_tab' action",
},
"query": {
"type": "string",
"description": "Search query for 'web_search' action",
},
"goal": {
"type": "string",
"description": "Extraction goal for 'extract_content' action",
},
"keys": {
"type": "string",
"description": "Keys to send for 'send_keys' action",
},
"seconds": {
"type": "integer",
"description": "Seconds to wait for 'wait' action",
},
},
"required": ["action"],
"dependencies": {
"go_to_url": ["url"],
"click_element": ["index"],
"input_text": ["index", "text"],
"switch_tab": ["tab_id"],
"open_tab": ["url"],
"scroll_down": ["scroll_amount"],
"scroll_up": ["scroll_amount"],
"scroll_to_text": ["text"],
"send_keys": ["keys"],
"get_dropdown_options": ["index"],
"select_dropdown_option": ["index", "text"],
"go_back": [],
"web_search": ["query"],
"wait": ["seconds"],
"extract_content": ["goal"],
},
}
lock: asyncio.Lock = Field(default_factory=asyncio.Lock)
browser: Optional[BrowserUseBrowser] = Field(default=None, exclude=True)
context: Optional[BrowserContext] = Field(default=None, exclude=True)
dom_service: Optional[DomService] = Field(default=None, exclude=True)
web_search_tool: WebSearch = Field(default_factory=WebSearch, exclude=True)
# Context for generic functionality
tool_context: Optional[Context] = Field(default=None, exclude=True)
llm: Optional[LLM] = Field(default_factory=LLM)
@field_validator("parameters", mode="before")
def validate_parameters(cls, v: dict, info: ValidationInfo) -> dict:
if not v:
raise ValueError("Parameters cannot be empty")
return v
async def _ensure_browser_initialized(self) -> BrowserContext:
if self.browser is None:
browser_config_kwargs = {"headless": False, "disable_security": True}
if config.browser_config:
from browser_use.browser.browser import ProxySettings
# handle proxy settings.
if config.browser_config.proxy and config.browser_config.proxy.server:
browser_config_kwargs["proxy"] = ProxySettings(
server=config.browser_config.proxy.server,
username=config.browser_config.proxy.username,
password=config.browser_config.proxy.password,
)
browser_attrs = [
"headless",
"disable_security",
"extra_chromium_args",
"chrome_instance_path",
"wss_url",
"cdp_url",
]
for attr in browser_attrs:
value = getattr(config.browser_config, attr, None)
if value is not None:
if not isinstance(value, list) or value:
browser_config_kwargs[attr] = value
self.browser = BrowserUseBrowser(BrowserConfig(**browser_config_kwargs))
if self.context is None:
context_config = BrowserContextConfig()
# if there is context config in the config, use it.
if (
config.browser_config
and hasattr(config.browser_config, "new_context_config")
and config.browser_config.new_context_config
):
context_config = config.browser_config.new_context_config
self.context = await self.browser.new_context(context_config)
self.dom_service = DomService(await self.context.get_current_page())
return self.context
async def execute(
self,
action: str,
url: Optional[str] = None,
index: Optional[int] = None,
text: Optional[str] = None,
scroll_amount: Optional[int] = None,
tab_id: Optional[int] = None,
query: Optional[str] = None,
goal: Optional[str] = None,
keys: Optional[str] = None,
seconds: Optional[int] = None,
**kwargs,
) -> ToolResult:
async with self.lock:
try:
context = await self._ensure_browser_initialized()
# Get max content length from config
max_content_length = getattr(
config.browser_config, "max_content_length", 2000
)
# Navigation actions
if action == "go_to_url":
if not url:
return ToolResult(
error="URL is required for 'go_to_url' action"
)
page = await context.get_current_page()
await page.goto(url)
await page.wait_for_load_state()
return ToolResult(output=f"Navigated to {url}")
elif action == "go_back":
await context.go_back()
return ToolResult(output="Navigated back")
elif action == "refresh":
await context.refresh_page()
return ToolResult(output="Refreshed current page")
elif action == "web_search":
if not query:
return ToolResult(
error="Query is required for 'web_search' action"
)
# Execute the web search and return results directly without browser navigation
search_response = await self.web_search_tool.execute(
query=query, fetch_content=True, num_results=1
)
# Navigate to the first search result
first_search_result = search_response.results[0]
url_to_navigate = first_search_result.url
page = await context.get_current_page()
await page.goto(url_to_navigate)
await page.wait_for_load_state()
return search_response
# Element interaction actions
elif action == "click_element":
if index is None:
return ToolResult(
error="Index is required for 'click_element' action"
)
element = await context.get_dom_element_by_index(index)
if not element:
return ToolResult(error=f"Element with index {index} not found")
download_path = await context._click_element_node(element)
output = f"Clicked element at index {index}"
if download_path:
output += f" - Downloaded file to {download_path}"
return ToolResult(output=output)
elif action == "input_text":
if index is None or not text:
return ToolResult(
error="Index and text are required for 'input_text' action"
)
element = await context.get_dom_element_by_index(index)
if not element:
return ToolResult(error=f"Element with index {index} not found")
await context._input_text_element_node(element, text)
return ToolResult(
output=f"Input '{text}' into element at index {index}"
)
elif action == "scroll_down" or action == "scroll_up":
direction = 1 if action == "scroll_down" else -1
amount = (
scroll_amount
if scroll_amount is not None
else context.config.browser_window_size["height"]
)
await context.execute_javascript(
f"window.scrollBy(0, {direction * amount});"
)
return ToolResult(
output=f"Scrolled {'down' if direction > 0 else 'up'} by {amount} pixels"
)
elif action == "scroll_to_text":
if not text:
return ToolResult(
error="Text is required for 'scroll_to_text' action"
)
page = await context.get_current_page()
try:
locator = page.get_by_text(text, exact=False)
await locator.scroll_into_view_if_needed()
return ToolResult(output=f"Scrolled to text: '{text}'")
except Exception as e:
return ToolResult(error=f"Failed to scroll to text: {str(e)}")
elif action == "send_keys":
if not keys:
return ToolResult(
error="Keys are required for 'send_keys' action"
)
page = await context.get_current_page()
await page.keyboard.press(keys)
return ToolResult(output=f"Sent keys: {keys}")
elif action == "get_dropdown_options":
if index is None:
return ToolResult(
error="Index is required for 'get_dropdown_options' action"
)
element = await context.get_dom_element_by_index(index)
if not element:
return ToolResult(error=f"Element with index {index} not found")
page = await context.get_current_page()
options = await page.evaluate(
"""
(xpath) => {
const select = document.evaluate(xpath, document, null,
XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (!select) return null;
return Array.from(select.options).map(opt => ({
text: opt.text,
value: opt.value,
index: opt.index
}));
}
""",
element.xpath,
)
return ToolResult(output=f"Dropdown options: {options}")
elif action == "select_dropdown_option":
if index is None or not text:
return ToolResult(
error="Index and text are required for 'select_dropdown_option' action"
)
element = await context.get_dom_element_by_index(index)
if not element:
return ToolResult(error=f"Element with index {index} not found")
page = await context.get_current_page()
await page.select_option(element.xpath, label=text)
return ToolResult(
output=f"Selected option '{text}' from dropdown at index {index}"
)
# Content extraction actions
elif action == "extract_content":
if not goal:
return ToolResult(
error="Goal is required for 'extract_content' action"
)
page = await context.get_current_page()
import markdownify
content = markdownify.markdownify(await page.content())
prompt = f"""\
Your task is to extract the content of the page. You will be given a page and a goal, and you should extract all relevant information around this goal from the page. If the goal is vague, summarize the page. Respond in json format.
Extraction goal: {goal}
Page content:
{content[:max_content_length]}
"""
messages = [{"role": "system", "content": prompt}]
# Define extraction function schema
extraction_function = {
"type": "function",
"function": {
"name": "extract_content",
"description": "Extract specific information from a webpage based on a goal",
"parameters": {
"type": "object",
"properties": {
"extracted_content": {
"type": "object",
"description": "The content extracted from the page according to the goal",
"properties": {
"text": {
"type": "string",
"description": "Text content extracted from the page",
},
"metadata": {
"type": "object",
"description": "Additional metadata about the extracted content",
"properties": {
"source": {
"type": "string",
"description": "Source of the extracted content",
}
},
},
},
}
},
"required": ["extracted_content"],
},
},
}
# Use LLM to extract content with required function calling
response = await self.llm.ask_tool(
messages,
tools=[extraction_function],
tool_choice="required",
)
if response and response.tool_calls:
args = json.loads(response.tool_calls[0].function.arguments)
extracted_content = args.get("extracted_content", {})
return ToolResult(
output=f"Extracted from page:\n{extracted_content}\n"
)
return ToolResult(output="No content was extracted from the page.")
# Tab management actions
elif action == "switch_tab":
if tab_id is None:
return ToolResult(
error="Tab ID is required for 'switch_tab' action"
)
await context.switch_to_tab(tab_id)
page = await context.get_current_page()
await page.wait_for_load_state()
return ToolResult(output=f"Switched to tab {tab_id}")
elif action == "open_tab":
if not url:
return ToolResult(error="URL is required for 'open_tab' action")
await context.create_new_tab(url)
return ToolResult(output=f"Opened new tab with {url}")
elif action == "close_tab":
await context.close_current_tab()
return ToolResult(output="Closed current tab")
# Utility actions
elif action == "wait":
seconds_to_wait = seconds if seconds is not None else 3
await asyncio.sleep(seconds_to_wait)
return ToolResult(output=f"Waited for {seconds_to_wait} seconds")
else:
return ToolResult(error=f"Unknown action: {action}")
except Exception as e:
return ToolResult(error=f"Browser action '{action}' failed: {str(e)}")
async def get_current_state(
self, context: Optional[BrowserContext] = None
) -> ToolResult:
try:
# Use provided context or fall back to self.context
ctx = context or self.context
if not ctx:
return ToolResult(error="Browser context not initialized")
state = await ctx.get_state()
# Create a viewport_info dictionary if it doesn't exist
viewport_height = 0
if hasattr(state, "viewport_info") and state.viewport_info:
viewport_height = state.viewport_info.height
elif hasattr(ctx, "config") and hasattr(ctx.config, "browser_window_size"):
viewport_height = ctx.config.browser_window_size.get("height", 0)
# Take a screenshot for the state
page = await ctx.get_current_page()
await page.bring_to_front()
await page.wait_for_load_state()
screenshot = await page.screenshot(
full_page=True, animations="disabled", type="jpeg", quality=100
)
screenshot = base64.b64encode(screenshot).decode("utf-8")
# Build the state info with all required fields
state_info = {
"url": state.url,
"title": state.title,
"tabs": [tab.model_dump() for tab in state.tabs],
"help": "[0], [1], [2], etc., represent clickable indices corresponding to the elements listed. Clicking on these indices will navigate to or interact with the respective content behind them.",
"interactive_elements": (
state.element_tree.clickable_elements_to_string()
if state.element_tree
else ""
),
"scroll_info": {
"pixels_above": getattr(state, "pixels_above", 0),
"pixels_below": getattr(state, "pixels_below", 0),
"total_height": getattr(state, "pixels_above", 0)
+ getattr(state, "pixels_below", 0)
+ viewport_height,
},
"viewport_height": viewport_height,
}
return ToolResult(
output=json.dumps(state_info, indent=4, ensure_ascii=False),
base64_image=screenshot,
)
except Exception as e:
return ToolResult(error=f"Failed to get browser state: {str(e)}")
async def cleanup(self):
async with self.lock:
if self.context is not None:
await self.context.close()
self.context = None
self.dom_service = None
if self.browser is not None:
await self.browser.close()
self.browser = None
def __del__(self):
if self.browser is not None or self.context is not None:
try:
asyncio.run(self.cleanup())
except RuntimeError:
loop = asyncio.new_event_loop()
loop.run_until_complete(self.cleanup())
loop.close()
@classmethod
def create_with_context(cls, context: Context) -> "BrowserUseTool[Context]":
tool = cls()
tool.tool_context = context
return tool | --- +++ @@ -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 @@ seconds: Optional[int] = None,
**kwargs,
) -> ToolResult:
+ """
+ Execute a specified browser action.
+
+ Args:
+ action: The browser action to perform
+ url: URL for navigation or new tab
+ index: Element index for click or input actions
+ text: Text for input action or search query
+ scroll_amount: Pixels to scroll for scroll action
+ tab_id: Tab ID for switch_tab action
+ query: Search query for Google search
+ goal: Extraction goal for content extraction
+ keys: Keys to send for keyboard actions
+ seconds: Seconds to wait
+ **kwargs: Additional arguments
+
+ Returns:
+ ToolResult with the action's output or error
+ """
async with self.lock:
try:
context = await self._ensure_browser_initialized()
@@ -459,6 +479,10 @@ async def get_current_state(
self, context: Optional[BrowserContext] = None
) -> ToolResult:
+ """
+ Get the current browser state as a ToolResult.
+ If context is not provided, uses self.context.
+ """
try:
# Use provided context or fall back to self.context
ctx = context or self.context
@@ -515,6 +539,7 @@ return ToolResult(error=f"Failed to get browser state: {str(e)}")
async def cleanup(self):
+ """Clean up browser resources."""
async with self.lock:
if self.context is not None:
await self.context.close()
@@ -525,6 +550,7 @@ self.browser = None
def __del__(self):
+ """Ensure cleanup when object is destroyed."""
if self.browser is not None or self.context is not None:
try:
asyncio.run(self.cleanup())
@@ -535,6 +561,7 @@
@classmethod
def create_with_context(cls, context: Context) -> "BrowserUseTool[Context]":
+ """Factory method to create a BrowserUseTool with a specific context."""
tool = cls()
tool.tool_context = context
- return tool+ return tool
| 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 should be redirected to a file, e.g. command = `python3 app.py > server.log 2>&1 &`.
* Interactive: If a bash command returns exit code `-1`, this means the process is not yet finished. The assistant must then send a second call to terminal with an empty `command` (which will retrieve any additional logs), or it can send additional text (set `command` to the text) to STDIN of the running process, or it can send command=`ctrl+c` to interrupt the process.
* Timeout: If a command execution result says "Command timed out. Sending SIGINT to the process", the assistant should retry running the command in the background.
"""
class _BashSession:
_started: bool
_process: asyncio.subprocess.Process
command: str = "/bin/bash"
_output_delay: float = 0.2 # seconds
_timeout: float = 120.0 # seconds
_sentinel: str = "<<exit>>"
def __init__(self):
self._started = False
self._timed_out = False
async def start(self):
if self._started:
return
self._process = await asyncio.create_subprocess_shell(
self.command,
preexec_fn=os.setsid,
shell=True,
bufsize=0,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
self._started = True
def stop(self):
if not self._started:
raise ToolError("Session has not started.")
if self._process.returncode is not None:
return
self._process.terminate()
async def run(self, command: str):
if not self._started:
raise ToolError("Session has not started.")
if self._process.returncode is not None:
return CLIResult(
system="tool must be restarted",
error=f"bash has exited with returncode {self._process.returncode}",
)
if self._timed_out:
raise ToolError(
f"timed out: bash has not returned in {self._timeout} seconds and must be restarted",
)
# we know these are not None because we created the process with PIPEs
assert self._process.stdin
assert self._process.stdout
assert self._process.stderr
# send command to the process
self._process.stdin.write(
command.encode() + f"; echo '{self._sentinel}'\n".encode()
)
await self._process.stdin.drain()
# read output from the process, until the sentinel is found
try:
async with asyncio.timeout(self._timeout):
while True:
await asyncio.sleep(self._output_delay)
# if we read directly from stdout/stderr, it will wait forever for
# EOF. use the StreamReader buffer directly instead.
output = (
self._process.stdout._buffer.decode()
) # pyright: ignore[reportAttributeAccessIssue]
if self._sentinel in output:
# strip the sentinel and break
output = output[: output.index(self._sentinel)]
break
except asyncio.TimeoutError:
self._timed_out = True
raise ToolError(
f"timed out: bash has not returned in {self._timeout} seconds and must be restarted",
) from None
if output.endswith("\n"):
output = output[:-1]
error = (
self._process.stderr._buffer.decode()
) # pyright: ignore[reportAttributeAccessIssue]
if error.endswith("\n"):
error = error[:-1]
# clear the buffers so that the next output can be read correctly
self._process.stdout._buffer.clear() # pyright: ignore[reportAttributeAccessIssue]
self._process.stderr._buffer.clear() # pyright: ignore[reportAttributeAccessIssue]
return CLIResult(output=output, error=error)
class Bash(BaseTool):
name: str = "bash"
description: str = _BASH_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The bash command to execute. Can be empty to view additional logs when previous exit code is `-1`. Can be `ctrl+c` to interrupt the currently running process.",
},
},
"required": ["command"],
}
_session: Optional[_BashSession] = None
async def execute(
self, command: str | None = None, restart: bool = False, **kwargs
) -> CLIResult:
if restart:
if self._session:
self._session.stop()
self._session = _BashSession()
await self._session.start()
return CLIResult(system="tool has been restarted.")
if self._session is None:
self._session = _BashSession()
await self._session.start()
if command is not None:
return await self._session.run(command)
raise ToolError("no command provided.")
if __name__ == "__main__":
bash = Bash()
rst = asyncio.run(bash.execute("ls -l"))
print(rst) | --- +++ @@ -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 ToolError("Session has not started.")
if self._process.returncode is not None:
@@ -51,6 +53,7 @@ self._process.terminate()
async def run(self, command: str):
+ """Execute a command in the bash shell."""
if not self._started:
raise ToolError("Session has not started.")
if self._process.returncode is not None:
@@ -111,6 +114,7 @@
class Bash(BaseTool):
+ """A tool for executing bash commands"""
name: str = "bash"
description: str = _BASH_DESCRIPTION
@@ -151,4 +155,4 @@ if __name__ == "__main__":
bash = Bash()
rst = asyncio.run(bash.execute("ls -l"))
- print(rst)+ print(rst)
| 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:
arbitrary_types_allowed = True
def __init__(
self, agents: Union[BaseAgent, List[BaseAgent], Dict[str, BaseAgent]], **data
):
# Handle different ways of providing agents
if isinstance(agents, BaseAgent):
agents_dict = {"default": agents}
elif isinstance(agents, list):
agents_dict = {f"agent_{i}": agent for i, agent in enumerate(agents)}
else:
agents_dict = agents
# If primary agent not specified, use first agent
primary_key = data.get("primary_agent_key")
if not primary_key and agents_dict:
primary_key = next(iter(agents_dict))
data["primary_agent_key"] = primary_key
# Set the agents dictionary
data["agents"] = agents_dict
# Initialize using BaseModel's init
super().__init__(**data)
@property
def primary_agent(self) -> Optional[BaseAgent]:
return self.agents.get(self.primary_agent_key)
def get_agent(self, key: str) -> Optional[BaseAgent]:
return self.agents.get(key)
def add_agent(self, key: str, agent: BaseAgent) -> None:
self.agents[key] = agent
@abstractmethod
async def execute(self, input_text: str) -> str: | --- +++ @@ -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 agent for the flow"""
return self.agents.get(self.primary_agent_key)
def get_agent(self, key: str) -> Optional[BaseAgent]:
+ """Get a specific agent by key"""
return self.agents.get(key)
def add_agent(self, key: str, agent: BaseAgent) -> None:
+ """Add a new agent to the flow"""
self.agents[key] = agent
@abstractmethod
- async def execute(self, input_text: str) -> str:+ async def execute(self, input_text: str) -> str:
+ """Execute the flow with given input"""
| 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:
# arbitrary_types_allowed = True
# async def __call__(self, **kwargs) -> Any:
# """Execute the tool with given parameters."""
# return await self.execute(**kwargs)
# @abstractmethod
# async def execute(self, **kwargs) -> Any:
# """Execute the tool with given parameters."""
# def to_param(self) -> Dict:
# """Convert tool to function call format."""
# return {
# "type": "function",
# "function": {
# "name": self.name,
# "description": self.description,
# "parameters": self.parameters,
# },
# }
class ToolResult(BaseModel):
output: Any = Field(default=None)
error: Optional[str] = Field(default=None)
base64_image: Optional[str] = Field(default=None)
system: Optional[str] = Field(default=None)
class Config:
arbitrary_types_allowed = True
def __bool__(self):
return any(getattr(self, field) for field in self.__fields__)
def __add__(self, other: "ToolResult"):
def combine_fields(
field: Optional[str], other_field: Optional[str], concatenate: bool = True
):
if field and other_field:
if concatenate:
return field + other_field
raise ValueError("Cannot combine tool results")
return field or other_field
return ToolResult(
output=combine_fields(self.output, other.output),
error=combine_fields(self.error, other.error),
base64_image=combine_fields(self.base64_image, other.base64_image, False),
system=combine_fields(self.system, other.system),
)
def __str__(self):
return f"Error: {self.error}" if self.error else self.output
def replace(self, **kwargs):
# return self.copy(update=kwargs)
return type(self)(**{**self.dict(), **kwargs})
class BaseTool(ABC, BaseModel):
name: str
description: str
parameters: Optional[dict] = None
# _schemas: Dict[str, List[ToolSchema]] = {}
class Config:
arbitrary_types_allowed = True
underscore_attrs_are_private = False
# def __init__(self, **data):
# """Initialize tool with model validation and schema registration."""
# super().__init__(**data)
# logger.debug(f"Initializing tool class: {self.__class__.__name__}")
# self._register_schemas()
# def _register_schemas(self):
# """Register schemas from all decorated methods."""
# for name, method in inspect.getmembers(self, predicate=inspect.ismethod):
# if hasattr(method, 'tool_schemas'):
# self._schemas[name] = method.tool_schemas
# logger.debug(f"Registered schemas for method '{name}' in {self.__class__.__name__}")
async def __call__(self, **kwargs) -> Any:
return await self.execute(**kwargs)
@abstractmethod
async def execute(self, **kwargs) -> Any:
def to_param(self) -> Dict:
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": self.parameters,
},
}
# def get_schemas(self) -> Dict[str, List[ToolSchema]]:
# """Get all registered tool schemas.
# Returns:
# Dict mapping method names to their schema definitions
# """
# return self._schemas
def success_response(self, data: Union[Dict[str, Any], str]) -> ToolResult:
if isinstance(data, str):
text = data
else:
text = json.dumps(data, indent=2)
logger.debug(f"Created success response for {self.__class__.__name__}")
return ToolResult(output=text)
def fail_response(self, msg: str) -> ToolResult:
logger.debug(f"Tool {self.__class__.__name__} returned failed result: {msg}")
return ToolResult(error=msg)
class CLIResult(ToolResult):
class ToolFailure(ToolResult): | --- +++ @@ -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, **kwargs):
+ """Returns a new ToolResult with the given fields replaced."""
# return self.copy(update=kwargs)
return type(self)(**{**self.dict(), **kwargs})
class BaseTool(ABC, BaseModel):
+ """Consolidated base class for all tools combining BaseModel and Tool functionality.
+
+ Provides:
+ - Pydantic model validation
+ - Schema registration
+ - Standardized result handling
+ - Abstract execution interface
+
+ Attributes:
+ name (str): Tool name
+ description (str): Tool description
+ parameters (dict): Tool parameters schema
+ _schemas (Dict[str, List[ToolSchema]]): Registered method schemas
+ """
name: str
description: str
@@ -98,12 +114,19 @@ # logger.debug(f"Registered schemas for method '{name}' in {self.__class__.__name__}")
async def __call__(self, **kwargs) -> Any:
+ """Execute the tool with given parameters."""
return await self.execute(**kwargs)
@abstractmethod
async def execute(self, **kwargs) -> Any:
+ """Execute the tool with given parameters."""
def to_param(self) -> Dict:
+ """Convert tool to function call format.
+
+ Returns:
+ Dictionary with tool metadata in OpenAI function calling format
+ """
return {
"type": "function",
"function": {
@@ -122,6 +145,14 @@ # return self._schemas
def success_response(self, data: Union[Dict[str, Any], str]) -> ToolResult:
+ """Create a successful tool result.
+
+ Args:
+ data: Result data (dictionary or string)
+
+ Returns:
+ ToolResult with success=True and formatted output
+ """
if isinstance(data, str):
text = data
else:
@@ -130,11 +161,21 @@ return ToolResult(output=text)
def fail_response(self, msg: str) -> ToolResult:
+ """Create a failed tool result.
+
+ Args:
+ msg: Error message describing the failure
+
+ Returns:
+ ToolResult with success=False and error message
+ """
logger.debug(f"Tool {self.__class__.__name__} returned failed result: {msg}")
return ToolResult(error=msg)
class CLIResult(ToolResult):
+ """A ToolResult that can be rendered as a CLI output."""
-class ToolFailure(ToolResult):+class ToolFailure(ToolResult):
+ """A ToolResult that represents a failure."""
| 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,
retry_if_exception_type,
stop_after_attempt,
wait_random_exponential,
)
from app.bedrock import BedrockClient
from app.config import LLMSettings, config
from app.exceptions import TokenLimitExceeded
from app.logger import logger # Assuming a logger is set up in your app
from app.schema import (
ROLE_VALUES,
TOOL_CHOICE_TYPE,
TOOL_CHOICE_VALUES,
Message,
ToolChoice,
)
REASONING_MODELS = ["o1", "o3-mini"]
MULTIMODAL_MODELS = [
"gpt-4-vision-preview",
"gpt-4o",
"gpt-4o-mini",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-3-haiku-20240307",
]
class TokenCounter:
# Token constants
BASE_MESSAGE_TOKENS = 4
FORMAT_TOKENS = 2
LOW_DETAIL_IMAGE_TOKENS = 85
HIGH_DETAIL_TILE_TOKENS = 170
# Image processing constants
MAX_SIZE = 2048
HIGH_DETAIL_TARGET_SHORT_SIDE = 768
TILE_SIZE = 512
def __init__(self, tokenizer):
self.tokenizer = tokenizer
def count_text(self, text: str) -> int:
return 0 if not text else len(self.tokenizer.encode(text))
def count_image(self, image_item: dict) -> int:
detail = image_item.get("detail", "medium")
# For low detail, always return fixed token count
if detail == "low":
return self.LOW_DETAIL_IMAGE_TOKENS
# For medium detail (default in OpenAI), use high detail calculation
# OpenAI doesn't specify a separate calculation for medium
# For high detail, calculate based on dimensions if available
if detail == "high" or detail == "medium":
# If dimensions are provided in the image_item
if "dimensions" in image_item:
width, height = image_item["dimensions"]
return self._calculate_high_detail_tokens(width, height)
return (
self._calculate_high_detail_tokens(1024, 1024) if detail == "high" else 1024
)
def _calculate_high_detail_tokens(self, width: int, height: int) -> int:
# Step 1: Scale to fit in MAX_SIZE x MAX_SIZE square
if width > self.MAX_SIZE or height > self.MAX_SIZE:
scale = self.MAX_SIZE / max(width, height)
width = int(width * scale)
height = int(height * scale)
# Step 2: Scale so shortest side is HIGH_DETAIL_TARGET_SHORT_SIDE
scale = self.HIGH_DETAIL_TARGET_SHORT_SIDE / min(width, height)
scaled_width = int(width * scale)
scaled_height = int(height * scale)
# Step 3: Count number of 512px tiles
tiles_x = math.ceil(scaled_width / self.TILE_SIZE)
tiles_y = math.ceil(scaled_height / self.TILE_SIZE)
total_tiles = tiles_x * tiles_y
# Step 4: Calculate final token count
return (
total_tiles * self.HIGH_DETAIL_TILE_TOKENS
) + self.LOW_DETAIL_IMAGE_TOKENS
def count_content(self, content: Union[str, List[Union[str, dict]]]) -> int:
if not content:
return 0
if isinstance(content, str):
return self.count_text(content)
token_count = 0
for item in content:
if isinstance(item, str):
token_count += self.count_text(item)
elif isinstance(item, dict):
if "text" in item:
token_count += self.count_text(item["text"])
elif "image_url" in item:
token_count += self.count_image(item)
return token_count
def count_tool_calls(self, tool_calls: List[dict]) -> int:
token_count = 0
for tool_call in tool_calls:
if "function" in tool_call:
function = tool_call["function"]
token_count += self.count_text(function.get("name", ""))
token_count += self.count_text(function.get("arguments", ""))
return token_count
def count_message_tokens(self, messages: List[dict]) -> int:
total_tokens = self.FORMAT_TOKENS # Base format tokens
for message in messages:
tokens = self.BASE_MESSAGE_TOKENS # Base tokens per message
# Add role tokens
tokens += self.count_text(message.get("role", ""))
# Add content tokens
if "content" in message:
tokens += self.count_content(message["content"])
# Add tool calls tokens
if "tool_calls" in message:
tokens += self.count_tool_calls(message["tool_calls"])
# Add name and tool_call_id tokens
tokens += self.count_text(message.get("name", ""))
tokens += self.count_text(message.get("tool_call_id", ""))
total_tokens += tokens
return total_tokens
class LLM:
_instances: Dict[str, "LLM"] = {}
def __new__(
cls, config_name: str = "default", llm_config: Optional[LLMSettings] = None
):
if config_name not in cls._instances:
instance = super().__new__(cls)
instance.__init__(config_name, llm_config)
cls._instances[config_name] = instance
return cls._instances[config_name]
def __init__(
self, config_name: str = "default", llm_config: Optional[LLMSettings] = None
):
if not hasattr(self, "client"): # Only initialize if not already initialized
llm_config = llm_config or config.llm
llm_config = llm_config.get(config_name, llm_config["default"])
self.model = llm_config.model
self.max_tokens = llm_config.max_tokens
self.temperature = llm_config.temperature
self.api_type = llm_config.api_type
self.api_key = llm_config.api_key
self.api_version = llm_config.api_version
self.base_url = llm_config.base_url
# Add token counting related attributes
self.total_input_tokens = 0
self.total_completion_tokens = 0
self.max_input_tokens = (
llm_config.max_input_tokens
if hasattr(llm_config, "max_input_tokens")
else None
)
# Initialize tokenizer
try:
self.tokenizer = tiktoken.encoding_for_model(self.model)
except KeyError:
# If the model is not in tiktoken's presets, use cl100k_base as default
self.tokenizer = tiktoken.get_encoding("cl100k_base")
if self.api_type == "azure":
self.client = AsyncAzureOpenAI(
base_url=self.base_url,
api_key=self.api_key,
api_version=self.api_version,
)
elif self.api_type == "aws":
self.client = BedrockClient()
else:
self.client = AsyncOpenAI(api_key=self.api_key, base_url=self.base_url)
self.token_counter = TokenCounter(self.tokenizer)
def count_tokens(self, text: str) -> int:
if not text:
return 0
return len(self.tokenizer.encode(text))
def count_message_tokens(self, messages: List[dict]) -> int:
return self.token_counter.count_message_tokens(messages)
def update_token_count(self, input_tokens: int, completion_tokens: int = 0) -> None:
# Only track tokens if max_input_tokens is set
self.total_input_tokens += input_tokens
self.total_completion_tokens += completion_tokens
logger.info(
f"Token usage: Input={input_tokens}, Completion={completion_tokens}, "
f"Cumulative Input={self.total_input_tokens}, Cumulative Completion={self.total_completion_tokens}, "
f"Total={input_tokens + completion_tokens}, Cumulative Total={self.total_input_tokens + self.total_completion_tokens}"
)
def check_token_limit(self, input_tokens: int) -> bool:
if self.max_input_tokens is not None:
return (self.total_input_tokens + input_tokens) <= self.max_input_tokens
# If max_input_tokens is not set, always return True
return True
def get_limit_error_message(self, input_tokens: int) -> str:
if (
self.max_input_tokens is not None
and (self.total_input_tokens + input_tokens) > self.max_input_tokens
):
return f"Request may exceed input token limit (Current: {self.total_input_tokens}, Needed: {input_tokens}, Max: {self.max_input_tokens})"
return "Token limit exceeded"
@staticmethod
def format_messages(
messages: List[Union[dict, Message]], supports_images: bool = False
) -> List[dict]:
formatted_messages = []
for message in messages:
# Convert Message objects to dictionaries
if isinstance(message, Message):
message = message.to_dict()
if isinstance(message, dict):
# If message is a dict, ensure it has required fields
if "role" not in message:
raise ValueError("Message dict must contain 'role' field")
# Process base64 images if present and model supports images
if supports_images and message.get("base64_image"):
# Initialize or convert content to appropriate format
if not message.get("content"):
message["content"] = []
elif isinstance(message["content"], str):
message["content"] = [
{"type": "text", "text": message["content"]}
]
elif isinstance(message["content"], list):
# Convert string items to proper text objects
message["content"] = [
(
{"type": "text", "text": item}
if isinstance(item, str)
else item
)
for item in message["content"]
]
# Add the image to content
message["content"].append(
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{message['base64_image']}"
},
}
)
# Remove the base64_image field
del message["base64_image"]
# If model doesn't support images but message has base64_image, handle gracefully
elif not supports_images and message.get("base64_image"):
# Just remove the base64_image field and keep the text content
del message["base64_image"]
if "content" in message or "tool_calls" in message:
formatted_messages.append(message)
# else: do not include the message
else:
raise TypeError(f"Unsupported message type: {type(message)}")
# Validate all messages have required fields
for msg in formatted_messages:
if msg["role"] not in ROLE_VALUES:
raise ValueError(f"Invalid role: {msg['role']}")
return formatted_messages
@retry(
wait=wait_random_exponential(min=1, max=60),
stop=stop_after_attempt(6),
retry=retry_if_exception_type(
(OpenAIError, Exception, ValueError)
), # Don't retry TokenLimitExceeded
)
async def ask(
self,
messages: List[Union[dict, Message]],
system_msgs: Optional[List[Union[dict, Message]]] = None,
stream: bool = True,
temperature: Optional[float] = None,
) -> str:
try:
# Check if the model supports images
supports_images = self.model in MULTIMODAL_MODELS
# Format system and user messages with image support check
if system_msgs:
system_msgs = self.format_messages(system_msgs, supports_images)
messages = system_msgs + self.format_messages(messages, supports_images)
else:
messages = self.format_messages(messages, supports_images)
# Calculate input token count
input_tokens = self.count_message_tokens(messages)
# Check if token limits are exceeded
if not self.check_token_limit(input_tokens):
error_message = self.get_limit_error_message(input_tokens)
# Raise a special exception that won't be retried
raise TokenLimitExceeded(error_message)
params = {
"model": self.model,
"messages": messages,
}
if self.model in REASONING_MODELS:
params["max_completion_tokens"] = self.max_tokens
else:
params["max_tokens"] = self.max_tokens
params["temperature"] = (
temperature if temperature is not None else self.temperature
)
if not stream:
# Non-streaming request
response = await self.client.chat.completions.create(
**params, stream=False
)
if not response.choices or not response.choices[0].message.content:
raise ValueError("Empty or invalid response from LLM")
# Update token counts
self.update_token_count(
response.usage.prompt_tokens, response.usage.completion_tokens
)
return response.choices[0].message.content
# Streaming request, For streaming, update estimated token count before making the request
self.update_token_count(input_tokens)
response = await self.client.chat.completions.create(**params, stream=True)
collected_messages = []
completion_text = ""
async for chunk in response:
chunk_message = chunk.choices[0].delta.content or ""
collected_messages.append(chunk_message)
completion_text += chunk_message
print(chunk_message, end="", flush=True)
print() # Newline after streaming
full_response = "".join(collected_messages).strip()
if not full_response:
raise ValueError("Empty response from streaming LLM")
# estimate completion tokens for streaming response
completion_tokens = self.count_tokens(completion_text)
logger.info(
f"Estimated completion tokens for streaming response: {completion_tokens}"
)
self.total_completion_tokens += completion_tokens
return full_response
except TokenLimitExceeded:
# Re-raise token limit errors without logging
raise
except ValueError:
logger.exception(f"Validation error")
raise
except OpenAIError as oe:
logger.exception(f"OpenAI API error")
if isinstance(oe, AuthenticationError):
logger.error("Authentication failed. Check API key.")
elif isinstance(oe, RateLimitError):
logger.error("Rate limit exceeded. Consider increasing retry attempts.")
elif isinstance(oe, APIError):
logger.error(f"API error: {oe}")
raise
except Exception:
logger.exception(f"Unexpected error in ask")
raise
@retry(
wait=wait_random_exponential(min=1, max=60),
stop=stop_after_attempt(6),
retry=retry_if_exception_type(
(OpenAIError, Exception, ValueError)
), # Don't retry TokenLimitExceeded
)
async def ask_with_images(
self,
messages: List[Union[dict, Message]],
images: List[Union[str, dict]],
system_msgs: Optional[List[Union[dict, Message]]] = None,
stream: bool = False,
temperature: Optional[float] = None,
) -> str:
try:
# For ask_with_images, we always set supports_images to True because
# this method should only be called with models that support images
if self.model not in MULTIMODAL_MODELS:
raise ValueError(
f"Model {self.model} does not support images. Use a model from {MULTIMODAL_MODELS}"
)
# Format messages with image support
formatted_messages = self.format_messages(messages, supports_images=True)
# Ensure the last message is from the user to attach images
if not formatted_messages or formatted_messages[-1]["role"] != "user":
raise ValueError(
"The last message must be from the user to attach images"
)
# Process the last user message to include images
last_message = formatted_messages[-1]
# Convert content to multimodal format if needed
content = last_message["content"]
multimodal_content = (
[{"type": "text", "text": content}]
if isinstance(content, str)
else content
if isinstance(content, list)
else []
)
# Add images to content
for image in images:
if isinstance(image, str):
multimodal_content.append(
{"type": "image_url", "image_url": {"url": image}}
)
elif isinstance(image, dict) and "url" in image:
multimodal_content.append({"type": "image_url", "image_url": image})
elif isinstance(image, dict) and "image_url" in image:
multimodal_content.append(image)
else:
raise ValueError(f"Unsupported image format: {image}")
# Update the message with multimodal content
last_message["content"] = multimodal_content
# Add system messages if provided
if system_msgs:
all_messages = (
self.format_messages(system_msgs, supports_images=True)
+ formatted_messages
)
else:
all_messages = formatted_messages
# Calculate tokens and check limits
input_tokens = self.count_message_tokens(all_messages)
if not self.check_token_limit(input_tokens):
raise TokenLimitExceeded(self.get_limit_error_message(input_tokens))
# Set up API parameters
params = {
"model": self.model,
"messages": all_messages,
"stream": stream,
}
# Add model-specific parameters
if self.model in REASONING_MODELS:
params["max_completion_tokens"] = self.max_tokens
else:
params["max_tokens"] = self.max_tokens
params["temperature"] = (
temperature if temperature is not None else self.temperature
)
# Handle non-streaming request
if not stream:
response = await self.client.chat.completions.create(**params)
if not response.choices or not response.choices[0].message.content:
raise ValueError("Empty or invalid response from LLM")
self.update_token_count(response.usage.prompt_tokens)
return response.choices[0].message.content
# Handle streaming request
self.update_token_count(input_tokens)
response = await self.client.chat.completions.create(**params)
collected_messages = []
async for chunk in response:
chunk_message = chunk.choices[0].delta.content or ""
collected_messages.append(chunk_message)
print(chunk_message, end="", flush=True)
print() # Newline after streaming
full_response = "".join(collected_messages).strip()
if not full_response:
raise ValueError("Empty response from streaming LLM")
return full_response
except TokenLimitExceeded:
raise
except ValueError as ve:
logger.error(f"Validation error in ask_with_images: {ve}")
raise
except OpenAIError as oe:
logger.error(f"OpenAI API error: {oe}")
if isinstance(oe, AuthenticationError):
logger.error("Authentication failed. Check API key.")
elif isinstance(oe, RateLimitError):
logger.error("Rate limit exceeded. Consider increasing retry attempts.")
elif isinstance(oe, APIError):
logger.error(f"API error: {oe}")
raise
except Exception as e:
logger.error(f"Unexpected error in ask_with_images: {e}")
raise
@retry(
wait=wait_random_exponential(min=1, max=60),
stop=stop_after_attempt(6),
retry=retry_if_exception_type(
(OpenAIError, Exception, ValueError)
), # Don't retry TokenLimitExceeded
)
async def ask_tool(
self,
messages: List[Union[dict, Message]],
system_msgs: Optional[List[Union[dict, Message]]] = None,
timeout: int = 300,
tools: Optional[List[dict]] = None,
tool_choice: TOOL_CHOICE_TYPE = ToolChoice.AUTO, # type: ignore
temperature: Optional[float] = None,
**kwargs,
) -> ChatCompletionMessage | None:
try:
# Validate tool_choice
if tool_choice not in TOOL_CHOICE_VALUES:
raise ValueError(f"Invalid tool_choice: {tool_choice}")
# Check if the model supports images
supports_images = self.model in MULTIMODAL_MODELS
# Format messages
if system_msgs:
system_msgs = self.format_messages(system_msgs, supports_images)
messages = system_msgs + self.format_messages(messages, supports_images)
else:
messages = self.format_messages(messages, supports_images)
# Calculate input token count
input_tokens = self.count_message_tokens(messages)
# If there are tools, calculate token count for tool descriptions
tools_tokens = 0
if tools:
for tool in tools:
tools_tokens += self.count_tokens(str(tool))
input_tokens += tools_tokens
# Check if token limits are exceeded
if not self.check_token_limit(input_tokens):
error_message = self.get_limit_error_message(input_tokens)
# Raise a special exception that won't be retried
raise TokenLimitExceeded(error_message)
# Validate tools if provided
if tools:
for tool in tools:
if not isinstance(tool, dict) or "type" not in tool:
raise ValueError("Each tool must be a dict with 'type' field")
# Set up the completion request
params = {
"model": self.model,
"messages": messages,
"tools": tools,
"tool_choice": tool_choice,
"timeout": timeout,
**kwargs,
}
if self.model in REASONING_MODELS:
params["max_completion_tokens"] = self.max_tokens
else:
params["max_tokens"] = self.max_tokens
params["temperature"] = (
temperature if temperature is not None else self.temperature
)
params["stream"] = False # Always use non-streaming for tool requests
response: ChatCompletion = await self.client.chat.completions.create(
**params
)
# Check if response is valid
if not response.choices or not response.choices[0].message:
print(response)
# raise ValueError("Invalid or empty response from LLM")
return None
# Update token counts
self.update_token_count(
response.usage.prompt_tokens, response.usage.completion_tokens
)
return response.choices[0].message
except TokenLimitExceeded:
# Re-raise token limit errors without logging
raise
except ValueError as ve:
logger.error(f"Validation error in ask_tool: {ve}")
raise
except OpenAIError as oe:
logger.error(f"OpenAI API error: {oe}")
if isinstance(oe, AuthenticationError):
logger.error("Authentication failed. Check API key.")
elif isinstance(oe, RateLimitError):
logger.error("Rate limit exceeded. Consider increasing retry attempts.")
elif isinstance(oe, APIError):
logger.error(f"API error: {oe}")
raise
except Exception as e:
logger.error(f"Unexpected error in ask_tool: {e}")
raise | --- +++ @@ -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 for an image based on detail level and dimensions
+
+ For "low" detail: fixed 85 tokens
+ For "high" detail:
+ 1. Scale to fit in 2048x2048 square
+ 2. Scale shortest side to 768px
+ 3. Count 512px tiles (170 tokens each)
+ 4. Add 85 tokens
+ """
detail = image_item.get("detail", "medium")
# For low detail, always return fixed token count
@@ -82,6 +93,7 @@ )
def _calculate_high_detail_tokens(self, width: int, height: int) -> int:
+ """Calculate tokens for high detail images based on dimensions"""
# Step 1: Scale to fit in MAX_SIZE x MAX_SIZE square
if width > self.MAX_SIZE or height > self.MAX_SIZE:
scale = self.MAX_SIZE / max(width, height)
@@ -104,6 +116,7 @@ ) + self.LOW_DETAIL_IMAGE_TOKENS
def count_content(self, content: Union[str, List[Union[str, dict]]]) -> int:
+ """Calculate tokens for message content"""
if not content:
return 0
@@ -122,6 +135,7 @@ return token_count
def count_tool_calls(self, tool_calls: List[dict]) -> int:
+ """Calculate tokens for tool calls"""
token_count = 0
for tool_call in tool_calls:
if "function" in tool_call:
@@ -131,6 +145,7 @@ return token_count
def count_message_tokens(self, messages: List[dict]) -> int:
+ """Calculate the total number of tokens in a message list"""
total_tokens = self.FORMAT_TOKENS # Base format tokens
for message in messages:
@@ -212,6 +227,7 @@ self.token_counter = TokenCounter(self.tokenizer)
def count_tokens(self, text: str) -> int:
+ """Calculate the number of tokens in a text"""
if not text:
return 0
return len(self.tokenizer.encode(text))
@@ -220,6 +236,7 @@ return self.token_counter.count_message_tokens(messages)
def update_token_count(self, input_tokens: int, completion_tokens: int = 0) -> None:
+ """Update token counts"""
# Only track tokens if max_input_tokens is set
self.total_input_tokens += input_tokens
self.total_completion_tokens += completion_tokens
@@ -230,12 +247,14 @@ )
def check_token_limit(self, input_tokens: int) -> bool:
+ """Check if token limits are exceeded"""
if self.max_input_tokens is not None:
return (self.total_input_tokens + input_tokens) <= self.max_input_tokens
# If max_input_tokens is not set, always return True
return True
def get_limit_error_message(self, input_tokens: int) -> str:
+ """Generate error message for token limit exceeded"""
if (
self.max_input_tokens is not None
and (self.total_input_tokens + input_tokens) > self.max_input_tokens
@@ -248,6 +267,28 @@ def format_messages(
messages: List[Union[dict, Message]], supports_images: bool = False
) -> List[dict]:
+ """
+ Format messages for LLM by converting them to OpenAI message format.
+
+ Args:
+ messages: List of messages that can be either dict or Message objects
+ supports_images: Flag indicating if the target model supports image inputs
+
+ Returns:
+ List[dict]: List of formatted messages in OpenAI format
+
+ Raises:
+ ValueError: If messages are invalid or missing required fields
+ TypeError: If unsupported message types are provided
+
+ Examples:
+ >>> msgs = [
+ ... Message.system_message("You are a helpful assistant"),
+ ... {"role": "user", "content": "Hello"},
+ ... Message.user_message("How are you?")
+ ... ]
+ >>> formatted = LLM.format_messages(msgs)
+ """
formatted_messages = []
for message in messages:
@@ -324,6 +365,24 @@ stream: bool = True,
temperature: Optional[float] = None,
) -> str:
+ """
+ Send a prompt to the LLM and get the response.
+
+ Args:
+ messages: List of conversation messages
+ system_msgs: Optional system messages to prepend
+ stream (bool): Whether to stream the response
+ temperature (float): Sampling temperature for the response
+
+ Returns:
+ str: The generated response
+
+ Raises:
+ TokenLimitExceeded: If token limits are exceeded
+ ValueError: If messages are invalid or response is empty
+ OpenAIError: If API call fails after retries
+ Exception: For unexpected errors
+ """
try:
# Check if the model supports images
supports_images = self.model in MULTIMODAL_MODELS
@@ -434,6 +493,25 @@ stream: bool = False,
temperature: Optional[float] = None,
) -> str:
+ """
+ Send a prompt with images to the LLM and get the response.
+
+ Args:
+ messages: List of conversation messages
+ images: List of image URLs or image data dictionaries
+ system_msgs: Optional system messages to prepend
+ stream (bool): Whether to stream the response
+ temperature (float): Sampling temperature for the response
+
+ Returns:
+ str: The generated response
+
+ Raises:
+ TokenLimitExceeded: If token limits are exceeded
+ ValueError: If messages are invalid or response is empty
+ OpenAIError: If API call fails after retries
+ Exception: For unexpected errors
+ """
try:
# For ask_with_images, we always set supports_images to True because
# this method should only be called with models that support images
@@ -573,6 +651,27 @@ temperature: Optional[float] = None,
**kwargs,
) -> ChatCompletionMessage | None:
+ """
+ Ask LLM using functions/tools and return the response.
+
+ Args:
+ messages: List of conversation messages
+ system_msgs: Optional system messages to prepend
+ timeout: Request timeout in seconds
+ tools: List of tools to use
+ tool_choice: Tool choice strategy
+ temperature: Sampling temperature for the response
+ **kwargs: Additional completion arguments
+
+ Returns:
+ ChatCompletionMessage: The model's response
+
+ Raises:
+ TokenLimitExceeded: If token limits are exceeded
+ ValueError: If tools, tool_choice, or messages are invalid
+ OpenAIError: If API call fails after retries
+ Exception: For unexpected errors
+ """
try:
# Validate tool_choice
if tool_choice not in TOOL_CHOICE_VALUES:
@@ -664,4 +763,4 @@ raise
except Exception as e:
logger.error(f"Unexpected error in ask_tool: {e}")
- raise+ raise
| 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 import PlanningTool
class PlanStepStatus(str, Enum):
NOT_STARTED = "not_started"
IN_PROGRESS = "in_progress"
COMPLETED = "completed"
BLOCKED = "blocked"
@classmethod
def get_all_statuses(cls) -> list[str]:
return [status.value for status in cls]
@classmethod
def get_active_statuses(cls) -> list[str]:
return [cls.NOT_STARTED.value, cls.IN_PROGRESS.value]
@classmethod
def get_status_marks(cls) -> Dict[str, str]:
return {
cls.COMPLETED.value: "[✓]",
cls.IN_PROGRESS.value: "[→]",
cls.BLOCKED.value: "[!]",
cls.NOT_STARTED.value: "[ ]",
}
class PlanningFlow(BaseFlow):
llm: LLM = Field(default_factory=lambda: LLM())
planning_tool: PlanningTool = Field(default_factory=PlanningTool)
executor_keys: List[str] = Field(default_factory=list)
active_plan_id: str = Field(default_factory=lambda: f"plan_{int(time.time())}")
current_step_index: Optional[int] = None
def __init__(
self, agents: Union[BaseAgent, List[BaseAgent], Dict[str, BaseAgent]], **data
):
# Set executor keys before super().__init__
if "executors" in data:
data["executor_keys"] = data.pop("executors")
# Set plan ID if provided
if "plan_id" in data:
data["active_plan_id"] = data.pop("plan_id")
# Initialize the planning tool if not provided
if "planning_tool" not in data:
planning_tool = PlanningTool()
data["planning_tool"] = planning_tool
# Call parent's init with the processed data
super().__init__(agents, **data)
# Set executor_keys to all agent keys if not specified
if not self.executor_keys:
self.executor_keys = list(self.agents.keys())
def get_executor(self, step_type: Optional[str] = None) -> BaseAgent:
# If step type is provided and matches an agent key, use that agent
if step_type and step_type in self.agents:
return self.agents[step_type]
# Otherwise use the first available executor or fall back to primary agent
for key in self.executor_keys:
if key in self.agents:
return self.agents[key]
# Fallback to primary agent
return self.primary_agent
async def execute(self, input_text: str) -> str:
try:
if not self.primary_agent:
raise ValueError("No primary agent available")
# Create initial plan if input provided
if input_text:
await self._create_initial_plan(input_text)
# Verify plan was created successfully
if self.active_plan_id not in self.planning_tool.plans:
logger.error(
f"Plan creation failed. Plan ID {self.active_plan_id} not found in planning tool."
)
return f"Failed to create plan for: {input_text}"
result = ""
while True:
# Get current step to execute
self.current_step_index, step_info = await self._get_current_step_info()
# Exit if no more steps or plan completed
if self.current_step_index is None:
result += await self._finalize_plan()
break
# Execute current step with appropriate agent
step_type = step_info.get("type") if step_info else None
executor = self.get_executor(step_type)
step_result = await self._execute_step(executor, step_info)
result += step_result + "\n"
# Check if agent wants to terminate
if hasattr(executor, "state") and executor.state == AgentState.FINISHED:
break
return result
except Exception as e:
logger.error(f"Error in PlanningFlow: {str(e)}")
return f"Execution failed: {str(e)}"
async def _create_initial_plan(self, request: str) -> None:
logger.info(f"Creating initial plan with ID: {self.active_plan_id}")
system_message_content = (
"You are a planning assistant. Create a concise, actionable plan with clear steps. "
"Focus on key milestones rather than detailed sub-steps. "
"Optimize for clarity and efficiency."
)
agents_description = []
for key in self.executor_keys:
if key in self.agents:
agents_description.append(
{
"name": key.upper(),
"description": self.agents[key].description,
}
)
if len(agents_description) > 1:
# Add description of agents to select
system_message_content += (
f"\nNow we have {agents_description} agents. "
f"The infomation of them are below: {json.dumps(agents_description)}\n"
"When creating steps in the planning tool, please specify the agent names using the format '[agent_name]'."
)
# Create a system message for plan creation
system_message = Message.system_message(system_message_content)
# Create a user message with the request
user_message = Message.user_message(
f"Create a reasonable plan with clear steps to accomplish the task: {request}"
)
# Call LLM with PlanningTool
response = await self.llm.ask_tool(
messages=[user_message],
system_msgs=[system_message],
tools=[self.planning_tool.to_param()],
tool_choice=ToolChoice.AUTO,
)
# Process tool calls if present
if response.tool_calls:
for tool_call in response.tool_calls:
if tool_call.function.name == "planning":
# Parse the arguments
args = tool_call.function.arguments
if isinstance(args, str):
try:
args = json.loads(args)
except json.JSONDecodeError:
logger.error(f"Failed to parse tool arguments: {args}")
continue
# Ensure plan_id is set correctly and execute the tool
args["plan_id"] = self.active_plan_id
# Execute the tool via ToolCollection instead of directly
result = await self.planning_tool.execute(**args)
logger.info(f"Plan creation result: {str(result)}")
return
# If execution reached here, create a default plan
logger.warning("Creating default plan")
# Create default plan using the ToolCollection
await self.planning_tool.execute(
**{
"command": "create",
"plan_id": self.active_plan_id,
"title": f"Plan for: {request[:50]}{'...' if len(request) > 50 else ''}",
"steps": ["Analyze request", "Execute task", "Verify results"],
}
)
async def _get_current_step_info(self) -> tuple[Optional[int], Optional[dict]]:
if (
not self.active_plan_id
or self.active_plan_id not in self.planning_tool.plans
):
logger.error(f"Plan with ID {self.active_plan_id} not found")
return None, None
try:
# Direct access to plan data from planning tool storage
plan_data = self.planning_tool.plans[self.active_plan_id]
steps = plan_data.get("steps", [])
step_statuses = plan_data.get("step_statuses", [])
# Find first non-completed step
for i, step in enumerate(steps):
if i >= len(step_statuses):
status = PlanStepStatus.NOT_STARTED.value
else:
status = step_statuses[i]
if status in PlanStepStatus.get_active_statuses():
# Extract step type/category if available
step_info = {"text": step}
# Try to extract step type from the text (e.g., [SEARCH] or [CODE])
import re
type_match = re.search(r"\[([A-Z_]+)\]", step)
if type_match:
step_info["type"] = type_match.group(1).lower()
# Mark current step as in_progress
try:
await self.planning_tool.execute(
command="mark_step",
plan_id=self.active_plan_id,
step_index=i,
step_status=PlanStepStatus.IN_PROGRESS.value,
)
except Exception as e:
logger.warning(f"Error marking step as in_progress: {e}")
# Update step status directly if needed
if i < len(step_statuses):
step_statuses[i] = PlanStepStatus.IN_PROGRESS.value
else:
while len(step_statuses) < i:
step_statuses.append(PlanStepStatus.NOT_STARTED.value)
step_statuses.append(PlanStepStatus.IN_PROGRESS.value)
plan_data["step_statuses"] = step_statuses
return i, step_info
return None, None # No active step found
except Exception as e:
logger.warning(f"Error finding current step index: {e}")
return None, None
async def _execute_step(self, executor: BaseAgent, step_info: dict) -> str:
# Prepare context for the agent with current plan status
plan_status = await self._get_plan_text()
step_text = step_info.get("text", f"Step {self.current_step_index}")
# Create a prompt for the agent to execute the current step
step_prompt = f"""
CURRENT PLAN STATUS:
{plan_status}
YOUR CURRENT TASK:
You are now working on step {self.current_step_index}: "{step_text}"
Please only execute this current step using the appropriate tools. When you're done, provide a summary of what you accomplished.
"""
# Use agent.run() to execute the step
try:
step_result = await executor.run(step_prompt)
# Mark the step as completed after successful execution
await self._mark_step_completed()
return step_result
except Exception as e:
logger.error(f"Error executing step {self.current_step_index}: {e}")
return f"Error executing step {self.current_step_index}: {str(e)}"
async def _mark_step_completed(self) -> None:
if self.current_step_index is None:
return
try:
# Mark the step as completed
await self.planning_tool.execute(
command="mark_step",
plan_id=self.active_plan_id,
step_index=self.current_step_index,
step_status=PlanStepStatus.COMPLETED.value,
)
logger.info(
f"Marked step {self.current_step_index} as completed in plan {self.active_plan_id}"
)
except Exception as e:
logger.warning(f"Failed to update plan status: {e}")
# Update step status directly in planning tool storage
if self.active_plan_id in self.planning_tool.plans:
plan_data = self.planning_tool.plans[self.active_plan_id]
step_statuses = plan_data.get("step_statuses", [])
# Ensure the step_statuses list is long enough
while len(step_statuses) <= self.current_step_index:
step_statuses.append(PlanStepStatus.NOT_STARTED.value)
# Update the status
step_statuses[self.current_step_index] = PlanStepStatus.COMPLETED.value
plan_data["step_statuses"] = step_statuses
async def _get_plan_text(self) -> str:
try:
result = await self.planning_tool.execute(
command="get", plan_id=self.active_plan_id
)
return result.output if hasattr(result, "output") else str(result)
except Exception as e:
logger.error(f"Error getting plan: {e}")
return self._generate_plan_text_from_storage()
def _generate_plan_text_from_storage(self) -> str:
try:
if self.active_plan_id not in self.planning_tool.plans:
return f"Error: Plan with ID {self.active_plan_id} not found"
plan_data = self.planning_tool.plans[self.active_plan_id]
title = plan_data.get("title", "Untitled Plan")
steps = plan_data.get("steps", [])
step_statuses = plan_data.get("step_statuses", [])
step_notes = plan_data.get("step_notes", [])
# Ensure step_statuses and step_notes match the number of steps
while len(step_statuses) < len(steps):
step_statuses.append(PlanStepStatus.NOT_STARTED.value)
while len(step_notes) < len(steps):
step_notes.append("")
# Count steps by status
status_counts = {status: 0 for status in PlanStepStatus.get_all_statuses()}
for status in step_statuses:
if status in status_counts:
status_counts[status] += 1
completed = status_counts[PlanStepStatus.COMPLETED.value]
total = len(steps)
progress = (completed / total) * 100 if total > 0 else 0
plan_text = f"Plan: {title} (ID: {self.active_plan_id})\n"
plan_text += "=" * len(plan_text) + "\n\n"
plan_text += (
f"Progress: {completed}/{total} steps completed ({progress:.1f}%)\n"
)
plan_text += f"Status: {status_counts[PlanStepStatus.COMPLETED.value]} completed, {status_counts[PlanStepStatus.IN_PROGRESS.value]} in progress, "
plan_text += f"{status_counts[PlanStepStatus.BLOCKED.value]} blocked, {status_counts[PlanStepStatus.NOT_STARTED.value]} not started\n\n"
plan_text += "Steps:\n"
status_marks = PlanStepStatus.get_status_marks()
for i, (step, status, notes) in enumerate(
zip(steps, step_statuses, step_notes)
):
# Use status marks to indicate step status
status_mark = status_marks.get(
status, status_marks[PlanStepStatus.NOT_STARTED.value]
)
plan_text += f"{i}. {status_mark} {step}\n"
if notes:
plan_text += f" Notes: {notes}\n"
return plan_text
except Exception as e:
logger.error(f"Error generating plan text from storage: {e}")
return f"Error: Unable to retrieve plan with ID {self.active_plan_id}"
async def _finalize_plan(self) -> str:
plan_text = await self._get_plan_text()
# Create a summary using the flow's LLM directly
try:
system_message = Message.system_message(
"You are a planning assistant. Your task is to summarize the completed plan."
)
user_message = Message.user_message(
f"The plan has been completed. Here is the final plan status:\n\n{plan_text}\n\nPlease provide a summary of what was accomplished and any final thoughts."
)
response = await self.llm.ask(
messages=[user_message], system_msgs=[system_message]
)
return f"Plan completed:\n\n{response}"
except Exception as e:
logger.error(f"Error finalizing plan with LLM: {e}")
# Fallback to using an agent for the summary
try:
agent = self.primary_agent
summary_prompt = f"""
The plan has been completed. Here is the final plan status:
{plan_text}
Please provide a summary of what was accomplished and any final thoughts.
"""
summary = await agent.run(summary_prompt)
return f"Plan completed:\n\n{summary}"
except Exception as e2:
logger.error(f"Error finalizing plan with agent: {e2}")
return "Plan completed. Error generating summary." | --- +++ @@ -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 step status values"""
return [status.value for status in cls]
@classmethod
def get_active_statuses(cls) -> list[str]:
+ """Return a list of values representing active statuses (not started or in progress)"""
return [cls.NOT_STARTED.value, cls.IN_PROGRESS.value]
@classmethod
def get_status_marks(cls) -> Dict[str, str]:
+ """Return a mapping of statuses to their marker symbols"""
return {
cls.COMPLETED.value: "[✓]",
cls.IN_PROGRESS.value: "[→]",
@@ -39,6 +43,7 @@
class PlanningFlow(BaseFlow):
+ """A flow that manages planning and execution of tasks using agents."""
llm: LLM = Field(default_factory=lambda: LLM())
planning_tool: PlanningTool = Field(default_factory=PlanningTool)
@@ -70,6 +75,10 @@ self.executor_keys = list(self.agents.keys())
def get_executor(self, step_type: Optional[str] = None) -> BaseAgent:
+ """
+ Get an appropriate executor agent for the current step.
+ Can be extended to select agents based on step type/requirements.
+ """
# If step type is provided and matches an agent key, use that agent
if step_type and step_type in self.agents:
return self.agents[step_type]
@@ -83,6 +92,7 @@ return self.primary_agent
async def execute(self, input_text: str) -> str:
+ """Execute the planning flow with agents."""
try:
if not self.primary_agent:
raise ValueError("No primary agent available")
@@ -124,6 +134,7 @@ return f"Execution failed: {str(e)}"
async def _create_initial_plan(self, request: str) -> None:
+ """Create an initial plan based on the request using the flow's LLM and PlanningTool."""
logger.info(f"Creating initial plan with ID: {self.active_plan_id}")
system_message_content = (
@@ -200,6 +211,10 @@ )
async def _get_current_step_info(self) -> tuple[Optional[int], Optional[dict]]:
+ """
+ Parse the current plan to identify the first non-completed step's index and info.
+ Returns (None, None) if no active step is found.
+ """
if (
not self.active_plan_id
or self.active_plan_id not in self.planning_tool.plans
@@ -260,6 +275,7 @@ return None, None
async def _execute_step(self, executor: BaseAgent, step_info: dict) -> str:
+ """Execute the current step with the specified agent using agent.run()."""
# Prepare context for the agent with current plan status
plan_status = await self._get_plan_text()
step_text = step_info.get("text", f"Step {self.current_step_index}")
@@ -288,6 +304,7 @@ return f"Error executing step {self.current_step_index}: {str(e)}"
async def _mark_step_completed(self) -> None:
+ """Mark the current step as completed."""
if self.current_step_index is None:
return
@@ -318,6 +335,7 @@ plan_data["step_statuses"] = step_statuses
async def _get_plan_text(self) -> str:
+ """Get the current plan as formatted text."""
try:
result = await self.planning_tool.execute(
command="get", plan_id=self.active_plan_id
@@ -328,6 +346,7 @@ return self._generate_plan_text_from_storage()
def _generate_plan_text_from_storage(self) -> str:
+ """Generate plan text directly from storage if the planning tool fails."""
try:
if self.active_plan_id not in self.planning_tool.plans:
return f"Error: Plan with ID {self.active_plan_id} not found"
@@ -385,6 +404,7 @@ return f"Error: Unable to retrieve plan with ID {self.active_plan_id}"
async def _finalize_plan(self) -> str:
+ """Finalize the plan and provide a summary using the flow's LLM directly."""
plan_text = await self._get_plan_text()
# Create a summary using the flow's LLM directly
@@ -419,4 +439,4 @@ return f"Plan completed:\n\n{summary}"
except Exception as e2:
logger.error(f"Error finalizing plan with agent: {e2}")
- return "Plan completed. Error generating summary."+ return "Plan completed. Error generating summary."
| 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.
Features:
- Extracts clean markdown content optimized for LLMs
- Handles JavaScript-heavy sites and dynamic content
- Supports multiple URLs in a single request
- Fast and reliable with built-in error handling
Perfect for content analysis, research, and feeding web content to AI models."""
parameters: dict = {
"type": "object",
"properties": {
"urls": {
"type": "array",
"items": {"type": "string"},
"description": "(required) List of URLs to crawl. Can be a single URL or multiple URLs.",
"minItems": 1,
},
"timeout": {
"type": "integer",
"description": "(optional) Timeout in seconds for each URL. Default is 30.",
"default": 30,
"minimum": 5,
"maximum": 120,
},
"bypass_cache": {
"type": "boolean",
"description": "(optional) Whether to bypass cache and fetch fresh content. Default is false.",
"default": False,
},
"word_count_threshold": {
"type": "integer",
"description": "(optional) Minimum word count for content blocks. Default is 10.",
"default": 10,
"minimum": 1,
},
},
"required": ["urls"],
}
async def execute(
self,
urls: Union[str, List[str]],
timeout: int = 30,
bypass_cache: bool = False,
word_count_threshold: int = 10,
) -> ToolResult:
# Normalize URLs to list
if isinstance(urls, str):
url_list = [urls]
else:
url_list = urls
# Validate URLs
valid_urls = []
for url in url_list:
if self._is_valid_url(url):
valid_urls.append(url)
else:
logger.warning(f"Invalid URL skipped: {url}")
if not valid_urls:
return ToolResult(error="No valid URLs provided")
try:
# Import crawl4ai components
from crawl4ai import (
AsyncWebCrawler,
BrowserConfig,
CacheMode,
CrawlerRunConfig,
)
# Configure browser settings
browser_config = BrowserConfig(
headless=True,
verbose=False,
browser_type="chromium",
ignore_https_errors=True,
java_script_enabled=True,
)
# Configure crawler settings
run_config = CrawlerRunConfig(
cache_mode=CacheMode.BYPASS if bypass_cache else CacheMode.ENABLED,
word_count_threshold=word_count_threshold,
process_iframes=True,
remove_overlay_elements=True,
excluded_tags=["script", "style"],
page_timeout=timeout * 1000, # Convert to milliseconds
verbose=False,
wait_until="domcontentloaded",
)
results = []
successful_count = 0
failed_count = 0
# Process each URL
async with AsyncWebCrawler(config=browser_config) as crawler:
for url in valid_urls:
try:
logger.info(f"🕷️ Crawling URL: {url}")
start_time = asyncio.get_event_loop().time()
result = await crawler.arun(url=url, config=run_config)
end_time = asyncio.get_event_loop().time()
execution_time = end_time - start_time
if result.success:
# Count words in markdown
word_count = 0
if hasattr(result, "markdown") and result.markdown:
word_count = len(result.markdown.split())
# Count links
links_count = 0
if hasattr(result, "links") and result.links:
internal_links = result.links.get("internal", [])
external_links = result.links.get("external", [])
links_count = len(internal_links) + len(external_links)
# Count images
images_count = 0
if hasattr(result, "media") and result.media:
images = result.media.get("images", [])
images_count = len(images)
results.append(
{
"url": url,
"success": True,
"status_code": getattr(result, "status_code", 200),
"title": result.metadata.get("title")
if result.metadata
else None,
"markdown": result.markdown
if hasattr(result, "markdown")
else None,
"word_count": word_count,
"links_count": links_count,
"images_count": images_count,
"execution_time": execution_time,
}
)
successful_count += 1
logger.info(
f"✅ Successfully crawled {url} in {execution_time:.2f}s"
)
else:
results.append(
{
"url": url,
"success": False,
"error_message": getattr(
result, "error_message", "Unknown error"
),
"execution_time": execution_time,
}
)
failed_count += 1
logger.warning(f"❌ Failed to crawl {url}")
except Exception as e:
error_msg = f"Error crawling {url}: {str(e)}"
logger.error(error_msg)
results.append(
{"url": url, "success": False, "error_message": error_msg}
)
failed_count += 1
# Format output
output_lines = [f"🕷️ Crawl4AI Results Summary:"]
output_lines.append(f"📊 Total URLs: {len(valid_urls)}")
output_lines.append(f"✅ Successful: {successful_count}")
output_lines.append(f"❌ Failed: {failed_count}")
output_lines.append("")
for i, result in enumerate(results, 1):
output_lines.append(f"{i}. {result['url']}")
if result["success"]:
output_lines.append(
f" ✅ Status: Success (HTTP {result.get('status_code', 'N/A')})"
)
if result.get("title"):
output_lines.append(f" 📄 Title: {result['title']}")
if result.get("markdown"):
# Show first 300 characters of markdown content
content_preview = result["markdown"]
if len(result["markdown"]) > 300:
content_preview += "..."
output_lines.append(f" 📝 Content: {content_preview}")
output_lines.append(
f" 📊 Stats: {result.get('word_count', 0)} words, {result.get('links_count', 0)} links, {result.get('images_count', 0)} images"
)
if result.get("execution_time"):
output_lines.append(
f" ⏱️ Time: {result['execution_time']:.2f}s"
)
else:
output_lines.append(f" ❌ Status: Failed")
if result.get("error_message"):
output_lines.append(f" 🚫 Error: {result['error_message']}")
output_lines.append("")
return ToolResult(output="\n".join(output_lines))
except ImportError:
error_msg = "Crawl4AI is not installed. Please install it with: pip install crawl4ai"
logger.error(error_msg)
return ToolResult(error=error_msg)
except Exception as e:
error_msg = f"Crawl4AI execution failed: {str(e)}"
logger.error(error_msg)
return ToolResult(error=error_msg)
def _is_valid_url(self, url: str) -> bool:
try:
result = urlparse(url)
return all([result.scheme, result.netloc]) and result.scheme in [
"http",
"https",
]
except Exception:
return False | --- +++ @@ -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,11 @@
class Crawl4aiTool(BaseTool):
+ """
+ Web crawler tool powered by Crawl4AI.
+
+ Provides clean markdown extraction optimized for AI processing.
+ """
name: str = "crawl4ai"
description: str = """Web crawler that extracts clean, AI-ready content from web pages.
@@ -58,6 +69,18 @@ bypass_cache: bool = False,
word_count_threshold: int = 10,
) -> ToolResult:
+ """
+ Execute web crawling for the specified URLs.
+
+ Args:
+ urls: Single URL string or list of URLs to crawl
+ timeout: Timeout in seconds for each URL
+ bypass_cache: Whether to bypass cache
+ word_count_threshold: Minimum word count for content blocks
+
+ Returns:
+ ToolResult with crawl results
+ """
# Normalize URLs to list
if isinstance(urls, str):
url_list = [urls]
@@ -235,6 +258,7 @@ return ToolResult(error=error_msg)
def _is_valid_url(self, url: str) -> bool:
+ """Validate if a URL is properly formatted."""
try:
result = urlparse(url)
return all([result.scheme, result.netloc]) and result.scheme in [
@@ -242,4 +266,4 @@ "https",
]
except Exception:
- return False+ return False
| 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):
async def read_file(self, path: PathLike) -> str:
...
async def write_file(self, path: PathLike, content: str) -> None:
...
async def is_directory(self, path: PathLike) -> bool:
...
async def exists(self, path: PathLike) -> bool:
...
async def run_command(
self, cmd: str, timeout: Optional[float] = 120.0
) -> Tuple[int, str, str]:
...
class LocalFileOperator(FileOperator):
encoding: str = "utf-8"
async def read_file(self, path: PathLike) -> str:
try:
return Path(path).read_text(encoding=self.encoding)
except Exception as e:
raise ToolError(f"Failed to read {path}: {str(e)}") from None
async def write_file(self, path: PathLike, content: str) -> None:
try:
Path(path).write_text(content, encoding=self.encoding)
except Exception as e:
raise ToolError(f"Failed to write to {path}: {str(e)}") from None
async def is_directory(self, path: PathLike) -> bool:
return Path(path).is_dir()
async def exists(self, path: PathLike) -> bool:
return Path(path).exists()
async def run_command(
self, cmd: str, timeout: Optional[float] = 120.0
) -> Tuple[int, str, str]:
process = await asyncio.create_subprocess_shell(
cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
try:
stdout, stderr = await asyncio.wait_for(
process.communicate(), timeout=timeout
)
return (
process.returncode or 0,
stdout.decode(),
stderr.decode(),
)
except asyncio.TimeoutError as exc:
try:
process.kill()
except ProcessLookupError:
pass
raise TimeoutError(
f"Command '{cmd}' timed out after {timeout} seconds"
) from exc
class SandboxFileOperator(FileOperator):
def __init__(self):
self.sandbox_client = SANDBOX_CLIENT
async def _ensure_sandbox_initialized(self):
if not self.sandbox_client.sandbox:
await self.sandbox_client.create(config=SandboxSettings())
async def read_file(self, path: PathLike) -> str:
await self._ensure_sandbox_initialized()
try:
return await self.sandbox_client.read_file(str(path))
except Exception as e:
raise ToolError(f"Failed to read {path} in sandbox: {str(e)}") from None
async def write_file(self, path: PathLike, content: str) -> None:
await self._ensure_sandbox_initialized()
try:
await self.sandbox_client.write_file(str(path), content)
except Exception as e:
raise ToolError(f"Failed to write to {path} in sandbox: {str(e)}") from None
async def is_directory(self, path: PathLike) -> bool:
await self._ensure_sandbox_initialized()
result = await self.sandbox_client.run_command(
f"test -d {path} && echo 'true' || echo 'false'"
)
return result.strip() == "true"
async def exists(self, path: PathLike) -> bool:
await self._ensure_sandbox_initialized()
result = await self.sandbox_client.run_command(
f"test -e {path} && echo 'true' || echo 'false'"
)
return result.strip() == "true"
async def run_command(
self, cmd: str, timeout: Optional[float] = 120.0
) -> Tuple[int, str, str]:
await self._ensure_sandbox_initialized()
try:
stdout = await self.sandbox_client.run_command(
cmd, timeout=int(timeout) if timeout else None
)
return (
0, # Always return 0 since we don't have explicit return code from sandbox
stdout,
"", # No stderr capture in the current sandbox implementation
)
except TimeoutError as exc:
raise TimeoutError(
f"Command '{cmd}' timed out after {timeout} seconds in sandbox"
) from exc
except Exception as exc:
return 1, "", f"Error executing command in sandbox: {str(exc)}" | --- +++ @@ -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_file(self, path: PathLike) -> str:
+ """Read content from a file."""
...
async def write_file(self, path: PathLike, content: str) -> None:
+ """Write content to a file."""
...
async def is_directory(self, path: PathLike) -> bool:
+ """Check if path points to a directory."""
...
async def exists(self, path: PathLike) -> bool:
+ """Check if path exists."""
...
async def run_command(
self, cmd: str, timeout: Optional[float] = 120.0
) -> Tuple[int, str, str]:
+ """Run a shell command and return (return_code, stdout, stderr)."""
...
class LocalFileOperator(FileOperator):
+ """File operations implementation for local filesystem."""
encoding: str = "utf-8"
async def read_file(self, path: PathLike) -> str:
+ """Read content from a local file."""
try:
return Path(path).read_text(encoding=self.encoding)
except Exception as e:
raise ToolError(f"Failed to read {path}: {str(e)}") from None
async def write_file(self, path: PathLike, content: str) -> None:
+ """Write content to a local file."""
try:
Path(path).write_text(content, encoding=self.encoding)
except Exception as e:
raise ToolError(f"Failed to write to {path}: {str(e)}") from None
async def is_directory(self, path: PathLike) -> bool:
+ """Check if path points to a directory."""
return Path(path).is_dir()
async def exists(self, path: PathLike) -> bool:
+ """Check if path exists."""
return Path(path).exists()
async def run_command(
self, cmd: str, timeout: Optional[float] = 120.0
) -> Tuple[int, str, str]:
+ """Run a shell command locally."""
process = await asyncio.create_subprocess_shell(
cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
@@ -81,15 +94,18 @@
class SandboxFileOperator(FileOperator):
+ """File operations implementation for sandbox environment."""
def __init__(self):
self.sandbox_client = SANDBOX_CLIENT
async def _ensure_sandbox_initialized(self):
+ """Ensure sandbox is initialized."""
if not self.sandbox_client.sandbox:
await self.sandbox_client.create(config=SandboxSettings())
async def read_file(self, path: PathLike) -> str:
+ """Read content from a file in sandbox."""
await self._ensure_sandbox_initialized()
try:
return await self.sandbox_client.read_file(str(path))
@@ -97,6 +113,7 @@ raise ToolError(f"Failed to read {path} in sandbox: {str(e)}") from None
async def write_file(self, path: PathLike, content: str) -> None:
+ """Write content to a file in sandbox."""
await self._ensure_sandbox_initialized()
try:
await self.sandbox_client.write_file(str(path), content)
@@ -104,6 +121,7 @@ raise ToolError(f"Failed to write to {path} in sandbox: {str(e)}") from None
async def is_directory(self, path: PathLike) -> bool:
+ """Check if path points to a directory in sandbox."""
await self._ensure_sandbox_initialized()
result = await self.sandbox_client.run_command(
f"test -d {path} && echo 'true' || echo 'false'"
@@ -111,6 +129,7 @@ return result.strip() == "true"
async def exists(self, path: PathLike) -> bool:
+ """Check if path exists in sandbox."""
await self._ensure_sandbox_initialized()
result = await self.sandbox_client.run_command(
f"test -e {path} && echo 'true' || echo 'false'"
@@ -120,6 +139,7 @@ async def run_command(
self, cmd: str, timeout: Optional[float] = 120.0
) -> Tuple[int, str, str]:
+ """Run a command in sandbox environment."""
await self._ensure_sandbox_initialized()
try:
stdout = await self.sandbox_client.run_command(
@@ -135,4 +155,4 @@ f"Command '{cmd}' timed out after {timeout} seconds in sandbox"
) from exc
except Exception as exc:
- return 1, "", f"Error executing command in sandbox: {str(exc)}"+ return 1, "", f"Error executing command in sandbox: {str(exc)}"
| 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",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"enter",
"esc",
"backspace",
"tab",
"space",
"delete",
"ctrl",
"alt",
"shift",
"win",
"up",
"down",
"left",
"right",
"f1",
"f2",
"f3",
"f4",
"f5",
"f6",
"f7",
"f8",
"f9",
"f10",
"f11",
"f12",
"ctrl+c",
"ctrl+v",
"ctrl+x",
"ctrl+z",
"ctrl+a",
"ctrl+s",
"alt+tab",
"alt+f4",
"ctrl+alt+delete",
]
MOUSE_BUTTONS = ["left", "right", "middle"]
_COMPUTER_USE_DESCRIPTION = """\
A comprehensive computer automation tool that allows interaction with the desktop environment.
* This tool provides commands for controlling mouse, keyboard, and taking screenshots
* It maintains state including current mouse position
* Use this when you need to automate desktop applications, fill forms, or perform GUI interactions
Key capabilities include:
* Mouse Control: Move, click, drag, scroll
* Keyboard Input: Type text, press keys or key combinations
* Screenshots: Capture and save screen images
* Waiting: Pause execution for specified duration
"""
class ComputerUseTool(SandboxToolsBase):
name: str = "computer_use"
description: str = _COMPUTER_USE_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": [
"move_to",
"click",
"scroll",
"typing",
"press",
"wait",
"mouse_down",
"mouse_up",
"drag_to",
"hotkey",
"screenshot",
],
"description": "The computer action to perform",
},
"x": {"type": "number", "description": "X coordinate for mouse actions"},
"y": {"type": "number", "description": "Y coordinate for mouse actions"},
"button": {
"type": "string",
"enum": MOUSE_BUTTONS,
"description": "Mouse button for click/drag actions",
"default": "left",
},
"num_clicks": {
"type": "integer",
"description": "Number of clicks",
"enum": [1, 2, 3],
"default": 1,
},
"amount": {
"type": "integer",
"description": "Scroll amount (positive for up, negative for down)",
"minimum": -10,
"maximum": 10,
},
"text": {"type": "string", "description": "Text to type"},
"key": {
"type": "string",
"enum": KEYBOARD_KEYS,
"description": "Key to press",
},
"keys": {
"type": "string",
"enum": KEYBOARD_KEYS,
"description": "Key combination to press",
},
"duration": {
"type": "number",
"description": "Duration in seconds to wait",
"default": 0.5,
},
},
"required": ["action"],
"dependencies": {
"move_to": ["x", "y"],
"click": [],
"scroll": ["amount"],
"typing": ["text"],
"press": ["key"],
"wait": [],
"mouse_down": [],
"mouse_up": [],
"drag_to": ["x", "y"],
"hotkey": ["keys"],
"screenshot": [],
},
}
session: Optional[aiohttp.ClientSession] = Field(default=None, exclude=True)
mouse_x: int = Field(default=0, exclude=True)
mouse_y: int = Field(default=0, exclude=True)
api_base_url: Optional[str] = Field(default=None, exclude=True)
def __init__(self, sandbox: Optional[Sandbox] = None, **data):
super().__init__(**data)
if sandbox is not None:
self._sandbox = sandbox # 直接操作基类的私有属性
self.api_base_url = sandbox.get_preview_link(8000).url
logging.info(
f"Initialized ComputerUseTool with API URL: {self.api_base_url}"
)
@classmethod
def create_with_sandbox(cls, sandbox: Sandbox) -> "ComputerUseTool":
return cls(sandbox=sandbox) # 通过构造函数初始化
async def _get_session(self) -> aiohttp.ClientSession:
if self.session is None or self.session.closed:
self.session = aiohttp.ClientSession()
return self.session
async def _api_request(
self, method: str, endpoint: str, data: Optional[Dict] = None
) -> Dict:
try:
session = await self._get_session()
url = f"{self.api_base_url}/api{endpoint}"
logging.debug(f"API request: {method} {url} {data}")
if method.upper() == "GET":
async with session.get(url) as response:
result = await response.json()
else: # POST
async with session.post(url, json=data) as response:
result = await response.json()
logging.debug(f"API response: {result}")
return result
except Exception as e:
logging.error(f"API request failed: {str(e)}")
return {"success": False, "error": str(e)}
async def execute(
self,
action: Literal[
"move_to",
"click",
"scroll",
"typing",
"press",
"wait",
"mouse_down",
"mouse_up",
"drag_to",
"hotkey",
"screenshot",
],
x: Optional[float] = None,
y: Optional[float] = None,
button: str = "left",
num_clicks: int = 1,
amount: Optional[int] = None,
text: Optional[str] = None,
key: Optional[str] = None,
keys: Optional[str] = None,
duration: float = 0.5,
**kwargs,
) -> ToolResult:
try:
if action == "move_to":
if x is None or y is None:
return ToolResult(error="x and y coordinates are required")
x_int = int(round(float(x)))
y_int = int(round(float(y)))
result = await self._api_request(
"POST", "/automation/mouse/move", {"x": x_int, "y": y_int}
)
if result.get("success", False):
self.mouse_x = x_int
self.mouse_y = y_int
return ToolResult(output=f"Moved to ({x_int}, {y_int})")
else:
return ToolResult(
error=f"Failed to move: {result.get('error', 'Unknown error')}"
)
elif action == "click":
x_val = x if x is not None else self.mouse_x
y_val = y if y is not None else self.mouse_y
x_int = int(round(float(x_val)))
y_int = int(round(float(y_val)))
num_clicks = int(num_clicks)
result = await self._api_request(
"POST",
"/automation/mouse/click",
{
"x": x_int,
"y": y_int,
"clicks": num_clicks,
"button": button.lower(),
},
)
if result.get("success", False):
self.mouse_x = x_int
self.mouse_y = y_int
return ToolResult(
output=f"{num_clicks} {button} click(s) performed at ({x_int}, {y_int})"
)
else:
return ToolResult(
error=f"Failed to click: {result.get('error', 'Unknown error')}"
)
elif action == "scroll":
if amount is None:
return ToolResult(error="Scroll amount is required")
amount = int(float(amount))
amount = max(-10, min(10, amount))
result = await self._api_request(
"POST",
"/automation/mouse/scroll",
{"clicks": amount, "x": self.mouse_x, "y": self.mouse_y},
)
if result.get("success", False):
direction = "up" if amount > 0 else "down"
steps = abs(amount)
return ToolResult(
output=f"Scrolled {direction} {steps} step(s) at position ({self.mouse_x}, {self.mouse_y})"
)
else:
return ToolResult(
error=f"Failed to scroll: {result.get('error', 'Unknown error')}"
)
elif action == "typing":
if text is None:
return ToolResult(error="Text is required for typing")
text = str(text)
result = await self._api_request(
"POST",
"/automation/keyboard/write",
{"message": text, "interval": 0.01},
)
if result.get("success", False):
return ToolResult(output=f"Typed: {text}")
else:
return ToolResult(
error=f"Failed to type: {result.get('error', 'Unknown error')}"
)
elif action == "press":
if key is None:
return ToolResult(error="Key is required for press action")
key = str(key).lower()
result = await self._api_request(
"POST", "/automation/keyboard/press", {"keys": key, "presses": 1}
)
if result.get("success", False):
return ToolResult(output=f"Pressed key: {key}")
else:
return ToolResult(
error=f"Failed to press key: {result.get('error', 'Unknown error')}"
)
elif action == "wait":
duration = float(duration)
duration = max(0, min(10, duration))
await asyncio.sleep(duration)
return ToolResult(output=f"Waited {duration} seconds")
elif action == "mouse_down":
x_val = x if x is not None else self.mouse_x
y_val = y if y is not None else self.mouse_y
x_int = int(round(float(x_val)))
y_int = int(round(float(y_val)))
result = await self._api_request(
"POST",
"/automation/mouse/down",
{"x": x_int, "y": y_int, "button": button.lower()},
)
if result.get("success", False):
self.mouse_x = x_int
self.mouse_y = y_int
return ToolResult(
output=f"{button} button pressed at ({x_int}, {y_int})"
)
else:
return ToolResult(
error=f"Failed to press button: {result.get('error', 'Unknown error')}"
)
elif action == "mouse_up":
x_val = x if x is not None else self.mouse_x
y_val = y if y is not None else self.mouse_y
x_int = int(round(float(x_val)))
y_int = int(round(float(y_val)))
result = await self._api_request(
"POST",
"/automation/mouse/up",
{"x": x_int, "y": y_int, "button": button.lower()},
)
if result.get("success", False):
self.mouse_x = x_int
self.mouse_y = y_int
return ToolResult(
output=f"{button} button released at ({x_int}, {y_int})"
)
else:
return ToolResult(
error=f"Failed to release button: {result.get('error', 'Unknown error')}"
)
elif action == "drag_to":
if x is None or y is None:
return ToolResult(error="x and y coordinates are required")
target_x = int(round(float(x)))
target_y = int(round(float(y)))
start_x = self.mouse_x
start_y = self.mouse_y
result = await self._api_request(
"POST",
"/automation/mouse/drag",
{"x": target_x, "y": target_y, "duration": 0.3, "button": "left"},
)
if result.get("success", False):
self.mouse_x = target_x
self.mouse_y = target_y
return ToolResult(
output=f"Dragged from ({start_x}, {start_y}) to ({target_x}, {target_y})"
)
else:
return ToolResult(
error=f"Failed to drag: {result.get('error', 'Unknown error')}"
)
elif action == "hotkey":
if keys is None:
return ToolResult(error="Keys are required for hotkey action")
keys = str(keys).lower().strip()
key_sequence = keys.split("+")
result = await self._api_request(
"POST",
"/automation/keyboard/hotkey",
{"keys": key_sequence, "interval": 0.01},
)
if result.get("success", False):
return ToolResult(output=f"Pressed key combination: {keys}")
else:
return ToolResult(
error=f"Failed to press keys: {result.get('error', 'Unknown error')}"
)
elif action == "screenshot":
result = await self._api_request("POST", "/automation/screenshot")
if "image" in result:
base64_str = result["image"]
timestamp = time.strftime("%Y%m%d_%H%M%S")
# Save screenshot to file
screenshots_dir = "screenshots"
if not os.path.exists(screenshots_dir):
os.makedirs(screenshots_dir)
timestamped_filename = os.path.join(
screenshots_dir, f"screenshot_{timestamp}.png"
)
latest_filename = "latest_screenshot.png"
# Decode base64 string and save to file
img_data = base64.b64decode(base64_str)
with open(timestamped_filename, "wb") as f:
f.write(img_data)
# Save a copy as the latest screenshot
with open(latest_filename, "wb") as f:
f.write(img_data)
return ToolResult(
output=f"Screenshot saved as {timestamped_filename}",
base64_image=base64_str,
)
else:
return ToolResult(error="Failed to capture screenshot")
else:
return ToolResult(error=f"Unknown action: {action}")
except Exception as e:
return ToolResult(error=f"Computer action failed: {str(e)}")
async def cleanup(self):
if self.session and not self.session.closed:
await self.session.close()
self.session = None
def __del__(self):
if hasattr(self, "session") and self.session is not None:
try:
asyncio.run(self.cleanup())
except RuntimeError:
loop = asyncio.new_event_loop()
loop.run_until_complete(self.cleanup())
loop.close() | --- +++ @@ -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)
def __init__(self, sandbox: Optional[Sandbox] = None, **data):
+ """Initialize with optional sandbox."""
super().__init__(**data)
if sandbox is not None:
self._sandbox = sandbox # 直接操作基类的私有属性
@@ -191,9 +193,11 @@
@classmethod
def create_with_sandbox(cls, sandbox: Sandbox) -> "ComputerUseTool":
+ """Factory method to create a tool with sandbox."""
return cls(sandbox=sandbox) # 通过构造函数初始化
async def _get_session(self) -> aiohttp.ClientSession:
+ """Get or create aiohttp session for API requests."""
if self.session is None or self.session.closed:
self.session = aiohttp.ClientSession()
return self.session
@@ -201,6 +205,7 @@ async def _api_request(
self, method: str, endpoint: str, data: Optional[Dict] = None
) -> Dict:
+ """Send request to automation service API."""
try:
session = await self._get_session()
url = f"{self.api_base_url}/api{endpoint}"
@@ -243,6 +248,23 @@ duration: float = 0.5,
**kwargs,
) -> ToolResult:
+ """
+ Execute a specified computer automation action.
+ Args:
+ action: The action to perform
+ x: X coordinate for mouse actions
+ y: Y coordinate for mouse actions
+ button: Mouse button for click/drag actions
+ num_clicks: Number of clicks to perform
+ amount: Scroll amount (positive for up, negative for down)
+ text: Text to type
+ key: Key to press
+ keys: Key combination to press
+ duration: Duration in seconds to wait
+ **kwargs: Additional arguments
+ Returns:
+ ToolResult with the action's output or error
+ """
try:
if action == "move_to":
if x is None or y is None:
@@ -449,15 +471,17 @@ return ToolResult(error=f"Computer action failed: {str(e)}")
async def cleanup(self):
+ """Clean up resources."""
if self.session and not self.session.closed:
await self.session.close()
self.session = None
def __del__(self):
+ """Ensure cleanup on destruction."""
if hasattr(self, "session") and self.session is not None:
try:
asyncio.run(self.cleanup())
except RuntimeError:
loop = asyncio.new_event_loop()
loop.run_until_complete(self.cleanup())
- loop.close()+ loop.close()
| 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 BaseTool, ToolResult
from app.tool.tool_collection import ToolCollection
class MCPClientTool(BaseTool):
session: Optional[ClientSession] = None
server_id: str = "" # Add server identifier
original_name: str = ""
async def execute(self, **kwargs) -> ToolResult:
if not self.session:
return ToolResult(error="Not connected to MCP server")
try:
logger.info(f"Executing tool: {self.original_name}")
result = await self.session.call_tool(self.original_name, kwargs)
content_str = ", ".join(
item.text for item in result.content if isinstance(item, TextContent)
)
return ToolResult(output=content_str or "No output returned.")
except Exception as e:
return ToolResult(error=f"Error executing tool: {str(e)}")
class MCPClients(ToolCollection):
sessions: Dict[str, ClientSession] = {}
exit_stacks: Dict[str, AsyncExitStack] = {}
description: str = "MCP client tools for server interaction"
def __init__(self):
super().__init__() # Initialize with empty tools list
self.name = "mcp" # Keep name for backward compatibility
async def connect_sse(self, server_url: str, server_id: str = "") -> None:
if not server_url:
raise ValueError("Server URL is required.")
server_id = server_id or server_url
# Always ensure clean disconnection before new connection
if server_id in self.sessions:
await self.disconnect(server_id)
exit_stack = AsyncExitStack()
self.exit_stacks[server_id] = exit_stack
streams_context = sse_client(url=server_url)
streams = await exit_stack.enter_async_context(streams_context)
session = await exit_stack.enter_async_context(ClientSession(*streams))
self.sessions[server_id] = session
await self._initialize_and_list_tools(server_id)
async def connect_stdio(
self, command: str, args: List[str], server_id: str = ""
) -> None:
if not command:
raise ValueError("Server command is required.")
server_id = server_id or command
# Always ensure clean disconnection before new connection
if server_id in self.sessions:
await self.disconnect(server_id)
exit_stack = AsyncExitStack()
self.exit_stacks[server_id] = exit_stack
server_params = StdioServerParameters(command=command, args=args)
stdio_transport = await exit_stack.enter_async_context(
stdio_client(server_params)
)
read, write = stdio_transport
session = await exit_stack.enter_async_context(ClientSession(read, write))
self.sessions[server_id] = session
await self._initialize_and_list_tools(server_id)
async def _initialize_and_list_tools(self, server_id: str) -> None:
session = self.sessions.get(server_id)
if not session:
raise RuntimeError(f"Session not initialized for server {server_id}")
await session.initialize()
response = await session.list_tools()
# Create proper tool objects for each server tool
for tool in response.tools:
original_name = tool.name
tool_name = f"mcp_{server_id}_{original_name}"
tool_name = self._sanitize_tool_name(tool_name)
server_tool = MCPClientTool(
name=tool_name,
description=tool.description,
parameters=tool.inputSchema,
session=session,
server_id=server_id,
original_name=original_name,
)
self.tool_map[tool_name] = server_tool
# Update tools tuple
self.tools = tuple(self.tool_map.values())
logger.info(
f"Connected to server {server_id} with tools: {[tool.name for tool in response.tools]}"
)
def _sanitize_tool_name(self, name: str) -> str:
import re
# Replace invalid characters with underscores
sanitized = re.sub(r"[^a-zA-Z0-9_-]", "_", name)
# Remove consecutive underscores
sanitized = re.sub(r"_+", "_", sanitized)
# Remove leading/trailing underscores
sanitized = sanitized.strip("_")
# Truncate to 64 characters if needed
if len(sanitized) > 64:
sanitized = sanitized[:64]
return sanitized
async def list_tools(self) -> ListToolsResult:
tools_result = ListToolsResult(tools=[])
for session in self.sessions.values():
response = await session.list_tools()
tools_result.tools += response.tools
return tools_result
async def disconnect(self, server_id: str = "") -> None:
if server_id:
if server_id in self.sessions:
try:
exit_stack = self.exit_stacks.get(server_id)
# Close the exit stack which will handle session cleanup
if exit_stack:
try:
await exit_stack.aclose()
except RuntimeError as e:
if "cancel scope" in str(e).lower():
logger.warning(
f"Cancel scope error during disconnect from {server_id}, continuing with cleanup: {e}"
)
else:
raise
# Clean up references
self.sessions.pop(server_id, None)
self.exit_stacks.pop(server_id, None)
# Remove tools associated with this server
self.tool_map = {
k: v
for k, v in self.tool_map.items()
if v.server_id != server_id
}
self.tools = tuple(self.tool_map.values())
logger.info(f"Disconnected from MCP server {server_id}")
except Exception as e:
logger.error(f"Error disconnecting from server {server_id}: {e}")
else:
# Disconnect from all servers in a deterministic order
for sid in sorted(list(self.sessions.keys())):
await self.disconnect(sid)
self.tool_map = {}
self.tools = tuple()
logger.info("Disconnected from all MCP servers") | --- +++ @@ -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, **kwargs) -> ToolResult:
+ """Execute the tool by making a remote call to the MCP server."""
if not self.session:
return ToolResult(error="Not connected to MCP server")
@@ -33,6 +35,9 @@
class MCPClients(ToolCollection):
+ """
+ A collection of tools that connects to multiple MCP servers and manages available tools through the Model Context Protocol.
+ """
sessions: Dict[str, ClientSession] = {}
exit_stacks: Dict[str, AsyncExitStack] = {}
@@ -43,6 +48,7 @@ self.name = "mcp" # Keep name for backward compatibility
async def connect_sse(self, server_url: str, server_id: str = "") -> None:
+ """Connect to an MCP server using SSE transport."""
if not server_url:
raise ValueError("Server URL is required.")
@@ -65,6 +71,7 @@ async def connect_stdio(
self, command: str, args: List[str], server_id: str = ""
) -> None:
+ """Connect to an MCP server using stdio transport."""
if not command:
raise ValueError("Server command is required.")
@@ -88,6 +95,7 @@ await self._initialize_and_list_tools(server_id)
async def _initialize_and_list_tools(self, server_id: str) -> None:
+ """Initialize session and populate tool map."""
session = self.sessions.get(server_id)
if not session:
raise RuntimeError(f"Session not initialized for server {server_id}")
@@ -118,6 +126,7 @@ )
def _sanitize_tool_name(self, name: str) -> str:
+ """Sanitize tool name to match MCPClientTool requirements."""
import re
# Replace invalid characters with underscores
@@ -136,6 +145,7 @@ return sanitized
async def list_tools(self) -> ListToolsResult:
+ """List all available tools."""
tools_result = ListToolsResult(tools=[])
for session in self.sessions.values():
response = await session.list_tools()
@@ -143,6 +153,7 @@ return tools_result
async def disconnect(self, server_id: str = "") -> None:
+ """Disconnect from a specific MCP server or all servers if no server_id provided."""
if server_id:
if server_id in self.sessions:
try:
@@ -180,4 +191,4 @@ await self.disconnect(sid)
self.tool_map = {}
self.tools = tuple()
- logger.info("Disconnected from all MCP servers")+ logger.info("Disconnected from all MCP servers")
| 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_COMPRESSED_SIZE = 5 * 1024 * 1024
# 压缩设置
DEFAULT_MAX_WIDTH = 1920
DEFAULT_MAX_HEIGHT = 1080
DEFAULT_JPEG_QUALITY = 85
DEFAULT_PNG_COMPRESS_LEVEL = 6
_VISION_DESCRIPTION = """
A sandbox-based vision tool that allows the agent to read image files inside the sandbox using the see_image action.
* Only the see_image action is supported, with the parameter being the relative path of the image under /workspace.
* The image will be compressed and converted to base64 for use in subsequent context.
* Supported formats: JPG, PNG, GIF, WEBP. Maximum size: 10MB.
"""
class SandboxVisionTool(SandboxToolsBase):
name: str = "sandbox_vision"
description: str = _VISION_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["see_image"],
"description": "要执行的视觉动作,目前仅支持 see_image",
},
"file_path": {
"type": "string",
"description": "图片在 /workspace 下的相对路径,如 'screenshots/image.png'",
},
},
"required": ["action", "file_path"],
"dependencies": {"see_image": ["file_path"]},
}
# def __init__(self, project_id: str, thread_id: str, thread_manager: ThreadManager):
# super().__init__(project_id=project_id, thread_manager=thread_manager)
# self.thread_id = thread_id
# self.thread_manager = thread_manager
vision_message: Optional[ThreadMessage] = Field(default=None, exclude=True)
def __init__(
self, sandbox: Optional[Sandbox] = None, thread_id: Optional[str] = None, **data
):
super().__init__(**data)
if sandbox is not None:
self._sandbox = sandbox
def compress_image(self, image_bytes: bytes, mime_type: str, file_path: str):
try:
img = Image.open(BytesIO(image_bytes))
if img.mode in ("RGBA", "LA", "P"):
background = Image.new("RGB", img.size, (255, 255, 255))
if img.mode == "P":
img = img.convert("RGBA")
background.paste(
img, mask=img.split()[-1] if img.mode == "RGBA" else None
)
img = background
width, height = img.size
if width > DEFAULT_MAX_WIDTH or height > DEFAULT_MAX_HEIGHT:
ratio = min(DEFAULT_MAX_WIDTH / width, DEFAULT_MAX_HEIGHT / height)
new_width = int(width * ratio)
new_height = int(height * ratio)
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
output = BytesIO()
if mime_type == "image/gif":
img.save(output, format="GIF", optimize=True)
output_mime = "image/gif"
elif mime_type == "image/png":
img.save(
output,
format="PNG",
optimize=True,
compress_level=DEFAULT_PNG_COMPRESS_LEVEL,
)
output_mime = "image/png"
else:
img.save(
output, format="JPEG", quality=DEFAULT_JPEG_QUALITY, optimize=True
)
output_mime = "image/jpeg"
compressed_bytes = output.getvalue()
return compressed_bytes, output_mime
except Exception:
return image_bytes, mime_type
async def execute(
self, action: str, file_path: Optional[str] = None, **kwargs
) -> ToolResult:
if action != "see_image":
return self.fail_response(f"未知的视觉动作: {action}")
if not file_path:
return self.fail_response("file_path 参数不能为空")
try:
await self._ensure_sandbox()
cleaned_path = self.clean_path(file_path)
full_path = f"{self.workspace_path}/{cleaned_path}"
try:
file_info = self.sandbox.fs.get_file_info(full_path)
if file_info.is_dir:
return self.fail_response(f"路径 '{cleaned_path}' 是目录,不是图片文件。")
except Exception:
return self.fail_response(f"图片文件未找到: '{cleaned_path}'")
if file_info.size > MAX_IMAGE_SIZE:
return self.fail_response(
f"图片文件 '{cleaned_path}' 过大 ({file_info.size / (1024*1024):.2f}MB),最大允许 {MAX_IMAGE_SIZE / (1024*1024)}MB。"
)
try:
image_bytes = self.sandbox.fs.download_file(full_path)
except Exception:
return self.fail_response(f"无法读取图片文件: {cleaned_path}")
mime_type, _ = mimetypes.guess_type(full_path)
if not mime_type or not mime_type.startswith("image/"):
ext = os.path.splitext(cleaned_path)[1].lower()
if ext == ".jpg" or ext == ".jpeg":
mime_type = "image/jpeg"
elif ext == ".png":
mime_type = "image/png"
elif ext == ".gif":
mime_type = "image/gif"
elif ext == ".webp":
mime_type = "image/webp"
else:
return self.fail_response(
f"不支持或未知的图片格式: '{cleaned_path}'。支持: JPG, PNG, GIF, WEBP。"
)
compressed_bytes, compressed_mime_type = self.compress_image(
image_bytes, mime_type, cleaned_path
)
if len(compressed_bytes) > MAX_COMPRESSED_SIZE:
return self.fail_response(
f"图片文件 '{cleaned_path}' 压缩后仍过大 ({len(compressed_bytes) / (1024*1024):.2f}MB),最大允许 {MAX_COMPRESSED_SIZE / (1024*1024)}MB。"
)
base64_image = base64.b64encode(compressed_bytes).decode("utf-8")
image_context_data = {
"mime_type": compressed_mime_type,
"base64": base64_image,
"file_path": cleaned_path,
"original_size": file_info.size,
"compressed_size": len(compressed_bytes),
}
message = ThreadMessage(
type="image_context", content=image_context_data, is_llm_message=False
)
self.vision_message = message
# return self.success_response(f"成功加载并压缩图片 '{cleaned_path}' (由 {file_info.size / 1024:.1f}KB 压缩到 {len(compressed_bytes) / 1024:.1f}KB)。")
return ToolResult(
output=f"成功加载并压缩图片 '{cleaned_path}'",
base64_image=base64_image,
)
except Exception as e:
return self.fail_response(f"see_image 执行异常: {str(e)}") | --- +++ @@ -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
def compress_image(self, image_bytes: bytes, mime_type: str, file_path: str):
+ """压缩图片,保持合理质量。"""
try:
img = Image.open(BytesIO(image_bytes))
if img.mode in ("RGBA", "LA", "P"):
@@ -105,6 +107,12 @@ async def execute(
self, action: str, file_path: Optional[str] = None, **kwargs
) -> ToolResult:
+ """
+ 执行视觉动作,目前仅支持 see_image。
+ 参数:
+ action: 必须为 'see_image'
+ file_path: 图片相对路径
+ """
if action != "see_image":
return self.fail_response(f"未知的视觉动作: {action}")
if not file_path:
@@ -167,4 +175,4 @@ base64_image=base64_image,
)
except Exception as e:
- return self.fail_response(f"see_image 执行异常: {str(e)}")+ return self.fail_response(f"see_image 执行异常: {str(e)}")
| 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 formatting."
)
# Type mapping for JSON schema
type_mapping: dict = {
str: "string",
int: "integer",
float: "number",
bool: "boolean",
dict: "object",
list: "array",
}
response_type: Optional[Type] = None
required: List[str] = Field(default_factory=lambda: ["response"])
def __init__(self, response_type: Optional[Type] = str):
super().__init__()
self.response_type = response_type
self.parameters = self._build_parameters()
def _build_parameters(self) -> dict:
if self.response_type == str:
return {
"type": "object",
"properties": {
"response": {
"type": "string",
"description": "The response text that should be delivered to the user.",
},
},
"required": self.required,
}
if isinstance(self.response_type, type) and issubclass(
self.response_type, BaseModel
):
schema = self.response_type.model_json_schema()
return {
"type": "object",
"properties": schema["properties"],
"required": schema.get("required", self.required),
}
return self._create_type_schema(self.response_type)
def _create_type_schema(self, type_hint: Type) -> dict:
origin = get_origin(type_hint)
args = get_args(type_hint)
# Handle primitive types
if origin is None:
return {
"type": "object",
"properties": {
"response": {
"type": self.type_mapping.get(type_hint, "string"),
"description": f"Response of type {type_hint.__name__}",
}
},
"required": self.required,
}
# Handle List type
if origin is list:
item_type = args[0] if args else Any
return {
"type": "object",
"properties": {
"response": {
"type": "array",
"items": self._get_type_info(item_type),
}
},
"required": self.required,
}
# Handle Dict type
if origin is dict:
value_type = args[1] if len(args) > 1 else Any
return {
"type": "object",
"properties": {
"response": {
"type": "object",
"additionalProperties": self._get_type_info(value_type),
}
},
"required": self.required,
}
# Handle Union type
if origin is Union:
return self._create_union_schema(args)
return self._build_parameters()
def _get_type_info(self, type_hint: Type) -> dict:
if isinstance(type_hint, type) and issubclass(type_hint, BaseModel):
return type_hint.model_json_schema()
return {
"type": self.type_mapping.get(type_hint, "string"),
"description": f"Value of type {getattr(type_hint, '__name__', 'any')}",
}
def _create_union_schema(self, types: tuple) -> dict:
return {
"type": "object",
"properties": {
"response": {"anyOf": [self._get_type_info(t) for t in types]}
},
"required": self.required,
}
async def execute(self, required: list | None = None, **kwargs) -> Any:
required = required or self.required
# Handle case when required is a list
if isinstance(required, list) and len(required) > 0:
if len(required) == 1:
required_field = required[0]
result = kwargs.get(required_field, "")
else:
# Return multiple fields as a dictionary
return {field: kwargs.get(field, "") for field in required}
else:
required_field = "response"
result = kwargs.get(required_field, "")
# Type conversion logic
if self.response_type == str:
return result
if isinstance(self.response_type, type) and issubclass(
self.response_type, BaseModel
):
return self.response_type(**kwargs)
if get_origin(self.response_type) in (list, dict):
return result # Assuming result is already in correct format
try:
return self.response_type(result)
except (ValueError, TypeError):
return result | --- +++ @@ -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 = self._build_parameters()
def _build_parameters(self) -> dict:
+ """Build parameters schema based on response type."""
if self.response_type == str:
return {
"type": "object",
@@ -54,6 +56,7 @@ return self._create_type_schema(self.response_type)
def _create_type_schema(self, type_hint: Type) -> dict:
+ """Create a JSON schema for the given type."""
origin = get_origin(type_hint)
args = get_args(type_hint)
@@ -105,6 +108,7 @@ return self._build_parameters()
def _get_type_info(self, type_hint: Type) -> dict:
+ """Get type information for a single type."""
if isinstance(type_hint, type) and issubclass(type_hint, BaseModel):
return type_hint.model_json_schema()
@@ -114,6 +118,7 @@ }
def _create_union_schema(self, types: tuple) -> dict:
+ """Create schema for Union types."""
return {
"type": "object",
"properties": {
@@ -123,6 +128,15 @@ }
async def execute(self, required: list | None = None, **kwargs) -> Any:
+ """Execute the chat completion with type conversion.
+
+ Args:
+ required: List of required field names or None
+ **kwargs: Response data
+
+ Returns:
+ Converted response based on response_type
+ """
required = required or self.required
# Handle case when required is a list
@@ -152,4 +166,4 @@ try:
return self.response_type(result)
except (ValueError, TypeError):
- return result+ return result
| 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 logger
from app.tool.base import BaseTool
from app.tool.bash import Bash
from app.tool.browser_use_tool import BrowserUseTool
from app.tool.str_replace_editor import StrReplaceEditor
from app.tool.terminate import Terminate
class MCPServer:
def __init__(self, name: str = "openmanus"):
self.server = FastMCP(name)
self.tools: Dict[str, BaseTool] = {}
# Initialize standard tools
self.tools["bash"] = Bash()
self.tools["browser"] = BrowserUseTool()
self.tools["editor"] = StrReplaceEditor()
self.tools["terminate"] = Terminate()
def register_tool(self, tool: BaseTool, method_name: Optional[str] = None) -> None:
tool_name = method_name or tool.name
tool_param = tool.to_param()
tool_function = tool_param["function"]
# Define the async function to be registered
async def tool_method(**kwargs):
logger.info(f"Executing {tool_name}: {kwargs}")
result = await tool.execute(**kwargs)
logger.info(f"Result of {tool_name}: {result}")
# Handle different types of results (match original logic)
if hasattr(result, "model_dump"):
return json.dumps(result.model_dump())
elif isinstance(result, dict):
return json.dumps(result)
return result
# Set method metadata
tool_method.__name__ = tool_name
tool_method.__doc__ = self._build_docstring(tool_function)
tool_method.__signature__ = self._build_signature(tool_function)
# Store parameter schema (important for tools that access it programmatically)
param_props = tool_function.get("parameters", {}).get("properties", {})
required_params = tool_function.get("parameters", {}).get("required", [])
tool_method._parameter_schema = {
param_name: {
"description": param_details.get("description", ""),
"type": param_details.get("type", "any"),
"required": param_name in required_params,
}
for param_name, param_details in param_props.items()
}
# Register with server
self.server.tool()(tool_method)
logger.info(f"Registered tool: {tool_name}")
def _build_docstring(self, tool_function: dict) -> str:
description = tool_function.get("description", "")
param_props = tool_function.get("parameters", {}).get("properties", {})
required_params = tool_function.get("parameters", {}).get("required", [])
# Build docstring (match original format)
docstring = description
if param_props:
docstring += "\n\nParameters:\n"
for param_name, param_details in param_props.items():
required_str = (
"(required)" if param_name in required_params else "(optional)"
)
param_type = param_details.get("type", "any")
param_desc = param_details.get("description", "")
docstring += (
f" {param_name} ({param_type}) {required_str}: {param_desc}\n"
)
return docstring
def _build_signature(self, tool_function: dict) -> Signature:
param_props = tool_function.get("parameters", {}).get("properties", {})
required_params = tool_function.get("parameters", {}).get("required", [])
parameters = []
# Follow original type mapping
for param_name, param_details in param_props.items():
param_type = param_details.get("type", "")
default = Parameter.empty if param_name in required_params else None
# Map JSON Schema types to Python types (same as original)
annotation = Any
if param_type == "string":
annotation = str
elif param_type == "integer":
annotation = int
elif param_type == "number":
annotation = float
elif param_type == "boolean":
annotation = bool
elif param_type == "object":
annotation = dict
elif param_type == "array":
annotation = list
# Create parameter with same structure as original
param = Parameter(
name=param_name,
kind=Parameter.KEYWORD_ONLY,
default=default,
annotation=annotation,
)
parameters.append(param)
return Signature(parameters=parameters)
async def cleanup(self) -> None:
logger.info("Cleaning up resources")
# Follow original cleanup logic - only clean browser tool
if "browser" in self.tools and hasattr(self.tools["browser"], "cleanup"):
await self.tools["browser"].cleanup()
def register_all_tools(self) -> None:
for tool in self.tools.values():
self.register_tool(tool)
def run(self, transport: str = "stdio") -> None:
# Register all tools
self.register_all_tools()
# Register cleanup function (match original behavior)
atexit.register(lambda: asyncio.run(self.cleanup()))
# Start server (with same logging as original)
logger.info(f"Starting OpenManus server ({transport} mode)")
self.server.run(transport=transport)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="OpenManus MCP Server")
parser.add_argument(
"--transport",
choices=["stdio"],
default="stdio",
help="Communication method: stdio or http (default: stdio)",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
# Create and run server (maintaining original flow)
server = MCPServer()
server.run(transport=args.transport) | --- +++ @@ -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: BaseTool, method_name: Optional[str] = None) -> None:
+ """Register a tool with parameter validation and documentation."""
tool_name = method_name or tool.name
tool_param = tool.to_param()
tool_function = tool_param["function"]
@@ -74,6 +76,7 @@ logger.info(f"Registered tool: {tool_name}")
def _build_docstring(self, tool_function: dict) -> str:
+ """Build a formatted docstring from tool function metadata."""
description = tool_function.get("description", "")
param_props = tool_function.get("parameters", {}).get("properties", {})
required_params = tool_function.get("parameters", {}).get("required", [])
@@ -95,6 +98,7 @@ return docstring
def _build_signature(self, tool_function: dict) -> Signature:
+ """Build a function signature from tool function metadata."""
param_props = tool_function.get("parameters", {}).get("properties", {})
required_params = tool_function.get("parameters", {}).get("required", [])
@@ -132,16 +136,19 @@ return Signature(parameters=parameters)
async def cleanup(self) -> None:
+ """Clean up server resources."""
logger.info("Cleaning up resources")
# Follow original cleanup logic - only clean browser tool
if "browser" in self.tools and hasattr(self.tools["browser"], "cleanup"):
await self.tools["browser"].cleanup()
def register_all_tools(self) -> None:
+ """Register all tools with the server."""
for tool in self.tools.values():
self.register_tool(tool)
def run(self, transport: str = "stdio") -> None:
+ """Run the MCP server."""
# Register all tools
self.register_all_tools()
@@ -154,6 +161,7 @@
def parse_args() -> argparse.Namespace:
+ """Parse command line arguments."""
parser = argparse.ArgumentParser(description="OpenManus MCP Server")
parser.add_argument(
"--transport",
@@ -169,4 +177,4 @@
# Create and run server (maintaining original flow)
server = MCPServer()
- server.run(transport=args.transport)+ server.run(transport=args.transport)
| 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 workspace directory.
IMPORTANT: Commands are non-blocking by default and run in a tmux session.
This is ideal for long-running operations like starting servers or build processes.
Uses sessions to maintain state between commands.
This tool is essential for running CLI tools, installing packages, and managing system operations.
"""
class SandboxShellTool(SandboxToolsBase):
name: str = "sandbox_shell"
description: str = _SHELL_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": [
"execute_command",
"check_command_output",
"terminate_command",
"list_commands",
],
"description": "The shell action to perform",
},
"command": {
"type": "string",
"description": "The shell command to execute. Use this for running CLI tools, installing packages, "
"or system operations. Commands can be chained using &&, ||, and | operators.",
},
"folder": {
"type": "string",
"description": "Optional relative path to a subdirectory of /workspace where the command should be "
"executed. Example: 'data/pdfs'",
},
"session_name": {
"type": "string",
"description": "Optional name of the tmux session to use. Use named sessions for related commands "
"that need to maintain state. Defaults to a random session name.",
},
"blocking": {
"type": "boolean",
"description": "Whether to wait for the command to complete. Defaults to false for non-blocking "
"execution.",
"default": False,
},
"timeout": {
"type": "integer",
"description": "Optional timeout in seconds for blocking commands. Defaults to 60. Ignored for "
"non-blocking commands.",
"default": 60,
},
"kill_session": {
"type": "boolean",
"description": "Whether to terminate the tmux session after checking. Set to true when you're done "
"with the command.",
"default": False,
},
},
"required": ["action"],
"dependencies": {
"execute_command": ["command"],
"check_command_output": ["session_name"],
"terminate_command": ["session_name"],
"list_commands": [],
},
}
def __init__(
self, sandbox: Optional[Sandbox] = None, thread_id: Optional[str] = None, **data
):
super().__init__(**data)
if sandbox is not None:
self._sandbox = sandbox
async def _ensure_session(self, session_name: str = "default") -> str:
if session_name not in self._sessions:
session_id = str(uuid4())
try:
await self._ensure_sandbox() # Ensure sandbox is initialized
self.sandbox.process.create_session(session_id)
self._sessions[session_name] = session_id
except Exception as e:
raise RuntimeError(f"Failed to create session: {str(e)}")
return self._sessions[session_name]
async def _cleanup_session(self, session_name: str):
if session_name in self._sessions:
try:
await self._ensure_sandbox() # Ensure sandbox is initialized
self.sandbox.process.delete_session(self._sessions[session_name])
del self._sessions[session_name]
except Exception as e:
print(f"Warning: Failed to cleanup session {session_name}: {str(e)}")
async def _execute_raw_command(self, command: str) -> Dict[str, Any]:
# Ensure session exists for raw commands
session_id = await self._ensure_session("raw_commands")
# Execute command in session
from app.daytona.sandbox import SessionExecuteRequest
req = SessionExecuteRequest(
command=command, run_async=False, cwd=self.workspace_path
)
response = self.sandbox.process.execute_session_command(
session_id=session_id,
req=req,
timeout=30, # Short timeout for utility commands
)
logs = self.sandbox.process.get_session_command_logs(
session_id=session_id, command_id=response.cmd_id
)
return {"output": logs, "exit_code": response.exit_code}
async def _execute_command(
self,
command: str,
folder: Optional[str] = None,
session_name: Optional[str] = None,
blocking: bool = False,
timeout: int = 60,
) -> ToolResult:
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
# Set up working directory
cwd = self.workspace_path
if folder:
folder = folder.strip("/")
cwd = f"{self.workspace_path}/{folder}"
# Generate a session name if not provided
if not session_name:
session_name = f"session_{str(uuid4())[:8]}"
# Check if tmux session already exists
check_session = await self._execute_raw_command(
f"tmux has-session -t {session_name} 2>/dev/null || echo 'not_exists'"
)
session_exists = "not_exists" not in check_session.get("output", "")
if not session_exists:
# Create a new tmux session
await self._execute_raw_command(
f"tmux new-session -d -s {session_name}"
)
# Ensure we're in the correct directory and send command to tmux
full_command = f"cd {cwd} && {command}"
wrapped_command = full_command.replace('"', '\\"') # Escape double quotes
# Send command to tmux session
await self._execute_raw_command(
f'tmux send-keys -t {session_name} "{wrapped_command}" Enter'
)
if blocking:
# For blocking execution, wait and capture output
start_time = time.time()
while (time.time() - start_time) < timeout:
# Wait a bit before checking
time.sleep(2)
# Check if session still exists (command might have exited)
check_result = await self._execute_raw_command(
f"tmux has-session -t {session_name} 2>/dev/null || echo 'ended'"
)
if "ended" in check_result.get("output", ""):
break
# Get current output and check for common completion indicators
output_result = await self._execute_raw_command(
f"tmux capture-pane -t {session_name} -p -S - -E -"
)
current_output = output_result.get("output", "")
# Check for prompt indicators that suggest command completion
last_lines = current_output.split("\n")[-3:]
completion_indicators = [
"$",
"#",
">",
"Done",
"Completed",
"Finished",
"✓",
]
if any(
indicator in line
for indicator in completion_indicators
for line in last_lines
):
break
# Capture final output
output_result = await self._execute_raw_command(
f"tmux capture-pane -t {session_name} -p -S - -E -"
)
final_output = output_result.get("output", "")
# Kill the session after capture
await self._execute_raw_command(f"tmux kill-session -t {session_name}")
return self.success_response(
{
"output": final_output,
"session_name": session_name,
"cwd": cwd,
"completed": True,
}
)
else:
# For non-blocking, just return immediately
return self.success_response(
{
"session_name": session_name,
"cwd": cwd,
"message": f"Command sent to tmux session '{session_name}'. Use check_command_output to view results.",
"completed": False,
}
)
except Exception as e:
# Attempt to clean up session in case of error
if session_name:
try:
await self._execute_raw_command(
f"tmux kill-session -t {session_name}"
)
except:
pass
return self.fail_response(f"Error executing command: {str(e)}")
async def _check_command_output(
self, session_name: str, kill_session: bool = False
) -> ToolResult:
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
# Check if session exists
check_result = await self._execute_raw_command(
f"tmux has-session -t {session_name} 2>/dev/null || echo 'not_exists'"
)
if "not_exists" in check_result.get("output", ""):
return self.fail_response(
f"Tmux session '{session_name}' does not exist."
)
# Get output from tmux pane
output_result = await self._execute_raw_command(
f"tmux capture-pane -t {session_name} -p -S - -E -"
)
output = output_result.get("output", "")
# Kill session if requested
if kill_session:
await self._execute_raw_command(f"tmux kill-session -t {session_name}")
termination_status = "Session terminated."
else:
termination_status = "Session still running."
return self.success_response(
{
"output": output,
"session_name": session_name,
"status": termination_status,
}
)
except Exception as e:
return self.fail_response(f"Error checking command output: {str(e)}")
async def _terminate_command(self, session_name: str) -> ToolResult:
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
# Check if session exists
check_result = await self._execute_raw_command(
f"tmux has-session -t {session_name} 2>/dev/null || echo 'not_exists'"
)
if "not_exists" in check_result.get("output", ""):
return self.fail_response(
f"Tmux session '{session_name}' does not exist."
)
# Kill the session
await self._execute_raw_command(f"tmux kill-session -t {session_name}")
return self.success_response(
{"message": f"Tmux session '{session_name}' terminated successfully."}
)
except Exception as e:
return self.fail_response(f"Error terminating command: {str(e)}")
async def _list_commands(self) -> ToolResult:
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
# List all tmux sessions
result = await self._execute_raw_command(
"tmux list-sessions 2>/dev/null || echo 'No sessions'"
)
output = result.get("output", "")
if "No sessions" in output or not output.strip():
return self.success_response(
{"message": "No active tmux sessions found.", "sessions": []}
)
# Parse session list
sessions = []
for line in output.split("\n"):
if line.strip():
parts = line.split(":")
if parts:
session_name = parts[0].strip()
sessions.append(session_name)
return self.success_response(
{
"message": f"Found {len(sessions)} active sessions.",
"sessions": sessions,
}
)
except Exception as e:
return self.fail_response(f"Error listing commands: {str(e)}")
async def execute(
self,
action: str,
command: str,
folder: Optional[str] = None,
session_name: Optional[str] = None,
blocking: bool = False,
timeout: int = 60,
kill_session: bool = False,
) -> ToolResult:
async with asyncio.Lock():
try:
# Navigation actions
if action == "execute_command":
if not command:
return self.fail_response("command is required for navigation")
return await self._execute_command(
command, folder, session_name, blocking, timeout
)
elif action == "check_command_output":
if session_name is None:
return self.fail_response(
"session_name is required for navigation"
)
return await self._check_command_output(session_name, kill_session)
elif action == "terminate_command":
if session_name is None:
return self.fail_response(
"session_name is required for click_element"
)
return await self._terminate_command(session_name)
elif action == "list_commands":
return await self._list_commands()
else:
return self.fail_response(f"Unknown action: {action}")
except Exception as e:
logger.error(f"Error executing shell action: {e}")
return self.fail_response(f"Error executing shell action: {e}")
async def cleanup(self):
for session_name in list(self._sessions.keys()):
await self._cleanup_session(session_name)
# Also clean up any tmux sessions
try:
await self._ensure_sandbox()
await self._execute_raw_command("tmux kill-server 2>/dev/null || true")
except Exception as e:
logger.error(f"Error shell box cleanup action: {e}") | --- +++ @@ -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"
description: str = _SHELL_DESCRIPTION
@@ -81,11 +84,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
async def _ensure_session(self, session_name: str = "default") -> str:
+ """Ensure a session exists and return its ID."""
if session_name not in self._sessions:
session_id = str(uuid4())
try:
@@ -97,6 +102,7 @@ return self._sessions[session_name]
async def _cleanup_session(self, session_name: str):
+ """Clean up a session if it exists."""
if session_name in self._sessions:
try:
await self._ensure_sandbox() # Ensure sandbox is initialized
@@ -106,6 +112,7 @@ print(f"Warning: Failed to cleanup session {session_name}: {str(e)}")
async def _execute_raw_command(self, command: str) -> Dict[str, Any]:
+ """Execute a raw command directly in the sandbox."""
# Ensure session exists for raw commands
session_id = await self._ensure_session("raw_commands")
@@ -357,6 +364,19 @@ timeout: int = 60,
kill_session: bool = False,
) -> ToolResult:
+ """
+ Execute a browser action in the sandbox environment.
+ Args:
+ timeout:
+ blocking:
+ session_name:
+ folder:
+ command:
+ kill_session:
+ action: The browser action to perform
+ Returns:
+ ToolResult with the action's output or error
+ """
async with asyncio.Lock():
try:
# Navigation actions
@@ -387,6 +407,7 @@ return self.fail_response(f"Error executing shell action: {e}")
async def cleanup(self):
+ """Clean up all sessions."""
for session_name in list(self._sessions.keys()):
await self._cleanup_session(session_name)
@@ -395,4 +416,4 @@ await self._ensure_sandbox()
await self._execute_raw_command("tmux kill-server 2>/dev/null || true")
except Exception as e:
- logger.error(f"Error shell box cleanup action: {e}")+ logger.error(f"Error shell box cleanup action: {e}")
| 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.0.3440.106 Safari/537.36",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/49.0.2623.108 Chrome/49.0.2623.108 Safari/537.36",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; pt-BR) AppleWebKit/533.3 (KHTML, like Gecko) QtWeb Internet Browser/3.7 http://www.QtWeb.net",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.2 (KHTML, like Gecko) ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/532.2",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.4pre) Gecko/20070404 K-Ninja/2.1.3",
"Mozilla/5.0 (Future Star Technologies Corp.; Star-Blade OS; x86_64; U; en-US) iNet Browser 4.7",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080414 Firefox/2.0.0.13 Pogo/2.0.0.13.6866",
]
HEADERS = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": USER_AGENTS[0],
"Referer": "https://www.bing.com/",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9",
}
BING_HOST_URL = "https://www.bing.com"
BING_SEARCH_URL = "https://www.bing.com/search?q="
class BingSearchEngine(WebSearchEngine):
session: Optional[requests.Session] = None
def __init__(self, **data):
super().__init__(**data)
self.session = requests.Session()
self.session.headers.update(HEADERS)
def _search_sync(self, query: str, num_results: int = 10) -> List[SearchItem]:
if not query:
return []
list_result = []
first = 1
next_url = BING_SEARCH_URL + query
while len(list_result) < num_results:
data, next_url = self._parse_html(
next_url, rank_start=len(list_result), first=first
)
if data:
list_result.extend(data)
if not next_url:
break
first += 10
return list_result[:num_results]
def _parse_html(
self, url: str, rank_start: int = 0, first: int = 1
) -> Tuple[List[SearchItem], str]:
try:
res = self.session.get(url=url)
res.encoding = "utf-8"
root = BeautifulSoup(res.text, "lxml")
list_data = []
ol_results = root.find("ol", id="b_results")
if not ol_results:
return [], None
for li in ol_results.find_all("li", class_="b_algo"):
title = ""
url = ""
abstract = ""
try:
h2 = li.find("h2")
if h2:
title = h2.text.strip()
url = h2.a["href"].strip()
p = li.find("p")
if p:
abstract = p.text.strip()
if ABSTRACT_MAX_LENGTH and len(abstract) > ABSTRACT_MAX_LENGTH:
abstract = abstract[:ABSTRACT_MAX_LENGTH]
rank_start += 1
# Create a SearchItem object
list_data.append(
SearchItem(
title=title or f"Bing Result {rank_start}",
url=url,
description=abstract,
)
)
except Exception:
continue
next_btn = root.find("a", title="Next page")
if not next_btn:
return list_data, None
next_url = BING_HOST_URL + next_btn["href"]
return list_data, next_url
except Exception as e:
logger.warning(f"Error parsing HTML: {e}")
return [], None
def perform_search(
self, query: str, num_results: int = 10, *args, **kwargs
) -> List[SearchItem]:
return self._search_sync(query, num_results=num_results) | --- +++ @@ -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 _search_sync(self, query: str, num_results: int = 10) -> List[SearchItem]:
+ """
+ Synchronous Bing search implementation to retrieve search results.
+
+ Args:
+ query (str): The search query to submit to Bing.
+ num_results (int, optional): Maximum number of results to return. Defaults to 10.
+
+ Returns:
+ List[SearchItem]: A list of search items with title, URL, and description.
+ """
if not query:
return []
@@ -66,6 +77,12 @@ def _parse_html(
self, url: str, rank_start: int = 0, first: int = 1
) -> Tuple[List[SearchItem], str]:
+ """
+ Parse Bing search result HTML to extract search results and the next page URL.
+
+ Returns:
+ tuple: (List of SearchItem objects, next page URL or None)
+ """
try:
res = self.session.get(url=url)
res.encoding = "utf-8"
@@ -119,4 +136,9 @@ def perform_search(
self, query: str, num_results: int = 10, *args, **kwargs
) -> List[SearchItem]:
- return self._search_sync(query, num_results=num_results)+ """
+ Bing search engine.
+
+ Returns results formatted according to SearchItem model.
+ """
+ return self._search_sync(query, num_results=num_results)
| 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
self.tool_map = {tool.name: tool for tool in tools}
def __iter__(self):
return iter(self.tools)
def to_params(self) -> List[Dict[str, Any]]:
return [tool.to_param() for tool in self.tools]
async def execute(
self, *, name: str, tool_input: Dict[str, Any] = None
) -> ToolResult:
tool = self.tool_map.get(name)
if not tool:
return ToolFailure(error=f"Tool {name} is invalid")
try:
result = await tool(**tool_input)
return result
except ToolError as e:
return ToolFailure(error=e.message)
async def execute_all(self) -> List[ToolResult]:
results = []
for tool in self.tools:
try:
result = await tool()
results.append(result)
except ToolError as e:
results.append(ToolFailure(error=e.message))
return results
def get_tool(self, name: str) -> BaseTool:
return self.tool_map.get(name)
def add_tool(self, tool: BaseTool):
if tool.name in self.tool_map:
logger.warning(f"Tool {tool.name} already exists in collection, skipping")
return self
self.tools += (tool,)
self.tool_map[tool.name] = tool
return self
def add_tools(self, *tools: BaseTool):
for tool in tools:
self.add_tool(tool)
return self | --- +++ @@ -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 @@ return ToolFailure(error=e.message)
async def execute_all(self) -> List[ToolResult]:
+ """Execute all tools in the collection sequentially."""
results = []
for tool in self.tools:
try:
@@ -46,6 +49,10 @@ return self.tool_map.get(name)
def add_tool(self, tool: BaseTool):
+ """Add a single tool to the collection.
+
+ If a tool with the same name already exists, it will be skipped and a warning will be logged.
+ """
if tool.name in self.tool_map:
logger.warning(f"Tool {tool.name} already exists in collection, skipping")
return self
@@ -55,6 +62,10 @@ return self
def add_tools(self, *tools: BaseTool):
+ """Add multiple tools to the collection.
+
+ If any tool has a name conflict with an existing tool, it will be skipped and a warning will be logged.
+ """
for tool in tools:
self.add_tool(tool)
- return self+ return self
| 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:
def __init__(
self,
max_sandboxes: int = 100,
idle_timeout: int = 3600,
cleanup_interval: int = 300,
):
self.max_sandboxes = max_sandboxes
self.idle_timeout = idle_timeout
self.cleanup_interval = cleanup_interval
# Docker client
self._client = docker.from_env()
# Resource mappings
self._sandboxes: Dict[str, DockerSandbox] = {}
self._last_used: Dict[str, float] = {}
# Concurrency control
self._locks: Dict[str, asyncio.Lock] = {}
self._global_lock = asyncio.Lock()
self._active_operations: Set[str] = set()
# Cleanup task
self._cleanup_task: Optional[asyncio.Task] = None
self._is_shutting_down = False
# Start automatic cleanup
self.start_cleanup_task()
async def ensure_image(self, image: str) -> bool:
try:
self._client.images.get(image)
return True
except ImageNotFound:
try:
logger.info(f"Pulling image {image}...")
await asyncio.get_event_loop().run_in_executor(
None, self._client.images.pull, image
)
return True
except (APIError, Exception) as e:
logger.error(f"Failed to pull image {image}: {e}")
return False
@asynccontextmanager
async def sandbox_operation(self, sandbox_id: str):
if sandbox_id not in self._locks:
self._locks[sandbox_id] = asyncio.Lock()
async with self._locks[sandbox_id]:
if sandbox_id not in self._sandboxes:
raise KeyError(f"Sandbox {sandbox_id} not found")
self._active_operations.add(sandbox_id)
try:
self._last_used[sandbox_id] = asyncio.get_event_loop().time()
yield self._sandboxes[sandbox_id]
finally:
self._active_operations.remove(sandbox_id)
async def create_sandbox(
self,
config: Optional[SandboxSettings] = None,
volume_bindings: Optional[Dict[str, str]] = None,
) -> str:
async with self._global_lock:
if len(self._sandboxes) >= self.max_sandboxes:
raise RuntimeError(
f"Maximum number of sandboxes ({self.max_sandboxes}) reached"
)
config = config or SandboxSettings()
if not await self.ensure_image(config.image):
raise RuntimeError(f"Failed to ensure Docker image: {config.image}")
sandbox_id = str(uuid.uuid4())
try:
sandbox = DockerSandbox(config, volume_bindings)
await sandbox.create()
self._sandboxes[sandbox_id] = sandbox
self._last_used[sandbox_id] = asyncio.get_event_loop().time()
self._locks[sandbox_id] = asyncio.Lock()
logger.info(f"Created sandbox {sandbox_id}")
return sandbox_id
except Exception as e:
logger.error(f"Failed to create sandbox: {e}")
if sandbox_id in self._sandboxes:
await self.delete_sandbox(sandbox_id)
raise RuntimeError(f"Failed to create sandbox: {e}")
async def get_sandbox(self, sandbox_id: str) -> DockerSandbox:
async with self.sandbox_operation(sandbox_id) as sandbox:
return sandbox
def start_cleanup_task(self) -> None:
async def cleanup_loop():
while not self._is_shutting_down:
try:
await self._cleanup_idle_sandboxes()
except Exception as e:
logger.error(f"Error in cleanup loop: {e}")
await asyncio.sleep(self.cleanup_interval)
self._cleanup_task = asyncio.create_task(cleanup_loop())
async def _cleanup_idle_sandboxes(self) -> None:
current_time = asyncio.get_event_loop().time()
to_cleanup = []
async with self._global_lock:
for sandbox_id, last_used in self._last_used.items():
if (
sandbox_id not in self._active_operations
and current_time - last_used > self.idle_timeout
):
to_cleanup.append(sandbox_id)
for sandbox_id in to_cleanup:
try:
await self.delete_sandbox(sandbox_id)
except Exception as e:
logger.error(f"Error cleaning up sandbox {sandbox_id}: {e}")
async def cleanup(self) -> None:
logger.info("Starting manager cleanup...")
self._is_shutting_down = True
# Cancel cleanup task
if self._cleanup_task:
self._cleanup_task.cancel()
try:
await asyncio.wait_for(self._cleanup_task, timeout=1.0)
except (asyncio.CancelledError, asyncio.TimeoutError):
pass
# Get all sandbox IDs to clean up
async with self._global_lock:
sandbox_ids = list(self._sandboxes.keys())
# Concurrently clean up all sandboxes
cleanup_tasks = []
for sandbox_id in sandbox_ids:
task = asyncio.create_task(self._safe_delete_sandbox(sandbox_id))
cleanup_tasks.append(task)
if cleanup_tasks:
# Wait for all cleanup tasks to complete, with timeout to avoid infinite waiting
try:
await asyncio.wait(cleanup_tasks, timeout=30.0)
except asyncio.TimeoutError:
logger.error("Sandbox cleanup timed out")
# Clean up remaining references
self._sandboxes.clear()
self._last_used.clear()
self._locks.clear()
self._active_operations.clear()
logger.info("Manager cleanup completed")
async def _safe_delete_sandbox(self, sandbox_id: str) -> None:
try:
if sandbox_id in self._active_operations:
logger.warning(
f"Sandbox {sandbox_id} has active operations, waiting for completion"
)
for _ in range(10): # Wait at most 10 times
await asyncio.sleep(0.5)
if sandbox_id not in self._active_operations:
break
else:
logger.warning(
f"Timeout waiting for sandbox {sandbox_id} operations to complete"
)
# Get reference to sandbox object
sandbox = self._sandboxes.get(sandbox_id)
if sandbox:
await sandbox.cleanup()
# Remove sandbox record from manager
async with self._global_lock:
self._sandboxes.pop(sandbox_id, None)
self._last_used.pop(sandbox_id, None)
self._locks.pop(sandbox_id, None)
logger.info(f"Deleted sandbox {sandbox_id}")
except Exception as e:
logger.error(f"Error during cleanup of sandbox {sandbox_id}: {e}")
async def delete_sandbox(self, sandbox_id: str) -> None:
if sandbox_id not in self._sandboxes:
return
try:
await self._safe_delete_sandbox(sandbox_id)
except Exception as e:
logger.error(f"Failed to delete sandbox {sandbox_id}: {e}")
async def __aenter__(self) -> "SandboxManager":
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
await self.cleanup()
def get_stats(self) -> Dict:
return {
"total_sandboxes": len(self._sandboxes),
"active_operations": len(self._active_operations),
"max_sandboxes": self.max_sandboxes,
"idle_timeout": self.idle_timeout,
"cleanup_interval": self.cleanup_interval,
"is_shutting_down": self._is_shutting_down,
} | --- +++ @@ -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_sandboxes: Maximum allowed number of sandboxes.
+ idle_timeout: Sandbox idle timeout in seconds.
+ cleanup_interval: Cleanup check interval in seconds.
+ _sandboxes: Active sandbox instance mapping.
+ _last_used: Last used time record for sandboxes.
+ """
def __init__(
self,
@@ -19,6 +32,13 @@ idle_timeout: int = 3600,
cleanup_interval: int = 300,
):
+ """Initializes sandbox manager.
+
+ Args:
+ max_sandboxes: Maximum sandbox count limit.
+ idle_timeout: Idle timeout in seconds.
+ cleanup_interval: Cleanup check interval in seconds.
+ """
self.max_sandboxes = max_sandboxes
self.idle_timeout = idle_timeout
self.cleanup_interval = cleanup_interval
@@ -43,6 +63,14 @@ self.start_cleanup_task()
async def ensure_image(self, image: str) -> bool:
+ """Ensures Docker image is available.
+
+ Args:
+ image: Image name.
+
+ Returns:
+ bool: Whether image is available.
+ """
try:
self._client.images.get(image)
return True
@@ -59,6 +87,16 @@
@asynccontextmanager
async def sandbox_operation(self, sandbox_id: str):
+ """Context manager for sandbox operations.
+
+ Provides concurrency control and usage time updates.
+
+ Args:
+ sandbox_id: Sandbox ID.
+
+ Raises:
+ KeyError: If sandbox not found.
+ """
if sandbox_id not in self._locks:
self._locks[sandbox_id] = asyncio.Lock()
@@ -78,6 +116,18 @@ config: Optional[SandboxSettings] = None,
volume_bindings: Optional[Dict[str, str]] = None,
) -> str:
+ """Creates a new sandbox instance.
+
+ Args:
+ config: Sandbox configuration.
+ volume_bindings: Volume mapping configuration.
+
+ Returns:
+ str: Sandbox ID.
+
+ Raises:
+ RuntimeError: If max sandbox count reached or creation fails.
+ """
async with self._global_lock:
if len(self._sandboxes) >= self.max_sandboxes:
raise RuntimeError(
@@ -107,10 +157,22 @@ raise RuntimeError(f"Failed to create sandbox: {e}")
async def get_sandbox(self, sandbox_id: str) -> DockerSandbox:
+ """Gets a sandbox instance.
+
+ Args:
+ sandbox_id: Sandbox ID.
+
+ Returns:
+ DockerSandbox: Sandbox instance.
+
+ Raises:
+ KeyError: If sandbox does not exist.
+ """
async with self.sandbox_operation(sandbox_id) as sandbox:
return sandbox
def start_cleanup_task(self) -> None:
+ """Starts automatic cleanup task."""
async def cleanup_loop():
while not self._is_shutting_down:
@@ -123,6 +185,7 @@ self._cleanup_task = asyncio.create_task(cleanup_loop())
async def _cleanup_idle_sandboxes(self) -> None:
+ """Cleans up idle sandboxes."""
current_time = asyncio.get_event_loop().time()
to_cleanup = []
@@ -141,6 +204,7 @@ logger.error(f"Error cleaning up sandbox {sandbox_id}: {e}")
async def cleanup(self) -> None:
+ """Cleans up all resources."""
logger.info("Starting manager cleanup...")
self._is_shutting_down = True
@@ -178,6 +242,11 @@ logger.info("Manager cleanup completed")
async def _safe_delete_sandbox(self, sandbox_id: str) -> None:
+ """Safely deletes a single sandbox.
+
+ Args:
+ sandbox_id: Sandbox ID to delete.
+ """
try:
if sandbox_id in self._active_operations:
logger.warning(
@@ -207,6 +276,11 @@ logger.error(f"Error during cleanup of sandbox {sandbox_id}: {e}")
async def delete_sandbox(self, sandbox_id: str) -> None:
+ """Deletes specified sandbox.
+
+ Args:
+ sandbox_id: Sandbox ID.
+ """
if sandbox_id not in self._sandboxes:
return
@@ -216,12 +290,19 @@ logger.error(f"Failed to delete sandbox {sandbox_id}: {e}")
async def __aenter__(self) -> "SandboxManager":
+ """Async context manager entry."""
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
+ """Async context manager exit."""
await self.cleanup()
def get_stats(self) -> Dict:
+ """Gets manager statistics.
+
+ Returns:
+ Dict: Statistics information.
+ """
return {
"total_sandboxes": len(self._sandboxes),
"active_operations": len(self._active_operations),
@@ -229,4 +310,4 @@ "idle_timeout": self.idle_timeout,
"cleanup_interval": self.cleanup_interval,
"is_shutting_down": self._is_shutting_down,
- }+ }
| 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 SandboxTimeoutError(SandboxError):
+ """Exception raised when a sandbox operation times out."""
-class SandboxResourceError(SandboxError):+class SandboxResourceError(SandboxError):
+ """Exception raised for resource-related errors."""
| 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.sandbox.core.terminal import AsyncDockerizedTerminal
class DockerSandbox:
def __init__(
self,
config: Optional[SandboxSettings] = None,
volume_bindings: Optional[Dict[str, str]] = None,
):
self.config = config or SandboxSettings()
self.volume_bindings = volume_bindings or {}
self.client = docker.from_env()
self.container: Optional[Container] = None
self.terminal: Optional[AsyncDockerizedTerminal] = None
async def create(self) -> "DockerSandbox":
try:
# Prepare container config
host_config = self.client.api.create_host_config(
mem_limit=self.config.memory_limit,
cpu_period=100000,
cpu_quota=int(100000 * self.config.cpu_limit),
network_mode="none" if not self.config.network_enabled else "bridge",
binds=self._prepare_volume_bindings(),
)
# Generate unique container name with sandbox_ prefix
container_name = f"sandbox_{uuid.uuid4().hex[:8]}"
# Create container
container = await asyncio.to_thread(
self.client.api.create_container,
image=self.config.image,
command="tail -f /dev/null",
hostname="sandbox",
working_dir=self.config.work_dir,
host_config=host_config,
name=container_name,
tty=True,
detach=True,
)
self.container = self.client.containers.get(container["Id"])
# Start container
await asyncio.to_thread(self.container.start)
# Initialize terminal
self.terminal = AsyncDockerizedTerminal(
container["Id"],
self.config.work_dir,
env_vars={"PYTHONUNBUFFERED": "1"}
# Ensure Python output is not buffered
)
await self.terminal.init()
return self
except Exception as e:
await self.cleanup() # Ensure resources are cleaned up
raise RuntimeError(f"Failed to create sandbox: {e}") from e
def _prepare_volume_bindings(self) -> Dict[str, Dict[str, str]]:
bindings = {}
# Create and add working directory mapping
work_dir = self._ensure_host_dir(self.config.work_dir)
bindings[work_dir] = {"bind": self.config.work_dir, "mode": "rw"}
# Add custom volume bindings
for host_path, container_path in self.volume_bindings.items():
bindings[host_path] = {"bind": container_path, "mode": "rw"}
return bindings
@staticmethod
def _ensure_host_dir(path: str) -> str:
host_path = os.path.join(
tempfile.gettempdir(),
f"sandbox_{os.path.basename(path)}_{os.urandom(4).hex()}",
)
os.makedirs(host_path, exist_ok=True)
return host_path
async def run_command(self, cmd: str, timeout: Optional[int] = None) -> str:
if not self.terminal:
raise RuntimeError("Sandbox not initialized")
try:
return await self.terminal.run_command(
cmd, timeout=timeout or self.config.timeout
)
except TimeoutError:
raise SandboxTimeoutError(
f"Command execution timed out after {timeout or self.config.timeout} seconds"
)
async def read_file(self, path: str) -> str:
if not self.container:
raise RuntimeError("Sandbox not initialized")
try:
# Get file archive
resolved_path = self._safe_resolve_path(path)
tar_stream, _ = await asyncio.to_thread(
self.container.get_archive, resolved_path
)
# Read file content from tar stream
content = await self._read_from_tar(tar_stream)
return content.decode("utf-8")
except NotFound:
raise FileNotFoundError(f"File not found: {path}")
except Exception as e:
raise RuntimeError(f"Failed to read file: {e}")
async def write_file(self, path: str, content: str) -> None:
if not self.container:
raise RuntimeError("Sandbox not initialized")
try:
resolved_path = self._safe_resolve_path(path)
parent_dir = os.path.dirname(resolved_path)
# Create parent directory
if parent_dir:
await self.run_command(f"mkdir -p {parent_dir}")
# Prepare file data
tar_stream = await self._create_tar_stream(
os.path.basename(path), content.encode("utf-8")
)
# Write file
await asyncio.to_thread(
self.container.put_archive, parent_dir or "/", tar_stream
)
except Exception as e:
raise RuntimeError(f"Failed to write file: {e}")
def _safe_resolve_path(self, path: str) -> str:
# Check for path traversal attempts
if ".." in path.split("/"):
raise ValueError("Path contains potentially unsafe patterns")
resolved = (
os.path.join(self.config.work_dir, path)
if not os.path.isabs(path)
else path
)
return resolved
async def copy_from(self, src_path: str, dst_path: str) -> None:
try:
# Ensure destination file's parent directory exists
parent_dir = os.path.dirname(dst_path)
if parent_dir:
os.makedirs(parent_dir, exist_ok=True)
# Get file stream
resolved_src = self._safe_resolve_path(src_path)
stream, stat = await asyncio.to_thread(
self.container.get_archive, resolved_src
)
# Create temporary directory to extract file
with tempfile.TemporaryDirectory() as tmp_dir:
# Write stream to temporary file
tar_path = os.path.join(tmp_dir, "temp.tar")
with open(tar_path, "wb") as f:
for chunk in stream:
f.write(chunk)
# Extract file
with tarfile.open(tar_path) as tar:
members = tar.getmembers()
if not members:
raise FileNotFoundError(f"Source file is empty: {src_path}")
# If destination is a directory, we should preserve relative path structure
if os.path.isdir(dst_path):
tar.extractall(dst_path)
else:
# If destination is a file, we only extract the source file's content
if len(members) > 1:
raise RuntimeError(
f"Source path is a directory but destination is a file: {src_path}"
)
with open(dst_path, "wb") as dst:
src_file = tar.extractfile(members[0])
if src_file is None:
raise RuntimeError(
f"Failed to extract file: {src_path}"
)
dst.write(src_file.read())
except docker.errors.NotFound:
raise FileNotFoundError(f"Source file not found: {src_path}")
except Exception as e:
raise RuntimeError(f"Failed to copy file: {e}")
async def copy_to(self, src_path: str, dst_path: str) -> None:
try:
if not os.path.exists(src_path):
raise FileNotFoundError(f"Source file not found: {src_path}")
# Create destination directory in container
resolved_dst = self._safe_resolve_path(dst_path)
container_dir = os.path.dirname(resolved_dst)
if container_dir:
await self.run_command(f"mkdir -p {container_dir}")
# Create tar file to upload
with tempfile.TemporaryDirectory() as tmp_dir:
tar_path = os.path.join(tmp_dir, "temp.tar")
with tarfile.open(tar_path, "w") as tar:
# Handle directory source path
if os.path.isdir(src_path):
os.path.basename(src_path.rstrip("/"))
for root, _, files in os.walk(src_path):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.join(
os.path.basename(dst_path),
os.path.relpath(file_path, src_path),
)
tar.add(file_path, arcname=arcname)
else:
# Add single file to tar
tar.add(src_path, arcname=os.path.basename(dst_path))
# Read tar file content
with open(tar_path, "rb") as f:
data = f.read()
# Upload to container
await asyncio.to_thread(
self.container.put_archive,
os.path.dirname(resolved_dst) or "/",
data,
)
# Verify file was created successfully
try:
await self.run_command(f"test -e {resolved_dst}")
except Exception:
raise RuntimeError(f"Failed to verify file creation: {dst_path}")
except FileNotFoundError:
raise
except Exception as e:
raise RuntimeError(f"Failed to copy file: {e}")
@staticmethod
async def _create_tar_stream(name: str, content: bytes) -> io.BytesIO:
tar_stream = io.BytesIO()
with tarfile.open(fileobj=tar_stream, mode="w") as tar:
tarinfo = tarfile.TarInfo(name=name)
tarinfo.size = len(content)
tar.addfile(tarinfo, io.BytesIO(content))
tar_stream.seek(0)
return tar_stream
@staticmethod
async def _read_from_tar(tar_stream) -> bytes:
with tempfile.NamedTemporaryFile() as tmp:
for chunk in tar_stream:
tmp.write(chunk)
tmp.seek(0)
with tarfile.open(fileobj=tmp) as tar:
member = tar.next()
if not member:
raise RuntimeError("Empty tar archive")
file_content = tar.extractfile(member)
if not file_content:
raise RuntimeError("Failed to extract file content")
return file_content.read()
async def cleanup(self) -> None:
errors = []
try:
if self.terminal:
try:
await self.terminal.close()
except Exception as e:
errors.append(f"Terminal cleanup error: {e}")
finally:
self.terminal = None
if self.container:
try:
await asyncio.to_thread(self.container.stop, timeout=5)
except Exception as e:
errors.append(f"Container stop error: {e}")
try:
await asyncio.to_thread(self.container.remove, force=True)
except Exception as e:
errors.append(f"Container remove error: {e}")
finally:
self.container = None
except Exception as e:
errors.append(f"General cleanup error: {e}")
if errors:
print(f"Warning: Errors during cleanup: {', '.join(errors)}")
async def __aenter__(self) -> "DockerSandbox":
return await self.create()
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
await self.cleanup() | --- +++ @@ -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 mapping configuration.
+ client: Docker client.
+ container: Docker container instance.
+ terminal: Container terminal interface.
+ """
def __init__(
self,
config: Optional[SandboxSettings] = None,
volume_bindings: Optional[Dict[str, str]] = None,
):
+ """Initializes a sandbox instance.
+
+ Args:
+ config: Sandbox configuration. Default configuration used if None.
+ volume_bindings: Volume mappings in {host_path: container_path} format.
+ """
self.config = config or SandboxSettings()
self.volume_bindings = volume_bindings or {}
self.client = docker.from_env()
@@ -29,6 +47,15 @@ self.terminal: Optional[AsyncDockerizedTerminal] = None
async def create(self) -> "DockerSandbox":
+ """Creates and starts the sandbox container.
+
+ Returns:
+ Current sandbox instance.
+
+ Raises:
+ docker.errors.APIError: If Docker API call fails.
+ RuntimeError: If container creation or startup fails.
+ """
try:
# Prepare container config
host_config = self.client.api.create_host_config(
@@ -76,6 +103,11 @@ raise RuntimeError(f"Failed to create sandbox: {e}") from e
def _prepare_volume_bindings(self) -> Dict[str, Dict[str, str]]:
+ """Prepares volume binding configuration.
+
+ Returns:
+ Volume binding configuration dictionary.
+ """
bindings = {}
# Create and add working directory mapping
@@ -90,6 +122,14 @@
@staticmethod
def _ensure_host_dir(path: str) -> str:
+ """Ensures directory exists on the host.
+
+ Args:
+ path: Directory path.
+
+ Returns:
+ Actual path on the host.
+ """
host_path = os.path.join(
tempfile.gettempdir(),
f"sandbox_{os.path.basename(path)}_{os.urandom(4).hex()}",
@@ -98,6 +138,19 @@ return host_path
async def run_command(self, cmd: str, timeout: Optional[int] = None) -> str:
+ """Runs a command in the sandbox.
+
+ Args:
+ cmd: Command to execute.
+ timeout: Timeout in seconds.
+
+ Returns:
+ Command output as string.
+
+ Raises:
+ RuntimeError: If sandbox not initialized or command execution fails.
+ TimeoutError: If command execution times out.
+ """
if not self.terminal:
raise RuntimeError("Sandbox not initialized")
@@ -111,6 +164,18 @@ )
async def read_file(self, path: str) -> str:
+ """Reads a file from the container.
+
+ Args:
+ path: File path.
+
+ Returns:
+ File contents as string.
+
+ Raises:
+ FileNotFoundError: If file does not exist.
+ RuntimeError: If read operation fails.
+ """
if not self.container:
raise RuntimeError("Sandbox not initialized")
@@ -131,6 +196,15 @@ raise RuntimeError(f"Failed to read file: {e}")
async def write_file(self, path: str, content: str) -> None:
+ """Writes content to a file in the container.
+
+ Args:
+ path: Target path.
+ content: File content.
+
+ Raises:
+ RuntimeError: If write operation fails.
+ """
if not self.container:
raise RuntimeError("Sandbox not initialized")
@@ -156,6 +230,17 @@ raise RuntimeError(f"Failed to write file: {e}")
def _safe_resolve_path(self, path: str) -> str:
+ """Safely resolves container path, preventing path traversal.
+
+ Args:
+ path: Original path.
+
+ Returns:
+ Resolved absolute path.
+
+ Raises:
+ ValueError: If path contains potentially unsafe patterns.
+ """
# Check for path traversal attempts
if ".." in path.split("/"):
raise ValueError("Path contains potentially unsafe patterns")
@@ -168,6 +253,16 @@ return resolved
async def copy_from(self, src_path: str, dst_path: str) -> None:
+ """Copies a file from the container.
+
+ Args:
+ src_path: Source file path (container).
+ dst_path: Destination path (host).
+
+ Raises:
+ FileNotFoundError: If source file does not exist.
+ RuntimeError: If copy operation fails.
+ """
try:
# Ensure destination file's parent directory exists
parent_dir = os.path.dirname(dst_path)
@@ -218,6 +313,16 @@ raise RuntimeError(f"Failed to copy file: {e}")
async def copy_to(self, src_path: str, dst_path: str) -> None:
+ """Copies a file to the container.
+
+ Args:
+ src_path: Source file path (host).
+ dst_path: Destination path (container).
+
+ Raises:
+ FileNotFoundError: If source file does not exist.
+ RuntimeError: If copy operation fails.
+ """
try:
if not os.path.exists(src_path):
raise FileNotFoundError(f"Source file not found: {src_path}")
@@ -271,6 +376,15 @@
@staticmethod
async def _create_tar_stream(name: str, content: bytes) -> io.BytesIO:
+ """Creates a tar file stream.
+
+ Args:
+ name: Filename.
+ content: File content.
+
+ Returns:
+ Tar file stream.
+ """
tar_stream = io.BytesIO()
with tarfile.open(fileobj=tar_stream, mode="w") as tar:
tarinfo = tarfile.TarInfo(name=name)
@@ -281,6 +395,17 @@
@staticmethod
async def _read_from_tar(tar_stream) -> bytes:
+ """Reads file content from a tar stream.
+
+ Args:
+ tar_stream: Tar file stream.
+
+ Returns:
+ File content.
+
+ Raises:
+ RuntimeError: If read operation fails.
+ """
with tempfile.NamedTemporaryFile() as tmp:
for chunk in tar_stream:
tmp.write(chunk)
@@ -298,6 +423,7 @@ return file_content.read()
async def cleanup(self) -> None:
+ """Cleans up sandbox resources."""
errors = []
try:
if self.terminal:
@@ -328,7 +454,9 @@ print(f"Warning: Errors during cleanup: {', '.join(errors)}")
async def __aenter__(self) -> "DockerSandbox":
+ """Async context manager entry."""
return await self.create()
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
- await self.cleanup()+ """Async context manager exit."""
+ await self.cleanup()
| 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
EXCLUDED_DIRS = {"node_modules", ".next", "dist", "build", ".git"}
# File extensions to exclude from operations
EXCLUDED_EXT = {
".ico",
".svg",
".png",
".jpg",
".jpeg",
".gif",
".bmp",
".tiff",
".webp",
".db",
".sql",
}
def should_exclude_file(rel_path: str) -> bool:
# Check filename
filename = os.path.basename(rel_path)
if filename in EXCLUDED_FILES:
return True
# Check directory
dir_path = os.path.dirname(rel_path)
if any(excluded in dir_path for excluded in EXCLUDED_DIRS):
return True
# Check extension
_, ext = os.path.splitext(filename)
if ext.lower() in EXCLUDED_EXT:
return True
return False
def clean_path(path: str, workspace_path: str = "/workspace") -> str:
# Remove any leading slash
path = path.lstrip("/")
# Remove workspace prefix if present
if path.startswith(workspace_path.lstrip("/")):
path = path[len(workspace_path.lstrip("/")) :]
# Remove workspace/ prefix if present
if path.startswith("workspace/"):
path = path[9:]
# Remove any remaining leading slash
path = path.lstrip("/")
return path | --- +++ @@ -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
+ """
# Check filename
filename = os.path.basename(rel_path)
if filename in EXCLUDED_FILES:
@@ -53,6 +61,15 @@
def clean_path(path: str, workspace_path: str = "/workspace") -> str:
+ """Clean and normalize a path to be relative to the workspace
+
+ Args:
+ path: The path to clean
+ workspace_path: The base workspace path to remove (default: "/workspace")
+
+ Returns:
+ The cleaned path, relative to the workspace
+ """
# Remove any leading slash
path = path.lstrip("/")
@@ -67,4 +84,4 @@ # Remove any remaining leading slash
path = path.lstrip("/")
- return path+ return path
| 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 copy_to(self, local_path: str, container_path: str) -> None:
...
async def read_file(self, path: str) -> str:
...
async def write_file(self, path: str, content: str) -> None:
...
class BaseSandboxClient(ABC):
@abstractmethod
async def create(
self,
config: Optional[SandboxSettings] = None,
volume_bindings: Optional[Dict[str, str]] = None,
) -> None:
@abstractmethod
async def run_command(self, command: str, timeout: Optional[int] = None) -> str:
@abstractmethod
async def copy_from(self, container_path: str, local_path: str) -> None:
@abstractmethod
async def copy_to(self, local_path: str, container_path: str) -> None:
@abstractmethod
async def read_file(self, path: str) -> str:
@abstractmethod
async def write_file(self, path: str, content: str) -> None:
@abstractmethod
async def cleanup(self) -> None:
class LocalSandboxClient(BaseSandboxClient):
def __init__(self):
self.sandbox: Optional[DockerSandbox] = None
async def create(
self,
config: Optional[SandboxSettings] = None,
volume_bindings: Optional[Dict[str, str]] = None,
) -> None:
self.sandbox = DockerSandbox(config, volume_bindings)
await self.sandbox.create()
async def run_command(self, command: str, timeout: Optional[int] = None) -> str:
if not self.sandbox:
raise RuntimeError("Sandbox not initialized")
return await self.sandbox.run_command(command, timeout)
async def copy_from(self, container_path: str, local_path: str) -> None:
if not self.sandbox:
raise RuntimeError("Sandbox not initialized")
await self.sandbox.copy_from(container_path, local_path)
async def copy_to(self, local_path: str, container_path: str) -> None:
if not self.sandbox:
raise RuntimeError("Sandbox not initialized")
await self.sandbox.copy_to(local_path, container_path)
async def read_file(self, path: str) -> str:
if not self.sandbox:
raise RuntimeError("Sandbox not initialized")
return await self.sandbox.read_file(path)
async def write_file(self, path: str, content: str) -> None:
if not self.sandbox:
raise RuntimeError("Sandbox not initialized")
await self.sandbox.write_file(path, content)
async def cleanup(self) -> None:
if self.sandbox:
await self.sandbox.cleanup()
self.sandbox = None
def create_sandbox_client() -> LocalSandboxClient:
return LocalSandboxClient()
SANDBOX_CLIENT = create_sandbox_client() | --- +++ @@ -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.
+ local_path: Local destination path.
+ """
...
async def copy_to(self, local_path: str, container_path: str) -> None:
+ """Copies file from local to container.
+
+ Args:
+ local_path: Local source file path.
+ container_path: Destination path in container.
+ """
...
async def read_file(self, path: str) -> str:
+ """Reads file content from container.
+
+ Args:
+ path: File path in container.
+
+ Returns:
+ str: File content.
+ """
...
async def write_file(self, path: str, content: str) -> None:
+ """Writes content to file in container.
+
+ Args:
+ path: File path in container.
+ content: Content to write.
+ """
...
class BaseSandboxClient(ABC):
+ """Base sandbox client interface."""
@abstractmethod
async def create(
@@ -28,29 +56,38 @@ config: Optional[SandboxSettings] = None,
volume_bindings: Optional[Dict[str, str]] = None,
) -> None:
+ """Creates sandbox."""
@abstractmethod
async def run_command(self, command: str, timeout: Optional[int] = None) -> str:
+ """Executes command."""
@abstractmethod
async def copy_from(self, container_path: str, local_path: str) -> None:
+ """Copies file from container."""
@abstractmethod
async def copy_to(self, local_path: str, container_path: str) -> None:
+ """Copies file to container."""
@abstractmethod
async def read_file(self, path: str) -> str:
+ """Reads file."""
@abstractmethod
async def write_file(self, path: str, content: str) -> None:
+ """Writes file."""
@abstractmethod
async def cleanup(self) -> None:
+ """Cleans up resources."""
class LocalSandboxClient(BaseSandboxClient):
+ """Local sandbox client implementation."""
def __init__(self):
+ """Initializes local sandbox client."""
self.sandbox: Optional[DockerSandbox] = None
async def create(
@@ -58,42 +95,107 @@ config: Optional[SandboxSettings] = None,
volume_bindings: Optional[Dict[str, str]] = None,
) -> None:
+ """Creates a sandbox.
+
+ Args:
+ config: Sandbox configuration.
+ volume_bindings: Volume mappings.
+
+ Raises:
+ RuntimeError: If sandbox creation fails.
+ """
self.sandbox = DockerSandbox(config, volume_bindings)
await self.sandbox.create()
async def run_command(self, command: str, timeout: Optional[int] = None) -> str:
+ """Runs command in sandbox.
+
+ Args:
+ command: Command to execute.
+ timeout: Execution timeout in seconds.
+
+ Returns:
+ Command output.
+
+ Raises:
+ RuntimeError: If sandbox not initialized.
+ """
if not self.sandbox:
raise RuntimeError("Sandbox not initialized")
return await self.sandbox.run_command(command, timeout)
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.
+ local_path: Local destination path.
+
+ Raises:
+ RuntimeError: If sandbox not initialized.
+ """
if not self.sandbox:
raise RuntimeError("Sandbox not initialized")
await self.sandbox.copy_from(container_path, local_path)
async def copy_to(self, local_path: str, container_path: str) -> None:
+ """Copies file from local to container.
+
+ Args:
+ local_path: Local source file path.
+ container_path: Destination path in container.
+
+ Raises:
+ RuntimeError: If sandbox not initialized.
+ """
if not self.sandbox:
raise RuntimeError("Sandbox not initialized")
await self.sandbox.copy_to(local_path, container_path)
async def read_file(self, path: str) -> str:
+ """Reads file from container.
+
+ Args:
+ path: File path in container.
+
+ Returns:
+ File content.
+
+ Raises:
+ RuntimeError: If sandbox not initialized.
+ """
if not self.sandbox:
raise RuntimeError("Sandbox not initialized")
return await self.sandbox.read_file(path)
async def write_file(self, path: str, content: str) -> None:
+ """Writes file to container.
+
+ Args:
+ path: File path in container.
+ content: File content.
+
+ Raises:
+ RuntimeError: If sandbox not initialized.
+ """
if not self.sandbox:
raise RuntimeError("Sandbox not initialized")
await self.sandbox.write_file(path, content)
async def cleanup(self) -> None:
+ """Cleans up resources."""
if self.sandbox:
await self.sandbox.cleanup()
self.sandbox = None
def create_sandbox_client() -> LocalSandboxClient:
+ """Creates a sandbox client.
+
+ Returns:
+ LocalSandboxClient: Sandbox client instance.
+ """
return LocalSandboxClient()
-SANDBOX_CLIENT = create_sandbox_client()+SANDBOX_CLIENT = create_sandbox_client()
| 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 import BaseTool, ToolResult
from app.tool.search import (
BaiduSearchEngine,
BingSearchEngine,
DuckDuckGoSearchEngine,
GoogleSearchEngine,
WebSearchEngine,
)
from app.tool.search.base import SearchItem
class SearchResult(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
position: int = Field(description="Position in search results")
url: str = Field(description="URL of the search result")
title: str = Field(default="", description="Title of the search result")
description: str = Field(
default="", description="Description or snippet of the search result"
)
source: str = Field(description="The search engine that provided this result")
raw_content: Optional[str] = Field(
default=None, description="Raw content from the search result page if available"
)
def __str__(self) -> str:
return f"{self.title} ({self.url})"
class SearchMetadata(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
total_results: int = Field(description="Total number of results found")
language: str = Field(description="Language code used for the search")
country: str = Field(description="Country code used for the search")
class SearchResponse(ToolResult):
query: str = Field(description="The search query that was executed")
results: List[SearchResult] = Field(
default_factory=list, description="List of search results"
)
metadata: Optional[SearchMetadata] = Field(
default=None, description="Metadata about the search"
)
@model_validator(mode="after")
def populate_output(self) -> "SearchResponse":
if self.error:
return self
result_text = [f"Search results for '{self.query}':"]
for i, result in enumerate(self.results, 1):
# Add title with position number
title = result.title.strip() or "No title"
result_text.append(f"\n{i}. {title}")
# Add URL with proper indentation
result_text.append(f" URL: {result.url}")
# Add description if available
if result.description.strip():
result_text.append(f" Description: {result.description}")
# Add content preview if available
if result.raw_content:
content_preview = result.raw_content[:1000].replace("\n", " ").strip()
if len(result.raw_content) > 1000:
content_preview += "..."
result_text.append(f" Content: {content_preview}")
# Add metadata at the bottom if available
if self.metadata:
result_text.extend(
[
f"\nMetadata:",
f"- Total results: {self.metadata.total_results}",
f"- Language: {self.metadata.language}",
f"- Country: {self.metadata.country}",
]
)
self.output = "\n".join(result_text)
return self
class WebContentFetcher:
@staticmethod
async def fetch_content(url: str, timeout: int = 10) -> Optional[str]:
headers = {
"WebSearch": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
try:
# Use asyncio to run requests in a thread pool
response = await asyncio.get_event_loop().run_in_executor(
None, lambda: requests.get(url, headers=headers, timeout=timeout)
)
if response.status_code != 200:
logger.warning(
f"Failed to fetch content from {url}: HTTP {response.status_code}"
)
return None
# Parse HTML with BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
# Remove script and style elements
for script in soup(["script", "style", "header", "footer", "nav"]):
script.extract()
# Get text content
text = soup.get_text(separator="\n", strip=True)
# Clean up whitespace and limit size (100KB max)
text = " ".join(text.split())
return text[:10000] if text else None
except Exception as e:
logger.warning(f"Error fetching content from {url}: {e}")
return None
class WebSearch(BaseTool):
name: str = "web_search"
description: str = """Search the web for real-time information about any topic.
This tool returns comprehensive search results with relevant information, URLs, titles, and descriptions.
If the primary search engine fails, it automatically falls back to alternative engines."""
parameters: dict = {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "(required) The search query to submit to the search engine.",
},
"num_results": {
"type": "integer",
"description": "(optional) The number of search results to return. Default is 5.",
"default": 5,
},
"lang": {
"type": "string",
"description": "(optional) Language code for search results (default: en).",
"default": "en",
},
"country": {
"type": "string",
"description": "(optional) Country code for search results (default: us).",
"default": "us",
},
"fetch_content": {
"type": "boolean",
"description": "(optional) Whether to fetch full content from result pages. Default is false.",
"default": False,
},
},
"required": ["query"],
}
_search_engine: dict[str, WebSearchEngine] = {
"google": GoogleSearchEngine(),
"baidu": BaiduSearchEngine(),
"duckduckgo": DuckDuckGoSearchEngine(),
"bing": BingSearchEngine(),
}
content_fetcher: WebContentFetcher = WebContentFetcher()
async def execute(
self,
query: str,
num_results: int = 5,
lang: Optional[str] = None,
country: Optional[str] = None,
fetch_content: bool = False,
) -> SearchResponse:
# Get settings from config
retry_delay = (
getattr(config.search_config, "retry_delay", 60)
if config.search_config
else 60
)
max_retries = (
getattr(config.search_config, "max_retries", 3)
if config.search_config
else 3
)
# Use config values for lang and country if not specified
if lang is None:
lang = (
getattr(config.search_config, "lang", "en")
if config.search_config
else "en"
)
if country is None:
country = (
getattr(config.search_config, "country", "us")
if config.search_config
else "us"
)
search_params = {"lang": lang, "country": country}
# Try searching with retries when all engines fail
for retry_count in range(max_retries + 1):
results = await self._try_all_engines(query, num_results, search_params)
if results:
# Fetch content if requested
if fetch_content:
results = await self._fetch_content_for_results(results)
# Return a successful structured response
return SearchResponse(
status="success",
query=query,
results=results,
metadata=SearchMetadata(
total_results=len(results),
language=lang,
country=country,
),
)
if retry_count < max_retries:
# All engines failed, wait and retry
logger.warning(
f"All search engines failed. Waiting {retry_delay} seconds before retry {retry_count + 1}/{max_retries}..."
)
await asyncio.sleep(retry_delay)
else:
logger.error(
f"All search engines failed after {max_retries} retries. Giving up."
)
# Return an error response
return SearchResponse(
query=query,
error="All search engines failed to return results after multiple retries.",
results=[],
)
async def _try_all_engines(
self, query: str, num_results: int, search_params: Dict[str, Any]
) -> List[SearchResult]:
engine_order = self._get_engine_order()
failed_engines = []
for engine_name in engine_order:
engine = self._search_engine[engine_name]
logger.info(f"🔎 Attempting search with {engine_name.capitalize()}...")
search_items = await self._perform_search_with_engine(
engine, query, num_results, search_params
)
if not search_items:
continue
if failed_engines:
logger.info(
f"Search successful with {engine_name.capitalize()} after trying: {', '.join(failed_engines)}"
)
# Transform search items into structured results
return [
SearchResult(
position=i + 1,
url=item.url,
title=item.title
or f"Result {i+1}", # Ensure we always have a title
description=item.description or "",
source=engine_name,
)
for i, item in enumerate(search_items)
]
if failed_engines:
logger.error(f"All search engines failed: {', '.join(failed_engines)}")
return []
async def _fetch_content_for_results(
self, results: List[SearchResult]
) -> List[SearchResult]:
if not results:
return []
# Create tasks for each result
tasks = [self._fetch_single_result_content(result) for result in results]
# Type annotation to help type checker
fetched_results = await asyncio.gather(*tasks)
# Explicit validation of return type
return [
(
result
if isinstance(result, SearchResult)
else SearchResult(**result.dict())
)
for result in fetched_results
]
async def _fetch_single_result_content(self, result: SearchResult) -> SearchResult:
if result.url:
content = await self.content_fetcher.fetch_content(result.url)
if content:
result.raw_content = content
return result
def _get_engine_order(self) -> List[str]:
preferred = (
getattr(config.search_config, "engine", "google").lower()
if config.search_config
else "google"
)
fallbacks = (
[engine.lower() for engine in config.search_config.fallback_engines]
if config.search_config
and hasattr(config.search_config, "fallback_engines")
else []
)
# Start with preferred engine, then fallbacks, then remaining engines
engine_order = [preferred] if preferred in self._search_engine else []
engine_order.extend(
[
fb
for fb in fallbacks
if fb in self._search_engine and fb not in engine_order
]
)
engine_order.extend([e for e in self._search_engine if e not in engine_order])
return engine_order
@retry(
stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=1, max=10)
)
async def _perform_search_with_engine(
self,
engine: WebSearchEngine,
query: str,
num_results: int,
search_params: Dict[str, Any],
) -> List[SearchItem]:
return await asyncio.get_event_loop().run_in_executor(
None,
lambda: list(
engine.perform_search(
query,
num_results=num_results,
lang=search_params.get("lang"),
country=search_params.get("country"),
)
),
)
if __name__ == "__main__":
web_search = WebSearch()
search_response = asyncio.run(
web_search.execute(
query="Python programming", fetch_content=True, num_results=1
)
)
print(search_response.to_tool_result()) | --- +++ @@ -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."""
return f"{self.title} ({self.url})"
class SearchMetadata(BaseModel):
+ """Metadata about the search operation."""
model_config = ConfigDict(arbitrary_types_allowed=True)
@@ -48,6 +51,7 @@
class SearchResponse(ToolResult):
+ """Structured response from the web search tool, inheriting ToolResult."""
query: str = Field(description="The search query that was executed")
results: List[SearchResult] = Field(
@@ -59,6 +63,7 @@
@model_validator(mode="after")
def populate_output(self) -> "SearchResponse":
+ """Populate output or error fields based on search results."""
if self.error:
return self
@@ -99,9 +104,20 @@
class WebContentFetcher:
+ """Utility class for fetching web content."""
@staticmethod
async def fetch_content(url: str, timeout: int = 10) -> Optional[str]:
+ """
+ Fetch and extract the main content from a webpage.
+
+ Args:
+ url: The URL to fetch content from
+ timeout: Request timeout in seconds
+
+ Returns:
+ Extracted text content or None if fetching fails
+ """
headers = {
"WebSearch": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
@@ -138,6 +154,7 @@
class WebSearch(BaseTool):
+ """Search the web for information using various search engines."""
name: str = "web_search"
description: str = """Search the web for real-time information about any topic.
@@ -189,6 +206,19 @@ country: Optional[str] = None,
fetch_content: bool = False,
) -> SearchResponse:
+ """
+ Execute a Web search and return detailed search results.
+
+ Args:
+ query: The search query to submit to the search engine
+ num_results: The number of search results to return (default: 5)
+ lang: Language code for search results (default from config)
+ country: Country code for search results (default from config)
+ fetch_content: Whether to fetch content from result pages (default: False)
+
+ Returns:
+ A structured response containing search results and metadata
+ """
# Get settings from config
retry_delay = (
getattr(config.search_config, "retry_delay", 60)
@@ -260,6 +290,7 @@ async def _try_all_engines(
self, query: str, num_results: int, search_params: Dict[str, Any]
) -> List[SearchResult]:
+ """Try all search engines in the configured order."""
engine_order = self._get_engine_order()
failed_engines = []
@@ -298,6 +329,7 @@ async def _fetch_content_for_results(
self, results: List[SearchResult]
) -> List[SearchResult]:
+ """Fetch and add web content to search results."""
if not results:
return []
@@ -318,6 +350,7 @@ ]
async def _fetch_single_result_content(self, result: SearchResult) -> SearchResult:
+ """Fetch content for a single search result."""
if result.url:
content = await self.content_fetcher.fetch_content(result.url)
if content:
@@ -325,6 +358,7 @@ return result
def _get_engine_order(self) -> List[str]:
+ """Determines the order in which to try search engines."""
preferred = (
getattr(config.search_config, "engine", "google").lower()
if config.search_config
@@ -360,6 +394,7 @@ num_results: int,
search_params: Dict[str, Any],
) -> List[SearchItem]:
+ """Execute search with the given engine and parameters."""
return await asyncio.get_event_loop().run_in_executor(
None,
lambda: list(
@@ -380,4 +415,4 @@ query="Python programming", fetch_content=True, num_results=1
)
)
- print(search_response.to_tool_result())+ print(search_response.to_tool_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 (
FileOperator,
LocalFileOperator,
PathLike,
SandboxFileOperator,
)
Command = Literal[
"view",
"create",
"str_replace",
"insert",
"undo_edit",
]
# Constants
SNIPPET_LINES: int = 4
MAX_RESPONSE_LEN: int = 16000
TRUNCATED_MESSAGE: str = (
"<response clipped><NOTE>To save on context only part of this file has been shown to you. "
"You should retry this tool after you have searched inside the file with `grep -n` "
"in order to find the line numbers of what you are looking for.</NOTE>"
)
# Tool description
_STR_REPLACE_EDITOR_DESCRIPTION = """Custom editing tool for viewing, creating and editing files
* State is persistent across command calls and discussions with the user
* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep
* The `create` command cannot be used if the specified `path` already exists as a file
* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`
* The `undo_edit` command will revert the last edit made to the file at `path`
Notes for using the `str_replace` command:
* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!
* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique
* The `new_str` parameter should contain the edited lines that should replace the `old_str`
"""
def maybe_truncate(
content: str, truncate_after: Optional[int] = MAX_RESPONSE_LEN
) -> str:
if not truncate_after or len(content) <= truncate_after:
return content
return content[:truncate_after] + TRUNCATED_MESSAGE
class StrReplaceEditor(BaseTool):
name: str = "str_replace_editor"
description: str = _STR_REPLACE_EDITOR_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"command": {
"description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.",
"enum": ["view", "create", "str_replace", "insert", "undo_edit"],
"type": "string",
},
"path": {
"description": "Absolute path to file or directory.",
"type": "string",
},
"file_text": {
"description": "Required parameter of `create` command, with the content of the file to be created.",
"type": "string",
},
"old_str": {
"description": "Required parameter of `str_replace` command containing the string in `path` to replace.",
"type": "string",
},
"new_str": {
"description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.",
"type": "string",
},
"insert_line": {
"description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.",
"type": "integer",
},
"view_range": {
"description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",
"items": {"type": "integer"},
"type": "array",
},
},
"required": ["command", "path"],
}
_file_history: DefaultDict[PathLike, List[str]] = defaultdict(list)
_local_operator: LocalFileOperator = LocalFileOperator()
_sandbox_operator: SandboxFileOperator = SandboxFileOperator()
# def _get_operator(self, use_sandbox: bool) -> FileOperator:
def _get_operator(self) -> FileOperator:
return (
self._sandbox_operator
if config.sandbox.use_sandbox
else self._local_operator
)
async def execute(
self,
*,
command: Command,
path: str,
file_text: str | None = None,
view_range: list[int] | None = None,
old_str: str | None = None,
new_str: str | None = None,
insert_line: int | None = None,
**kwargs: Any,
) -> str:
# Get the appropriate file operator
operator = self._get_operator()
# Validate path and command combination
await self.validate_path(command, Path(path), operator)
# Execute the appropriate command
if command == "view":
result = await self.view(path, view_range, operator)
elif command == "create":
if file_text is None:
raise ToolError("Parameter `file_text` is required for command: create")
await operator.write_file(path, file_text)
self._file_history[path].append(file_text)
result = ToolResult(output=f"File created successfully at: {path}")
elif command == "str_replace":
if old_str is None:
raise ToolError(
"Parameter `old_str` is required for command: str_replace"
)
result = await self.str_replace(path, old_str, new_str, operator)
elif command == "insert":
if insert_line is None:
raise ToolError(
"Parameter `insert_line` is required for command: insert"
)
if new_str is None:
raise ToolError("Parameter `new_str` is required for command: insert")
result = await self.insert(path, insert_line, new_str, operator)
elif command == "undo_edit":
result = await self.undo_edit(path, operator)
else:
# This should be caught by type checking, but we include it for safety
raise ToolError(
f'Unrecognized command {command}. The allowed commands for the {self.name} tool are: {", ".join(get_args(Command))}'
)
return str(result)
async def validate_path(
self, command: str, path: Path, operator: FileOperator
) -> None:
# Check if path is absolute
if not path.is_absolute():
raise ToolError(f"The path {path} is not an absolute path")
# Only check if path exists for non-create commands
if command != "create":
if not await operator.exists(path):
raise ToolError(
f"The path {path} does not exist. Please provide a valid path."
)
# Check if path is a directory
is_dir = await operator.is_directory(path)
if is_dir and command != "view":
raise ToolError(
f"The path {path} is a directory and only the `view` command can be used on directories"
)
# Check if file exists for create command
elif command == "create":
exists = await operator.exists(path)
if exists:
raise ToolError(
f"File already exists at: {path}. Cannot overwrite files using command `create`."
)
async def view(
self,
path: PathLike,
view_range: Optional[List[int]] = None,
operator: FileOperator = None,
) -> CLIResult:
# Determine if path is a directory
is_dir = await operator.is_directory(path)
if is_dir:
# Directory handling
if view_range:
raise ToolError(
"The `view_range` parameter is not allowed when `path` points to a directory."
)
return await self._view_directory(path, operator)
else:
# File handling
return await self._view_file(path, operator, view_range)
@staticmethod
async def _view_directory(path: PathLike, operator: FileOperator) -> CLIResult:
find_cmd = f"find {path} -maxdepth 2 -not -path '*/\\.*'"
# Execute command using the operator
returncode, stdout, stderr = await operator.run_command(find_cmd)
if not stderr:
stdout = (
f"Here's the files and directories up to 2 levels deep in {path}, "
f"excluding hidden items:\n{stdout}\n"
)
return CLIResult(output=stdout, error=stderr)
async def _view_file(
self,
path: PathLike,
operator: FileOperator,
view_range: Optional[List[int]] = None,
) -> CLIResult:
# Read file content
file_content = await operator.read_file(path)
init_line = 1
# Apply view range if specified
if view_range:
if len(view_range) != 2 or not all(isinstance(i, int) for i in view_range):
raise ToolError(
"Invalid `view_range`. It should be a list of two integers."
)
file_lines = file_content.split("\n")
n_lines_file = len(file_lines)
init_line, final_line = view_range
# Validate view range
if init_line < 1 or init_line > n_lines_file:
raise ToolError(
f"Invalid `view_range`: {view_range}. Its first element `{init_line}` should be "
f"within the range of lines of the file: {[1, n_lines_file]}"
)
if final_line > n_lines_file:
raise ToolError(
f"Invalid `view_range`: {view_range}. Its second element `{final_line}` should be "
f"smaller than the number of lines in the file: `{n_lines_file}`"
)
if final_line != -1 and final_line < init_line:
raise ToolError(
f"Invalid `view_range`: {view_range}. Its second element `{final_line}` should be "
f"larger or equal than its first `{init_line}`"
)
# Apply range
if final_line == -1:
file_content = "\n".join(file_lines[init_line - 1 :])
else:
file_content = "\n".join(file_lines[init_line - 1 : final_line])
# Format and return result
return CLIResult(
output=self._make_output(file_content, str(path), init_line=init_line)
)
async def str_replace(
self,
path: PathLike,
old_str: str,
new_str: Optional[str] = None,
operator: FileOperator = None,
) -> CLIResult:
# Read file content and expand tabs
file_content = (await operator.read_file(path)).expandtabs()
old_str = old_str.expandtabs()
new_str = new_str.expandtabs() if new_str is not None else ""
# Check if old_str is unique in the file
occurrences = file_content.count(old_str)
if occurrences == 0:
raise ToolError(
f"No replacement was performed, old_str `{old_str}` did not appear verbatim in {path}."
)
elif occurrences > 1:
# Find line numbers of occurrences
file_content_lines = file_content.split("\n")
lines = [
idx + 1
for idx, line in enumerate(file_content_lines)
if old_str in line
]
raise ToolError(
f"No replacement was performed. Multiple occurrences of old_str `{old_str}` "
f"in lines {lines}. Please ensure it is unique"
)
# Replace old_str with new_str
new_file_content = file_content.replace(old_str, new_str)
# Write the new content to the file
await operator.write_file(path, new_file_content)
# Save the original content to history
self._file_history[path].append(file_content)
# Create a snippet of the edited section
replacement_line = file_content.split(old_str)[0].count("\n")
start_line = max(0, replacement_line - SNIPPET_LINES)
end_line = replacement_line + SNIPPET_LINES + new_str.count("\n")
snippet = "\n".join(new_file_content.split("\n")[start_line : end_line + 1])
# Prepare the success message
success_msg = f"The file {path} has been edited. "
success_msg += self._make_output(
snippet, f"a snippet of {path}", start_line + 1
)
success_msg += "Review the changes and make sure they are as expected. Edit the file again if necessary."
return CLIResult(output=success_msg)
async def insert(
self,
path: PathLike,
insert_line: int,
new_str: str,
operator: FileOperator = None,
) -> CLIResult:
# Read and prepare content
file_text = (await operator.read_file(path)).expandtabs()
new_str = new_str.expandtabs()
file_text_lines = file_text.split("\n")
n_lines_file = len(file_text_lines)
# Validate insert_line
if insert_line < 0 or insert_line > n_lines_file:
raise ToolError(
f"Invalid `insert_line` parameter: {insert_line}. It should be within "
f"the range of lines of the file: {[0, n_lines_file]}"
)
# Perform insertion
new_str_lines = new_str.split("\n")
new_file_text_lines = (
file_text_lines[:insert_line]
+ new_str_lines
+ file_text_lines[insert_line:]
)
# Create a snippet for preview
snippet_lines = (
file_text_lines[max(0, insert_line - SNIPPET_LINES) : insert_line]
+ new_str_lines
+ file_text_lines[insert_line : insert_line + SNIPPET_LINES]
)
# Join lines and write to file
new_file_text = "\n".join(new_file_text_lines)
snippet = "\n".join(snippet_lines)
await operator.write_file(path, new_file_text)
self._file_history[path].append(file_text)
# Prepare success message
success_msg = f"The file {path} has been edited. "
success_msg += self._make_output(
snippet,
"a snippet of the edited file",
max(1, insert_line - SNIPPET_LINES + 1),
)
success_msg += "Review the changes and make sure they are as expected (correct indentation, no duplicate lines, etc). Edit the file again if necessary."
return CLIResult(output=success_msg)
async def undo_edit(
self, path: PathLike, operator: FileOperator = None
) -> CLIResult:
if not self._file_history[path]:
raise ToolError(f"No edit history found for {path}.")
old_text = self._file_history[path].pop()
await operator.write_file(path, old_text)
return CLIResult(
output=f"Last edit to {path} undone successfully. {self._make_output(old_text, str(path))}"
)
def _make_output(
self,
file_content: str,
file_descriptor: str,
init_line: int = 1,
expand_tabs: bool = True,
) -> str:
file_content = maybe_truncate(file_content)
if expand_tabs:
file_content = file_content.expandtabs()
# Add line numbers to each line
file_content = "\n".join(
[
f"{i + init_line:6}\t{line}"
for i, line in enumerate(file_content.split("\n"))
]
)
return (
f"Here's the result of running `cat -n` on {file_descriptor}:\n"
+ file_content
+ "\n"
) | --- +++ @@ -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 content exceeds the specified length."""
if not truncate_after or len(content) <= truncate_after:
return content
return content[:truncate_after] + TRUNCATED_MESSAGE
class StrReplaceEditor(BaseTool):
+ """A tool for viewing, creating, and editing files with sandbox support."""
name: str = "str_replace_editor"
description: str = _STR_REPLACE_EDITOR_DESCRIPTION
@@ -101,6 +104,7 @@
# def _get_operator(self, use_sandbox: bool) -> FileOperator:
def _get_operator(self) -> FileOperator:
+ """Get the appropriate file operator based on execution mode."""
return (
self._sandbox_operator
if config.sandbox.use_sandbox
@@ -119,6 +123,7 @@ insert_line: int | None = None,
**kwargs: Any,
) -> str:
+ """Execute a file operation command."""
# Get the appropriate file operator
operator = self._get_operator()
@@ -161,6 +166,7 @@ async def validate_path(
self, command: str, path: Path, operator: FileOperator
) -> None:
+ """Validate path and command combination based on execution environment."""
# Check if path is absolute
if not path.is_absolute():
raise ToolError(f"The path {path} is not an absolute path")
@@ -193,6 +199,7 @@ view_range: Optional[List[int]] = None,
operator: FileOperator = None,
) -> CLIResult:
+ """Display file or directory content."""
# Determine if path is a directory
is_dir = await operator.is_directory(path)
@@ -210,6 +217,7 @@
@staticmethod
async def _view_directory(path: PathLike, operator: FileOperator) -> CLIResult:
+ """Display directory contents."""
find_cmd = f"find {path} -maxdepth 2 -not -path '*/\\.*'"
# Execute command using the operator
@@ -229,6 +237,7 @@ operator: FileOperator,
view_range: Optional[List[int]] = None,
) -> CLIResult:
+ """Display file content, optionally within a specified line range."""
# Read file content
file_content = await operator.read_file(path)
init_line = 1
@@ -279,6 +288,7 @@ new_str: Optional[str] = None,
operator: FileOperator = None,
) -> CLIResult:
+ """Replace a unique string in a file with a new string."""
# Read file content and expand tabs
file_content = (await operator.read_file(path)).expandtabs()
old_str = old_str.expandtabs()
@@ -334,6 +344,7 @@ new_str: str,
operator: FileOperator = None,
) -> CLIResult:
+ """Insert text at a specific line in a file."""
# Read and prepare content
file_text = (await operator.read_file(path)).expandtabs()
new_str = new_str.expandtabs()
@@ -383,6 +394,7 @@ async def undo_edit(
self, path: PathLike, operator: FileOperator = None
) -> CLIResult:
+ """Revert the last edit made to a file."""
if not self._file_history[path]:
raise ToolError(f"No edit history found for {path}.")
@@ -400,6 +412,7 @@ init_line: int = 1,
expand_tabs: bool = True,
) -> str:
+ """Format file content for display with line numbers."""
file_content = maybe_truncate(file_content)
if expand_tabs:
file_content = file_content.expandtabs()
@@ -416,4 +429,4 @@ f"Here's the result of running `cat -n` on {file_descriptor}:\n"
+ file_content
+ "\n"
- )+ )
| 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, query, sessionId) -> str:
config = {"configurable": {"thread_id": sessionId}}
response = await self.run(query)
return self.get_agent_response(config, response)
async def stream(self, query: str) -> AsyncIterable[Dict[str, Any]]:
raise NotImplementedError("Streaming is not supported by Manus yet.")
def get_agent_response(self, config, agent_response):
return {
"is_task_complete": True,
"require_user_input": False,
"content": agent_response,
}
SUPPORTED_CONTENT_TYPES: ClassVar[List[str]] = ["text", "text/plain"] | --- +++ @@ -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: str) -> AsyncIterable[Dict[str, Any]]:
+ """Streaming is not supported by Manus."""
raise NotImplementedError("Streaming is not supported by Manus yet.")
def get_agent_response(self, config, agent_response):
@@ -27,4 +29,4 @@ "content": agent_response,
}
- SUPPORTED_CONTENT_TYPES: ClassVar[List[str]] = ["text", "text/plain"]+ SUPPORTED_CONTENT_TYPES: ClassVar[List[str]] = ["text", "text/plain"]
| 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 creating plans, updating plan steps, and tracking progress.
"""
class PlanningTool(BaseTool):
name: str = "planning"
description: str = _PLANNING_TOOL_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"command": {
"description": "The command to execute. Available commands: create, update, list, get, set_active, mark_step, delete.",
"enum": [
"create",
"update",
"list",
"get",
"set_active",
"mark_step",
"delete",
],
"type": "string",
},
"plan_id": {
"description": "Unique identifier for the plan. Required for create, update, set_active, and delete commands. Optional for get and mark_step (uses active plan if not specified).",
"type": "string",
},
"title": {
"description": "Title for the plan. Required for create command, optional for update command.",
"type": "string",
},
"steps": {
"description": "List of plan steps. Required for create command, optional for update command.",
"type": "array",
"items": {"type": "string"},
},
"step_index": {
"description": "Index of the step to update (0-based). Required for mark_step command.",
"type": "integer",
},
"step_status": {
"description": "Status to set for a step. Used with mark_step command.",
"enum": ["not_started", "in_progress", "completed", "blocked"],
"type": "string",
},
"step_notes": {
"description": "Additional notes for a step. Optional for mark_step command.",
"type": "string",
},
},
"required": ["command"],
"additionalProperties": False,
}
plans: dict = {} # Dictionary to store plans by plan_id
_current_plan_id: Optional[str] = None # Track the current active plan
async def execute(
self,
*,
command: Literal[
"create", "update", "list", "get", "set_active", "mark_step", "delete"
],
plan_id: Optional[str] = None,
title: Optional[str] = None,
steps: Optional[List[str]] = None,
step_index: Optional[int] = None,
step_status: Optional[
Literal["not_started", "in_progress", "completed", "blocked"]
] = None,
step_notes: Optional[str] = None,
**kwargs,
):
if command == "create":
return self._create_plan(plan_id, title, steps)
elif command == "update":
return self._update_plan(plan_id, title, steps)
elif command == "list":
return self._list_plans()
elif command == "get":
return self._get_plan(plan_id)
elif command == "set_active":
return self._set_active_plan(plan_id)
elif command == "mark_step":
return self._mark_step(plan_id, step_index, step_status, step_notes)
elif command == "delete":
return self._delete_plan(plan_id)
else:
raise ToolError(
f"Unrecognized command: {command}. Allowed commands are: create, update, list, get, set_active, mark_step, delete"
)
def _create_plan(
self, plan_id: Optional[str], title: Optional[str], steps: Optional[List[str]]
) -> ToolResult:
if not plan_id:
raise ToolError("Parameter `plan_id` is required for command: create")
if plan_id in self.plans:
raise ToolError(
f"A plan with ID '{plan_id}' already exists. Use 'update' to modify existing plans."
)
if not title:
raise ToolError("Parameter `title` is required for command: create")
if (
not steps
or not isinstance(steps, list)
or not all(isinstance(step, str) for step in steps)
):
raise ToolError(
"Parameter `steps` must be a non-empty list of strings for command: create"
)
# Create a new plan with initialized step statuses
plan = {
"plan_id": plan_id,
"title": title,
"steps": steps,
"step_statuses": ["not_started"] * len(steps),
"step_notes": [""] * len(steps),
}
self.plans[plan_id] = plan
self._current_plan_id = plan_id # Set as active plan
return ToolResult(
output=f"Plan created successfully with ID: {plan_id}\n\n{self._format_plan(plan)}"
)
def _update_plan(
self, plan_id: Optional[str], title: Optional[str], steps: Optional[List[str]]
) -> ToolResult:
if not plan_id:
raise ToolError("Parameter `plan_id` is required for command: update")
if plan_id not in self.plans:
raise ToolError(f"No plan found with ID: {plan_id}")
plan = self.plans[plan_id]
if title:
plan["title"] = title
if steps:
if not isinstance(steps, list) or not all(
isinstance(step, str) for step in steps
):
raise ToolError(
"Parameter `steps` must be a list of strings for command: update"
)
# Preserve existing step statuses for unchanged steps
old_steps = plan["steps"]
old_statuses = plan["step_statuses"]
old_notes = plan["step_notes"]
# Create new step statuses and notes
new_statuses = []
new_notes = []
for i, step in enumerate(steps):
# If the step exists at the same position in old steps, preserve status and notes
if i < len(old_steps) and step == old_steps[i]:
new_statuses.append(old_statuses[i])
new_notes.append(old_notes[i])
else:
new_statuses.append("not_started")
new_notes.append("")
plan["steps"] = steps
plan["step_statuses"] = new_statuses
plan["step_notes"] = new_notes
return ToolResult(
output=f"Plan updated successfully: {plan_id}\n\n{self._format_plan(plan)}"
)
def _list_plans(self) -> ToolResult:
if not self.plans:
return ToolResult(
output="No plans available. Create a plan with the 'create' command."
)
output = "Available plans:\n"
for plan_id, plan in self.plans.items():
current_marker = " (active)" if plan_id == self._current_plan_id else ""
completed = sum(
1 for status in plan["step_statuses"] if status == "completed"
)
total = len(plan["steps"])
progress = f"{completed}/{total} steps completed"
output += f"• {plan_id}{current_marker}: {plan['title']} - {progress}\n"
return ToolResult(output=output)
def _get_plan(self, plan_id: Optional[str]) -> ToolResult:
if not plan_id:
# If no plan_id is provided, use the current active plan
if not self._current_plan_id:
raise ToolError(
"No active plan. Please specify a plan_id or set an active plan."
)
plan_id = self._current_plan_id
if plan_id not in self.plans:
raise ToolError(f"No plan found with ID: {plan_id}")
plan = self.plans[plan_id]
return ToolResult(output=self._format_plan(plan))
def _set_active_plan(self, plan_id: Optional[str]) -> ToolResult:
if not plan_id:
raise ToolError("Parameter `plan_id` is required for command: set_active")
if plan_id not in self.plans:
raise ToolError(f"No plan found with ID: {plan_id}")
self._current_plan_id = plan_id
return ToolResult(
output=f"Plan '{plan_id}' is now the active plan.\n\n{self._format_plan(self.plans[plan_id])}"
)
def _mark_step(
self,
plan_id: Optional[str],
step_index: Optional[int],
step_status: Optional[str],
step_notes: Optional[str],
) -> ToolResult:
if not plan_id:
# If no plan_id is provided, use the current active plan
if not self._current_plan_id:
raise ToolError(
"No active plan. Please specify a plan_id or set an active plan."
)
plan_id = self._current_plan_id
if plan_id not in self.plans:
raise ToolError(f"No plan found with ID: {plan_id}")
if step_index is None:
raise ToolError("Parameter `step_index` is required for command: mark_step")
plan = self.plans[plan_id]
if step_index < 0 or step_index >= len(plan["steps"]):
raise ToolError(
f"Invalid step_index: {step_index}. Valid indices range from 0 to {len(plan['steps'])-1}."
)
if step_status and step_status not in [
"not_started",
"in_progress",
"completed",
"blocked",
]:
raise ToolError(
f"Invalid step_status: {step_status}. Valid statuses are: not_started, in_progress, completed, blocked"
)
if step_status:
plan["step_statuses"][step_index] = step_status
if step_notes:
plan["step_notes"][step_index] = step_notes
return ToolResult(
output=f"Step {step_index} updated in plan '{plan_id}'.\n\n{self._format_plan(plan)}"
)
def _delete_plan(self, plan_id: Optional[str]) -> ToolResult:
if not plan_id:
raise ToolError("Parameter `plan_id` is required for command: delete")
if plan_id not in self.plans:
raise ToolError(f"No plan found with ID: {plan_id}")
del self.plans[plan_id]
# If the deleted plan was the active plan, clear the active plan
if self._current_plan_id == plan_id:
self._current_plan_id = None
return ToolResult(output=f"Plan '{plan_id}' has been deleted.")
def _format_plan(self, plan: Dict) -> str:
output = f"Plan: {plan['title']} (ID: {plan['plan_id']})\n"
output += "=" * len(output) + "\n\n"
# Calculate progress statistics
total_steps = len(plan["steps"])
completed = sum(1 for status in plan["step_statuses"] if status == "completed")
in_progress = sum(
1 for status in plan["step_statuses"] if status == "in_progress"
)
blocked = sum(1 for status in plan["step_statuses"] if status == "blocked")
not_started = sum(
1 for status in plan["step_statuses"] if status == "not_started"
)
output += f"Progress: {completed}/{total_steps} steps completed "
if total_steps > 0:
percentage = (completed / total_steps) * 100
output += f"({percentage:.1f}%)\n"
else:
output += "(0%)\n"
output += f"Status: {completed} completed, {in_progress} in progress, {blocked} blocked, {not_started} not started\n\n"
output += "Steps:\n"
# Add each step with its status and notes
for i, (step, status, notes) in enumerate(
zip(plan["steps"], plan["step_statuses"], plan["step_notes"])
):
status_symbol = {
"not_started": "[ ]",
"in_progress": "[→]",
"completed": "[✓]",
"blocked": "[!]",
}.get(status, "[ ]")
output += f"{i}. {status_symbol} {step}\n"
if notes:
output += f" Notes: {notes}\n"
return output | --- +++ @@ -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"
description: str = _PLANNING_TOOL_DESCRIPTION
@@ -81,6 +85,18 @@ step_notes: Optional[str] = None,
**kwargs,
):
+ """
+ Execute the planning tool with the given command and parameters.
+
+ Parameters:
+ - command: The operation to perform
+ - plan_id: Unique identifier for the plan
+ - title: Title for the plan (used with create command)
+ - steps: List of steps for the plan (used with create command)
+ - step_index: Index of the step to update (used with mark_step command)
+ - step_status: Status to set for a step (used with mark_step command)
+ - step_notes: Additional notes for a step (used with mark_step command)
+ """
if command == "create":
return self._create_plan(plan_id, title, steps)
@@ -104,6 +120,7 @@ def _create_plan(
self, plan_id: Optional[str], title: Optional[str], steps: Optional[List[str]]
) -> ToolResult:
+ """Create a new plan with the given ID, title, and steps."""
if not plan_id:
raise ToolError("Parameter `plan_id` is required for command: create")
@@ -143,6 +160,7 @@ def _update_plan(
self, plan_id: Optional[str], title: Optional[str], steps: Optional[List[str]]
) -> ToolResult:
+ """Update an existing plan with new title or steps."""
if not plan_id:
raise ToolError("Parameter `plan_id` is required for command: update")
@@ -189,6 +207,7 @@ )
def _list_plans(self) -> ToolResult:
+ """List all available plans."""
if not self.plans:
return ToolResult(
output="No plans available. Create a plan with the 'create' command."
@@ -207,6 +226,7 @@ return ToolResult(output=output)
def _get_plan(self, plan_id: Optional[str]) -> ToolResult:
+ """Get details of a specific plan."""
if not plan_id:
# If no plan_id is provided, use the current active plan
if not self._current_plan_id:
@@ -222,6 +242,7 @@ return ToolResult(output=self._format_plan(plan))
def _set_active_plan(self, plan_id: Optional[str]) -> ToolResult:
+ """Set a plan as the active plan."""
if not plan_id:
raise ToolError("Parameter `plan_id` is required for command: set_active")
@@ -240,6 +261,7 @@ step_status: Optional[str],
step_notes: Optional[str],
) -> ToolResult:
+ """Mark a step with a specific status and optional notes."""
if not plan_id:
# If no plan_id is provided, use the current active plan
if not self._current_plan_id:
@@ -282,6 +304,7 @@ )
def _delete_plan(self, plan_id: Optional[str]) -> ToolResult:
+ """Delete a plan."""
if not plan_id:
raise ToolError("Parameter `plan_id` is required for command: delete")
@@ -297,6 +320,7 @@ return ToolResult(output=f"Plan '{plan_id}' has been deleted.")
def _format_plan(self, plan: Dict) -> str:
+ """Format a plan for display."""
output = f"Plan: {plan['title']} (ID: {plan['plan_id']})\n"
output += "=" * len(output) + "\n\n"
@@ -336,4 +360,4 @@ if notes:
output += f" Notes: {notes}\n"
- return output+ return output
| 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()
self.container_id = container_id
self.exec_id = None
self.socket = None
async def create(self, working_dir: str, env_vars: Dict[str, str]) -> None:
startup_command = [
"bash",
"-c",
f"cd {working_dir} && "
"PROMPT_COMMAND='' "
"PS1='$ ' "
"exec bash --norc --noprofile",
]
exec_data = self.api.exec_create(
self.container_id,
startup_command,
stdin=True,
tty=True,
stdout=True,
stderr=True,
privileged=True,
user="root",
environment={**env_vars, "TERM": "dumb", "PS1": "$ ", "PROMPT_COMMAND": ""},
)
self.exec_id = exec_data["Id"]
socket_data = self.api.exec_start(
self.exec_id, socket=True, tty=True, stream=True, demux=True
)
if hasattr(socket_data, "_sock"):
self.socket = socket_data._sock
self.socket.setblocking(False)
else:
raise RuntimeError("Failed to get socket connection")
await self._read_until_prompt()
async def close(self) -> None:
try:
if self.socket:
# Send exit command to close bash session
try:
self.socket.sendall(b"exit\n")
# Allow time for command execution
await asyncio.sleep(0.1)
except:
pass # Ignore sending errors, continue cleanup
# Close socket connection
try:
self.socket.shutdown(socket.SHUT_RDWR)
except:
pass # Some platforms may not support shutdown
self.socket.close()
self.socket = None
if self.exec_id:
try:
# Check exec instance status
exec_inspect = self.api.exec_inspect(self.exec_id)
if exec_inspect.get("Running", False):
# If still running, wait for it to complete
await asyncio.sleep(0.5)
except:
pass # Ignore inspection errors, continue cleanup
self.exec_id = None
except Exception as e:
# Log error but don't raise, ensure cleanup continues
print(f"Warning: Error during session cleanup: {e}")
async def _read_until_prompt(self) -> str:
buffer = b""
while b"$ " not in buffer:
try:
chunk = self.socket.recv(4096)
if chunk:
buffer += chunk
except socket.error as e:
if e.errno == socket.EWOULDBLOCK:
await asyncio.sleep(0.1)
continue
raise
return buffer.decode("utf-8")
async def execute(self, command: str, timeout: Optional[int] = None) -> str:
if not self.socket:
raise RuntimeError("Session not initialized")
try:
# Sanitize command to prevent shell injection
sanitized_command = self._sanitize_command(command)
full_command = f"{sanitized_command}\necho $?\n"
self.socket.sendall(full_command.encode())
async def read_output() -> str:
buffer = b""
result_lines = []
command_sent = False
while True:
try:
chunk = self.socket.recv(4096)
if not chunk:
break
buffer += chunk
lines = buffer.split(b"\n")
buffer = lines[-1]
lines = lines[:-1]
for line in lines:
line = line.rstrip(b"\r")
if not command_sent:
command_sent = True
continue
if line.strip() == b"echo $?" or line.strip().isdigit():
continue
if line.strip():
result_lines.append(line)
if buffer.endswith(b"$ "):
break
except socket.error as e:
if e.errno == socket.EWOULDBLOCK:
await asyncio.sleep(0.1)
continue
raise
output = b"\n".join(result_lines).decode("utf-8")
output = re.sub(r"\n\$ echo \$\$?.*$", "", output)
return output
if timeout:
result = await asyncio.wait_for(read_output(), timeout)
else:
result = await read_output()
return result.strip()
except asyncio.TimeoutError:
raise TimeoutError(f"Command execution timed out after {timeout} seconds")
except Exception as e:
raise RuntimeError(f"Failed to execute command: {e}")
def _sanitize_command(self, command: str) -> str:
# Additional checks for specific risky commands
risky_commands = [
"rm -rf /",
"rm -rf /*",
"mkfs",
"dd if=/dev/zero",
":(){:|:&};:",
"chmod -R 777 /",
"chown -R",
]
for risky in risky_commands:
if risky in command.lower():
raise ValueError(
f"Command contains potentially dangerous operation: {risky}"
)
return command
class AsyncDockerizedTerminal:
def __init__(
self,
container: Union[str, Container],
working_dir: str = "/workspace",
env_vars: Optional[Dict[str, str]] = None,
default_timeout: int = 60,
) -> None:
self.client = docker.from_env()
self.container = (
container
if isinstance(container, Container)
else self.client.containers.get(container)
)
self.working_dir = working_dir
self.env_vars = env_vars or {}
self.default_timeout = default_timeout
self.session = None
async def init(self) -> None:
await self._ensure_workdir()
self.session = DockerSession(self.container.id)
await self.session.create(self.working_dir, self.env_vars)
async def _ensure_workdir(self) -> None:
try:
await self._exec_simple(f"mkdir -p {self.working_dir}")
except APIError as e:
raise RuntimeError(f"Failed to create working directory: {e}")
async def _exec_simple(self, cmd: str) -> Tuple[int, str]:
result = await asyncio.to_thread(
self.container.exec_run, cmd, environment=self.env_vars
)
return result.exit_code, result.output.decode("utf-8")
async def run_command(self, cmd: str, timeout: Optional[int] = None) -> str:
if not self.session:
raise RuntimeError("Terminal not initialized")
return await self.session.execute(cmd, timeout=timeout or self.default_timeout)
async def close(self) -> None:
if self.session:
await self.session.close()
async def __aenter__(self) -> "AsyncDockerizedTerminal":
await self.init()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
await self.close() | --- +++ @@ -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: str) -> None:
+ """Initializes a Docker session.
+
+ Args:
+ container_id: ID of the Docker container.
+ """
self.api = APIClient()
self.container_id = container_id
self.exec_id = None
self.socket = None
async def create(self, working_dir: str, env_vars: Dict[str, str]) -> None:
+ """Creates an interactive session with the container.
+
+ Args:
+ working_dir: Working directory inside the container.
+ env_vars: Environment variables to set.
+
+ Raises:
+ RuntimeError: If socket connection fails.
+ """
startup_command = [
"bash",
"-c",
@@ -53,6 +73,12 @@ await self._read_until_prompt()
async def close(self) -> None:
+ """Cleans up session resources.
+
+ 1. Sends exit command
+ 2. Closes socket connection
+ 3. Checks and cleans up exec instance
+ """
try:
if self.socket:
# Send exit command to close bash session
@@ -89,6 +115,14 @@ print(f"Warning: Error during session cleanup: {e}")
async def _read_until_prompt(self) -> str:
+ """Reads output until prompt is found.
+
+ Returns:
+ String containing output up to the prompt.
+
+ Raises:
+ socket.error: If socket communication fails.
+ """
buffer = b""
while b"$ " not in buffer:
try:
@@ -103,6 +137,19 @@ return buffer.decode("utf-8")
async def execute(self, command: str, timeout: Optional[int] = None) -> str:
+ """Executes a command and returns cleaned output.
+
+ Args:
+ command: Shell command to execute.
+ timeout: Maximum execution time in seconds.
+
+ Returns:
+ Command output as string with prompt markers removed.
+
+ Raises:
+ RuntimeError: If session not initialized or execution fails.
+ TimeoutError: If command execution exceeds timeout.
+ """
if not self.socket:
raise RuntimeError("Session not initialized")
@@ -169,6 +216,17 @@ raise RuntimeError(f"Failed to execute command: {e}")
def _sanitize_command(self, command: str) -> str:
+ """Sanitizes the command string to prevent shell injection.
+
+ Args:
+ command: Raw command string.
+
+ Returns:
+ Sanitized command string.
+
+ Raises:
+ ValueError: If command contains potentially dangerous patterns.
+ """
# Additional checks for specific risky commands
risky_commands = [
@@ -198,6 +256,14 @@ env_vars: Optional[Dict[str, str]] = None,
default_timeout: int = 60,
) -> None:
+ """Initializes an asynchronous terminal for Docker containers.
+
+ Args:
+ container: Docker container ID or Container object.
+ working_dir: Working directory inside the container.
+ env_vars: Environment variables to set.
+ default_timeout: Default command execution timeout in seconds.
+ """
self.client = docker.from_env()
self.container = (
container
@@ -210,36 +276,71 @@ self.session = None
async def init(self) -> None:
+ """Initializes the terminal environment.
+
+ Ensures working directory exists and creates an interactive session.
+
+ Raises:
+ RuntimeError: If initialization fails.
+ """
await self._ensure_workdir()
self.session = DockerSession(self.container.id)
await self.session.create(self.working_dir, self.env_vars)
async def _ensure_workdir(self) -> None:
+ """Ensures working directory exists in container.
+
+ Raises:
+ RuntimeError: If directory creation fails.
+ """
try:
await self._exec_simple(f"mkdir -p {self.working_dir}")
except APIError as e:
raise RuntimeError(f"Failed to create working directory: {e}")
async def _exec_simple(self, cmd: str) -> Tuple[int, str]:
+ """Executes a simple command using Docker's exec_run.
+
+ Args:
+ cmd: Command to execute.
+
+ Returns:
+ Tuple of (exit_code, output).
+ """
result = await asyncio.to_thread(
self.container.exec_run, cmd, environment=self.env_vars
)
return result.exit_code, result.output.decode("utf-8")
async def run_command(self, cmd: str, timeout: Optional[int] = None) -> str:
+ """Runs a command in the container with timeout.
+
+ Args:
+ cmd: Shell command to execute.
+ timeout: Maximum execution time in seconds.
+
+ Returns:
+ Command output as string.
+
+ Raises:
+ RuntimeError: If terminal not initialized.
+ """
if not self.session:
raise RuntimeError("Terminal not initialized")
return await self.session.execute(cmd, timeout=timeout or self.default_timeout)
async def close(self) -> None:
+ """Closes the terminal session."""
if self.session:
await self.session.close()
async def __aenter__(self) -> "AsyncDockerizedTerminal":
+ """Async context manager entry."""
await self.init()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
- await self.close()+ """Async context manager exit."""
+ await self.close()
| 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
self.agent = MCPAgent()
async def initialize(
self,
connection_type: str,
server_url: str | None = None,
) -> None:
logger.info(f"Initializing MCPAgent with {connection_type} connection...")
if connection_type == "stdio":
await self.agent.initialize(
connection_type="stdio",
command=sys.executable,
args=["-m", self.server_reference],
)
else: # sse
await self.agent.initialize(connection_type="sse", server_url=server_url)
logger.info(f"Connected to MCP server via {connection_type}")
async def run_interactive(self) -> None:
print("\nMCP Agent Interactive Mode (type 'exit' to quit)\n")
while True:
user_input = input("\nEnter your request: ")
if user_input.lower() in ["exit", "quit", "q"]:
break
response = await self.agent.run(user_input)
print(f"\nAgent: {response}")
async def run_single_prompt(self, prompt: str) -> None:
await self.agent.run(prompt)
async def run_default(self) -> None:
prompt = input("Enter your prompt: ")
if not prompt.strip():
logger.warning("Empty prompt provided.")
return
logger.warning("Processing your request...")
await self.agent.run(prompt)
logger.info("Request processing completed.")
async def cleanup(self) -> None:
await self.agent.cleanup()
logger.info("Session ended")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Run the MCP Agent")
parser.add_argument(
"--connection",
"-c",
choices=["stdio", "sse"],
default="stdio",
help="Connection type: stdio or sse",
)
parser.add_argument(
"--server-url",
default="http://127.0.0.1:8000/sse",
help="URL for SSE connection",
)
parser.add_argument(
"--interactive", "-i", action="store_true", help="Run in interactive mode"
)
parser.add_argument("--prompt", "-p", help="Single prompt to execute and exit")
return parser.parse_args()
async def run_mcp() -> None:
args = parse_args()
runner = MCPRunner()
try:
await runner.initialize(args.connection, args.server_url)
if args.prompt:
await runner.run_single_prompt(args.prompt)
elif args.interactive:
await runner.run_interactive()
else:
await runner.run_default()
except KeyboardInterrupt:
logger.info("Program interrupted by user")
except Exception as e:
logger.error(f"Error running MCPAgent: {str(e)}", exc_info=True)
sys.exit(1)
finally:
await runner.cleanup()
if __name__ == "__main__":
asyncio.run(run_mcp()) | --- +++ @@ -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:
+ """Initialize the MCP agent with the appropriate connection."""
logger.info(f"Initializing MCPAgent with {connection_type} connection...")
if connection_type == "stdio":
@@ -34,6 +36,7 @@ logger.info(f"Connected to MCP server via {connection_type}")
async def run_interactive(self) -> None:
+ """Run the agent in interactive mode."""
print("\nMCP Agent Interactive Mode (type 'exit' to quit)\n")
while True:
user_input = input("\nEnter your request: ")
@@ -43,9 +46,11 @@ print(f"\nAgent: {response}")
async def run_single_prompt(self, prompt: str) -> None:
+ """Run the agent with a single prompt."""
await self.agent.run(prompt)
async def run_default(self) -> None:
+ """Run the agent in default mode."""
prompt = input("Enter your prompt: ")
if not prompt.strip():
logger.warning("Empty prompt provided.")
@@ -56,11 +61,13 @@ logger.info("Request processing completed.")
async def cleanup(self) -> None:
+ """Clean up agent resources."""
await self.agent.cleanup()
logger.info("Session ended")
def parse_args() -> argparse.Namespace:
+ """Parse command line arguments."""
parser = argparse.ArgumentParser(description="Run the MCP Agent")
parser.add_argument(
"--connection",
@@ -82,6 +89,7 @@
async def run_mcp() -> None:
+ """Main entry point for the MCP runner."""
args = parse_args()
runner = MCPRunner()
@@ -105,4 +113,4 @@
if __name__ == "__main__":
- asyncio.run(run_mcp())+ asyncio.run(run_mcp())
| 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_DESCRIPTION = """\
A sandbox-based file system tool that allows file operations in a secure sandboxed environment.
* This tool provides commands for creating, reading, updating, and deleting files in the workspace
* All operations are performed relative to the /workspace directory for security
* Use this when you need to manage files, edit code, or manipulate file contents in a sandbox
* Each action requires specific parameters as defined in the tool's dependencies
Key capabilities include:
* File creation: Create new files with specified content and permissions
* File modification: Replace specific strings or completely rewrite files
* File deletion: Remove files from the workspace
* File reading: Read file contents with optional line range specification
"""
class SandboxFilesTool(SandboxToolsBase):
name: str = "sandbox_files"
description: str = _FILES_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": [
"create_file",
"str_replace",
"full_file_rewrite",
"delete_file",
],
"description": "The file operation to perform",
},
"file_path": {
"type": "string",
"description": "Path to the file, relative to /workspace (e.g., 'src/main.py')",
},
"file_contents": {
"type": "string",
"description": "Content to write to the file",
},
"old_str": {
"type": "string",
"description": "Text to be replaced (must appear exactly once)",
},
"new_str": {
"type": "string",
"description": "Replacement text",
},
"permissions": {
"type": "string",
"description": "File permissions in octal format (e.g., '644')",
"default": "644",
},
},
"required": ["action"],
"dependencies": {
"create_file": ["file_path", "file_contents"],
"str_replace": ["file_path", "old_str", "new_str"],
"full_file_rewrite": ["file_path", "file_contents"],
"delete_file": ["file_path"],
},
}
SNIPPET_LINES: int = Field(default=4, exclude=True)
# workspace_path: str = Field(default="/workspace", exclude=True)
# sandbox: Optional[Sandbox] = Field(default=None, exclude=True)
def __init__(
self, sandbox: Optional[Sandbox] = None, thread_id: Optional[str] = None, **data
):
super().__init__(**data)
if sandbox is not None:
self._sandbox = sandbox
def clean_path(self, path: str) -> str:
return clean_path(path, self.workspace_path)
def _should_exclude_file(self, rel_path: str) -> bool:
return should_exclude_file(rel_path)
def _file_exists(self, path: str) -> bool:
try:
self.sandbox.fs.get_file_info(path)
return True
except Exception:
return False
async def get_workspace_state(self) -> dict:
files_state = {}
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
files = self.sandbox.fs.list_files(self.workspace_path)
for file_info in files:
rel_path = file_info.name
# Skip excluded files and directories
if self._should_exclude_file(rel_path) or file_info.is_dir:
continue
try:
full_path = f"{self.workspace_path}/{rel_path}"
content = self.sandbox.fs.download_file(full_path).decode()
files_state[rel_path] = {
"content": content,
"is_dir": file_info.is_dir,
"size": file_info.size,
"modified": file_info.mod_time,
}
except Exception as e:
print(f"Error reading file {rel_path}: {e}")
except UnicodeDecodeError:
print(f"Skipping binary file: {rel_path}")
return files_state
except Exception as e:
print(f"Error getting workspace state: {str(e)}")
return {}
async def execute(
self,
action: str,
file_path: Optional[str] = None,
file_contents: Optional[str] = None,
old_str: Optional[str] = None,
new_str: Optional[str] = None,
permissions: Optional[str] = "644",
**kwargs,
) -> ToolResult:
async with asyncio.Lock():
try:
# File creation
if action == "create_file":
if not file_path or not file_contents:
return self.fail_response(
"file_path and file_contents are required for create_file"
)
return await self._create_file(
file_path, file_contents, permissions
)
# String replacement
elif action == "str_replace":
if not file_path or not old_str or not new_str:
return self.fail_response(
"file_path, old_str, and new_str are required for str_replace"
)
return await self._str_replace(file_path, old_str, new_str)
# Full file rewrite
elif action == "full_file_rewrite":
if not file_path or not file_contents:
return self.fail_response(
"file_path and file_contents are required for full_file_rewrite"
)
return await self._full_file_rewrite(
file_path, file_contents, permissions
)
# File deletion
elif action == "delete_file":
if not file_path:
return self.fail_response(
"file_path is required for delete_file"
)
return await self._delete_file(file_path)
else:
return self.fail_response(f"Unknown action: {action}")
except Exception as e:
logger.error(f"Error executing file action: {e}")
return self.fail_response(f"Error executing file action: {e}")
async def _create_file(
self, file_path: str, file_contents: str, permissions: str = "644"
) -> ToolResult:
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
file_path = self.clean_path(file_path)
full_path = f"{self.workspace_path}/{file_path}"
if self._file_exists(full_path):
return self.fail_response(
f"File '{file_path}' already exists. Use full_file_rewrite to modify existing files."
)
# Create parent directories if needed
parent_dir = "/".join(full_path.split("/")[:-1])
if parent_dir:
self.sandbox.fs.create_folder(parent_dir, "755")
# Write the file content
self.sandbox.fs.upload_file(file_contents.encode(), full_path)
self.sandbox.fs.set_file_permissions(full_path, permissions)
message = f"File '{file_path}' created successfully."
# Check if index.html was created and add 8080 server info (only in root workspace)
if file_path.lower() == "index.html":
try:
website_link = self.sandbox.get_preview_link(8080)
website_url = (
website_link.url
if hasattr(website_link, "url")
else str(website_link).split("url='")[1].split("'")[0]
)
message += f"\n\n[Auto-detected index.html - HTTP server available at: {website_url}]"
message += "\n[Note: Use the provided HTTP server URL above instead of starting a new server]"
except Exception as e:
logger.warning(
f"Failed to get website URL for index.html: {str(e)}"
)
return self.success_response(message)
except Exception as e:
return self.fail_response(f"Error creating file: {str(e)}")
async def _str_replace(
self, file_path: str, old_str: str, new_str: str
) -> ToolResult:
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
file_path = self.clean_path(file_path)
full_path = f"{self.workspace_path}/{file_path}"
if not self._file_exists(full_path):
return self.fail_response(f"File '{file_path}' does not exist")
content = self.sandbox.fs.download_file(full_path).decode()
old_str = old_str.expandtabs()
new_str = new_str.expandtabs()
occurrences = content.count(old_str)
if occurrences == 0:
return self.fail_response(f"String '{old_str}' not found in file")
if occurrences > 1:
lines = [
i + 1
for i, line in enumerate(content.split("\n"))
if old_str in line
]
return self.fail_response(
f"Multiple occurrences found in lines {lines}. Please ensure string is unique"
)
# Perform replacement
new_content = content.replace(old_str, new_str)
self.sandbox.fs.upload_file(new_content.encode(), full_path)
# Show snippet around the edit
replacement_line = content.split(old_str)[0].count("\n")
start_line = max(0, replacement_line - self.SNIPPET_LINES)
end_line = replacement_line + self.SNIPPET_LINES + new_str.count("\n")
snippet = "\n".join(new_content.split("\n")[start_line : end_line + 1])
message = f"Replacement successful."
return self.success_response(message)
except Exception as e:
return self.fail_response(f"Error replacing string: {str(e)}")
async def _full_file_rewrite(
self, file_path: str, file_contents: str, permissions: str = "644"
) -> ToolResult:
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
file_path = self.clean_path(file_path)
full_path = f"{self.workspace_path}/{file_path}"
if not self._file_exists(full_path):
return self.fail_response(
f"File '{file_path}' does not exist. Use create_file to create a new file."
)
self.sandbox.fs.upload_file(file_contents.encode(), full_path)
self.sandbox.fs.set_file_permissions(full_path, permissions)
message = f"File '{file_path}' completely rewritten successfully."
# Check if index.html was rewritten and add 8080 server info (only in root workspace)
if file_path.lower() == "index.html":
try:
website_link = self.sandbox.get_preview_link(8080)
website_url = (
website_link.url
if hasattr(website_link, "url")
else str(website_link).split("url='")[1].split("'")[0]
)
message += f"\n\n[Auto-detected index.html - HTTP server available at: {website_url}]"
message += "\n[Note: Use the provided HTTP server URL above instead of starting a new server]"
except Exception as e:
logger.warning(
f"Failed to get website URL for index.html: {str(e)}"
)
return self.success_response(message)
except Exception as e:
return self.fail_response(f"Error rewriting file: {str(e)}")
async def _delete_file(self, file_path: str) -> ToolResult:
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
file_path = self.clean_path(file_path)
full_path = f"{self.workspace_path}/{file_path}"
if not self._file_exists(full_path):
return self.fail_response(f"File '{file_path}' does not exist")
self.sandbox.fs.delete_file(full_path)
return self.success_response(f"File '{file_path}' deleted successfully.")
except Exception as e:
return self.fail_response(f"Error deleting file: {str(e)}")
async def cleanup(self):
@classmethod
def create_with_context(cls, context: Context) -> "SandboxFilesTool[Context]":
raise NotImplementedError(
"create_with_context not implemented for SandboxFilesTool"
) | --- +++ @@ -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
def clean_path(self, path: str) -> str:
+ """Clean and normalize a path to be relative to /workspace"""
return clean_path(path, self.workspace_path)
def _should_exclude_file(self, rel_path: str) -> bool:
+ """Check if a file should be excluded based on path, name, or extension"""
return should_exclude_file(rel_path)
def _file_exists(self, path: str) -> bool:
+ """Check if a file exists in the sandbox"""
try:
self.sandbox.fs.get_file_info(path)
return True
@@ -96,6 +100,7 @@ return False
async def get_workspace_state(self) -> dict:
+ """Get the current workspace state by reading all files"""
files_state = {}
try:
# Ensure sandbox is initialized
@@ -139,6 +144,18 @@ permissions: Optional[str] = "644",
**kwargs,
) -> ToolResult:
+ """
+ Execute a file operation in the sandbox environment.
+ Args:
+ action: The file operation to perform
+ file_path: Path to the file relative to /workspace
+ file_contents: Content to write to the file
+ old_str: Text to be replaced (for str_replace)
+ new_str: Replacement text (for str_replace)
+ permissions: File permissions in octal format
+ Returns:
+ ToolResult with the operation's output or error
+ """
async with asyncio.Lock():
try:
# File creation
@@ -187,6 +204,7 @@ async def _create_file(
self, file_path: str, file_contents: str, permissions: str = "644"
) -> ToolResult:
+ """Create a new file with the provided contents"""
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
@@ -232,6 +250,7 @@ async def _str_replace(
self, file_path: str, old_str: str, new_str: str
) -> ToolResult:
+ """Replace specific text in a file"""
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
@@ -278,6 +297,7 @@ async def _full_file_rewrite(
self, file_path: str, file_contents: str, permissions: str = "644"
) -> ToolResult:
+ """Completely rewrite an existing file with new content"""
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
@@ -315,6 +335,7 @@ return self.fail_response(f"Error rewriting file: {str(e)}")
async def _delete_file(self, file_path: str) -> ToolResult:
+ """Delete a file at the given path"""
try:
# Ensure sandbox is initialized
await self._ensure_sandbox()
@@ -330,9 +351,11 @@ return self.fail_response(f"Error deleting file: {str(e)}")
async def cleanup(self):
+ """Clean up sandbox resources."""
@classmethod
def create_with_context(cls, context: Context) -> "SandboxFilesTool[Context]":
+ """Factory method to create a SandboxFilesTool with a specific context."""
raise NotImplementedError(
"create_with_context not implemented for SandboxFilesTool"
- )+ )
| 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 print statements to see results."
parameters: dict = {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "The Python code to execute.",
},
},
"required": ["code"],
}
def _run_code(self, code: str, result_dict: dict, safe_globals: dict) -> None:
original_stdout = sys.stdout
try:
output_buffer = StringIO()
sys.stdout = output_buffer
exec(code, safe_globals, safe_globals)
result_dict["observation"] = output_buffer.getvalue()
result_dict["success"] = True
except Exception as e:
result_dict["observation"] = str(e)
result_dict["success"] = False
finally:
sys.stdout = original_stdout
async def execute(
self,
code: str,
timeout: int = 5,
) -> Dict:
with multiprocessing.Manager() as manager:
result = manager.dict({"observation": "", "success": False})
if isinstance(__builtins__, dict):
safe_globals = {"__builtins__": __builtins__}
else:
safe_globals = {"__builtins__": __builtins__.__dict__.copy()}
proc = multiprocessing.Process(
target=self._run_code, args=(code, result, safe_globals)
)
proc.start()
proc.join(timeout)
# timeout process
if proc.is_alive():
proc.terminate()
proc.join(1)
return {
"observation": f"Execution timeout after {timeout} seconds",
"success": False,
}
return dict(result) | --- +++ @@ -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 statements to see results."
@@ -40,6 +41,16 @@ code: str,
timeout: int = 5,
) -> Dict:
+ """
+ Executes the provided Python code with a timeout.
+
+ Args:
+ code (str): The Python code to execute.
+ timeout (int): Execution timeout in seconds.
+
+ Returns:
+ Dict: Contains 'output' with execution output or error message and 'success' status.
+ """
with multiprocessing.Manager() as manager:
result = manager.dict({"observation": "", "success": False})
@@ -61,4 +72,4 @@ "observation": f"Execution timeout after {timeout} seconds",
"success": False,
}
- return dict(result)+ return dict(result)
| 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: ignore
class ToolChoice(str, Enum):
NONE = "none"
AUTO = "auto"
REQUIRED = "required"
TOOL_CHOICE_VALUES = tuple(choice.value for choice in ToolChoice)
TOOL_CHOICE_TYPE = Literal[TOOL_CHOICE_VALUES] # type: ignore
class AgentState(str, Enum):
IDLE = "IDLE"
RUNNING = "RUNNING"
FINISHED = "FINISHED"
ERROR = "ERROR"
class Function(BaseModel):
name: str
arguments: str
class ToolCall(BaseModel):
id: str
type: str = "function"
function: Function
class Message(BaseModel):
role: ROLE_TYPE = Field(...) # type: ignore
content: Optional[str] = Field(default=None)
tool_calls: Optional[List[ToolCall]] = Field(default=None)
name: Optional[str] = Field(default=None)
tool_call_id: Optional[str] = Field(default=None)
base64_image: Optional[str] = Field(default=None)
def __add__(self, other) -> List["Message"]:
if isinstance(other, list):
return [self] + other
elif isinstance(other, Message):
return [self, other]
else:
raise TypeError(
f"unsupported operand type(s) for +: '{type(self).__name__}' and '{type(other).__name__}'"
)
def __radd__(self, other) -> List["Message"]:
if isinstance(other, list):
return other + [self]
else:
raise TypeError(
f"unsupported operand type(s) for +: '{type(other).__name__}' and '{type(self).__name__}'"
)
def to_dict(self) -> dict:
message = {"role": self.role}
if self.content is not None:
message["content"] = self.content
if self.tool_calls is not None:
message["tool_calls"] = [tool_call.dict() for tool_call in self.tool_calls]
if self.name is not None:
message["name"] = self.name
if self.tool_call_id is not None:
message["tool_call_id"] = self.tool_call_id
if self.base64_image is not None:
message["base64_image"] = self.base64_image
return message
@classmethod
def user_message(
cls, content: str, base64_image: Optional[str] = None
) -> "Message":
return cls(role=Role.USER, content=content, base64_image=base64_image)
@classmethod
def system_message(cls, content: str) -> "Message":
return cls(role=Role.SYSTEM, content=content)
@classmethod
def assistant_message(
cls, content: Optional[str] = None, base64_image: Optional[str] = None
) -> "Message":
return cls(role=Role.ASSISTANT, content=content, base64_image=base64_image)
@classmethod
def tool_message(
cls, content: str, name, tool_call_id: str, base64_image: Optional[str] = None
) -> "Message":
return cls(
role=Role.TOOL,
content=content,
name=name,
tool_call_id=tool_call_id,
base64_image=base64_image,
)
@classmethod
def from_tool_calls(
cls,
tool_calls: List[Any],
content: Union[str, List[str]] = "",
base64_image: Optional[str] = None,
**kwargs,
):
formatted_calls = [
{"id": call.id, "function": call.function.model_dump(), "type": "function"}
for call in tool_calls
]
return cls(
role=Role.ASSISTANT,
content=content,
tool_calls=formatted_calls,
base64_image=base64_image,
**kwargs,
)
class Memory(BaseModel):
messages: List[Message] = Field(default_factory=list)
max_messages: int = Field(default=100)
def add_message(self, message: Message) -> None:
self.messages.append(message)
# Optional: Implement message limit
if len(self.messages) > self.max_messages:
self.messages = self.messages[-self.max_messages :]
def add_messages(self, messages: List[Message]) -> None:
self.messages.extend(messages)
# Optional: Implement message limit
if len(self.messages) > self.max_messages:
self.messages = self.messages[-self.max_messages :]
def clear(self) -> None:
self.messages.clear()
def get_recent_messages(self, n: int) -> List[Message]:
return self.messages[-n:]
def to_dict_list(self) -> List[dict]:
return [msg.to_dict() for msg in self.messages] | --- +++ @@ -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 execution states"""
IDLE = "IDLE"
RUNNING = "RUNNING"
@@ -41,6 +44,7 @@
class ToolCall(BaseModel):
+ """Represents a tool/function call in a message"""
id: str
type: str = "function"
@@ -48,6 +52,7 @@
class Message(BaseModel):
+ """Represents a chat message in the conversation"""
role: ROLE_TYPE = Field(...) # type: ignore
content: Optional[str] = Field(default=None)
@@ -57,6 +62,7 @@ base64_image: Optional[str] = Field(default=None)
def __add__(self, other) -> List["Message"]:
+ """支持 Message + list 或 Message + Message 的操作"""
if isinstance(other, list):
return [self] + other
elif isinstance(other, Message):
@@ -67,6 +73,7 @@ )
def __radd__(self, other) -> List["Message"]:
+ """支持 list + Message 的操作"""
if isinstance(other, list):
return other + [self]
else:
@@ -75,6 +82,7 @@ )
def to_dict(self) -> dict:
+ """Convert message to dictionary format"""
message = {"role": self.role}
if self.content is not None:
message["content"] = self.content
@@ -92,22 +100,26 @@ def user_message(
cls, content: str, base64_image: Optional[str] = None
) -> "Message":
+ """Create a user message"""
return cls(role=Role.USER, content=content, base64_image=base64_image)
@classmethod
def system_message(cls, content: str) -> "Message":
+ """Create a system message"""
return cls(role=Role.SYSTEM, content=content)
@classmethod
def assistant_message(
cls, content: Optional[str] = None, base64_image: Optional[str] = None
) -> "Message":
+ """Create an assistant message"""
return cls(role=Role.ASSISTANT, content=content, base64_image=base64_image)
@classmethod
def tool_message(
cls, content: str, name, tool_call_id: str, base64_image: Optional[str] = None
) -> "Message":
+ """Create a tool message"""
return cls(
role=Role.TOOL,
content=content,
@@ -124,6 +136,13 @@ base64_image: Optional[str] = None,
**kwargs,
):
+ """Create ToolCallsMessage from raw tool calls.
+
+ Args:
+ tool_calls: Raw tool calls from LLM
+ content: Optional message content
+ base64_image: Optional base64 encoded image
+ """
formatted_calls = [
{"id": call.id, "function": call.function.model_dump(), "type": "function"}
for call in tool_calls
@@ -142,22 +161,27 @@ max_messages: int = Field(default=100)
def add_message(self, message: Message) -> None:
+ """Add a message to memory"""
self.messages.append(message)
# Optional: Implement message limit
if len(self.messages) > self.max_messages:
self.messages = self.messages[-self.max_messages :]
def add_messages(self, messages: List[Message]) -> None:
+ """Add multiple messages to memory"""
self.messages.extend(messages)
# Optional: Implement message limit
if len(self.messages) > self.max_messages:
self.messages = self.messages[-self.max_messages :]
def clear(self) -> None:
+ """Clear all messages"""
self.messages.clear()
def get_recent_messages(self, n: int) -> List[Message]:
+ """Get n most recent messages"""
return self.messages[-n:]
def to_dict_list(self) -> List[dict]:
- return [msg.to_dict() for msg in self.messages]+ """Convert messages to list of dicts"""
+ return [msg.to_dict() for msg in self.messages]
| 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 import ToolResult
from app.utils.logger import logger
# Context = TypeVar("Context")
_BROWSER_DESCRIPTION = """\
A sandbox-based browser automation tool that allows interaction with web pages through various actions.
* This tool provides commands for controlling a browser session in a sandboxed environment
* It maintains state across calls, keeping the browser session alive until explicitly closed
* Use this when you need to browse websites, fill forms, click buttons, or extract content in a secure sandbox
* Each action requires specific parameters as defined in the tool's dependencies
Key capabilities include:
* Navigation: Go to specific URLs, go back in history
* Interaction: Click elements by index, input text, send keyboard commands
* Scrolling: Scroll up/down by pixel amount or scroll to specific text
* Tab management: Switch between tabs or close tabs
* Content extraction: Get dropdown options or select dropdown options
"""
# noinspection PyArgumentList
class SandboxBrowserTool(SandboxToolsBase):
name: str = "sandbox_browser"
description: str = _BROWSER_DESCRIPTION
parameters: dict = {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": [
"navigate_to",
"go_back",
"wait",
"click_element",
"input_text",
"send_keys",
"switch_tab",
"close_tab",
"scroll_down",
"scroll_up",
"scroll_to_text",
"get_dropdown_options",
"select_dropdown_option",
"click_coordinates",
"drag_drop",
],
"description": "The browser action to perform",
},
"url": {
"type": "string",
"description": "URL for 'navigate_to' action",
},
"index": {
"type": "integer",
"description": "Element index for interaction actions",
},
"text": {
"type": "string",
"description": "Text for input or scroll actions",
},
"amount": {
"type": "integer",
"description": "Pixel amount to scroll",
},
"page_id": {
"type": "integer",
"description": "Tab ID for tab management actions",
},
"keys": {
"type": "string",
"description": "Keys to send for keyboard actions",
},
"seconds": {
"type": "integer",
"description": "Seconds to wait",
},
"x": {
"type": "integer",
"description": "X coordinate for click or drag actions",
},
"y": {
"type": "integer",
"description": "Y coordinate for click or drag actions",
},
"element_source": {
"type": "string",
"description": "Source element for drag and drop",
},
"element_target": {
"type": "string",
"description": "Target element for drag and drop",
},
},
"required": ["action"],
"dependencies": {
"navigate_to": ["url"],
"click_element": ["index"],
"input_text": ["index", "text"],
"send_keys": ["keys"],
"switch_tab": ["page_id"],
"close_tab": ["page_id"],
"scroll_down": ["amount"],
"scroll_up": ["amount"],
"scroll_to_text": ["text"],
"get_dropdown_options": ["index"],
"select_dropdown_option": ["index", "text"],
"click_coordinates": ["x", "y"],
"drag_drop": ["element_source", "element_target"],
"wait": ["seconds"],
},
}
browser_message: Optional[ThreadMessage] = Field(default=None, exclude=True)
def __init__(
self, sandbox: Optional[Sandbox] = None, thread_id: Optional[str] = None, **data
):
super().__init__(**data)
if sandbox is not None:
self._sandbox = sandbox # Directly set the base class private attribute
def _validate_base64_image(
self, base64_string: str, max_size_mb: int = 10
) -> tuple[bool, str]:
try:
if not base64_string or len(base64_string) < 10:
return False, "Base64 string is empty or too short"
if base64_string.startswith("data:"):
try:
base64_string = base64_string.split(",", 1)[1]
except (IndexError, ValueError):
return False, "Invalid data URL format"
import re
if not re.match(r"^[A-Za-z0-9+/]*={0,2}$", base64_string):
return False, "Invalid base64 characters detected"
if len(base64_string) % 4 != 0:
return False, "Invalid base64 string length"
try:
image_data = base64.b64decode(base64_string, validate=True)
except Exception as e:
return False, f"Base64 decoding failed: {str(e)}"
max_size_bytes = max_size_mb * 1024 * 1024
if len(image_data) > max_size_bytes:
return False, f"Image size exceeds limit ({max_size_bytes} bytes)"
try:
image_stream = io.BytesIO(image_data)
with Image.open(image_stream) as img:
img.verify()
supported_formats = {"JPEG", "PNG", "GIF", "BMP", "WEBP", "TIFF"}
if img.format not in supported_formats:
return False, f"Unsupported image format: {img.format}"
image_stream.seek(0)
with Image.open(image_stream) as img_check:
width, height = img_check.size
max_dimension = 8192
if width > max_dimension or height > max_dimension:
return (
False,
f"Image dimensions exceed limit ({max_dimension}x{max_dimension})",
)
if width < 1 or height < 1:
return False, f"Invalid image dimensions: {width}x{height}"
except Exception as e:
return False, f"Invalid image data: {str(e)}"
return True, "Valid image"
except Exception as e:
logger.error(f"Unexpected error during base64 image validation: {e}")
return False, f"Validation error: {str(e)}"
async def _execute_browser_action(
self, endpoint: str, params: dict = None, method: str = "POST"
) -> ToolResult:
try:
await self._ensure_sandbox()
url = f"http://localhost:8003/api/automation/{endpoint}"
if method == "GET" and params:
query_params = "&".join([f"{k}={v}" for k, v in params.items()])
url = f"{url}?{query_params}"
curl_cmd = (
f"curl -s -X {method} '{url}' -H 'Content-Type: application/json'"
)
else:
curl_cmd = (
f"curl -s -X {method} '{url}' -H 'Content-Type: application/json'"
)
if params:
json_data = json.dumps(params)
curl_cmd += f" -d '{json_data}'"
logger.debug(f"Executing curl command: {curl_cmd}")
response = self.sandbox.process.exec(curl_cmd, timeout=30)
if response.exit_code == 0:
try:
result = json.loads(response.result)
result.setdefault("content", "")
result.setdefault("role", "assistant")
if "screenshot_base64" in result:
screenshot_data = result["screenshot_base64"]
is_valid, validation_message = self._validate_base64_image(
screenshot_data
)
if not is_valid:
logger.warning(
f"Screenshot validation failed: {validation_message}"
)
result["image_validation_error"] = validation_message
del result["screenshot_base64"]
# added_message = await self.thread_manager.add_message(
# thread_id=self.thread_id,
# type="browser_state",
# content=result,
# is_llm_message=False
# )
message = ThreadMessage(
type="browser_state", content=result, is_llm_message=False
)
self.browser_message = message
success_response = {
"success": result.get("success", False),
"message": result.get("message", "Browser action completed"),
}
# if added_message and 'message_id' in added_message:
# success_response['message_id'] = added_message['message_id']
for field in [
"url",
"title",
"element_count",
"pixels_below",
"ocr_text",
"image_url",
]:
if field in result:
success_response[field] = result[field]
return (
self.success_response(success_response)
if success_response["success"]
else self.fail_response(success_response)
)
except json.JSONDecodeError as e:
logger.error(f"Failed to parse response JSON: {e}")
return self.fail_response(f"Failed to parse response JSON: {e}")
else:
logger.error(f"Browser automation request failed: {response}")
return self.fail_response(
f"Browser automation request failed: {response}"
)
except Exception as e:
logger.error(f"Error executing browser action: {e}")
logger.debug(traceback.format_exc())
return self.fail_response(f"Error executing browser action: {e}")
async def execute(
self,
action: str,
url: Optional[str] = None,
index: Optional[int] = None,
text: Optional[str] = None,
amount: Optional[int] = None,
page_id: Optional[int] = None,
keys: Optional[str] = None,
seconds: Optional[int] = None,
x: Optional[int] = None,
y: Optional[int] = None,
element_source: Optional[str] = None,
element_target: Optional[str] = None,
**kwargs,
) -> ToolResult:
# async with self.lock:
try:
# Navigation actions
if action == "navigate_to":
if not url:
return self.fail_response("URL is required for navigation")
return await self._execute_browser_action("navigate_to", {"url": url})
elif action == "go_back":
return await self._execute_browser_action("go_back", {})
# Interaction actions
elif action == "click_element":
if index is None:
return self.fail_response("Index is required for click_element")
return await self._execute_browser_action(
"click_element", {"index": index}
)
elif action == "input_text":
if index is None or not text:
return self.fail_response(
"Index and text are required for input_text"
)
return await self._execute_browser_action(
"input_text", {"index": index, "text": text}
)
elif action == "send_keys":
if not keys:
return self.fail_response("Keys are required for send_keys")
return await self._execute_browser_action("send_keys", {"keys": keys})
# Tab management
elif action == "switch_tab":
if page_id is None:
return self.fail_response("Page ID is required for switch_tab")
return await self._execute_browser_action(
"switch_tab", {"page_id": page_id}
)
elif action == "close_tab":
if page_id is None:
return self.fail_response("Page ID is required for close_tab")
return await self._execute_browser_action(
"close_tab", {"page_id": page_id}
)
# Scrolling actions
elif action == "scroll_down":
params = {"amount": amount} if amount is not None else {}
return await self._execute_browser_action("scroll_down", params)
elif action == "scroll_up":
params = {"amount": amount} if amount is not None else {}
return await self._execute_browser_action("scroll_up", params)
elif action == "scroll_to_text":
if not text:
return self.fail_response("Text is required for scroll_to_text")
return await self._execute_browser_action(
"scroll_to_text", {"text": text}
)
# Dropdown actions
elif action == "get_dropdown_options":
if index is None:
return self.fail_response(
"Index is required for get_dropdown_options"
)
return await self._execute_browser_action(
"get_dropdown_options", {"index": index}
)
elif action == "select_dropdown_option":
if index is None or not text:
return self.fail_response(
"Index and text are required for select_dropdown_option"
)
return await self._execute_browser_action(
"select_dropdown_option", {"index": index, "text": text}
)
# Coordinate-based actions
elif action == "click_coordinates":
if x is None or y is None:
return self.fail_response(
"X and Y coordinates are required for click_coordinates"
)
return await self._execute_browser_action(
"click_coordinates", {"x": x, "y": y}
)
elif action == "drag_drop":
if not element_source or not element_target:
return self.fail_response(
"Source and target elements are required for drag_drop"
)
return await self._execute_browser_action(
"drag_drop",
{
"element_source": element_source,
"element_target": element_target,
},
)
# Utility actions
elif action == "wait":
seconds_to_wait = seconds if seconds is not None else 3
return await self._execute_browser_action(
"wait", {"seconds": seconds_to_wait}
)
else:
return self.fail_response(f"Unknown action: {action}")
except Exception as e:
logger.error(f"Error executing browser action: {e}")
return self.fail_response(f"Error executing browser action: {e}")
async def get_current_state(
self, message: Optional[ThreadMessage] = None
) -> ToolResult:
try:
# Use provided context or fall back to self.context
message = message or self.browser_message
if not message:
return ToolResult(error="Browser context not initialized")
state = message.content
screenshot = state.get("screenshot_base64")
# Build the state info with all required fields
state_info = {
"url": state.get("url", ""),
"title": state.get("title", ""),
"tabs": [tab.model_dump() for tab in state.get("tabs", [])],
"pixels_above": getattr(state, "pixels_above", 0),
"pixels_below": getattr(state, "pixels_below", 0),
"help": "[0], [1], [2], etc., represent clickable indices corresponding to the elements listed. Clicking on these indices will navigate to or interact with the respective content behind them.",
}
return ToolResult(
output=json.dumps(state_info, indent=4, ensure_ascii=False),
base64_image=screenshot,
)
except Exception as e:
return ToolResult(error=f"Failed to get browser state: {str(e)}")
@classmethod
def create_with_sandbox(cls, sandbox: Sandbox) -> "SandboxBrowserTool":
return cls(sandbox=sandbox) | --- +++ @@ -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__(
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 # Directly set the base class private attribute
@@ -136,6 +138,14 @@ def _validate_base64_image(
self, base64_string: str, max_size_mb: int = 10
) -> tuple[bool, str]:
+ """
+ Validate base64 image data.
+ Args:
+ base64_string: The base64 encoded image data
+ max_size_mb: Maximum allowed image size in megabytes
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
try:
if not base64_string or len(base64_string) < 10:
return False, "Base64 string is empty or too short"
@@ -185,6 +195,7 @@ async def _execute_browser_action(
self, endpoint: str, params: dict = None, method: str = "POST"
) -> ToolResult:
+ """Execute a browser automation action through the sandbox API."""
try:
await self._ensure_sandbox()
url = f"http://localhost:8003/api/automation/{endpoint}"
@@ -280,6 +291,24 @@ element_target: Optional[str] = None,
**kwargs,
) -> ToolResult:
+ """
+ Execute a browser action in the sandbox environment.
+ Args:
+ action: The browser action to perform
+ url: URL for navigation
+ index: Element index for interaction
+ text: Text for input or scroll actions
+ amount: Pixel amount to scroll
+ page_id: Tab ID for tab management
+ keys: Keys to send for keyboard actions
+ seconds: Seconds to wait
+ x: X coordinate for click/drag
+ y: Y coordinate for click/drag
+ element_source: Source element for drag and drop
+ element_target: Target element for drag and drop
+ Returns:
+ ToolResult with the action's output or error
+ """
# async with self.lock:
try:
# Navigation actions
@@ -387,6 +416,10 @@ async def get_current_state(
self, message: Optional[ThreadMessage] = None
) -> ToolResult:
+ """
+ Get the current browser state as a ToolResult.
+ If context is not provided, uses self.context.
+ """
try:
# Use provided context or fall back to self.context
message = message or self.browser_message
@@ -413,4 +446,5 @@
@classmethod
def create_with_sandbox(cls, sandbox: Sandbox) -> "SandboxBrowserTool":
- return cls(sandbox=sandbox)+ """Factory method to create a tool with sandbox."""
+ return cls(sandbox=sandbox)
| 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 description or snippet of the search result"
)
def __str__(self) -> str:
return f"{self.title} - {self.url}"
class WebSearchEngine(BaseModel):
model_config = {"arbitrary_types_allowed": True}
def perform_search(
self, query: str, num_results: int = 10, *args, **kwargs
) -> List[SearchItem]:
raise NotImplementedError | --- +++ @@ -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:
+ """String representation of a search result item."""
return f"{self.title} - {self.url}"
class WebSearchEngine(BaseModel):
+ """Base class for web search engines."""
model_config = {"arbitrary_types_allowed": True}
def perform_search(
self, query: str, num_results: int = 10, *args, **kwargs
) -> List[SearchItem]:
- raise NotImplementedError+ """
+ Perform a web search and return a list of search items.
+
+ Args:
+ query (str): The search query to submit to the search engine.
+ num_results (int, optional): The number of search results to return. Default is 10.
+ args: Additional arguments.
+ kwargs: Additional keyword arguments.
+
+ Returns:
+ List[SearchItem]: A list of SearchItem objects matching the search query.
+ """
+ raise NotImplementedError
| 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
from rich.traceback import install
from constants import (
THEME_PRIMARY, THEME_BORDER, THEME_ACCENT,
THEME_SUCCESS, THEME_ERROR, THEME_WARNING,
THEME_DIM, THEME_ARCHIVED, THEME_URL,
)
# Enable rich tracebacks globally
install()
_theme = Theme({
"purple": "#7B61FF",
"success": THEME_SUCCESS,
"error": THEME_ERROR,
"warning": THEME_WARNING,
"archived": THEME_ARCHIVED,
"url": THEME_URL,
"dim": THEME_DIM,
})
# Single shared console — all tool files do: from core import console
console = Console(theme=_theme)
def clear_screen():
os.system("cls" if system() == "Windows" else "clear")
def validate_input(ip, val_range: list) -> int | None:
if not val_range:
return None
try:
ip = int(ip)
if ip in val_range:
return ip
except (TypeError, ValueError):
pass
return None
def _show_inline_help():
console.print(Panel(
Text.assemble(
(" Navigation\n", "bold white"),
(" ─────────────────────────────────\n", "dim"),
(" 1–N ", "bold cyan"), ("select item\n", "white"),
(" 97 ", "bold cyan"), ("install all (in category)\n", "white"),
("\n Tool menu: Install, Run, Update, Open Folder\n", "dim"),
(" 99 ", "bold cyan"), ("go back\n", "white"),
(" 98 ", "bold cyan"), ("open project page / archived\n", "white"),
(" ? ", "bold cyan"), ("show this help\n", "white"),
(" q ", "bold cyan"), ("quit hackingtool\n", "white"),
),
title="[bold magenta] ? Quick Help [/bold magenta]",
border_style="magenta",
box=box.ROUNDED,
padding=(0, 2),
))
Prompt.ask("[dim]Press Enter to return[/dim]", default="")
class HackingTool:
TITLE: str = ""
DESCRIPTION: str = ""
INSTALL_COMMANDS: list[str] = []
UNINSTALL_COMMANDS: list[str] = []
RUN_COMMANDS: list[str] = []
OPTIONS: list[tuple[str, Callable]] = []
PROJECT_URL: str = ""
# OS / capability metadata
SUPPORTED_OS: list[str] = ["linux", "macos"]
REQUIRES_ROOT: bool = False
REQUIRES_WIFI: bool = False
REQUIRES_GO: bool = False
REQUIRES_RUBY: bool = False
REQUIRES_JAVA: bool = False
REQUIRES_DOCKER: bool = False
# Tags for search/filter (e.g. ["osint", "web", "recon", "scanner"])
TAGS: list[str] = []
# Archived tool flags
ARCHIVED: bool = False
ARCHIVED_REASON: str = ""
def __init__(self, options=None, installable=True, runnable=True):
options = options or []
if not isinstance(options, list):
raise TypeError("options must be a list of (option_name, option_fn) tuples")
self.OPTIONS = []
if installable:
self.OPTIONS.append(("Install", self.install))
if runnable:
self.OPTIONS.append(("Run", self.run))
self.OPTIONS.append(("Update", self.update))
self.OPTIONS.append(("Open Folder", self.open_folder))
self.OPTIONS.extend(options)
@property
def is_installed(self) -> bool:
if self.RUN_COMMANDS:
cmd = self.RUN_COMMANDS[0]
# Handle "cd foo && binary --help" pattern
if "&&" in cmd:
cmd = cmd.split("&&")[-1].strip()
if cmd.startswith("sudo "):
cmd = cmd[5:].strip()
binary = cmd.split()[0] if cmd else ""
if binary and binary not in (".", "echo", "cd"):
if shutil.which(binary):
return True
# Check if git clone target dir exists
if self.INSTALL_COMMANDS:
for ic in self.INSTALL_COMMANDS:
if "git clone" in ic:
parts = ic.split()
repo_url = [p for p in parts if p.startswith("http")]
if repo_url:
dirname = repo_url[0].rstrip("/").rsplit("/", 1)[-1].replace(".git", "")
if os.path.isdir(dirname):
return True
return False
def show_info(self):
desc = f"[cyan]{self.DESCRIPTION}[/cyan]"
if self.PROJECT_URL:
desc += f"\n[url]🔗 {self.PROJECT_URL}[/url]"
if self.ARCHIVED:
desc += f"\n[archived]⚠ ARCHIVED: {self.ARCHIVED_REASON}[/archived]"
console.print(Panel(
desc,
title=f"[{THEME_PRIMARY}]{self.TITLE}[/{THEME_PRIMARY}]",
border_style="purple",
box=box.DOUBLE,
))
def show_options(self, parent=None):
while True:
clear_screen()
self.show_info()
table = Table(title="Options", box=box.SIMPLE_HEAVY)
table.add_column("No.", style="bold cyan", justify="center")
table.add_column("Action", style="bold yellow")
for index, option in enumerate(self.OPTIONS):
table.add_row(str(index + 1), option[0])
if self.PROJECT_URL:
table.add_row("98", "Open Project Page")
table.add_row("99", f"Back to {parent.TITLE if parent else 'Main Menu'}")
console.print(table)
console.print(
" [dim cyan]?[/dim cyan][dim]help "
"[/dim][dim cyan]q[/dim cyan][dim]uit "
"[/dim][dim cyan]99[/dim cyan][dim] back[/dim]"
)
raw = Prompt.ask("[bold cyan]╰─>[/bold cyan]", default="").strip().lower()
if not raw:
continue
if raw in ("?", "help"):
_show_inline_help()
continue
if raw in ("q", "quit", "exit"):
raise SystemExit(0)
try:
choice = int(raw)
except ValueError:
console.print("[error]⚠ Enter a number, ? for help, or q to quit.[/error]")
Prompt.ask("[dim]Press Enter to continue[/dim]", default="")
continue
if choice == 99:
return
elif choice == 98 and self.PROJECT_URL:
self.show_project_page()
elif 1 <= choice <= len(self.OPTIONS):
try:
self.OPTIONS[choice - 1][1]()
except Exception:
console.print_exception(show_locals=True)
Prompt.ask("[dim]Press Enter to continue[/dim]", default="")
else:
console.print("[error]⚠ Invalid option.[/error]")
def before_install(self): pass
def install(self):
self.before_install()
if isinstance(self.INSTALL_COMMANDS, (list, tuple)):
for cmd in self.INSTALL_COMMANDS:
console.print(f"[warning]→ {cmd}[/warning]")
os.system(cmd)
self.after_install()
def after_install(self):
console.print("[success]✔ Successfully installed![/success]")
def before_uninstall(self) -> bool:
return True
def uninstall(self):
if self.before_uninstall():
if isinstance(self.UNINSTALL_COMMANDS, (list, tuple)):
for cmd in self.UNINSTALL_COMMANDS:
console.print(f"[error]→ {cmd}[/error]")
os.system(cmd)
self.after_uninstall()
def after_uninstall(self): pass
def update(self):
if not self.is_installed:
console.print("[warning]Tool is not installed yet. Install it first.[/warning]")
return
updated = False
for ic in (self.INSTALL_COMMANDS or []):
if "git clone" in ic:
# Extract repo dir name from clone command
parts = ic.split()
repo_urls = [p for p in parts if p.startswith("http")]
if repo_urls:
dirname = repo_urls[0].rstrip("/").rsplit("/", 1)[-1].replace(".git", "")
if os.path.isdir(dirname):
console.print(f"[cyan]→ git -C {dirname} pull[/cyan]")
os.system(f"git -C {dirname} pull")
updated = True
elif "pip install" in ic:
# Re-run pip install (--upgrade)
upgrade_cmd = ic.replace("pip install", "pip install --upgrade")
console.print(f"[cyan]→ {upgrade_cmd}[/cyan]")
os.system(upgrade_cmd)
updated = True
elif "go install" in ic:
# Re-run go install (fetches latest)
console.print(f"[cyan]→ {ic}[/cyan]")
os.system(ic)
updated = True
elif "gem install" in ic:
upgrade_cmd = ic.replace("gem install", "gem update")
console.print(f"[cyan]→ {upgrade_cmd}[/cyan]")
os.system(upgrade_cmd)
updated = True
if updated:
console.print("[success]✔ Update complete![/success]")
else:
console.print("[dim]No automatic update method available for this tool.[/dim]")
def _get_tool_dir(self) -> str | None:
# 1. Check git clone target dir
for ic in (self.INSTALL_COMMANDS or []):
if "git clone" in ic:
parts = ic.split()
# If last arg is not a URL, it's a custom dir name
repo_urls = [p for p in parts if p.startswith("http")]
if repo_urls:
dirname = repo_urls[0].rstrip("/").rsplit("/", 1)[-1].replace(".git", "")
# Check custom target dir (arg after URL)
url_idx = parts.index(repo_urls[0])
if url_idx + 1 < len(parts):
dirname = parts[url_idx + 1]
if os.path.isdir(dirname):
return os.path.abspath(dirname)
# 2. Check binary location via which
if self.RUN_COMMANDS:
cmd = self.RUN_COMMANDS[0]
if "&&" in cmd:
# "cd foo && bar" → check "foo"
cd_part = cmd.split("&&")[0].strip()
if cd_part.startswith("cd "):
d = cd_part[3:].strip()
if os.path.isdir(d):
return os.path.abspath(d)
binary = cmd.split()[0] if cmd else ""
if binary.startswith("sudo"):
binary = cmd.split()[1] if len(cmd.split()) > 1 else ""
path = shutil.which(binary) if binary else None
if path:
return os.path.dirname(os.path.realpath(path))
return None
def open_folder(self):
tool_dir = self._get_tool_dir()
if tool_dir:
console.print(f"[success]Opening folder: {tool_dir}[/success]")
console.print("[dim]Type 'exit' to return to hackingtool.[/dim]")
os.system(f'cd "{tool_dir}" && $SHELL')
else:
console.print("[warning]Tool directory not found.[/warning]")
if self.PROJECT_URL:
console.print(f"[dim]You can clone it manually:[/dim]")
console.print(f"[cyan] git clone {self.PROJECT_URL}.git[/cyan]")
def before_run(self): pass
def run(self):
self.before_run()
if isinstance(self.RUN_COMMANDS, (list, tuple)):
for cmd in self.RUN_COMMANDS:
console.print(f"[cyan]⚙ Running:[/cyan] [bold]{cmd}[/bold]")
os.system(cmd)
self.after_run()
def after_run(self): pass
def show_project_page(self):
console.print(f"[url]🌐 Opening: {self.PROJECT_URL}[/url]")
webbrowser.open_new_tab(self.PROJECT_URL)
class HackingToolsCollection:
TITLE: str = ""
DESCRIPTION: str = ""
TOOLS: list = []
def __init__(self):
pass
def show_info(self):
console.rule(f"[{THEME_PRIMARY}]{self.TITLE}[/{THEME_PRIMARY}]", style="purple")
if self.DESCRIPTION:
console.print(f"[italic cyan]{self.DESCRIPTION}[/italic cyan]\n")
def _active_tools(self) -> list:
from os_detect import CURRENT_OS
return [
t for t in self.TOOLS
if not getattr(t, "ARCHIVED", False)
and CURRENT_OS.system in getattr(t, "SUPPORTED_OS", ["linux", "macos"])
]
def _archived_tools(self) -> list:
return [t for t in self.TOOLS if getattr(t, "ARCHIVED", False)]
def _incompatible_tools(self) -> list:
from os_detect import CURRENT_OS
return [
t for t in self.TOOLS
if not getattr(t, "ARCHIVED", False)
and CURRENT_OS.system not in getattr(t, "SUPPORTED_OS", ["linux", "macos"])
]
def _show_archived_tools(self):
archived = self._archived_tools()
if not archived:
console.print("[dim]No archived tools in this category.[/dim]")
Prompt.ask("[dim]Press Enter to return[/dim]", default="")
return
while True:
clear_screen()
console.rule(f"[archived]Archived Tools — {self.TITLE}[/archived]", style="yellow")
table = Table(box=box.MINIMAL_DOUBLE_HEAD, show_lines=True)
table.add_column("No.", justify="center", style="bold yellow")
table.add_column("Tool", style="dim yellow")
table.add_column("Reason", style="dim white")
for i, tool in enumerate(archived):
reason = getattr(tool, "ARCHIVED_REASON", "No reason given")
table.add_row(str(i + 1), tool.TITLE, reason)
table.add_row("99", "Back", "")
console.print(table)
raw = Prompt.ask("[bold yellow][?] Select[/bold yellow]", default="99")
try:
choice = int(raw)
except ValueError:
continue
if choice == 99:
return
elif 1 <= choice <= len(archived):
archived[choice - 1].show_options(parent=self)
def show_options(self, parent=None):
while True:
clear_screen()
self.show_info()
active = self._active_tools()
incompatible = self._incompatible_tools()
archived = self._archived_tools()
table = Table(title="Available Tools", box=box.SIMPLE_HEAD, show_lines=True)
table.add_column("No.", justify="center", style="bold cyan", width=6)
table.add_column("", width=2) # installed indicator
table.add_column("Tool", style="bold yellow", min_width=24)
table.add_column("Description", style="white", overflow="fold")
for index, tool in enumerate(active, start=1):
desc = getattr(tool, "DESCRIPTION", "") or "—"
desc = desc.splitlines()[0] if desc != "—" else "—"
has_status = hasattr(tool, "is_installed")
status = ("[green]✔[/green]" if tool.is_installed else "[dim]✘[/dim]") if has_status else ""
table.add_row(str(index), status, tool.TITLE, desc)
# Count not-installed tools for "Install All" label (skip sub-collections)
not_installed = [t for t in active if hasattr(t, "is_installed") and not t.is_installed]
if not_installed:
table.add_row(
"[bold green]97[/bold green]", "",
f"[bold green]Install all ({len(not_installed)} not installed)[/bold green]", "",
)
if archived:
table.add_row("[dim]98[/dim]", "", f"[archived]Archived tools ({len(archived)})[/archived]", "")
if incompatible:
console.print(f"[dim]({len(incompatible)} tools hidden — not supported on current OS)[/dim]")
table.add_row("99", "", f"Back to {parent.TITLE if parent else 'Main Menu'}", "")
console.print(table)
console.print(
" [dim cyan]?[/dim cyan][dim]help "
"[/dim][dim cyan]q[/dim cyan][dim]uit "
"[/dim][dim cyan]99[/dim cyan][dim] back[/dim]"
)
raw = Prompt.ask("[bold cyan]╰─>[/bold cyan]", default="").strip().lower()
if not raw:
continue
if raw in ("?", "help"):
_show_inline_help()
continue
if raw in ("q", "quit", "exit"):
raise SystemExit(0)
try:
choice = int(raw)
except ValueError:
console.print("[error]⚠ Enter a number, ? for help, or q to quit.[/error]")
continue
if choice == 99:
return
elif choice == 97 and not_installed:
console.print(Panel(
f"[bold]Installing {len(not_installed)} tools...[/bold]",
border_style="green", box=box.ROUNDED,
))
for i, tool in enumerate(not_installed, start=1):
console.print(f"\n[bold cyan]({i}/{len(not_installed)})[/bold cyan] {tool.TITLE}")
try:
tool.install()
except Exception:
console.print(f"[error]✘ Failed: {tool.TITLE}[/error]")
Prompt.ask("\n[dim]Press Enter to continue[/dim]", default="")
elif choice == 98 and archived:
self._show_archived_tools()
elif 1 <= choice <= len(active):
try:
active[choice - 1].show_options(parent=self)
except Exception:
console.print_exception(show_locals=True)
Prompt.ask("[dim]Press Enter to continue[/dim]", default="")
else:
console.print("[error]⚠ Invalid option.[/error]") | --- +++ @@ -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.print(Panel(
Text.assemble(
(" Navigation\n", "bold white"),
@@ -114,6 +116,7 @@
@property
def is_installed(self) -> bool:
+ """Check if the tool's binary is on PATH or its clone dir exists."""
if self.RUN_COMMANDS:
cmd = self.RUN_COMMANDS[0]
# Handle "cd foo && binary --help" pattern
@@ -151,6 +154,7 @@ ))
def show_options(self, parent=None):
+ """Iterative menu loop — no recursion, no stack growth."""
while True:
clear_screen()
self.show_info()
@@ -228,6 +232,7 @@ def after_uninstall(self): pass
def update(self):
+ """Smart update — detects install method and runs the right update command."""
if not self.is_installed:
console.print("[warning]Tool is not installed yet. Install it first.[/warning]")
return
@@ -267,6 +272,7 @@ console.print("[dim]No automatic update method available for this tool.[/dim]")
def _get_tool_dir(self) -> str | None:
+ """Find the tool's local directory — clone target, pip location, or binary path."""
# 1. Check git clone target dir
for ic in (self.INSTALL_COMMANDS or []):
if "git clone" in ic:
@@ -302,6 +308,7 @@ return None
def open_folder(self):
+ """Open the tool's directory in a new shell so the user can work manually."""
tool_dir = self._get_tool_dir()
if tool_dir:
console.print(f"[success]Opening folder: {tool_dir}[/success]")
@@ -344,6 +351,7 @@ console.print(f"[italic cyan]{self.DESCRIPTION}[/italic cyan]\n")
def _active_tools(self) -> list:
+ """Return tools that are not archived and are OS-compatible."""
from os_detect import CURRENT_OS
return [
t for t in self.TOOLS
@@ -363,6 +371,7 @@ ]
def _show_archived_tools(self):
+ """Show archived tools sub-menu (option 98)."""
archived = self._archived_tools()
if not archived:
console.print("[dim]No archived tools in this category.[/dim]")
@@ -397,6 +406,7 @@ archived[choice - 1].show_options(parent=self)
def show_options(self, parent=None):
+ """Iterative menu loop — no recursion, no stack growth."""
while True:
clear_screen()
self.show_info()
@@ -476,4 +486,4 @@ console.print_exception(show_locals=True)
Prompt.ask("[dim]Press Enter to continue[/dim]", default="")
else:
- console.print("[error]⚠ Invalid option.[/error]")+ console.print("[error]⚠ Invalid option.[/error]")
| 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.version_info.major}.{sys.version_info.minor}.\n"
f"Install with: sudo apt install python3.10"
)
sys.exit(1)
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Confirm
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.text import Text
from rich import box
from constants import (
REPO_URL, APP_INSTALL_DIR, APP_BIN_PATH,
VERSION, VERSION_DISPLAY,
USER_CONFIG_DIR, USER_TOOLS_DIR, USER_CONFIG_FILE,
DEFAULT_CONFIG,
)
from os_detect import CURRENT_OS, REQUIRED_PACKAGES, PACKAGE_UPDATE_CMDS, PACKAGE_INSTALL_CMDS
console = Console()
VENV_DIR_NAME = "venv"
REQUIREMENTS = "requirements.txt"
# ── Privilege check ────────────────────────────────────────────────────────────
def check_root():
if os.geteuid() != 0:
console.print(Panel(
"[error]This installer must be run as root.\n"
"Use: [bold]sudo python3 install.py[/bold][/error]",
border_style="red",
))
sys.exit(1)
# ── OS compatibility check ─────────────────────────────────────────────────────
def check_os_compatibility():
info = CURRENT_OS
console.print(
f"[dim]Detected: OS={info.system} | distro={info.distro_id or 'n/a'} | "
f"pkg_mgr={info.pkg_manager or 'none'} | arch={info.arch}[/dim]"
)
if info.system == "windows":
console.print(Panel(
"[error]Windows is not supported natively.[/error]\n"
"Use WSL2 with a Kali or Ubuntu image.",
border_style="red",
))
sys.exit(1)
if info.is_wsl:
console.print("[warning]WSL detected. Wireless tools will NOT work in WSL.[/warning]")
if info.system == "macos":
console.print(Panel(
"[warning]macOS support is partial.[/warning]\n"
"Network/wireless tools require Linux. OSINT and web tools work.",
border_style="yellow",
))
if not shutil.which("brew"):
console.print("[error]Homebrew not found. Install it first: https://brew.sh[/error]")
sys.exit(1)
if not info.pkg_manager:
console.print("[warning]No supported package manager found.[/warning]")
console.print("[dim]Supported: apt-get, pacman, dnf, zypper, apk, brew[/dim]")
# ── Internet check ─────────────────────────────────────────────────────────────
def check_internet() -> bool:
console.print("[dim]Checking internet...[/dim]")
for host in ("https://github.com", "https://www.google.com"):
r = subprocess.run(
["curl", "-sSf", "--max-time", "8", host],
capture_output=True,
)
if r.returncode == 0:
console.print("[success]✔ Internet connection OK[/success]")
return True
console.print("[error]✘ No internet connection[/error]")
return False
# ── System packages ────────────────────────────────────────────────────────────
def install_system_packages():
mgr = CURRENT_OS.pkg_manager
if not mgr:
console.print("[warning]Skipping system packages — no package manager found.[/warning]")
return
# Use sudo only when not already root (uid != 0).
# Inside Docker we run as root and sudo is not installed.
priv = "" if os.geteuid() == 0 else "sudo "
# Update index first (skip for brew — not needed)
if mgr != "brew":
update_cmd = PACKAGE_UPDATE_CMDS.get(mgr, "")
if update_cmd:
console.print(f"[dim]Updating package index ({mgr})...[/dim]")
subprocess.run(f"{priv}{update_cmd}", shell=True, check=False)
packages = REQUIRED_PACKAGES.get(mgr, [])
if not packages:
return
install_tpl = PACKAGE_INSTALL_CMDS[mgr]
cmd = install_tpl.format(packages=" ".join(packages))
console.print(f"[dim]Installing system dependencies ({mgr})...[/dim]")
result = subprocess.run(f"{priv}{cmd}", shell=True, check=False)
if result.returncode != 0:
console.print("[warning]Some packages failed — you may need to install them manually.[/warning]")
# ── App directory ──────────────────────────────────────────────────────────────
def _is_source_dir() -> bool:
return (Path(__file__).resolve().parent / "hackingtool.py").exists()
def prepare_install_dir():
if APP_INSTALL_DIR.exists():
console.print(f"[warning]{APP_INSTALL_DIR} already exists.[/warning]")
if not Confirm.ask("Replace it? This removes the existing installation.", default=False):
console.print("[error]Installation aborted.[/error]")
sys.exit(1)
subprocess.run(["rm", "-rf", str(APP_INSTALL_DIR)], check=True)
APP_INSTALL_DIR.mkdir(parents=True, exist_ok=True)
def install_source() -> bool:
source_dir = Path(__file__).resolve().parent
if _is_source_dir() and source_dir != APP_INSTALL_DIR:
# Already in a local clone — copy instead of re-cloning
console.print(f"[dim]Copying source from {source_dir}...[/dim]")
# Remove first to ensure clean copy (prepare_install_dir may have created it)
if APP_INSTALL_DIR.exists():
subprocess.run(["rm", "-rf", str(APP_INSTALL_DIR)], check=True)
subprocess.run(["cp", "-a", str(source_dir), str(APP_INSTALL_DIR)], check=True)
# Fix ownership so git doesn't complain about "dubious ownership"
subprocess.run(["chown", "-R", "root:root", str(APP_INSTALL_DIR)], check=False)
console.print("[success]✔ Source copied (no re-clone needed)[/success]")
return True
# Not running from source — clone from GitHub
console.print(f"[dim]Cloning {REPO_URL}...[/dim]")
r = subprocess.run(["git", "clone", "--depth", "1", REPO_URL, str(APP_INSTALL_DIR)], check=False)
if r.returncode == 0:
console.print("[success]✔ Repository cloned[/success]")
return True
console.print("[error]✘ Failed to clone repository[/error]")
return False
# ── Python venv ────────────────────────────────────────────────────────────────
def create_venv_and_install():
venv_path = APP_INSTALL_DIR / VENV_DIR_NAME
console.print("[dim]Creating virtual environment...[/dim]")
subprocess.run([sys.executable, "-m", "venv", str(venv_path)], check=True)
pip = str(venv_path / "bin" / "pip")
req = APP_INSTALL_DIR / REQUIREMENTS
if req.exists():
console.print("[dim]Installing Python requirements...[/dim]")
subprocess.run([pip, "install", "--quiet", "-r", str(req)], check=False)
else:
console.print("[warning]requirements.txt not found — skipping pip install.[/warning]")
# ── Launcher script ────────────────────────────────────────────────────────────
def create_launcher():
launcher = APP_INSTALL_DIR / "hackingtool.sh"
launcher.write_text(
"#!/bin/bash\n"
f'source "{APP_INSTALL_DIR / VENV_DIR_NAME}/bin/activate"\n'
f'python3 "{APP_INSTALL_DIR / "hackingtool.py"}" "$@"\n'
)
launcher.chmod(0o755)
if APP_BIN_PATH.exists():
APP_BIN_PATH.unlink()
shutil.move(str(launcher), str(APP_BIN_PATH))
console.print(f"[success]✔ Launcher installed at {APP_BIN_PATH}[/success]")
# ── User directories ───────────────────────────────────────────────────────────
def create_user_directories():
import json
USER_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
USER_TOOLS_DIR.mkdir(parents=True, exist_ok=True)
if not USER_CONFIG_FILE.exists():
USER_CONFIG_FILE.write_text(json.dumps(DEFAULT_CONFIG, indent=2, sort_keys=True))
console.print(f"[success]✔ Config created at {USER_CONFIG_FILE}[/success]")
console.print(f"[success]✔ Tools directory: {USER_TOOLS_DIR}[/success]")
# ── Entry point ────────────────────────────────────────────────────────────────
def main():
check_root()
console.clear()
console.print(Panel(
Text(f"HackingTool Installer {VERSION_DISPLAY}", style="bold magenta"),
box=box.DOUBLE, border_style="bright_magenta",
))
check_os_compatibility()
if not check_internet():
sys.exit(1)
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}")) as p:
p.add_task("Installing system packages...", total=None)
install_system_packages()
prepare_install_dir()
if not install_source():
sys.exit(1)
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}")) as p:
p.add_task("Setting up virtualenv & requirements...", total=None)
create_venv_and_install()
create_launcher()
create_user_directories()
console.print(Panel(
"[bold magenta]Installation complete![/bold magenta]\n\n"
"Type [bold cyan]hackingtool[/bold cyan] in a terminal to start.",
border_style="magenta",
))
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
console.print("\n[error]Installation interrupted.[/error]")
sys.exit(1)
except subprocess.CalledProcessError as e:
console.print(f"[error]Command failed: {e}[/error]")
sys.exit(1) | --- +++ @@ -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 or 'n/a'} | "
@@ -132,6 +133,7 @@ # ── App directory ──────────────────────────────────────────────────────────────
def _is_source_dir() -> bool:
+ """Check if install.py is being run from a local clone (hackingtool.py exists alongside it)."""
return (Path(__file__).resolve().parent / "hackingtool.py").exists()
@@ -146,6 +148,7 @@
def install_source() -> bool:
+ """Clone the repo or copy from local source if already in a clone."""
source_dir = Path(__file__).resolve().parent
if _is_source_dir() and source_dir != APP_INSTALL_DIR:
@@ -205,6 +208,11 @@ # ── User directories ───────────────────────────────────────────────────────────
def create_user_directories():
+ """
+ Create ~/.hackingtool/ and write initial config.json.
+ Uses Path.home() — always correct regardless of username or OS.
+ Safe to run as root (creates /root/.hackingtool/) or as a normal user.
+ """
import json
USER_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
USER_TOOLS_DIR.mkdir(parents=True, exist_ok=True)
@@ -261,4 +269,4 @@ sys.exit(1)
except subprocess.CalledProcessError as e:
console.print(f"[error]Command failed: {e}[/error]")
- sys.exit(1)+ sys.exit(1)
| 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 with: sudo apt install python3.10"
)
sys.exit(1)
import os
import platform
import socket
import datetime
import random
import webbrowser
from itertools import zip_longest
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.prompt import Prompt, Confirm
from rich.align import Align
from rich.text import Text
from rich import box
from rich.rule import Rule
from rich.columns import Columns
from core import HackingToolsCollection, clear_screen, console
from constants import VERSION_DISPLAY, REPO_WEB_URL
from config import get_tools_dir
from tools.anonsurf import AnonSurfTools
from tools.ddos import DDOSTools
from tools.exploit_frameworks import ExploitFrameworkTools
from tools.forensics import ForensicTools
from tools.information_gathering import InformationGatheringTools
from tools.other_tools import OtherTools
from tools.payload_creator import PayloadCreatorTools
from tools.phishing_attack import PhishingAttackTools
from tools.post_exploitation import PostExploitationTools
from tools.remote_administration import RemoteAdministrationTools
from tools.reverse_engineering import ReverseEngineeringTools
from tools.sql_injection import SqlInjectionTools
from tools.steganography import SteganographyTools
from tools.tool_manager import ToolManager
from tools.web_attack import WebAttackTools
from tools.wireless_attack import WirelessAttackTools
from tools.wordlist_generator import WordlistGeneratorTools
from tools.xss_attack import XSSAttackTools
from tools.active_directory import ActiveDirectoryTools
from tools.cloud_security import CloudSecurityTools
from tools.mobile_security import MobileSecurityTools
# ── Tool registry ──────────────────────────────────────────────────────────────
# (full_title, icon, menu_label)
# menu_label is the concise name shown in the 2-column main menu grid.
# full_title is shown when entering the category.
tool_definitions = [
("Anonymously Hiding Tools", "🛡 ", "Anonymously Hiding"),
("Information gathering tools", "🔍", "Information Gathering"),
("Wordlist Generator", "📚", "Wordlist Generator"),
("Wireless attack tools", "📶", "Wireless Attack"),
("SQL Injection Tools", "🧩", "SQL Injection"),
("Phishing attack tools", "🎣", "Phishing Attack"),
("Web Attack tools", "🌐", "Web Attack"),
("Post exploitation tools", "🔧", "Post Exploitation"),
("Forensic tools", "🕵 ", "Forensics"),
("Payload creation tools", "📦", "Payload Creation"),
("Exploit framework", "🧰", "Exploit Framework"),
("Reverse engineering tools", "🔁", "Reverse Engineering"),
("DDOS Attack Tools", "⚡", "DDOS Attack"),
("Remote Administrator Tools (RAT)", "🖥 ", "Remote Admin (RAT)"),
("XSS Attack Tools", "💥", "XSS Attack"),
("Steganography tools", "🖼 ", "Steganography"),
("Active Directory Tools", "🏢", "Active Directory"),
("Cloud Security Tools", "☁ ", "Cloud Security"),
("Mobile Security Tools", "📱", "Mobile Security"),
("Other tools", "✨", "Other Tools"),
("Update or Uninstall | Hackingtool", "♻ ", "Update / Uninstall"),
]
all_tools = [
AnonSurfTools(),
InformationGatheringTools(),
WordlistGeneratorTools(),
WirelessAttackTools(),
SqlInjectionTools(),
PhishingAttackTools(),
WebAttackTools(),
PostExploitationTools(),
ForensicTools(),
PayloadCreatorTools(),
ExploitFrameworkTools(),
ReverseEngineeringTools(),
DDOSTools(),
RemoteAdministrationTools(),
XSSAttackTools(),
SteganographyTools(),
ActiveDirectoryTools(),
CloudSecurityTools(),
MobileSecurityTools(),
OtherTools(),
ToolManager(),
]
# Used by generate_readme.py
class AllTools(HackingToolsCollection):
TITLE = "All tools"
TOOLS = all_tools
# ── Help overlay ───────────────────────────────────────────────────────────────
def show_help():
console.print(Panel(
Text.assemble(
(" Main menu\n", "bold white"),
(" ─────────────────────────────────────\n", "dim"),
(" 1–20 ", "bold cyan"), ("open a category\n", "white"),
(" 21 ", "bold cyan"), ("Update / Uninstall hackingtool\n", "white"),
(" / or s ", "bold cyan"), ("search tools by name or keyword\n", "white"),
(" t ", "bold cyan"), ("filter tools by tag (osint, web, c2, ...)\n", "white"),
(" r ", "bold cyan"), ("recommend tools for a task\n", "white"),
(" ? ", "bold cyan"), ("show this help\n", "white"),
(" q ", "bold cyan"), ("quit hackingtool\n\n", "white"),
(" Inside a category\n", "bold white"),
(" ─────────────────────────────────────\n", "dim"),
(" 1–N ", "bold cyan"), ("select a tool\n", "white"),
(" 99 ", "bold cyan"), ("back to main menu\n", "white"),
(" 98 ", "bold cyan"), ("open project page (if available)\n\n", "white"),
(" Inside a tool\n", "bold white"),
(" ─────────────────────────────────────\n", "dim"),
(" 1 ", "bold cyan"), ("install tool\n", "white"),
(" 2 ", "bold cyan"), ("run tool\n", "white"),
(" 99 ", "bold cyan"), ("back to category\n", "white"),
),
title="[bold magenta] ? Quick Help [/bold magenta]",
border_style="magenta",
box=box.ROUNDED,
padding=(0, 2),
))
Prompt.ask("[dim]Press Enter to return[/dim]", default="")
# ── Header: ASCII art + live system info ──────────────────────────────────────
# Full "HACKING TOOL" block-letter art — 12 lines, split layout with stats
_BANNER_ART = [
" ██╗ ██╗ █████╗ ██████╗██╗ ██╗██╗███╗ ██╗ ██████╗ ",
" ██║ ██║██╔══██╗██╔════╝██║ ██╔╝██║████╗ ██║██╔════╝ ",
" ███████║███████║██║ █████╔╝ ██║██╔██╗ ██║██║ ███╗",
" ██╔══██║██╔══██║██║ ██╔═██╗ ██║██║╚██╗██║██║ ██║",
" ██║ ██║██║ ██║╚██████╗██║ ██╗██║██║ ╚████║╚██████╔╝",
" ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═════╝ ",
" ████████╗ ██████╗ ██████╗ ██╗",
" ╚══██╔══╝██╔═══██╗██╔═══██╗██║",
" ██║ ██║ ██║██║ ██║██║",
" ██║ ██║ ██║██║ ██║██║",
" ██║ ╚██████╔╝╚██████╔╝███████╗",
" ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝",
]
_QUOTES = [
'"The quieter you become, the more you can hear."',
'"Offense informs defense."',
'"There is no patch for human stupidity."',
'"In God we trust. All others we monitor."',
'"Hackers are the immune system of the internet."',
'"Every system is hackable — know yours before others do."',
'"Enumerate before you exploit."',
'"A scope defines your playground."',
'"The more you sweat in training, the less you bleed in battle."',
'"Security is a process, not a product."',
]
def _sys_info() -> dict:
info: dict = {}
# OS pretty name
try:
info["os"] = platform.freedesktop_os_release().get("PRETTY_NAME", "")
except Exception:
info["os"] = ""
if not info["os"]:
info["os"] = f"{platform.system()} {platform.release()}"
info["kernel"] = platform.release()
# Current user
try:
info["user"] = os.getlogin()
except Exception:
info["user"] = os.environ.get("USER", os.environ.get("LOGNAME", "root"))
info["host"] = socket.gethostname()
# Local IP — connect to a routable address without sending data
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(0)
s.connect(("10.254.254.254", 1))
info["ip"] = s.getsockname()[0]
s.close()
except Exception:
info["ip"] = "127.0.0.1"
info["time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
return info
def _build_header() -> Panel:
info = _sys_info()
# 12 stat lines paired with the 12 art lines
stat_lines = [
(" os › ", info["os"][:34]),
(" kernel › ", info["kernel"][:34]),
(" user › ", f"{info['user']} @ {info['host'][:20]}"),
(" ip › ", info["ip"]),
(" tools › ", f"{len(all_tools)} categories · 185+ modules"),
(" session › ", info["time"]),
("", ""),
(" python › ", f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"),
(" arch › ", platform.machine()),
(" status › ", "✔ READY"),
("", ""),
("", ""),
]
grid = Table.grid(padding=0)
grid.add_column("art", no_wrap=True)
grid.add_column("sep", no_wrap=True)
grid.add_column("lbl", no_wrap=True)
grid.add_column("val", no_wrap=True)
for art_line, (lbl_text, val_text) in zip(_BANNER_ART, stat_lines):
grid.add_row(
Text(art_line, style="bold bright_green"),
Text(" │ ", style="dim green"),
Text(lbl_text, style="dim green"),
Text(val_text, style="bright_green"),
)
# Quote + warning below the split row
quote = random.choice(_QUOTES)
body = Table.grid(padding=(0, 0))
body.add_column()
body.add_row(grid)
body.add_row(Text(""))
body.add_row(Text(f" {quote}", style="italic dim"))
body.add_row(Text(" ⚠ For authorized security testing only",
style="bold dim red"))
return Panel(
body,
title=f"[bold bright_magenta][ HackingTool {VERSION_DISPLAY} ][/bold bright_magenta]",
title_align="left",
subtitle=f"[dim][ {info['time']} ][/dim]",
subtitle_align="right",
border_style="bright_magenta",
box=box.HEAVY,
padding=(0, 1),
)
# ── Main menu renderer ─────────────────────────────────────────────────────────
def build_menu():
clear_screen()
console.print(_build_header())
# ── 2-column category grid ──
# Items 1-17 in two columns, item 18 (ToolManager) shown separately
categories = tool_definitions[:-1] # 17 items
update_def = tool_definitions[-1] # ToolManager
mid = (len(categories) + 1) // 2 # 9 (left), 8 (right)
left = list(enumerate(categories[:mid], start=1))
right = list(enumerate(categories[mid:], start=mid + 1))
grid = Table.grid(padding=(0, 1), expand=True)
grid.add_column("ln", justify="right", style="bold magenta", width=5)
grid.add_column("li", width=3)
grid.add_column("lt", style="magenta", ratio=1, no_wrap=True)
grid.add_column("gap", width=3)
grid.add_column("rn", justify="right", style="bold magenta", width=5)
grid.add_column("ri", width=3)
grid.add_column("rt", style="magenta", ratio=1, no_wrap=True)
for (li, (_, lic, ll)), r in zip_longest(left, right, fillvalue=None):
if r:
ri, (_, ric, rl) = r
grid.add_row(str(li), lic, ll, "", str(ri), ric, rl)
else:
grid.add_row(str(li), lic, ll, "", "", "", "")
console.print(Panel(
grid,
title="[bold magenta] Select a Category [/bold magenta]",
border_style="bright_magenta",
box=box.ROUNDED,
padding=(0, 1),
))
# ── ToolManager row ──
tm_num = len(categories) + 1
console.print(
f" [bold magenta] {tm_num}[/bold magenta] {update_def[1]} "
f"[magenta]{update_def[2]}[/magenta]"
)
# ── Claude-style dual-line prompt area ──
console.print(Rule(style="dim magenta"))
console.print(
" [dim cyan]/[/dim cyan][dim]search[/dim] "
"[dim cyan]t[/dim cyan] [dim]tags[/dim] "
"[dim cyan]r[/dim cyan] [dim]recommend[/dim] "
"[dim cyan]?[/dim cyan] [dim]help[/dim] "
"[dim cyan]q[/dim cyan] [dim]quit[/dim]"
)
# ── Search ─────────────────────────────────────────────────────────────────────
def _collect_all_tools() -> list[tuple]:
from core import HackingTool, HackingToolsCollection
results = []
def _walk(items, parent_title=""):
for item in items:
if isinstance(item, HackingToolsCollection):
_walk(item.TOOLS, item.TITLE)
elif isinstance(item, HackingTool):
results.append((item, parent_title))
_walk(all_tools)
return results
def _get_all_tags() -> dict[str, list[tuple]]:
import re
_rules = {
r'(osint|harvester|maigret|holehe|spiderfoot|sherlock|recon)': 'osint',
r'(subdomain|subfinder|amass|sublist|subdomainfinder)': 'recon',
r'(scanner|scan|nmap|masscan|rustscan|nikto|nuclei|trivy)': 'scanner',
r'(brute|gobuster|ffuf|dirb|dirsearch|ferox|hashcat|john|kerbrute)': 'bruteforce',
r'(web|http|proxy|zap|xss|sql|wafw00f|arjun|caido|mitmproxy)': 'web',
r'(wireless|wifi|wlan|airgeddon|bettercap|wifite|fluxion|deauth)': 'wireless',
r'(phish|social.media|evilginx|setoolkit|social.fish|social.engineer)': 'social-engineering',
r'(c2|sliver|havoc|mythic|pwncat|reverse.shell|pyshell)': 'c2',
r'(privesc|peass|linpeas|winpeas)': 'privesc',
r'(tunnel|pivot|ligolo|chisel|proxy|anon)': 'network',
r'(password|credential|hash|crack|secret|trufflehog|gitleaks)': 'credentials',
r'(forensic|memory|volatility|binwalk|autopsy|wireshark|pspy)': 'forensics',
r'(reverse.eng|ghidra|radare|jadx|androguard|apk)': 'reversing',
r'(cloud|aws|azure|gcp|kubernetes|prowler|scout|pacu)': 'cloud',
r'(mobile|android|ios|frida|mobsf|objection|droid)': 'mobile',
r'(active.directory|bloodhound|netexec|impacket|responder|certipy|kerberos|winrm|smb|ldap)': 'active-directory',
r'(ddos|dos|slowloris|goldeneye|ufonet)': 'ddos',
r'(payload|msfvenom|fatrat|venom|stitch|enigma)': 'payload',
r'(crawler|spider|katana|gospider)': 'crawler',
}
tag_index: dict[str, list[tuple]] = {}
for tool, cat in _collect_all_tools():
combined = f"{tool.TITLE} {tool.DESCRIPTION}".lower()
# Manual tags first
tool_tags = set(getattr(tool, "TAGS", []) or [])
# Auto-derive tags from title/description
for pattern, tag in _rules.items():
if re.search(pattern, combined, re.IGNORECASE):
tool_tags.add(tag)
for t in tool_tags:
tag_index.setdefault(t, []).append((tool, cat))
return tag_index
def filter_by_tag():
tag_index = _get_all_tags()
sorted_tags = sorted(tag_index.keys())
# Show tags in a compact grid
console.print(Panel(
" ".join(f"[bold cyan]{t}[/bold cyan]([dim]{len(tag_index[t])}[/dim])" for t in sorted_tags),
title="[bold magenta] Available Tags [/bold magenta]",
border_style="magenta", box=box.ROUNDED, padding=(0, 2),
))
tag = Prompt.ask("[bold cyan]Enter tag[/bold cyan]", default="").strip().lower()
if not tag or tag not in tag_index:
if tag:
console.print(f"[dim]Tag '{tag}' not found.[/dim]")
Prompt.ask("[dim]Press Enter to return[/dim]", default="")
return
matches = tag_index[tag]
table = Table(
title=f"Tools tagged '{tag}'",
box=box.SIMPLE_HEAD, show_lines=True,
)
table.add_column("No.", justify="center", style="bold cyan", width=5)
table.add_column("", width=2)
table.add_column("Tool", style="bold yellow", min_width=20)
table.add_column("Category", style="magenta", min_width=15)
for i, (tool, cat) in enumerate(matches, start=1):
status = "[green]✔[/green]" if tool.is_installed else "[dim]✘[/dim]"
table.add_row(str(i), status, tool.TITLE, cat)
table.add_row("99", "", "Back to main menu", "")
console.print(table)
raw = Prompt.ask("[bold cyan]>[/bold cyan]", default="").strip()
if not raw or raw == "99":
return
try:
idx = int(raw)
except ValueError:
return
if 1 <= idx <= len(matches):
tool, cat = matches[idx - 1]
tool.show_options()
_RECOMMENDATIONS = {
"scan a network": ["scanner", "port-scanner"],
"find subdomains": ["recon"],
"scan for vulnerabilities": ["scanner", "web"],
"crack passwords": ["bruteforce", "credentials"],
"find leaked secrets": ["credentials"],
"phishing campaign": ["social-engineering"],
"post exploitation": ["c2", "privesc"],
"pivot through network": ["network"],
"pentest active directory": ["active-directory"],
"pentest web application": ["web", "scanner"],
"pentest cloud": ["cloud"],
"pentest mobile app": ["mobile"],
"reverse engineer binary": ["reversing"],
"capture wifi handshake": ["wireless"],
"intercept http traffic": ["web", "network"],
"forensic analysis": ["forensics"],
"ddos testing": ["ddos"],
"create payloads": ["payload"],
"find xss vulnerabilities": ["web"],
"brute force directories": ["bruteforce", "web"],
"osint / recon a target": ["osint", "recon"],
"hide my identity": ["network"],
}
def recommend_tools():
table = Table(
title="What do you want to do?",
box=box.SIMPLE_HEAD,
)
table.add_column("No.", justify="center", style="bold cyan", width=5)
table.add_column("Task", style="bold yellow")
tasks = list(_RECOMMENDATIONS.keys())
for i, task in enumerate(tasks, start=1):
table.add_row(str(i), task.title())
table.add_row("99", "Back to main menu")
console.print(table)
raw = Prompt.ask("[bold cyan]>[/bold cyan]", default="").strip()
if not raw or raw == "99":
return
try:
idx = int(raw)
except ValueError:
return
if 1 <= idx <= len(tasks):
task = tasks[idx - 1]
tag_names = _RECOMMENDATIONS[task]
tag_index = _get_all_tags()
# Collect unique tools across all matching tags
seen = set()
matches = []
for tag in tag_names:
for tool, cat in tag_index.get(tag, []):
if id(tool) not in seen:
seen.add(id(tool))
matches.append((tool, cat))
if not matches:
console.print("[dim]No tools found for this task.[/dim]")
Prompt.ask("[dim]Press Enter to return[/dim]", default="")
return
console.print(Panel(
f"[bold]Recommended tools for: {task.title()}[/bold]",
border_style="green", box=box.ROUNDED,
))
rtable = Table(box=box.SIMPLE_HEAD, show_lines=True)
rtable.add_column("No.", justify="center", style="bold cyan", width=5)
rtable.add_column("", width=2)
rtable.add_column("Tool", style="bold yellow", min_width=20)
rtable.add_column("Category", style="magenta")
for i, (tool, cat) in enumerate(matches, start=1):
status = "[green]✔[/green]" if tool.is_installed else "[dim]✘[/dim]"
rtable.add_row(str(i), status, tool.TITLE, cat)
rtable.add_row("99", "", "Back", "")
console.print(rtable)
raw2 = Prompt.ask("[bold cyan]>[/bold cyan]", default="").strip()
if raw2 and raw2 != "99":
try:
ridx = int(raw2)
if 1 <= ridx <= len(matches):
matches[ridx - 1][0].show_options()
except ValueError:
pass
def search_tools(query: str | None = None):
if query is None:
query = Prompt.ask("[bold cyan]/ Search[/bold cyan]", default="").strip().lower()
else:
query = query.lower()
if not query:
return
all_tool_list = _collect_all_tools()
# Match against title + description + tags
matches = []
for tool, category in all_tool_list:
title = (tool.TITLE or "").lower()
desc = (tool.DESCRIPTION or "").lower()
tags = " ".join(getattr(tool, "TAGS", []) or []).lower()
if query in title or query in desc or query in tags:
matches.append((tool, category))
if not matches:
console.print(f"[dim]No tools found matching '{query}'[/dim]")
Prompt.ask("[dim]Press Enter to return[/dim]", default="")
return
# Display results
table = Table(
title=f"Search results for '{query}'",
box=box.SIMPLE_HEAD, show_lines=True,
)
table.add_column("No.", justify="center", style="bold cyan", width=5)
table.add_column("Tool", style="bold yellow", min_width=20)
table.add_column("Category", style="magenta", min_width=15)
table.add_column("Description", style="white", overflow="fold")
for i, (tool, cat) in enumerate(matches, start=1):
desc = (tool.DESCRIPTION or "—").splitlines()[0]
table.add_row(str(i), tool.TITLE, cat, desc)
table.add_row("99", "Back to main menu", "", "")
console.print(table)
raw = Prompt.ask("[bold cyan]>[/bold cyan]", default="").strip().lower()
if not raw or raw == "99":
return
try:
idx = int(raw)
except ValueError:
return
if 1 <= idx <= len(matches):
tool, cat = matches[idx - 1]
console.print(Panel(
f"[bold magenta]{tool.TITLE}[/bold magenta] [dim]({cat})[/dim]",
border_style="magenta", box=box.ROUNDED,
))
tool.show_options()
# ── Main interaction loop ──────────────────────────────────────────────────────
def interact_menu():
while True:
try:
build_menu()
raw = Prompt.ask(
"[bold magenta]╰─>[/bold magenta]", default=""
).strip()
if not raw:
continue
raw_lower = raw.lower()
if raw_lower in ("?", "help"):
show_help()
continue
if raw.startswith("/"):
# Inline search: /subdomain → search immediately
query = raw[1:].strip()
search_tools(query=query if query else None)
continue
if raw_lower in ("s", "search"):
search_tools()
continue
if raw_lower in ("t", "tag", "tags", "filter"):
filter_by_tag()
continue
if raw_lower in ("r", "rec", "recommend"):
recommend_tools()
continue
if raw_lower in ("q", "quit", "exit"):
console.print(Panel(
"[bold white on magenta] Goodbye — Come Back Safely [/bold white on magenta]",
box=box.HEAVY, border_style="magenta",
))
break
try:
choice = int(raw_lower)
except ValueError:
console.print("[red]⚠ Invalid input — enter a number, /query to search, or q to quit.[/red]")
Prompt.ask("[dim]Press Enter to continue[/dim]", default="")
continue
if 1 <= choice <= len(all_tools):
title, icon, _ = tool_definitions[choice - 1]
console.print(Panel(
f"[bold magenta]{icon} {title}[/bold magenta]",
border_style="magenta", box=box.ROUNDED,
))
try:
all_tools[choice - 1].show_options()
except Exception as e:
console.print(Panel(
f"[red]Error while opening {title}[/red]\n{e}",
border_style="red",
))
Prompt.ask("[dim]Press Enter to return to main menu[/dim]", default="")
else:
console.print(f"[red]⚠ Choose 1–{len(all_tools)}, ? for help, or q to quit.[/red]")
Prompt.ask("[dim]Press Enter to continue[/dim]", default="")
except KeyboardInterrupt:
console.print("\n[bold red]Interrupted — exiting[/bold red]")
break
# ── Entry point ────────────────────────────────────────────────────────────────
def main():
try:
from os_detect import CURRENT_OS
if CURRENT_OS.system == "windows":
console.print(Panel("[bold red]Please run this tool on Linux or macOS.[/bold red]"))
if Confirm.ask("Open guidance link in your browser?", default=True):
webbrowser.open_new_tab(f"{REPO_WEB_URL}#windows")
return
if CURRENT_OS.system not in ("linux", "macos"):
console.print(f"[yellow]Unsupported OS: {CURRENT_OS.system}. Proceeding anyway...[/yellow]")
get_tools_dir() # ensures ~/.hackingtool/tools/ exists
interact_menu()
except KeyboardInterrupt:
console.print("\n[bold red]Exiting...[/bold red]")
if __name__ == "__main__":
main() | --- +++ @@ -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 all collections and return (tool_instance, category_name) pairs."""
from core import HackingTool, HackingToolsCollection
results = []
@@ -342,6 +344,7 @@
def _get_all_tags() -> dict[str, list[tuple]]:
+ """Build tag → [(tool, category)] index from all tools."""
import re
_rules = {
r'(osint|harvester|maigret|holehe|spiderfoot|sherlock|recon)': 'osint',
@@ -379,6 +382,7 @@
def filter_by_tag():
+ """Show available tags, user picks one, show matching tools."""
tag_index = _get_all_tags()
sorted_tags = sorted(tag_index.keys())
@@ -452,6 +456,7 @@
def recommend_tools():
+ """Show common tasks, user picks one, show matching tools."""
table = Table(
title="What do you want to do?",
box=box.SIMPLE_HEAD,
@@ -523,6 +528,7 @@
def search_tools(query: str | None = None):
+ """Search tools — accepts inline query or prompts for one."""
if query is None:
query = Prompt.ask("[bold cyan]/ Search[/bold cyan]", default="").strip().lower()
else:
@@ -678,4 +684,4 @@
if __name__ == "__main__":
- main()+ main()
| 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_text())
return {**DEFAULT_CONFIG, **on_disk}
except (json.JSONDecodeError, OSError) as exc:
logger.warning("Config file unreadable (%s), using defaults.", exc)
return dict(DEFAULT_CONFIG)
def save(cfg: dict[str, Any]) -> None:
USER_CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
USER_CONFIG_FILE.write_text(json.dumps(cfg, indent=2, sort_keys=True))
def get_tools_dir() -> Path:
cfg = load()
tools_dir = Path(cfg.get("tools_dir", str(USER_TOOLS_DIR))).expanduser().resolve()
tools_dir.mkdir(parents=True, exist_ok=True)
return tools_dir
def get_sudo_cmd() -> str:
import shutil
return "doas" if shutil.which("doas") else "sudo" | --- +++ @@ -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:
+ """Write config to disk, creating parent directories if needed."""
USER_CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
USER_CONFIG_FILE.write_text(json.dumps(cfg, indent=2, sort_keys=True))
def get_tools_dir() -> Path:
+ """
+ Return the directory where external tools are stored.
+ Creates it if it does not exist.
+ Always an absolute path — never relies on process CWD.
+ """
cfg = load()
tools_dir = Path(cfg.get("tools_dir", str(USER_TOOLS_DIR))).expanduser().resolve()
tools_dir.mkdir(parents=True, exist_ok=True)
@@ -31,5 +38,6 @@
def get_sudo_cmd() -> str:
+ """Return 'doas' if available, else 'sudo'. Never hardcode 'sudo'."""
import shutil
return "doas" if shutil.which("doas") else "sudo" | 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 = "" # "debian", "rhel", etc. (from ID_LIKE)
distro_version: str = "" # "2024.1", "22.04", etc.
pkg_manager: str = "" # "apt-get", "pacman", "dnf", "brew", etc.
is_root: bool = False
home_dir: Path = field(default_factory=Path.home)
is_wsl: bool = False # Windows Subsystem for Linux
arch: str = "" # "x86_64", "aarch64", "arm64"
def detect() -> OSInfo:
import os
system_raw = platform.system()
system = system_raw.lower()
if system == "darwin":
system = "macos"
info = OSInfo(
system = system,
is_root = (os.geteuid() == 0) if hasattr(os, "geteuid") else False,
home_dir = Path.home(),
arch = platform.machine(),
)
# ── Linux-specific ─────────────────────────────────────────────────────────
if system == "linux":
# Detect WSL
try:
info.is_wsl = "microsoft" in Path("/proc/version").read_text().lower()
except (FileNotFoundError, PermissionError):
pass
# Read /etc/os-release (standard on all modern distros)
os_release: dict[str, str] = {}
for path in ("/etc/os-release", "/usr/lib/os-release"):
try:
for line in Path(path).read_text().splitlines():
k, _, v = line.partition("=")
os_release[k.strip()] = v.strip().strip('"')
break
except FileNotFoundError:
continue
info.distro_id = os_release.get("ID", "").lower()
info.distro_like = os_release.get("ID_LIKE", "").lower()
info.distro_version = os_release.get("VERSION_ID", "")
# ── Package manager detection (in priority order) ──────────────────────────
for mgr in ("apt-get", "pacman", "dnf", "zypper", "apk", "brew", "pkg"):
if shutil.which(mgr):
info.pkg_manager = mgr
break
return info
# Module-level singleton — computed once on import
CURRENT_OS: OSInfo = detect()
# ── Per-OS package manager commands ────────────────────────────────────────────
PACKAGE_INSTALL_CMDS: dict[str, str] = {
"apt-get": "apt-get install -y {packages}",
"pacman": "pacman -S --noconfirm {packages}",
"dnf": "dnf install -y {packages}",
"zypper": "zypper install -y {packages}",
"apk": "apk add {packages}",
"brew": "brew install {packages}",
"pkg": "pkg install -y {packages}",
}
PACKAGE_UPDATE_CMDS: dict[str, str] = {
"apt-get": "apt-get update -qq && apt-get upgrade -y",
"pacman": "pacman -Syu --noconfirm",
"dnf": "dnf upgrade -y",
"zypper": "zypper update -y",
"apk": "apk update && apk upgrade",
"brew": "brew update && brew upgrade",
"pkg": "pkg update && pkg upgrade -y",
}
# Core system packages needed per package manager
REQUIRED_PACKAGES: dict[str, list[str]] = {
"apt-get": ["git", "python3-pip", "python3-venv", "curl", "wget",
"ruby", "ruby-dev", "golang-go", "php", "default-jre-headless"],
"pacman": ["git", "python-pip", "curl", "wget",
"ruby", "go", "php", "jre-openjdk-headless"],
"dnf": ["git", "python3-pip", "curl", "wget",
"ruby", "golang", "php", "java-17-openjdk-headless"],
"zypper": ["git", "python3-pip", "curl", "wget", "ruby", "go", "php"],
"brew": ["git", "python3", "curl", "wget", "ruby", "go", "php"],
"pkg": ["git", "python3", "py39-pip", "curl", "wget", "ruby", "go", "php83"],
}
def install_packages(packages: list[str], os_info: OSInfo | None = None) -> bool:
import subprocess
if os_info is None:
os_info = CURRENT_OS
mgr = os_info.pkg_manager
if mgr not in PACKAGE_INSTALL_CMDS:
print(f"[warning] Unknown package manager. Install manually: {packages}")
return False
cmd_template = PACKAGE_INSTALL_CMDS[mgr]
pkg_str = " ".join(packages)
cmd = cmd_template.format(packages=pkg_str)
# Prepend privilege escalation only on Linux (brew on macOS doesn't need sudo)
if os_info.system == "linux" and not os_info.is_root:
from constants import PRIV_CMD
cmd = f"{PRIV_CMD} {cmd}"
result = subprocess.run(cmd, shell=True, check=False)
return result.returncode == 0 | --- +++ @@ -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: OSInfo | None = None) -> bool:
+ """Install system packages using the detected package manager."""
import subprocess
if os_info is None:
os_info = CURRENT_OS
| 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 to format the content using black
linted_content = black.format_str(content, mode=black.FileMode(**config))
except black.NothingChanged:
# If nothing changed, log the info and return the original content
print("\nInfo: No changes were made during formatting.\n")
linted_content = content
except Exception as error:
# If any other exception occurs, log the error and return the original content
print(f"\nError: Could not format due to {error}\n")
linted_content = content
return linted_content
def lint_files(self, files_dict: FilesDict, config: dict = None) -> FilesDict:
if config is None:
config = {}
for filename, content in files_dict.items():
extension = filename[
filename.rfind(".") :
].lower() # Ensure case insensitivity
if extension in self.linters:
original_content = content
linted_content = self.linters[extension](content, config)
if linted_content != original_content:
print(f"Linted {filename}.")
else:
print(f"No changes made for {filename}.")
files_dict[filename] = linted_content
else:
print(f"No linter registered for {filename}.")
return files_dict | --- +++ @@ -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 occurs during formatting, it logs the error and returns the original content.
+ """
try:
# Try to format the content using black
linted_content = black.format_str(content, mode=black.FileMode(**config))
@@ -25,6 +29,21 @@ return linted_content
def lint_files(self, files_dict: FilesDict, config: dict = None) -> FilesDict:
+ """
+ Lints files based on their extension using registered linting functions.
+
+ Parameters
+ ----------
+ files_dict : FilesDict
+ The dictionary of file names to their respective source code content.
+ config : dict, optional
+ A dictionary of configuration options for the linting tools.
+
+ Returns
+ -------
+ FilesDict
+ The dictionary of file names to their respective source code content after linting.
+ """
if config is None:
config = {}
@@ -42,4 +61,4 @@ files_dict[filename] = linted_content
else:
print(f"No linter registered for {filename}.")
- return files_dict+ return files_dict
| 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
BENCHMARKS = {
"gptme": load_gptme,
"apps": load_apps,
"mbpp": load_mbpp,
}
def get_benchmark(name: str, config: BenchConfig) -> Benchmark:
if name not in BENCHMARKS:
raise ValueError(f"Unknown benchmark {name}.")
return BENCHMARKS[name](config.__getattribute__(name)) | --- +++ @@ -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 the benchmark is unknown.
+"""
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
@@ -12,6 +23,26 @@
def get_benchmark(name: str, config: BenchConfig) -> Benchmark:
+ """
+ Retrieves a Benchmark object by name. Raises ValueError if the benchmark is unknown.
+
+ Parameters
+ ----------
+ name : str
+ The name of the benchmark to retrieve.
+ config : BenchConfig
+ Configuration object for the benchmarks.
+
+ Returns
+ -------
+ Benchmark
+ The Benchmark object corresponding to the given name.
+
+ Raises
+ ------
+ ValueError
+ If the benchmark name is not found in the BENCHMARKS mapping.
+ """
if name not in BENCHMARKS:
raise ValueError(f"Unknown benchmark {name}.")
- return BENCHMARKS[name](config.__getattribute__(name))+ return BENCHMARKS[name](config.__getattribute__(name))
| 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:
self.start_line_pre_edit = start_line_pre_edit
self.hunk_len_pre_edit = hunk_len_pre_edit
self.start_line_post_edit = start_line_post_edit
self.hunk_len_post_edit = hunk_len_post_edit
self.category_counts = {RETAIN: 0, ADD: 0, REMOVE: 0}
self.lines = list()
self.add_lines(lines)
self.forward_block_len = 10
# Note that this assumption should not be done on hunk level, however, if the below is true, no validation is possible anyway.
if self.category_counts[RETAIN] == 0 and self.category_counts[REMOVE] == 0:
self.is_new_file = True
else:
self.is_new_file = False
def add_retained_line(self, line, index) -> None:
self.lines.insert(index, (RETAIN, line))
self.category_counts[RETAIN] += 1
def relabel_line(self, index, new_label) -> None:
old_label = self.lines[index][0]
self.lines[index] = (new_label, self.lines[index][1])
self.category_counts[old_label] -= 1
self.category_counts[new_label] += 1
def pop_line(self, line, index) -> None:
self.lines.pop(index)
assert self.category_counts[line[0]] > 0
self.category_counts[line[0]] -= 1
def add_lines(self, new_lines) -> None:
for line in new_lines:
self.lines.append(line)
self.category_counts[line[0]] += 1
def hunk_to_string(self) -> str:
string = f"@@ -{self.start_line_pre_edit},{self.hunk_len_pre_edit} +{self.start_line_post_edit},{self.hunk_len_post_edit} @@\n"
for line_type, line_content in self.lines:
line_prefix = (
" " if line_type == RETAIN else "+" if line_type == ADD else "-"
)
string += f"{line_prefix}{line_content}\n"
return string
def make_forward_block(self, hunk_ind: int, forward_block_len) -> str:
forward_lines = [
line[1] for line in self.lines[hunk_ind:] if not line[0] == ADD
]
forward_block = "\n".join(forward_lines[0:forward_block_len])
return forward_block
def check_start_line(self, lines_dict: dict) -> bool:
if self.is_new_file:
# this hunk cannot be falsified and is by definition true
return True
if self.start_line_pre_edit in lines_dict:
# check the location of the actual starting line:
is_similar(self.lines[0][1], lines_dict[self.start_line_pre_edit])
else:
pass
def find_start_line(self, lines_dict: dict, problems: list) -> bool:
# ToDo handle the case where the start line is 0 or 1 characters separately
if self.lines[0][0] == ADD:
# handle the case where the start line is an add
start_line = None
# find the first line that is not an add
for index, line in enumerate(self.lines):
if line[0] != ADD:
for line_number, line_content in lines_dict.items():
# if the line is similar to a non-blank line in line_dict, we can pick the line prior to it
if is_similar(line[1], line_content) and line[1] != "":
start_line = line_number - 1
break
# if the start line is not found, append a problem message
if start_line is None:
problems.append(
f"In {self.hunk_to_string()}:can not find the starting line of the diff"
)
return False
else:
# the line prior to the start line is found now we insert it to the first place as the start line
self.start_line_pre_edit = start_line
retain_line = lines_dict.get(start_line, "")
if retain_line:
self.add_retained_line(lines_dict[start_line], 0)
return self.validate_and_correct(lines_dict, problems)
else:
problems.append(
f"In {self.hunk_to_string()}:The starting line of the diff {self.hunk_to_string()} does not exist in the code"
)
return False
pot_start_lines = {
key: is_similar(self.lines[0][1], line) for key, line in lines_dict.items()
}
sum_of_matches = sum(pot_start_lines.values())
if sum_of_matches == 0:
# before we go any further, we should check if it's a comment from LLM
if self.lines[0][1].count("#") > 0:
# if it is, we can mark it as an ADD lines
self.relabel_line(0, ADD)
# and restart the validation at the next line
return self.validate_and_correct(lines_dict, problems)
else:
problems.append(
f"In {self.hunk_to_string()}:The starting line of the diff {self.hunk_to_string()} does not exist in the code"
)
return False
elif sum_of_matches == 1:
start_ind = list(pot_start_lines.keys())[
list(pot_start_lines.values()).index(True)
] # lines are one indexed
else:
logging.warning("multiple candidates for starting index")
# ToDo handle all the cases better again here. Smartest choice is that, for each candidate check match to the next line etc (recursively)
start_ind = list(pot_start_lines.keys())[
list(pot_start_lines.values()).index(True)
]
self.start_line_pre_edit = start_ind
# This should now be fulfilled by default
assert is_similar(self.lines[0][1], lines_dict[self.start_line_pre_edit])
return True
def validate_lines(self, lines_dict: dict, problems: list) -> bool:
hunk_ind = 0
file_ind = self.start_line_pre_edit
# make an orig hunk lines for logging
# orig_hunk_lines = deepcopy(self.lines)
while hunk_ind < len(self.lines) and file_ind <= max(lines_dict):
if self.lines[hunk_ind][0] == ADD:
# this cannot be validated, jump one index
hunk_ind += 1
elif not is_similar(self.lines[hunk_ind][1], lines_dict[file_ind]):
# before we go any further, we should relabel the comment from LLM
if self.lines[hunk_ind][1].count("#") > 0:
self.relabel_line(hunk_ind, ADD)
continue
# make a forward block from the code for comparisons
forward_code = "\n".join(
[
lines_dict[ind]
for ind in range(
file_ind,
min(
file_ind + self.forward_block_len,
max(lines_dict.keys()),
),
)
]
)
# make the original forward block for quantitative comparison
forward_block = self.make_forward_block(
hunk_ind, self.forward_block_len
)
orig_count_ratio = count_ratio(forward_block, forward_code)
# Here we have 2 cases
# 1) some lines were simply skipped in the diff and we should add them to the diff
# If this is the case, adding the line to the diff, should give an improved forward diff
forward_block_missing_line = self.make_forward_block(
hunk_ind, self.forward_block_len - 1
)
# insert the missing line in front of the block
forward_block_missing_line = "\n".join(
[lines_dict[file_ind], forward_block_missing_line]
)
missing_line_count_ratio = count_ratio(
forward_block_missing_line, forward_code
)
# 2) Additional lines, not belonging to the code were added to the diff
forward_block_false_line = self.make_forward_block(
hunk_ind + 1, self.forward_block_len
)
false_line_count_ratio = count_ratio(
forward_block_false_line, forward_code
)
if (
orig_count_ratio >= missing_line_count_ratio
and orig_count_ratio >= false_line_count_ratio
):
problems.append(
f"In Hunk:{self.hunk_to_string()}, there was at least one mismatch."
)
return False
elif missing_line_count_ratio > false_line_count_ratio:
self.add_retained_line(lines_dict[file_ind], hunk_ind)
hunk_ind += 1
file_ind += 1
# NOTE: IF THE LLM SKIPS SOME LINES AND HAS ADDs ADJACENT TO THE SKIPPED BLOCK,
# WE CANNOT KNOW WHETHER THE ADDs SHOULD BE BEFORE OR AFTER THE BLOCK. WE OPT FOR PUTTING IT BEFORE.
# IF IT MATTERED, WE ASSUME THE LLM WOULD NOT SKIP THE BLOCK
else:
self.pop_line(self.lines[hunk_ind], hunk_ind)
else:
hunk_ind += 1
file_ind += 1
# if we have not validated all lines, we have a problem
if hunk_ind < len(self.lines) - 1:
remaining_lines = "\n".join(
f"{line_type}: {line_content}"
for line_type, line_content in self.lines[file_ind + 1 :]
)
problems.append(
f"In {self.hunk_to_string()}:Hunk validation stopped before the lines {remaining_lines} were validated. The diff is incorrect"
)
return False
return True
def validate_and_correct(
self,
lines_dict: dict,
problems: list,
) -> bool:
start_true = self.check_start_line(lines_dict)
if not start_true:
if not self.find_start_line(lines_dict, problems):
return False
# Now we should be able to validate the hunk line by line and add missing line
if not self.validate_lines(lines_dict, problems):
return False
# Pass the validation
return True
class Diff:
def __init__(self, filename_pre, filename_post) -> None:
self.filename_pre = filename_pre
self.filename_post = filename_post
self.hunks = []
def is_new_file(self) -> bool:
if self.filename_pre == "/dev/null":
return True
return any(hunk.is_new_file for hunk in self.hunks)
def diff_to_string(self) -> str:
string = f"--- {self.filename_pre}\n+++ {self.filename_post}\n"
for hunk in self.hunks:
string += hunk.hunk_to_string()
return string.strip()
def validate_and_correct(self, lines_dict: dict) -> List[str]:
problems = []
past_hunk = None
cut_lines_dict = lines_dict.copy()
for hunk in self.hunks:
if past_hunk is not None:
# make sure to not cut so much that the start_line gets out of range
cut_ind = min(
past_hunk.start_line_pre_edit + past_hunk.hunk_len_pre_edit,
hunk.start_line_pre_edit,
)
cut_lines_dict = {
key: val for key, val in cut_lines_dict.items() if key >= (cut_ind)
}
is_valid = hunk.validate_and_correct(cut_lines_dict, problems)
if not is_valid and len(problems) > 0:
for idx, val in enumerate(problems):
print(f"\nInvalid Hunk NO.{idx}---\n{val}\n---")
self.hunks.remove(hunk)
# now correct the numbers, assuming the start line pre-edit has been fixed
hunk.hunk_len_pre_edit = (
hunk.category_counts[RETAIN] + hunk.category_counts[REMOVE]
)
hunk.hunk_len_post_edit = (
hunk.category_counts[RETAIN] + hunk.category_counts[ADD]
)
if past_hunk is not None:
hunk.start_line_post_edit = (
hunk.start_line_pre_edit
+ past_hunk.hunk_len_post_edit
- past_hunk.hunk_len_pre_edit
+ past_hunk.start_line_post_edit
- past_hunk.start_line_pre_edit
)
else:
hunk.start_line_post_edit = hunk.start_line_pre_edit
past_hunk = hunk
return problems
def is_similar(str1, str2, similarity_threshold=0.9) -> bool:
return count_ratio(str1, str2) >= similarity_threshold
def count_ratio(str1, str2) -> float:
str1, str2 = str1.replace(" ", "").lower(), str2.replace(" ", "").lower()
counter1, counter2 = Counter(str1), Counter(str2)
intersection = sum((counter1 & counter2).values())
longer_length = max(len(str1), len(str2))
if longer_length == 0:
return 1
else:
return intersection / longer_length | --- +++ @@ -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 of these diffs, enabling users to understand, validate, and correct changes between file versions.
+
+Key Features:
+
+1. The `Hunk` class encapsulates a contiguous block of changes within a file. It includes detailed information such as start lines before and after edits, lengths of change blocks, and specific line changes categorized as additions, deletions, or unchanged.
+
+2. The `Diff` class represents a complete set of changes across a file and may contain multiple `Hunk` objects. It facilitates operations like generating string representations of diffs, and validating and correcting hunks based on the original file content.
+
+3. Functions within the module allow for the validation of hunks against original files, identifying mismatches, and making necessary corrections. This feature ensures that diffs are accurate and reflect true changes.
+
+4. Utility functions `is_similar` and `count_ratio` offer the capability to compare strings for similarity, accounting for variations in spacing and case. This aids in the validation process by allowing a flexible comparison of code lines.
+
+Dependencies:
+
+- `logging`: Utilized for logging warnings and errors encountered during the validation and correction process.
+- `collections.Counter`: Used for counting occurrences of characters in strings, supporting the string similarity assessment functions.
+
+Functions and Classes:
+
+1. `Hunk`: Class representing a block of changes within a file, with methods for managing and validating these changes.
+
+2. `Diff`: Class representing the entire set of changes in a file, containing multiple `Hunk` instances and methods for overall diff management.
+
+3. `is_similar(str1, str2, similarity_threshold)`: Function to compare two strings for similarity, useful in validating line changes in hunks.
+
+4. `count_ratio(str1, str2)`: Function that computes the ratio of common characters to the length of the longer string, aiding in the assessment of line similarity.
+
+This module is essential for developers and teams utilizing version control systems, providing tools for a deeper analysis and correction of diffs, ensuring the integrity and accuracy of code changes.
+
+"""
import logging
from collections import Counter
@@ -9,6 +42,18 @@
class Hunk:
+ """
+ Represents a section of a file diff, containing changes made to that section.
+
+ Attributes:
+ start_line_pre_edit (int): The starting line number in the original file.
+ hunk_len_pre_edit (int): The length of the hunk in the original file.
+ start_line_post_edit (int): The starting line number in the edited file.
+ hunk_len_post_edit (int): The length of the hunk in the edited file.
+ lines (list): A list of tuples representing the lines in the hunk and their types (RETAIN, ADD, REMOVE).
+ category_counts (dict): A count of lines by their type.
+ is_new_file (bool): Flag indicating if the hunk represents a new file.
+ """
def __init__(
self,
@@ -33,26 +78,31 @@ self.is_new_file = False
def add_retained_line(self, line, index) -> None:
+ """Adds a retained line to the hunk at the specified index."""
self.lines.insert(index, (RETAIN, line))
self.category_counts[RETAIN] += 1
def relabel_line(self, index, new_label) -> None:
+ """Changes the label of a line at the specified index."""
old_label = self.lines[index][0]
self.lines[index] = (new_label, self.lines[index][1])
self.category_counts[old_label] -= 1
self.category_counts[new_label] += 1
def pop_line(self, line, index) -> None:
+ """Removes a line from the hunk at the specified index."""
self.lines.pop(index)
assert self.category_counts[line[0]] > 0
self.category_counts[line[0]] -= 1
def add_lines(self, new_lines) -> None:
+ """Adds multiple lines to the hunk."""
for line in new_lines:
self.lines.append(line)
self.category_counts[line[0]] += 1
def hunk_to_string(self) -> str:
+ """Converts the hunk to a string representation."""
string = f"@@ -{self.start_line_pre_edit},{self.hunk_len_pre_edit} +{self.start_line_post_edit},{self.hunk_len_post_edit} @@\n"
for line_type, line_content in self.lines:
line_prefix = (
@@ -62,6 +112,7 @@ return string
def make_forward_block(self, hunk_ind: int, forward_block_len) -> str:
+ """Creates a block of lines for forward comparison."""
forward_lines = [
line[1] for line in self.lines[hunk_ind:] if not line[0] == ADD
]
@@ -69,6 +120,7 @@ return forward_block
def check_start_line(self, lines_dict: dict) -> bool:
+ """Check if the starting line of a hunk is present in the original code and returns a boolean value accordingly."""
if self.is_new_file:
# this hunk cannot be falsified and is by definition true
return True
@@ -79,6 +131,7 @@ pass
def find_start_line(self, lines_dict: dict, problems: list) -> bool:
+ """Finds the starting line of the hunk in the original code and returns a boolean value accordingly. If the starting line is not found, it appends a problem message to the problems list."""
# ToDo handle the case where the start line is 0 or 1 characters separately
if self.lines[0][0] == ADD:
@@ -145,6 +198,7 @@ return True
def validate_lines(self, lines_dict: dict, problems: list) -> bool:
+ """Validates the lines of the hunk against the original file and returns a boolean value accordingly. If the lines do not match, it appends a problem message to the problems list."""
hunk_ind = 0
file_ind = self.start_line_pre_edit
# make an orig hunk lines for logging
@@ -236,6 +290,12 @@ lines_dict: dict,
problems: list,
) -> bool:
+ """
+ Validates and corrects the hunk based on the original lines.
+
+ This function attempts to validate the hunk by comparing its lines to the original file and making corrections
+ where necessary. It also identifies problems such as non-matching lines or incorrect line types.
+ """
start_true = self.check_start_line(lines_dict)
if not start_true:
@@ -250,6 +310,14 @@
class Diff:
+ """
+ Represents a file diff, containing multiple hunks of changes.
+
+ Attributes:
+ filename_pre (str): The name of the original file.
+ filename_post (str): The name of the edited file.
+ hunks (list): A list of Hunk objects representing the changes in the diff.
+ """
def __init__(self, filename_pre, filename_post) -> None:
self.filename_pre = filename_pre
@@ -257,17 +325,20 @@ self.hunks = []
def is_new_file(self) -> bool:
+ """Determines if the diff represents a new file."""
if self.filename_pre == "/dev/null":
return True
return any(hunk.is_new_file for hunk in self.hunks)
def diff_to_string(self) -> str:
+ """Converts the diff to a string representation."""
string = f"--- {self.filename_pre}\n+++ {self.filename_post}\n"
for hunk in self.hunks:
string += hunk.hunk_to_string()
return string.strip()
def validate_and_correct(self, lines_dict: dict) -> List[str]:
+ """Validates and corrects each hunk in the diff."""
problems = []
past_hunk = None
cut_lines_dict = lines_dict.copy()
@@ -308,11 +379,35 @@
def is_similar(str1, str2, similarity_threshold=0.9) -> bool:
+ """
+ Compares two strings for similarity, ignoring spaces and case.
+
+ Parameters
+ ----------
+ str1, str2 : str
+ The strings to compare.
+ similarity_threshold: float
+ How similar must the strings be
+
+ Returns
+ -------
+ bool
+ True if the strings are similar, False otherwise.
+ """
return count_ratio(str1, str2) >= similarity_threshold
def count_ratio(str1, str2) -> float:
+ """
+ Computes the ratio of common characters to the length of the longer string, ignoring spaces and case.
+
+ Parameters:
+ - str1, str2 (str): The strings to compare.
+
+ Returns:
+ - float: The ratio of common characters to the length of the longer string.
+ """
str1, str2 = str1.replace(" ", "").lower(), str2.replace(" ", "").lower()
counter1, counter2 = Counter(str1), Counter(str2)
@@ -321,4 +416,4 @@ if longer_length == 0:
return 1
else:
- return intersection / longer_length+ return intersection / longer_length
| 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(
n_benchmarks: Union[int, None] = None,
):
path = Path("benchmark")
folders: Iterable[Path] = path.iterdir()
if n_benchmarks:
folders = islice(folders, n_benchmarks)
benchmarks = []
results = []
for bench_folder in folders:
if os.path.isdir(bench_folder):
print(f"Running benchmark for {bench_folder}")
log_path = bench_folder / "log.txt"
log_file = open(log_path, "w")
process = subprocess.Popen(
[
"python",
"-u", # Unbuffered output
"-m",
"gpt_engineer.cli.main",
bench_folder,
"--steps",
"benchmark",
],
stdout=log_file,
stderr=log_file,
bufsize=0,
)
benchmarks.append(bench_folder)
results.append((process, log_file))
print("You can stream the log file by running:")
print(f"tail -f {log_path}")
print()
for bench_folder, (process, file) in zip(benchmarks, results):
process.wait()
file.close()
print("process", bench_folder.name, "finished with code", process.returncode)
print("Running it. Original benchmark prompt:")
print()
with open(bench_folder / "prompt") as f:
print(f.read())
print()
with contextlib.suppress(KeyboardInterrupt):
subprocess.run(
[
"python",
"-m",
"gpt_engineer.cli.main",
bench_folder,
"--steps",
"evaluate",
],
)
generate_report(benchmarks, path)
def generate_report(benchmarks, benchmark_path):
headers = ["Benchmark", "Ran", "Works", "Perfect", "Notes"]
rows = []
for bench_folder in benchmarks:
memory = bench_folder / ".gpteng" / "memory"
with open(memory / "review") as f:
review = json.loads(f.read())
rows.append(
[
bench_folder.name,
to_emoji(review.get("ran", None)),
to_emoji(review.get("works", None)),
to_emoji(review.get("perfect", None)),
review.get("comments", None),
]
)
table: str = tabulate(rows, headers, tablefmt="pipe")
print("\nBenchmark report:\n")
print(table)
print()
append_to_results = ask_yes_no("Append report to the results file?")
if append_to_results:
results_path = benchmark_path / "RESULTS.md"
current_date = datetime.now().strftime("%Y-%m-%d")
insert_markdown_section(results_path, current_date, table, 2)
def to_emoji(value: bool) -> str:
return "\U00002705" if value else "\U0000274C"
def insert_markdown_section(file_path, section_title, section_text, level):
with open(file_path, "r") as file:
lines = file.readlines()
header_prefix = "#" * level
new_section = f"{header_prefix} {section_title}\n\n{section_text}\n\n"
# Find the first section with the specified level
line_number = -1
for i, line in enumerate(lines):
if line.startswith(header_prefix):
line_number = i
break
if line_number != -1:
lines.insert(line_number, new_section)
else:
print(
f"Markdown file was of unexpected format. No section of level {level} found. "
"Did not write results."
)
return
# Write the file
with open(file_path, "w") as file:
file.writelines(lines)
def ask_yes_no(question: str) -> bool:
while True:
response = input(question + " (y/n): ").lower().strip()
if response == "y":
return True
elif response == "n":
return False
else:
print("Please enter either 'y' or 'n'.")
if __name__ == "__main__":
run(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: Union[int, None] = None,
):
+ """
+ Main function that runs benchmarks on folders within the 'benchmark' directory.
+
+ Parameters
+ ----------
+ n_benchmarks : Union[int, None], optional
+ The number of benchmarks to run. If None, all benchmarks are run.
+
+ """
path = Path("benchmark")
@@ -82,6 +95,17 @@
def generate_report(benchmarks, benchmark_path):
+ """
+ Generates a report of the benchmark results and optionally appends it to a markdown file.
+
+ Parameters
+ ----------
+ benchmarks : list
+ A list of benchmark folder paths that have been processed.
+ benchmark_path : Path
+ The path to the benchmark directory.
+
+ """
headers = ["Benchmark", "Ran", "Works", "Perfect", "Notes"]
rows = []
@@ -110,11 +134,40 @@
def to_emoji(value: bool) -> str:
+ """
+ Converts a boolean value to its corresponding emoji representation.
+
+ Parameters
+ ----------
+ value : bool
+ The boolean value to convert.
+
+ Returns
+ -------
+ str
+ An emoji string representing the boolean value.
+
+ """
return "\U00002705" if value else "\U0000274C"
def insert_markdown_section(file_path, section_title, section_text, level):
+ """
+ Inserts a new section into a markdown file at the specified level.
+
+ Parameters
+ ----------
+ file_path : Path
+ The path to the markdown file.
+ section_title : str
+ The title of the section to insert.
+ section_text : str
+ The text content of the section to insert.
+ level : int
+ The header level of the section.
+
+ """
with open(file_path, "r") as file:
lines = file.readlines()
@@ -144,6 +197,20 @@
def ask_yes_no(question: str) -> bool:
+ """
+ Asks a yes/no question and returns the response as a boolean value.
+
+ Parameters
+ ----------
+ question : str
+ The yes/no question to ask.
+
+ Returns
+ -------
+ bool
+ True if the answer is 'yes', False if 'no'.
+
+ """
while True:
response = input(question + " (y/n): ").lower().strip()
@@ -156,4 +223,4 @@
if __name__ == "__main__":
- run(main)+ run(main)
| 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 BaseChatModel
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage,
messages_from_dict,
messages_to_dict,
)
from langchain_anthropic import ChatAnthropic
from langchain_openai import AzureChatOpenAI, ChatOpenAI
from gpt_engineer.core.token_usage import TokenUsageLog
# Type hint for a chat message
Message = Union[AIMessage, HumanMessage, SystemMessage]
# Set up logging
logger = logging.getLogger(__name__)
class AI:
def __init__(
self,
model_name="gpt-4-turbo",
temperature=0.1,
azure_endpoint=None,
streaming=True,
vision=False,
):
self.temperature = temperature
self.azure_endpoint = azure_endpoint
self.model_name = model_name
self.streaming = streaming
self.vision = (
("vision-preview" in model_name)
or ("gpt-4-turbo" in model_name and "preview" not in model_name)
or ("claude" in model_name)
)
self.llm = self._create_chat_model()
self.token_usage_log = TokenUsageLog(model_name)
logger.debug(f"Using model {self.model_name}")
def start(self, system: str, user: Any, *, step_name: str) -> List[Message]:
messages: List[Message] = [
SystemMessage(content=system),
HumanMessage(content=user),
]
return self.next(messages, step_name=step_name)
def _extract_content(self, content):
if isinstance(content, str):
return content
elif isinstance(content, list) and content and "text" in content[0]:
# Assuming the structure of list content is [{'type': 'text', 'text': 'Some text'}, ...]
return content[0]["text"]
else:
return ""
def _collapse_text_messages(self, messages: List[Message]):
collapsed_messages = []
if not messages:
return collapsed_messages
previous_message = messages[0]
combined_content = self._extract_content(previous_message.content)
for current_message in messages[1:]:
if current_message.type == previous_message.type:
combined_content += "\n\n" + self._extract_content(
current_message.content
)
else:
collapsed_messages.append(
previous_message.__class__(content=combined_content)
)
previous_message = current_message
combined_content = self._extract_content(current_message.content)
collapsed_messages.append(previous_message.__class__(content=combined_content))
return collapsed_messages
def next(
self,
messages: List[Message],
prompt: Optional[str] = None,
*,
step_name: str,
) -> List[Message]:
if prompt:
messages.append(HumanMessage(content=prompt))
logger.debug(
"Creating a new chat completion: %s",
"\n".join([m.pretty_repr() for m in messages]),
)
if not self.vision:
messages = self._collapse_text_messages(messages)
response = self.backoff_inference(messages)
self.token_usage_log.update_log(
messages=messages, answer=response.content, step_name=step_name
)
messages.append(response)
logger.debug(f"Chat completion finished: {messages}")
return messages
@backoff.on_exception(backoff.expo, openai.RateLimitError, max_tries=7, max_time=45)
def backoff_inference(self, messages):
return self.llm.invoke(messages) # type: ignore
@staticmethod
def serialize_messages(messages: List[Message]) -> str:
return json.dumps(messages_to_dict(messages))
@staticmethod
def deserialize_messages(jsondictstr: str) -> List[Message]:
data = json.loads(jsondictstr)
# Modify implicit is_chunk property to ALWAYS false
# since Langchain's Message schema is stricter
prevalidated_data = [
{**item, "tools": {**item.get("tools", {}), "is_chunk": False}}
for item in data
]
return list(messages_from_dict(prevalidated_data)) # type: ignore
def _create_chat_model(self) -> BaseChatModel:
if self.azure_endpoint:
return AzureChatOpenAI(
azure_endpoint=self.azure_endpoint,
openai_api_version=os.getenv(
"OPENAI_API_VERSION", "2024-05-01-preview"
),
deployment_name=self.model_name,
openai_api_type="azure",
streaming=self.streaming,
callbacks=[StreamingStdOutCallbackHandler()],
)
elif "claude" in self.model_name:
return ChatAnthropic(
model=self.model_name,
temperature=self.temperature,
callbacks=[StreamingStdOutCallbackHandler()],
streaming=self.streaming,
max_tokens_to_sample=4096,
)
elif self.vision:
return ChatOpenAI(
model=self.model_name,
temperature=self.temperature,
streaming=self.streaming,
callbacks=[StreamingStdOutCallbackHandler()],
max_tokens=4096, # vision models default to low max token limits
)
else:
return ChatOpenAI(
model=self.model_name,
temperature=self.temperature,
streaming=self.streaming,
callbacks=[StreamingStdOutCallbackHandler()],
)
def serialize_messages(messages: List[Message]) -> str:
return AI.serialize_messages(messages)
class ClipboardAI(AI):
# Ignore not init superclass
def __init__(self, **_): # type: ignore
self.vision = False
self.token_usage_log = TokenUsageLog("clipboard_llm")
@staticmethod
def serialize_messages(messages: List[Message]) -> str:
return "\n\n".join([f"{m.type}:\n{m.content}" for m in messages])
@staticmethod
def multiline_input():
print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
content = []
while True:
try:
line = input()
except EOFError:
break
content.append(line)
return "\n".join(content)
def next(
self,
messages: List[Message],
prompt: Optional[str] = None,
*,
step_name: str,
) -> List[Message]:
if prompt:
messages.append(HumanMessage(content=prompt))
logger.debug(f"Creating a new chat completion: {messages}")
msgs = self.serialize_messages(messages)
pyperclip.copy(msgs)
Path("clipboard.txt").write_text(msgs)
print(
"Messages copied to clipboard and written to clipboard.txt,",
len(msgs),
"characters in total",
)
response = self.multiline_input()
messages.append(AIMessage(content=response))
logger.debug(f"Chat completion finished: {messages}")
return messages | --- +++ @@ -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 API.
+
+Classes:
+ AI: A class that interfaces with language models for conversation management and message serialization.
+
+Functions:
+ serialize_messages(messages: List[Message]) -> str
+ Serialize a list of messages to a JSON string.
+"""
from __future__ import annotations
@@ -34,6 +48,42 @@
class AI:
+ """
+ A class that interfaces with language models for conversation management and message serialization.
+
+ This class provides methods to start and advance conversations, handle message serialization,
+ and implement backoff strategies for rate limit errors when interacting with the OpenAI API.
+
+ Attributes
+ ----------
+ temperature : float
+ The temperature setting for the language model.
+ azure_endpoint : str
+ The endpoint URL for the Azure-hosted language model.
+ model_name : str
+ The name of the language model to use.
+ streaming : bool
+ A flag indicating whether to use streaming for the language model.
+ llm : BaseChatModel
+ The language model instance for conversation management.
+ token_usage_log : TokenUsageLog
+ A log for tracking token usage during conversations.
+
+ Methods
+ -------
+ start(system: str, user: str, step_name: str) -> List[Message]
+ Start the conversation with a system message and a user message.
+ next(messages: List[Message], prompt: Optional[str], step_name: str) -> List[Message]
+ Advances the conversation by sending message history to LLM and updating with the response.
+ backoff_inference(messages: List[Message]) -> Any
+ Perform inference using the language model with an exponential backoff strategy.
+ serialize_messages(messages: List[Message]) -> str
+ Serialize a list of messages to a JSON string.
+ deserialize_messages(jsondictstr: str) -> List[Message]
+ Deserialize a JSON string to a list of messages.
+ _create_chat_model() -> BaseChatModel
+ Create a chat model with the specified model name and temperature.
+ """
def __init__(
self,
@@ -43,6 +93,16 @@ streaming=True,
vision=False,
):
+ """
+ Initialize the AI class.
+
+ Parameters
+ ----------
+ model_name : str, optional
+ The name of the model to use, by default "gpt-4".
+ temperature : float, optional
+ The temperature to use for the model, by default 0.1.
+ """
self.temperature = temperature
self.azure_endpoint = azure_endpoint
self.model_name = model_name
@@ -58,6 +118,23 @@ logger.debug(f"Using model {self.model_name}")
def start(self, system: str, user: Any, *, step_name: str) -> List[Message]:
+ """
+ Start the conversation with a system message and a user message.
+
+ Parameters
+ ----------
+ system : str
+ The content of the system message.
+ user : str
+ The content of the user message.
+ step_name : str
+ The name of the step.
+
+ Returns
+ -------
+ List[Message]
+ The list of messages in the conversation.
+ """
messages: List[Message] = [
SystemMessage(content=system),
@@ -66,6 +143,17 @@ return self.next(messages, step_name=step_name)
def _extract_content(self, content):
+ """
+ Extracts text content from a message, supporting both string and list types.
+ Parameters
+ ----------
+ content : Union[str, List[dict]]
+ The content of a message, which could be a string or a list.
+ Returns
+ -------
+ str
+ The extracted text content.
+ """
if isinstance(content, str):
return content
elif isinstance(content, list) and content and "text" in content[0]:
@@ -75,6 +163,24 @@ return ""
def _collapse_text_messages(self, messages: List[Message]):
+ """
+ Combine consecutive messages of the same type into a single message, where if the message content
+ is a list type, the first text element's content is taken. This method keeps `combined_content` as a string.
+
+ This method iterates through the list of messages, combining consecutive messages of the same type
+ by joining their content with a newline character. If the content is a list, it extracts text from the first
+ text element's content. This reduces the number of messages and simplifies the conversation for processing.
+
+ Parameters
+ ----------
+ messages : List[Message]
+ The list of messages to collapse.
+
+ Returns
+ -------
+ List[Message]
+ The list of messages after collapsing consecutive messages of the same type.
+ """
collapsed_messages = []
if not messages:
return collapsed_messages
@@ -104,6 +210,24 @@ *,
step_name: str,
) -> List[Message]:
+ """
+ Advances the conversation by sending message history
+ to LLM and updating with the response.
+
+ Parameters
+ ----------
+ messages : List[Message]
+ The list of messages in the conversation.
+ prompt : Optional[str], optional
+ The prompt to use, by default None.
+ step_name : str
+ The name of the step.
+
+ Returns
+ -------
+ List[Message]
+ The updated list of messages in the conversation.
+ """
if prompt:
messages.append(HumanMessage(content=prompt))
@@ -128,14 +252,72 @@
@backoff.on_exception(backoff.expo, openai.RateLimitError, max_tries=7, max_time=45)
def backoff_inference(self, messages):
+ """
+ Perform inference using the language model while implementing an exponential backoff strategy.
+
+ This function will retry the inference in case of a rate limit error from the OpenAI API.
+ It uses an exponential backoff strategy, meaning the wait time between retries increases
+ exponentially. The function will attempt to retry up to 7 times within a span of 45 seconds.
+
+ Parameters
+ ----------
+ messages : List[Message]
+ A list of chat messages which will be passed to the language model for processing.
+
+ callbacks : List[Callable]
+ A list of callback functions that are triggered after each inference. These functions
+ can be used for logging, monitoring, or other auxiliary tasks.
+
+ Returns
+ -------
+ Any
+ The output from the language model after processing the provided messages.
+
+ Raises
+ ------
+ openai.error.RateLimitError
+ If the number of retries exceeds the maximum or if the rate limit persists beyond the
+ allotted time, the function will ultimately raise a RateLimitError.
+
+ Example
+ -------
+ >>> messages = [SystemMessage(content="Hello"), HumanMessage(content="How's the weather?")]
+ >>> response = backoff_inference(messages)
+ """
return self.llm.invoke(messages) # type: ignore
@staticmethod
def serialize_messages(messages: List[Message]) -> str:
+ """
+ Serialize a list of messages to a JSON string.
+
+ Parameters
+ ----------
+ messages : List[Message]
+ The list of messages to serialize.
+
+ Returns
+ -------
+ str
+ The serialized messages as a JSON string.
+ """
return json.dumps(messages_to_dict(messages))
@staticmethod
def deserialize_messages(jsondictstr: str) -> List[Message]:
+ """
+ Deserialize a JSON string to a list of messages.
+
+ Parameters
+ ----------
+ jsondictstr : str
+ The JSON string to deserialize.
+
+ Returns
+ -------
+ List[Message]
+ The deserialized list of messages.
+ """
data = json.loads(jsondictstr)
# Modify implicit is_chunk property to ALWAYS false
# since Langchain's Message schema is stricter
@@ -146,6 +328,21 @@ return list(messages_from_dict(prevalidated_data)) # type: ignore
def _create_chat_model(self) -> BaseChatModel:
+ """
+ Create a chat model with the specified model name and temperature.
+
+ Parameters
+ ----------
+ model : str
+ The name of the model to create.
+ temperature : float
+ The temperature to use for the model.
+
+ Returns
+ -------
+ BaseChatModel
+ The created chat model.
+ """
if self.azure_endpoint:
return AzureChatOpenAI(
azure_endpoint=self.azure_endpoint,
@@ -215,6 +412,9 @@ *,
step_name: str,
) -> List[Message]:
+ """
+ Not yet fully supported
+ """
if prompt:
messages.append(HumanMessage(content=prompt))
@@ -234,4 +434,4 @@ messages.append(AIMessage(content=response))
logger.debug(f"Chat completion finished: {messages}")
- return messages+ return messages
| 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
from gpt_engineer.benchmark.benchmarks.load import get_benchmark
from gpt_engineer.benchmark.run import export_yaml_results, print_results, run
app = typer.Typer(
context_settings={"help_option_names": ["-h", "--help"]}
) # creates a CLI app
def get_agent(path):
# Dynamically import the python module at path
sys.path.append(os.path.dirname(path))
agent_module = importlib.import_module(path.replace("/", ".").replace(".py", ""))
return agent_module.default_config_agent()
@app.command(
help="""
Run any benchmark(s) against the specified agent.
\b
Currently available benchmarks are: apps and mbpp
"""
)
def main(
path_to_agent: Annotated[
str,
typer.Argument(
help="python file that contains a function called 'default_config_agent'"
),
],
bench_config: Annotated[
str, typer.Argument(help="optional task name in benchmark")
] = os.path.join(os.path.dirname(__file__), "default_bench_config.toml"),
yaml_output: Annotated[
Optional[str],
typer.Option(help="print results for each task", show_default=False),
] = None,
verbose: Annotated[
Optional[bool],
typer.Option(help="print results for each task", show_default=False),
] = False,
use_cache: Annotated[
Optional[bool],
typer.Option(
help="Speeds up computations and saves tokens when running the same prompt multiple times by caching the LLM response.",
show_default=False,
),
] = True,
):
if use_cache:
set_llm_cache(SQLiteCache(database_path=".langchain.db"))
load_env_if_needed()
config = BenchConfig.from_toml(bench_config)
print("using config file: " + bench_config)
benchmarks = list()
benchmark_results = dict()
for specific_config_name in vars(config):
specific_config = getattr(config, specific_config_name)
if hasattr(specific_config, "active"):
if specific_config.active:
benchmarks.append(specific_config_name)
for benchmark_name in benchmarks:
benchmark = get_benchmark(benchmark_name, config)
if len(benchmark.tasks) == 0:
print(
benchmark_name
+ " was skipped, since no tasks are specified. Increase the number of tasks in the config file at: "
+ bench_config
)
continue
agent = get_agent(path_to_agent)
results = run(agent, benchmark, verbose=verbose)
print(
f"\n--- Results for agent {path_to_agent}, benchmark: {benchmark_name} ---"
)
print_results(results)
print()
benchmark_results[benchmark_name] = {
"detailed": [result.to_dict() for result in results]
}
if yaml_output is not None:
export_yaml_results(yaml_output, benchmark_results, config.to_dict())
if __name__ == "__main__":
typer.run(main) | --- +++ @@ -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
+ Dynamically imports and returns the default configuration agent from the given path.
+
+main : function
+ The main function that runs the specified benchmarks with the given agent.
+ Outputs the results to the console.
+
+Attributes
+----------
+__name__ : str
+ The standard boilerplate for invoking the main function when the script is executed.
+"""
import importlib
import os.path
import sys
@@ -20,6 +41,19 @@
def get_agent(path):
+ """
+ Dynamically imports and returns the default configuration agent from the given path.
+
+ Parameters
+ ----------
+ path : str
+ The file path to the module containing the default configuration agent.
+
+ Returns
+ -------
+ BaseAgent
+ An instance of the imported default configuration agent.
+ """
# Dynamically import the python module at path
sys.path.append(os.path.dirname(path))
agent_module = importlib.import_module(path.replace("/", ".").replace(".py", ""))
@@ -60,6 +94,25 @@ ),
] = True,
):
+ """
+ The main function that runs the specified benchmarks with the given agent and outputs the results to the console.
+
+ Parameters
+ ----------
+ path_to_agent : str
+ The file path to the Python module that contains a function called 'default_config_agent'.
+ bench_config : str, default=default_bench_config.toml
+ Configuration file for choosing which benchmark problems to run. See default config for more details.
+ yaml_output: Optional[str], default=None
+ Pass a path to a yaml file to have results written to file.
+ verbose : Optional[bool], default=False
+ A flag to indicate whether to print results for each task.
+ use_cache : Optional[bool], default=True
+ Speeds up computations and saves tokens when running the same prompt multiple times by caching the LLM response.
+ Returns
+ -------
+ None
+ """
if use_cache:
set_llm_cache(SQLiteCache(database_path=".langchain.db"))
load_env_if_needed()
@@ -98,4 +151,4 @@
if __name__ == "__main__":
- typer.run(main)+ typer.run(main)
| 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_engineer.core.prompt import Prompt
@dataclass_json
@dataclass
class Review:
ran: Optional[bool]
perfect: Optional[bool]
works: Optional[bool]
comments: str
raw: str
@dataclass_json
@dataclass
class Learning:
prompt: str
model: str
temperature: float
config: str
logs: str
session: str
review: Optional[Review]
timestamp: str = field(default_factory=lambda: datetime.utcnow().isoformat())
version: str = "0.3"
TERM_CHOICES = (
colored("y", "green")
+ "/"
+ colored("n", "red")
+ "/"
+ colored("u", "yellow")
+ "(ncertain): "
)
def human_review_input() -> Optional[Review]:
print()
if not check_collection_consent():
return None
print()
print(
colored("To help gpt-engineer learn, please answer 3 questions:", "light_green")
)
print()
ran = input("Did the generated code run at all? " + TERM_CHOICES)
ran = ask_for_valid_input(ran)
if ran == "y":
perfect = input(
"Did the generated code do everything you wanted? " + TERM_CHOICES
)
perfect = ask_for_valid_input(perfect)
if perfect != "y":
useful = input("Did the generated code do anything useful? " + TERM_CHOICES)
useful = ask_for_valid_input(useful)
else:
useful = ""
else:
perfect = ""
useful = ""
if perfect != "y":
comments = input(
"If you have time, please explain what was not working "
+ colored("(ok to leave blank)\n", "light_green")
)
else:
comments = ""
return Review(
raw=", ".join([ran, perfect, useful]),
ran={"y": True, "n": False, "u": None, "": None}[ran],
works={"y": True, "n": False, "u": None, "": None}[useful],
perfect={"y": True, "n": False, "u": None, "": None}[perfect],
comments=comments,
)
def ask_for_valid_input(ran):
while ran not in ("y", "n", "u"):
ran = input("Invalid input. Please enter y, n, or u: ")
return ran
def check_collection_consent() -> bool:
path = Path(".gpte_consent")
if path.exists() and path.read_text() == "true":
return True
else:
return ask_collection_consent()
def ask_collection_consent() -> bool:
answer = input(
"Is it ok if we store your prompts to help improve GPT Engineer? (y/n)"
)
while answer.lower() not in ("y", "n"):
answer = input("Invalid input. Please enter y or n: ")
if answer.lower() == "y":
path = Path(".gpte_consent")
path.write_text("true")
print(colored("Thank you️", "light_green"))
print()
print(
"(If you no longer wish to participate in data collection, delete the file .gpte_consent)"
)
return True
else:
print(
colored(
"No worries! GPT Engineer will not collect your prompts. ❤️",
"light_green",
)
)
return False
def extract_learning(
prompt: Prompt,
model: str,
temperature: float,
config: Tuple[str, ...],
memory: DiskMemory,
review: Review,
) -> Learning:
return Learning(
prompt=prompt.to_json(),
model=model,
temperature=temperature,
config=json.dumps(config),
session=get_session(),
logs=memory.to_json(),
review=review,
)
def get_session() -> str:
path = Path(tempfile.gettempdir()) / "gpt_engineer_user_id.txt"
try:
if path.exists():
user_id = path.read_text()
else:
# random uuid:
user_id = str(random.randint(0, 2**32))
path.write_text(user_id)
return user_id
except IOError:
return "ephemeral_" + str(random.randint(0, 2**32)) | --- +++ @@ -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 tool's performance.
+
+Classes
+-------
+Review : dataclass
+ Represents a user's review of the generated code, including whether it ran, was perfect, was useful, and any additional comments.
+Learning : dataclass
+ Encapsulates the metadata and feedback collected during a session of using the GPT Engineer tool, including the prompt, model, temperature, configuration, logs, session identifier, user review, and timestamp.
+
+Functions
+---------
+human_review_input() -> Optional[Review]
+ Interactively gathers feedback from the user regarding the performance of generated code and returns a Review instance.
+check_collection_consent() -> bool
+ Checks if the user has previously given consent to store their data and, if not, asks for it.
+ask_collection_consent() -> bool
+ Prompts the user for consent to store their data for the purpose of improving GPT Engineer.
+extract_learning(prompt: Prompt, model: str, temperature: float, config: Tuple[str, ...], memory: DiskMemory, review: Review) -> Learning
+ Extracts feedback and session details to create a Learning instance based on the provided parameters.
+get_session() -> str
+ Retrieves a unique identifier for the current user session, creating one if it does not exist.
+
+Constants
+---------
+TERM_CHOICES : tuple
+ Terminal color choices for user interactive prompts, formatted with termcolor for readability.
+"""
import json
import random
@@ -18,6 +46,22 @@ @dataclass_json
@dataclass
class Review:
+ """
+ A dataclass that represents a user's review of the generated code.
+
+ Attributes
+ ----------
+ ran : Optional[bool]
+ Indicates whether the generated code ran without errors.
+ perfect : Optional[bool]
+ Indicates whether the generated code met all the user's requirements.
+ works : Optional[bool]
+ Indicates whether the generated code was useful, even if not perfect.
+ comments : str
+ Any additional comments provided by the user.
+ raw : str
+ A raw string representation of the user's responses.
+ """
ran: Optional[bool]
perfect: Optional[bool]
@@ -29,6 +73,30 @@ @dataclass_json
@dataclass
class Learning:
+ """
+ A dataclass that encapsulates the learning data collected during a GPT Engineer session.
+
+ Attributes
+ ----------
+ prompt : str
+ A JSON string representing the prompt provided to GPT Engineer.
+ model : str
+ The name of the model used during the session.
+ temperature : float
+ The temperature setting used for the model's responses.
+ config : str
+ A JSON string representing the configuration settings for the session.
+ logs : str
+ A JSON string representing the logs of the session.
+ session : str
+ A unique identifier for the user session.
+ review : Optional[Review]
+ The user's review of the generated code.
+ timestamp : str
+ The UTC timestamp when the learning data was created.
+ version : str
+ The version of the learning data schema.
+ """
prompt: str
model: str
@@ -52,6 +120,16 @@
def human_review_input() -> Optional[Review]:
+ """
+ Interactively prompts the user to review the generated code and returns their feedback encapsulated in a Review object.
+
+ This function will first check if the user has given consent to collect their feedback. If consent is given, it will ask the user a series of questions about the generated code's performance and capture their responses.
+
+ Returns
+ -------
+ Optional[Review]
+ A Review object containing the user's feedback, or None if consent is not given.
+ """
print()
if not check_collection_consent():
return None
@@ -103,6 +181,16 @@
def check_collection_consent() -> bool:
+ """
+ Checks if the user has previously given consent to store their data for feedback collection.
+
+ This function looks for a file that stores the user's consent status. If the file exists and contains 'true', consent is assumed. If the file does not exist or does not contain 'true', the function will prompt the user for consent.
+
+ Returns
+ -------
+ bool
+ True if the user has given consent, False otherwise.
+ """
path = Path(".gpte_consent")
if path.exists() and path.read_text() == "true":
return True
@@ -111,6 +199,16 @@
def ask_collection_consent() -> bool:
+ """
+ Asks the user for their consent to store their data for the purpose of improving the GPT Engineer tool.
+
+ The user's response is recorded in a file for future reference. If the user consents, the function will write 'true' to the file. If the user does not consent, no data will be collected, and the function will not modify the file.
+
+ Returns
+ -------
+ bool
+ True if the user consents, False otherwise.
+ """
answer = input(
"Is it ok if we store your prompts to help improve GPT Engineer? (y/n)"
)
@@ -144,6 +242,29 @@ memory: DiskMemory,
review: Review,
) -> Learning:
+ """
+ Constructs a Learning object containing the session's metadata and user feedback.
+
+ Parameters
+ ----------
+ prompt : str
+ The initial prompt provided to the GPT Engineer.
+ model : str
+ The name of the model used during the session.
+ temperature : float
+ The temperature setting used for the model's responses.
+ config : Tuple[str, ...]
+ A tuple representing the configuration settings for the session.
+ memory : DiskMemory
+ An object representing the disk memory used during the session.
+ review : Review
+ The user's review of the generated code.
+
+ Returns
+ -------
+ Learning
+ An instance of Learning containing all the session details and user feedback.
+ """
return Learning(
prompt=prompt.to_json(),
model=model,
@@ -156,6 +277,16 @@
def get_session() -> str:
+ """
+ Retrieves or generates a unique identifier for the current user session.
+
+ This function attempts to read a unique user ID from a temporary file. If the file does not exist, it generates a new random ID, writes it to the file, and returns it. This ID is used to uniquely identify the user's session.
+
+ Returns
+ -------
+ str
+ A unique identifier for the user session.
+ """
path = Path(tempfile.gettempdir()) / "gpt_engineer_user_id.txt"
try:
@@ -167,4 +298,4 @@ path.write_text(user_id)
return user_id
except IOError:
- return "ephemeral_" + str(random.randint(0, 2**32))+ return "ephemeral_" + str(random.randint(0, 2**32))
| 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.types import Assertable, Benchmark, Task
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.prompt import Prompt
DATASET_PATH = Path(__file__).parent / "dataset"
class MbppAssertion:
def __init__(self, assertion: str):
self.assertion = assertion
def evaluate(self, assertable: Assertable) -> bool:
generated_code = assertable.files["main.py"]
code_with_assertion = f"{generated_code}\n{self.assertion}"
# Create new execution environment for every run to avoid side effects
env = DiskExecutionEnv()
env.upload(FilesDict({"main.py": code_with_assertion}))
pro = env.popen("python main.py")
try:
stdout, stderr = pro.communicate(timeout=2)
stdout, stderr = stdout.decode("utf-8"), stderr.decode("utf-8")
except TimeoutExpired:
print("Execution Timeout")
return False
return not stderr
def _get_dataset() -> Union[Dataset, DatasetDict]:
try:
return load_from_disk(str(DATASET_PATH))
except FileNotFoundError:
print("Dataset not found locally, downloading...")
dataset = load_dataset("mbpp", "sanitized", trust_remote_code=True)
dataset.save_to_disk(str(DATASET_PATH))
return dataset
def load_mbpp(config: MbppConfig) -> Benchmark:
dataset = _get_dataset()
tasks = []
problems = []
for dataset_type in ["test", "train"]:
problems += [
Problem(
source_file=problem["source_file"],
task_id=problem["task_id"],
prompt=problem["prompt"],
code=problem["code"],
test_imports=problem["test_imports"],
test_list=problem["test_list"],
)
for index, problem in enumerate(dataset[dataset_type])
if index < config.__getattribute__(dataset_type + "_len")
]
for problem in problems:
prompt = Prompt(
problem.prompt
+ "Please extend given function without changing it's declaration including arguments."
)
tasks.append(
Task(
name=str(problem.task_id),
initial_code=FilesDict({"main.py": problem.starting_code}),
command=None, # Explicitly setting `None` because each assertion runs code
prompt=prompt,
assertions={
f"correct assertion {i}": MbppAssertion(
assertion=assertion
).evaluate
for i, assertion in enumerate(problem.test_list)
},
)
)
return Benchmark(
name="mbpp",
tasks=tasks,
) | --- +++ @@ -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
+---------
+load_mbpp : function
+ Loads the MBPP benchmark, which consists of a series coding problems.
+"""
from pathlib import Path
from subprocess import TimeoutExpired
from typing import Union
@@ -50,6 +62,14 @@
def load_mbpp(config: MbppConfig) -> Benchmark:
+ """
+ Loads the MBPP benchmark, which consists of a series coding problems.
+
+ Returns
+ -------
+ Benchmark
+ A Benchmark object containing a list of Task objects for the MBPP evaluation.
+ """
dataset = _get_dataset()
tasks = []
problems = []
@@ -91,4 +111,4 @@ return Benchmark(
name="mbpp",
tasks=tasks,
- )+ )
| 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_dict(chat: str) -> FilesDict:
# Regex to match file paths and associated code blocks
regex = r"(\S+)\n\s*```[^\n]*\n(.+?)```"
matches = re.finditer(regex, chat, re.DOTALL)
files_dict = FilesDict()
for match in matches:
# Clean and standardize the file path
path = re.sub(r'[\:<>"|?*]', "", match.group(1))
path = re.sub(r"^\[(.*)\]$", r"\1", path)
path = re.sub(r"^`(.*)`$", r"\1", path)
path = re.sub(r"[\]\:]$", "", path)
# Extract and clean the code content
content = match.group(2)
# Add the cleaned path and content to the FilesDict
files_dict[path.strip()] = content.strip()
return files_dict
def apply_diffs(diffs: Dict[str, Diff], files: FilesDict) -> FilesDict:
files = FilesDict(files.copy())
REMOVE_FLAG = "<REMOVE_LINE>" # Placeholder to mark lines for removal
for diff in diffs.values():
if diff.is_new_file():
# If it's a new file, create it with the content from the diff
files[diff.filename_post] = "\n".join(
line[1] for hunk in diff.hunks for line in hunk.lines
)
else:
# Convert the file content to a dictionary of lines
line_dict = file_to_lines_dict(files[diff.filename_pre])
for hunk in diff.hunks:
current_line = hunk.start_line_pre_edit
for line in hunk.lines:
if line[0] == RETAIN:
current_line += 1
elif line[0] == ADD:
# Handle added lines
current_line -= 1
if (
current_line in line_dict.keys()
and line_dict[current_line] != REMOVE_FLAG
):
line_dict[current_line] += "\n" + line[1]
else:
line_dict[current_line] = line[1]
current_line += 1
elif line[0] == REMOVE:
# Mark removed lines with REMOVE_FLAG
line_dict[current_line] = REMOVE_FLAG
current_line += 1
# Remove lines marked for removal
line_dict = {
key: line_content
for key, line_content in line_dict.items()
if REMOVE_FLAG not in line_content
}
# Reassemble the file content
files[diff.filename_post] = "\n".join(line_dict.values())
return files
def parse_diffs(diff_string: str, diff_timeout=3) -> dict:
# Regex to match individual diff blocks
diff_block_pattern = regex.compile(
r"```.*?\n\s*?--- .*?\n\s*?\+\+\+ .*?\n(?:@@ .*? @@\n(?:[-+ ].*?\n)*?)*?```",
re.DOTALL,
)
diffs = {}
try:
for block in diff_block_pattern.finditer(diff_string, timeout=diff_timeout):
diff_block = block.group()
# Parse individual diff blocks and update the diffs dictionary
diff = parse_diff_block(diff_block)
for filename, diff_obj in diff.items():
if filename not in diffs:
diffs[filename] = diff_obj
else:
print(
f"\nMultiple diffs found for {filename}. Only the first one is kept."
)
except TimeoutError:
print("gpt-engineer timed out while parsing git diff")
if not diffs:
print(
"GPT did not provide any proposed changes. Please try to reselect the files for uploading and edit your prompt file."
)
return diffs
def parse_diff_block(diff_block: str) -> dict:
lines = diff_block.strip().split("\n")[1:-1] # Exclude the opening and closing ```
diffs = {}
current_diff = None
hunk_lines = []
filename_pre = None
filename_post = None
hunk_header = None
for line in lines:
if line.startswith("--- "):
# Pre-edit filename
filename_pre = line[4:]
elif line.startswith("+++ "):
# Post-edit filename and initiation of a new Diff object
if (
filename_post is not None
and current_diff is not None
and hunk_header is not None
):
current_diff.hunks.append(Hunk(*hunk_header, hunk_lines))
hunk_lines = []
filename_post = line[4:]
current_diff = Diff(filename_pre, filename_post)
diffs[filename_post] = current_diff
elif line.startswith("@@ "):
# Start of a new hunk in the diff
if hunk_lines and current_diff is not None and hunk_header is not None:
current_diff.hunks.append(Hunk(*hunk_header, hunk_lines))
hunk_lines = []
hunk_header = parse_hunk_header(line)
elif line.startswith("+"):
# Added line
hunk_lines.append((ADD, line[1:]))
elif line.startswith("-"):
# Removed line
hunk_lines.append((REMOVE, line[1:]))
else:
# Retained line
hunk_lines.append((RETAIN, line[1:]))
# Append the last hunk if any
if current_diff is not None and hunk_lines and hunk_header is not None:
current_diff.hunks.append(Hunk(*hunk_header, hunk_lines))
return diffs
def parse_hunk_header(header_line) -> Tuple[int, int, int, int]:
pattern = re.compile(r"^@@ -\d{1,},\d{1,} \+\d{1,},\d{1,} @@$")
if not pattern.match(header_line):
# Return a default value if the header does not match the expected format
return 0, 0, 0, 0
pre, post = header_line.split(" ")[1:3]
start_line_pre_edit, hunk_len_pre_edit = map(int, pre[1:].split(","))
start_line_post_edit, hunk_len_post_edit = map(int, post[1:].split(","))
return (
start_line_pre_edit,
hunk_len_pre_edit,
start_line_post_edit,
hunk_len_post_edit,
) | --- +++ @@ -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 code files based on chat inputs and diff information.
+
+Key Components:
+- chat_to_files_dict: Parses a chat transcript, extracting file paths and associated code blocks, and organizes
+ them into a FilesDict object, which is a custom dictionary format designed to hold file contents keyed by their paths.
+
+- apply_diffs: Takes a dictionary of Diff objects (which represent changes to be made to files) and a FilesDict
+ object containing the current state of files. It applies the changes described by the Diff objects to the
+ corresponding files in the FilesDict, updating the file contents as specified by the diffs.
+
+- parse_diffs: Parses a string containing diffs in the unified git diff format, extracting the changes described
+ in the diffs and organizing them into a dictionary of Diff objects, keyed by the filename to which each diff applies.
+
+- parse_diff_block: Parses a single block of text from a diff string, translating it into a Diff object that
+ represents the changes described in that block of text.
+
+This script is intended for use in environments where code collaboration or review is conducted through chat interfaces,
+allowing for the dynamic application of changes to code bases and the efficient handling of file and diff information in chat transcripts.
+"""
import logging
import re
@@ -14,6 +36,15 @@
def chat_to_files_dict(chat: str) -> FilesDict:
+ """
+ Converts a chat string containing file paths and code blocks into a FilesDict object.
+
+ Args:
+ - chat (str): The chat string containing file paths and code blocks.
+
+ Returns:
+ - FilesDict: A dictionary with file paths as keys and code blocks as values.
+ """
# Regex to match file paths and associated code blocks
regex = r"(\S+)\n\s*```[^\n]*\n(.+?)```"
matches = re.finditer(regex, chat, re.DOTALL)
@@ -36,6 +67,16 @@
def apply_diffs(diffs: Dict[str, Diff], files: FilesDict) -> FilesDict:
+ """
+ Applies diffs to the provided files.
+
+ Args:
+ - diffs (Dict[str, Diff]): A dictionary of diffs to apply, keyed by filename.
+ - files (FilesDict): The original files to which diffs will be applied.
+
+ Returns:
+ - FilesDict: The updated files after applying diffs.
+ """
files = FilesDict(files.copy())
REMOVE_FLAG = "<REMOVE_LINE>" # Placeholder to mark lines for removal
for diff in diffs.values():
@@ -80,6 +121,15 @@
def parse_diffs(diff_string: str, diff_timeout=3) -> dict:
+ """
+ Parses a diff string in the unified git diff format.
+
+ Args:
+ - diff_string (str): The diff string to parse.
+
+ Returns:
+ - dict: A dictionary of Diff objects keyed by filename.
+ """
# Regex to match individual diff blocks
diff_block_pattern = regex.compile(
r"```.*?\n\s*?--- .*?\n\s*?\+\+\+ .*?\n(?:@@ .*? @@\n(?:[-+ ].*?\n)*?)*?```",
@@ -112,6 +162,15 @@
def parse_diff_block(diff_block: str) -> dict:
+ """
+ Parses a block of diff text into a Diff object.
+
+ Args:
+ - diff_block (str): A single block of diff text.
+
+ Returns:
+ - dict: A dictionary containing a single Diff object keyed by the post-edit filename.
+ """
lines = diff_block.strip().split("\n")[1:-1] # Exclude the opening and closing ```
diffs = {}
current_diff = None
@@ -160,6 +219,15 @@
def parse_hunk_header(header_line) -> Tuple[int, int, int, int]:
+ """
+ Parses the header of a hunk from a diff.
+
+ Args:
+ - header_line (str): The header line of a hunk.
+
+ Returns:
+ - tuple: A tuple containing start and length information for pre- and post-edit.
+ """
pattern = re.compile(r"^@@ -\d{1,},\d{1,} \+\d{1,},\d{1,} @@$")
if not pattern.match(header_line):
@@ -174,4 +242,4 @@ hunk_len_pre_edit,
start_line_post_edit,
hunk_len_post_edit,
- )+ )
| 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 gpt_engineer.core.chat_to_files import chat_to_files_dict
from gpt_engineer.core.default.paths import CODE_GEN_LOG_FILE, ENTRYPOINT_FILE
from gpt_engineer.core.default.steps import curr_fn, improve_fn, setup_sys_prompt
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.preprompts_holder import PrepromptsHolder
from gpt_engineer.core.prompt import Prompt
# Type hint for chat messages
Message = Union[AIMessage, HumanMessage, SystemMessage]
MAX_SELF_HEAL_ATTEMPTS = 10
def get_platform_info() -> str:
v = version_info
a = f"Python Version: {v.major}.{v.minor}.{v.micro}"
b = f"\nOS: {platform()}\n"
return a + b
def self_heal(
ai: AI,
execution_env: BaseExecutionEnv,
files_dict: FilesDict,
prompt: Prompt = None,
preprompts_holder: PrepromptsHolder = None,
memory: BaseMemory = None,
diff_timeout=3,
) -> FilesDict:
# step 1. execute the entrypoint
# log_path = dbs.workspace.path / "log.txt"
if ENTRYPOINT_FILE not in files_dict:
raise FileNotFoundError(
"The required entrypoint "
+ ENTRYPOINT_FILE
+ " does not exist in the code."
)
attempts = 0
if preprompts_holder is None:
raise AssertionError("Prepromptsholder required for self-heal")
while attempts < MAX_SELF_HEAL_ATTEMPTS:
attempts += 1
timed_out = False
# Start the process
execution_env.upload(files_dict)
p = execution_env.popen(files_dict[ENTRYPOINT_FILE])
# Wait for the process to complete and get output
stdout_full, stderr_full = p.communicate()
if (p.returncode != 0 and p.returncode != 2) and not timed_out:
print("run.sh failed. The log is:")
print(stdout_full.decode("utf-8"))
print(stderr_full.decode("utf-8"))
new_prompt = Prompt(
f"A program with this specification was requested:\n{prompt}\n, but running it produced the following output:\n{stdout_full}\n and the following errors:\n{stderr_full}. Please change it so that it fulfills the requirements."
)
files_dict = improve_fn(
ai, new_prompt, files_dict, memory, preprompts_holder, diff_timeout
)
else:
break
return files_dict
def clarified_gen(
ai: AI, prompt: Prompt, memory: BaseMemory, preprompts_holder: PrepromptsHolder
) -> FilesDict:
preprompts = preprompts_holder.get_preprompts()
messages: List[Message] = [SystemMessage(content=preprompts["clarify"])]
user_input = prompt.text # clarify does not work with vision right now
while True:
messages = ai.next(messages, user_input, step_name=curr_fn())
msg = messages[-1].content.strip()
if "nothing to clarify" in msg.lower():
break
if msg.lower().startswith("no"):
print("Nothing to clarify.")
break
print('(answer in text, or "c" to move on)\n')
user_input = input("")
print()
if not user_input or user_input == "c":
print("(letting gpt-engineer make its own assumptions)")
print()
messages = ai.next(
messages,
"Make your own assumptions and state them explicitly before starting",
step_name=curr_fn(),
)
print()
user_input += """
\n\n
Is anything else unclear? If yes, ask another question.\n
Otherwise state: "Nothing to clarify"
"""
print()
messages = [
SystemMessage(content=setup_sys_prompt(preprompts)),
] + messages[
1:
] # skip the first clarify message, which was the original clarify priming prompt
messages = ai.next(
messages,
preprompts["generate"].replace("FILE_FORMAT", preprompts["file_format"]),
step_name=curr_fn(),
)
print()
chat = messages[-1].content.strip()
memory.log(CODE_GEN_LOG_FILE, "\n\n".join(x.pretty_repr() for x in messages))
files_dict = chat_to_files_dict(chat)
return files_dict
def lite_gen(
ai: AI, prompt: Prompt, memory: BaseMemory, preprompts_holder: PrepromptsHolder
) -> FilesDict:
preprompts = preprompts_holder.get_preprompts()
messages = ai.start(
prompt.to_langchain_content(), preprompts["file_format"], step_name=curr_fn()
)
chat = messages[-1].content.strip()
memory.log(CODE_GEN_LOG_FILE, "\n\n".join(x.pretty_repr() for x in messages))
files_dict = chat_to_files_dict(chat)
return files_dict | --- +++ @@ -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
+ virtual environment is the one being used.
+
+ Returns:
+ str: A string containing the OS and Python version information.
+ """
v = version_info
a = f"Python Version: {v.major}.{v.minor}.{v.micro}"
@@ -36,6 +46,39 @@ memory: BaseMemory = None,
diff_timeout=3,
) -> FilesDict:
+ """
+ Attempts to execute the code from the entrypoint and if it fails, sends the error output back to the AI with instructions to fix.
+
+ Parameters
+ ----------
+ ai : AI
+ An instance of the AI model.
+ execution_env : BaseExecutionEnv
+ The execution environment where the code is run.
+ files_dict : FilesDict
+ A dictionary of file names to their contents.
+ preprompts_holder : PrepromptsHolder, optional
+ A holder for preprompt messages.
+
+ Returns
+ -------
+ FilesDict
+ The updated files dictionary after self-healing attempts.
+
+ Raises
+ ------
+ FileNotFoundError
+ If the required entrypoint file does not exist in the code.
+ AssertionError
+ If the preprompts_holder is None.
+
+ Notes
+ -----
+ This code will make `MAX_SELF_HEAL_ATTEMPTS` to try and fix the code
+ before giving up.
+ This makes the assuption that the previous step was `gen_entrypoint`,
+ this code could work with `simple_gen`, or `gen_clarified_code` as well.
+ """
# step 1. execute the entrypoint
# log_path = dbs.workspace.path / "log.txt"
@@ -79,6 +122,25 @@ def clarified_gen(
ai: AI, prompt: Prompt, memory: BaseMemory, preprompts_holder: PrepromptsHolder
) -> FilesDict:
+ """
+ Generates code based on clarifications obtained from the user and saves it to a specified workspace.
+
+ Parameters
+ ----------
+ ai : AI
+ An instance of the AI model, responsible for processing and generating the code.
+ prompt : str
+ The user's clarification prompt.
+ memory : BaseMemory
+ The memory instance where the generated code log is saved.
+ preprompts_holder : PrepromptsHolder
+ A holder for preprompt messages.
+
+ Returns
+ -------
+ FilesDict
+ A dictionary of file names to their contents generated by the AI.
+ """
preprompts = preprompts_holder.get_preprompts()
messages: List[Message] = [SystemMessage(content=preprompts["clarify"])]
@@ -136,6 +198,30 @@ def lite_gen(
ai: AI, prompt: Prompt, memory: BaseMemory, preprompts_holder: PrepromptsHolder
) -> FilesDict:
+ """
+ Executes the AI model using the main prompt and saves the generated results to the specified workspace.
+
+ Parameters
+ ----------
+ ai : AI
+ An instance of the AI model.
+ prompt : str
+ The main prompt to feed to the AI model.
+ memory : BaseMemory
+ The memory instance where the generated code log is saved.
+ preprompts_holder : PrepromptsHolder
+ A holder for preprompt messages.
+
+ Returns
+ -------
+ FilesDict
+ A dictionary of file names to their contents generated by the AI.
+
+ Notes
+ -----
+ The function assumes the `ai.start` method and the `to_files` utility to be correctly
+ set up and functional. Ensure these prerequisites before invoking `lite_gen`.
+ """
preprompts = preprompts_holder.get_preprompts()
messages = ai.start(
@@ -144,4 +230,4 @@ chat = messages[-1].content.strip()
memory.log(CODE_GEN_LOG_FILE, "\n\n".join(x.pretty_repr() for x in messages))
files_dict = chat_to_files_dict(chat)
- return files_dict+ return files_dict
| 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",
tasks=[
Task(
name="hello",
initial_code=FilesDict({"hello.py": "print('Hello, world!')"}),
command="python hello.py",
prompt=Prompt("Change the code in hello.py to print 'Hello, human!'"),
assertions={
"correct output": lambda assertable: assertable.stdout
== "Hello, human!\n",
"correct file": lambda assertable: assertable.files[
"hello.py"
].strip()
== "print('Hello, human!')",
},
),
Task(
name="hello-patch",
initial_code=FilesDict({"hello.py": "print('Hello, world!')"}),
command="python hello.py",
prompt=Prompt("Patch the code in hello.py to print 'Hello, human!'"),
assertions={
"correct output": lambda assertable: assertable.stdout
== "Hello, human!\n",
"correct file": lambda assertable: assertable.files[
"hello.py"
].strip()
== "print('Hello, human!')",
},
),
Task(
name="hello-ask",
initial_code=FilesDict({"hello.py": "print('Hello, world!')"}),
command="echo 'Erik' | python hello.py",
prompt=Prompt(
"modify hello.py to ask the user for their name and print 'Hello, <name>!'. don't try to execute it"
),
assertions={
"correct output": lambda assertable: "Hello, Erik!"
in assertable.stdout,
},
),
Task(
name="prime100",
initial_code=FilesDict(
{}
), # Empty dictionary since no initial code is provided
command="python prime.py",
prompt=Prompt(
"write a script prime.py that computes and prints the 100th prime number"
),
assertions={
"correct output": lambda assertable: "541"
in assertable.stdout.split(),
},
),
Task(
name="init-git",
initial_code=FilesDict(
{}
), # Empty dictionary since no initial code is provided
command="git status",
prompt=Prompt(
"initialize a git repository, write a main.py file, and commit it"
),
assertions={
"clean exit": lambda assertable: assertable.process.returncode == 0,
"clean working tree": lambda assertable: "nothing to commit, working tree clean"
in assertable.stdout,
"main.py exists": lambda assertable: "main.py" in assertable.files,
"we have a commit": lambda assertable: "No commits yet"
not in assertable.stdout,
},
),
],
) | --- +++ @@ -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
+---------
+load_gptme : function
+ Loads the GPT-Me benchmark, which consists of a series of tasks for evaluation.
+"""
from gpt_engineer.benchmark.bench_config import GptmeConfig
from gpt_engineer.benchmark.types import Benchmark, Task
from gpt_engineer.core.files_dict import FilesDict
@@ -5,6 +17,14 @@
def load_gptme(config: GptmeConfig) -> Benchmark:
+ """
+ Loads the GPT-Me benchmark, which consists of a series of tasks for evaluation.
+
+ Returns
+ -------
+ Benchmark
+ A Benchmark object containing a list of Task objects for the GPT-Me evaluation.
+ """
return Benchmark(
name="gptme",
tasks=[
@@ -81,4 +101,4 @@ },
),
],
- )+ )
| 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 rudderstack.analytics as rudder_analytics
rudder_analytics.write_key = "2Re4kqwL61GDp7S8ewe6K5dbogG"
rudder_analytics.dataPlaneUrl = "https://gptengineerezm.dataplane.rudderstack.com"
rudder_analytics.track(
user_id=learning.session,
event="learning",
properties=learning.to_dict(), # type: ignore
)
def collect_learnings(
prompt: Prompt,
model: str,
temperature: float,
config: any,
memory: DiskMemory,
review: Review,
):
learnings = extract_learning(prompt, model, temperature, config, memory, review)
try:
send_learning(learnings)
except RuntimeError:
# try to remove some parts of learning that might be too big
# rudderstack max event size is 32kb
max_size = 32 << 10 # 32KB in bytes
current_size = len(learnings.to_json().encode("utf-8")) # get size in bytes
overflow = current_size - max_size
# Add some extra characters for the "[REMOVED...]" string and for safety margin
remove_length = overflow + len(f"[REMOVED {overflow} CHARACTERS]") + 100
learnings.logs = (
learnings.logs[:-remove_length]
+ f"\n\n[REMOVED {remove_length} CHARACTERS]"
)
print(
"WARNING: learning too big, removing some parts. "
"Please report if this results in a crash."
)
try:
send_learning(learnings)
except RuntimeError:
print(
"Sending learnings crashed despite truncation. Progressing without saving learnings."
)
# def steps_file_hash():
# """
# Compute the SHA-256 hash of the steps file.
#
# Returns
# -------
# str
# The SHA-256 hash of the steps file.
# """
# with open(steps.__file__, "r") as f:
# content = f.read()
# return hashlib.sha256(content.encode("utf-8")).hexdigest()
def collect_and_send_human_review(
prompt: Prompt,
model: str,
temperature: float,
config: Tuple[str, ...],
memory: DiskMemory,
):
review = human_review_input()
if review:
collect_learnings(prompt, model, temperature, config, memory, review) | --- +++ @@ -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.
+
+Functions:
+ send_learning(learning): Sends learning data to RudderStack.
+ collect_learnings(prompt, model, temperature, config, memory, review): Processes and sends learning data.
+ collect_and_send_human_review(prompt, model, temperature, config, memory): Collects human feedback and sends it.
+
+Dependencies:
+ hashlib: For generating SHA-256 hash.
+ typing: For type annotations.
+ gpt_engineer.core: Core functionalities of gpt-engineer.
+ gpt_engineer.cli.learning: Handles the extraction of learning data.
+
+Notes:
+ Data sent to RudderStack is not shared with third parties and is used solely to
+ improve gpt-engineer and allow it to handle a broader range of use cases.
+ Consent logic is in gpt_engineer/learning.py.
+"""
from typing import Tuple
@@ -12,6 +35,21 @@
def send_learning(learning: Learning):
+ """
+ Send the learning data to RudderStack for analysis.
+
+ Parameters
+ ----------
+ learning : Learning
+ An instance of the Learning class containing the data to be sent.
+
+ Notes
+ -----
+ This function is only called if consent is given to share data.
+ Data is not shared to a third party. It is used with the sole purpose of
+ improving gpt-engineer, and letting it handle more use cases.
+ Consent logic is in gpt_engineer/learning.py.
+ """
import rudderstack.analytics as rudder_analytics
rudder_analytics.write_key = "2Re4kqwL61GDp7S8ewe6K5dbogG"
@@ -32,6 +70,29 @@ memory: DiskMemory,
review: Review,
):
+ """
+ Collect the learning data and send it to RudderStack for analysis.
+
+ Parameters
+ ----------
+ prompt : str
+ The initial prompt or question that was provided to the model.
+ model : str
+ The name of the model used for generating the response.
+ temperature : float
+ The temperature setting used in the model's response generation.
+ config : any
+ Configuration parameters used for the learning session.
+ memory : DiskMemory
+ An instance of DiskMemory for storing and retrieving data.
+ review : Review
+ An instance of Review containing human feedback on the model's response.
+
+ Notes
+ -----
+ This function attempts to send the learning data to RudderStack. If the data size exceeds
+ the maximum allowed size, it trims the data and retries sending it.
+ """
learnings = extract_learning(prompt, model, temperature, config, memory, review)
try:
send_learning(learnings)
@@ -84,7 +145,33 @@ config: Tuple[str, ...],
memory: DiskMemory,
):
+ """
+ Collects human feedback on the code and sends it for analysis.
+
+ Parameters
+ ----------
+ prompt : str
+ The initial prompt or question that was provided to the model.
+ model : str
+ The name of the model used for generating the response.
+ temperature : float
+ The temperature setting used in the model's response generation.
+ config : Tuple[str, ...]
+ Configuration parameters used for the learning session.
+ memory : DiskMemory
+ An instance of DiskMemory for storing and retrieving data.
+
+ Returns
+ -------
+ None
+
+ Notes
+ -----
+ This function prompts the user for a review of the generated or improved code using the
+ `human_review_input` function. If a valid review is provided, it's serialized to JSON format
+ and stored within the database's memory under the "review" key.
+ """
review = human_review_input()
if review:
- collect_learnings(prompt, model, temperature, config, memory, review)+ collect_learnings(prompt, model, temperature, config, memory, review)
| 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.types import Assertable, Benchmark, Task
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.prompt import Prompt
DATASET_PATH = Path(__file__).parent / "dataset"
class AppsAssertion:
def __init__(self, expected: str, command: str):
self.expected_output = self._format(expected)
self.command = command
def evaluate(self, assertable: Assertable) -> bool:
# Create new execution environment for every run to avoid side effects
env = DiskExecutionEnv()
env.upload(assertable.files)
pro = env.popen(self.command)
try:
stdout, stderr = pro.communicate(timeout=2)
stdout, stderr = stdout.decode("utf-8"), stderr.decode("utf-8")
except TimeoutExpired:
print("Execution Timeout")
return False
return self.expected_output in self._format(stdout)
def _format(self, string: str) -> str:
return string.replace(" ", "").replace("\n", "")
def _get_dataset() -> Union[Dataset, DatasetDict]:
try:
return load_from_disk(str(DATASET_PATH))
except FileNotFoundError:
print("Dataset not found locally, downloading...")
dataset = load_dataset("codeparrot/apps", trust_remote_code=True)
dataset.save_to_disk(str(DATASET_PATH))
return dataset
def load_apps(config: AppsConfig) -> Benchmark:
dataset = _get_dataset()
tasks = []
problems = list()
for dataset_type in ["test", "train"]:
problems += [
Problem(
id=problem["problem_id"],
question=problem["question"],
input_output=problem["input_output"],
starter_code=problem["starter_code"],
)
for index, problem in enumerate(dataset[dataset_type])
if (index < config.__getattribute__(dataset_type + "_end_index"))
and (index >= config.__getattribute__(dataset_type + "_start_index"))
]
for problem in problems:
prompt = Prompt(
problem.question
+ "\nThe program, including its inputs, should be run from the command "
"line like 'python main \"input1 input2 etc \"', with all inputs inside "
"the quotation marks. The program should not read inputs from stdin."
)
tasks.append(
Task(
name=str(problem.id),
initial_code=FilesDict({"main.py": problem.starter_code}),
command=None, # Explicitly setting `None` because each assertion specifies its command
prompt=prompt,
assertions={
f"correct output {i}": AppsAssertion(
expected=problem.outputs[i],
command="python main.py" + ' "' + problem.inputs[i] + '"',
).evaluate
for i in range(
min(len(problem.outputs), config.examples_per_problem)
)
},
)
)
return Benchmark(
name="apps",
tasks=tasks,
) | --- +++ @@ -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
+---------
+load_apps : function
+ Loads the APPS benchmark, which consists of a series coding problems.
+"""
from pathlib import Path
from subprocess import TimeoutExpired
from typing import Union
@@ -50,6 +62,14 @@
def load_apps(config: AppsConfig) -> Benchmark:
+ """
+ Loads the APPS benchmark, which consists of a series coding problems.
+
+ Returns
+ -------
+ Benchmark
+ A Benchmark object containing a list of Task objects for the APPS evaluation.
+ """
dataset = _get_dataset()
tasks = []
problems = list()
@@ -95,4 +115,4 @@ return Benchmark(
name="apps",
tasks=tasks,
- )+ )
| 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 import BaseMemory
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
from gpt_engineer.core.default.disk_memory import DiskMemory
from gpt_engineer.core.default.paths import PREPROMPTS_PATH
from gpt_engineer.core.default.steps import (
execute_entrypoint,
gen_code,
gen_entrypoint,
improve_fn,
)
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.preprompts_holder import PrepromptsHolder
from gpt_engineer.core.prompt import Prompt
CodeGenType = TypeVar("CodeGenType", bound=Callable[[AI, str, BaseMemory], FilesDict])
CodeProcessor = TypeVar(
"CodeProcessor", bound=Callable[[AI, BaseExecutionEnv, FilesDict], FilesDict]
)
ImproveType = TypeVar(
"ImproveType", bound=Callable[[AI, str, FilesDict, BaseMemory], FilesDict]
)
class CliAgent(BaseAgent):
def __init__(
self,
memory: BaseMemory,
execution_env: BaseExecutionEnv,
ai: AI = None,
code_gen_fn: CodeGenType = gen_code,
improve_fn: ImproveType = improve_fn,
process_code_fn: CodeProcessor = execute_entrypoint,
preprompts_holder: PrepromptsHolder = None,
):
self.memory = memory
self.execution_env = execution_env
self.ai = ai or AI()
self.code_gen_fn = code_gen_fn
self.process_code_fn = process_code_fn
self.improve_fn = improve_fn
self.preprompts_holder = preprompts_holder or PrepromptsHolder(PREPROMPTS_PATH)
@classmethod
def with_default_config(
cls,
memory: DiskMemory,
execution_env: DiskExecutionEnv,
ai: AI = None,
code_gen_fn: CodeGenType = gen_code,
improve_fn: ImproveType = improve_fn,
process_code_fn: CodeProcessor = execute_entrypoint,
preprompts_holder: PrepromptsHolder = None,
diff_timeout=3,
):
return cls(
memory=memory,
execution_env=execution_env,
ai=ai,
code_gen_fn=code_gen_fn,
process_code_fn=process_code_fn,
improve_fn=improve_fn,
preprompts_holder=preprompts_holder or PrepromptsHolder(PREPROMPTS_PATH),
)
def init(self, prompt: Prompt) -> FilesDict:
files_dict = self.code_gen_fn(
self.ai, prompt, self.memory, self.preprompts_holder
)
entrypoint = gen_entrypoint(
self.ai, prompt, files_dict, self.memory, self.preprompts_holder
)
combined_dict = {**files_dict, **entrypoint}
files_dict = FilesDict(combined_dict)
files_dict = self.process_code_fn(
self.ai,
self.execution_env,
files_dict,
preprompts_holder=self.preprompts_holder,
prompt=prompt,
memory=self.memory,
)
return files_dict
def improve(
self,
files_dict: FilesDict,
prompt: Prompt,
execution_command: Optional[str] = None,
diff_timeout=3,
) -> FilesDict:
files_dict = self.improve_fn(
self.ai,
prompt,
files_dict,
self.memory,
self.preprompts_holder,
diff_timeout=diff_timeout,
)
# entrypoint = gen_entrypoint(
# self.ai, prompt, files_dict, self.memory, self.preprompts_holder
# )
# combined_dict = {**files_dict, **entrypoint}
# files_dict = FilesDict(combined_dict)
# files_dict = self.process_code_fn(
# self.ai,
# self.execution_env,
# files_dict,
# preprompts_holder=self.preprompts_holder,
# prompt=prompt,
# memory=self.memory,
# )
return files_dict | --- +++ @@ -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 typing import Callable, Optional, TypeVar
@@ -29,6 +34,52 @@
class CliAgent(BaseAgent):
+ """
+ The `CliAgent` class is responsible for managing the lifecycle of code generation and improvement
+ using an AI model. It orchestrates the generation of new code and the improvement of existing code
+ based on given prompts and utilizes a memory system and execution environment for processing.
+
+ Parameters
+ ----------
+ memory : BaseMemory
+ An instance of a class that adheres to the BaseMemory interface, used for storing and retrieving
+ information during the code generation process.
+ execution_env : BaseExecutionEnv
+ An instance of a class that adheres to the BaseExecutionEnv interface, used for executing code
+ and managing the execution environment.
+ ai : AI, optional
+ An instance of the AI class that manages calls to the language model. If not provided, a default
+ instance is created.
+ code_gen_fn : CodeGenType, optional
+ A callable that takes an AI instance, a prompt, and a memory instance to generate code. Defaults
+ to the `gen_code` function.
+ improve_fn : ImproveType, optional
+ A callable that takes an AI instance, a prompt, a FilesDict instance, and a memory instance to
+ improve code. Defaults to the `improve` function.
+ process_code_fn : CodeProcessor, optional
+ A callable that takes an AI instance, an execution environment, and a FilesDict instance to
+ process code. Defaults to the `execute_entrypoint` function.
+ preprompts_holder : PrepromptsHolder, optional
+ An instance of PrepromptsHolder that manages preprompt templates. If not provided, a default
+ instance is created using the PREPROMPTS_PATH.
+
+ Attributes
+ ----------
+ memory : BaseMemory
+ The memory instance where the agent stores and retrieves information.
+ execution_env : BaseExecutionEnv
+ The execution environment instance where the agent executes and manages code.
+ ai : AI
+ The AI instance used for interacting with the language model.
+ code_gen_fn : CodeGenType
+ The function used for generating code.
+ improve_fn : ImproveType
+ The function used for improving code.
+ process_code_fn : CodeProcessor
+ The function used for processing code.
+ preprompts_holder : PrepromptsHolder
+ The holder for preprompt templates.
+ """
def __init__(
self,
@@ -60,6 +111,34 @@ preprompts_holder: PrepromptsHolder = None,
diff_timeout=3,
):
+ """
+ Creates a new instance of CliAgent with default configurations for memory, execution environment,
+ AI, and other functional parameters.
+
+ Parameters
+ ----------
+ memory : DiskMemory
+ An instance of DiskMemory for storing and retrieving information.
+ execution_env : DiskExecutionEnv
+ An instance of DiskExecutionEnv for executing code.
+ ai : AI, optional
+ An instance of AI for interacting with the language model. Defaults to None, which will create
+ a new AI instance.
+ code_gen_fn : CodeGenType, optional
+ A function for generating code. Defaults to `gen_code`.
+ improve_fn : ImproveType, optional
+ A function for improving code. Defaults to `improve`.
+ process_code_fn : CodeProcessor, optional
+ A function for processing code. Defaults to `execute_entrypoint`.
+ preprompts_holder : PrepromptsHolder, optional
+ An instance of PrepromptsHolder for managing preprompt templates. Defaults to None, which will
+ create a new PrepromptsHolder instance using PREPROMPTS_PATH.
+
+ Returns
+ -------
+ CliAgent
+ An instance of CliAgent configured with the provided or default parameters.
+ """
return cls(
memory=memory,
execution_env=execution_env,
@@ -71,6 +150,19 @@ )
def init(self, prompt: Prompt) -> FilesDict:
+ """
+ Generates a new piece of code using the AI and step bundle based on the provided prompt.
+
+ Parameters
+ ----------
+ prompt : str
+ A string prompt that guides the code generation process.
+
+ Returns
+ -------
+ FilesDict
+ An instance of the `FilesDict` class containing the generated code.
+ """
files_dict = self.code_gen_fn(
self.ai, prompt, self.memory, self.preprompts_holder
@@ -97,6 +189,23 @@ execution_command: Optional[str] = None,
diff_timeout=3,
) -> FilesDict:
+ """
+ Improves an existing piece of code using the AI and step bundle based on the provided prompt.
+
+ Parameters
+ ----------
+ files_dict : FilesDict
+ An instance of `FilesDict` containing the code to be improved.
+ prompt : str
+ A string prompt that guides the code improvement process.
+ execution_command : str, optional
+ An optional command to execute the code. If not provided, the default execution command is used.
+
+ Returns
+ -------
+ FilesDict
+ An instance of the `FilesDict` class containing the improved code.
+ """
files_dict = self.improve_fn(
self.ai,
@@ -120,4 +229,4 @@ # memory=self.memory,
# )
- return files_dict+ return files_dict
| 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 DiskExecutionEnv
from gpt_engineer.core.default.disk_memory import DiskMemory
from gpt_engineer.core.default.paths import PREPROMPTS_PATH, memory_path
from gpt_engineer.core.default.steps import gen_code, gen_entrypoint, improve_fn
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.preprompts_holder import PrepromptsHolder
from gpt_engineer.core.prompt import Prompt
class SimpleAgent(BaseAgent):
def __init__(
self,
memory: BaseMemory,
execution_env: BaseExecutionEnv,
ai: AI = None,
preprompts_holder: PrepromptsHolder = None,
):
self.preprompts_holder = preprompts_holder or PrepromptsHolder(PREPROMPTS_PATH)
self.memory = memory
self.execution_env = execution_env
self.ai = ai or AI()
@classmethod
def with_default_config(
cls, path: str, ai: AI = None, preprompts_holder: PrepromptsHolder = None
):
return cls(
memory=DiskMemory(memory_path(path)),
execution_env=DiskExecutionEnv(),
ai=ai,
preprompts_holder=preprompts_holder or PrepromptsHolder(PREPROMPTS_PATH),
)
def init(self, prompt: Prompt) -> FilesDict:
files_dict = gen_code(self.ai, prompt, self.memory, self.preprompts_holder)
entrypoint = gen_entrypoint(
self.ai, prompt, files_dict, self.memory, self.preprompts_holder
)
combined_dict = {**files_dict, **entrypoint}
files_dict = FilesDict(combined_dict)
return files_dict
def improve(
self,
files_dict: FilesDict,
prompt: Prompt,
execution_command: Optional[str] = None,
) -> FilesDict:
files_dict = improve_fn(
self.ai, prompt, files_dict, self.memory, self.preprompts_holder
)
return files_dict
def default_config_agent():
return SimpleAgent.with_default_config(tempfile.mkdtemp()) | --- +++ @@ -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 generate and refine code based on user prompts.
+
+"""
import tempfile
@@ -17,6 +25,24 @@
class SimpleAgent(BaseAgent):
+ """
+ An agent that uses AI to generate and improve code based on a given prompt.
+
+ This agent is capable of initializing a codebase from a prompt and improving an existing
+ codebase based on user input. It uses an AI model to generate and refine code, and it
+ interacts with a repository and an execution environment to manage and execute the code.
+
+ Attributes
+ ----------
+ memory : BaseMemory
+ The memory interface where the code and related data are stored.
+ execution_env : BaseExecutionEnv
+ The execution environment in which the code is executed.
+ ai : AI
+ The AI model used for generating and improving code.
+ preprompts_holder : PrepromptsHolder
+ The holder for preprompt messages that guide the AI model.
+ """
def __init__(
self,
@@ -63,4 +89,12 @@
def default_config_agent():
- return SimpleAgent.with_default_config(tempfile.mkdtemp())+ """
+ Creates an instance of SimpleAgent with default configuration.
+
+ Returns
+ -------
+ SimpleAgent
+ An instance of SimpleAgent with a temporary directory as its base path.
+ """
+ return SimpleAgent.with_default_config(tempfile.mkdtemp())
| 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):
if not isinstance(key, (str, Path)):
raise TypeError("Keys must be strings or Path's")
if not isinstance(value, str):
raise TypeError("Values must be strings")
super().__setitem__(key, value)
def to_chat(self):
chat_str = ""
for file_name, file_content in self.items():
lines_dict = file_to_lines_dict(file_content)
chat_str += f"File: {file_name}\n"
for line_number, line_content in lines_dict.items():
chat_str += f"{line_number} {line_content}\n"
chat_str += "\n"
return f"```\n{chat_str}```"
def to_log(self):
log_str = ""
for file_name, file_content in self.items():
log_str += f"File: {file_name}\n"
log_str += file_content
log_str += "\n"
return log_str
def file_to_lines_dict(file_content: str) -> dict:
lines_dict = OrderedDict(
{
line_number: line_content
for line_number, line_content in enumerate(file_content.split("\n"), 1)
}
)
return lines_dict | --- +++ @@ -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 its contents for chat-based interaction
+with an AI agent and to enforce type checks on keys and values.
+
+Classes:
+ FilesDict: A dictionary-based container for managing code files.
+"""
from collections import OrderedDict
from pathlib import Path
from typing import Union
@@ -6,8 +17,35 @@ # class Code(MutableMapping[str | Path, str]):
# ToDo: implement as mutable mapping, potentially holding a dict instead of being a dict.
class FilesDict(dict):
+ """
+ A dictionary-based container for managing code files.
+
+ This class extends the standard dictionary to enforce string keys and values,
+ representing filenames and their corresponding code content. It provides methods
+ to format its contents for chat-based interaction with an AI agent and to enforce
+ type checks on keys and values.
+ """
def __setitem__(self, key: Union[str, Path], value: str):
+ """
+ Set the code content for the given filename, enforcing type checks on the key and value.
+
+ Overrides the dictionary's __setitem__ to enforce type checks on the key and value.
+ The key must be a string or a Path object, and the value must be a string representing
+ the code content.
+
+ Parameters
+ ----------
+ key : Union[str, Path]
+ The filename as a key for the code content.
+ value : str
+ The code content to associate with the filename.
+
+ Raises
+ ------
+ TypeError
+ If the key is not a string or Path, or if the value is not a string.
+ """
if not isinstance(key, (str, Path)):
raise TypeError("Keys must be strings or Path's")
if not isinstance(value, str):
@@ -15,6 +53,15 @@ super().__setitem__(key, value)
def to_chat(self):
+ """
+ Formats the items of the object (assuming file name and content pairs)
+ into a string suitable for chat display.
+
+ Returns
+ -------
+ str
+ A string representation of the files.
+ """
chat_str = ""
for file_name, file_content in self.items():
lines_dict = file_to_lines_dict(file_content)
@@ -25,6 +72,15 @@ return f"```\n{chat_str}```"
def to_log(self):
+ """
+ Formats the items of the object (assuming file name and content pairs)
+ into a string suitable for log display.
+
+ Returns
+ -------
+ str
+ A string representation of the files.
+ """
log_str = ""
for file_name, file_content in self.items():
log_str += f"File: {file_name}\n"
@@ -34,10 +90,26 @@
def file_to_lines_dict(file_content: str) -> dict:
+ """
+ Converts file content into a dictionary where each line number is a key
+ and the corresponding line content is the value.
+
+ Parameters
+ ----------
+ file_name : str
+ The name of the file.
+ file_content : str
+ The content of the file.
+
+ Returns
+ -------
+ dict
+ A dictionary with file names as keys and dictionaries (line numbers as keys and line contents as values) as values.
+ """
lines_dict = OrderedDict(
{
line_number: line_content
for line_number, line_content in enumerate(file_content.split("\n"), 1)
}
)
- return lines_dict+ return lines_dict
| 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_engineer.applications.cli.cli_agent import CliAgent
from gpt_engineer.applications.cli.collect import collect_and_send_human_review
from gpt_engineer.applications.cli.file_selector import FileSelector
from gpt_engineer.core.ai import AI, ClipboardAI
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
from gpt_engineer.core.default.disk_memory import DiskMemory
from gpt_engineer.core.default.file_store import FileStore
from gpt_engineer.core.default.paths import PREPROMPTS_PATH, memory_path
from gpt_engineer.core.default.steps import (
execute_entrypoint,
gen_code,
handle_improve_mode,
improve_fn as improve_fn,
)
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.git import stage_uncommitted_to_git
from gpt_engineer.core.preprompts_holder import PrepromptsHolder
from gpt_engineer.core.prompt import Prompt
from gpt_engineer.tools.custom_steps import clarified_gen, lite_gen, self_heal
app = typer.Typer(
context_settings={"help_option_names": ["-h", "--help"]}
) # creates a CLI app
def load_env_if_needed():
# We have all these checks for legacy reasons...
if os.getenv("OPENAI_API_KEY") is None:
load_dotenv()
if os.getenv("OPENAI_API_KEY") is None:
load_dotenv(dotenv_path=os.path.join(os.getcwd(), ".env"))
openai.api_key = os.getenv("OPENAI_API_KEY")
if os.getenv("ANTHROPIC_API_KEY") is None:
load_dotenv()
if os.getenv("ANTHROPIC_API_KEY") is None:
load_dotenv(dotenv_path=os.path.join(os.getcwd(), ".env"))
def concatenate_paths(base_path, sub_path):
# Compute the relative path from base_path to sub_path
relative_path = os.path.relpath(sub_path, base_path)
# If the relative path is not in the parent directory, use the original sub_path
if not relative_path.startswith(".."):
return sub_path
# Otherwise, concatenate base_path and sub_path
return os.path.normpath(os.path.join(base_path, sub_path))
def load_prompt(
input_repo: DiskMemory,
improve_mode: bool,
prompt_file: str,
image_directory: str,
entrypoint_prompt_file: str = "",
) -> Prompt:
if os.path.isdir(prompt_file):
raise ValueError(
f"The path to the prompt, {prompt_file}, already exists as a directory. No prompt can be read from it. Please specify a prompt file using --prompt_file"
)
prompt_str = input_repo.get(prompt_file)
if prompt_str:
print(colored("Using prompt from file:", "green"), prompt_file)
print(prompt_str)
else:
if not improve_mode:
prompt_str = input(
"\nWhat application do you want gpt-engineer to generate?\n"
)
else:
prompt_str = input("\nHow do you want to improve the application?\n")
if entrypoint_prompt_file == "":
entrypoint_prompt = ""
else:
full_entrypoint_prompt_file = concatenate_paths(
input_repo.path, entrypoint_prompt_file
)
if os.path.isfile(full_entrypoint_prompt_file):
entrypoint_prompt = input_repo.get(full_entrypoint_prompt_file)
else:
raise ValueError("The provided file at --entrypoint-prompt does not exist")
if image_directory == "":
return Prompt(prompt_str, entrypoint_prompt=entrypoint_prompt)
full_image_directory = concatenate_paths(input_repo.path, image_directory)
if os.path.isdir(full_image_directory):
if len(os.listdir(full_image_directory)) == 0:
raise ValueError("The provided --image_directory is empty.")
image_repo = DiskMemory(full_image_directory)
return Prompt(
prompt_str,
image_repo.get(".").to_dict(),
entrypoint_prompt=entrypoint_prompt,
)
else:
raise ValueError("The provided --image_directory is not a directory.")
def get_preprompts_path(use_custom_preprompts: bool, input_path: Path) -> Path:
original_preprompts_path = PREPROMPTS_PATH
if not use_custom_preprompts:
return original_preprompts_path
custom_preprompts_path = input_path / "preprompts"
if not custom_preprompts_path.exists():
custom_preprompts_path.mkdir()
for file in original_preprompts_path.glob("*"):
if not (custom_preprompts_path / file.name).exists():
(custom_preprompts_path / file.name).write_text(file.read_text())
return custom_preprompts_path
def compare(f1: FilesDict, f2: FilesDict):
def colored_diff(s1, s2):
lines1 = s1.splitlines()
lines2 = s2.splitlines()
diff = difflib.unified_diff(lines1, lines2, lineterm="")
RED = "\033[38;5;202m"
GREEN = "\033[92m"
RESET = "\033[0m"
colored_lines = []
for line in diff:
if line.startswith("+"):
colored_lines.append(GREEN + line + RESET)
elif line.startswith("-"):
colored_lines.append(RED + line + RESET)
else:
colored_lines.append(line)
return "\n".join(colored_lines)
for file in sorted(set(f1) | set(f2)):
diff = colored_diff(f1.get(file, ""), f2.get(file, ""))
if diff:
print(f"Changes to {file}:")
print(diff)
def prompt_yesno() -> bool:
TERM_CHOICES = colored("y", "green") + "/" + colored("n", "red") + " "
while True:
response = input(TERM_CHOICES).strip().lower()
if response in ["y", "yes"]:
return True
if response in ["n", "no"]:
break
print("Please respond with 'y' or 'n'")
def get_system_info():
system_info = {
"os": platform.system(),
"os_version": platform.version(),
"architecture": platform.machine(),
"python_version": sys.version,
"packages": format_installed_packages(get_installed_packages()),
}
return system_info
def get_installed_packages():
try:
result = subprocess.run(
[sys.executable, "-m", "pip", "list", "--format=json"],
capture_output=True,
text=True,
)
packages = json.loads(result.stdout)
return {pkg["name"]: pkg["version"] for pkg in packages}
except Exception as e:
return str(e)
def format_installed_packages(packages):
return "\n".join([f"{name}: {version}" for name, version in packages.items()])
@app.command(
help="""
GPT-engineer lets you:
\b
- Specify a software in natural language
- Sit back and watch as an AI writes and executes the code
- Ask the AI to implement improvements
"""
)
def main(
project_path: str = typer.Argument(".", help="path"),
model: str = typer.Option(
os.environ.get("MODEL_NAME", "gpt-4o"), "--model", "-m", help="model id string"
),
temperature: float = typer.Option(
0.1,
"--temperature",
"-t",
help="Controls randomness: lower values for more focused, deterministic outputs",
),
improve_mode: bool = typer.Option(
False,
"--improve",
"-i",
help="Improve an existing project by modifying the files.",
),
lite_mode: bool = typer.Option(
False,
"--lite",
"-l",
help="Lite mode: run a generation using only the main prompt.",
),
clarify_mode: bool = typer.Option(
False,
"--clarify",
"-c",
help="Clarify mode - discuss specification with AI before implementation.",
),
self_heal_mode: bool = typer.Option(
False,
"--self-heal",
"-sh",
help="Self-heal mode - fix the code by itself when it fails.",
),
azure_endpoint: str = typer.Option(
"",
"--azure",
"-a",
help="""Endpoint for your Azure OpenAI Service (https://xx.openai.azure.com).
In that case, the given model is the deployment name chosen in the Azure AI Studio.""",
),
use_custom_preprompts: bool = typer.Option(
False,
"--use-custom-preprompts",
help="""Use your project's custom preprompts instead of the default ones.
Copies all original preprompts to the project's workspace if they don't exist there.""",
),
llm_via_clipboard: bool = typer.Option(
False,
"--llm-via-clipboard",
help="Use the clipboard to communicate with the AI.",
),
verbose: bool = typer.Option(
False, "--verbose", "-v", help="Enable verbose logging for debugging."
),
debug: bool = typer.Option(
False, "--debug", "-d", help="Enable debug mode for debugging."
),
prompt_file: str = typer.Option(
"prompt",
"--prompt_file",
help="Relative path to a text file containing a prompt.",
),
entrypoint_prompt_file: str = typer.Option(
"",
"--entrypoint_prompt",
help="Relative path to a text file containing a file that specifies requirements for you entrypoint.",
),
image_directory: str = typer.Option(
"",
"--image_directory",
help="Relative path to a folder containing images.",
),
use_cache: bool = typer.Option(
False,
"--use_cache",
help="Speeds up computations and saves tokens when running the same prompt multiple times by caching the LLM response.",
),
skip_file_selection: bool = typer.Option(
False,
"--skip-file-selection",
"-s",
help="Skip interactive file selection in improve mode and use the generated TOML file directly.",
),
no_execution: bool = typer.Option(
False,
"--no_execution",
help="Run setup but to not call LLM or write any code. For testing purposes.",
),
sysinfo: bool = typer.Option(
False,
"--sysinfo",
help="Output system information for debugging",
),
diff_timeout: int = typer.Option(
3,
"--diff_timeout",
help="Diff regexp timeout. Default: 3. Increase if regexp search timeouts.",
),
):
if debug:
import pdb
sys.excepthook = lambda *_: pdb.pm()
if sysinfo:
sys_info = get_system_info()
for key, value in sys_info.items():
print(f"{key}: {value}")
raise typer.Exit()
# Validate arguments
if improve_mode and (clarify_mode or lite_mode):
typer.echo("Error: Clarify and lite mode are not compatible with improve mode.")
raise typer.Exit(code=1)
# Set up logging
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO)
if use_cache:
set_llm_cache(SQLiteCache(database_path=".langchain.db"))
if improve_mode:
assert not (
clarify_mode or lite_mode
), "Clarify and lite mode are not active for improve mode"
load_env_if_needed()
if llm_via_clipboard:
ai = ClipboardAI()
else:
ai = AI(
model_name=model,
temperature=temperature,
azure_endpoint=azure_endpoint,
)
path = Path(project_path)
print("Running gpt-engineer in", path.absolute(), "\n")
prompt = load_prompt(
DiskMemory(path),
improve_mode,
prompt_file,
image_directory,
entrypoint_prompt_file,
)
# todo: if ai.vision is false and not llm_via_clipboard - ask if they would like to use gpt-4-vision-preview instead? If so recreate AI
if not ai.vision:
prompt.image_urls = None
# configure generation function
if clarify_mode:
code_gen_fn = clarified_gen
elif lite_mode:
code_gen_fn = lite_gen
else:
code_gen_fn = gen_code
# configure execution function
if self_heal_mode:
execution_fn = self_heal
else:
execution_fn = execute_entrypoint
preprompts_holder = PrepromptsHolder(
get_preprompts_path(use_custom_preprompts, Path(project_path))
)
memory = DiskMemory(memory_path(project_path))
memory.archive_logs()
execution_env = DiskExecutionEnv()
agent = CliAgent.with_default_config(
memory,
execution_env,
ai=ai,
code_gen_fn=code_gen_fn,
improve_fn=improve_fn,
process_code_fn=execution_fn,
preprompts_holder=preprompts_holder,
)
files = FileStore(project_path)
if not no_execution:
if improve_mode:
files_dict_before, is_linting = FileSelector(project_path).ask_for_files(
skip_file_selection=skip_file_selection
)
# lint the code
if is_linting:
files_dict_before = files.linting(files_dict_before)
files_dict = handle_improve_mode(
prompt, agent, memory, files_dict_before, diff_timeout=diff_timeout
)
if not files_dict or files_dict_before == files_dict:
print(
f"No changes applied. Could you please upload the debug_log_file.txt in {memory.path}/logs folder in a github issue?"
)
else:
print("\nChanges to be made:")
compare(files_dict_before, files_dict)
print()
print(colored("Do you want to apply these changes?", "light_green"))
if not prompt_yesno():
files_dict = files_dict_before
else:
files_dict = agent.init(prompt)
# collect user feedback if user consents
config = (code_gen_fn.__name__, execution_fn.__name__)
collect_and_send_human_review(prompt, model, temperature, config, memory)
stage_uncommitted_to_git(path, files_dict, improve_mode)
files.push(files_dict)
if ai.token_usage_log.is_openai_model():
print("Total api cost: $ ", ai.token_usage_log.usage_cost())
elif os.getenv("LOCAL_MODEL"):
print("Total api cost: $ 0.0 since we are using local LLM.")
else:
print("Total tokens used: ", ai.token_usage_log.total_tokens())
if __name__ == "__main__":
app() | --- +++ @@ -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 AI interaction,
+- Manage the generation or improvement of code projects.
+
+Main Functionality
+------------------
+- Load environment variables required for OpenAI API interaction.
+- Parse user-specified parameters for project configuration and AI behavior.
+- Facilitate interaction with AI models, databases, and archival processes.
+
+Parameters
+----------
+None
+
+Notes
+-----
+- The `OPENAI_API_KEY` must be set in the environment or provided in a `.env` file within the working directory.
+- The default project path is `projects/example`.
+- When using the `azure_endpoint` parameter, provide the Azure OpenAI service endpoint URL.
+"""
import difflib
import json
@@ -43,6 +69,13 @@
def load_env_if_needed():
+ """
+ Load environment variables if the OPENAI_API_KEY is not already set.
+
+ This function checks if the OPENAI_API_KEY environment variable is set,
+ and if not, it attempts to load it from a .env file in the current working
+ directory. It then sets the openai.api_key for use in the application.
+ """
# We have all these checks for legacy reasons...
if os.getenv("OPENAI_API_KEY") is None:
load_dotenv()
@@ -76,6 +109,21 @@ image_directory: str,
entrypoint_prompt_file: str = "",
) -> Prompt:
+ """
+ Load or request a prompt from the user based on the mode.
+
+ Parameters
+ ----------
+ input_repo : DiskMemory
+ The disk memory object where prompts and other data are stored.
+ improve_mode : bool
+ Flag indicating whether the application is in improve mode.
+
+ Returns
+ -------
+ str
+ The loaded or inputted prompt.
+ """
if os.path.isdir(prompt_file):
raise ValueError(
@@ -123,6 +171,21 @@
def get_preprompts_path(use_custom_preprompts: bool, input_path: Path) -> Path:
+ """
+ Get the path to the preprompts, using custom ones if specified.
+
+ Parameters
+ ----------
+ use_custom_preprompts : bool
+ Flag indicating whether to use custom preprompts.
+ input_path : Path
+ The path to the project directory.
+
+ Returns
+ -------
+ Path
+ The path to the directory containing the preprompts.
+ """
original_preprompts_path = PREPROMPTS_PATH
if not use_custom_preprompts:
return original_preprompts_path
@@ -316,6 +379,54 @@ help="Diff regexp timeout. Default: 3. Increase if regexp search timeouts.",
),
):
+ """
+ The main entry point for the CLI tool that generates or improves a project.
+
+ This function sets up the CLI tool, loads environment variables, initializes
+ the AI, and processes the user's request to generate or improve a project
+ based on the provided arguments.
+
+ Parameters
+ ----------
+ project_path : str
+ The file path to the project directory.
+ model : str
+ The model ID string for the AI.
+ temperature : float
+ The temperature setting for the AI's responses.
+ improve_mode : bool
+ Flag indicating whether to improve an existing project.
+ lite_mode : bool
+ Flag indicating whether to run in lite mode.
+ clarify_mode : bool
+ Flag indicating whether to discuss specifications with AI before implementation.
+ self_heal_mode : bool
+ Flag indicating whether to enable self-healing mode.
+ azure_endpoint : str
+ The endpoint for Azure OpenAI services.
+ use_custom_preprompts : bool
+ Flag indicating whether to use custom preprompts.
+ prompt_file : str
+ Relative path to a text file containing a prompt.
+ entrypoint_prompt_file: str
+ Relative path to a text file containing a file that specifies requirements for you entrypoint.
+ image_directory: str
+ Relative path to a folder containing images.
+ use_cache: bool
+ Speeds up computations and saves tokens when running the same prompt multiple times by caching the LLM response.
+ verbose : bool
+ Flag indicating whether to enable verbose logging.
+ skip_file_selection: bool
+ Skip interactive file selection in improve mode and use the generated TOML file directly
+ no_execution: bool
+ Run setup but to not call LLM or write any code. For testing purposes.
+ sysinfo: bool
+ Flag indicating whether to output system information for debugging.
+
+ Returns
+ -------
+ None
+ """
if debug:
import pdb
@@ -447,4 +558,4 @@
if __name__ == "__main__":
- app()+ app()
| 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_engineer.core.git import filter_by_gitignore, is_git_repo
class FileSelector:
IGNORE_FOLDERS = {"site-packages", "node_modules", "venv", "__pycache__"}
FILE_LIST_NAME = "file_selection.toml"
COMMENT = (
"# Remove '#' to select a file or turn off linting.\n\n"
"# Linting with BLACK (Python) enhances code suggestions from LLMs. "
"To disable linting, uncomment the relevant option in the linting settings.\n\n"
"# gpt-engineer can only read selected files. "
"Including irrelevant files will degrade performance, "
"cost additional tokens and potentially overflow token limit.\n\n"
)
LINTING_STRING = '[linting]\n# "linting" = "off"\n\n'
is_linting = True
def __init__(self, project_path: Union[str, Path]):
self.project_path = project_path
self.metadata_db = DiskMemory(metadata_path(self.project_path))
self.toml_path = self.metadata_db.path / self.FILE_LIST_NAME
def ask_for_files(self, skip_file_selection=False) -> tuple[FilesDict, bool]:
if os.getenv("GPTE_TEST_MODE") or skip_file_selection:
# In test mode, retrieve files from a predefined TOML configuration
# also get from toml if skip_file_selector is active
assert self.FILE_LIST_NAME in self.metadata_db
selected_files = self.get_files_from_toml(self.project_path, self.toml_path)
else:
# Otherwise, use the editor file selector for interactive selection
if self.FILE_LIST_NAME in self.metadata_db:
print(
f"File list detected at {self.toml_path}. Edit or delete it if you want to select new files."
)
selected_files = self.editor_file_selector(self.project_path, False)
else:
selected_files = self.editor_file_selector(self.project_path, True)
content_dict = {}
for file_path in selected_files:
# selected files contains paths that are relative to the project path
try:
# to open the file we need the path from the cwd
with open(
Path(self.project_path) / file_path, "r", encoding="utf-8"
) as content:
content_dict[str(file_path)] = content.read()
except FileNotFoundError:
print(f"Warning: File not found {file_path}")
except UnicodeDecodeError:
print(f"Warning: File not UTF-8 encoded {file_path}, skipping")
return FilesDict(content_dict), self.is_linting
def editor_file_selector(
self, input_path: Union[str, Path], init: bool = True
) -> List[str]:
root_path = Path(input_path)
tree_dict = {}
toml_file = DiskMemory(metadata_path(input_path)).path / "file_selection.toml"
# Define the toml file path
# Initialize .toml file with file tree if in initial state
if init:
tree_dict = {x: "selected" for x in self.get_current_files(root_path)}
s = toml.dumps({"files": tree_dict})
# add comments on all lines that match = "selected"
s = "\n".join(
[
"# " + line if line.endswith(' = "selected"') else line
for line in s.split("\n")
]
)
# Write to the toml file
with open(toml_file, "w") as f:
f.write(self.COMMENT)
f.write(self.LINTING_STRING)
f.write(s)
else:
# Load existing files from the .toml configuration
all_files = self.get_current_files(root_path)
s = toml.dumps({"files": {x: "selected" for x in all_files}})
# get linting status from the toml file
with open(toml_file, "r") as file:
linting_status = toml.load(file)
if (
"linting" in linting_status
and linting_status["linting"].get("linting", "").lower() == "off"
):
self.is_linting = False
self.LINTING_STRING = '[linting]\n"linting" = "off"\n\n'
print("\nLinting is disabled")
with open(toml_file, "r") as file:
selected_files = toml.load(file)
lines = s.split("\n")
s = "\n".join(
lines[:1]
+ [
line
if line.split(" = ")[0].strip('"') in selected_files["files"]
else "# " + line
for line in lines[1:]
]
)
# Write the merged list back to the .toml for user review and modification
with open(toml_file, "w") as file:
file.write(self.COMMENT) # Ensure to write the comment
file.write(self.LINTING_STRING)
file.write(s)
print(
"Please select and deselect (add # in front) files, save it, and close it to continue..."
)
self.open_with_default_editor(
toml_file
) # Open the .toml file in the default editor for user modification
return self.get_files_from_toml(
input_path, toml_file
) # Return the list of selected files after user edits
def open_with_default_editor(self, file_path: Union[str, Path]):
editors = [
"gedit",
"notepad",
"nvim",
"write",
"nano",
"vim",
"emacs",
] # Putting the beginner-friendly text editor forward
chosen_editor = os.environ.get("EDITOR")
# Try the preferred editor first, then fallback to common editors
if chosen_editor:
try:
subprocess.run([chosen_editor, file_path])
return
except Exception:
pass
for editor in editors:
try:
subprocess.run([editor, file_path])
return
except Exception:
continue
print("No suitable text editor found. Please edit the file manually.")
def is_utf8(self, file_path: Union[str, Path]) -> bool:
try:
with open(file_path, "rb") as file:
file.read().decode("utf-8")
return True
except UnicodeDecodeError:
return False
def get_files_from_toml(
self, input_path: Union[str, Path], toml_file: Union[str, Path]
) -> List[str]:
selected_files = []
edited_tree = toml.load(toml_file) # Load the edited .toml file
# check if users have disabled linting or not
if (
"linting" in edited_tree
and edited_tree["linting"].get("linting", "").lower() == "off"
):
self.is_linting = False
print("\nLinting is disabled")
else:
self.is_linting = True
# Iterate through the files in the .toml and append selected files to the list
for file, _ in edited_tree["files"].items():
selected_files.append(file)
# Ensure that at least one file is selected, or raise an exception
if not selected_files:
raise Exception(
"No files were selected. Please select at least one file to proceed."
)
print(f"\nYou have selected the following files:\n{input_path}")
project_path = Path(input_path).resolve()
selected_paths = set(
project_path.joinpath(file).resolve(strict=False) for file in selected_files
)
for displayable_path in DisplayablePath.make_tree(project_path):
if displayable_path.path in selected_paths:
p = displayable_path
while p.parent and p.parent.path not in selected_paths:
selected_paths.add(p.parent.path)
p = p.parent
try:
for displayable_path in DisplayablePath.make_tree(project_path):
if displayable_path.path in selected_paths:
print(displayable_path.displayable())
except FileNotFoundError:
print("Specified path does not exist: ", project_path)
except Exception as e:
print("An error occurred while trying to display the file tree:", e)
print("\n")
return selected_files
def merge_file_lists(
self, existing_files: Dict[str, Any], new_files: Dict[str, Any]
) -> Dict[str, Any]:
# Update the existing files with any new files or changes
for file, properties in new_files.items():
if file not in existing_files:
existing_files[file] = properties # Add new files as unselected
# If you want to update other properties of existing files, you can do so here
return existing_files
def should_filter_file(self, file_path: Path, filters: List[str]) -> bool:
for f in filters:
if fnmatch.fnmatchcase(str(file_path), f):
return True
return False
def get_current_files(self, project_path: Union[str, Path]) -> List[str]:
all_files = []
project_path = Path(
project_path
).resolve() # Ensure path is absolute and resolved
file_list = project_path.glob("**/*")
for path in file_list: # Recursively list all files
if path.is_file():
relpath = path.relative_to(project_path)
parts = relpath.parts
if any(part.startswith(".") for part in parts):
continue # Skip hidden files
if any(part in self.IGNORE_FOLDERS for part in parts):
continue
if relpath.name == "prompt":
continue # Skip files named 'prompt'
all_files.append(str(relpath))
if is_git_repo(project_path) and "projects" not in project_path.parts:
all_files = filter_by_gitignore(project_path, all_files)
return sorted(all_files, key=lambda x: Path(x).as_posix())
class DisplayablePath(object):
display_filename_prefix_middle = "├── "
display_filename_prefix_last = "└── "
display_parent_prefix_middle = " "
display_parent_prefix_last = "│ "
def __init__(
self, path: Union[str, Path], parent_path: "DisplayablePath", is_last: bool
):
self.depth = 0
self.path = Path(str(path))
self.parent = parent_path
self.is_last = is_last
if self.parent:
self.depth = self.parent.depth + 1 # Increment depth if it has a parent
@property
def display_name(self) -> str:
if self.path.is_dir():
return self.path.name + "/"
return self.path.name
@classmethod
def make_tree(
cls, root: Union[str, Path], parent=None, is_last=False, criteria=None
) -> Generator["DisplayablePath", None, None]:
root = Path(str(root)) # Ensure root is a Path object
criteria = criteria or cls._default_criteria
displayable_root = cls(root, parent, is_last)
yield displayable_root
if root.is_dir(): # Check if root is a directory before iterating
children = sorted(
list(path for path in root.iterdir() if criteria(path)),
key=lambda s: str(s).lower(),
)
count = 1
for path in children:
is_last = count == len(children)
yield from cls.make_tree(
path, parent=displayable_root, is_last=is_last, criteria=criteria
)
count += 1
@classmethod
def _default_criteria(cls, path: Path) -> bool:
return True
def displayable(self) -> str:
if self.parent is None:
return self.display_name
_filename_prefix = (
self.display_filename_prefix_last
if self.is_last
else self.display_filename_prefix_middle
)
parts = ["{!s} {!s}".format(_filename_prefix, self.display_name)]
parent = self.parent
while parent and parent.parent is not None:
parts.append(
self.display_parent_prefix_middle
if parent.is_last
else self.display_parent_prefix_last
)
parent = parent.parent
return "".join(reversed(parts)) # Assemble the parts into the final string | --- +++ @@ -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
+selections for later use. Designed for efficient workflow enhancement in file-intensive
+environments, it offers customizable file filtering and seamless editor integration.
+
+Key Components:
+- FileSelector: Manages file selection and interaction.
+- DisplayablePath: Provides a structured view of file paths.
+
+Usage:
+Typically used in project setup or management phases for selecting specific files.
+It operates within the GPT-Engineer environment, relying on core functionalities for
+file handling and persistence.
+"""
import fnmatch
import os
@@ -15,6 +33,22 @@
class FileSelector:
+ """
+ Manages file selection and interaction within a project directory.
+
+ This class provides methods to interactively select files from the terminal,
+ save selections for later use, and integrate with system editors for direct
+ file modification.
+
+ Attributes
+ ----------
+ IGNORE_FOLDERS : set
+ A set of directory names to ignore during file selection.
+ FILE_LIST_NAME : str
+ The name of the file that stores the selected files list.
+ COMMENT : str
+ The comment string to be added to the top of the file selection list.
+ """
IGNORE_FOLDERS = {"site-packages", "node_modules", "venv", "__pycache__"}
FILE_LIST_NAME = "file_selection.toml"
@@ -30,11 +64,30 @@ is_linting = True
def __init__(self, project_path: Union[str, Path]):
+ """
+ Initializes the FileSelector with a given project path.
+
+ Parameters
+ ----------
+ project_path : Union[str, Path]
+ The path to the project directory where file selection is to be performed.
+ """
self.project_path = project_path
self.metadata_db = DiskMemory(metadata_path(self.project_path))
self.toml_path = self.metadata_db.path / self.FILE_LIST_NAME
def ask_for_files(self, skip_file_selection=False) -> tuple[FilesDict, bool]:
+ """
+ Prompts the user to select files for context improvement.
+
+ This method supports selection from the terminal or using a previously saved list.
+ In test mode, it retrieves files from a predefined TOML configuration.
+
+ Returns
+ -------
+ FilesDict
+ A dictionary with file paths as keys and file contents as values.
+ """
if os.getenv("GPTE_TEST_MODE") or skip_file_selection:
# In test mode, retrieve files from a predefined TOML configuration
@@ -70,6 +123,21 @@ def editor_file_selector(
self, input_path: Union[str, Path], init: bool = True
) -> List[str]:
+ """
+ Provides an interactive file selection interface using a .toml file.
+
+ Parameters
+ ----------
+ input_path : Union[str, Path]
+ The path where file selection is to be performed.
+ init : bool, optional
+ Indicates whether to initialize the .toml file with the file tree.
+
+ Returns
+ -------
+ List[str]
+ A list of strings representing the paths of selected files.
+ """
root_path = Path(input_path)
tree_dict = {}
@@ -142,6 +210,14 @@ ) # Return the list of selected files after user edits
def open_with_default_editor(self, file_path: Union[str, Path]):
+ """
+ Opens a file with the system's default text editor.
+
+ Parameters
+ ----------
+ file_path : Union[str, Path]
+ The path to the file to be opened in the text editor.
+ """
editors = [
"gedit",
@@ -171,6 +247,19 @@ print("No suitable text editor found. Please edit the file manually.")
def is_utf8(self, file_path: Union[str, Path]) -> bool:
+ """
+ Checks if the file at the given path is UTF-8 encoded.
+
+ Parameters
+ ----------
+ file_path : Union[str, Path]
+ The path to the file to be checked.
+
+ Returns
+ -------
+ bool
+ True if the file is UTF-8 encoded, False otherwise.
+ """
try:
with open(file_path, "rb") as file:
@@ -182,6 +271,26 @@ def get_files_from_toml(
self, input_path: Union[str, Path], toml_file: Union[str, Path]
) -> List[str]:
+ """
+ Retrieves a list of selected files from a .toml configuration file.
+
+ Parameters
+ ----------
+ input_path : Union[str, Path]
+ The path where file selection was performed.
+ toml_file : Union[str, Path]
+ The path to the .toml file containing the file selection.
+
+ Returns
+ -------
+ List[str]
+ A list of strings representing the paths of selected files.
+
+ Raises
+ ------
+ Exception
+ If no files are selected in the .toml file.
+ """
selected_files = []
edited_tree = toml.load(toml_file) # Load the edited .toml file
@@ -235,6 +344,21 @@ def merge_file_lists(
self, existing_files: Dict[str, Any], new_files: Dict[str, Any]
) -> Dict[str, Any]:
+ """
+ Merges two lists of files, preserving the selection status.
+
+ Parameters
+ ----------
+ existing_files : Dict[str, Any]
+ The dictionary of existing files with their properties.
+ new_files : Dict[str, Any]
+ The dictionary of new files with their properties.
+
+ Returns
+ -------
+ Dict[str, Any]
+ The updated dictionary of files after merging.
+ """
# Update the existing files with any new files or changes
for file, properties in new_files.items():
if file not in existing_files:
@@ -244,12 +368,28 @@ return existing_files
def should_filter_file(self, file_path: Path, filters: List[str]) -> bool:
+ """
+ Determines if a file should be ignored based on .gitignore rules.
+ """
for f in filters:
if fnmatch.fnmatchcase(str(file_path), f):
return True
return False
def get_current_files(self, project_path: Union[str, Path]) -> List[str]:
+ """
+ Generates a list of all files in the project directory. Will use .gitignore files if project_path is a git repository.
+
+ Parameters
+ ----------
+ project_path : Union[str, Path]
+ The path to the project directory.
+
+ Returns
+ -------
+ List[str]
+ A list of strings representing the relative paths of all files in the project directory.
+ """
all_files = []
project_path = Path(
project_path
@@ -277,6 +417,12 @@
class DisplayablePath(object):
+ """
+ Represents and displays a file system path in a tree-like structure.
+
+ This class is used to visually represent the structure of directories and files
+ in a way that is similar to a file explorer's tree view.
+ """
display_filename_prefix_middle = "├── "
display_filename_prefix_last = "└── "
@@ -286,6 +432,18 @@ def __init__(
self, path: Union[str, Path], parent_path: "DisplayablePath", is_last: bool
):
+ """
+ Initializes a DisplayablePath object with a given path and parent.
+
+ Parameters
+ ----------
+ path : Union[str, Path]
+ The file system path to be displayed.
+ parent_path : DisplayablePath
+ The parent path in the tree structure.
+ is_last : bool
+ Indicates whether this is the last sibling in the tree structure.
+ """
self.depth = 0
self.path = Path(str(path))
self.parent = parent_path
@@ -295,6 +453,9 @@
@property
def display_name(self) -> str:
+ """
+ Get the display name of the file or directory.
+ """
if self.path.is_dir():
return self.path.name + "/"
return self.path.name
@@ -303,6 +464,25 @@ def make_tree(
cls, root: Union[str, Path], parent=None, is_last=False, criteria=None
) -> Generator["DisplayablePath", None, None]:
+ """
+ Creates a tree of DisplayablePath objects from a root directory.
+
+ Parameters
+ ----------
+ root : Union[str, Path]
+ The root directory from which to start creating the tree.
+ parent : DisplayablePath, optional
+ The parent path in the tree structure.
+ is_last : bool, optional
+ Indicates whether this is the last sibling in the tree structure.
+ criteria : callable, optional
+ A function to filter the paths included in the tree.
+
+ Yields
+ ------
+ DisplayablePath
+ The next DisplayablePath object in the tree.
+ """
root = Path(str(root)) # Ensure root is a Path object
criteria = criteria or cls._default_criteria
displayable_root = cls(root, parent, is_last)
@@ -323,9 +503,20 @@
@classmethod
def _default_criteria(cls, path: Path) -> bool:
+ """
+ The default criteria function to filter the paths.
+ """
return True
def displayable(self) -> str:
+ """
+ Returns a string representation of the path for display in a tree-like structure.
+
+ Returns
+ -------
+ str
+ The displayable string representation of the file or directory.
+ """
if self.parent is None:
return self.display_name
@@ -346,4 +537,4 @@ )
parent = parent.parent
- return "".join(reversed(parts)) # Assemble the parts into the final string+ return "".join(reversed(parts)) # Assemble the parts into the final string
| 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) -> FilesDict:
pass | --- +++ @@ -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 actions.
+
+Classes:
+ BaseAgent: Abstract base class for an agent that interacts with code.
+"""
from abc import ABC, abstractmethod
from gpt_engineer.core.files_dict import FilesDict
@@ -5,6 +15,12 @@
class BaseAgent(ABC):
+ """
+ Abstract base class for an agent that interacts with code.
+
+ 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 actions.
+ """
@abstractmethod
def init(self, prompt: Prompt) -> FilesDict:
@@ -12,4 +28,4 @@
@abstractmethod
def improve(self, files_dict: FilesDict, prompt: Prompt) -> FilesDict:
- pass+ pass
| 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 database that stores its tools as files in a directory.
class DiskMemory(BaseMemory):
def __init__(self, path: Union[str, Path]):
self.path: Path = Path(path).absolute()
self.path.mkdir(parents=True, exist_ok=True)
def __contains__(self, key: str) -> bool:
return (self.path / key).is_file()
def __getitem__(self, key: str) -> str:
full_path = self.path / key
if not full_path.is_file():
raise KeyError(f"File '{key}' could not be found in '{self.path}'")
if full_path.suffix in [".png", ".jpeg", ".jpg"]:
with full_path.open("rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
mime_type = "image/png" if full_path.suffix == ".png" else "image/jpeg"
return f"data:{mime_type};base64,{encoded_string}"
else:
with full_path.open("r", encoding="utf-8") as f:
return f.read()
def get(self, key: str, default: Optional[Any] = None) -> Any:
item_path = self.path / key
try:
if item_path.is_file():
return self[key]
elif item_path.is_dir():
return DiskMemory(item_path)
else:
return default
except:
return default
def __setitem__(self, key: Union[str, Path], val: str) -> None:
if str(key).startswith("../"):
raise ValueError(f"File name {key} attempted to access parent path.")
if not isinstance(val, str):
raise TypeError("val must be str")
full_path = self.path / key
full_path.parent.mkdir(parents=True, exist_ok=True)
full_path.write_text(val, encoding="utf-8")
def __delitem__(self, key: Union[str, Path]) -> None:
item_path = self.path / key
if not item_path.exists():
raise KeyError(f"Item '{key}' could not be found in '{self.path}'")
if item_path.is_file():
item_path.unlink()
elif item_path.is_dir():
shutil.rmtree(item_path)
def __iter__(self) -> Iterator[str]:
return iter(
sorted(
str(item.relative_to(self.path))
for item in sorted(self.path.rglob("*"))
if item.is_file()
)
)
def __len__(self) -> int:
return len(list(self.__iter__()))
def _supported_files(self) -> str:
valid_extensions = {
ext for lang in SUPPORTED_LANGUAGES for ext in lang["extensions"]
}
file_paths = [
str(item)
for item in self
if Path(item).is_file() and Path(item).suffix in valid_extensions
]
return "\n".join(file_paths)
def _all_files(self) -> str:
file_paths = [str(item) for item in self if Path(item).is_file()]
return "\n".join(file_paths)
def to_path_list_string(self, supported_code_files_only: bool = False) -> str:
if supported_code_files_only:
return self._supported_files()
else:
return self._all_files()
def to_dict(self) -> Dict[Union[str, Path], str]:
return {file_path: self[file_path] for file_path in self}
def to_json(self) -> str:
return json.dumps(self.to_dict())
def log(self, key: Union[str, Path], val: str) -> None:
if str(key).startswith("../"):
raise ValueError(f"File name {key} attempted to access parent path.")
if not isinstance(val, str):
raise TypeError("val must be str")
full_path = self.path / "logs" / key
full_path.parent.mkdir(parents=True, exist_ok=True)
# Touch if it doesnt exist
if not full_path.exists():
full_path.touch()
with open(full_path, "a", encoding="utf-8") as file:
file.write(f"\n{datetime.now().isoformat()}\n")
file.write(val + "\n")
def archive_logs(self):
if "logs" in self:
archive_dir = (
self.path / f"logs_{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}"
)
shutil.move(self.path / "logs", archive_dir) | --- +++ @@ -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
+----------
+None
+
+Functions
+---------
+None
+
+Classes
+-------
+DiskMemory
+ A file-based key-value store where keys correspond to filenames and values to file contents.
+"""
import base64
import json
@@ -13,16 +34,71 @@
# This class represents a simple database that stores its tools as files in a directory.
class DiskMemory(BaseMemory):
+ """
+ A file-based key-value store where keys correspond to filenames and values to file contents.
+
+ This class provides an interface to a file-based database, leveraging file operations to
+ facilitate CRUD-like interactions. It allows for quick checks on the existence of keys,
+ retrieval of values based on keys, and setting new key-value pairs.
+
+ Attributes
+ ----------
+ path : Path
+ The directory path where the database files are stored.
+ """
def __init__(self, path: Union[str, Path]):
+ """
+ Initialize the DiskMemory class with a specified path.
+
+ Parameters
+ ----------
+ path : str or Path
+ The path to the directory where the database files will be stored.
+
+ """
self.path: Path = Path(path).absolute()
self.path.mkdir(parents=True, exist_ok=True)
def __contains__(self, key: str) -> bool:
+ """
+ Determine whether the database contains a file with the specified key.
+
+ Parameters
+ ----------
+ key : str
+ The key (filename) to check for existence in the database.
+
+ Returns
+ -------
+ bool
+ Returns True if the file exists, False otherwise.
+
+ """
return (self.path / key).is_file()
def __getitem__(self, key: str) -> str:
+ """
+ Retrieve the content of a file in the database corresponding to the given key.
+ If the file is an image with a .png or .jpeg extension, it returns the content
+ in Base64-encoded string format.
+
+ Parameters
+ ----------
+ key : str
+ The key (filename) whose content is to be retrieved.
+
+ Returns
+ -------
+ str
+ The content of the file associated with the key, or Base64-encoded string if it's a .png or .jpeg file.
+
+ Raises
+ ------
+ KeyError
+ If the file corresponding to the key does not exist in the database.
+ """
full_path = self.path / key
if not full_path.is_file():
@@ -38,6 +114,21 @@ return f.read()
def get(self, key: str, default: Optional[Any] = None) -> Any:
+ """
+ Retrieve the content of a file in the database, or return a default value if not found.
+
+ Parameters
+ ----------
+ key : str
+ The key (filename) whose content is to be retrieved.
+ default : Any, optional
+ The default value to return if the file does not exist. Default is None.
+
+ Returns
+ -------
+ Any
+ The content of the file if it exists, a new DiskMemory instance if the key corresponds to a directory.
+ """
item_path = self.path / key
try:
@@ -51,6 +142,24 @@ return default
def __setitem__(self, key: Union[str, Path], val: str) -> None:
+ """
+ Set or update the content of a file in the database corresponding to the given key.
+
+ Parameters
+ ----------
+ key : str or Path
+ The key (filename) where the content is to be set.
+ val : str
+ The content to be written to the file.
+
+ Raises
+ ------
+ ValueError
+ If the key attempts to access a parent path.
+ TypeError
+ If the value is not a string.
+
+ """
if str(key).startswith("../"):
raise ValueError(f"File name {key} attempted to access parent path.")
@@ -63,6 +172,20 @@ full_path.write_text(val, encoding="utf-8")
def __delitem__(self, key: Union[str, Path]) -> None:
+ """
+ Delete a file or directory from the database corresponding to the given key.
+
+ Parameters
+ ----------
+ key : str or Path
+ The key (filename or directory name) to be deleted.
+
+ Raises
+ ------
+ KeyError
+ If the file or directory corresponding to the key does not exist in the database.
+
+ """
item_path = self.path / key
if not item_path.exists():
raise KeyError(f"Item '{key}' could not be found in '{self.path}'")
@@ -73,6 +196,15 @@ shutil.rmtree(item_path)
def __iter__(self) -> Iterator[str]:
+ """
+ Iterate over the keys (filenames) in the database.
+
+ Yields
+ ------
+ Iterator[str]
+ An iterator over the sorted list of keys (filenames) in the database.
+
+ """
return iter(
sorted(
str(item.relative_to(self.path))
@@ -82,6 +214,15 @@ )
def __len__(self) -> int:
+ """
+ Get the number of files in the database.
+
+ Returns
+ -------
+ int
+ The number of files in the database.
+
+ """
return len(list(self.__iter__()))
def _supported_files(self) -> str:
@@ -100,18 +241,62 @@ return "\n".join(file_paths)
def to_path_list_string(self, supported_code_files_only: bool = False) -> str:
+ """
+ Generate a string representation of the file paths in the database.
+
+ Parameters
+ ----------
+ supported_code_files_only : bool, optional
+ If True, filter the list to include only supported code file extensions.
+ Default is False.
+
+ Returns
+ -------
+ str
+ A newline-separated string of file paths.
+
+ """
if supported_code_files_only:
return self._supported_files()
else:
return self._all_files()
def to_dict(self) -> Dict[Union[str, Path], str]:
+ """
+ Convert the database contents to a dictionary.
+
+ Returns
+ -------
+ Dict[Union[str, Path], str]
+ A dictionary with keys as filenames and values as file contents.
+
+ """
return {file_path: self[file_path] for file_path in self}
def to_json(self) -> str:
+ """
+ Serialize the database contents to a JSON string.
+
+ Returns
+ -------
+ str
+ A JSON string representation of the database contents.
+
+ """
return json.dumps(self.to_dict())
def log(self, key: Union[str, Path], val: str) -> None:
+ """
+ Append to a file or create and write to it if it doesn't exist.
+
+ Parameters
+ ----------
+ key : str or Path
+ The key (filename) where the content is to be appended.
+ val : str
+ The content to be appended to the file.
+
+ """
if str(key).startswith("../"):
raise ValueError(f"File name {key} attempted to access parent path.")
@@ -131,8 +316,11 @@ file.write(val + "\n")
def archive_logs(self):
+ """
+ Moves all logs to archive directory based on current timestamp
+ """
if "logs" in self:
archive_dir = (
self.path / f"logs_{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}"
)
- shutil.move(self.path / "logs", archive_dir)+ shutil.move(self.path / "logs", archive_dir)
| 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):
def __init__(self, path: Union[str, Path, None] = None):
self.files = FileStore(path)
def upload(self, files: FilesDict) -> "DiskExecutionEnv":
self.files.push(files)
return self
def download(self) -> FilesDict:
return self.files.pull()
def popen(self, command: str) -> subprocess.Popen:
p = subprocess.Popen(
command,
shell=True,
cwd=self.files.working_dir,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return p
def run(self, command: str, timeout: Optional[int] = None) -> Tuple[str, str, int]:
start = time.time()
print("\n--- Start of run ---")
# while running, also print the stdout and stderr
p = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=self.files.working_dir,
text=True,
shell=True,
)
print("$", command)
stdout_full, stderr_full = "", ""
try:
while p.poll() is None:
assert p.stdout is not None
assert p.stderr is not None
stdout = p.stdout.readline()
stderr = p.stderr.readline()
if stdout:
print(stdout, end="")
stdout_full += stdout
if stderr:
print(stderr, end="")
stderr_full += stderr
if timeout and time.time() - start > timeout:
print("Timeout!")
p.kill()
raise TimeoutError()
except KeyboardInterrupt:
print()
print("Stopping execution.")
print("Execution stopped.")
p.kill()
print()
print("--- Finished run ---\n")
return stdout_full, stderr_full, p.returncode | --- +++ @@ -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.
+
+Classes
+-------
+DiskExecutionEnv
+ An execution environment that runs code on the local file system and captures
+ the output of the execution.
+
+Imports
+-------
+- subprocess: For running shell commands.
+- time: For timing the execution of commands.
+- Path: For handling file system paths.
+- Optional, Tuple, Union: For type annotations.
+- BaseExecutionEnv: For inheriting the base execution environment interface.
+- FileStore: For managing file storage.
+- FilesDict: For handling collections of files.
+"""
import subprocess
import time
@@ -11,6 +34,20 @@
class DiskExecutionEnv(BaseExecutionEnv):
+ """
+ An execution environment that runs code on the local file system and captures
+ the output of the execution.
+
+ This class is responsible for executing code that is stored on disk. It ensures that
+ the necessary entrypoint file exists and then runs the code using a subprocess. If the
+ execution is interrupted by the user, it handles the interruption gracefully.
+
+ Attributes
+ ----------
+ store : FileStore
+ An instance of FileStore that manages the storage of files in the execution
+ environment.
+ """
def __init__(self, path: Union[str, Path, None] = None):
self.files = FileStore(path)
@@ -71,4 +108,4 @@ print()
print("--- Finished run ---\n")
- return stdout_full, stderr_full, p.returncode+ return stdout_full, stderr_full, p.returncode
| 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}")
for path in benchmark.iterdir():
if path.name in ["prompt", "main_prompt"]:
continue
# Get filename of Path object
if path.is_dir():
# delete the entire directory
shutil.rmtree(path)
else:
# delete the file
os.remove(path)
if __name__ == "__main__":
run(main) | --- +++ @@ -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 that iterates through all directories in the 'benchmark' folder
+ and cleans them by removing all files and directories except for 'prompt' and
+ 'main_prompt'.
+ """
benchmarks = Path("benchmark")
@@ -31,4 +40,4 @@
if __name__ == "__main__":
- run(main)+ run(main)
| 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,
verbose=False,
) -> List[TaskResult]:
task_results = []
for task in benchmark.tasks:
print(f"--> Running task: {task.name}\n")
t0 = time.time()
files_dict = agent.improve(task.initial_code, task.prompt)
t1 = time.time()
env = DiskExecutionEnv()
env.upload(files_dict)
if task.command:
p = env.popen(task.command)
stdout, stderr = p.communicate(benchmark.timeout)
stdout, stderr = stdout.decode("utf-8"), stderr.decode("utf-8")
else:
p, stdout, stderr = None, None, None
exec_result = Assertable(
files=files_dict,
env=env,
process=p,
stdout=stdout,
stderr=stderr,
)
task_results.append(
TaskResult(
task_name=task.name,
assertion_results={
assertion_name: assertion(exec_result)
for assertion_name, assertion in task.assertions.items()
},
duration=t1 - t0,
)
)
if verbose:
print_results(task_results)
return task_results
def print_results(results: list[TaskResult]):
for task_result in results:
print(f"\n--- Results for {task_result.task_name} ---")
print(f"{task_result.task_name} ({task_result.duration:.2f}s)")
for assertion_name, assertion_result in task_result.assertion_results.items():
checkmark = "✅" if assertion_result else "❌"
print(f" {checkmark} {assertion_name}")
print()
success_rates = [task_result.success_rate for task_result in results]
avg_success_rate = sum(success_rates) / len(results)
total_time = sum(task_result.duration for task_result in results)
correct_assertions = sum(
sum(
assertion_result
for assertion_result in task_result.assertion_results.values()
)
for task_result in results
)
total_assertions = sum(
len(task_result.assertion_results) for task_result in results
)
correct_tasks = [
task_result for task_result in results if task_result.success_rate == 1
]
print("--- Results ---")
print(f"Total time: {total_time:.2f}s")
print(f"Completely correct tasks: {len(correct_tasks)}/{len(results)}")
print(f"Total correct assertions: {correct_assertions}/{total_assertions}")
print(f"Average success rate: {avg_success_rate * 100}% on {len(results)} tasks")
print("--- Results ---")
print()
def export_yaml_results(yaml_path, complete_results, config):
for results in complete_results.values():
correct_tasks = [
task_result
for task_result in results["detailed"]
if task_result["solved"] == 1.0
]
fraction_correct = len(correct_tasks) / len(results["detailed"])
results["fully_solved"] = fraction_correct
complete_results["config"] = config
with open(yaml_path, "w") as f:
yaml.dump(complete_results, f, indent=4) | --- +++ @@ -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.
+
+print_results : function
+ Prints the results of the benchmark tasks to the console.
+"""
import time
from typing import List
@@ -14,6 +28,23 @@ benchmark: Benchmark,
verbose=False,
) -> List[TaskResult]:
+ """
+ Runs the benchmark tasks using the provided agent and returns a list of TaskResult objects.
+
+ Parameters
+ ----------
+ agent : BaseAgent
+ The agent to use for running the benchmark tasks.
+ benchmark : Benchmark
+ The benchmark containing the tasks to run.
+ verbose : bool, default=False
+ A flag to indicate whether to print verbose output during the benchmark.
+
+ Returns
+ -------
+ List[TaskResult]
+ A list of TaskResult objects representing the results of the benchmark tasks.
+ """
task_results = []
for task in benchmark.tasks:
print(f"--> Running task: {task.name}\n")
@@ -57,6 +88,18 @@
def print_results(results: list[TaskResult]):
+ """
+ Prints the results of the benchmark tasks to the console.
+
+ Parameters
+ ----------
+ results : list[TaskResult]
+ A list of TaskResult objects representing the results of the benchmark tasks.
+
+ Returns
+ -------
+ None
+ """
for task_result in results:
print(f"\n--- Results for {task_result.task_name} ---")
print(f"{task_result.task_name} ({task_result.duration:.2f}s)")
@@ -104,4 +147,4 @@ results["fully_solved"] = fraction_correct
complete_results["config"] = config
with open(yaml_path, "w") as f:
- yaml.dump(complete_results, f, indent=4)+ yaml.dump(complete_results, f, indent=4)
| 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:
if message["role"] == "function":
formatted_messages.append(
f"function ({message['name']}): {message['content']}\n"
)
else:
assistant_content = (
message["function_call"]
if message.get("function_call")
else message["content"]
)
role_to_message = {
"system": f"system: {message['content']}\n",
"user": f"user: {message['content']}\n",
"assistant": f"assistant: {assistant_content}\n",
}
formatted_messages.append(role_to_message[message["role"]])
for formatted_message in formatted_messages:
role = messages[formatted_messages.index(formatted_message)]["role"]
color = role_to_color[role]
print(colored(formatted_message, color))
@app.command()
def main(
messages_path: str,
):
with open(messages_path) as f:
messages = json.load(f)
pretty_print_conversation(messages)
if __name__ == "__main__":
app() | --- +++ @@ -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.
+
+ Parameters
+ ----------
+ messages : list
+ A list of message dictionaries, each containing 'role', 'name', and 'content' keys.
+
+ """
role_to_color = {
"system": "red",
@@ -45,6 +58,15 @@ def main(
messages_path: str,
):
+ """
+ Main function that loads messages from a JSON file and prints them using pretty formatting.
+
+ Parameters
+ ----------
+ messages_path : str
+ The file path to the JSON file containing the messages.
+
+ """
with open(messages_path) as f:
messages = json.load(f)
@@ -52,4 +74,4 @@
if __name__ == "__main__":
- app()+ app()
| 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 = "gen_entrypoint_chat.txt"
ENTRYPOINT_FILE = "run.sh"
PREPROMPTS_PATH = Path(__file__).parent.parent.parent / "preprompts"
def memory_path(path):
return os.path.join(path, MEMORY_REL_PATH)
def metadata_path(path):
return os.path.join(path, META_DATA_REL_PATH) | --- +++ @@ -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_PATH : str
+ The relative path to the directory where metadata is stored.
+
+MEMORY_REL_PATH : str
+ The relative path to the directory where memory-related files are stored.
+
+CODE_GEN_LOG_FILE : str
+ The filename for the log file that contains all output from code generation.
+
+DEBUG_LOG_FILE : str
+ The filename for the log file that contains debug information.
+
+ENTRYPOINT_FILE : str
+ The filename for the entrypoint script that is executed to run the application.
+
+ENTRYPOINT_LOG_FILE : str
+ The filename for the log file that contains the chat related to entrypoint generation.
+
+PREPROMPTS_PATH : Path
+ The file system path to the directory containing preprompt files.
+
+Functions
+---------
+memory_path : function
+ Constructs the full path to the memory directory based on a given base path.
+
+metadata_path : function
+ Constructs the full path to the metadata directory based on a given base path.
+"""
import os
from pathlib import Path
@@ -15,8 +53,34 @@
def memory_path(path):
+ """
+ Constructs the full path to the memory directory based on a given base path.
+
+ Parameters
+ ----------
+ path : str
+ The base path to append the memory directory to.
+
+ Returns
+ -------
+ str
+ The full path to the memory directory.
+ """
return os.path.join(path, MEMORY_REL_PATH)
def metadata_path(path):
- return os.path.join(path, META_DATA_REL_PATH)+ """
+ Constructs the full path to the metadata directory based on a given base path.
+
+ Parameters
+ ----------
+ path : str
+ The base path to append the metadata directory to.
+
+ Returns
+ -------
+ str
+ The full path to the metadata directory.
+ """
+ return os.path.join(path, META_DATA_REL_PATH)
| 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/535db72607c4ae308566ede4af65295967bb33a8/libs/community/langchain_community/callbacks/openai_info.py
try:
from langchain.callbacks.openai_info import (
get_openai_token_cost_for_model, # fmt: skip
)
except ImportError:
from langchain_community.callbacks.openai_info import (
get_openai_token_cost_for_model, # fmt: skip
)
Message = Union[AIMessage, HumanMessage, SystemMessage]
logger = logging.getLogger(__name__)
@dataclass
class TokenUsage:
"""
Represents token usage statistics for a conversation step.
"""
step_name: str
in_step_prompt_tokens: int
in_step_completion_tokens: int
in_step_total_tokens: int
total_prompt_tokens: int
total_completion_tokens: int
total_tokens: int
class Tokenizer:
def __init__(self, model_name):
self.model_name = model_name
self._tiktoken_tokenizer = (
tiktoken.encoding_for_model(model_name)
if "gpt-4" in model_name or "gpt-3.5" in model_name
else tiktoken.get_encoding("cl100k_base")
)
def num_tokens(self, txt: str) -> int:
return len(self._tiktoken_tokenizer.encode(txt))
def num_tokens_for_base64_image(
self, image_base64: str, detail: str = "high"
) -> int:
if detail == "low":
return 85 # Fixed cost for low detail images
# Decode image from base64
image_data = base64.b64decode(image_base64)
# Convert byte data to image for size extraction
image = Image.open(io.BytesIO(image_data))
# Calculate the initial scale to fit within 2048 square while maintaining aspect ratio
max_dimension = max(image.size)
scale_factor = min(2048 / max_dimension, 1) # Ensure we don't scale up
new_width = int(image.size[0] * scale_factor)
new_height = int(image.size[1] * scale_factor)
# Scale such that the shortest side is 768px
shortest_side = min(new_width, new_height)
if shortest_side > 768:
resize_factor = 768 / shortest_side
new_width = int(new_width * resize_factor)
new_height = int(new_height * resize_factor)
# Calculate the number of 512px tiles needed
width_tiles = math.ceil(new_width / 512)
height_tiles = math.ceil(new_height / 512)
total_tiles = width_tiles * height_tiles
# Each tile costs 170 tokens, plus a base cost of 85 tokens for high detail
token_cost = total_tiles * 170 + 85
return token_cost
def num_tokens_from_messages(self, messages: List[Message]) -> int:
n_tokens = 0
for message in messages:
n_tokens += 4 # Account for message framing tokens
if isinstance(message.content, str):
# Content is a simple string
n_tokens += self.num_tokens(message.content)
elif isinstance(message.content, list):
# Content is a list, potentially mixed with text and images
for item in message.content:
if item.get("type") == "text":
n_tokens += self.num_tokens(item["text"])
elif item.get("type") == "image_url":
image_detail = item["image_url"].get("detail", "high")
image_base64 = item["image_url"].get("url")
n_tokens += self.num_tokens_for_base64_image(
image_base64, detail=image_detail
)
n_tokens += 2 # Account for assistant's reply framing tokens
return n_tokens
class TokenUsageLog:
def __init__(self, model_name):
self.model_name = model_name
self._cumulative_prompt_tokens = 0
self._cumulative_completion_tokens = 0
self._cumulative_total_tokens = 0
self._log = []
self._tokenizer = Tokenizer(model_name)
def update_log(self, messages: List[Message], answer: str, step_name: str) -> None:
prompt_tokens = self._tokenizer.num_tokens_from_messages(messages)
completion_tokens = self._tokenizer.num_tokens(answer)
total_tokens = prompt_tokens + completion_tokens
self._cumulative_prompt_tokens += prompt_tokens
self._cumulative_completion_tokens += completion_tokens
self._cumulative_total_tokens += total_tokens
self._log.append(
TokenUsage(
step_name=step_name,
in_step_prompt_tokens=prompt_tokens,
in_step_completion_tokens=completion_tokens,
in_step_total_tokens=total_tokens,
total_prompt_tokens=self._cumulative_prompt_tokens,
total_completion_tokens=self._cumulative_completion_tokens,
total_tokens=self._cumulative_total_tokens,
)
)
def log(self) -> List[TokenUsage]:
return self._log
def format_log(self) -> str:
result = "step_name,prompt_tokens_in_step,completion_tokens_in_step,total_tokens_in_step,total_prompt_tokens,total_completion_tokens,total_tokens\n"
for log in self._log:
result += f"{log.step_name},{log.in_step_prompt_tokens},{log.in_step_completion_tokens},{log.in_step_total_tokens},{log.total_prompt_tokens},{log.total_completion_tokens},{log.total_tokens}\n"
return result
def is_openai_model(self) -> bool:
return "gpt" in self.model_name.lower()
def total_tokens(self) -> int:
return self._cumulative_total_tokens
def usage_cost(self) -> float | None:
if not self.is_openai_model():
return None
try:
result = 0
for log in self.log():
result += get_openai_token_cost_for_model(
self.model_name, log.total_prompt_tokens, is_completion=False
)
result += get_openai_token_cost_for_model(
self.model_name, log.total_completion_tokens, is_completion=True
)
return result
except Exception as e:
print(f"Error calculating usage cost: {e}")
return None | --- +++ @@ -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 the step.
+ in_step_completion_tokens : int
+ The number of completion tokens used in the step.
+ in_step_total_tokens : int
+ The total number of tokens used in the step.
+ total_prompt_tokens : int
+ The cumulative number of prompt tokens used up to this step.
+ total_completion_tokens : int
+ The cumulative number of completion tokens used up to this step.
+ total_tokens : int
+ The cumulative total number of tokens used up to this step.
+ """
"""
Represents token usage statistics for a conversation step.
@@ -45,6 +65,9 @@
class Tokenizer:
+ """
+ Tokenizer for counting tokens in text.
+ """
def __init__(self, model_name):
self.model_name = model_name
@@ -55,11 +78,34 @@ )
def num_tokens(self, txt: str) -> int:
+ """
+ Get the number of tokens in a text.
+
+ Parameters
+ ----------
+ txt : str
+ The text to count the tokens in.
+
+ Returns
+ -------
+ int
+ The number of tokens in the text.
+ """
return len(self._tiktoken_tokenizer.encode(txt))
def num_tokens_for_base64_image(
self, image_base64: str, detail: str = "high"
) -> int:
+ """
+ Calculate the token size for a base64 encoded image based on OpenAI's token calculation rules.
+
+ Parameters:
+ - image_base64 (str): The base64 encoded string of the image.
+ - detail (str): The detail level of the image, 'low' or 'high'.
+
+ Returns:
+ - int: The token size of the image.
+ """
if detail == "low":
return 85 # Fixed cost for low detail images
@@ -94,6 +140,19 @@ return token_cost
def num_tokens_from_messages(self, messages: List[Message]) -> int:
+ """
+ Get the total number of tokens used by a list of messages, accounting for text and base64 encoded images.
+
+ Parameters
+ ----------
+ messages : List[Message]
+ The list of messages to count the tokens in.
+
+ Returns
+ -------
+ int
+ The total number of tokens used by the messages.
+ """
n_tokens = 0
for message in messages:
n_tokens += 4 # Account for message framing tokens
@@ -119,6 +178,9 @@
class TokenUsageLog:
+ """
+ Represents a log of token usage statistics for a conversation.
+ """
def __init__(self, model_name):
self.model_name = model_name
@@ -129,6 +191,18 @@ self._tokenizer = Tokenizer(model_name)
def update_log(self, messages: List[Message], answer: str, step_name: str) -> None:
+ """
+ Update the token usage log with the number of tokens used in the current step.
+
+ Parameters
+ ----------
+ messages : List[Message]
+ The list of messages in the conversation.
+ answer : str
+ The answer from the AI.
+ step_name : str
+ The name of the step.
+ """
prompt_tokens = self._tokenizer.num_tokens_from_messages(messages)
completion_tokens = self._tokenizer.num_tokens(answer)
total_tokens = prompt_tokens + completion_tokens
@@ -150,21 +224,61 @@ )
def log(self) -> List[TokenUsage]:
+ """
+ Get the token usage log.
+
+ Returns
+ -------
+ List[TokenUsage]
+ A log of token usage details per step in the conversation.
+ """
return self._log
def format_log(self) -> str:
+ """
+ Format the token usage log as a CSV string.
+
+ Returns
+ -------
+ str
+ The token usage log formatted as a CSV string.
+ """
result = "step_name,prompt_tokens_in_step,completion_tokens_in_step,total_tokens_in_step,total_prompt_tokens,total_completion_tokens,total_tokens\n"
for log in self._log:
result += f"{log.step_name},{log.in_step_prompt_tokens},{log.in_step_completion_tokens},{log.in_step_total_tokens},{log.total_prompt_tokens},{log.total_completion_tokens},{log.total_tokens}\n"
return result
def is_openai_model(self) -> bool:
+ """
+ Check if the model is an OpenAI model.
+
+ Returns
+ -------
+ bool
+ True if the model is an OpenAI model, False otherwise.
+ """
return "gpt" in self.model_name.lower()
def total_tokens(self) -> int:
+ """
+ Return the total number of tokens used in the conversation.
+
+ Returns
+ -------
+ int
+ The total number of tokens used in the conversation.
+ """
return self._cumulative_total_tokens
def usage_cost(self) -> float | None:
+ """
+ Return the total cost in USD of the API usage.
+
+ Returns
+ -------
+ float
+ Cost in USD.
+ """
if not self.is_openai_model():
return None
@@ -180,4 +294,4 @@ return result
except Exception as e:
print(f"Error calculating usage cost: {e}")
- return None+ return None
| 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 BaseExecutionEnv
from gpt_engineer.core.base_memory import BaseMemory
from gpt_engineer.core.chat_to_files import apply_diffs, chat_to_files_dict, parse_diffs
from gpt_engineer.core.default.constants import MAX_EDIT_REFINEMENT_STEPS
from gpt_engineer.core.default.paths import (
CODE_GEN_LOG_FILE,
DEBUG_LOG_FILE,
DIFF_LOG_FILE,
ENTRYPOINT_FILE,
ENTRYPOINT_LOG_FILE,
IMPROVE_LOG_FILE,
)
from gpt_engineer.core.files_dict import FilesDict, file_to_lines_dict
from gpt_engineer.core.preprompts_holder import PrepromptsHolder
from gpt_engineer.core.prompt import Prompt
def curr_fn() -> str:
return inspect.stack()[1].function
def setup_sys_prompt(preprompts: MutableMapping[Union[str, Path], str]) -> str:
return (
preprompts["roadmap"]
+ preprompts["generate"].replace("FILE_FORMAT", preprompts["file_format"])
+ "\nUseful to know:\n"
+ preprompts["philosophy"]
)
def setup_sys_prompt_existing_code(
preprompts: MutableMapping[Union[str, Path], str]
) -> str:
return (
preprompts["roadmap"]
+ preprompts["improve"].replace("FILE_FORMAT", preprompts["file_format_diff"])
+ "\nUseful to know:\n"
+ preprompts["philosophy"]
)
def gen_code(
ai: AI, prompt: Prompt, memory: BaseMemory, preprompts_holder: PrepromptsHolder
) -> FilesDict:
preprompts = preprompts_holder.get_preprompts()
messages = ai.start(
setup_sys_prompt(preprompts), prompt.to_langchain_content(), step_name=curr_fn()
)
chat = messages[-1].content.strip()
memory.log(CODE_GEN_LOG_FILE, "\n\n".join(x.pretty_repr() for x in messages))
files_dict = chat_to_files_dict(chat)
return files_dict
def gen_entrypoint(
ai: AI,
prompt: Prompt,
files_dict: FilesDict,
memory: BaseMemory,
preprompts_holder: PrepromptsHolder,
) -> FilesDict:
user_prompt = prompt.entrypoint_prompt
if not user_prompt:
user_prompt = """
Make a unix script that
a) installs dependencies
b) runs all necessary parts of the codebase (in parallel if necessary)
"""
preprompts = preprompts_holder.get_preprompts()
messages = ai.start(
system=(preprompts["entrypoint"]),
user=user_prompt
+ "\nInformation about the codebase:\n\n"
+ files_dict.to_chat(),
step_name=curr_fn(),
)
print()
chat = messages[-1].content.strip()
regex = r"```\S*\n(.+?)```"
matches = re.finditer(regex, chat, re.DOTALL)
entrypoint_code = FilesDict(
{ENTRYPOINT_FILE: "\n".join(match.group(1) for match in matches)}
)
memory.log(ENTRYPOINT_LOG_FILE, "\n\n".join(x.pretty_repr() for x in messages))
return entrypoint_code
def execute_entrypoint(
ai: AI,
execution_env: BaseExecutionEnv,
files_dict: FilesDict,
prompt: Prompt = None,
preprompts_holder: PrepromptsHolder = None,
memory: BaseMemory = None,
) -> FilesDict:
if ENTRYPOINT_FILE not in files_dict:
raise FileNotFoundError(
"The required entrypoint "
+ ENTRYPOINT_FILE
+ " does not exist in the code."
)
command = files_dict[ENTRYPOINT_FILE]
print()
print(
colored(
"Do you want to execute this code? (Y/n)",
"red",
)
)
print()
print(command)
print()
if input("").lower() not in ["", "y", "yes"]:
print("Ok, not executing the code.")
return files_dict
print("Executing the code...")
print()
print(
colored(
"Note: If it does not work as expected, consider running the code"
+ " in another way than above.",
"green",
)
)
print()
print("You can press ctrl+c *once* to stop the execution.")
print()
execution_env.upload(files_dict).run(f"bash {ENTRYPOINT_FILE}")
return files_dict
def improve_fn(
ai: AI,
prompt: Prompt,
files_dict: FilesDict,
memory: BaseMemory,
preprompts_holder: PrepromptsHolder,
diff_timeout=3,
) -> FilesDict:
preprompts = preprompts_holder.get_preprompts()
messages = [
SystemMessage(content=setup_sys_prompt_existing_code(preprompts)),
]
# Add files as input
messages.append(HumanMessage(content=f"{files_dict.to_chat()}"))
messages.append(HumanMessage(content=prompt.to_langchain_content()))
memory.log(
DEBUG_LOG_FILE,
"UPLOADED FILES:\n" + files_dict.to_log() + "\nPROMPT:\n" + prompt.text,
)
return _improve_loop(ai, files_dict, memory, messages, diff_timeout=diff_timeout)
def _improve_loop(
ai: AI, files_dict: FilesDict, memory: BaseMemory, messages: List, diff_timeout=3
) -> FilesDict:
messages = ai.next(messages, step_name=curr_fn())
files_dict, errors = salvage_correct_hunks(
messages, files_dict, memory, diff_timeout=diff_timeout
)
retries = 0
while errors and retries < MAX_EDIT_REFINEMENT_STEPS:
messages.append(
HumanMessage(
content="Some previously produced diffs were not on the requested format, or the code part was not found in the code. Details:\n"
+ "\n".join(errors)
+ "\n Only rewrite the problematic diffs, making sure that the failing ones are now on the correct format and can be found in the code. Make sure to not repeat past mistakes. \n"
)
)
messages = ai.next(messages, step_name=curr_fn())
files_dict, errors = salvage_correct_hunks(
messages, files_dict, memory, diff_timeout
)
retries += 1
return files_dict
def salvage_correct_hunks(
messages: List, files_dict: FilesDict, memory: BaseMemory, diff_timeout=3
) -> tuple[FilesDict, List[str]]:
error_messages = []
ai_response = messages[-1].content.strip()
diffs = parse_diffs(ai_response, diff_timeout=diff_timeout)
# validate and correct diffs
for _, diff in diffs.items():
# if diff is a new file, validation and correction is unnecessary
if not diff.is_new_file():
problems = diff.validate_and_correct(
file_to_lines_dict(files_dict[diff.filename_pre])
)
error_messages.extend(problems)
files_dict = apply_diffs(diffs, files_dict)
memory.log(IMPROVE_LOG_FILE, "\n\n".join(x.pretty_repr() for x in messages))
memory.log(DIFF_LOG_FILE, "\n\n".join(error_messages))
return files_dict, error_messages
class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for file in self.files:
file.write(obj)
def flush(self):
for file in self.files:
file.flush()
def handle_improve_mode(prompt, agent, memory, files_dict, diff_timeout=3):
captured_output = io.StringIO()
old_stdout = sys.stdout
sys.stdout = Tee(sys.stdout, captured_output)
try:
files_dict = agent.improve(files_dict, prompt, diff_timeout=diff_timeout)
except Exception as e:
print(
f"Error while improving the project: {e}\nCould you please upload the debug_log_file.txt in {memory.path}/logs folder to github?\nFULL STACK TRACE:\n"
)
traceback.print_exc(file=sys.stdout) # Print the full stack trace
finally:
# Reset stdout
sys.stdout = old_stdout
# Get the captured output
captured_string = captured_output.getvalue()
print(captured_string)
memory.log(DEBUG_LOG_FILE, "\nCONSOLE OUTPUT:\n" + captured_string)
return files_dict | --- +++ @@ -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 for the codebase, executing the entrypoint, and refining code edits.
+
+Functions
+---------
+curr_fn : function
+ Returns the name of the current function.
+
+setup_sys_prompt : function
+ Sets up the system prompt for generating code.
+
+gen_code : function
+ Generates code from a prompt using AI and returns the generated files.
+
+gen_entrypoint : function
+ Generates an entrypoint for the codebase and returns the entrypoint files.
+
+execute_entrypoint : function
+ Executes the entrypoint of the codebase.
+
+setup_sys_prompt_existing_code : function
+ Sets up the system prompt for improving existing code.
+
+
+improve : function
+ Improves the code based on user input and returns the updated files.
+"""
import inspect
import io
@@ -30,10 +61,31 @@
def curr_fn() -> str:
+ """
+ Returns the name of the current function.
+
+ Returns
+ -------
+ str
+ The name of the function that called this function.
+ """
return inspect.stack()[1].function
def setup_sys_prompt(preprompts: MutableMapping[Union[str, Path], str]) -> str:
+ """
+ Sets up the system prompt for generating code.
+
+ Parameters
+ ----------
+ preprompts : MutableMapping[Union[str, Path], str]
+ A mapping of preprompt messages to guide the AI model.
+
+ Returns
+ -------
+ str
+ The system prompt message for the AI model.
+ """
return (
preprompts["roadmap"]
+ preprompts["generate"].replace("FILE_FORMAT", preprompts["file_format"])
@@ -45,6 +97,19 @@ def setup_sys_prompt_existing_code(
preprompts: MutableMapping[Union[str, Path], str]
) -> str:
+ """
+ Sets up the system prompt for improving existing code.
+
+ Parameters
+ ----------
+ preprompts : MutableMapping[Union[str, Path], str]
+ A mapping of preprompt messages to guide the AI model.
+
+ Returns
+ -------
+ str
+ The system prompt message for the AI model to improve existing code.
+ """
return (
preprompts["roadmap"]
+ preprompts["improve"].replace("FILE_FORMAT", preprompts["file_format_diff"])
@@ -56,6 +121,25 @@ def gen_code(
ai: AI, prompt: Prompt, memory: BaseMemory, preprompts_holder: PrepromptsHolder
) -> FilesDict:
+ """
+ Generates code from a prompt using AI and returns the generated files.
+
+ Parameters
+ ----------
+ ai : AI
+ The AI model used for generating code.
+ prompt : str
+ The user prompt to generate code from.
+ memory : BaseMemory
+ The memory interface where the code and related data are stored.
+ preprompts_holder : PrepromptsHolder
+ The holder for preprompt messages that guide the AI model.
+
+ Returns
+ -------
+ FilesDict
+ A dictionary of file names to their respective source code content.
+ """
preprompts = preprompts_holder.get_preprompts()
messages = ai.start(
setup_sys_prompt(preprompts), prompt.to_langchain_content(), step_name=curr_fn()
@@ -73,6 +157,25 @@ memory: BaseMemory,
preprompts_holder: PrepromptsHolder,
) -> FilesDict:
+ """
+ Generates an entrypoint for the codebase and returns the entrypoint files.
+
+ Parameters
+ ----------
+ ai : AI
+ The AI model used for generating the entrypoint.
+ files_dict : FilesDict
+ The dictionary of file names to their respective source code content.
+ memory : BaseMemory
+ The memory interface where the code and related data are stored.
+ preprompts_holder : PrepromptsHolder
+ The holder for preprompt messages that guide the AI model.
+
+ Returns
+ -------
+ FilesDict
+ A dictionary containing the entrypoint file.
+ """
user_prompt = prompt.entrypoint_prompt
if not user_prompt:
user_prompt = """
@@ -107,6 +210,25 @@ preprompts_holder: PrepromptsHolder = None,
memory: BaseMemory = None,
) -> FilesDict:
+ """
+ Executes the entrypoint of the codebase.
+
+ Parameters
+ ----------
+ ai : AI
+ The AI model used for generating the entrypoint.
+ execution_env : BaseExecutionEnv
+ The execution environment in which the code is executed.
+ files_dict : FilesDict
+ The dictionary of file names to their respective source code content.
+ preprompts_holder : PrepromptsHolder, optional
+ The holder for preprompt messages that guide the AI model.
+
+ Returns
+ -------
+ FilesDict
+ The dictionary of file names to their respective source code content after execution.
+ """
if ENTRYPOINT_FILE not in files_dict:
raise FileNotFoundError(
"The required entrypoint "
@@ -154,6 +276,27 @@ preprompts_holder: PrepromptsHolder,
diff_timeout=3,
) -> FilesDict:
+ """
+ Improves the code based on user input and returns the updated files.
+
+ Parameters
+ ----------
+ ai : AI
+ The AI model used for improving code.
+ prompt :str
+ The user prompt to improve the code.
+ files_dict : FilesDict
+ The dictionary of file names to their respective source code content.
+ memory : BaseMemory
+ The memory interface where the code and related data are stored.
+ preprompts_holder : PrepromptsHolder
+ The holder for preprompt messages that guide the AI model.
+
+ Returns
+ -------
+ FilesDict
+ The dictionary of file names to their respective updated source code content.
+ """
preprompts = preprompts_holder.get_preprompts()
messages = [
SystemMessage(content=setup_sys_prompt_existing_code(preprompts)),
@@ -251,4 +394,4 @@ print(captured_string)
memory.log(DEBUG_LOG_FILE, "\nCONSOLE OUTPUT:\n" + captured_string)
- return files_dict+ return files_dict
| 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 NotImplementedError
@abstractmethod
def popen(self, command: str) -> Popen:
raise NotImplementedError
@abstractmethod
def upload(self, files: FilesDict) -> "BaseExecutionEnv":
raise NotImplementedError
@abstractmethod
def download(self) -> FilesDict:
raise NotImplementedError | --- +++ @@ -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.
+ """
@abstractmethod
def run(self, command: str, timeout: Optional[int] = None) -> Tuple[str, str, int]:
+ """
+ Runs a command in the execution environment.
+ """
raise NotImplementedError
@abstractmethod
def popen(self, command: str) -> Popen:
+ """
+ Runs a command in the execution environment.
+ """
raise NotImplementedError
@abstractmethod
def upload(self, files: FilesDict) -> "BaseExecutionEnv":
+ """
+ Uploads files to the execution environment.
+ """
raise NotImplementedError
@abstractmethod
def download(self) -> FilesDict:
- raise NotImplementedError+ """
+ Downloads files from the execution environment.
+ """
+ raise NotImplementedError
| 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 = "./src" # source directory (under the base directory) from which context will be retrieved
[gptengineer-app] # this namespace is used for gptengineer.app, may be used for internal experiments
project_id = "..."
# we support multiple OpenAPI schemas, used as context for the LLM
openapi = [
{ url = "https://api.gptengineer.app/openapi.json" },
{ url = "https://some-color-translating-api/openapi.json" },
]
"""
@dataclass
class _PathsConfig:
base: str | None = None
src: str | None = None
@dataclass
class _RunConfig:
build: str | None = None
test: str | None = None
lint: str | None = None
format: str | None = None
@dataclass
class _OpenApiConfig:
url: str
@dataclass
class _GptEngineerAppConfig:
project_id: str
openapi: list[_OpenApiConfig] | None = None
def filter_none(d: dict) -> dict:
# Drop None values and empty dictionaries from a dictionary
return {
k: v
for k, v in (
(k, filter_none(v) if isinstance(v, dict) else v)
for k, v in d.items()
if v is not None
)
if not (isinstance(v, dict) and not v) # Check for non-empty after filtering
}
@dataclass
class Config:
paths: _PathsConfig = field(default_factory=_PathsConfig)
run: _RunConfig = field(default_factory=_RunConfig)
gptengineer_app: _GptEngineerAppConfig | None = None
@classmethod
def from_toml(cls, config_file: Path | str):
if isinstance(config_file, str):
config_file = Path(config_file)
config_dict = read_config(config_file)
return cls.from_dict(config_dict)
@classmethod
def from_dict(cls, config_dict: dict):
run = _RunConfig(**config_dict.get("run", {}))
paths = _PathsConfig(**config_dict.get("paths", {}))
# load optional gptengineer-app section
gptengineer_app_dict = config_dict.get("gptengineer-app", {})
gptengineer_app = None
if gptengineer_app_dict:
assert (
"project_id" in gptengineer_app_dict
), "project_id is required in gptengineer-app section"
gptengineer_app = _GptEngineerAppConfig(
# required if gptengineer-app section is present
project_id=gptengineer_app_dict["project_id"],
openapi=[
_OpenApiConfig(**openapi)
for openapi in gptengineer_app_dict.get("openapi", [])
]
or None,
)
return cls(paths=paths, run=run, gptengineer_app=gptengineer_app)
def to_dict(self) -> dict:
d = asdict(self)
d["gptengineer-app"] = d.pop("gptengineer_app", None)
# Drop None values and empty dictionaries
# Needed because tomlkit.dumps() doesn't handle None values,
# and we don't want to write empty sections.
d = filter_none(d)
return d
def to_toml(self, config_file: Path | str, save=True) -> str:
if isinstance(config_file, str):
config_file = Path(config_file)
# Load the TOMLDocument and overwrite it with the new values
config = read_config(config_file)
default_config = Config().to_dict()
for k, v in self.to_dict().items():
# only write values that are already explicitly set, or that differ from defaults
if k in config or v != default_config[k]:
if isinstance(v, dict):
config[k] = {
k2: v2
for k2, v2 in v.items()
if (
k2 in config[k]
or default_config.get(k) is None
or v2 != default_config[k].get(k2)
)
}
else:
config[k] = v
toml_str = tomlkit.dumps(config)
if save:
with open(config_file, "w") as f:
f.write(toml_str)
return toml_str
def read_config(config_file: Path) -> tomlkit.TOMLDocument:
assert config_file.exists(), f"Config file {config_file} does not exist"
with open(config_file, "r") as f:
return tomlkit.load(f) | --- +++ @@ -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 import Path
@@ -66,6 +71,7 @@
@dataclass
class Config:
+ """Configuration for the GPT Engineer CLI and gptengineer.app via `gpt-engineer.toml`."""
paths: _PathsConfig = field(default_factory=_PathsConfig)
run: _RunConfig = field(default_factory=_RunConfig)
@@ -114,6 +120,7 @@ return d
def to_toml(self, config_file: Path | str, save=True) -> str:
+ """Write the configuration to a TOML file."""
if isinstance(config_file, str):
config_file = Path(config_file)
@@ -145,6 +152,7 @@
def read_config(config_file: Path) -> tomlkit.TOMLDocument:
+ """Read the configuration file"""
assert config_file.exists(), f"Config file {config_file} does not exist"
with open(config_file, "r") as f:
- return tomlkit.load(f)+ return tomlkit.load(f)
| 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: FilesDict
env: BaseExecutionEnv
process: Optional[Popen]
stdout: Optional[str]
stderr: Optional[str]
Assertion = Callable[[Assertable], bool]
@dataclass
class Task:
name: str
initial_code: Optional[FilesDict]
command: Optional[str]
prompt: Prompt
assertions: Optional[Dict[str, Assertion]]
@dataclass
class Benchmark:
name: str
tasks: list[Task]
timeout: Optional[int] = None
@dataclass
class TaskResult:
task_name: str
assertion_results: dict[str, bool]
duration: float
# Returns success rate from 0.00 up to 1.00
@property
def success_rate(self) -> float:
if not self.assertion_results:
return 0.0
succeeded = len(
[result for result in self.assertion_results.values() if result is True]
)
return succeeded / len(self.assertion_results)
def to_dict(self) -> dict:
out_dict = {key: value for key, value in self.__dict__.items()}
out_dict["solved"] = self.success_rate
return out_dict | --- +++ @@ -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 against in a benchmark task.
+
+ Assertion:
+ Type alias for a callable that takes an Assertable and returns a boolean.
+
+ Task:
+ Represents a single task within a benchmark, including its assertions.
+
+ Benchmark:
+ Represents a collection of tasks used to evaluate a model's performance.
+
+ TaskResult:
+ Represents the result of running a single task within a benchmark.
+"""
from dataclasses import dataclass
from subprocess import Popen
from typing import Callable, Dict, Optional
@@ -9,6 +31,16 @@
@dataclass
class Assertable:
+ """
+ A class representing an object which can be asserted against.
+
+ Attributes:
+ files (FilesDict): The code files involved in the assertion.
+ env (BaseExecutionEnv): The execution environment in which the code is run.
+ process (Popen): The subprocess in which the code is run.
+ stdout (str): The standard output from the code execution.
+ stderr (str): The standard error from the code execution.
+ """
files: FilesDict
env: BaseExecutionEnv
@@ -31,6 +63,7 @@
@dataclass
class Benchmark:
+ """A benchmark is a collection of tasks that evaluate a model's performance."""
name: str
tasks: list[Task]
@@ -58,4 +91,4 @@ def to_dict(self) -> dict:
out_dict = {key: value for key, value in self.__dict__.items()}
out_dict["solved"] = self.success_rate
- return out_dict+ return out_dict
| 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) -> str:
pass | --- +++ @@ -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 import ABC, abstractmethod
from pathlib import Path
from typing import Union
@@ -6,6 +13,13 @@
class BaseVersionManager(ABC):
+ """
+ Abstract base class for a version manager.
+
+ Defines the interface for version managers that handle 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.
+ """
@abstractmethod
def __init__(self, path: Union[str, Path]):
@@ -13,4 +27,4 @@
@abstractmethod
def snapshot(self, files_dict: FilesDict) -> str:
- pass+ pass
| 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.zeros(ndim)) if bias else None
def forward(self, input):
return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)
class CausalSelfAttention(nn.Module):
def __init__(self, config):
super().__init__()
assert config.n_embd % config.n_head == 0
# key, query, value projections for all heads, but in a batch
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
# output projection
self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
# regularization
self.attn_dropout = nn.Dropout(config.dropout)
self.resid_dropout = nn.Dropout(config.dropout)
self.n_head = config.n_head
self.n_embd = config.n_embd
self.dropout = config.dropout
# flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
if not self.flash:
print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
# causal mask to ensure that attention is only applied to the left in the input sequence
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
.view(1, 1, config.block_size, config.block_size))
def forward(self, x):
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
# causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
if self.flash:
# efficient attention using Flash Attention CUDA kernels
y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0, is_causal=True)
else:
# manual implementation of attention
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
att = F.softmax(att, dim=-1)
att = self.attn_dropout(att)
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
# output projection
y = self.resid_dropout(self.c_proj(y))
return y
class MLP(nn.Module):
def __init__(self, config):
super().__init__()
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
self.gelu = nn.GELU()
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
self.dropout = nn.Dropout(config.dropout)
def forward(self, x):
x = self.c_fc(x)
x = self.gelu(x)
x = self.c_proj(x)
x = self.dropout(x)
return x
class Block(nn.Module):
def __init__(self, config):
super().__init__()
self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)
self.attn = CausalSelfAttention(config)
self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)
self.mlp = MLP(config)
def forward(self, x):
x = x + self.attn(self.ln_1(x))
x = x + self.mlp(self.ln_2(x))
return x
@dataclass
class GPTConfig:
block_size: int = 1024
vocab_size: int = 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
n_layer: int = 12
n_head: int = 12
n_embd: int = 768
dropout: float = 0.0
bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
class GPT(nn.Module):
def __init__(self, config):
super().__init__()
assert config.vocab_size is not None
assert config.block_size is not None
self.config = config
self.transformer = nn.ModuleDict(dict(
wte = nn.Embedding(config.vocab_size, config.n_embd),
wpe = nn.Embedding(config.block_size, config.n_embd),
drop = nn.Dropout(config.dropout),
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
ln_f = LayerNorm(config.n_embd, bias=config.bias),
))
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
# with weight tying when using torch.compile() some warnings get generated:
# "UserWarning: functional_call was passed multiple values for tied weights.
# This behavior is deprecated and will be an error in future versions"
# not 100% sure what this is, so far seems to be harmless. TODO investigate
self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying
# init all weights
self.apply(self._init_weights)
# apply special scaled init to the residual projections, per GPT-2 paper
for pn, p in self.named_parameters():
if pn.endswith('c_proj.weight'):
torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))
# report number of parameters
print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
def get_num_params(self, non_embedding=True):
n_params = sum(p.numel() for p in self.parameters())
if non_embedding:
n_params -= self.transformer.wpe.weight.numel()
return n_params
def _init_weights(self, module):
if isinstance(module, nn.Linear):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
if module.bias is not None:
torch.nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
def forward(self, idx, targets=None):
device = idx.device
b, t = idx.size()
assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)
# forward the GPT model itself
tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
x = self.transformer.drop(tok_emb + pos_emb)
for block in self.transformer.h:
x = block(x)
x = self.transformer.ln_f(x)
if targets is not None:
# if we are given some desired targets also calculate the loss
logits = self.lm_head(x)
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
else:
# inference-time mini-optimization: only forward the lm_head on the very last position
logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
loss = None
return logits, loss
def crop_block_size(self, block_size):
# model surgery to decrease the block size if necessary
# e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
# but want to use a smaller block size for some smaller, simpler model
assert block_size <= self.config.block_size
self.config.block_size = block_size
self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size])
for block in self.transformer.h:
if hasattr(block.attn, 'bias'):
block.attn.bias = block.attn.bias[:,:,:block_size,:block_size]
@classmethod
def from_pretrained(cls, model_type, override_args=None):
assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
override_args = override_args or {} # default to empty dict
# only dropout can be overridden see more notes below
assert all(k == 'dropout' for k in override_args)
from transformers import GPT2LMHeadModel
print("loading weights from pretrained gpt: %s" % model_type)
# n_layer, n_head and n_embd are determined from model_type
config_args = {
'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
}[model_type]
print("forcing vocab_size=50257, block_size=1024, bias=True")
config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
config_args['bias'] = True # always True for GPT model checkpoints
# we can override the dropout rate, if desired
if 'dropout' in override_args:
print(f"overriding dropout rate to {override_args['dropout']}")
config_args['dropout'] = override_args['dropout']
# create a from-scratch initialized minGPT model
config = GPTConfig(**config_args)
model = GPT(config)
sd = model.state_dict()
sd_keys = sd.keys()
sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
# init a huggingface/transformers model
model_hf = GPT2LMHeadModel.from_pretrained(model_type)
sd_hf = model_hf.state_dict()
# copy while ensuring all of the parameters are aligned and match in names and shapes
sd_keys_hf = sd_hf.keys()
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
# basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
# this means that we have to transpose these weights when we import them
assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
for k in sd_keys_hf:
if any(k.endswith(w) for w in transposed):
# special treatment for the Conv1D weights we need to transpose
assert sd_hf[k].shape[::-1] == sd[k].shape
with torch.no_grad():
sd[k].copy_(sd_hf[k].t())
else:
# vanilla copy over the other parameters
assert sd_hf[k].shape == sd[k].shape
with torch.no_grad():
sd[k].copy_(sd_hf[k])
return model
def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
# start with all of the candidate parameters
param_dict = {pn: p for pn, p in self.named_parameters()}
# filter out those that do not require grad
param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
# create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
# i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
optim_groups = [
{'params': decay_params, 'weight_decay': weight_decay},
{'params': nodecay_params, 'weight_decay': 0.0}
]
num_decay_params = sum(p.numel() for p in decay_params)
num_nodecay_params = sum(p.numel() for p in nodecay_params)
print(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
print(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
# Create AdamW optimizer and use the fused version if it is available
fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
use_fused = fused_available and device_type == 'cuda'
extra_args = dict(fused=True) if use_fused else dict()
optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args)
print(f"using fused AdamW: {use_fused}")
return optimizer
def estimate_mfu(self, fwdbwd_per_iter, dt):
# first estimate the number of flops we do per iteration.
# see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
N = self.get_num_params()
cfg = self.config
L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd//cfg.n_head, cfg.block_size
flops_per_token = 6*N + 12*L*H*Q*T
flops_per_fwdbwd = flops_per_token * T
flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
# express our flops throughput as ratio of A100 bfloat16 peak flops
flops_achieved = flops_per_iter * (1.0/dt) # per second
flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
mfu = flops_achieved / flops_promised
return mfu
@torch.no_grad()
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
for _ in range(max_new_tokens):
# if the sequence context is growing too long we must crop it at block_size
idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
# forward the model to get the logits for the index in the sequence
logits, _ = self(idx_cond)
# pluck the logits at the final step and scale by desired temperature
logits = logits[:, -1, :] / temperature
# optionally crop the logits to only the top k options
if top_k is not None:
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
logits[logits < v[:, [-1]]] = -float('Inf')
# apply softmax to convert logits to (normalized) probabilities
probs = F.softmax(logits, dim=-1)
# sample from the distribution
idx_next = torch.multinomial(probs, num_samples=1)
# append sampled index to the running sequence and continue
idx = torch.cat((idx, idx_next), dim=1)
return idx | --- +++ @@ -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/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py
+"""
import math
import inspect
@@ -8,6 +16,7 @@ from torch.nn import functional as F
class LayerNorm(nn.Module):
+ """ LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """
def __init__(self, ndim, bias):
super().__init__()
@@ -139,6 +148,12 @@ print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
def get_num_params(self, non_embedding=True):
+ """
+ Return the number of parameters in the model.
+ For non-embedding count (default), the position embeddings get subtracted.
+ The token embeddings would too, except due to the parameter sharing these
+ params are actually used as weights in the final layer, so we include them.
+ """
n_params = sum(p.numel() for p in self.parameters())
if non_embedding:
n_params -= self.transformer.wpe.weight.numel()
@@ -272,6 +287,7 @@ return optimizer
def estimate_mfu(self, fwdbwd_per_iter, dt):
+ """ estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS """
# first estimate the number of flops we do per iteration.
# see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
N = self.get_num_params()
@@ -288,6 +304,11 @@
@torch.no_grad()
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
+ """
+ Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
+ the sequence max_new_tokens times, feeding the predictions back into the model each time.
+ Most likely you'll want to make sure to be in model.eval() mode of operation for this.
+ """
for _ in range(max_new_tokens):
# if the sequence context is growing too long we must crop it at block_size
idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
@@ -306,4 +327,4 @@ # append sampled index to the running sequence and continue
idx = torch.cat((idx, idx_next), dim=1)
- return idx+ return idx
| 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 dist
from PIL import Image
from torch.utils.data import Dataset, dataloader, distributed
from ultralytics.cfg import IterableSimpleNamespace
from ultralytics.data.dataset import GroundingDataset, YOLODataset, YOLOMultiModalDataset
from ultralytics.data.loaders import (
LOADERS,
LoadImagesAndVideos,
LoadPilAndNumpy,
LoadScreenshots,
LoadStreams,
LoadTensor,
SourceTypes,
autocast_list,
)
from ultralytics.data.utils import IMG_FORMATS, VID_FORMATS
from ultralytics.utils import RANK, colorstr
from ultralytics.utils.checks import check_file
from ultralytics.utils.torch_utils import TORCH_2_0
class InfiniteDataLoader(dataloader.DataLoader):
def __init__(self, *args: Any, **kwargs: Any):
if not TORCH_2_0:
kwargs.pop("prefetch_factor", None) # not supported by earlier versions
super().__init__(*args, **kwargs)
object.__setattr__(self, "batch_sampler", _RepeatSampler(self.batch_sampler))
self.iterator = super().__iter__()
def __len__(self) -> int:
return len(self.batch_sampler.sampler)
def __iter__(self) -> Iterator:
for _ in range(len(self)):
yield next(self.iterator)
def __del__(self):
try:
if not hasattr(self.iterator, "_workers"):
return
for w in self.iterator._workers: # force terminate
if w.is_alive():
w.terminate()
self.iterator._shutdown_workers() # cleanup
except Exception:
pass
def reset(self):
self.iterator = self._get_iterator()
class _RepeatSampler:
def __init__(self, sampler: Any):
self.sampler = sampler
def __iter__(self) -> Iterator:
while True:
yield from iter(self.sampler)
class ContiguousDistributedSampler(torch.utils.data.Sampler):
def __init__(
self,
dataset: Dataset,
num_replicas: int | None = None,
batch_size: int | None = None,
rank: int | None = None,
shuffle: bool = False,
) -> None:
if num_replicas is None:
num_replicas = dist.get_world_size() if dist.is_initialized() else 1
if rank is None:
rank = dist.get_rank() if dist.is_initialized() else 0
if batch_size is None:
batch_size = getattr(dataset, "batch_size", 1)
self.num_replicas = num_replicas
self.rank = rank
self.epoch = 0
self.shuffle = shuffle
self.total_size = len(dataset)
# ensure all ranks have a sample if batch size >= total size; degenerates to round-robin sampler
self.batch_size = 1 if batch_size >= self.total_size else batch_size
self.num_batches = math.ceil(self.total_size / self.batch_size)
def _get_rank_indices(self) -> tuple[int, int]:
# Calculate which batches this rank handles
batches_per_rank_base = self.num_batches // self.num_replicas
remainder = self.num_batches % self.num_replicas
# This rank gets an extra batch if rank < remainder
batches_for_this_rank = batches_per_rank_base + (1 if self.rank < remainder else 0)
# Calculate starting batch: base position + number of extra batches given to earlier ranks
start_batch = self.rank * batches_per_rank_base + min(self.rank, remainder)
end_batch = start_batch + batches_for_this_rank
# Convert batch indices to sample indices
start_idx = start_batch * self.batch_size
end_idx = min(end_batch * self.batch_size, self.total_size)
return start_idx, end_idx
def __iter__(self) -> Iterator:
start_idx, end_idx = self._get_rank_indices()
indices = list(range(start_idx, end_idx))
if self.shuffle:
g = torch.Generator()
g.manual_seed(self.epoch)
indices = [indices[i] for i in torch.randperm(len(indices), generator=g).tolist()]
return iter(indices)
def __len__(self) -> int:
start_idx, end_idx = self._get_rank_indices()
return end_idx - start_idx
def set_epoch(self, epoch: int) -> None:
self.epoch = epoch
def seed_worker(worker_id: int) -> None:
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
def build_yolo_dataset(
cfg: IterableSimpleNamespace,
img_path: str,
batch: int,
data: dict[str, Any],
mode: str = "train",
rect: bool = False,
stride: int = 32,
multi_modal: bool = False,
) -> Dataset:
dataset = YOLOMultiModalDataset if multi_modal else YOLODataset
return dataset(
img_path=img_path,
imgsz=cfg.imgsz,
batch_size=batch,
augment=mode == "train", # augmentation
hyp=cfg, # TODO: probably add a get_hyps_from_cfg function
rect=cfg.rect or rect, # rectangular batches
cache=cfg.cache or None,
single_cls=cfg.single_cls or False,
stride=stride,
pad=0.0 if mode == "train" else 0.5,
prefix=colorstr(f"{mode}: "),
task=cfg.task,
classes=cfg.classes,
data=data,
fraction=cfg.fraction if mode == "train" else 1.0,
)
def build_grounding(
cfg: IterableSimpleNamespace,
img_path: str,
json_file: str,
batch: int,
mode: str = "train",
rect: bool = False,
stride: int = 32,
max_samples: int = 80,
) -> Dataset:
return GroundingDataset(
img_path=img_path,
json_file=json_file,
max_samples=max_samples,
imgsz=cfg.imgsz,
batch_size=batch,
augment=mode == "train", # augmentation
hyp=cfg, # TODO: probably add a get_hyps_from_cfg function
rect=cfg.rect or rect, # rectangular batches
cache=cfg.cache or None,
single_cls=cfg.single_cls or False,
stride=stride,
pad=0.0 if mode == "train" else 0.5,
prefix=colorstr(f"{mode}: "),
task=cfg.task,
classes=cfg.classes,
fraction=cfg.fraction if mode == "train" else 1.0,
)
def build_dataloader(
dataset,
batch: int,
workers: int,
shuffle: bool = True,
rank: int = -1,
drop_last: bool = False,
pin_memory: bool = True,
) -> InfiniteDataLoader:
batch = min(batch, len(dataset))
nd = torch.cuda.device_count() # number of CUDA devices
nw = min(os.cpu_count() // max(nd, 1), workers) # number of workers
sampler = (
None
if rank == -1
else distributed.DistributedSampler(dataset, shuffle=shuffle)
if shuffle
else ContiguousDistributedSampler(dataset)
)
generator = torch.Generator()
generator.manual_seed(6148914691236517205 + RANK)
return InfiniteDataLoader(
dataset=dataset,
batch_size=batch,
shuffle=shuffle and sampler is None,
num_workers=nw,
sampler=sampler,
prefetch_factor=4 if nw > 0 else None, # increase over default 2
pin_memory=nd > 0 and pin_memory,
collate_fn=getattr(dataset, "collate_fn", None),
worker_init_fn=seed_worker,
generator=generator,
drop_last=drop_last and len(dataset) % batch != 0,
)
def check_source(
source: str | int | Path | list | tuple | np.ndarray | Image.Image | torch.Tensor,
) -> tuple[Any, bool, bool, bool, bool, bool]:
webcam, screenshot, from_img, in_memory, tensor = False, False, False, False, False
if isinstance(source, (str, int, Path)): # int for local usb camera
source = str(source)
source_lower = source.lower()
is_url = source_lower.startswith(("https://", "http://", "rtsp://", "rtmp://", "tcp://"))
is_file = (urlsplit(source_lower).path if is_url else source_lower).rpartition(".")[-1] in (
IMG_FORMATS | VID_FORMATS
)
webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file)
screenshot = source_lower == "screen"
if is_url and is_file:
source = check_file(source) # download
elif isinstance(source, LOADERS):
in_memory = True
elif isinstance(source, (list, tuple)):
source = autocast_list(source) # convert all list elements to PIL or np arrays
from_img = True
elif isinstance(source, (Image.Image, np.ndarray)):
from_img = True
elif isinstance(source, torch.Tensor):
tensor = True
else:
raise TypeError("Unsupported image type. For supported types see https://docs.ultralytics.com/modes/predict")
return source, webcam, screenshot, from_img, in_memory, tensor
def load_inference_source(
source: str | int | Path | list | tuple | np.ndarray | Image.Image | torch.Tensor,
batch: int = 1,
vid_stride: int = 1,
buffer: bool = False,
channels: int = 3,
):
source, stream, screenshot, from_img, in_memory, tensor = check_source(source)
source_type = source.source_type if in_memory else SourceTypes(stream, screenshot, from_img, tensor)
# DataLoader
if tensor:
dataset = LoadTensor(source)
elif in_memory:
dataset = source
elif stream:
dataset = LoadStreams(source, vid_stride=vid_stride, buffer=buffer, channels=channels)
elif screenshot:
dataset = LoadScreenshots(source, channels=channels)
elif from_img:
dataset = LoadPilAndNumpy(source, channels=channels)
else:
dataset = LoadImagesAndVideos(source, batch=batch, vid_stride=vid_stride, channels=channels)
# Attach source types to the dataset
setattr(dataset, "source_type", source_type)
return dataset | --- +++ @@ -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 the dataset multiple times without recreating workers.
+
+ Attributes:
+ batch_sampler (_RepeatSampler): A sampler that repeats indefinitely.
+ iterator (Iterator): The iterator from the parent DataLoader.
+
+ Methods:
+ __len__: Return the length of the batch sampler's sampler.
+ __iter__: Yield batches from the underlying iterator.
+ __del__: Ensure workers are properly terminated.
+ reset: Reset the iterator, useful when modifying dataset settings during training.
+
+ Examples:
+ Create an infinite DataLoader for training
+ >>> dataset = YOLODataset(...)
+ >>> dataloader = InfiniteDataLoader(dataset, batch_size=16, shuffle=True)
+ >>> for batch in dataloader: # Infinite iteration
+ >>> train_step(batch)
+ """
def __init__(self, *args: Any, **kwargs: Any):
+ """Initialize the InfiniteDataLoader with the same arguments as DataLoader."""
if not TORCH_2_0:
kwargs.pop("prefetch_factor", None) # not supported by earlier versions
super().__init__(*args, **kwargs)
@@ -44,13 +67,16 @@ self.iterator = super().__iter__()
def __len__(self) -> int:
+ """Return the length of the batch sampler's sampler."""
return len(self.batch_sampler.sampler)
def __iter__(self) -> Iterator:
+ """Create an iterator that yields indefinitely from the underlying iterator."""
for _ in range(len(self)):
yield next(self.iterator)
def __del__(self):
+ """Ensure that workers are properly terminated when the DataLoader is deleted."""
try:
if not hasattr(self.iterator, "_workers"):
return
@@ -62,20 +88,61 @@ pass
def reset(self):
+ """Reset the iterator to allow modifications to the dataset during training."""
self.iterator = self._get_iterator()
class _RepeatSampler:
+ """Sampler that repeats forever for infinite iteration.
+
+ This sampler wraps another sampler and yields its contents indefinitely, allowing for infinite iteration over a
+ dataset without recreating the sampler.
+
+ Attributes:
+ sampler (torch.utils.data.Sampler): The sampler to repeat.
+ """
def __init__(self, sampler: Any):
+ """Initialize the _RepeatSampler with a sampler to repeat indefinitely."""
self.sampler = sampler
def __iter__(self) -> Iterator:
+ """Iterate over the sampler indefinitely, yielding its contents."""
while True:
yield from iter(self.sampler)
class ContiguousDistributedSampler(torch.utils.data.Sampler):
+ """Distributed sampler that assigns contiguous batch-aligned chunks of the dataset to each GPU.
+
+ Unlike PyTorch's DistributedSampler which distributes samples in a round-robin fashion (GPU 0 gets indices
+ [0,2,4,...], GPU 1 gets [1,3,5,...]), this sampler gives each GPU contiguous batches of the dataset (GPU 0 gets
+ batches [0,1,2,...], GPU 1 gets batches [k,k+1,...], etc.). This preserves any ordering or grouping in the original
+ dataset, which is critical when samples are organized by similarity (e.g., images sorted by size to enable efficient
+ batching without padding when using rect=True).
+
+ The sampler handles uneven batch counts by distributing remainder batches to the first few ranks, ensuring all
+ samples are covered exactly once across all GPUs.
+
+ Args:
+ dataset (Dataset): Dataset to sample from. Must implement __len__.
+ num_replicas (int, optional): Number of distributed processes. Defaults to world size.
+ batch_size (int, optional): Batch size used by dataloader. Defaults to dataset.batch_size or 1.
+ rank (int, optional): Rank of current process. Defaults to current rank.
+ shuffle (bool, optional): Whether to shuffle indices within each rank's chunk. Defaults to False. When True,
+ shuffling is deterministic and controlled by set_epoch() for reproducibility.
+
+ Examples:
+ >>> # For validation with size-grouped images
+ >>> sampler = ContiguousDistributedSampler(val_dataset, batch_size=32, shuffle=False)
+ >>> loader = DataLoader(val_dataset, batch_size=32, sampler=sampler)
+ >>> # For training with shuffling
+ >>> sampler = ContiguousDistributedSampler(train_dataset, batch_size=32, shuffle=True)
+ >>> for epoch in range(num_epochs):
+ ... sampler.set_epoch(epoch)
+ ... for batch in loader:
+ ... ...
+ """
def __init__(
self,
@@ -85,6 +152,7 @@ rank: int | None = None,
shuffle: bool = False,
) -> None:
+ """Initialize the sampler with dataset and distributed training parameters."""
if num_replicas is None:
num_replicas = dist.get_world_size() if dist.is_initialized() else 1
if rank is None:
@@ -102,6 +170,7 @@ self.num_batches = math.ceil(self.total_size / self.batch_size)
def _get_rank_indices(self) -> tuple[int, int]:
+ """Calculate the start and end sample indices for this rank."""
# Calculate which batches this rank handles
batches_per_rank_base = self.num_batches // self.num_replicas
remainder = self.num_batches % self.num_replicas
@@ -120,6 +189,7 @@ return start_idx, end_idx
def __iter__(self) -> Iterator:
+ """Generate indices for this rank's contiguous chunk of the dataset."""
start_idx, end_idx = self._get_rank_indices()
indices = list(range(start_idx, end_idx))
@@ -131,14 +201,21 @@ return iter(indices)
def __len__(self) -> int:
+ """Return the number of samples in this rank's chunk."""
start_idx, end_idx = self._get_rank_indices()
return end_idx - start_idx
def set_epoch(self, epoch: int) -> None:
+ """Set the epoch for this sampler to ensure different shuffling patterns across epochs.
+
+ Args:
+ epoch (int): Epoch number to use as the random seed for shuffling.
+ """
self.epoch = epoch
def seed_worker(worker_id: int) -> None:
+ """Set dataloader worker seed for reproducibility across worker processes."""
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
@@ -154,6 +231,7 @@ stride: int = 32,
multi_modal: bool = False,
) -> Dataset:
+ """Build and return a YOLO dataset based on configuration parameters."""
dataset = YOLOMultiModalDataset if multi_modal else YOLODataset
return dataset(
img_path=img_path,
@@ -184,6 +262,7 @@ stride: int = 32,
max_samples: int = 80,
) -> Dataset:
+ """Build and return a GroundingDataset based on configuration parameters."""
return GroundingDataset(
img_path=img_path,
json_file=json_file,
@@ -213,6 +292,25 @@ drop_last: bool = False,
pin_memory: bool = True,
) -> InfiniteDataLoader:
+ """Create and return an InfiniteDataLoader for training or validation.
+
+ Args:
+ dataset (Dataset): Dataset to load data from.
+ batch (int): Batch size for the dataloader.
+ workers (int): Number of worker processes for data loading.
+ shuffle (bool, optional): Whether to shuffle the dataset.
+ rank (int, optional): Process rank in distributed training. -1 for single-GPU training.
+ drop_last (bool, optional): Whether to drop the last incomplete batch.
+ pin_memory (bool, optional): Whether to use pinned memory for dataloader.
+
+ Returns:
+ (InfiniteDataLoader): A dataloader that can be used for training or validation.
+
+ Examples:
+ Create a dataloader for training
+ >>> dataset = YOLODataset(...)
+ >>> dataloader = build_dataloader(dataset, batch=16, workers=4, shuffle=True)
+ """
batch = min(batch, len(dataset))
nd = torch.cuda.device_count() # number of CUDA devices
nw = min(os.cpu_count() // max(nd, 1), workers) # number of workers
@@ -243,6 +341,26 @@ def check_source(
source: str | int | Path | list | tuple | np.ndarray | Image.Image | torch.Tensor,
) -> tuple[Any, bool, bool, bool, bool, bool]:
+ """Check the type of input source and return corresponding flag values.
+
+ Args:
+ source (str | int | Path | list | tuple | np.ndarray | PIL.Image | torch.Tensor): The input source to check.
+
+ Returns:
+ source (str | int | Path | list | tuple | np.ndarray | PIL.Image | torch.Tensor): The processed source.
+ webcam (bool): Whether the source is a webcam.
+ screenshot (bool): Whether the source is a screenshot.
+ from_img (bool): Whether the source is an image or list of images.
+ in_memory (bool): Whether the source is an in-memory object.
+ tensor (bool): Whether the source is a torch.Tensor.
+
+ Examples:
+ Check a file path source
+ >>> source, webcam, screenshot, from_img, in_memory, tensor = check_source("image.jpg")
+
+ Check a webcam source
+ >>> source, webcam, screenshot, from_img, in_memory, tensor = check_source(0)
+ """
webcam, screenshot, from_img, in_memory, tensor = False, False, False, False, False
if isinstance(source, (str, int, Path)): # int for local usb camera
source = str(source)
@@ -277,6 +395,26 @@ buffer: bool = False,
channels: int = 3,
):
+ """Load an inference source for object detection and apply necessary transformations.
+
+ Args:
+ source (str | int | Path | list | tuple | np.ndarray | PIL.Image | torch.Tensor): The input source for
+ inference.
+ batch (int, optional): Batch size for dataloaders.
+ vid_stride (int, optional): The frame interval for video sources.
+ buffer (bool, optional): Whether stream frames will be buffered.
+ channels (int, optional): The number of input channels for the model.
+
+ Returns:
+ (Dataset): A dataset object for the specified input source with attached source_type attribute.
+
+ Examples:
+ Load an image source for inference
+ >>> dataset = load_inference_source("image.jpg", batch=1)
+
+ Load a video stream source
+ >>> dataset = load_inference_source("rtsp://example.com/stream", vid_stride=2)
+ """
source, stream, screenshot, from_img, in_memory, tensor = check_source(source)
source_type = source.source_type if in_memory else SourceTypes(stream, screenshot, from_img, tensor)
@@ -297,4 +435,4 @@ # Attach source types to the dataset
setattr(dataset, "source_type", source_type)
- return dataset+ return dataset
| 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.data import load_inference_source
from ultralytics.data.augment import LetterBox
from ultralytics.nn.autobackend import AutoBackend
from ultralytics.utils import DEFAULT_CFG, LOGGER, MACOS, WINDOWS, callbacks, colorstr, ops
from ultralytics.utils.checks import check_imgsz, check_imshow
from ultralytics.utils.files import increment_path
from ultralytics.utils.torch_utils import attempt_compile, select_device, smart_inference_mode
STREAM_WARNING = """
Inference results will accumulate in RAM unless `stream=True` is passed, which can cause out-of-memory errors for large
sources or long-running streams and videos. See https://docs.ultralytics.com/modes/predict/ for help.
Example:
results = model(source=..., stream=True) # generator of Results objects
for r in results:
boxes = r.boxes # Boxes object for bbox outputs
masks = r.masks # Masks object for segment masks outputs
probs = r.probs # Class probabilities for classification outputs
"""
class BasePredictor:
def __init__(
self,
cfg=DEFAULT_CFG,
overrides: dict[str, Any] | None = None,
_callbacks: dict | None = None,
):
self.args = get_cfg(cfg, overrides)
self.save_dir = get_save_dir(self.args)
if self.args.conf is None:
self.args.conf = 0.25 # default conf=0.25
self.done_warmup = False
if self.args.show:
self.args.show = check_imshow(warn=True)
# Usable if setup is done
self.model = None
self.data = self.args.data # data_dict
self.imgsz = None
self.device = None
self.dataset = None
self.vid_writer = {} # dict of {save_path: video_writer, ...}
self.plotted_img = None
self.source_type = None
self.seen = 0
self.windows = []
self.batch = None
self.results = None
self.transforms = None
self.callbacks = _callbacks or callbacks.get_default_callbacks()
self.txt_path = None
self._lock = threading.Lock() # for automatic thread-safe inference
callbacks.add_integration_callbacks(self)
def preprocess(self, im: torch.Tensor | list[np.ndarray]) -> torch.Tensor:
not_tensor = not isinstance(im, torch.Tensor)
if not_tensor:
im = np.stack(self.pre_transform(im))
if im.shape[-1] == 3:
im = im[..., ::-1] # BGR to RGB
im = im.transpose((0, 3, 1, 2)) # BHWC to BCHW, (n, 3, h, w)
im = np.ascontiguousarray(im) # contiguous
im = torch.from_numpy(im)
im = im.to(self.device)
im = im.half() if self.model.fp16 else im.float() # uint8 to fp16/32
if not_tensor:
im /= 255 # 0 - 255 to 0.0 - 1.0
return im
def inference(self, im: torch.Tensor, *args, **kwargs):
visualize = (
increment_path(self.save_dir / Path(self.batch[0][0]).stem, mkdir=True)
if self.args.visualize and (not self.source_type.tensor)
else False
)
return self.model(im, augment=self.args.augment, visualize=visualize, embed=self.args.embed, *args, **kwargs)
def pre_transform(self, im: list[np.ndarray]) -> list[np.ndarray]:
same_shapes = len({x.shape for x in im}) == 1
letterbox = LetterBox(
self.imgsz,
auto=same_shapes
and self.args.rect
and (self.model.format == "pt" or (getattr(self.model, "dynamic", False) and self.model.format != "imx")),
stride=self.model.stride,
)
return [letterbox(image=x) for x in im]
def postprocess(self, preds, img, orig_imgs):
return preds
def __call__(self, source=None, model=None, stream: bool = False, *args, **kwargs):
self.stream = stream
if stream:
return self.stream_inference(source, model, *args, **kwargs)
else:
return list(self.stream_inference(source, model, *args, **kwargs)) # merge list of Results into one
def predict_cli(self, source=None, model=None):
gen = self.stream_inference(source, model)
for _ in gen: # sourcery skip: remove-empty-nested-block, noqa
pass
def setup_source(self, source, stride: int | None = None):
self.imgsz = check_imgsz(self.args.imgsz, stride=stride or self.model.stride, min_dim=2) # check image size
self.dataset = load_inference_source(
source=source,
batch=self.args.batch,
vid_stride=self.args.vid_stride,
buffer=self.args.stream_buffer,
channels=getattr(self.model, "channels", 3),
)
self.source_type = self.dataset.source_type
if (
self.source_type.stream
or self.source_type.screenshot
or len(self.dataset) > 1000 # many images
or any(getattr(self.dataset, "video_flag", [False]))
): # long sequence
import torchvision # noqa (import here triggers torchvision NMS use in nms.py)
if not getattr(self, "stream", True): # videos
LOGGER.warning(STREAM_WARNING)
self.vid_writer = {}
@smart_inference_mode()
def stream_inference(self, source=None, model=None, *args, **kwargs):
if self.args.verbose:
LOGGER.info("")
# Setup model
if not self.model:
self.setup_model(model)
with self._lock: # for thread-safe inference
# Setup source every time predict is called
self.setup_source(source if source is not None else self.args.source)
# Check if save_dir/ label file exists
if self.args.save or self.args.save_txt:
(self.save_dir / "labels" if self.args.save_txt else self.save_dir).mkdir(parents=True, exist_ok=True)
# Warmup model
if not self.done_warmup:
self.model.warmup(
imgsz=(
1 if self.model.format in {"pt", "triton"} else self.dataset.bs,
self.model.channels,
*self.imgsz,
)
)
self.done_warmup = True
self.seen, self.windows, self.batch = 0, [], None
profilers = (
ops.Profile(device=self.device),
ops.Profile(device=self.device),
ops.Profile(device=self.device),
)
self.run_callbacks("on_predict_start")
for batch in self.dataset:
self.batch = batch
self.run_callbacks("on_predict_batch_start")
paths, im0s, s = self.batch
# Preprocess
with profilers[0]:
im = self.preprocess(im0s)
# Inference
with profilers[1]:
preds = self.inference(im, *args, **kwargs)
if self.args.embed:
yield from [preds] if isinstance(preds, torch.Tensor) else preds # yield embedding tensors
continue
# Postprocess
with profilers[2]:
self.results = self.postprocess(preds, im, im0s)
self.run_callbacks("on_predict_postprocess_end")
# Visualize, save, write results
n = len(im0s)
try:
for i in range(n):
self.seen += 1
self.results[i].speed = {
"preprocess": profilers[0].dt * 1e3 / n,
"inference": profilers[1].dt * 1e3 / n,
"postprocess": profilers[2].dt * 1e3 / n,
}
if self.args.verbose or self.args.save or self.args.save_txt or self.args.show:
s[i] += self.write_results(i, Path(paths[i]), im, s)
except StopIteration:
break
# Print batch results
if self.args.verbose:
LOGGER.info("\n".join(s))
self.run_callbacks("on_predict_batch_end")
yield from self.results
# Release assets
for v in self.vid_writer.values():
if isinstance(v, cv2.VideoWriter):
v.release()
if self.args.show:
cv2.destroyAllWindows() # close any open windows
# Print final results
if self.args.verbose and self.seen:
t = tuple(x.t / self.seen * 1e3 for x in profilers) # speeds per image
LOGGER.info(
f"Speed: %.1fms preprocess, %.1fms inference, %.1fms postprocess per image at shape "
f"{(min(self.args.batch, self.seen), getattr(self.model, 'channels', 3), *im.shape[2:])}" % t
)
if self.args.save or self.args.save_txt or self.args.save_crop:
nl = len(list(self.save_dir.glob("labels/*.txt"))) # number of labels
s = f"\n{nl} label{'s' * (nl > 1)} saved to {self.save_dir / 'labels'}" if self.args.save_txt else ""
LOGGER.info(f"Results saved to {colorstr('bold', self.save_dir)}{s}")
self.run_callbacks("on_predict_end")
def setup_model(self, model, verbose: bool = True):
if hasattr(model, "end2end"):
if self.args.end2end is not None:
model.end2end = self.args.end2end
if model.end2end:
model.set_head_attr(max_det=self.args.max_det, agnostic_nms=self.args.agnostic_nms)
self.model = AutoBackend(
model=model or self.args.model,
device=select_device(self.args.device, verbose=verbose),
dnn=self.args.dnn,
data=self.args.data,
fp16=self.args.half,
fuse=True,
verbose=verbose,
)
self.device = self.model.device # update device
self.args.half = self.model.fp16 # update half
if hasattr(self.model, "imgsz") and not getattr(self.model, "dynamic", False):
self.args.imgsz = self.model.imgsz # reuse imgsz from export metadata
self.model.eval()
self.model = attempt_compile(self.model, device=self.device, mode=self.args.compile)
def write_results(self, i: int, p: Path, im: torch.Tensor, s: list[str]) -> str:
string = "" # print string
if len(im.shape) == 3:
im = im[None] # expand for batch dim
if self.source_type.stream or self.source_type.from_img or self.source_type.tensor: # batch_size >= 1
string += f"{i}: "
frame = self.dataset.count
else:
match = re.search(r"frame (\d+)/", s[i])
frame = int(match[1]) if match else None # 0 if frame undetermined
self.txt_path = self.save_dir / "labels" / (p.stem + ("" if self.dataset.mode == "image" else f"_{frame}"))
string += "{:g}x{:g} ".format(*im.shape[2:])
result = self.results[i]
result.save_dir = self.save_dir.__str__() # used in other locations
string += f"{result.verbose()}{result.speed['inference']:.1f}ms"
# Add predictions to image
if self.args.save or self.args.show:
self.plotted_img = result.plot(
line_width=self.args.line_width,
boxes=self.args.show_boxes,
conf=self.args.show_conf,
labels=self.args.show_labels,
im_gpu=None if self.args.retina_masks else im[i],
)
# Save results
if self.args.save_txt:
result.save_txt(f"{self.txt_path}.txt", save_conf=self.args.save_conf)
if self.args.save_crop:
result.save_crop(save_dir=self.save_dir / "crops", file_name=self.txt_path.stem)
if self.args.show:
self.show(str(p))
if self.args.save:
self.save_predicted_images(self.save_dir / p.name, frame)
return string
def save_predicted_images(self, save_path: Path, frame: int = 0):
im = self.plotted_img
# Save videos and streams
if self.dataset.mode in {"stream", "video"}:
fps = self.dataset.fps if self.dataset.mode == "video" else 30
frames_path = self.save_dir / f"{save_path.stem}_frames" # save frames to a separate directory
if save_path not in self.vid_writer: # new video
if self.args.save_frames:
Path(frames_path).mkdir(parents=True, exist_ok=True)
suffix, fourcc = (".mp4", "avc1") if MACOS else (".avi", "WMV2") if WINDOWS else (".avi", "MJPG")
self.vid_writer[save_path] = cv2.VideoWriter(
filename=str(Path(save_path).with_suffix(suffix)),
fourcc=cv2.VideoWriter_fourcc(*fourcc),
fps=fps, # integer required, floats produce error in MP4 codec
frameSize=(im.shape[1], im.shape[0]), # (width, height)
)
# Save video
self.vid_writer[save_path].write(im)
if self.args.save_frames:
cv2.imwrite(f"{frames_path}/{save_path.stem}_{frame}.jpg", im)
# Save images
else:
cv2.imwrite(str(save_path.with_suffix(".jpg")), im) # save to JPG for best support
def show(self, p: str = ""):
im = self.plotted_img
if platform.system() == "Linux" and p not in self.windows:
self.windows.append(p)
cv2.namedWindow(p, cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
cv2.resizeWindow(p, im.shape[1], im.shape[0]) # (width, height)
cv2.imshow(p, im)
if cv2.waitKey(300 if self.dataset.mode == "image" else 1) & 0xFF == ord("q"): # 300ms if image; else 1ms
raise StopIteration
def run_callbacks(self, event: str):
for callback in self.callbacks.get(event, []):
callback(self)
def add_callback(self, event: str, func: Callable):
self.callbacks[event].append(func) | --- +++ @@ -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
+ img.jpg # image
+ vid.mp4 # video
+ screen # screenshot
+ path/ # directory
+ list.txt # list of images
+ list.streams # list of streams
+ 'path/*.jpg' # glob
+ 'https://youtu.be/LNwODJXcvt4' # YouTube
+ 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP, TCP stream
+
+Usage - formats:
+ $ yolo mode=predict model=yolo26n.pt # PyTorch
+ yolo26n.torchscript # TorchScript
+ yolo26n.onnx # ONNX Runtime or OpenCV DNN with dnn=True
+ yolo26n_openvino_model # OpenVINO
+ yolo26n.engine # TensorRT
+ yolo26n.mlpackage # CoreML (macOS-only)
+ yolo26n_saved_model # TensorFlow SavedModel
+ yolo26n.pb # TensorFlow GraphDef
+ yolo26n.tflite # TensorFlow Lite
+ yolo26n_edgetpu.tflite # TensorFlow Edge TPU
+ yolo26n_paddle_model # PaddlePaddle
+ yolo26n.mnn # MNN
+ yolo26n_ncnn_model # NCNN
+ yolo26n_imx_model # Sony IMX
+ yolo26n_rknn_model # Rockchip RKNN
+ yolo26n.pte # PyTorch Executorch
+"""
from __future__ import annotations
@@ -35,6 +68,45 @@
class BasePredictor:
+ """A base class for creating predictors.
+
+ This class provides the foundation for prediction functionality, handling model setup, inference, and result
+ processing across various input sources.
+
+ Attributes:
+ args (SimpleNamespace): Configuration for the predictor.
+ save_dir (Path): Directory to save results.
+ done_warmup (bool): Whether the predictor has finished setup.
+ model (torch.nn.Module): Model used for prediction.
+ data (str): Data configuration.
+ device (torch.device): Device used for prediction.
+ dataset (Dataset): Dataset used for prediction.
+ vid_writer (dict[Path, cv2.VideoWriter]): Dictionary of {save_path: video_writer} for saving video output.
+ plotted_img (np.ndarray): Last plotted image.
+ source_type (SimpleNamespace): Type of input source.
+ seen (int): Number of images processed.
+ windows (list[str]): List of window names for visualization.
+ batch (tuple): Current batch data.
+ results (list[Any]): Current batch results.
+ transforms (Callable): Image transforms for classification.
+ callbacks (dict[str, list[Callable]]): Callback functions for different events.
+ txt_path (Path): Path to save text results.
+ _lock (threading.Lock): Lock for thread-safe inference.
+
+ Methods:
+ preprocess: Prepare input image before inference.
+ inference: Run inference on a given image.
+ postprocess: Process raw predictions into structured results.
+ predict_cli: Run prediction for command line interface.
+ setup_source: Set up input source and inference mode.
+ stream_inference: Stream inference on input source.
+ setup_model: Initialize and configure the model.
+ write_results: Write inference results to files.
+ save_predicted_images: Save prediction visualizations.
+ show: Display results in a window.
+ run_callbacks: Execute registered callbacks for an event.
+ add_callback: Register a new callback function.
+ """
def __init__(
self,
@@ -42,6 +114,13 @@ overrides: dict[str, Any] | None = None,
_callbacks: dict | None = None,
):
+ """Initialize the BasePredictor class.
+
+ Args:
+ cfg (str | Path | dict | SimpleNamespace): Path to a configuration file or a configuration dictionary.
+ overrides (dict, optional): Configuration overrides.
+ _callbacks (dict, optional): Dictionary of callback functions.
+ """
self.args = get_cfg(cfg, overrides)
self.save_dir = get_save_dir(self.args)
if self.args.conf is None:
@@ -70,6 +149,14 @@ callbacks.add_integration_callbacks(self)
def preprocess(self, im: torch.Tensor | list[np.ndarray]) -> torch.Tensor:
+ """Prepare input image before inference.
+
+ Args:
+ im (torch.Tensor | list[np.ndarray]): Images of shape (N, 3, H, W) for tensor, [(H, W, 3) x N] for list.
+
+ Returns:
+ (torch.Tensor): Preprocessed image tensor of shape (N, 3, H, W).
+ """
not_tensor = not isinstance(im, torch.Tensor)
if not_tensor:
im = np.stack(self.pre_transform(im))
@@ -86,6 +173,7 @@ return im
def inference(self, im: torch.Tensor, *args, **kwargs):
+ """Run inference on a given image using the specified model and arguments."""
visualize = (
increment_path(self.save_dir / Path(self.batch[0][0]).stem, mkdir=True)
if self.args.visualize and (not self.source_type.tensor)
@@ -94,6 +182,14 @@ return self.model(im, augment=self.args.augment, visualize=visualize, embed=self.args.embed, *args, **kwargs)
def pre_transform(self, im: list[np.ndarray]) -> list[np.ndarray]:
+ """Pre-transform input image before inference.
+
+ Args:
+ im (list[np.ndarray]): List of images with shape [(H, W, 3) x N].
+
+ Returns:
+ (list[np.ndarray]): List of transformed images.
+ """
same_shapes = len({x.shape for x in im}) == 1
letterbox = LetterBox(
self.imgsz,
@@ -105,9 +201,23 @@ return [letterbox(image=x) for x in im]
def postprocess(self, preds, img, orig_imgs):
+ """Post-process predictions for an image and return them."""
return preds
def __call__(self, source=None, model=None, stream: bool = False, *args, **kwargs):
+ """Perform inference on an image or stream.
+
+ Args:
+ source (str | Path | list[str] | list[Path] | list[np.ndarray] | np.ndarray | torch.Tensor, optional):
+ Source for inference.
+ model (str | Path | torch.nn.Module, optional): Model for inference.
+ stream (bool): Whether to stream the inference results. If True, returns a generator.
+ *args (Any): Additional arguments for the inference method.
+ **kwargs (Any): Additional keyword arguments for the inference method.
+
+ Returns:
+ (list[ultralytics.engine.results.Results] | generator): Results objects or generator of Results objects.
+ """
self.stream = stream
if stream:
return self.stream_inference(source, model, *args, **kwargs)
@@ -115,11 +225,33 @@ return list(self.stream_inference(source, model, *args, **kwargs)) # merge list of Results into one
def predict_cli(self, source=None, model=None):
+ """Method used for Command Line Interface (CLI) prediction.
+
+ This function is designed to run predictions using the CLI. It sets up the source and model, then processes the
+ inputs in a streaming manner. This method ensures that no outputs accumulate in memory by consuming the
+ generator without storing results.
+
+ Args:
+ source (str | Path | list[str] | list[Path] | list[np.ndarray] | np.ndarray | torch.Tensor, optional):
+ Source for inference.
+ model (str | Path | torch.nn.Module, optional): Model for inference.
+
+ Notes:
+ Do not modify this function or remove the generator. The generator ensures that no outputs are
+ accumulated in memory, which is critical for preventing memory issues during long-running predictions.
+ """
gen = self.stream_inference(source, model)
for _ in gen: # sourcery skip: remove-empty-nested-block, noqa
pass
def setup_source(self, source, stride: int | None = None):
+ """Set up source and inference mode.
+
+ Args:
+ source (str | Path | list[str] | list[Path] | list[np.ndarray] | np.ndarray | torch.Tensor): Source for
+ inference.
+ stride (int, optional): Model stride for image size checking.
+ """
self.imgsz = check_imgsz(self.args.imgsz, stride=stride or self.model.stride, min_dim=2) # check image size
self.dataset = load_inference_source(
source=source,
@@ -143,6 +275,18 @@
@smart_inference_mode()
def stream_inference(self, source=None, model=None, *args, **kwargs):
+ """Stream inference on input source and save results to file.
+
+ Args:
+ source (str | Path | list[str] | list[Path] | list[np.ndarray] | np.ndarray | torch.Tensor, optional):
+ Source for inference.
+ model (str | Path | torch.nn.Module, optional): Model for inference.
+ *args (Any): Additional arguments for the inference method.
+ **kwargs (Any): Additional keyword arguments for the inference method.
+
+ Yields:
+ (ultralytics.engine.results.Results): Results objects.
+ """
if self.args.verbose:
LOGGER.info("")
@@ -241,6 +385,12 @@ self.run_callbacks("on_predict_end")
def setup_model(self, model, verbose: bool = True):
+ """Initialize YOLO model with given parameters and set it to evaluation mode.
+
+ Args:
+ model (str | Path | torch.nn.Module): Model to load or use.
+ verbose (bool): Whether to print verbose output.
+ """
if hasattr(model, "end2end"):
if self.args.end2end is not None:
model.end2end = self.args.end2end
@@ -264,6 +414,17 @@ self.model = attempt_compile(self.model, device=self.device, mode=self.args.compile)
def write_results(self, i: int, p: Path, im: torch.Tensor, s: list[str]) -> str:
+ """Write inference results to a file or directory.
+
+ Args:
+ i (int): Index of the current image in the batch.
+ p (Path): Path to the current image.
+ im (torch.Tensor): Preprocessed image tensor.
+ s (list[str]): List of result strings.
+
+ Returns:
+ (str): String with result information.
+ """
string = "" # print string
if len(im.shape) == 3:
im = im[None] # expand for batch dim
@@ -303,6 +464,12 @@ return string
def save_predicted_images(self, save_path: Path, frame: int = 0):
+ """Save video predictions as mp4/avi or images as jpg at specified path.
+
+ Args:
+ save_path (Path): Path to save the results.
+ frame (int): Frame number for video mode.
+ """
im = self.plotted_img
# Save videos and streams
@@ -330,6 +497,7 @@ cv2.imwrite(str(save_path.with_suffix(".jpg")), im) # save to JPG for best support
def show(self, p: str = ""):
+ """Display an image in a window."""
im = self.plotted_img
if platform.system() == "Linux" and p not in self.windows:
self.windows.append(p)
@@ -340,8 +508,10 @@ raise StopIteration
def run_callbacks(self, event: str):
+ """Run all registered callbacks for a specific event."""
for callback in self.callbacks.get(event, []):
callback(self)
def add_callback(self, event: str, func: Callable):
- self.callbacks[event].append(func)+ """Add a callback function for a specific event."""
+ self.callbacks[event].append(func)
| 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 ultralytics.hub.utils import HELP_MSG, HUB_WEB_ROOT, PREFIX
from ultralytics.utils import IS_COLAB, LOGGER, SETTINGS, TQDM, checks
from ultralytics.utils.errors import HUBModelError
AGENT_NAME = f"python-{__version__}-colab" if IS_COLAB else f"python-{__version__}-local"
class HUBTrainingSession:
def __init__(self, identifier: str):
from hub_sdk import HUBClient
self.rate_limits = {"metrics": 3, "ckpt": 900, "heartbeat": 300} # rate limits (seconds)
self.metrics_queue = {} # holds metrics for each epoch until upload
self.metrics_upload_failed_queue = {} # holds metrics for each epoch if upload failed
self.timers = {} # holds timers in ultralytics/utils/callbacks/hub.py
self.model = None
self.model_url = None
self.model_file = None
self.train_args = None
# Parse input
api_key, model_id, self.filename = self._parse_identifier(identifier)
# Get credentials
active_key = api_key or SETTINGS.get("api_key")
credentials = {"api_key": active_key} if active_key else None # set credentials
# Initialize client
self.client = HUBClient(credentials)
# Load models
try:
if model_id:
self.load_model(model_id) # load existing model
else:
self.model = self.client.model() # load empty model
except Exception:
if identifier.startswith(f"{HUB_WEB_ROOT}/models/") and not self.client.authenticated:
LOGGER.warning(
f"{PREFIX}Please log in using 'yolo login API_KEY'. "
"You can find your API Key at: https://hub.ultralytics.com/settings?tab=api+keys."
)
@classmethod
def create_session(cls, identifier: str, args: dict[str, Any] | None = None):
try:
session = cls(identifier)
if args and not identifier.startswith(f"{HUB_WEB_ROOT}/models/"): # not a HUB model URL
session.create_model(args)
assert session.model.id, "HUB model not loaded correctly"
return session
# PermissionError and ModuleNotFoundError indicate hub-sdk not installed
except (PermissionError, ModuleNotFoundError, AssertionError):
return None
def load_model(self, model_id: str):
self.model = self.client.model(model_id)
if not self.model.data: # then model does not exist
raise HUBModelError(f"❌ Model not found: '{model_id}'. Verify the model ID is correct.")
self.model_url = f"{HUB_WEB_ROOT}/models/{self.model.id}"
if self.model.is_trained():
LOGGER.info(f"Loading trained HUB model {self.model_url} 🚀")
url = self.model.get_weights_url("best") # download URL with auth
self.model_file = checks.check_file(url, download_dir=Path(SETTINGS["weights_dir"]) / "hub" / self.model.id)
return
# Set training args and start heartbeats for HUB to monitor agent
self._set_train_args()
self.model.start_heartbeat(self.rate_limits["heartbeat"])
LOGGER.info(f"{PREFIX}View model at {self.model_url} 🚀")
def create_model(self, model_args: dict[str, Any]):
payload = {
"config": {
"batchSize": model_args.get("batch", -1),
"epochs": model_args.get("epochs", 300),
"imageSize": model_args.get("imgsz", 640),
"patience": model_args.get("patience", 100),
"device": str(model_args.get("device", "")), # convert None to string
"cache": str(model_args.get("cache", "ram")), # convert True, False, None to string
},
"dataset": {"name": model_args.get("data")},
"lineage": {
"architecture": {"name": self.filename.replace(".pt", "").replace(".yaml", "")},
"parent": {},
},
"meta": {"name": self.filename},
}
if self.filename.endswith(".pt"):
payload["lineage"]["parent"]["name"] = self.filename
self.model.create_model(payload)
if not self.model.id:
raise HUBModelError(f"❌ Failed to create model '{self.filename}' on Ultralytics HUB. Please try again.")
self.model_url = f"{HUB_WEB_ROOT}/models/{self.model.id}"
# Start heartbeats for HUB to monitor agent
self.model.start_heartbeat(self.rate_limits["heartbeat"])
LOGGER.info(f"{PREFIX}View model at {self.model_url} 🚀")
@staticmethod
def _parse_identifier(identifier: str):
api_key, model_id, filename = None, None, None
if identifier.endswith((".pt", ".yaml")):
filename = identifier
elif identifier.startswith(f"{HUB_WEB_ROOT}/models/"):
parsed_url = urlparse(identifier)
model_id = Path(parsed_url.path).stem # handle possible final backslash robustly
query_params = parse_qs(parsed_url.query) # dictionary, i.e. {"api_key": ["API_KEY_HERE"]}
api_key = query_params.get("api_key", [None])[0]
else:
raise HUBModelError(f"model='{identifier} invalid, correct format is {HUB_WEB_ROOT}/models/MODEL_ID")
return api_key, model_id, filename
def _set_train_args(self):
if self.model.is_resumable():
# Model has saved weights
self.train_args = {"data": self.model.get_dataset_url(), "resume": True}
self.model_file = self.model.get_weights_url("last")
else:
# Model has no saved weights
self.train_args = self.model.data.get("train_args") # new response
# Set the model file as either a *.pt or *.yaml file
self.model_file = (
self.model.get_weights_url("parent") if self.model.is_pretrained() else self.model.get_architecture()
)
if "data" not in self.train_args:
# RF bug - datasets are sometimes not exported
raise ValueError("Dataset may still be processing. Please wait a minute and try again.")
self.model_file = checks.check_yolov5u_filename(self.model_file, verbose=False) # YOLOv5->YOLOv5u
self.model_id = self.model.id
def request_queue(
self,
request_func,
retry: int = 3,
timeout: int = 30,
thread: bool = True,
verbose: bool = True,
progress_total: int | None = None,
stream_response: bool | None = None,
*args,
**kwargs,
):
def retry_request():
t0 = time.time() # Record the start time for the timeout
response = None
for i in range(retry + 1):
if (time.time() - t0) > timeout:
LOGGER.warning(f"{PREFIX}Timeout for request reached. {HELP_MSG}")
break # Timeout reached, exit loop
response = request_func(*args, **kwargs)
if response is None:
LOGGER.warning(f"{PREFIX}Received no response from the request. {HELP_MSG}")
time.sleep(2**i) # Exponential backoff before retrying
continue # Skip further processing and retry
if progress_total:
self._show_upload_progress(progress_total, response)
elif stream_response:
self._iterate_content(response)
if HTTPStatus.OK <= response.status_code < HTTPStatus.MULTIPLE_CHOICES:
# if request related to metrics upload
if kwargs.get("metrics"):
self.metrics_upload_failed_queue = {}
return response # Success, no need to retry
if i == 0:
# Initial attempt, check status code and provide messages
message = self._get_failure_message(response, retry, timeout)
if verbose:
LOGGER.warning(f"{PREFIX}{message} {HELP_MSG} ({response.status_code})")
if not self._should_retry(response.status_code):
LOGGER.warning(f"{PREFIX}Request failed. {HELP_MSG} ({response.status_code}")
break # Not an error that should be retried, exit loop
time.sleep(2**i) # Exponential backoff for retries
# if request related to metrics upload and exceed retries
if response is None and kwargs.get("metrics"):
self.metrics_upload_failed_queue.update(kwargs.get("metrics"))
return response
if thread:
# Start a new thread to run the retry_request function
threading.Thread(target=retry_request, daemon=True).start()
else:
# If running in the main thread, call retry_request directly
return retry_request()
@staticmethod
def _should_retry(status_code: int) -> bool:
retry_codes = {
HTTPStatus.REQUEST_TIMEOUT,
HTTPStatus.BAD_GATEWAY,
HTTPStatus.GATEWAY_TIMEOUT,
}
return status_code in retry_codes
def _get_failure_message(self, response, retry: int, timeout: int) -> str:
if self._should_retry(response.status_code):
return f"Retrying {retry}x for {timeout}s." if retry else ""
elif response.status_code == HTTPStatus.TOO_MANY_REQUESTS: # rate limit
headers = response.headers
return (
f"Rate limit reached ({headers['X-RateLimit-Remaining']}/{headers['X-RateLimit-Limit']}). "
f"Please retry after {headers['Retry-After']}s."
)
else:
try:
return response.json().get("message", "No JSON message.")
except AttributeError:
return "Unable to read JSON."
def upload_metrics(self):
return self.request_queue(self.model.upload_metrics, metrics=self.metrics_queue.copy(), thread=True)
def upload_model(
self,
epoch: int,
weights: str,
is_best: bool = False,
map: float = 0.0,
final: bool = False,
) -> None:
weights = Path(weights)
if not weights.is_file():
last = weights.with_name(f"last{weights.suffix}")
if final and last.is_file():
LOGGER.warning(
f"{PREFIX} Model 'best.pt' not found, copying 'last.pt' to 'best.pt' and uploading. "
"This often happens when resuming training in transient environments like Google Colab. "
"For more reliable training, consider using Ultralytics HUB Cloud. "
"Learn more at https://docs.ultralytics.com/hub/cloud-training."
)
shutil.copy(last, weights) # copy last.pt to best.pt
else:
LOGGER.warning(f"{PREFIX} Model upload issue. Missing model {weights}.")
return
self.request_queue(
self.model.upload_model,
epoch=epoch,
weights=str(weights),
is_best=is_best,
map=map,
final=final,
retry=10,
timeout=3600,
thread=not final,
progress_total=weights.stat().st_size if final else None, # only show progress if final
stream_response=True,
)
@staticmethod
def _show_upload_progress(content_length: int, response) -> None:
with TQDM(total=content_length, unit="B", unit_scale=True, unit_divisor=1024) as pbar:
for data in response.iter_content(chunk_size=1024):
pbar.update(len(data))
@staticmethod
def _iterate_content(response) -> None:
for _ in response.iter_content(chunk_size=1024):
pass # Do nothing with data chunks | --- +++ @@ -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:
+ model_id (str): Identifier for the YOLO model being trained.
+ model_url (str): URL for the model in Ultralytics HUB.
+ rate_limits (dict[str, int]): Rate limits for different API calls in seconds.
+ timers (dict[str, Any]): Timers for rate limiting.
+ metrics_queue (dict[str, Any]): Queue for the model's metrics.
+ metrics_upload_failed_queue (dict[str, Any]): Queue for metrics that failed to upload.
+ model (Any): Model data fetched from Ultralytics HUB.
+ model_file (str): Path to the model file.
+ train_args (dict[str, Any]): Arguments for training the model.
+ client (Any): Client for interacting with Ultralytics HUB.
+ filename (str): Filename of the model.
+
+ Examples:
+ Create a training session with a model URL
+ >>> session = HUBTrainingSession("https://hub.ultralytics.com/models/example-model")
+ >>> session.upload_metrics()
+ """
def __init__(self, identifier: str):
+ """Initialize the HUBTrainingSession with the provided model identifier.
+
+ Args:
+ identifier (str): Model identifier used to initialize the HUB training session. It can be a URL string or a
+ model key with specific format.
+
+ Raises:
+ ValueError: If the provided model identifier is invalid.
+ ConnectionError: If connecting with global API key is not supported.
+ ModuleNotFoundError: If hub-sdk package is not installed.
+ """
from hub_sdk import HUBClient
self.rate_limits = {"metrics": 3, "ckpt": 900, "heartbeat": 300} # rate limits (seconds)
@@ -57,6 +91,15 @@
@classmethod
def create_session(cls, identifier: str, args: dict[str, Any] | None = None):
+ """Create an authenticated HUBTrainingSession or return None.
+
+ Args:
+ identifier (str): Model identifier used to initialize the HUB training session.
+ args (dict[str, Any], optional): Arguments for creating a new model if identifier is not a HUB model URL.
+
+ Returns:
+ session (HUBTrainingSession | None): An authenticated session or None if creation fails.
+ """
try:
session = cls(identifier)
if args and not identifier.startswith(f"{HUB_WEB_ROOT}/models/"): # not a HUB model URL
@@ -68,6 +111,14 @@ return None
def load_model(self, model_id: str):
+ """Load an existing model from Ultralytics HUB using the provided model identifier.
+
+ Args:
+ model_id (str): The identifier of the model to load.
+
+ Raises:
+ ValueError: If the specified HUB model does not exist.
+ """
self.model = self.client.model(model_id)
if not self.model.data: # then model does not exist
raise HUBModelError(f"❌ Model not found: '{model_id}'. Verify the model ID is correct.")
@@ -85,6 +136,15 @@ LOGGER.info(f"{PREFIX}View model at {self.model_url} 🚀")
def create_model(self, model_args: dict[str, Any]):
+ """Initialize a HUB training session with the specified model arguments.
+
+ Args:
+ model_args (dict[str, Any]): Arguments for creating the model, including batch size, epochs, image size,
+ etc.
+
+ Returns:
+ (None): If the model could not be created.
+ """
payload = {
"config": {
"batchSize": model_args.get("batch", -1),
@@ -119,6 +179,24 @@
@staticmethod
def _parse_identifier(identifier: str):
+ """Parse the given identifier to determine the type and extract relevant components.
+
+ The method supports different identifier formats:
+ - A HUB model URL https://hub.ultralytics.com/models/MODEL
+ - A HUB model URL with API Key https://hub.ultralytics.com/models/MODEL?api_key=APIKEY
+ - A local filename that ends with '.pt' or '.yaml'
+
+ Args:
+ identifier (str): The identifier string to be parsed.
+
+ Returns:
+ api_key (str | None): Extracted API key if present.
+ model_id (str | None): Extracted model ID if present.
+ filename (str | None): Extracted filename if present.
+
+ Raises:
+ HUBModelError: If the identifier format is not recognized.
+ """
api_key, model_id, filename = None, None, None
if identifier.endswith((".pt", ".yaml")):
filename = identifier
@@ -132,6 +210,16 @@ return api_key, model_id, filename
def _set_train_args(self):
+ """Initialize training arguments and create a model entry on the Ultralytics HUB.
+
+ This method sets up training arguments based on the model's state and updates them with any additional arguments
+ provided. It handles different states of the model, such as whether it's resumable, pretrained, or requires
+ specific file setup.
+
+ Raises:
+ ValueError: If the model is already trained, if required dataset information is missing, or if there are
+ issues with the provided training arguments.
+ """
if self.model.is_resumable():
# Model has saved weights
self.train_args = {"data": self.model.get_dataset_url(), "resume": True}
@@ -164,8 +252,25 @@ *args,
**kwargs,
):
+ """Execute request_func with retries, timeout handling, optional threading, and progress tracking.
+
+ Args:
+ request_func (callable): The function to execute.
+ retry (int): Number of retry attempts.
+ timeout (int): Maximum time to wait for the request to complete.
+ thread (bool): Whether to run the request in a separate thread.
+ verbose (bool): Whether to log detailed messages.
+ progress_total (int, optional): Total size for progress tracking.
+ stream_response (bool, optional): Whether to stream the response.
+ *args (Any): Additional positional arguments for request_func.
+ **kwargs (Any): Additional keyword arguments for request_func.
+
+ Returns:
+ (requests.Response | None): The response object if thread=False, otherwise None.
+ """
def retry_request():
+ """Attempt to call request_func with retries, timeout, and optional threading."""
t0 = time.time() # Record the start time for the timeout
response = None
for i in range(retry + 1):
@@ -218,6 +323,7 @@
@staticmethod
def _should_retry(status_code: int) -> bool:
+ """Determine if a request should be retried based on the HTTP status code."""
retry_codes = {
HTTPStatus.REQUEST_TIMEOUT,
HTTPStatus.BAD_GATEWAY,
@@ -226,6 +332,16 @@ return status_code in retry_codes
def _get_failure_message(self, response, retry: int, timeout: int) -> str:
+ """Generate a retry message based on the response status code.
+
+ Args:
+ response (requests.Response): The HTTP response object.
+ retry (int): The number of retry attempts allowed.
+ timeout (int): The maximum timeout duration.
+
+ Returns:
+ (str): The retry message.
+ """
if self._should_retry(response.status_code):
return f"Retrying {retry}x for {timeout}s." if retry else ""
elif response.status_code == HTTPStatus.TOO_MANY_REQUESTS: # rate limit
@@ -241,6 +357,7 @@ return "Unable to read JSON."
def upload_metrics(self):
+ """Upload model metrics to Ultralytics HUB."""
return self.request_queue(self.model.upload_metrics, metrics=self.metrics_queue.copy(), thread=True)
def upload_model(
@@ -251,6 +368,15 @@ map: float = 0.0,
final: bool = False,
) -> None:
+ """Upload a model checkpoint to Ultralytics HUB.
+
+ Args:
+ epoch (int): The current training epoch.
+ weights (str): Path to the model weights file.
+ is_best (bool): Indicates if the current model is the best one so far.
+ map (float): Mean average precision of the model.
+ final (bool): Indicates if the model is the final model after training.
+ """
weights = Path(weights)
if not weights.is_file():
last = weights.with_name(f"last{weights.suffix}")
@@ -282,11 +408,13 @@
@staticmethod
def _show_upload_progress(content_length: int, response) -> None:
+ """Display a progress bar to track the upload progress of a file download."""
with TQDM(total=content_length, unit="B", unit_scale=True, unit_divisor=1024) as pbar:
for data in response.iter_content(chunk_size=1024):
pbar.update(len(data))
@staticmethod
def _iterate_content(response) -> None:
+ """Process the streamed HTTP response data."""
for _ in response.iter_content(chunk_size=1024):
- pass # Do nothing with data chunks+ pass # Do nothing with data chunks
| 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 __init__(self, model: str = "sam_b.pt") -> None:
if model and Path(model).suffix not in {".pt", ".pth"}:
raise NotImplementedError("SAM prediction requires pre-trained *.pt or *.pth model.")
self.is_sam2 = "sam2" in Path(model).stem
self.is_sam3 = "sam3" in Path(model).stem
super().__init__(model=model, task="segment")
def _load(self, weights: str, task=None):
if self.is_sam3:
from .build_sam3 import build_interactive_sam3
self.model = build_interactive_sam3(weights)
else:
from .build import build_sam # slow import
self.model = build_sam(weights)
def predict(self, source, stream: bool = False, bboxes=None, points=None, labels=None, **kwargs):
overrides = dict(conf=0.25, task="segment", mode="predict", imgsz=1024)
kwargs = {**overrides, **kwargs}
prompts = dict(bboxes=bboxes, points=points, labels=labels)
return super().predict(source, stream, prompts=prompts, **kwargs)
def __call__(self, source=None, stream: bool = False, bboxes=None, points=None, labels=None, **kwargs):
return self.predict(source, stream, bboxes, points, labels, **kwargs)
def info(self, detailed: bool = False, verbose: bool = True):
return model_info(self.model, detailed=detailed, verbose=verbose)
@property
def task_map(self) -> dict[str, dict[str, type[Predictor]]]:
return {
"segment": {"predictor": SAM2Predictor if self.is_sam2 else SAM3Predictor if self.is_sam3 else Predictor}
} | --- +++ @@ -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 unparalleled versatility in image analysis,
+and has been trained on the SA-1B dataset. It features zero-shot performance capabilities, enabling it to adapt to new
+image distributions and tasks without prior knowledge.
+
+Key Features:
+ - Promptable segmentation
+ - Real-time performance
+ - Zero-shot transfer capabilities
+ - Trained on SA-1B dataset
+"""
from __future__ import annotations
@@ -11,8 +25,37 @@
class SAM(Model):
+ """SAM (Segment Anything Model) interface class for real-time image segmentation tasks.
+
+ This class provides an interface to the Segment Anything Model (SAM) from Ultralytics, designed for promptable
+ segmentation with versatility in image analysis. It supports various prompts such as bounding boxes, points, or
+ labels, and features zero-shot performance capabilities.
+
+ Attributes:
+ model (torch.nn.Module): The loaded SAM model.
+ is_sam2 (bool): Indicates whether the model is SAM2 variant.
+ task (str): The task type, set to "segment" for SAM models.
+
+ Methods:
+ predict: Perform segmentation prediction on the given image or video source.
+ info: Log information about the SAM model.
+
+ Examples:
+ >>> sam = SAM("sam_b.pt")
+ >>> results = sam.predict("image.jpg", points=[[500, 375]])
+ >>> for r in results:
+ ... print(f"Detected {len(r.masks)} masks")
+ """
def __init__(self, model: str = "sam_b.pt") -> None:
+ """Initialize the SAM (Segment Anything Model) instance.
+
+ Args:
+ model (str): Path to the pre-trained SAM model file. File should have a .pt or .pth extension.
+
+ Raises:
+ NotImplementedError: If the model file extension is not .pt or .pth.
+ """
if model and Path(model).suffix not in {".pt", ".pth"}:
raise NotImplementedError("SAM prediction requires pre-trained *.pt or *.pth model.")
self.is_sam2 = "sam2" in Path(model).stem
@@ -20,6 +63,16 @@ super().__init__(model=model, task="segment")
def _load(self, weights: str, task=None):
+ """Load the specified weights into the SAM model.
+
+ Args:
+ weights (str): Path to the weights file. Should be a .pt or .pth file containing the model parameters.
+ task (str | None): Task name. If provided, it specifies the particular task the model is being loaded for.
+
+ Examples:
+ >>> sam = SAM("sam_b.pt")
+ >>> sam._load("path/to/custom_weights.pt")
+ """
if self.is_sam3:
from .build_sam3 import build_interactive_sam3
@@ -30,19 +83,87 @@ self.model = build_sam(weights)
def predict(self, source, stream: bool = False, bboxes=None, points=None, labels=None, **kwargs):
+ """Perform segmentation prediction on the given image or video source.
+
+ Args:
+ source (str | PIL.Image | np.ndarray): Path to the image or video file, or a PIL.Image object, or a
+ np.ndarray object.
+ stream (bool): If True, enables real-time streaming.
+ bboxes (list[list[float]] | None): List of bounding box coordinates for prompted segmentation.
+ points (list[list[float]] | None): List of points for prompted segmentation.
+ labels (list[int] | None): List of labels for prompted segmentation.
+ **kwargs (Any): Additional keyword arguments for prediction.
+
+ Returns:
+ (list): The model predictions.
+
+ Examples:
+ >>> sam = SAM("sam_b.pt")
+ >>> results = sam.predict("image.jpg", points=[[500, 375]])
+ >>> for r in results:
+ ... print(f"Detected {len(r.masks)} masks")
+ """
overrides = dict(conf=0.25, task="segment", mode="predict", imgsz=1024)
kwargs = {**overrides, **kwargs}
prompts = dict(bboxes=bboxes, points=points, labels=labels)
return super().predict(source, stream, prompts=prompts, **kwargs)
def __call__(self, source=None, stream: bool = False, bboxes=None, points=None, labels=None, **kwargs):
+ """Perform segmentation prediction on the given image or video source.
+
+ This method is an alias for the 'predict' method, providing a convenient way to call the SAM model for
+ segmentation tasks.
+
+ Args:
+ source (str | PIL.Image | np.ndarray | None): Path to the image or video file, or a PIL.Image object, or a
+ np.ndarray object.
+ stream (bool): If True, enables real-time streaming.
+ bboxes (list[list[float]] | None): List of bounding box coordinates for prompted segmentation.
+ points (list[list[float]] | None): List of points for prompted segmentation.
+ labels (list[int] | None): List of labels for prompted segmentation.
+ **kwargs (Any): Additional keyword arguments to be passed to the predict method.
+
+ Returns:
+ (list): The model predictions, typically containing segmentation masks and other relevant information.
+
+ Examples:
+ >>> sam = SAM("sam_b.pt")
+ >>> results = sam("image.jpg", points=[[500, 375]])
+ >>> print(f"Detected {len(results[0].masks)} masks")
+ """
return self.predict(source, stream, bboxes, points, labels, **kwargs)
def info(self, detailed: bool = False, verbose: bool = True):
+ """Log information about the SAM model.
+
+ Args:
+ detailed (bool): If True, displays detailed information about the model layers and operations.
+ verbose (bool): If True, prints the information to the console.
+
+ Returns:
+ (tuple): A tuple containing the model's information (string representations of the model).
+
+ Examples:
+ >>> sam = SAM("sam_b.pt")
+ >>> info = sam.info()
+ >>> print(info[0]) # Print summary information
+ """
return model_info(self.model, detailed=detailed, verbose=verbose)
@property
def task_map(self) -> dict[str, dict[str, type[Predictor]]]:
+ """Provide a mapping from the 'segment' task to its corresponding 'Predictor'.
+
+ Returns:
+ (dict[str, dict[str, type[Predictor]]]): A dictionary mapping the 'segment' task to its corresponding
+ Predictor class. For SAM2 models, it maps to SAM2Predictor, otherwise to the standard Predictor.
+
+ Examples:
+ >>> sam = SAM("sam_b.pt")
+ >>> task_map = sam.task_map
+ >>> print(task_map)
+ {'segment': {'predictor': <class 'ultralytics.models.sam.predict.Predictor'>}}
+ """
return {
"segment": {"predictor": SAM2Predictor if self.is_sam2 else SAM3Predictor if self.is_sam3 else Predictor}
- }+ }
| 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:
from plugin import postprocess_site # mkdocs-ultralytics-plugin
except ImportError:
postprocess_site = None
from build_reference import build_reference_docs
from ultralytics.utils import LINUX, LOGGER, MACOS
from ultralytics.utils.tqdm import TQDM
os.environ["JUPYTER_PLATFORM_DIRS"] = "1" # fix DeprecationWarning: Jupyter is migrating to use standard platformdirs
DOCS = Path(__file__).parent.resolve()
SITE = DOCS.parent / "site"
LINK_PATTERN = re.compile(r"(https?://[^\s()<>]*[^\s()<>.,:;!?\'\"])")
TITLE_PATTERN = re.compile(r"<title>(.*?)</title>", flags=re.IGNORECASE | re.DOTALL)
MD_LINK_PATTERN = re.compile(r'(["\']?)([^"\'>\s]+?)\.md(["\']?)')
DOC_KIND_LABELS = {"Class", "Function", "Method", "Property"}
DOC_KIND_COLORS = {
"Class": "#039dfc", # blue
"Method": "#ef5eff", # magenta
"Function": "#fc9803", # orange
"Property": "#02e835", # green
}
def prepare_docs_markdown(clone_repos: bool = True):
LOGGER.info("Removing existing build artifacts")
shutil.rmtree(SITE, ignore_errors=True)
shutil.rmtree(DOCS / "repos", ignore_errors=True)
if clone_repos:
# Get docs repo
repo = "https://github.com/ultralytics/docs"
local_dir = DOCS / "repos" / Path(repo).name
subprocess.run(
["git", "clone", "-q", "--depth=1", "--single-branch", "-b", "main", repo, str(local_dir)], check=True
)
shutil.rmtree(DOCS / "en/compare", ignore_errors=True) # delete if exists
shutil.copytree(local_dir / "docs/en/compare", DOCS / "en/compare") # for docs
LOGGER.info(f"Cloned/Updated {repo} in {local_dir}")
# Add frontmatter
for file in TQDM((DOCS / "en").rglob("*.md"), desc="Adding frontmatter"):
update_markdown_files(file)
def update_markdown_files(md_filepath: Path):
if md_filepath.exists():
content = md_filepath.read_text().strip()
# Replace apostrophes
content = content.replace("‘", "'").replace("’", "'")
# Add frontmatter if missing
if not content.strip().startswith("---\n"):
header = "---\ncomments: true\ndescription: TODO ADD DESCRIPTION\nkeywords: TODO ADD KEYWORDS\n---\n\n"
content = header + content
# Ensure MkDocs admonitions "=== " lines are preceded and followed by empty newlines
lines = content.split("\n")
new_lines = []
for i, line in enumerate(lines):
stripped_line = line.strip()
if stripped_line.startswith("=== "):
if i > 0 and new_lines[-1] != "":
new_lines.append("")
new_lines.append(line)
if i < len(lines) - 1 and lines[i + 1].strip() != "":
new_lines.append("")
else:
new_lines.append(line)
content = "\n".join(new_lines)
# Add EOF newline if missing
if not content.endswith("\n"):
content += "\n"
# Save page
md_filepath.write_text(content)
return
def update_docs_html():
from concurrent.futures import ProcessPoolExecutor
html_files = list(SITE.rglob("*.html"))
if not html_files:
LOGGER.info("Updated HTML files: 0")
return
desc = f"Updating HTML at {SITE}"
max_workers = os.cpu_count() or 1
with ProcessPoolExecutor(max_workers=max_workers) as executor:
pbar = TQDM(executor.map(_process_html_file, html_files), total=len(html_files), desc=desc)
updated = 0
for res in pbar:
updated += bool(res)
pbar.set_description(f"{desc} ({updated}/{len(html_files)} updated)")
def _process_html_file(html_file: Path) -> bool:
try:
content = html_file.read_text(encoding="utf-8")
except Exception as e:
LOGGER.warning(f"Could not read {html_file}: {e}")
return False
changed = False
try:
rel_path = html_file.relative_to(SITE).as_posix()
except ValueError:
rel_path = html_file.name
# For pages sourced from external repos (compare), drop edit/copy buttons to avoid wrong links
if rel_path.startswith("compare/"):
before = content
content = re.sub(
r'<a[^>]*class="[^"]*md-content__button[^"]*"[^>]*>.*?</a>',
"",
content,
flags=re.IGNORECASE | re.DOTALL,
)
if content != before:
changed = True
if rel_path == "404.html":
new_content = re.sub(r"<title>.*?</title>", "<title>Ultralytics Docs - Not Found</title>", content)
if new_content != content:
content, changed = new_content, True
new_content = update_docs_soup(content, html_file=html_file)
if new_content != content:
content, changed = new_content, True
new_content = _rewrite_md_links(content)
if new_content != content:
content, changed = new_content, True
if changed:
try:
html_file.write_text(content, encoding="utf-8")
return True
except Exception as e:
LOGGER.warning(f"Could not write {html_file}: {e}")
return False
def update_docs_soup(content: str, html_file: Path | None = None, max_title_length: int = 70) -> str:
title_match = TITLE_PATTERN.search(content)
needs_title_trim = bool(
title_match and len(title_match.group(1)) > max_title_length and "-" in title_match.group(1)
)
needs_link_conversion = ("<p" in content or "<li" in content) and bool(LINK_PATTERN.search(content))
needs_codelineno_cleanup = "__codelineno-" in content
rel_path = ""
if html_file:
try:
rel_path = html_file.relative_to(SITE).as_posix()
except Exception:
rel_path = html_file.as_posix()
needs_kind_highlight = "reference" in rel_path or "reference" in content
if not (needs_title_trim or needs_link_conversion or needs_codelineno_cleanup or needs_kind_highlight):
return content
try:
soup = BeautifulSoup(content, "lxml")
except Exception:
soup = BeautifulSoup(content, "html.parser")
modified = False
# Truncate long meta title if needed
title_tag = soup.find("title") if needs_title_trim else None
if title_tag and len(title_tag.text) > max_title_length and "-" in title_tag.text:
title_tag.string = title_tag.text.rsplit("-", 1)[0].strip()
modified = True
# Find the main content area
main_content = soup.find("main") or soup.find("div", class_="md-content")
if not main_content:
return str(soup) if modified else content
# Convert plaintext links to HTML hyperlinks
if needs_link_conversion:
for paragraph in main_content.select("p, li"):
for text_node in paragraph.find_all(string=True, recursive=False):
if text_node.parent.name not in {"a", "code"}:
new_text = LINK_PATTERN.sub(r'<a href="\1">\1</a>', str(text_node))
if "<a href=" in new_text:
text_node.replace_with(BeautifulSoup(new_text, "html.parser"))
modified = True
# Remove href attributes from code line numbers in code blocks
if needs_codelineno_cleanup:
for a in soup.select('a[href^="#__codelineno-"], a[id^="__codelineno-"]'):
if a.string: # If the a tag has text (the line number)
# Check if parent is a span with class="normal"
if a.parent and a.parent.name == "span" and "normal" in a.parent.get("class", []):
del a.parent["class"]
a.replace_with(a.string) # Replace with just the text
else: # If it has no text
a.replace_with(soup.new_tag("span")) # Replace with an empty span
modified = True
def highlight_labels(nodes):
nonlocal modified
for node in nodes:
if not node.contents:
continue
first = node.contents[0]
if hasattr(first, "get") and "doc-kind" in (first.get("class") or []):
continue
text = first if isinstance(first, str) else getattr(first, "string", "")
if not text:
continue
stripped = str(text).strip()
if not stripped:
continue
kind = stripped.split()[0].rstrip(":")
if kind not in DOC_KIND_LABELS:
continue
span = soup.new_tag("span", attrs={"class": f"doc-kind doc-kind-{kind.lower()}"})
span.string = kind.lower()
first.replace_with(span)
tail = str(text)[len(kind) :]
tail_stripped = tail.lstrip()
if tail_stripped.startswith(kind):
tail = tail_stripped[len(kind) :]
if not tail and len(node.contents) > 0:
tail = " "
if tail:
span.insert_after(tail)
modified = True
highlight_labels(soup.select("main h1, main h2, main h3, main h4, main h5"))
highlight_labels(soup.select("nav.md-nav--secondary .md-ellipsis, nav.md-nav__list .md-ellipsis"))
if "reference" in rel_path:
for ellipsis in soup.select("nav.md-nav--secondary .md-ellipsis"):
kind = ellipsis.find(class_=lambda c: c and "doc-kind" in c.split())
text = str(kind.next_sibling).strip() if kind and kind.next_sibling else ellipsis.get_text(strip=True)
if "." not in text:
continue
ellipsis.clear()
short = text.rsplit(".", 1)[-1]
if kind:
ellipsis.append(kind)
ellipsis.append(f" {short}")
else:
ellipsis.append(short)
modified = True
if needs_kind_highlight and not modified and soup.select(".doc-kind"):
# Ensure style injection when pre-existing badges are present
modified = True
if modified:
head = soup.find("head")
if head and not soup.select("style[data-doc-kind]"):
style = soup.new_tag("style", attrs={"data-doc-kind": "true"})
style.string = (
".doc-kind{display:inline-flex;align-items:center;gap:0.25em;padding:0.21em 0.59em;border-radius:999px;"
"font-weight:700;font-size:0.81em;letter-spacing:0.06em;text-transform:uppercase;"
"line-height:1;color:var(--doc-kind-color,#f8fafc);"
"background:var(--doc-kind-bg,rgba(255,255,255,0.12));}"
f".doc-kind-class{{--doc-kind-color:{DOC_KIND_COLORS['Class']};--doc-kind-bg:rgba(3,157,252,0.22);}}"
f".doc-kind-function{{--doc-kind-color:{DOC_KIND_COLORS['Function']};--doc-kind-bg:rgba(252,152,3,0.22);}}"
f".doc-kind-method{{--doc-kind-color:{DOC_KIND_COLORS['Method']};--doc-kind-bg:rgba(239,94,255,0.22);}}"
f".doc-kind-property{{--doc-kind-color:{DOC_KIND_COLORS['Property']};--doc-kind-bg:rgba(2,232,53,0.22);}}"
)
head.append(style)
return str(soup) if modified else content
def _rewrite_md_links(content: str) -> str:
if ".md" not in content:
return content
lines = []
for line in content.split("\n"):
if "github.com" not in line:
line = line.replace("index.md", "")
line = MD_LINK_PATTERN.sub(r"\1\2/\3", line)
lines.append(line)
return "\n".join(lines)
# Precompiled regex patterns for minification
HTML_COMMENT = re.compile(r"<!--[\s\S]*?-->")
HTML_PRESERVE = re.compile(r"<(pre|code|textarea|script)[^>]*>[\s\S]*?</\1>", re.IGNORECASE)
HTML_TAG_SPACE = re.compile(r">\s+<")
HTML_MULTI_SPACE = re.compile(r"\s{2,}")
HTML_EMPTY_LINE = re.compile(r"^\s*$\n", re.MULTILINE)
CSS_COMMENT = re.compile(r"/\*[\s\S]*?\*/")
def remove_comments_and_empty_lines(content: str, file_type: str) -> str:
if file_type == "html":
content = HTML_COMMENT.sub("", content) # Remove HTML comments
# Preserve whitespace in <pre>, <code>, <textarea> tags
preserved = []
def preserve(match):
preserved.append(match.group(0))
return f"___PRESERVE_{len(preserved) - 1}___"
content = HTML_PRESERVE.sub(preserve, content)
content = HTML_TAG_SPACE.sub("><", content) # Remove whitespace between tags
content = HTML_MULTI_SPACE.sub(" ", content) # Collapse multiple spaces
content = HTML_EMPTY_LINE.sub("", content) # Remove empty lines
# Restore preserved content
for i, text in enumerate(preserved):
content = content.replace(f"___PRESERVE_{i}___", text)
elif file_type == "css":
content = CSS_COMMENT.sub("", content) # Remove CSS comments
# Remove whitespace around specific characters
content = re.sub(r"\s*([{}:;,])\s*", r"\1", content)
# Remove empty lines
content = re.sub(r"^\s*\n", "", content, flags=re.MULTILINE)
# Collapse multiple spaces to single space
content = re.sub(r"\s{2,}", " ", content)
# Remove all newlines
content = re.sub(r"\n", "", content)
elif file_type == "js":
# Handle JS single-line comments (preserving http:// and https://)
lines = content.split("\n")
processed_lines = []
for line in lines:
# Only remove comments if they're not part of a URL
if "//" in line and "http://" not in line and "https://" not in line:
processed_lines.append(line.partition("//")[0])
else:
processed_lines.append(line)
content = "\n".join(processed_lines)
# Remove JS multi-line comments and clean whitespace
content = re.sub(r"/\*[\s\S]*?\*/", "", content)
# Remove empty lines
content = re.sub(r"^\s*\n", "", content, flags=re.MULTILINE)
# Collapse multiple spaces to single space
content = re.sub(r"\s{2,}", " ", content)
# Safe space removal around punctuation and operators (never include colons - breaks JS)
content = re.sub(r"\s*([;{}])\s*", r"\1", content)
content = re.sub(r"(\w)\s*\(|\)\s*{|\s*([+\-*/=])\s*", lambda m: m.group(0).replace(" ", ""), content)
return content
def minify_files(html: bool = True, css: bool = True, js: bool = True):
minify, compress, jsmin = None, None, None
try:
if html:
from minify_html import minify
if css:
from csscompressor import compress
if js:
import jsmin
except ImportError as e:
LOGGER.info(f"Missing required package: {e}")
return
stats = {}
for ext, minifier in {
"html": (lambda x: minify(x, keep_closing_tags=True, minify_css=True, minify_js=True)) if html else None,
"css": compress if css else None,
"js": jsmin.jsmin if js else None,
}.items():
orig = minified = 0
files = list(SITE.rglob(f"*.{ext}"))
if not files:
continue
pbar = TQDM(files, desc=f"Minifying {ext.upper()} - reduced 0.00% (0.00 KB saved)")
for f in pbar:
content = f.read_text(encoding="utf-8")
out = minifier(content) if minifier else remove_comments_and_empty_lines(content, ext)
orig += len(content)
minified += len(out)
f.write_text(out, encoding="utf-8")
saved = orig - minified
pct = (saved / orig) * 100 if orig else 0.0
pbar.set_description(f"Minifying {ext.upper()} - reduced {pct:.2f}% ({saved / 1024:.2f} KB saved)")
stats[ext] = {"original": orig, "minified": minified}
def render_jinja_macros() -> None:
mkdocs_yml = DOCS.parent / "mkdocs.yml"
default_yaml = DOCS.parent / "ultralytics" / "cfg" / "default.yaml"
class SafeFallbackLoader(yaml.SafeLoader):
def _ignore_unknown(loader, tag_suffix, node):
if isinstance(node, yaml.ScalarNode):
return loader.construct_scalar(node)
if isinstance(node, yaml.SequenceNode):
return loader.construct_sequence(node)
if isinstance(node, yaml.MappingNode):
return loader.construct_mapping(node)
return None
SafeFallbackLoader.add_multi_constructor("", _ignore_unknown)
def load_yaml(path: Path, *, safe_loader: yaml.Loader = yaml.SafeLoader) -> dict:
if not path.exists():
return {}
try:
with open(path, encoding="utf-8") as f:
return yaml.load(f, Loader=safe_loader) or {}
except Exception as e:
LOGGER.warning(f"Could not load {path}: {e}")
return {}
mkdocs_cfg = load_yaml(mkdocs_yml, safe_loader=SafeFallbackLoader)
extra_vars = mkdocs_cfg.get("extra", {}) or {}
site_name = mkdocs_cfg.get("site_name", "Ultralytics Docs")
extra_vars.update(load_yaml(default_yaml))
env = Environment(
loader=load_from_path([DOCS / "en", DOCS]),
auto_escape_callback=lambda _: False,
trim_blocks=True,
lstrip_blocks=True,
keep_trailing_newline=True,
)
def indent_filter(value: str, width: int = 4, first: bool = False, blank: bool = False) -> str:
prefix = " " * int(width)
result = []
for i, line in enumerate(str(value).splitlines(keepends=True)):
if not line.strip() and not blank:
result.append(line)
continue
if i == 0 and not first:
result.append(line)
else:
result.append(prefix + line)
return "".join(result)
env.add_filter("indent", indent_filter)
reserved_keys = {"name"}
base_context = {**extra_vars, "page": {"meta": {}}, "config": {"site_name": site_name}}
files_processed = 0
files_with_macros = 0
macros_total = 0
pbar = TQDM((DOCS / "en").rglob("*.md"), desc="MiniJinja: 0 macros, 0 pages")
for md_file in pbar:
if "macros" in md_file.parts or "reference" in md_file.parts:
continue
files_processed += 1
try:
content = md_file.read_text(encoding="utf-8")
except Exception as e:
LOGGER.warning(f"Could not read {md_file}: {e}")
continue
if "{{" not in content and "{%" not in content:
continue
parts = content.split("---\n")
frontmatter = ""
frontmatter_data = {}
markdown_content = content
if content.startswith("---\n") and len(parts) >= 3:
frontmatter = f"---\n{parts[1]}---\n"
markdown_content = "---\n".join(parts[2:])
try:
frontmatter_data = yaml.safe_load(parts[1]) or {}
except Exception as e:
LOGGER.warning(f"Could not parse frontmatter in {md_file}: {e}")
macro_hits = markdown_content.count("{{") + markdown_content.count("{%")
if not macro_hits:
continue
context = {k: v for k, v in base_context.items() if k not in reserved_keys}
context.update({k: v for k, v in frontmatter_data.items() if k not in reserved_keys})
context["page"] = context.get("page", {})
context["page"]["meta"] = frontmatter_data
try:
rendered = env.render_str(markdown_content, name=str(md_file.relative_to(DOCS)), **context)
except Exception as e:
LOGGER.warning(f"Error rendering macros in {md_file}: {e}")
continue
md_file.write_text(frontmatter + rendered, encoding="utf-8")
files_with_macros += 1
macros_total += macro_hits
pbar.set_description(f"MiniJinja: {macros_total} macros, {files_with_macros} pages")
def backup_docs_sources() -> tuple[Path, list[tuple[Path, Path]]]:
backup_root = Path(tempfile.mkdtemp(prefix="docs_backup_", dir=str(DOCS.parent)))
sources = [DOCS / "en", DOCS / "macros"]
copied: list[tuple[Path, Path]] = []
for src in sources:
if not src.exists():
continue
dst = backup_root / src.name
shutil.copytree(src, dst)
copied.append((src, dst))
return backup_root, copied
def restore_docs_sources(backup_root: Path, backups: list[tuple[Path, Path]]):
for src, dst in backups:
shutil.rmtree(src, ignore_errors=True)
if dst.exists():
shutil.copytree(dst, src)
shutil.rmtree(backup_root, ignore_errors=True)
def main():
if not shutil.which("zensical"):
raise SystemExit("zensical is not installed. Install it with: pip install -e '.[dev]'")
start_time = time.perf_counter()
backup_root: Path | None = None
docs_backups: list[tuple[Path, Path]] = []
restored = False
def restore_all():
nonlocal restored
if backup_root:
LOGGER.info("Restoring docs directory from backup")
restore_docs_sources(backup_root, docs_backups)
restored = True
try:
backup_root, docs_backups = backup_docs_sources()
prepare_docs_markdown()
build_reference_docs(update_nav=False)
render_jinja_macros()
# Remove cloned repos before serving/building to keep the tree lean during mkdocs processing
shutil.rmtree(DOCS / "repos", ignore_errors=True)
# Build the main documentation
LOGGER.info(f"Building docs from {DOCS}")
subprocess.run(["zensical", "build", "-f", str(DOCS.parent / "mkdocs.yml"), "--strict"], check=True)
LOGGER.info(f"Site built at {SITE}")
# Remove search index JSON files to disable search
Path(SITE / "search.json").unlink(missing_ok=True)
# Update docs HTML pages
update_docs_html()
# Post-process site for meta tags, authors, social cards, and mkdocstrings polish
if postprocess_site:
postprocess_site(
site_dir=SITE,
docs_dir=DOCS / "en",
site_url="https://docs.ultralytics.com",
default_image="https://raw.githubusercontent.com/ultralytics/assets/main/yolov8/banner-yolov8.png",
default_author="glenn.jocher@ultralytics.com",
add_desc=False,
add_image=True,
add_authors=True,
add_json_ld=True,
add_share_buttons=True,
add_css=False,
verbose=True,
)
else:
LOGGER.warning("postprocess_site not available; skipping mkdocstrings postprocessing")
# Minify files
minify_files(html=False, css=False, js=False)
# Add missing pages to sitemap
sitemap = SITE / "sitemap.xml"
if sitemap.exists():
content = sitemap.read_text()
in_sitemap = set(re.findall(r"<loc>([^<]+)</loc>", content))
all_pages = {
f"https://docs.ultralytics.com/{f.relative_to(SITE).as_posix().replace('index.html', '')}"
for f in SITE.rglob("*.html")
if f.name != "404.html"
}
if missing := (all_pages - in_sitemap):
entries = "\n".join(f" <url>\n <loc>{u}</loc>\n </url>" for u in sorted(missing))
sitemap.write_text(content.replace("</urlset>", f"{entries}\n</urlset>"))
LOGGER.info(
f"{len(all_pages)}/{len(all_pages)} pages in sitemap.xml ✅ (+{len(missing)} added)"
if missing
else f"{len(in_sitemap)}/{len(all_pages)} pages in sitemap.xml ✅"
)
# Print results and auto-serve on macOS
size = sum(f.stat().st_size for f in SITE.rglob("*") if f.is_file()) >> 20
duration = time.perf_counter() - start_time
LOGGER.info(f"Docs built correctly ✅ ({size:.1f}MB, {duration:.1f}s)")
# Restore sources before optionally serving
restore_all()
if (MACOS or LINUX) and not os.getenv("GITHUB_ACTIONS"):
import webbrowser
url = "http://localhost:8000"
LOGGER.info(f"Opening browser at {url}")
webbrowser.open(url)
try:
subprocess.run([sys.executable, "-m", "http.server", "--directory", str(SITE), "8000"], check=True)
except KeyboardInterrupt:
LOGGER.info(f"\n✅ Server stopped. Restart at {url}")
except Exception as e:
if "Address already in use" in str(e):
LOGGER.info("Port 8000 in use; skipping auto-serve. Serve manually if needed.")
else:
LOGGER.info(f"\n❌ Server failed: {e}")
else:
LOGGER.info('Serve site at http://localhost:8000 with "python -m http.server --directory site"')
finally:
if not restored:
restore_all()
shutil.rmtree(DOCS / "repos", ignore_errors=True)
if __name__ == "__main__":
main() | --- +++ @@ -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 Features:
+ - Automated building of MkDocs documentation: Compiles main documentation and localized versions from separate
+ MkDocs configuration files.
+ - Post-processing of generated HTML files: Updates HTML files to remove '.md' from internal links, ensuring
+ correct navigation in web-based documentation.
+
+Usage:
+ - Run from the root directory of your MkDocs project.
+ - Ensure MkDocs is installed and configuration files (main and localized) are present.
+ - The script builds documentation using MkDocs, then scans HTML files in 'site' to update links.
+ - Ideal for projects with Markdown documentation served as a static website.
+
+Note:
+ - Requires Python and MkDocs to be installed and configured.
+"""
from __future__ import annotations
@@ -41,6 +61,7 @@
def prepare_docs_markdown(clone_repos: bool = True):
+ """Build docs using mkdocs."""
LOGGER.info("Removing existing build artifacts")
shutil.rmtree(SITE, ignore_errors=True)
shutil.rmtree(DOCS / "repos", ignore_errors=True)
@@ -62,6 +83,7 @@
def update_markdown_files(md_filepath: Path):
+ """Create or update a Markdown file, ensuring frontmatter is present."""
if md_filepath.exists():
content = md_filepath.read_text().strip()
@@ -98,6 +120,7 @@
def update_docs_html():
+ """Update titles, edit links, and convert plaintext links in HTML documentation in one pass."""
from concurrent.futures import ProcessPoolExecutor
html_files = list(SITE.rglob("*.html"))
@@ -115,6 +138,7 @@
def _process_html_file(html_file: Path) -> bool:
+ """Process a single HTML file; returns True if modified."""
try:
content = html_file.read_text(encoding="utf-8")
except Exception as e:
@@ -162,6 +186,7 @@
def update_docs_soup(content: str, html_file: Path | None = None, max_title_length: int = 70) -> str:
+ """Convert plaintext links to HTML hyperlinks, truncate long meta titles, and remove code line hrefs."""
title_match = TITLE_PATTERN.search(content)
needs_title_trim = bool(
title_match and len(title_match.group(1)) > max_title_length and "-" in title_match.group(1)
@@ -219,6 +244,7 @@ modified = True
def highlight_labels(nodes):
+ """Inject doc-kind badges into headings and nav entries."""
nonlocal modified
for node in nodes:
@@ -291,6 +317,7 @@
def _rewrite_md_links(content: str) -> str:
+ """Replace .md references with trailing slashes in HTML content, skipping GitHub links."""
if ".md" not in content:
return content
@@ -313,12 +340,28 @@
def remove_comments_and_empty_lines(content: str, file_type: str) -> str:
+ """Remove comments and empty lines from a string of code, preserving newlines and URLs.
+
+ Args:
+ content (str): Code content to process.
+ file_type (str): Type of file ('html', 'css', or 'js').
+
+ Returns:
+ (str): Cleaned content with comments and empty lines removed.
+
+ Notes:
+ Typical reductions for Ultralytics Docs are:
+ - Total HTML reduction: 2.83% (1301.56 KB saved)
+ - Total CSS reduction: 1.75% (2.61 KB saved)
+ - Total JS reduction: 13.51% (99.31 KB saved)
+ """
if file_type == "html":
content = HTML_COMMENT.sub("", content) # Remove HTML comments
# Preserve whitespace in <pre>, <code>, <textarea> tags
preserved = []
def preserve(match):
+ """Mark HTML blocks that should not be minified."""
preserved.append(match.group(0))
return f"___PRESERVE_{len(preserved) - 1}___"
@@ -366,6 +409,7 @@
def minify_files(html: bool = True, css: bool = True, js: bool = True):
+ """Minify HTML, CSS, and JS files and print total reduction stats."""
minify, compress, jsmin = None, None, None
try:
if html:
@@ -402,12 +446,15 @@
def render_jinja_macros() -> None:
+ """Render MiniJinja macros in Markdown files before building with MkDocs."""
mkdocs_yml = DOCS.parent / "mkdocs.yml"
default_yaml = DOCS.parent / "ultralytics" / "cfg" / "default.yaml"
class SafeFallbackLoader(yaml.SafeLoader):
+ """SafeLoader that gracefully skips unknown tags (required for mkdocs.yml)."""
def _ignore_unknown(loader, tag_suffix, node):
+ """Gracefully handle YAML tags that aren't registered."""
if isinstance(node, yaml.ScalarNode):
return loader.construct_scalar(node)
if isinstance(node, yaml.SequenceNode):
@@ -419,6 +466,7 @@ SafeFallbackLoader.add_multi_constructor("", _ignore_unknown)
def load_yaml(path: Path, *, safe_loader: yaml.Loader = yaml.SafeLoader) -> dict:
+ """Load YAML safely, returning an empty dict on errors."""
if not path.exists():
return {}
try:
@@ -442,6 +490,7 @@ )
def indent_filter(value: str, width: int = 4, first: bool = False, blank: bool = False) -> str:
+ """Mimic Jinja's indent filter to preserve macros compatibility."""
prefix = " " * int(width)
result = []
for i, line in enumerate(str(value).splitlines(keepends=True)):
@@ -510,6 +559,7 @@
def backup_docs_sources() -> tuple[Path, list[tuple[Path, Path]]]:
+ """Create a temporary backup of docs sources so we can fully restore after building."""
backup_root = Path(tempfile.mkdtemp(prefix="docs_backup_", dir=str(DOCS.parent)))
sources = [DOCS / "en", DOCS / "macros"]
copied: list[tuple[Path, Path]] = []
@@ -523,6 +573,7 @@
def restore_docs_sources(backup_root: Path, backups: list[tuple[Path, Path]]):
+ """Restore docs sources from the temporary backup."""
for src, dst in backups:
shutil.rmtree(src, ignore_errors=True)
if dst.exists():
@@ -531,6 +582,7 @@
def main():
+ """Build docs, update titles and edit links, minify HTML, and print local server command."""
if not shutil.which("zensical"):
raise SystemExit("zensical is not installed. Install it with: pip install -e '.[dev]'")
@@ -540,6 +592,7 @@ restored = False
def restore_all():
+ """Restore docs sources from backup once build steps complete."""
nonlocal restored
if backup_root:
LOGGER.info("Restoring docs directory from backup")
@@ -639,4 +692,4 @@
if __name__ == "__main__":
- main()+ main()
| https://raw.githubusercontent.com/ultralytics/ultralytics/HEAD/docs/build_docs.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.