Memory Using SQLite
Author: Heesun Moon
Proofread : Juni Lee
This is a part of LangChain Open Tutorial
Overview
This tutorial explains the SQLChatMessageHistory class, which allows storing chat history in any database supported by SQLAlchemy.
Structured Query Language (SQL) is a domain-specific language used in programming and designed for managing data held in a Relational Database Management System (RDBMS), or for stream processing in a Relational Data Stream Management System (RDSMS). It is particularly useful for handling structured data, including relationships between entities and variables.
SQLAlchemy is an open-source SQL toolkit and Object-Relational Mapper (ORM) for the Python programming language, released under the MIT License.
To use a database other than SQLite, please make sure to install the appropriate database driver first.
Table of Contents
References
Environment Setup
Set up the environment. You may refer to Environment Setup for more details.
[Note]
langchain-opentutorialis a package that provides a set of easy-to-use environment setup, useful functions and utilities for tutorials.You can checkout the
langchain-opentutorialfor more details.
You can alternatively set OPENAI_API_KEY in .env file and load it.
[Note] This is not necessary if you've already set OPENAI_API_KEY in previous steps.
Usage
To use the storage, you need to provide only the following 2 things:
session_id- A unique identifier for the session, such as a user name, email, chat ID, etc.connection- A string that specifies the database connection. This string will be passed to SQLAlchemy'screate_enginefunction.
Now, let's check the stored conversation history.
You can also clear the session memory from db:
Adding Metadata
Metadata can be added by directly creating HumanMessage and AIMessage objects. This approach enables flexible data handling and logging.
Parameters:
additional_kwargs- Stores custom tags or metadata, such as priority or task type.response_metadata- Captures AI response details, including model, timestamp, and token count.
These fields enhance debugging and task tracking through detailed data storage.
Chaining
You can easily integrate this chat history class with LCEL Runnables.
The following shows how to create a function that returns chat history from sqlite.db.
Set config_fields to provide reference information when retrieving conversation details.
Set the "user_id" and "conversation_id" key-value pairs under the "configurable" key.
Let's ask a question about the name. If there is any previously saved conversation history, it will provide the correct response.
Use the
invokemethod of thechain_with_historyobject to generate an answer to the question.Pass a question dictionary and
configsettings to theinvokemethod as inputs.
This time, set the same user_id but use a different value for conversation_id.
Last updated