LangChain ReAct Agent: Using Tools to Answer Questions
March 24, 2025
AI AgentReAct AgentsTools
🛠️ LangChain ReAct Agent: Using Tools to Answer Questions
LangChain's ReAct agent framework allows language models to make decisions and interact with external tools. In this post, we'll walk through how to create a simple agent that uses a custom tool to answer the question: “What time is it?”
🧠 What’s the ReAct Pattern?
ReAct stands for Reasoning + Acting. It enables an agent to:
- Think step by step
- Use tools when needed
- Return a final answer
🔧 What We’re Building
- A custom tool to get the current time
- A ReAct agent using OpenAI’s GPT-4o
- An executor that ties it all together
1from dotenv import load_dotenv
2from langchain import hub
3from langchain.agents import AgentExecutor, create_react_agent
4from langchain_core.tools import Tool
5from langchain_openai import ChatOpenAI
6
7load_dotenv()
8
9def get_current_time(*args, **kwargs):
10 """Returns the current time in H:MM AM/PM format."""
11 import datetime
12 now = datetime.datetime.now()
13 return now.strftime("%I:%M %p")
14
15tools = [
16 Tool(
17 name="Time",
18 func=get_current_time,
19 description="Useful for when you need to know the current time",
20 ),
21]
22
23# Pull the prompt template from the hub
24prompt = hub.pull("hwchase17/react")
25
26llm = ChatOpenAI(model="gpt-4o", temperature=0)
27
28agent = create_react_agent(
29 llm=llm,
30 tools=tools,
31 prompt=prompt,
32 stop_sequence=True,
33)
34
35agent_executor = AgentExecutor.from_agent_and_tools(
36 agent=agent,
37 tools=tools,
38 verbose=True,
39)
40
41response = agent_executor.invo
42print(response)
🧱 How It Works
1. Define the Tool
This tool just returns the current time using Python's datetime
module:
1def get_current_time():
2 ...
2. Register the Tool
1Tool(name="Time", func=get_current_time, description="Useful for when you need to know the current time")
3. Use ReAct Prompt
We use a ReAct-style prompt from LangChain’s hub:
1prompt = hub.pull("hwchase17/react")
This allows the LLM to reason and decide whether to use a tool.
4. Execute with AgentExecutor
We create an agent executor that manages the interaction:
1agent_executor = AgentExecutor.from_agent_and_tools(...)
✅ Example Output
When asked:
"What time is it?"
the agent might respond:
The current time is 03:42 PM.
🚀 Why Use ReAct + Tools?
- Extend LLMs with real-time data
- Support tool use for calculations, APIs, or databases
- Create autonomous agents with decision-making skills