用 Python 实现智能体:计划、工具与本地记忆
把目标拆为可验证的调用,使用独立的天气、计划、计算和待办样例检查权限与错误。
学完这一章,你能够
- 把目标拆为可验证的调用,使用独立的天气、计划、计算和待办样例检查权限与错误。
分清目标、观察、选择和动作
目标规定要解决什么,观察是当前收到的数据,计划是下一步动作与参数。执行器读取工具结果,再决定继续、停下或返回。能输出一段计划只说明决策文本已生成,工具是否行动要看自己的执行记录。
用规则可以先验证感知、选择、执行和反馈这条链。规则版用固定数据和人工编排的计划步骤。需要模型时,用独立的适配器替换决策来源,仍由程序检查工具、参数与权限。短期观察属于当前任务,偏好和联系人等长期数据另有生命周期。
把天气提醒拆成两个动作
以潮湾的出行提醒为例,先查询天气卡片,把该地点与日期的结果保存在当轮状态。再判断雨量、审批和联系人。山城晴天、未知地点、联系人不存在、没有先查询,各自有独立结果。
只有用户侧明确批准,而且天气为雨、联系人确实存在,才在本机生成提醒预览。相同地点、日期和联系人在一个实例内只排入一次,重复请求返回已经排队。联系标识为训练数据,样例没有短信、邮件或真实天气网络。
下方是本机样例回放。潮湾的雨量是 6 毫米,等待批准时提醒队列仍为空。切换到批准后的用例,可看到只生成一份本地预览。

