LangChain ReAct Agent with Memory and Tools
March 24, 2025
AI AgentReAct AgentsToolsMemory
🛠️ Building a LangChain ReAct Agent with Memory and Tools
LangChain's structured agents enable powerful interaction patterns, especially when paired with memory and tools. In this post, we'll create a conversational AI assistant that can:
- Remember past interactions
- Answer real-time questions
- Use tools like current time and Wikipedia search
🛠️ Features
- Uses
ConversationBufferMemory
to track conversation history - Supports external tools for dynamic responses
- Handles parsing errors gracefully
1from dotenv import load_dotenv
2from langchain import hub
3from langchain.agents import AgentExecutor, create_structured_chat_agent
4from langchain.memory import ConversationBufferMemory
5from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
6from langchain_core.tools import Tool
7from langchain_openai import ChatOpenAI
8import datetime
9from wikipedia import summary
10
11load_dotenv()
12
13def get_current_time(*args, **kwargs):
14 now = datetime.datetime.now()
15 return now.strftime("%I:%M %p")
16
17def search_wikipedia(query):
18 try:
19 return summary(query, sentences=2)
20 except:
21 return "I couldn't find any information on that."
22
23tools = [
24 Tool(name="Time", func=get_current_time, description="Useful for when you need to know the current time."),
25 Tool(name="Wikipedia", func=search_wikipedia, description="Useful for when you need to know information about a topic."),
26]
27
28prompt = hub.pull("hwchase17/structured-chat-agent")
29llm = ChatOpenAI(model="gpt-4o")
30
31memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
32
33agent = create_structured_chat_agent(llm=llm, tools=tools, prompt=prompt)
34
35agent_executor = AgentExecutor.from_agent_and_tools(
36 agent=agent,
37 tools=tools,
38 verbose=True,
39 memory=memory,
40 handle_parsing_errors=True,
41)
42
43initial_message = "You are an AI assistant that can provide helpful answers using available tools.
44If you are unable to answer, you can use the following tools: Time and Wikipedia."
45memory.chat_memory.add_message(SystemMessage(content=initial_message))
46
47while True:
48 user_input = input("User: ")
49 if user_input.lower() == "exit":
50 break
51
52 memory.chat_memory.add_message(HumanMessage(content=user_input))
53 response = agent_executor.invoke({"input": user_input})
54 print("Bot:", response["output"])
55 memory.chat_memory.add_message(AIMessage(content=response["output"]))
🧠 Key Components
Tools
Two simple Python functions:
get_current_time
: gets the current time.search_wikipedia
: searches and returns a brief summary using Wikipedia.
Memory
1ConversationBufferMemory(memory_key="chat_history", return_messages=True)
This allows the agent to maintain memory across multiple turns.
Agent Setup
We use create_structured_chat_agent()
for cleaner tool interaction:
1agent = create_structured_chat_agent(llm=llm, tools=tools, prompt=prompt)
Executor
The AgentExecutor
connects everything and maintains state:
1agent_executor = AgentExecutor.from_agent_and_tools(...)
💬 Example Conversation
User: What time is it?
Bot: It is 04:17 PM.
User: Tell me about Python programming.
Bot: Python is a high level programming language... (Wikipedia summary)
User: What did I ask earlier?
Bot: You asked about the current time and Python programming.