pythonadvanced

LangChain Agent with Persistent Memory

Build an AI agent that persists conversation context across sessions using LangChain memory stores.

python
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_community.chat_message_histories import SQLChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_core.tools import tool

@tool
def get_current_time() -> str:
    '''Returns the current date and time.'''
    from datetime import datetime
    return datetime.now().isoformat()

llm    = ChatOpenAI(model='gpt-4o-mini')
prompt = ChatPromptTemplate.from_messages([('system','You are a helpful assistant.'), MessagesPlaceholder('history'), ('human','{input}'), ('placeholder','{agent_scratchpad}')])
agent  = create_tool_calling_agent(llm, [get_current_time], prompt)
executor = AgentExecutor(agent=agent, tools=[get_current_time])

def get_history(session_id: str):
    return SQLChatMessageHistory(session_id=session_id, connection_string='sqlite:///chat_history.db')

agent_with_history = RunnableWithMessageHistory(executor, get_history, input_messages_key='input', history_messages_key='history')

for msg in ['What time is it?', 'Remind me what you said about the time.']:
    r = agent_with_history.invoke({'input': msg}, config={'configurable': {'session_id': 'user_1'}})
    print(r['output'])

Use Cases

  • persistent agents
  • session management
  • stateful AI

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.