Day 5 of LangChain Series: Unpacking the AI “Think‑Act” Loop with Agents and Tools
This article explains how LangChain agents use a ReAct (Reasoning‑Acting) loop to decide when and which tools to invoke, shows built‑in and custom tools via the @tool decorator, compares ReAct with GPT‑4 native tool calling, and demonstrates a research‑assistant workflow that cuts report drafting time from hours to minutes.
Agent Architecture – ReAct Loop
The core of a LangChain agent is a reasoning‑acting loop. For each user input the model executes:
Think : reason about the next step and decide whether a tool is needed.
Action : invoke the selected tool.
Observation : feed the tool’s result back into the context and repeat until the model outputs a final answer.
┌───────────────────────────────────────┐
│ ReAct Agent Loop │
│ Input → Think → Action → Observation │
│ (repeat) │
│ Output │
└───────────────────────────────────────┘Built‑in Tools
LangChain ships with ready‑to‑use tools. Example installing the DuckDuckGo search dependency and invoking two tools:
# pip install ddgs # required for DuckDuckGoSearchRun
from langchain_community.tools import DuckDuckGoSearchRun, WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper
search = DuckDuckGoSearchRun()
wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())
result = search.invoke("LangChain latest version")
print(result)Custom Tools with @tool
Any Python function can be turned into an agent‑callable tool by decorating it with @tool. The decorator records the function name and description, which the model uses to decide when to call the tool.
from langchain_core.tools import tool
@tool
def get_weather(city: str) -> str:
"""Query city weather, must pass a Chinese city name"""
weather_data = {
"北京": "晴,25°C",
"上海": "多云,28°C",
"深圳": "雷阵雨,30°C",
}
return weather_data.get(city, f"未找到 {city} 的天气数据")
@tool
def get_date(days_from_now: int) -> str:
"""Calculate the date N days from today"""
from datetime import datetime, timedelta
future = datetime.now() + timedelta(days=days_from_now)
return future.strftime("%Y年%m月%d日")
print(get_weather.name) # get_weather
print(get_weather.description) # 查询城市天气,必须传入中文城市名Creating a ReAct Agent
Use create_agent (based on LangGraph) together with a ChatOpenAI model and the defined tools.
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
from langchain_core.tools import tool
@tool
def get_weather(city: str) -> str:
...
@tool
def calculator(expr: str) -> str:
return str(eval(expr))
model = ChatOpenAI(model="Pro/MiniMaxAI/MiniMax-M2.5", temperature=0)
agent = create_agent(
model,
tools=[get_weather, calculator],
system_prompt="你是一个智能助手,可以调用工具来回答问题。"
)
result = agent.invoke({"messages": [{"role": "user", "content": "北京和深圳的天气差异大吗?用计算器算一下温度差"}]})
print(result["messages"][-1].content)Sample output:
根据查询,北京今天天气晴朗,气温约25°C。Multi‑Tool Chaining: Search → Summarize → Answer
Combine a search tool with a custom summarizer and feed both into the agent.
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
from langchain_community.tools import DuckDuckGoSearchRun
from langchain_core.tools import tool
search = DuckDuckGoSearchRun()
@tool
def summarize_text(text: str, max_length: int = 50) -> str:
if len(text) <= max_length:
return text
return text[:max_length] + "..."
model = ChatOpenAI(model="Pro/MiniMaxAI/MiniMax-M2.5", temperature=0)
agent = create_agent(
model,
tools=[search, summarize_text],
system_prompt="你是一个研究助手,帮助用户搜索信息并总结。"
)
result = agent.invoke({"messages": [{"role": "user", "content": "搜索 LangChain 最新动态,然后总结成一段50字以内的短文"}]})
print(result["messages"][-1].content)Tool Calling vs. ReAct
GPT‑4 (and Claude‑sonnet‑4‑6+) provide native tool calling, allowing the model to select a tool in a single step. ReAct requires explicit step‑by‑step reasoning.
Model requirement : Tool Calling – GPT‑4 / Claude‑sonnet‑4‑6+; ReAct – any model that supports function calls.
Calling method : Tool Calling – model chooses tool in one call; ReAct – iterative Think → Action → Observation loops.
Efficiency : Tool Calling – high (single call); ReAct – lower (multiple loops).
Suitable scenarios : Tool Calling – simple, well‑defined tasks; ReAct – complex tasks that need intermediate reasoning.
Practical Case: AI Research Assistant
A full‑stack agent is built with search, Wikipedia, and a custom save_notes tool. The workflow automatically performs "search → organize → save" and the article reports that draft generation time drops from two hours to five minutes.
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
from langchain_community.tools import DuckDuckGoSearchRun, WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper
from langchain_core.tools import tool
@tool
def save_notes(content: str, filename: str) -> str:
"""Save notes to a file"""
with open(f"/tmp/{filename}.md", "w") as f:
f.write(content)
return f"已保存到 /tmp/{filename}.md"
search = DuckDuckGoSearchRun()
wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())
model = ChatOpenAI(model="Pro/MiniMaxAI/MiniMax-M2.5", temperature=0)
agent = create_agent(
model,
tools=[search, wikipedia, save_notes],
system_prompt="你是一个专业的研究助手,帮助用户收集信息、整理笔记。"
)
result = agent.invoke({"messages": [{"role": "user", "content": "搜索 2026 年 AI Agent 的最新进展,整理成笔记保存"}]})Result: The agent completes the three‑step workflow and reduces report drafting time dramatically.
Day 5 Recap
ReAct : Reasoning + Acting loop where the model decides when to call tools.
@tool : Decorator for defining custom tools; the description guides the model’s decision.
create_agent : Constructs an agent using the new LangGraph‑based API.
Tool Calling : GPT‑4 native tool invocation, more efficient for simple tasks.
agent.invoke({"messages": [...]}) : New invocation style that passes a list of messages to the agent.
Related Links
LangChain Agent documentation: https://python.langchain.com/docs/concepts/agents/
ReAct paper: https://arxiv.org/abs/2210.03629
Tool Calling guide: https://python.langchain.com/docs/concepts/tool_calling/
Built‑in tools list: https://python.langchain.com/docs/integrations/tools/
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tech Ocean
Focused on AI programming, sharing ready-to-use development efficiency solutions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
