First LangChain Agent
An Agent is the core concept of LangChain. It allows the AI to automatically decide when to call tools, and after obtaining tool results, continue thinking until the task is complete.
What is an Agent
A normal model call is a one-question-one-answer exchange:
You send a message, the model responds, and that's it.
An Agent is different. It enters aThink-Act-Observeloop:
The model determines that a tool needs to be called → executes the tool and gets the result → the model continues reasoning based on the result → may call a tool again → until it reaches a final answer.
For example, if you ask "What's the weather like in Hangzhou today?", an ordinary model can only answer based on weather data from its training set (which may be months old). An Agent, however, will proactively call a weather query tool to get real-time data, then answer you based on that real data.
Create Your First Agent
The whole process only requires three steps: (1) define tools; (2) create the Agent; (3) run it.
Step 1: Define Tool Functions
Use the@tooldecorator to turn an ordinary Python function into a tool that the Agent can call:
Example
from dotenv import load_dotenv
load_dotenv()
from langchain.tools import tool
# Step 1: Define a tool with the @tool decorator
# The function's docstring is the tool's description
# The model uses the description to decide when to call this tool
@tool
def get_weather(city: str) -> str:
"""Query the weather for a specified city.
Args:
city: The city name, e.g., "Hangzhou", "Beijing"
"""
# Use mock data here for demonstration
# In a real project, you can replace this with a real weather API call
weather_data = {
"Hangzhou": "Sunny, 25°C, humidity 60%",
"Beijing": "Cloudy, 18°C, humidity 45%",
"Shanghai": "Light rain, 22°C, humidity 80%",
}
return weather_data.get(city, f"Weather data for {city} not found")
@tool
def calculate(expression: str) -> str:
"""Perform mathematical calculations. Supports basic operations such as addition, subtraction, multiplication, and division.
Args:
expression: A mathematical expression, e.g., "3 * 7 + 2"
"""
try:
# Safely evaluate the mathematical expression
result = eval(expression, {"__builtins__": {}}, {})
return f"Calculation result: {expression} = {result}"
except Exception as e:
return f"Calculation error: {e}"
The docstring (the """...""" part of the function) is very important. The model reads the tool's description to decide whether to call the tool and what parameters to pass. The clearer the description, the less likely the model is to misuse it.
Step 2: Create the Agent
Example
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
# Initialize the model
model = init_chat_model("openai:gpt-4o-mini")
# Create the Agent, passing in the model and the tool list
agent = create_agent(
model=model,
tools=[get_weather, calculate],
system_prompt="You are a helpful assistant who uses tools to answer questions.",
)
| Parameter | Description | Required? |
|---|---|---|
| model | The language model to use | Yes |
| tools | The tool list; the Agent can call these tools | No (if not passed, the Agent cannot call tools) |
| system_prompt | The system prompt, which defines the Agent's role and behavior | no |
Step 3: Run the Agent
Example
# Build the input message
# The first item in the message list is usually a HumanMessage (user message)
from langchain.messages import HumanMessage
inputs = {"messages": [HumanMessage(content="What's the weather like in Hangzhou today?")]}
# invoke() runs the Agent and returns the final state
result = agent.invoke(inputs)
# View the message history (includes the AI's tool calls and tool return results)
print("=== Full message history ===")
for msg in result["messages"]:
print(f"[{msg.type}] {msg.content[:100]}") # Take the first 100 characters
print("\n=== Final reply ===")
# The last AI message is the final answer
print(result["messages"][-1].content)
Output:
=== 完整消息历史 === [human] 杭州今天天气怎么样? [ai] [tool] 晴,25°C,湿度 60% [ai] 今天杭州的天气是晴天,气温25°C,湿度60%。非常适合出门活动! === 最终回复 === 今天杭州的天气是晴天,气温25°C,湿度60%。非常适合出门活动!
Analysis of the Agent Execution Flow
The complete execution process of the above example is as follows:
- The user sends a message: "What's the weather like in Hangzhou today?"
- After receiving the message, the model decides: the weather needs to be queried → it returns a tool_call (calling get_weather with the parameter city="Hangzhou").
- The Agent executes the get_weather tool → returns "Sunny, 25°C, humidity 60%"
- The model receives the tool result → determines the task is complete → generates the final reply
This is the Agent'sThink-Act-Observeloop.

