LangChain Multi-Tool Personal Assistant
Earlier we introduced LangChain's Tools, Agent, Middleware, Structured Output, Streaming, and Checkpointer.
This chapter combines these capabilities to build a multi-tool personal assistant Agent.
This assistant can query the weather, view schedules, handle email requests, generate a structured daily summary based on the weather and schedule, and remember the chat content within the same session.
This project is based on LangChain 1.x, uses the DeepSeek chat model, and saves conversation state through SQLite.
**Note:** The weather, schedule, and email are all locally simulated features. The project does not access real weather services, Google Calendar, or mail servers, nor does it actually send emails.
I. System Features and Architecture
We want the personal assistant to have the following capabilities:
| Function | Implementation | Description |
|---|---|---|
| Weather query | get_weather Tool | Query simulated city weather |
| Schedule management | query_schedule Tool | View simulated schedules for a specified date |
| Email handling | send_email Tool + HITL | Request human confirmation before sending |
| structural summary | Pydantic + Structured Output | Generate DailySummary |
| Markdown display | to_markdown() | Render the daily summary |
| Execution process display | agent.stream() | Display model and tool execution steps |
| Conversation Memory | SqliteSaver | Save multi-turn session state |
| Dynamic date | @dynamic_prompt | Inject the current date and time zone |
System execution flow
用户发送自然语言指令
↓
LangChain Agent
↓
Dynamic Prompt
↓
模型判断
|
+-------+--------+
| | |
↓ ↓ ↓
天气工具 日程工具 邮件工具
| | |
| | ↓
| | 人工确认
| | ↓
+-------+--------+
↓
模型回复
↓
SqliteSaver 保存状态
Daily summary request:
天气数据 + 日程数据
↓
结构化摘要 Agent
↓
DailySummary
↓
Markdown
Note that the main Agent can decide on its own which tools to call, but the daily summary uses a separate structured generation step; ordinary email queries are not required to return a summary object.
II. Environment Preparation
Python 3.11 or a newer compatible version is recommended.
Create a virtual environment
python -m venv venv
Windows:
venv\Scripts\activate
macOS / Linux:
source venv/bin/activate
Install dependencies
python -m pip install -U langchain langchain-deepseek langgraph langgraph-checkpoint-sqlite pydantic python-dotenv
| Python Package | Purpose |
|---|---|
langchain |
Agent、Tools、Middleware |
langchain-deepseek |
DeepSeek model interface |
langgraph |
State and interruption recovery |
langgraph-checkpoint-sqlite |
SQLite conversation persistence |
pydantic |
Structured data validation |
python-dotenv |
Load environment variables |
Configure API Key
creation .env:
DEEPSEEK_API_KEY=your_deepseek_api_key
This tutorial only requires a DeepSeek API Key; no additional Embedding service configuration is needed, because RAG vector retrieval is not used.
3. Preparing simulated weather and schedules
To allow readers to test without integrating third-party weather and calendar APIs, we use Python dictionaries to store simulated data.
Unlike hardcoding a fixed 2024 date, this example generates schedules based on the program's run date.
Example: Simulated data
Example
from
datetime
import
datetime
,
timedelta
from
zoneinfo
import
ZoneInfo
TIMEZONE
=
ZoneInfo
(
"Asia/Shanghai"
)
def
today_str
(
)
str
:
return
datetime
.
now
(
TIMEZONE
)
.
date
(
)
.
isoformat
(
)
today
=
today_str
(
)
tomorrow
=
(
datetime
.
now
(
TIMEZONE
)
.
date
(
)
- timedelta
(
days
=
1
)
)
.
isoformat
(
)
weather_db
=
{
"Hangzhou"
:
{
"condition"
:
"Sunny"
,
"temp"
:
25
,
"humidity"
:
60
}
,
"Beijing"
:
{
"condition"
:
"Cloudy"
,
"temp"
:
18
,
"humidity"
:
45
}
,
"Shanghai"
:
{
"condition"
:
"Light rain"
,
"temp"
:
22
,
"humidity"
:
80
}
}
calendar_events
=
[
{
"id"
:
1
,
"date"
: today
,
"time"
:
"10:00"
,
"title"
:
"Team weekly meeting"
,
"duration"
:
"1 hour"
}
,
{
"id"
:
2
,
"date"
: today
,
"time"
:
"14:00"
,
"title"
:
"Python study"
,
"duration"
:
"2 hours"
}
,
{
"id"
:
3
,
"date"
: tomorrow
,
"time"
:
"15:00"
,
"title"
:
"Code review"
,
"duration"
:
"1.5 hours"
}
]
(
"Today:"
,
today
)
(
"Tomorrow:"
,
tomorrow
)
**Note:** These weather values are just fixed test data and cannot be used for real decisions such as travel or weather warnings.
A production project needs to integrate a real weather API and retain the data time, city, and source.
4. Tool 1: Weather query
Use @tool Define the weather tool.
The tool accepts a city name and queries the weather from the simulated database.
Example: get_weather
Example
from
langchain.
tools
import
tool
@
tool
def
get_weather
(
city:
str
)
str
:
"""Query the simulated weather for a specified city; this is not real-time weather."""
data
=
weather_db.
get
(
city.
strip
(
)
)
if
not
data:
return
f
"No simulated weather data for {city}. Supported: {', '.join(weather_db)}"
return
(
f
"Simulated weather for {city}: {data['condition']},"
f
"Temperature {data['temp']}°C,"
f
"Humidity {data['humidity']}%."
)
For example:
get_weather("杭州")
Tool returns:
杭州模拟天气:晴,温度 25°C,湿度 60%。
The Agent can convert this result into a more natural answer, but must not describe simulated weather as real-time weather.
5. Tool 2: Schedule query
The second tool is responsible for querying the schedule for a specified date.
If the user does not provide a date, today is queried by default.
Dates use the standard format:
YYYY-MM-DD
Example: query_schedule
Example
from
datetime
import
date
from
langchain.
tools
import
tool
@
tool
def
query_schedule
(
date_str:
str
=
""
)
str
:
"""Query the simulated schedule. date_str uses YYYY-MM-DD; leaving it empty means today."""
if
not
date_str:
date_str
=
today_str
(
)
try
:
date.
fromisoformat
(
date_str
)
except
ValueError
:
return
"Invalid date format; please use YYYY-MM-DD."
events
=
sorted
(
[
e
for
e
in
calendar_events
if
e
[
"date"
]
==
date_str
]
,
key
=
lambda
e: e
[
"time"
]
)
if
not
events:
return
f
"No simulated schedule for {date_str}."
lines
=
[
f
"Simulated schedule for {date_str}:"
]
for
event
in
events:
lines.
append
(
f
"- {event['time']} {event['title']}({event['duration']})"
)
return
"\n"
.
join
(
lines
)
If querying today, the output might be:
2026-10-13 的模拟日程:
- 10:00 团队周会(1小时)
- 14:00 Python 学习(2小时)
The dates here are only used to illustrate the format; the actual program reads the current day's date at runtime.
**Note:** The current schedule tool only supports reading; it does not support adding, deleting, or modifying schedules. You can continue adding later create_event、update_event and other tools.
6. Tool 3: Simulated email sending
Email sending is an operation with external side effects.
If the model were directly allowed to call real SMTP or a mail API, problems such as mis-sent emails, wrong recipients, or sensitive information leakage could occur.
Therefore, this tutorial adds a human confirmation step.
Execution flow:
用户要求发送邮件
↓
Agent 调用 send_email
↓
展示收件人、主题和正文
↓
interrupt() 暂停
↓
人工批准或拒绝
↓
模拟执行结果
Example: send_email
Example
from
langchain.
tools
import
tool
from
langgraph.
types
import
interrupt
@
tool
def
send_email
(
to:
str
,
subject:
str
,
body:
str
)
str
:
"""Simulate sending an email; human confirmation must be obtained first."""
decision
=
interrupt
(
{
"action"
:
"send_email"
,
"to"
: to
,
"subject"
: subject
,
"body"
: body
,
"message"
:
"Please confirm this simulated email."
}
)
if
not
isinstance
(
decision
,
dict
)
or
decision.
get
(
"approved"
)
is
not
True
:
return
"Email request cancelled; no email was sent."
return
(
f
"Simulated email operation approved: recipient {to},"
f
"subject '{subject}'. This program did not actually send an email."
)
There are two things to note here.
**First:** The tool returns the approval result only after approval is granted.
**Second:** This example does not call a real mail API, so it cannot return "email sent successfully" or fabricate an email ID.
If you want to integrate a real service, you should call the mail service after approval and confirm the sending status based on its actual response.
7. Dynamic prompts: Injecting date and time zone
A user might ask:
今天有什么安排?
明天下午有什么日程?
To help the model correctly understand "today" and "tomorrow", we can @dynamic_prompt dynamically inject the current date.
Unlike repeatedly adding SystemMessage in messages, dynamic_prompt constructs the system prompt at the model request stage, without modifying the chat history.
Example: inject_date_context
Example
from
datetime
import
datetime
from
langchain.
agents
.
middleware
import
dynamic_prompt
,
ModelRequest
@
dynamic_prompt
def
inject_date_context
(
request: ModelRequest
)
str
:
"""Add the current date and time zone to the system prompt."""
now
=
datetime
.
now
(
TIMEZONE
)
weekday
=
"MTWTFSS"
[
now.
weekday
(
)
]
return
(
"You are a personal assistant responsible for simulated weather queries, schedule queries, and email handling.\n"
f
"Current date: {now.date().isoformat()}, weekday {weekday}.\n"
"Time zone: Asia/Shanghai.\n"
"When the user does not specify a schedule date, default to today.\n"
"Weather is simulated data; do not claim it is real-time.\n"
"Email is only simulated; do not claim it was actually sent.\n"
"Do not fabricate tool call results."
)
The time zone is explicitly set here to avoid inconsistent date interpretation when the server uses a different time zone.
A production application can pass in the user's time zone through a trusted Runtime Context to implement personalized date handling for users in different regions.
8. Structured output: DailySummary
In addition to querying weather and schedules, users may also want a daily summary.
For example:
帮我整理今天的天气和日程,给我一份今日安排。
If the model is only allowed to output free text, the format may differ each time.
You can define a unified data structure with Pydantic.
Example: DailySummary
Example
from
pydantic
import
BaseModel
,
Field
class
DailySummary
(
BaseModel
)
:
"""Daily summary structure."""
date:
str
=
Field
(
description
=
"Date, in YYYY-MM-DD format"
)
city:
str
=
Field
(
description
=
"City where the weather applies"
)
weather_summary:
str
=
Field
(
description
=
"Weather overview"
)
event_count:
int
=
Field
(
ge
=
0
,
description
=
"Number of schedule items"
)
key_events:
list
[
str
]
=
Field
(
description
=
"Schedule items"
)
suggestion:
str
=
Field
(
description
=
"Suggestions based on known data"
)
The model needs to generate structured data according to these fields.
For example:
{
"date": "2026-10-13",
"city": "杭州",
"weather_summary": "模拟天气:晴,25°C",
"event_count": 2,
"key_events": ["10:00 团队周会", "14:00 Python 学习"],
"suggestion": "按计划参加会议和学习"
}
This is easier to use for frontend display, storage, and program processing than parsing free text directly.
9. Rendering structured data as Markdown
Structured output is suitable for program processing, while Markdown is suitable for display to users.
We can write a separate formatting function.
Example: to_markdown()
Example
def
to_markdown
(
summary: DailySummary
)
str
:
"""Convert DailySummary to Markdown."""
lines
=
[
f
"## {summary.date} Daily Summary"
,
""
,
f
"City: {summary.city}"
,
f
"Weather: {summary.weather_summary}"
,
f
"Number of schedule items: {summary.event_count}"
,
""
,
"### Schedule"
]
lines.
extend
(
f
"- {event}"
for
event
in
summary.
key_events
)
if
not
summary.
key_events
:
lines.
append
(
"- No schedule"
)
lines.
extend
(
[
""
,
f
"Note: {summary.suggestion}"
]
)
return
"\n"
.
join
(
lines
)
The generated result looks like:
## 2026-10-13 每日摘要
**城市:** 杭州
Weather: Simulated weather: Sunny, 25°C
Schedule count:
### 日程安排
- 10:00 团队周会
- 14:00 Python 学习
Suggestion: Attend meetings and study according to the plan
10. Why not set a global response_format on the main Agent?
The original code uses:
agent = create_agent(
model=model,
tools=[get_weather, query_schedule, send_email],
response_format=DailySummary
)
This approach has a problem: every call to the main Agent, including ordinary weather queries, email requests, and historical follow-ups, will attempt to generate a DailySummary.
For example, if the user just asks:
我刚才那封邮件的主题是什么?
the program might still try to generate a complete daily summary including weather and schedule.
This is not the behavior we want.
A more reasonable design is:
- Main Agent: responsible for tool calls and natural language conversation.
- Summary Agent: generates DailySummary only when a daily summary is needed.
Here we use ToolStrategy, to create a dedicated structured summary Agent.
Example: Creating the summary Agent
Example
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
structured_output
import
ToolStrategy
summary_agent
=
create_agent
(
model
=
model
,
tools
=
[
]
,
response_format
=
ToolStrategy
(
DailySummary
)
,
system_prompt
=
(
"You are a daily summary generator. Only generate a DailySummary based on the provided data."
"You must accurately count the schedule items and must not add weather or schedules that do not exist."
"The weather is simulated data and must be clearly marked."
)
)
After the call, the structured result can be obtained through:
result["structured_response"]
.
**Note:** Structured output depends on the relevant capabilities of the model. Even with Pydantic validation, you should check whether the business fields are consistent with the original tool data.
11. Generating the daily summary
To ensure that the weather and schedule in the summary both come from tools, we first execute the corresponding queries, then pass the results to the summary Agent.
This is a deterministic approach.
Example: generate_daily_summary()
Example
def
generate_daily_summary
(
city:
str
=
"Hangzhou"
)
str
:
"""Obtain simulated data and generate a structured daily summary."""
date_str
=
today_str
(
)
weather
=
get_weather.
invoke
(
{
"city"
: city
}
)
schedule
=
query_schedule.
invoke
(
{
"date_str"
: date_str
}
)
result
=
summary_agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
(
f
"Date: {date_str}\nCity: {city}\n"
f
"Weather data:\n{weather}\n"
f
"Schedule data:\n{schedule}\n"
"Please generate a structured summary based only on the above data."
)
}
]
}
)
summary
=
result
[
"structured_response"
]
return
to_markdown
(
summary
)
This function does not depend on whether the main Agent proactively calls tools; instead, it explicitly executes:
天气查询
↓
日程查询
↓
结构化摘要
↓
Markdown
Therefore, if the business requires the daily summary to contain both data sources, this approach is more controllable than relying solely on prompts.
For a production project, you should also verify whether the number of schedule items in the structured summary matches the number returned by the real tool, rather than fully trusting the number generated by the model.
12. Using SqliteSaver to save conversations
The personal assistant needs to remember what the user said in the same session.
For example:
用户:帮我准备一封邮件,主题是今日总结。
用户:刚才那封邮件的主题是什么?
Without a Checkpointer, the second round of questions may not be able to relate to the previous conversation.
SQLite is used here to save the Agent State.
Example: Create a Checkpointer
Example
from
langgraph.
checkpoint
.
sqlite
import
SqliteSaver
with
SqliteSaver.
from_conn_string
(
"personal_assistant.db"
)
as
checkpointer:
agent
=
create_agent
(
model
=
model
,
tools
=
[
get_weather
,
query_schedule
,
send_email
]
,
checkpointer
=
checkpointer
,
middleware
=
[
inject_date_context
]
)
A stable one needs to be used:
config = {
"configurable": {
"thread_id": "personal-chat-001"
}
}
Under the same thread_id, subsequent calls can restore the previously saved message history.
**Note:** All Agent calls using this SqliteSaver connection should be placed inside the with block.
SQLite is more suitable for local synchronous applications. Production multi-user Web services should use a backend suitable for concurrent access, such as PostgreSQL.
13. Streaming output: Displaying the Agent execution process
LangChain supports different Streaming modes.
Where:
| Mode | Purpose |
|---|---|
updates |
Display state updates after Agent nodes execute |
messages |
Receive text and tool call increments generated by the model |
custom |
Receive custom events |
This project wants to display:
正在调用 get_weather
get_weather 返回结果
正在调用 query_schedule
query_schedule 返回结果
生成最终回复
so you can use stream_mode="updates"。
**Note:** This kind of output displays observable execution steps and tool results, not the model's hidden internal reasoning process.
Example: Displaying node updates
Example
def
chat_stream
(
agent
,
message:
str
,
config:
dict
)
:
"""Display Agent updates by execution step."""
for
event
in
agent.
stream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: message
}
]
}
,
config
=
config
,
stream_mode
=
"updates"
)
:
for
node
,
update
in
event.
items
(
)
:
for
msg
in
update.
get
(
"messages"
,
[
]
)
:
if
msg.
type
==
"ai"
and
getattr
(
msg
,
"tool_calls"
,
[
]
)
:
for
call
in
msg.
tool_calls
:
(
"[Calling tool]"
,
call
[
"name"
]
)
elif
msg.
type
==
"tool"
:
(
"[Tool returned]"
,
msg.
name
,
str
(
msg.
content
)
[
:
120
]
)
elif
msg.
type
==
"ai"
and
msg.
content
:
(
"[Assistant]"
,
msg.
content
)
When using it, note that the Agent may trigger a HITL interruption during tool execution.
A production implementation should also check whether the current thread has a pending interruption before deciding whether to continue execution or return approval information.
14. Complete code: Multi-tool personal assistant
Below, weather, schedule, email approval, structured summary, and conversation memory are integrated into one file.
Filename:personal_assistant.py
This complete example designs email operations as simulated approval; it does not connect to real SMTP and does not automatically approve email sending.
Complete example
import
os
from
datetime
import
datetime
,
date
,
timedelta
from
zoneinfo
import
ZoneInfo
from
dotenv
import
load_dotenv
from
pydantic
import
BaseModel
,
Field
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
dynamic_prompt
,
ModelRequest
from
langchain.
agents
.
structured_output
import
ToolStrategy
from
langchain.
tools
import
tool
from
langchain_deepseek
import
ChatDeepSeek
from
langgraph.
checkpoint
.
sqlite
import
SqliteSaver
from
langgraph.
types
import
interrupt
,
Command
load_dotenv
(
)
assert
os
.
getenv
(
"DEEPSEEK_API_KEY"
)
,
"Please configure DEEPSEEK_API_KEY first"
TZ
=
ZoneInfo
(
"Asia/Shanghai"
)
def
today_str
(
)
:
return
datetime
.
now
(
TZ
)
.
date
(
)
.
isoformat
(
)
today
=
today_str
(
)
tomorrow
=
(
datetime
.
now
(
TZ
)
.
date
(
)
- timedelta
(
days
=
1
)
)
.
isoformat
(
)
weather_db
=
{
"Hangzhou"
:
{
"condition"
:
"Sunny"
,
"temp"
:
25
,
"humidity"
:
60
}
,
"Beijing"
:
{
"condition"
:
"Cloudy"
,
"temp"
:
18
,
"humidity"
:
45
}
,
"Shanghai"
:
{
"condition"
:
"Light rain"
,
"temp"
:
22
,
"humidity"
:
80
}
}
calendar_events
=
[
{
"date"
: today
,
"time"
:
"10:00"
,
"title"
:
"Team weekly meeting"
,
"duration"
:
"1 hour"
}
,
{
"date"
: today
,
"time"
:
"14:00"
,
"title"
:
"Python study"
,
"duration"
:
"2 hours"
}
,
{
"date"
: tomorrow
,
"time"
:
"15:00"
,
"title"
:
"Code review"
,
"duration"
:
"1.5 hours"
}
]
========== 1. Tools ==========
@
tool
def
get_weather
(
city:
str
)
str
:
"""Query the simulated weather for a specified city, not real-time weather."""
data
=
weather_db.
get
(
city.
strip
(
)
)
if
not
data:
return
f
"No simulated weather data for {city}"
return
f
"Simulated weather for {city}: {data['condition']}, {data['temp']}°C, humidity {data['humidity']}%"
@
tool
def
query_schedule
(
date_str:
str
=
""
)
str
:
"""Query the simulated schedule. Date format YYYY-MM-DD; leaving it empty means today."""
date_str
=
date_str
or
today_str
(
)
try
:
date.
fromisoformat
(
date_str
)
except
ValueError
:
return
"Invalid date format"
events
=
sorted
(
[
e
for
e
in
calendar_events
if
e
[
"date"
]
==
date_str
]
,
key
=
lambda
e: e
[
"time"
]
)
if
not
events:
return
f
"No simulated schedule for {date_str}"
return
"\n"
.
join
(
[
f
"Simulated schedule for {date_str}:"
]
[
f
"- {e['time']} {e['title']}({e['duration']})"
for
e
in
events
]
)
@
tool
def
send_email
(
to:
str
,
subject:
str
,
body:
str
)
str
:
"""Simulate sending an email; human approval must be obtained first."""
decision
=
interrupt
(
{
"action"
:
"send_email"
,
"to"
: to
,
"subject"
: subject
,
"body"
: body
,
"message"
:
"Please confirm the simulated email"
}
)
if
not
isinstance
(
decision
,
dict
)
or
decision.
get
(
"approved"
)
is
not
True
:
return
"Email operation cancelled; no email was sent"
return
f
"Simulated email operation approved: {to}, subject '{subject}'. Not actually sent."
========== 2. Dynamic prompts ==========
@
dynamic_prompt
def
inject_date_context
(
request: ModelRequest
)
str
:
now
=
datetime
.
now
(
TZ
)
return
(
"You are a Chinese-language personal assistant responsible for simulated weather, schedule, and email handling.\n"
f
"Current date: {now.date().isoformat()}, time zone: Asia/Shanghai.\n"
"You may ask the user when the date is unclear.\n"
"Weather and schedule are both simulated data.\n"
"Email must request approval through the send_email tool; do not claim it was actually sent.\n"
"Do not fabricate information you do not know."
)
========== 3. Structured summary ==========
class
DailySummary
(
BaseModel
)
:
date:
str
=
Field
(
description
=
"date"
)
city:
str
=
Field
(
description
=
"City"
)
weather_summary:
str
=
Field
(
description
=
"Simulated weather"
)
event_count:
int
=
Field
(
ge
=
0
,
description
=
"Number of schedule items"
)
key_events:
list
[
str
]
=
Field
(
description
=
"Schedule list"
)
suggestion:
str
=
Field
(
description
=
"Today's suggestions"
)
def
to_markdown
(
summary: DailySummary
)
str
:
lines
=
[
f
"## {summary.date} Daily Summary"
,
""
,
f
"City: {summary.city}"
,
f
"Weather: {summary.weather_summary}"
,
f
"Number of schedule items: {summary.event_count}"
,
""
,
"### Schedule"
]
lines.
extend
(
f
"- {e}"
for
e
in
summary.
key_events
)
if
not
summary.
key_events
:
lines.
append
(
"- No arrangements"
)
lines.
extend
(
[
""
,
f
"Today's suggestions: {summary.suggestion}"
]
)
return
"\n"
.
join
(
lines
)
model
=
ChatDeepSeek
(
model
=
"deepseek-chat"
,
temperature
=
0
)
summary_agent
=
create_agent
(
model
=
model
,
tools
=
[
]
,
response_format
=
ToolStrategy
(
DailySummary
)
,
system_prompt
=
(
"You are a daily summary generator. Only generate a summary based on the input data."
"Do not add schedule or weather facts that do not exist."
"You must note that the weather is simulated data."
)
)
def
daily_summary
(
city
=
"Hangzhou"
)
:
weather
=
get_weather.
invoke
(
{
"city"
: city
}
)
schedule
=
query_schedule.
invoke
(
{
"date_str"
: today_str
(
)
}
)
result
=
summary_agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: f
"Date: {today_str()}\nCity: {city}\nWeather: {weather}\nSchedule: {schedule}"
}
]
}
)
return
to_markdown
(
result
[
"structured_response"
]
)
========== 4. Main Agent ==========
def
make_agent
(
checkpointer
)
:
return
create_agent
(
model
=
model
,
tools
=
[
get_weather
,
query_schedule
,
send_email
]
,
middleware
=
[
inject_date_context
]
,
checkpointer
=
checkpointer
)
========== 5. Conversation functions ==========
def
chat
(
agent
,
message:
str
,
thread_id:
str
)
:
config
=
{
"configurable"
:
{
"thread_id"
: thread_id
}
}
(
"\nUser:"
,
message
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: message
}
]
}
,
config
=
config
)
pending
=
result.
get
(
"interrupt"
,
(
)
)
if
pending:
(
"[Waiting for human confirmation]"
)
for
item
in
pending:
(
item.
value
)
return
{
"status"
:
"pending"
,
"config"
: config
}
(
"Assistant:"
,
result
[
"messages"
]
[
1
]
.
content
)
return
{
"status"
:
"completed"
,
"config"
: config
}
def
resume_email
(
agent
,
config:
dict
,
approved:
bool
)
:
state
=
agent.
get_state
(
config
)
pending
=
[
i
for
task
in
state.
tasks
for
i
in
task.
interrupts
]
if
not
pending:
(
"No pending email approvals"
)
return
result
=
agent.
invoke
(
Command
(
resume
=
{
"approved"
: approved
}
)
,
config
=
config
)
if
result.
get
(
"interrupt"
)
:
(
"There are new pending requests"
)
else
:
(
"Assistant:"
,
result
[
"messages"
]
[
1
]
.
content
)
def
chat_updates
(
agent
,
message:
str
,
thread_id:
str
)
:
config
=
{
"configurable"
:
{
"thread_id"
: thread_id
}
}
(
"\nUser:"
,
message
)
for
event
in
agent.
stream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: message
}
]
}
,
config
=
config
,
stream_mode
=
"updates"
)
:
for
node
,
update
in
event.
items
(
)
:
for
msg
in
update.
get
(
"messages"
,
[
]
)
:
if
msg.
type
==
"ai"
and
getattr
(
msg
,
"tool_calls"
,
[
]
)
:
for
call
in
msg.
tool_calls
:
(
"[Calling tool]"
,
call
[
"name"
]
)
elif
msg.
type
==
"tool"
:
(
"[Tool returned]"
,
msg.
name
,
str
(
msg.
content
)
[
:
120
]
)
elif
msg.
type
==
"ai"
and
msg.
content
:
(
"[Assistant]"
,
msg.
content
)
========== 6. Run tests ==========
if
name
==
"main"
:
with
SqliteSaver.
from_conn_string
(
"personal_assistant.db"
)
as
checkpointer:
agent
=
make_agent
(
checkpointer
)
thread_id
=
"demo-personal-assistant"
(
"=== Test 1: Multi-tool collaboration ==="
)
chat_updates
(
agent
,
"Query the simulated weather in Hangzhou and today's simulated schedule."
,
thread_id
)
(
"\n=== Test 2: Structured daily summary ==="
)
(
daily_summary
(
"Hangzhou"
)
)
(
"\n=== Test 3: Email approval ==="
)
response
=
chat
(
agent
,
"Please simulate sending an email to team@example.com, with the subject 'Daily Summary' and the body confirming today's schedule."
,
thread_id
)
if
response
[
"status"
]
==
"pending"
:
Local teaching demo: explicitly refuse; nothing will actually be sent
resume_email
(
agent
,
response
[
"config"
]
,
approved
=
False
)
(
"\n=== Test 4: Conversation memory ==="
)
chat
(
agent
,
"What was the subject of the email I asked you to prepare just now?"
,
thread_id
)
How to run
After saving the file, execute:
python personal_assistant.py
The program will create:
personal_assistant.db
Used to save the main Agent's messages and execution state.
If you want to test with a completely fresh conversation, you can change the thread_id.
**Note:** If you use a leftover SQLite database from a previous run and the same thread_id, the Agent will restore the old history, which may affect this demo. You can use a different thread for each test to avoid mixing in old sessions.
XV. Sample Run Results
The following output is used to illustrate the functionality; actual responses depend on the model call results.
Test 1: Weather and schedule
=== 测试 1:多工具协作 ===
用户:查询杭州的模拟天气和今天的模拟日程。
[调用工具] get_weather
[调用工具] query_schedule
[工具返回] get_weather 杭州模拟天气:晴,25°C,湿度60%
[工具返回] query_schedule 今天的模拟日程:...
[助手] 根据模拟数据,杭州天气为晴,25°C。
今天有团队周会和 Python 学习两项安排。
The Agent selects two tools based on the question and aggregates the results.
The model may adjust the tool call order or even fail to call all the tools as expected. Therefore, the above is only a possible execution log.
Test 2: Structured daily summary
=== 测试 2:结构化每日摘要 ===
## 2026-10-13 Daily Summary
**城市:** 杭州
Weather: Simulated weather: Sunny, 25°C
Schedule count:
### 日程安排
- 10:00 团队周会
- 14:00 Python 学习
Today's suggestion: Schedule meetings and studying according to the plan.
The structured summary is generated only when daily_summary() is called; it does not affect other ordinary conversations.
Test 3: Email approval
=== 测试 3:邮件审批 ===
用户:请模拟给 team@example.com 发送邮件...
[等待人工确认]
{
"action": "send_email",
"to": "team@example.com",
"subject": "今日总结",
"body": "今天的日程已确认"
}
本地演示拒绝审批
助手:邮件请求已取消,没有发送邮件。
No real mail service is connected here, and no sending records are generated.
Test 4: Conversation memory
=== 测试 4:对话记忆 ===
用户:我刚才让你准备的邮件主题是什么?
助手:你刚才准备的模拟邮件主题是“今日总结”,
但这封邮件并没有实际发送。
As long as the same conversation thread has saved the previous messages, the Agent can answer using the history.
However, the model's answer may still be wrong, so when reliable state is needed, you should directly read the saved business data rather than relying entirely on the model's memory.
16. How to implement real email sending?
The current email tool is only a simulation.
To integrate a real mail service, you can choose SMTP, Gmail API, or other email service providers.
But the following steps must be separated:
AI 生成邮件草稿
↓
展示收件人、标题、正文
↓
用户或管理员确认
↓
后端校验身份与权限
↓
调用邮件服务
↓
获得真实发送结果
↓
返回消息 ID 或失败原因
It is not recommended to let the model directly hold the SMTP password or high-privilege credentials of the mail service.
The actual sending action should be performed by a trusted backend, taking into account duplicate sending protection, recipient verification, log auditing, and sending rate limits.
Especially when the Agent experiences a network retry or interruption recovery, you need to prevent the same email from being sent repeatedly.
17. Production environment considerations
1. Weather data must include time and source
A real weather API needs to return the city, weather time, and observation or forecast type. Historical weather or simulated data must not be treated as real-time weather.
2. Calendar tools require user authorization
When integrating a real calendar, the backend should access the corresponding calendar based on the authenticated user; the model must not be allowed to arbitrarily specify other users' accounts.
3. Email sending must obtain confirmation
Especially for emails containing recipients, attachments, or sensitive content, the complete information should be displayed before execution.
4. Structured output is not fact verification
Pydantic can validate field types, but cannot automatically verify whether the weather is real or whether the number of schedule items is correct.
5. Clarify the time zone
"Today", "tomorrow", and "3 PM" all depend on the user's time zone and cannot rely entirely on the server's default time zone.
6. Control the number of tool calls
The model may repeatedly call tools; practical applications should set reasonable execution limits, timeouts, and call monitoring.
7. Protect conversation records
The Checkpointer may save users' email bodies, schedules, and private information; access should be restricted and reasonable data retention policies set.
8. Avoid leaking the model's internal reasoning
The frontend should display observable tool steps and necessary progress information, rather than claiming it can directly display all of the model's internal thinking.
9. Use a concurrency-suitable Checkpointer for production deployment
SQLite is suitable for local and lightweight synchronous environments. Multi-user Web services should generally use a persistence solution that supports concurrent management, such as PostgreSQL.
18. Frequently asked questions
1. Can one Agent call multiple tools?
Yes. Register multiple tools through the tools parameter of create_agent(); the model can choose which to call based on the task.
2. Is the tool call order fixed?
Not necessarily. The Agent can adjust the order based on the model's judgment. When strict order is required, use a deterministic workflow.
3. Can simulated weather be used directly in real weather applications?
No. It needs to be replaced with a real weather API, with data source and time retained.
4. Why should a time zone be set for schedule queries?
Because dates and times may differ across regions, a time zone avoids incorrect interpretation of relative dates such as "today".
5. What is the difference between dynamic_prompt and before_model?
dynamic_prompt is suitable for dynamically constructing the System Prompt for the current model request; before_model is suitable for state checks and updates before executing the model.
6. Why shouldn't DailySummary be set globally?
Because tasks such as email handling and ordinary Q&A do not need a daily summary, forcing it globally would produce irrelevant structured results.
7. What is the purpose of ToolStrategy?
It can use the tool call mechanism to make the model generate structured data conforming to a specified Schema.
8. What can streaming output display?
It can display model-generated fragments, tool calls, tool results, and custom events, depending on the selected Streaming mode.
9. Is stream_mode="updates" token-by-token output?
No. It mainly displays state updates of graph nodes. To output model text step by step, you can use the messages mode.
10. Why does SqliteSaver need a thread_id?
Because the Checkpointer identifies and restores the corresponding session state through the thread_id.
11. Does email approval mean it was sent successfully?
No. Human approval only permits subsequent execution; whether it succeeded still needs to be checked against the real mail service's return result.
12. How to prevent the same email from being sent twice?
You can set a unique ID for email requests in the business backend and record the execution status to avoid duplicate sending caused by network retries or recovery.
13. Can I integrate Google Calendar or Gmail?
Yes, but it requires the corresponding authorization flow, API credentials, and access permission controls.
14. How does a personal assistant remember user preferences?
A Checkpointer can save the conversation history of the same thread; when long-term preferences need to be shared across sessions, you can use a Store or a business database.
Project Summary
This chapter builds a multi-tool personal assistant based on LangChain.
The following technologies are mainly used:
| LangChain Feature | Implemented in This Project |
|---|---|
| Tools | get_weather、query_schedule、send_email |
| Agent | Selecting multiple tools based on user intent |
| Dynamic Prompt | Injecting date and timezone information |
| Structured Output | DailySummary + ToolStrategy |
| Markdown | Formatting summaries with to_markdown() |
| Streaming | Displaying execution steps through updates |
| Checkpointer | Saving conversation state with SqliteSaver |
| HITL | Waiting for human confirmation before email operations |
The whole system can be summarized as follows:
自然语言输入
↓
LangChain Agent
↓
动态提示词
↓
工具选择
|
├── 天气查询
├── 日程查询
└── 邮件审批
↓
结果汇总
↓
保存对话
Independent summarization process:
天气 + 日程 → DailySummary → Markdown
**Core principle:** Let the Agent understand user intent and coordinate tools, let the tools handle querying and execution, let structured output generate stable data formats, and let the Checkpointer handle conversation memory. When real external operations such as sending emails are involved, separate permission verification and human confirmation are also required.
On this basis, you can further integrate real weather APIs, calendar services, email systems, and user management features, gradually building a personal AI assistant that can handle daily tasks.