Skip to content

Commit

Permalink
feat(chat): integrate prompt_toolkit for advanced input handling and …
Browse files Browse the repository at this point in the history
…rich for output formatting

- Added prompt_toolkit PromptSession to handle multi-line input, history, and cursor movement.
- Integrated rich for rendering Markdown and colorized output.
- Adjusted input processing to pass user queries to the assistant via create_message.
- Ensured the output is displayed using rich's console.print for proper formatting.
- Included error handling for invalid commands and exceptions during execution.
  • Loading branch information
Estrada Irribarra, Rodrigo Andres committed Oct 23, 2024
1 parent f6fa3fb commit afa4f2c
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 30 deletions.
4 changes: 1 addition & 3 deletions examples/example_usage.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ while [[ "$#" -gt 0 ]]; do
done

# Ejecuta los comandos con la variable COMMAND, que puede ser 'poetry run storycraftr' o 'storycraftr'
$COMMAND init "La Purga de los dioses" --primary-language "es" --alternate-languages "en" --author "Rodrigo Estrada" --genre "science fiction" --behavior "behavior.txt" --reference-author="Brandon Sanderson"

cd "La Purga de los dioses"
$COMMAND init "The Purge of the gods" --primary-language "en" --alternate-languages "es" --author "Rodrigo Estrada" --genre "science fiction" --behavior "behavior.txt" --reference-author="Brandon Sanderson"

$COMMAND outline general-outline "Summarize the overall plot of a dystopian science fiction where advanced technology, resembling magic, has led to the fall of humanity’s elite and the rise of a manipulative villain who seeks to destroy both the ruling class and the workers."

Expand Down
10 changes: 5 additions & 5 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ rich = "^13.9.2"
python-dotenv = "^1.0.1"
pyyaml = "^6.0.2"
requests = "^2.32.3"
prompt-toolkit = "^3.0.48"

[tool.poetry.dev-dependencies]
pytest = "^6.2.4"
Expand Down
4 changes: 3 additions & 1 deletion storycraftr/agent/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,10 @@ def create_or_get_assistant(book_path: str, progress: Progress = None, task=None
assistant = client.beta.assistants.create(
instructions=instructions,
name=name,
tools=[{"type": "code_interpreter"}, {"type": "file_search"}],
tools=[{"type": "file_search"}],
model="gpt-4o",
temperature=0.7, # Nivel de creatividad balanceado
top_p=1.0, # Considerar todas las opciones
)

client.beta.assistants.update(
Expand Down
60 changes: 39 additions & 21 deletions storycraftr/cmd/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from storycraftr.utils.core import load_book_config
from storycraftr.agent.agents import get_thread, create_or_get_assistant, create_message
from storycraftr.cmd import iterate, outline, worldbuilding, chapters
from prompt_toolkit import PromptSession
from prompt_toolkit.history import InMemoryHistory

console = Console()

Expand Down Expand Up @@ -39,37 +41,53 @@ def chat(book_path=None):
assistant = create_or_get_assistant(book_path)
thread = get_thread()

session = PromptSession(history=InMemoryHistory())

console.print("[bold green]USE help() to get help and exit() to exit[/bold green]")

while True:
user_input = console.input("[bold blue]You:[/bold blue] ")

if user_input.lower() == "exit()":
console.print("[bold red]Exiting chat...[/bold red]")
break
try:
# Capture user input with prompt_toolkit
user_input = session.prompt("You: ")

if user_input.lower() == "help()":
display_help()
continue
if user_input.lower() == "exit()":
console.print("[bold red]Exiting chat...[/bold red]")
break

if user_input.startswith("!"):
execute_cli_command(user_input[1:])
continue
if user_input.lower() == "help()":
display_help()
continue

user_input = (
f"Answer the next prompt formatted on markdown (text): {user_input}"
)
if user_input.startswith("!"):
execute_cli_command(user_input[1:])
continue

try:
response = create_message(
book_path, thread_id=thread.id, content=user_input, assistant=assistant
# Pass the user input to the assistant for processing
user_input = (
f"Answer the next prompt formatted on markdown (text): {user_input}"
)

try:
# Generate the response
response = create_message(
book_path,
thread_id=thread.id,
content=user_input,
assistant=assistant,
)

# Render Markdown response
markdown_response = Markdown(response)
console.print(markdown_response)

except Exception as e:
console.print(f"[bold red]Error: {str(e)}[/bold red]")

except KeyboardInterrupt:
console.print("[bold red]Exiting chat...[/bold red]")
break
except Exception as e:
console.print(f"[bold red]Error: {str(e)}[/bold red]")
continue

markdown_response = Markdown(response)
console.print(markdown_response)


def execute_cli_command(user_input):
Expand Down

0 comments on commit afa4f2c

Please sign in to comment.