pythonadvanced
LangChain Agent with Persistent Memory
Build an AI agent that persists conversation context across sessions using LangChain memory stores.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonintermediate
LangChain Conversation with Memory
Maintain conversation context across turns using LangChain memory modules.
Best for: Multi-turn chatbots
#ai#langchain
pythonintermediate
LangChain Tool-Using Agent
Build a LangChain agent with custom tools for web search, calculator, and Python REPL.
Best for: AI agents
#langchain#agent
pythonintermediate
LangChain Conversation with Memory
Build a stateful chatbot that remembers conversation history using LangChain memory.
Best for: stateful chatbots
#langchain#memory
pythonadvanced
LangChain SQL Database Agent
Create an AI agent that answers natural language questions by querying a SQL database.
Best for: NL2SQL
#langchain#sql