先把目录与工具接口定好
ZIP 内的 agent_loop.py 保存任务执行、状态和工具,bounded_math.py 专门解释有限的算术语法,brain.py 封装 Chat Completions。lab_tools.py 收集本地断言,浏览器页可查看实跑记录。
注册表把稳定工具名对应到预先定义的函数。无状态的查询、计划格式化和时间工具可写成静态方法。待办和提醒需访问实例数据,使用绑定到当前实例的方法。外部请求或数据库写入以后可接到独立工具,但仍应校验能力、超时和失败返回。
用实际 SDK 检查模型边界
在隔离环境安装指定的 Python SDK。客户端初始化时传入提供商地址与模型 ID。真实密钥应来自环境变量或凭据服务,示例用无网络拦截传输和固定假密钥。旧版 Chat Completions 客户端常从 choices[0].message.content 取文本,先判断是否有选项、结果是否结束和内容是否为空。
OpenAI 与 DeepSeek 的兼容请求仍各有模型、鉴权和字段规则。历史示例使用 deepseek-v4-flash,当前 DeepSeek 文档列出 deepseek-flash 和 deepseek-v4-pro。temperature 与 max_tokens 分别影响采样参数和生成上限,当前 DeepSeek 思考模式忽略 temperature。模型自我介绍里的价格、知识截止日和上下文数值不能作为接口规格。
本机 SDK 例验证了 system 和 user 消息、非流式请求、温度、生成预算、正常输出以及空值、截断、无效 JSON 和 429。调用失败时由适配层报告,执行器不会把错误字符串当成工具计划。
旅行、搜索和时间各有独立结果
旅行助手可把复杂目标拆成确认同行者、交通住宿和雨天备选。计划格式化器接受字符串数组,避免用逗号切自然语言步骤。程序既可直接回答,也可选目录查询、计划格式化或时间工具,再用受控结果生成反馈。
本站目录查询只读固定的灯塔条目,缺记录返回 no_record。时间工具明确使用固定 UTC 样本,换成真实系统时间时需要指定时区和时间来源。计划或搜索完成并不会自动预约交通或住宿。
用限定语法执行算术
使用用户输入调用 eval 会让程序按 Python 表达式执行。限制字符不能独自限制幂或巨大表达式。ast.literal_eval 可以解释数字、字符串和容器等字面量,不能作为一般算术求值器。本站用 ast.parse 检查节点,逐个计算允许的常量、一元符号、加减乘除和有界整数幂。
输入最多 64 字符,幂指数只接受 0 至 8 的整数,并限制中间值。除零、语法错误、未知操作符及超限分别处理。15 的平方加 20 的三分之一在 16 位十进制精度下为 231.6666666666667。0.10 加 0.2 返回 0.3。
解析计划后再调用工具
只靠自然语言中的工具名与指令行容易被换行、标点或额外说明破坏。约定一条 JSON 调用只包含 tool 与 args。解析后仍须检查重复键、名称白名单、参数名、类型和长度。模型不能在 args 自行授予审批。
执行器设置步数预算,遇到无效调用停止。没有工具的情况直接返回。需要最终总结时,把已执行结果传回模型,不将其输出当成下一轮授权。较成熟的供应商工具调用可用正式参数 schema,并关联工具调用 ID 与结果。
会话历史和待办的寿命
本章在同一实例保留最近八次目标与状态。每次 run 都新建短期观察,前一轮的天气不会自动授权新一轮提醒。新实例启动时,历史、待办和本地提醒队列为空。跨进程保存需设计独立持久存储及访问控制。
SDK 例把最近两轮以内经过挑选的用户和助手消息加入下次请求。实测过 system、user、assistant、user 的顺序。想扩展待办,可注册 add_todo 和 show_todos,并约束长度、条目数与会话归属。
从本机天气卡片到审批后的提醒预览
"""Run a local plan, tool calls, memory and an approval-gated preview."""
from datetime import datetime, timezone
from inspect import signature
import json
from bounded_math import calculate
from lab_tools import run_exercise
WEATHER = {("潮湾", "明天"): {"condition": "雨", "mm": 6},
("山城", "明天"): {"condition": "晴", "mm": 0}}
LISTINGS = {"灯塔": "周六开放 09:00–16:00"}
TRIP = ["确认同行者", "列出交通和住宿选项", "预留雨天安排"]
def checked_text(value):
if not isinstance(value, str) or not value.strip() or len(value) > 120:
raise ValueError("expected nonempty text of at most 120 characters")
return value.strip()
def call(tool, **args):
return {"tool": tool, "args": args}
def unique_fields(pairs):
fields = {}
for key, value in pairs:
if key in fields:
raise ValueError("duplicate field")
fields[key] = value
return fields
def read_call(raw):
if not isinstance(raw, str) or len(raw) > 1024:
raise ValueError("call exceeds input limit")
try:
item = json.loads(raw, object_pairs_hook=unique_fields)
except (json.JSONDecodeError, RecursionError) as error:
raise ValueError("invalid call JSON") from error
if not isinstance(item, dict) or set(item) != {"tool", "args"}:
raise ValueError("expected tool and args")
if not isinstance(item["tool"], str) or not isinstance(item["args"], dict):
raise ValueError("invalid tool or args")
return item
class Agent:
def __init__(self):
self.contacts = {"值班员": "fixture-desk"}
self.history = []
self.todos = []
self.outbox = {}
self.tools = {
"weather": self.weather, "remind": self.remind, "search": self.search,
"schedule": self.schedule, "time": self.time, "calculate": calculate,
"add_todo": self.add_todo, "show_todos": self.show_todos,
}
@staticmethod
def weather(city, day):
key = checked_text(city), checked_text(day)
return dict(WEATHER[key]) if key in WEATHER else {"condition": "未知", "mm": None}
def remind(self, city, day, contact, approved, *, scratch):
if type(approved) is not bool:
raise ValueError("approval must be boolean")
city, day, contact = map(checked_text, (city, day, contact))
if (city, day) not in scratch:
return "weather_required"
weather = scratch[city, day]
if weather["condition"] != "雨":
return "no_rain" if weather["condition"] == "晴" else "weather_unknown"
if not approved:
return "awaiting_approval"
target = self.contacts.get(contact)
if target is None:
return "unknown_contact"
key = (city, day, target)
if key in self.outbox:
return "already_queued"
self.outbox[key] = f"{city}{day}预计降雨 {weather['mm']} 毫米,请核对出行安排。"
return "queued_local_preview"
@staticmethod
def search(query):
return LISTINGS.get(checked_text(query), "no_record")
@staticmethod
def schedule(steps):
if not isinstance(steps, list) or not 1 <= len(steps) <= 8:
raise ValueError("expected 1 to 8 steps")
return [f"{index}. {checked_text(text)}" for index, text in enumerate(steps, 1)]
@staticmethod
def time():
return datetime(2026, 11, 10, 8, 30, tzinfo=timezone.utc).isoformat()
def add_todo(self, item):
if len(self.todos) >= 8:
raise ValueError("todo list is full")
self.todos.append(checked_text(item))
return len(self.todos)
def show_todos(self):
return list(self.todos)
def run(self, goal, calls, *, approved=False, budget=4):
goal = checked_text(goal)
if type(budget) is not int or not 0 <= budget <= 8:
raise ValueError("budget must be an integer from 0 to 8")
scratch = {}
trace = []
state = "answered" if not calls else "complete"
for index, raw in enumerate(calls):
if index == budget:
state = "step_limit"
break
name = None
try:
step = read_call(raw)
name, args = step["tool"], step["args"]
if name not in self.tools:
raise ValueError("unknown tool")
target = self.tools[name]
if name == "remind":
if set(args) != {"city", "day", "contact"}:
raise ValueError("approval is supplied by the caller")
args = {**args, "approved": approved, "scratch": scratch}
try:
signature(target).bind(**args)
except TypeError as error:
raise ValueError("invalid tool arguments") from error
output = target(**args)
if name == "weather":
scratch[args["city"].strip(), args["day"].strip()] = output
trace.append({"tool": name, "output": output})
except ValueError as error:
trace.append({"tool": name, "error": str(error)})
state = "tool_error"
break
if len(self.history) == 8:
self.history.pop(0)
self.history.append({"goal": goal, "state": state})
return {"state": state, "trace": trace, "history_count": len(self.history)}
def execute(agent, goal, steps, **options):
return agent.run(goal, [json.dumps(step) for step in steps], **options)
def forecast(city, day="明天", contact="值班员"):
return [call("weather", city=city, day=day), call("remind", city=city, day=day, contact=contact)]
def exercise(checks, _):
expect = checks.expect
agent = Agent()
wet = execute(agent, "查询潮湾出行天气", forecast("潮湾"))
expect("python_agent_rain_waits", ["潮湾","明天",False], "Observe the forecast, then require local approval",
[{"condition":"雨","mm":6},"awaiting_approval",0],
[*(row["output"] for row in wet["trace"]),len(agent.outbox)])
allowed = execute(agent, "批准潮湾提醒预览", forecast("潮湾"), approved=True)
duplicate = execute(agent, "再次运行同样的目标", forecast("潮湾"), approved=True)
expect("python_agent_local_outbox", [True,True], "Read the first queued preview and suppress the duplicate",
["queued_local_preview","already_queued",["潮湾明天预计降雨 6 毫米,请核对出行安排。"]],
[allowed["trace"][-1]["output"],duplicate["trace"][-1]["output"],list(agent.outbox.values())])
dry = execute(agent, "查询山城", forecast("山城"), approved=True)
unknown = execute(agent, "查询无记录城市", forecast("空港"), approved=True)
stranger = execute(agent, "查询潮湾但无联系人", forecast("潮湾",contact="访客"), approved=True)
expect("python_agent_weather_branches", ["山城","空港","访客"], "Run dry, unknown and missing-contact cases",
["no_rain","weather_unknown","unknown_contact",1],
[dry["trace"][-1]["output"],unknown["trace"][-1]["output"],stranger["trace"][-1]["output"],len(agent.outbox)])
fresh = execute(agent, "新一轮直接申请提醒", forecast("潮湾")[1:], approved=True)
expect("python_agent_scratch_isolation", "next turn without lookup", "Verify that previous observations cannot authorize a new action",
"weather_required",fresh["trace"][-1]["output"])
planner = Agent()
result = execute(planner, "制定旅行清单", [call("schedule",steps=TRIP),call("search",query="灯塔"),call("time")])
expect("python_agent_travel_time", TRIP, "Format the sequence, consult the local directory and read a fixed clock",
[["1. 确认同行者","2. 列出交通和住宿选项","3. 预留雨天安排"],"周六开放 09:00–16:00","2026-11-10T08:30:00+00:00"],
[row["output"] for row in result["trace"]])
expect("python_agent_search_miss", "车站", "Use a query with no fixture record", "no_record",
execute(planner,"查询车站",[call("search",query="车站")])["trace"][0]["output"])
calc = execute(planner, "算平方与分数", [call("calculate",expression="15**2+20/3")])
expect("python_agent_calculate", "15**2+20/3", "Dispatch a bounded decimal expression and read its result",
"231.6666666666667",calc["trace"][0]["output"])
arithmetic = ["3 + 5 * 2", "-(3 + 5)/2", ".10 + .2", "1/0", "2**9", "6//2", "__import__('os')", "9"*65]
observed = []
for sample in arithmetic:
row = execute(planner,"核对算术",[call("calculate",expression=sample)])["trace"][0]
observed.append(row.get("output",row.get("error")))
expect("python_agent_math_limits", arithmetic, "Dispatch arithmetic plus unsupported or excessive input",
["13","-4","0.3","division by zero","power outside exercise range","unsupported arithmetic operator",
"only decimal numbers and arithmetic operators are allowed","expected 1 to 64 characters"],observed)
expect("python_agent_history_limit", "several turns with the same instance", "Keep a bounded record of observed turns",
[8,"核对算术",0],[len(planner.history),planner.history[-1]["goal"],len(Agent().history)])
todo = Agent()
first = execute(todo,"添加待办",[call("add_todo",item="核对船期")])
second = execute(todo,"查看待办",[call("show_todos")])
expect("python_agent_todos", ["add","list","new instance"], "Observe two turns and verify a new instance starts empty",
[1,["核对船期"],2,[]],
[first["trace"][0]["output"],second["trace"][0]["output"],second["history_count"],Agent().show_todos()])
invalid = [
'{"tool":"erase","args":{}}',
'{"tool":"weather","args":{"city":"潮湾"}}',
'{"tool":"time","tool":"search","args":{}}',
'{"tool":',
'{"tool":"remind","args":{"city":"潮湾","day":"明天","contact":"值班员","approved":true}}',
'{"tool":"schedule","args":{"steps":[]}}',
]
statuses = []
for raw in invalid:
result = todo.run("拒绝非法调用", [raw,json.dumps(call("add_todo",item="不应写入"))])
statuses.append([result["state"],result["trace"][0]["error"]])
expect("python_agent_json_gate", invalid, "Stop on malformed, forbidden or unauthorized tool requests",
[[["tool_error",error] for error in ("unknown tool","invalid tool arguments","duplicate field","invalid call JSON",
"approval is supplied by the caller","expected 1 to 8 steps")],["核对船期"]],[statuses,todo.todos])
a = execute(todo,"直接反馈",[])
b = execute(todo,"限制步数",[call("time"),call("add_todo",item="不应写入")],budget=1)
expect("python_agent_stop", [0,1], "Compare direct answer with the loop reaching its budget",
["answered",[],"step_limit",1,["核对船期"]],[a["state"],a["trace"],b["state"],len(b["trace"]),todo.todos])
if __name__ == "__main__":
run_exercise(exercise)
- 潮湾下雨而未批准时队列为空。批准后只生成一次本地预览,晴天和未知地点不会排入。
所需环境:CPython 3.12、OpenAI SDK 3.46.0、httpx2 2.16.0、隔离样本和 Edge。
当前源码 SHA256:0fac3c59726b4f7b38d432e2a7ee0f4be1467b06c221fcf7816c6a1333353332
独立运行工具和模型适配器
ZIP 包含规则工具循环、算术解析器、本机 SDK 示例、运行条件和可交互的观察页。
所需环境:CPython 3.12、OpenAI SDK 3.46.0、httpx2 2.16.0、隔离样本和 Edge。
ZIP SHA256:4100d7f52cb5c50abfa089f628c3eb9848c537e4c219fc6c2c21f74d31d261d9
常见错误与边界
- 明确信息的时效和来源,天气卡片与固定时钟只属于这组训练样例。
- 选择工具、授权调用、执行结果和模型反馈分开记录。
练习与解答
给新的 Agent 添加一条待办,再执行第二轮读取。试着把不存在的工具放在第一步,确认其后的写入不会执行。
展开参考解答
同一实例能读回待办,新实例为空。非法调用返回 tool_error 并停止剩余步骤。