Below is one common cause and fix for the error you’re seeing.
The Issue
Streamlit’s session state is a dictionary-like object. In your code you initialize values with key‑access (e.g. st.session_state["retriever"]) but later inside your lambdas you access them using dot‑notation (e.g. st.session_state.retriever). When a key isn’t automatically turned into an attribute (which is not guaranteed), using dot‑notation can raise the error:
st.session_state has no attribute "retriever"
The Fix
Replace all dot‑notation accesses for session state keys with dictionary‐style key accesses. For example, modify this lambda:
"context": lambda x: format_docs(st.session_state.retriever.get_relevant_documents(x["question"]))
to use key‑access like this:
"context": lambda x: format_docs(st.session_state["retriever"].get_relevant_documents(x["question"]))
Make sure that any time you refer to session state values (retriever, chain, etc.), you do so using the bracket notation. This should fix the error about a missing attribute because you’re always working with the keys you initialized.
Updated Code Snippet
Below is the adjusted part of your code from the initialize of the chain:
if "chain" not in st.session_state:
try:
st.session_state.chain = (
{
"context": lambda x: format_docs(
st.session_state["retriever"].get_relevant_documents(x["question"])
),
"question": lambda x: x["question"],
"chat_history": lambda x: x["chat_history"]
}
| st.session_state.prompt
| st.session_state.llm
| StrOutputParser()
)
st.write("Chain initialized.")
except Exception as e:
st.error(f"Failed to initialize chain: {e}")
Recap
- Ensure your session state items are always accessed with dictionary syntax (st.session_state["retriever"]) because session state does not automatically create dot‑attributes.
- Make sure initialize_session_state() runs before any code that attempts to access these keys.
This should address the error you encountered with the retriever in your RAG application using LangChain and Streamlit.