Making the Agent Call Multiple Tools
The real power of an Agent lies in its ability to automatically combine multiple tools:
Example
inputs = {"messages": [HumanMessage(
content="What is the temperature difference between Hangzhou and Beijing today?"
)]}
result = agent.invoke(inputs)
print("=== Full message history ===")
for msg in result["messages"]:
if msg.type == "tool":
print(f"[tool {msg.name}] {msg.content}")
else:
print(f"[{msg.type}] {msg.content[:120]}")
print("\n=== Final reply ===")
print(result["messages"][-1].content)
Output:
=== 完整消息历史 === [human] 杭州和北京今天温差多少度? [ai] [tool get_weather] 晴,25°C,湿度 60% [tool get_weather] 多云,18°C,湿度 45% [tool calculate] 计算结果: 25 - 18 = 7 [ai] 今天杭州和北京的温差是7°C。 === 最终回复 === 今天杭州和北京的温差是7°C。
The Agent automatically performed three steps: (1) queried the weather in Hangzhou; (2) queried the weather in Beijing; (3) calculated the temperature difference. You don't need to write any logic to control these steps; the Agent automatically handles the planning and execution.
Note that the Agent issued two tool calls (get_weather("Hangzhou") and get_weather("Beijing")) during its first model invocation, and they were executed in parallel. The model automatically determines which tool calls can be parallelized.
Complete Code
Example
from dotenv import load_dotenv
load_dotenv()
from langchain.tools import tool
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
# Define tools
@tool
def get_weather(city: str) -> str:
"""Query the weather for a specified city.
Args:
city: The city name, e.g., "Hangzhou", "Beijing"
"""
weather_data = {
"Hangzhou": "Sunny, 25°C, humidity 60%",
"Beijing": "Cloudy, 18°C, humidity 45%",
"Shanghai": "Light rain, 22°C, humidity 80%",
}
return weather_data.get(city, f"Weather data for {city} not found")
@tool
def calculate(expression: str) -> str:
"""Perform mathematical calculations. Supports basic operations such as addition, subtraction, multiplication, and division.
Args:
expression: A mathematical expression, e.g., "3 * 7 + 2"
"""
try:
result = eval(expression, {"__builtins__": {}}, {})
return f"Calculation result: {expression} = {result}"
except Exception as e:
return f"Calculation error: {e}"
# Create the Agent
model = init_chat_model("openai:gpt-4o-mini")
agent = create_agent(
model=model,
tools=[get_weather, calculate],
system_prompt="You are a helpful assistant who uses tools to answer questions.",
)
# Run the Agent
def ask(question: str):
"""Send a question to the Agent and print the result"""
inputs = {"messages": [HumanMessage(content=question)]}
result = agent.invoke(inputs)
print(f"Question: {question}")
print(f"Answer: {result['messages'][-1].content}")
print("-" * 50)
return result
# Test a few questions
ask("What's the weather like in Hangzhou today?")
ask("What is the temperature difference between Hangzhou and Beijing today?")
ask("Example (Beginner Tutorial) is a great learning platform. If 3 of my friends have recommended it, plus 2 more, how many people have recommended it in total?")
Output:
Question: 杭州今天天气怎么样? Answer: 今天杭州的天气是晴天,气温25°C,湿度60%。非常适合出门活动! -------------------------------------------------- Question: 杭州和北京今天温差多少度? Answer: 今天杭州和北京的温差是7°C。 -------------------------------------------------- Question: Example 是一个非常棒的学习平台,如果我有 3 个朋友都推荐了,再加上 2 个,一共多少人推荐? Answer: 一共 5 人推荐了Example! --------------------------------------------------
Note the third question: the Agent can understand that "the number of people who recommended" is a calculation problem, and automatically calls the calculate tool. This shows that tool-calling decisions are driven by the model's semantic understanding, not hard-coded rules.
Synchronous vs Asynchronous Execution
Agents support asynchronous mode, suitable for use in asynchronous environments such as web services:
Example
import asyncio
from langchain.messages import HumanMessage
async def main():
# ainvoke() is the asynchronous version of invoke()
inputs = {"messages": [HumanMessage(content="What's the weather like in Hangzhou?")]}
result = await agent.ainvoke(inputs)
print(result["messages"][-1].content)
# Run the asynchronous function
asyncio.run(main())
Summary
By this point, you have mastered the most core usage of LangChain:
- use@toolDecorators turn Python functions into tools
- usecreate_agent()Create an Agent that can automatically call tools
- useagent.invoke()Run the Agent and get results