| # my_memory_logic.py | |
| import os | |
| # Import the PipelineRunnable from pipeline.py | |
| from pipeline import pipeline_runnable | |
| from langchain_core.chat_history import BaseChatMessageHistory | |
| from langchain_community.chat_message_histories import ChatMessageHistory | |
| from langchain_core.runnables.history import RunnableWithMessageHistory | |
| ############################################################################### | |
| # 1) In-memory store: session_id -> ChatMessageHistory | |
| ############################################################################### | |
| store = {} # e.g. { "abc123": ChatMessageHistory() } | |
| def get_session_history(session_id: str) -> BaseChatMessageHistory: | |
| if session_id not in store: | |
| store[session_id] = ChatMessageHistory() | |
| return store[session_id] | |
| ############################################################################### | |
| # 2) RunnableWithMessageHistory referencing pipeline_runnable | |
| ############################################################################### | |
| conversational_rag_chain = RunnableWithMessageHistory( | |
| pipeline_runnable, # The Runnable from pipeline.py | |
| get_session_history, | |
| input_messages_key="input", | |
| history_messages_key="chat_history", | |
| output_messages_key="answer" | |
| ) | |
| ############################################################################### | |
| # 3) Convenience function to run a query with session-based memory | |
| ############################################################################### | |
| def run_with_session_memory(user_query: str, session_id: str) -> str: | |
| """ | |
| Calls our `conversational_rag_chain` with session_id, | |
| returns the final 'answer' from pipeline_runnable. | |
| """ | |
| response = conversational_rag_chain.invoke( | |
| {"input": user_query}, | |
| config={ | |
| "configurable": { | |
| "session_id": session_id | |
| } | |
| } | |
| ) | |
| return response["answer"] | |