09. Save chat to SQLite

SQL (SQLAlchemy)

Structured Query Language (SQL) Domain-specific language used for silver programming, designed for managing data in relational database management systems (RDBMS) or for stream processing in relational data stream management systems (RDSMS). It is especially useful for dealing with structured data, including the relationship between entities and variables.

SQLAlchemy Is an open source for Python programming languages distributed according to MIT licenses SQL Toolkit and object relationship mapper (ORM).

In this laptop SQLAlchemy You can store chat records in any database supported by SQLChatMessageHistory Describe the class.

SQLite To use with a database other than, you need to install that database driver.

# API KEY A configuration file for managing environment variables
from dotenv import load_dotenv

# API KEY Load information
load_dotenv()
True

Usage

To use storage, only the following 2 are provided:

  1. session_id -A unique identifier for the session, such as username, email, chat ID, etc.

  2. connection -A string that specifies a database connection. This string is passed to SQLAlchemy's create_engine function.

from langchain_community.chat_message_histories import SQLChatMessageHistory

# SQLChatMessageHistory Create an object and set the session ID and database connection file.
chat_message_history = SQLChatMessageHistory(
    session_id="sql_history", connection="sqlite:///sqlite.db"
)
  • Check for saved conversation. chat_message_history.messages

We have this message recording class LCEL Runnables It can be easily combined with.

Apply to Chain

sqlite.db Create a function that brings in-conversation.

config_fields Set. This is used as a reference when viewing conversational information.

  • user_id : User ID

  • conversation_id : Conversation ID

  • "configurable" Under the key "user_id" , "conversation_id" Set the key-value pair.

Let's ask a question that asks for a name. If you have a conversation you saved earlier, you will answer it correctly.

  • chain_with_history Object invoke Call the method to generate an answer to the question.

  • invoke The method has a question dictionary config Settings are passed.

Same this time user_id I have conversion_id Set to have different values.

Last updated