add cache and Rerun button

This commit is contained in:
kosarevskiydp 2023-03-02 21:32:09 +03:00
parent b496c9a95e
commit c643138384
2 changed files with 32 additions and 22 deletions

21
chat.py
View File

@ -24,14 +24,21 @@ with open(css_file) as f:
st.markdown(f"<h1 style='text-align: center;'>{PAGE_TITLE}</h1>", unsafe_allow_html=True) st.markdown(f"<h1 style='text-align: center;'>{PAGE_TITLE}</h1>", unsafe_allow_html=True)
st.markdown("---") st.markdown("---")
api_key = st.text_input(label="Input OpenAI API key:")
api_key = api_key_checker(api_key)
user_text = st.text_area(label="Start your conversation with AI:") def main() -> None:
api_key = st.text_input(label="Input OpenAI API key:")
api_key = api_key_checker(api_key)
if api_key and user_text: user_text = st.text_area(label="Start your conversation with AI:")
if st.button("Rerun"):
st.cache_data.clear()
if api_key and user_text:
try: try:
ai_content = send_ai_request(api_key, user_text) completion = send_ai_request(api_key, user_text)
if st.checkbox(label="Show Full API Response", value=False):
st.json(completion)
ai_content = completion.get("choices")[0].get("message").get("content")
if ai_content: if ai_content:
st.markdown(ai_content) st.markdown(ai_content)
st.markdown("---") st.markdown("---")
@ -44,3 +51,7 @@ if api_key and user_text:
show_player(ai_content, lang_code, is_speech_slow) show_player(ai_content, lang_code, is_speech_slow)
except AuthenticationError as err: except AuthenticationError as err:
st.error(err) st.error(err)
if __name__ == "__main__":
main()

View File

@ -46,7 +46,9 @@ def show_player(ai_content: str, lang_code: str, is_speech_slow: bool) -> None:
st.audio(sound_file) st.audio(sound_file)
def send_ai_request(api_key: str, user_text: str, ) -> str: @st.cache_data()
# @st.cache_data(suppress_st_warning=True)
def send_ai_request(api_key: str, user_text: str, ) -> Dict:
openai.api_key = api_key openai.api_key = api_key
completion = openai.ChatCompletion.create( completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo", model="gpt-3.5-turbo",
@ -57,10 +59,7 @@ def send_ai_request(api_key: str, user_text: str, ) -> str:
} }
] ]
) )
if st.checkbox(label="Show Full API Response", value=False): return completion
st.json(completion)
return completion.get("choices")[0].get("message").get("content")
def api_key_checker(api_key: str) -> str: def api_key_checker(api_key: str) -> str: