Building AI Agents with LangChain and Tool Use
Build tool‑using AI agents with LangChain (ReAct/Plan‑and‑Execute), memory, tool safety, and error handling — from idea to working demo.
By AI Mastermind Lab · Published 1 Mar 2026
AI Agents represent the leap from "Chatbots" to "Digital Workers." Instead of just generating text, an Agent plans a workflow and executes tools to accomplish goals. LangChain simplifies this via rigorous tool structuring.
1. Defining Tools
Tools must have explicit, strictly typed definitions using Pydantic. If you don't define exactly what the tool accepts, the LLM will hallucinate invalid API calls.
from langchain.tools import tool
from pydantic import BaseModel, Field
class WeatherParams(BaseModel):
city: str = Field(description="The city name, e.g., 'San Francisco'")
units: str = Field(description="Temperature units: 'celsius' or 'fahrenheit'")
@tool("get_weather", args_schema=WeatherParams)
def get_weather(city: str, units: str) -> str:
"""Gets the current weather for a specific city."""
# Fake API call
return f"The weather in {city} is 72 {units}."
2. Structuring the Agent
Agents typically operate on a ReAct (Reason + Act) loop:
- Thought: What do I need to do next?
- Action: Choose a tool.
- Action Input: Provide the JSON input.
- Observation: What did the tool return?
- Repeat until the task is complete.
from langchain_openai import ChatOpenAI
from langchain.agents import create_openai_tools_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
tools = [get_weather]
llm = ChatOpenAI(model="gpt-4o", temperature=0)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant with access to tools. Always use them when required."),
("placeholder", "{chat_history}"),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
# Create and execute
agent = create_openai_tools_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
result = agent_executor.invoke({"input": "What's the weather like in Tokyo right now in celsius?"})
print(result["output"])
Safety First
Never deploy agents with read/write database tools or email APIs without Human-in-the-loop (HITL) approvals. An LLM can easily misinterpret a command and autonomously drop a production table or send a sensitive email.