Muhammad Ikhwan Perwira
Muhammad Ikhwan Perwira

Reputation: 1072

Change placeholder based on latest chat input streamlit

I have this code that supposed to change placeholder dynamically based on latest user input:

def main():
  last_prompt = st.session_state.get(
      "last_prompt", "A cat detective interrogating a suspicious goldfish in a bubble-filled aquarium courtroom.")
  prompt_input = st.chat_input(last_prompt)

  if prompt_input:
    st.session_state.last_prompt = prompt_input

But it's not working as I expected, the placeholder still show default placeholder instead of latest chat input. enter image description here

Upvotes: 1

Views: 31

Answers (2)

Qian
Qian

Reputation: 597

I believe the problem you encountered is caused by this line of code:

prompt_input = st.chat_input(last_prompt)

last_prompt is only a local variable; it won't be responsible for updating dynamically. You need to use the state variable st.session_state.last_prompt. So the code can be changed as:

prompt_input = st.chat_input(st.session_state.last_prompt)

Besides, as you also have a default value, which is "A cat detective interrogating a suspicious goldfish in a bubble-filled aquarium courtroom." You can have a logic before the state happens

if "last_prompt" not in st.session_state:
        st.session_state.last_prompt = "A cat detective interrogating a suspicious goldfish in a bubble-filled aquarium courtroom."

Upvotes: 1

Muhammad Ikhwan Perwira
Muhammad Ikhwan Perwira

Reputation: 1072

Using st.rerun solved my problem, but I don't know whether this will be performance issue since I heard there is fragmenting mechanism scope.

def main():
  last_prompt = st.session_state.get(
      "last_prompt", "A cat detective interrogating a suspicious goldfish in a bubble-filled aquarium courtroom.")
  prompt_input = st.chat_input(last_prompt)

  if prompt_input:
    if prompt_input != st.session_state.last_prompt:
      st.session_state.last_prompt = prompt_input
      st.rerun()
  
  # rest of my code...

Upvotes: 1

Related Questions