Objectives
- Understand SQL-backed persistent history tracking.
- Store message loops dynamically in a local SQLite file using
SQLChatMessageHistory. - Retrieve and output logs for a specific session ID from a completely separate script.
SQLite Persistence
Unlike cloud databases, SQLite requires zero credentials or network configurations. It saves all logs locally inside a standard.db database file.
Goal
Implement a live terminal chat loop that saves queries to a local SQLite database, and create a second script to retrieve and print those saved conversation logs.Sample Input
Sample Output
Automatic storage of messages inside the local SQLite database.Plan
- Saver Script:
- Import
SQLChatMessageHistoryfromlangchain_community.chat_message_histories. - Instantiate the history object using the local database connection.
- Start a console chat loop, adding inputs and replies to the history.
- Import
- Retriever Script:
- Connect to the same SQLite database.
- Iterate through and print the history messages.
Code Implementation
1. Conversation Loop & Saver (5a_chat_model_save_message_history_sqlite.py)
Letβs build the SQLite saver application incrementally step-by-step:Step 1: Imports and Setup
Plan:- Import environment variable loader
load_dotenvfromdotenv. - Import
SQLChatMessageHistoryfromlangchain_community.chat_message_histories. - Import the unified model initializer
init_chat_modelfromlangchain.chat_models.
Step 2: Initialize Database Connection
Plan:- Set up a unique
SESSION_IDstring to identify this chat session. - Define the local connection URI
sqlite:///chat_history.db. - Instantiate the
SQLChatMessageHistoryobject.
Step 3: Setup Chat Model
Plan:- Initialize a Groq-provided Llama model (
llama-3.3-70b-versatile) using the core abstraction helperinit_chat_model.
Step 4: Execute Interactive Chat Loop
Plan:- Prompt user queries from the console in a
while Trueloop. - Call
.add_user_message()to persist the input in the SQL database. - Call
model.invoke()passing the current full message array. - Call
.add_ai_message()to persist the modelβs answer.
Combined Saver Code
Combining all the steps above gives the final completed script:2. Session Retriever Script (5b_chat_model_retrieve_message_history_sqlite.py)
Below is the retriever script that loads the SQL log independently and outputs the session chat logs:Exercise: Session Config Checker π
Goal
Write a python utility functioncheck_logs(session_id: str) that connects to our local SQLite database and prints how many human vs AI messages are currently stored for the given session.
Sample Input
Sample Output
Plan
- Instantiate the
SQLChatMessageHistoryinside the function. - Iterate through
.messagesand count human and ai instances. - Print the formatted totals.
Solution
Solution
Practice & Exercises
To practice, open the interactive notebook:Practice & Exercises
Practice configuring SQL databases locally for persistent conversation sessions.π» VS Code | π Colab | π₯ Download