Objectives
- Implement a user login system using Streamlit inputs.
- Link the active username to SQL-backed session storage (
SQLChatMessageHistory). - Render user-specific history dynamically on login.
- Add sidebar administrative controls (like clearing chat logs).
Plan
- User Authentication: Setup a sidebar input to accept a username. If no user is logged in, show an info prompt to block the interface.
- SQLite Connection: Once a username is entered, initialize
SQLChatMessageHistoryusing the username as the session identifier. - History Rendering: Retrieve and loop through past session messages from the database, displaying them in user/assistant bubbles.
- Chat Logic: Integrate chat inputs so new messages are immediately written to the local database, passed to the model (initialized via core abstractions), and the resulting AI response is saved back to SQLite.
- Clear Controls: Implement a sidebar button that executes
chat_history.clear()to erase logs and resets the interface.
Step-by-Step Implementation
Let’s build the Custom ChatGPT Clone incrementally step-by-step:Step 1: Imports and Page Config
Plan:- Import
streamlit,SQLChatMessageHistory, and message schemas. - Load environment variables.
- Configure the browser page title and icon using
st.set_page_config.
Step 2: Sidebar Authentication
Plan:- Create a text input box in the sidebar for the username.
- Use an
if username:check to block execution of the chatbot until a valid session ID is provided.
Step 3: Initialize SQLite Persistent History & Model
Plan:- Setup connection variables and instantiate
SQLChatMessageHistoryinside the authentication block. - Add a default
SystemMessageif the session history is brand new. - Initialize the chat model using
init_chat_model.
Step 4: Render Saved Logs, Input Loops, and Clear Controls
Plan:- Loop through
chat_history.messagesto render user and assistant message bubbles. - Collect chat inputs, save them to the database, invoke the model, render the AI’s reply, and save it.
- Add a sidebar clear button that invokes
.clear()on the database history.
Combined Code
Combining all the steps above gives the final complete script:Exercise: Dynamic Model Swapper 🔀
Goal
Extend the sidebar options to include a model selector selectbox (st.sidebar.selectbox) that allows the logged-in user to swap between Llama (llama-3.3-70b-versatile via Groq) and Gemini (gemini-2.5-flash via Google GenAI) models dynamically without resetting the conversation history.
Plan
- Add a selectbox in the sidebar containing model strings:
"Llama 3.3 (Groq)"and"Gemini 2.5 (Google)". - Based on selection, set the corresponding
model_nameandmodel_providerparameters. - Pass these parameters to the
init_chat_modelinstantiation inside the app execution.
Solution
Solution