■ SQLChatMessageHistory 클래스의 생성자에서 table_name/session_id/connection 인자를 사용해 SQLChatMessageHistory 객체를 만드는 방법을 보여준다.
※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다.
▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
from dotenv import load_dotenv from langchain_community.chat_message_histories import SQLChatMessageHistory from langchain_core.prompts import ChatPromptTemplate from langchain_core.prompts import MessagesPlaceholder from langchain_core.runnables.history import RunnableWithMessageHistory from langchain_openai import ChatOpenAI from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables.utils import ConfigurableFieldSpec load_dotenv() chatPromptTemplate = ChatPromptTemplate.from_messages( [ ("system", "You are a helpful assistant."), MessagesPlaceholder(variable_name = "chat_history"), ("human" , "{question}") ] ) runnableSequence = chatPromptTemplate | ChatOpenAI(model_name = "gpt-4o-mini") | StrOutputParser() def getChatHistory(user_id, session_id): return SQLChatMessageHistory( table_name = user_id, session_id = session_id, connection = "sqlite:///sqlite.db" ) configurableFieldSpecList = [ ConfigurableFieldSpec( id = "user_id", annotation = str, name = "User ID", description = "Unique identifier for a user.", default = "", is_shared = True ), ConfigurableFieldSpec( id = "session_id", annotation = str, name = "Session ID", description = "Unique identifier for a session.", default = "", is_shared = True ) ] runnableWithMessageHistory = RunnableWithMessageHistory( runnableSequence, getChatHistory, input_messages_key = "question", history_messages_key = "chat_history", history_factory_config = configurableFieldSpecList ) |
※ pip install python-dotenv langchain-community langchain_openai 명령을 실행한다.