I tried the example chatbot code on the streamlit website [link].(Streamlit • A faster way to build and share data apps)
I have 2 questions.
- Why do I need to add
if "messages" not in st.session_state:
here? When the chatbot is first run, it’s obvious thatmessages
won’t exist, so why doesn’t it work if I just write a code withst.session_state
without the if statement?"
if "messages" not in st.session_state:
st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you?"}]
- Why is the code for generating chatbot responses and adding them to the chat window all placed under
if prompt := st.chat_input():
? This if statement runs when there is user input, but why does it behave like a for loop, running continuously instead of just once?
if prompt := st.chat_input():
if not openai_api_key:
st.info("Please add your OpenAI API key to continue.")
st.stop()
client = OpenAI(api_key=openai_api_key)
st.session_state.messages.append({"role": "user", "content": prompt})
st.chat_message("user").write(prompt)
response = client.chat.completions.create(model="gpt-3.5-turbo", messages=st.session_state.messages)
msg = response.choices[0].message.content
st.session_state.messages.append({"role": "assistant", "content": msg})
st.chat_message("assistant").write(msg)```