Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #422: Markdown formatting for chat history #444

Merged
merged 3 commits into from
Feb 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,8 @@ sgpt --role json_generator "random: user, password, email, address"
}
```

If the description of the role contains the words "APPLY MARKDOWN" (case sensitive), then chats will be displayed using markdown formatting.

### Request cache
Control cache using `--cache` (default) and `--no-cache` options. This caching applies for all `sgpt` requests to OpenAI API:
```shell
Expand Down
26 changes: 18 additions & 8 deletions sgpt/handlers/chat_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

import typer
from click import BadArgumentUsage
from rich.console import Console
from rich.markdown import Markdown

from ..config import cfg
from ..role import DefaultRoles, SystemRole
Expand Down Expand Up @@ -107,15 +109,15 @@ def __init__(self, chat_id: str, role: SystemRole) -> None:
def initiated(self) -> bool:
return self.chat_session.exists(self.chat_id)

@property
def initial_message(self) -> str:
chat_history = self.chat_session.get_messages(self.chat_id)
return chat_history[0] if chat_history else ""

@property
def is_same_role(self) -> bool:
# TODO: Should be optimized for REPL mode.
return self.role.same_role(self.initial_message)
return self.role.same_role(self.initial_message(self.chat_id))

@classmethod
def initial_message(cls, chat_id: str) -> str:
chat_history = cls.chat_session.get_messages(chat_id)
return chat_history[0] if chat_history else ""

@classmethod
@option_callback
Expand All @@ -126,7 +128,15 @@ def list_ids(cls, value: str) -> None:

@classmethod
def show_messages(cls, chat_id: str) -> None:
# Prints all messages from a specified chat ID to the console.
if "APPLY MARKDOWN" in cls.initial_message(chat_id):
for message in cls.chat_session.get_messages(chat_id):
if message.startswith("assistant:"):
Console().print(Markdown(message))
else:
typer.secho(message, fg=cfg.get("DEFAULT_COLOR"))
typer.echo()
return

for index, message in enumerate(cls.chat_session.get_messages(chat_id)):
color = "magenta" if index % 2 == 0 else "green"
typer.secho(message, fg=color)
Expand All @@ -138,7 +148,7 @@ def show_messages_callback(cls, chat_id: str) -> None:

def validate(self) -> None:
if self.initiated:
chat_role_name = self.role.get_role_name(self.initial_message)
chat_role_name = self.role.get_role_name(self.initial_message(self.chat_id))
if not chat_role_name:
raise BadArgumentUsage(
f'Could not determine chat role of "{self.chat_id}"'
Expand Down
37 changes: 37 additions & 0 deletions tests/test_default.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,43 @@ def test_default_stdin(completion):
assert "Prague" in result.stdout


@patch("rich.console.Console.print")
@patch("litellm.completion")
def test_show_chat_use_markdown(completion, console_print):
completion.return_value = mock_comp("ok")
chat_name = "_test"
chat_path = Path(cfg.get("CHAT_CACHE_PATH")) / chat_name
chat_path.unlink(missing_ok=True)

args = {"prompt": "my number is 2", "--chat": chat_name}
result = runner.invoke(app, cmd_args(**args))
assert result.exit_code == 0
assert chat_path.exists()

result = runner.invoke(app, ["--show-chat", chat_name])
assert result.exit_code == 0
console_print.assert_called()


@patch("rich.console.Console.print")
@patch("litellm.completion")
def test_show_chat_no_use_markdown(completion, console_print):
completion.return_value = mock_comp("ok")
chat_name = "_test"
chat_path = Path(cfg.get("CHAT_CACHE_PATH")) / chat_name
chat_path.unlink(missing_ok=True)

# Flag '--code' doesn't use markdown
args = {"prompt": "my number is 2", "--chat": chat_name, "--code": True}
result = runner.invoke(app, cmd_args(**args))
assert result.exit_code == 0
assert chat_path.exists()

result = runner.invoke(app, ["--show-chat", chat_name])
assert result.exit_code == 0
console_print.assert_not_called()


@patch("litellm.completion")
def test_default_chat(completion):
completion.side_effect = [mock_comp("ok"), mock_comp("4")]
Expand Down
Loading