Objectives
- Configure session state memory to retain message history across page reruns.
- Render user and assistant chat message containers.
- Hook Streamlit chat inputs to LangChain’s invocation pipeline.
Streamlit Chatbot App
Goal
Build a graphical web application where users can type messages and receive chat replies from a Groq-provided Llama model in real-time.User Interface Layout
- Title Banner: Displays a header ”💬 LangChain Streamlit Chatbot”.
- Chat Window: Shows user queries in a chat box on the right, and AI assistant answers on the left.
- Chat Input Field: Pinned to the bottom of the screen for user inputs.
Plan
- Import
streamlit,init_chat_model, and message schemas. - Initialize the chat model using
init_chat_model("llama-3.3-70b-versatile", model_provider="groq"). - Check and initialize
st.session_state.messageslist with a defaultSystemMessage. - Loop through existing session messages to render them in containers using
st.chat_message. - Capture user inputs using
st.chat_input, append to history, invoke the model, render the response, and append the response back to history.
Code Implementation
Let’s build the Streamlit application incrementally step-by-step:Step 1: Imports and Setup
We start by importingstreamlit, the unified init_chat_model initializer, and message schemas. We then load environment variables:
Step 2: Initialize Model and Message State
We set up page headers and check if our model and chat history list exist inst.session_state. This ensures our state objects persist across page reruns:
Step 3: Render Message History
We loop throughst.session_state.messages and render human queries and AI answers inside Streamlit’s native bubble containers (st.chat_message). We skip rendering the SystemMessage:
Step 4: Handle Chat Input and Response
We query a text box usingst.chat_input. When the user enters a prompt, we render it, append it to st.session_state.messages, query the model with the entire history, display the response inside a spinner, and append the reply to history.
[!NOTE] The Walrus Operator (:=): The syntaxif prompt := st.chat_input("What is on your mind?"):uses Python’s assignment expression (walrus operator) to:
- Assign the user’s input string returned by
st.chat_inputdirectly to thepromptvariable.- Evaluate the condition; if the input is not empty/submitted, the condition resolves to
Trueand executes the code block. If no input is submitted, it resolves toFalseand skips execution.
Step 5: Complete Application Code
Combining all the steps above gives the final completed script:Exercise: Custom System Prompt Selector 🎨
Goal
Add a sidebar dropdown (st.sidebar.selectbox) that allows the user to select the chatbot’s persona (e.g., “Math Tutor”, “French Translator”, “Creative Writer”) and updates the initial SystemMessage dynamically.
Sample Input
Sidebar selection:"French Translator"
Sample Output
Assistant greets the user and performs translations accordingly.Plan
- Add a selectbox in the sidebar containing the different persona options.
- Based on selection, retrieve the corresponding system instruction text.
- If the selection changes, clear the session messages list and re-initialize it with the new
SystemMessageto start a fresh context.
Solution
Solution