Skip to content

Commit

Permalink
🐛 fix dollar in markdown
Browse files Browse the repository at this point in the history
  • Loading branch information
baptiste-pasquier committed Mar 27, 2024
1 parent d956532 commit 7269e90
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
4 changes: 3 additions & 1 deletion frontend/lib/basic_chat.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import streamlit as st

from .utils import format_string


def basic_chat():
user_question = st.chat_input("Say something")
Expand All @@ -13,4 +15,4 @@ def basic_chat():
response = chain.stream(user_question)

with st.chat_message("assistant"):
st.write(response)
st.write(format_string(response))
6 changes: 4 additions & 2 deletions frontend/lib/session_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

from frontend.lib.backend_interface import query

from .utils import format_string


@dataclass
class Message:
Expand All @@ -28,7 +30,7 @@ def session_chat():
with st.container(border=True):
for message in st.session_state.get("messages", []):
with st.chat_message(message.sender):
st.write(message.content)
st.write(format_string(message.content))

if user_question:
if len(st.session_state.get("messages", [])) == 0:
Expand All @@ -54,7 +56,7 @@ def session_chat():
placeholder = st.empty()
for chunk in response:
full_response += chunk
placeholder.write(full_response)
placeholder.write(format_string(full_response))

bot_message = Message("assistant", full_response, session_id)
st.session_state["messages"].append(bot_message)
Expand Down
34 changes: 34 additions & 0 deletions frontend/lib/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""Utility functions for the frontend."""

import re


def protect_dollar(string: str) -> str:
r"""Escape unescaped dollar signs in a string.
This function takes a string and returns a new string where all dollar signs ($)
that are not preceded by a backslash (\) are escaped with an additional backslash.
This is useful for preparing strings that contain dollar signs for environments
where the dollar sign may be interpreted as a special character, such as in
Markdown.
Args:
string (str): The input string containing dollar signs to be escaped.
Returns:
str: A new string with unescaped dollar signs preceded by a backslash.
"""
return re.sub(r"(?<!\\)\$", r"\$", string)


def format_string(string: str) -> str:
"""Format a string for safe Markdown usage.
Args:
string (str): The input string to be formatted.
Returns:
str: The formatted string.
"""
string = protect_dollar(string)
return string

0 comments on commit 7269e90

Please sign in to comment.