Embedding refresh avoid

Hi, im working with a local host app and have been trying to troubleshoot this for days:

The App is simple, it just takes as input some model and looker data (A BI Tool) and a User Request and based on these inputs returns an embed URL os the requested report via OpenAI. Until this point everything works perfect:

The problem comes when i execute the User Feedback. This, just takes two inputs from the user to update a sqlite database with the feedback. It works perfect but i do not get that when it is run, the page ALWAYS refresh and the embed Looker URL disappear.

Have been trying for days.

Here is the code:


st.set_page_config(page_title="Capital GPT", layout="wide")

st.markdown("""
    <style>
    html {
        zoom: 100%;
    }
    </style>
    """, unsafe_allow_html=True)

session = requests.Session()

authenticate()

if 'looker_loaded' not in st.session_state:
    st.session_state.looker_loaded = False

if 'rating' not in st.session_state:
    st.session_state.rating = 0

if 'user_feedback' not in st.session_state:
    st.session_state.user_feedback = ""

if 'response' not in st.session_state:
    st.session_state.response = ""

if 'looker_url' not in st.session_state:
    st.session_state.looker_url = ""

if 'response_suggestion' not in st.session_state:
    st.session_state.response_suggestion = ""

with st.sidebar:
    model_name = st.selectbox("Select the Model: ", ["09_BusinessDevelopment_RENW", "PMA_Data", "Gestion_Energia"])
    if model_name == "09_BusinessDevelopment_RENW":
        explore_name = st.selectbox("Select the Explore: ", ["data_product_sips"])
    elif model_name == "PMA_Data":
        explore_name = st.selectbox("Select the Explore: ", ["data_product_expedientes_eolica_solar"])
    elif model_name == "Gestion_Energia":
        explore_name = st.selectbox("Select the Explore: ", ["datos_crudos_tadeas", "datos_crudos_buseco", "datos_crudos_solana", "datos_crudos_loma_de_los_pinos"])

    dimensions = [[e['name'].replace(e['view'] + '.', ''), e['label_short'], e['description'], e['type']]
                for e in get_explore(model_name, explore_name)['fields']['dimensions']]

    dimensions_to_json = [dict(zip(['name', 'label_short', 'description', 'type'], item)) for item in dimensions]

    with st.form(key="user_request"):
        system_message = get_context(explore_name, model_name, dimensions_to_json)
        user_message = st.text_area("Enter query here: ", height=5, placeholder="Enter your query")
        launch_query = st.form_submit_button("πŸ’«")

if launch_query:

    with st.sidebar:

        st.header("User Feedback")
        feedback_form = st.form(key="Feedback")
        rating = feedback_form.slider(label="Rate the answer:", min_value=0, max_value=10)
        user_feedback = feedback_form.text_area(label="Give a detailed feedback comment about improvements or congratulations")
        feedback_button = feedback_form.form_submit_button("Send Feedback")

        if feedback_button:
            sqlite_process(user_message, st.session_state.response, rating, user_feedback, explore_name)
            st.success("Thanks for your feedback!")

    response = get_openai_response(model="gpt-4-1106-preview", system_message=system_message, user_message=user_message)
    st.session_state.response = response
    response_url, response_suggestion = show_looker_embed(response)
    st.session_state.looker_loaded = True
    st.session_state.looker_url = response_url
    st.session_state.response_suggestion = response_suggestion

And the functions, all of them are cached like this:

@st.cache_data
def show_looker_embed(response):
    iframe_width = 1400
    iframe_height = 700

    response_url = response.split('\n')[0]

    if len(response.split('\n')) > 1:
        response_suggestion = '\n'.join(response.split('\n')[1:])
        st.write(f"{response_suggestion}")
    else:
        response_suggestion = ""
    components.iframe(response_url, width=iframe_width, height=iframe_height)

    return response_url, response_suggestion

Hi

Checks if the st.empty() and st.write() combination allows the content to be updated without refreshing the page.

    response = get_openai_response(model="gpt-4-1106-preview", system_message=system_message, user_message=user_message)
    st.session_state.response = response
    response_url, response_suggestion = show_looker_embed(response)
    
    # Use st.empty() to create an empty container
    container = st.empty()
    
    # Use st.write() to update the container with the Looker URL
    container.write(f'<iframe width="1400" height="700" src="{response_url}"></iframe>', unsafe_allow_html=True)

    st.session_state.looker_loaded = True
    st.session_state.looker_url = response_url
    st.session_state.response_suggestion = response_suggestion

Γ“scar

Hello @GabiAnt95,

Here’s a simplified logic flow that might help:

if 'looker_url' in st.session_state and st.session_state.looker_url:
    # Display the iframe only if the URL is already in session state
    components.iframe(st.session_state.looker_url, width=1400, height=700)
else:
    # Logic to set st.session_state.looker_url based on user query
    # This block should only execute when necessary to update the URL

if feedback_button:
    # Handle feedback submission without affecting the looker_url session state
    sqlite_process(user_message, st.session_state.response, rating, user_feedback, explore_name)
    st.success("Thanks for your feedback!")
    # Consider a way to keep or refresh the iframe content here, if necessary

Hope this helps!

Kind Regards,
Sahir Maharaj
Data Scientist | AI Engineer

P.S. Lets connect on LinkedIn!

➀ Want me to build your solution? Lets chat about how I can assist!
➀ Join my Medium community of 30k readers! Sharing my knowledge about data science and AI
➀ Website: https://sahirmaharaj.com
➀ Email: sahir@sahirmaharaj.com
➀ 100+ FREE Power BI Themes: Download Now

4 Likes