Skip to content

Commit

Permalink
fix: add cli-provided prompts to readline history
Browse files Browse the repository at this point in the history
  • Loading branch information
ErikBjare committed Oct 30, 2024
1 parent b931103 commit ffaa109
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
9 changes: 9 additions & 0 deletions gptme/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from .logmanager import ConversationMeta, get_user_conversations
from .message import Message
from .prompts import get_prompt
from .readline import add_history
from .tools import all_tools, init_tools
from .util import epoch_to_age, generate_name

Expand Down Expand Up @@ -192,9 +193,17 @@ def main(
"Failed to switch to interactive mode, continuing in non-interactive mode"
)

# add prompts to readline history
for prompt in prompts:
if prompt and len(prompt) > 1000:
# skip adding long prompts to history (slows down startup, unlikely to be useful)
continue
add_history(prompt)

# join prompts, grouped by `-` if present, since that's the separator for "chained"/multiple-round prompts
sep = "\n\n" + MULTIPROMPT_SEPARATOR
prompts = [p.strip() for p in "\n\n".join(prompts).split(sep) if p]
# TODO: referenced file paths in multiprompts should be read when run, not when parsed
prompt_msgs = [Message("user", p) for p in prompts]

if resume:
Expand Down
10 changes: 10 additions & 0 deletions gptme/readline.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@


logger = logging.getLogger(__name__)
init = False


# default history if none found
Expand All @@ -31,10 +32,18 @@


def add_history(line: str) -> None: # pragma: no cover
if not init:
load_readline_history()

readline.add_history(line)
readline.write_history_file(get_readline_history_file())


def load_readline_history() -> None: # pragma: no cover
global init
if init:
return

logger.debug("Loading history")
# enabled by default in CPython, make it explicit
readline.set_auto_history(True)
Expand All @@ -50,6 +59,7 @@ def load_readline_history() -> None: # pragma: no cover
logger.exception("Failed to load history file")

atexit.register(readline.write_history_file, history_file)
init = True


def register_tabcomplete() -> None: # pragma: no cover
Expand Down

0 comments on commit ffaa109

Please sign in to comment.