Repository: ErikBjare/gptme
File: gptme/message.py (Python)

Code before:
        """Get the input cost of the message in USD."""
        from .llm.models import get_model  # noreorder

        m = get_model(model)
        tok = len_tokens(self, f"{m.provider}/{m.model}")
        price = (m.price_output if output else m.price_input) / 1_000_000
        return tok * price


def format_msgs(
    msgs: list[Message],
    oneline: bool = False,
    highlight: bool = False,
    indent: int = 0,
) -> list[str]:
    """Formats messages for printing to the console."""
    outputs = []
    for msg in msgs:
        userprefix = msg.role.capitalize()
        if highlight:
            color = ROLE_COLOR[msg.role]
            userprefix = f"[bold {color}]{userprefix}[/bold {color}]"
        if msg.role == "system":
            first_line = msg.content.split("\n", 1)[0].lower()
            isSuccess = first_line.startswith(("saved", "appended", "patch successfully"))
            isError = first_line.startswith(("error", "failed")) or "Return code" in msg.content[-16:]
            if isSuccess:
                userprefix = f"{userprefix} ✅"
            elif isError:
                userprefix = f"{userprefix} ❌"
                
        # get terminal width
        max_len = shutil.get_terminal_size().columns - len(userprefix)
        output = ""
        if oneline:
            output += textwrap.shorten(
                msg.content.replace("\n", "\\n"), width=max_len, placeholder="..."
            )
            if len(output) < 20:
                output = msg.content.replace("\n", "\\n")[:max_len] + "..."
        else:
            multiline = len(msg.content.split("\n")) > 1
            output += "\n" + indent * " " if multiline else ""
            for i, block in enumerate(msg.content.split("```")):
                if i % 2 == 0:
                    output += textwrap.indent(block, prefix=indent * " ")
                    continue
                elif highlight:
                    lang = block.split("\n", 1)[0]
                    content = block.split("\n", 1)[-1]
                    fmt = "underline blue"

Review comment (suggestion):
When a shell command exits with a non-zero code the code is part of the message. Only captures unsuccessful commands. Could change the code to append the return code for each command and strip the zero return codes before displaying the message.

Code after:
        """Get the input cost of the message in USD."""
        from .llm.models import get_model  # noreorder

        m = get_model(model)
        tok = len_tokens(self, f"{m.provider}/{m.model}")
        price = (m.price_output if output else m.price_input) / 1_000_000
        return tok * price


def format_msgs(
    msgs: list[Message],
    oneline: bool = False,
    highlight: bool = False,
    indent: int = 0,
) -> list[str]:
    """Formats messages for printing to the console."""
    outputs = []
    for msg in msgs:
        userprefix = msg.role.capitalize()
        if highlight:
            color = ROLE_COLOR[msg.role]
            userprefix = f"[bold {color}]{userprefix}[/bold {color}]"
        if msg.role == "system":
            first_line = msg.content.split("\n", 1)[0].lower()
            isSuccess = first_line.startswith(("saved", "appended", "patch successfully", "ran"))
            isError = first_line.startswith(("error", "failed"))
            if isSuccess:
                userprefix = f"{userprefix} ✅"
            elif isError:
                userprefix = f"{userprefix} ❌"
                
        # get terminal width
        max_len = shutil.get_terminal_size().columns - len(userprefix)
        output = ""
        if oneline:
            output += textwrap.shorten(
                msg.content.replace("\n", "\\n"), width=max_len, placeholder="..."
            )
            if len(output) < 20:
                output = msg.content.replace("\n", "\\n")[:max_len] + "..."
        else:
            multiline = len(msg.content.split("\n")) > 1
            output += "\n" + indent * " " if multiline else ""
            for i, block in enumerate(msg.content.split("```")):
                if i % 2 == 0:
                    output += textwrap.indent(block, prefix=indent * " ")
                    continue
                elif highlight:
                    lang = block.split("\n", 1)[0]
                    content = block.split("\n", 1)[-1]
                    fmt = "underline blue"