Error: KeyError: 'st.session_state has no key "messages"

Summary

Am running into the following error - KeyError: 'st.session_state has no key “messages”

Steps to reproduce

Code snippet:

import os
from collections import defaultdict

os.environ['OPENAI_API_KEY'] = '<enter API key>'
os.environ["LANGCHAIN_TRACING_V2" ] = "true"
os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
os.environ["LANGCHAIN_API_KEY"] = '<enter API key>'
os.environ["LANGCHAIN_PROJECT"] = "Chatbot"

import openai
import streamlit as st

st.title("name")

if "openai_model" not in st.session_state:
    st.session_state["openai_model"] = "<enter model>"

st.session_state.messages = []
st.session_state.setdefault("messages", [])
messages = defaultdict(list, st.session_state.messages)

for message in messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

if prompt := st.chat_input("What is up?"):
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    with st.chat_message("assistant"):
        message_placeholder = st.empty()
        full_response = ""
        for response in openai.ChatCompletion.create(
            model=st.session_state["openai_model"],
            messages=[
                {"role": m["role"], "content": m["content"]}
                for m in st.session_state.messages
            ],
            stream=True,
        ):
            full_response += response.choices[0].delta.get("content", "")
            message_placeholder.markdown(full_response + "▌")
        message_placeholder.markdown(full_response)
    st.session_state.messages.append({"role": "assistant", "content": full_response})

Debug info

  • Streamlit version: 1.26.0(get it with $ streamlit version)
  • Python version: 3.10.8 (get it with $ python --version)
  • Using Conda? PipEnv? PyEnv? Pex?
  • OS version:Replit
  • Browser version:

@Anshul_Bhide
You need to check whether the key messages exists or not in the st.session_state. Just like you did for the openai_model.

1 Like

Check out this thread

1 Like

st.session_state.messages = [] removing this line from your code should fix the issue I believe

Updated the code as below and still getting the same error :frowning:

import os
from collections import defaultdict

os.environ[‘OPENAI_API_KEY’] = ‘’
os.environ[“LANGCHAIN_TRACING_V2” ] = “true”
os.environ[“LANGCHAIN_ENDPOINT”] = “https://api.smith.langchain.com
os.environ[“LANGCHAIN_API_KEY”] =‘’
os.environ[“LANGCHAIN_PROJECT”] = “Chatbot”

import openai
import streamlit as st

st.title(“Mom chatbot”)

if “openai_model” not in st.session_state:
st.session_state[“openai_model”] = “‘’”

if “messages” not in st.session_state:
st.session_state[“messages”] =

for message in st.session_state[“messages”]:
with st.chat_message(message[“role”]):
st.markdown(message[“content”])

if prompt := st.chat_input(“What is up?”):
st.session_state.messages.append({“role”: “user”, “content”: prompt})
with st.chat_message(“user”):
st.markdown(prompt)

with st.chat_message("assistant"):
    message_placeholder = st.empty()
    full_response = ""
    for response in openai.ChatCompletion.create(
        model=st.session_state["openai_model"],
        messages=[
            {"role": m["role"], "content": m["content"]}
            for m in st.session_state.messages
        ],
        stream=True,
    ):
        full_response += response.choices[0].delta.get("content", "")
        message_placeholder.markdown(full_response + "▌")
    message_placeholder.markdown(full_response)
st.session_state.messages.append({"role": "assistant", "content": full_response})

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.