构建首个 AI 智能体的 5 个实用 Python 脚本

作者:Bala Priya C,KDnuggets 特约编辑兼技术内容专家,2026年11月30日发表于人工智能
大多数初学者是通过聊天界面开始使用语言模型的:输入提示词,得到回复,然后继续做别的事。AI 智能体的工作方式不同。它会决定下一步做什么,使用工具执行操作,评估结果,并重复这一过程,直到任务完成。
这听起来像是需要一个重量级框架,但这个想法写起代码来很简单。更有趣的问题是:你如何让模型的输出保持格式良好,让它提前规划并从错误中恢复,让它跨会话记住信息,并阻止它做出会让你后悔的事?
下面的五个脚本会按顺序探讨这些问题,从一个极简循环到一个受监督的智能体。每个脚本都有一个离线的 --mock 或 --demo 模式,无需 API key 即可运行,因此你可以先观察其运行机制,之后再接入你选择的任意模型。
智能体框架把循环隐藏在抽象层后面,这让你构建的第一个智能体感觉像个黑盒,而黑盒很难调试。当出现问题时,你无法判断是模型推理得不好、某个工具失败了,还是框架吞掉了错误。
用纯 Python 实现了「推理、行动、观察」模式。模型写下一个想法并选择一个工具,脚本运行该工具,结果作为观察反馈回来。这个过程会重复,直到模型给出最终答案或达到步数限制。它自带三个小工具:计算器、单词计数器和日期查询。
该模型被指示以严格的 Thought / Action / Action Input 格式进行回复。在 Observation: 上设置停止序列可以防止它编造工具返回结果,因此脚本总能提供一个有效结果。回复通过正则表达式解析;如果模型违反格式,会告知它,并再给它一次机会。计算器使用 Python 的 ast 模块解析表达式,而不是调用 eval,因此模型永远无法通过它执行任意代码。硬性的 max_steps 上限保证循环总会终止。
2. 使用 Pydantic AI 的类型安全智能体
自由文本输出很脆弱。如果下游代码期望的优先级是 high,而模型返回的是 urgent,或者漏掉了某个字段,问题会在之后爆发,而且离根因很远。手工解析并重新提示效率低下。
把客户支持工单分诊为一个严格的 Pydantic 模型:category、priority、summary、sentiment、escalation 标志和 tags。你拿回的结果是真正的 Python 对象,而不是一个你必须信任的字符串。
该智能体通过 output_type=TicketTriage 创建,Pydantic AI 会把该 schema 传给模型,并校验每一次回复。当校验失败时,错误信息会返回给模型,让它能自我纠正,直至达到重试上限。第二层是 @output_validator,它强制执行一条 schema 无法表达的规则:critical 工单必须升级。离线 mock 故意在返回一个好答案之前先返回两个坏答案,这样你就能看到两层机制都能发现问题,并报告需要多少次重试。
3. 一个会重新规划的规划器-执行器智能体
像上面 ReAct 循环那样逐步循环的做法,会在每一个动作之后都询问模型下一步该做什么。这很灵活,但每一步都要消耗一次模型调用,而且在智能体真正执行之前,你无法知道它打算做什么。相反的做法——事先把所有事情都规划好——也有它自己的问题:计划是在智能体看到任何数据之前就写好的,所以有时会是错的。
它先写出完整计划,再执行计划,以此分析一个 CSV 文件。如果某个步骤失败,模型会看到已经完成了什么、哪里出了问题,并为剩余工作写一份新计划。当所有步骤都运行完毕后,它会根据收集到的结果写一份简短报告。离线演示中,计划里的某一步使用了一个并不存在的列名,因此你可以看到它失败、重新规划并恢复的过程。
规划器以 JSON 数组的形式返回计划,脚本会在任何内容运行之前对它进行校验:只允许已知工具、参数必须完全符合预期,并限制最大步骤数。格式不合规的计划会连同原因一并退回给模型一次。执行器就是普通的 Python,在运行各步骤时不进行任何模型调用。工具失败会抛出一种特定的错误类型,其中带有有用的提示信息,例如列出实际存在的列名,而正是这条信息让规划器得以修正错误。重新规划最多允许两次,此外还有全局步骤上限,即使模型不断产出糟糕的计划,智能体也会被叫停。文件访问被限制在一个工作区文件夹内。
4. 本地记忆管理器
语言模型是无状态的,因此一段对话只能“记住”你重新发送的内容。把所有内容都重新发送代价高昂,最终还会撑爆上下文窗口。而丢弃旧消息,则会让助手在对话进行到一半时忘记你的名字。
为聊天助手提供三层记忆,存储在重启后仍保留的 JSON 文件中:近期消息窗口、较旧消息的滚动摘要,以及可通过 /remember 添加的长期事实列表。
一旦近期窗口超出 Token 预算,最旧的消息会被并入摘要并从窗口中移除;切分点会移动,以确保窗口仍以用户消息开头,这是 API 的要求。事实通过其与当前消息的关键词重叠来检索,因此只有相关事实会被注入系统提示,而不是全部注入。保存是原子性的(先写入临时文件,再替换),因此崩溃不会损坏文件。摘要器是可插拔的:演示用简单的抽取式版本,真实聊天用 LLM 生成的版本。
5. 人在环中的守门人
当智能体能够写文件、发送电子邮件或删除东西时,一次错误的工具调用就不再只是糟糕的回答,而会成为现实世界中的副作用。你会希望在安全步骤上让智能体自主执行,而在有风险的步骤上由人来判断。
为每个工具包上一层风险等级。安全工具立即运行,确认级工具会暂停,等待输入 y、n 或 a(始终允许),高风险工具要求你输入 yes,被阻止的工具则永不运行。每个决定都会记入审计日志。
守门人位于模型的请求与工具调用之间。如果人类拒绝某个操作,拒绝结果以及可选的备注(例如 n: use a different filename)会作为工具结果返回给模型,使其能够调整,而不是盲目重试。该门禁采用故障关闭策略:如果无法获得输入,操作就会被拒绝。文件工具被限制在工作区文件夹内,电子邮件工具是模拟的,会写入一个发件箱文件,因此你可以安全地进行实验。
以下是全部五个脚本的摘要:
展示核心智能体循环
文本解析、停止序列、安全计算器、步数上限
在使用框架之前,先理解智能体如何运作
强制结构化输出
Schema 校验、重试、输出校验器
可靠地将模型输出传入其他代码
先规划,再执行
JSON 计划校验、失败后重新规划、步数上限
需要检查计划的多步骤任务
跨轮次和会话记忆
滚动摘要、事实召回、原子保存
长期运行的助手和个人聊天机器人
人在环路的守门人
风险分级、故障关闭(fail-closed)、审计日志、拒绝说明
会写入、发送或删除的智能体
先从离线模式入手理解基础知识,然后切换到你自己选择的模型,并一次只改一项。祝构建愉快!
Bala Priya 是驻印度的开发者、教育者和技术写作者。她撰写关于编程、数据科学、机器学习和 AI 的内容,专注于让复杂的技术概念变得实用且易于理解。她创作教程、操作指南和深度解析,帮助开发者构建、解决问题并理解复杂的技术概念。她的技术兴趣包括 LLM 应用、智能体式 AI、图算法、计算机视觉、可解释 AI 和 ML 系统。不写作或编程时,Bala 通常阅读经典文学、史诗奇幻或推想小说。她也喜欢谈论书籍、学习新事物,并与开发者社区分享所学。
译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。
查看英文原文(5 Useful Python Scripts for Building Your First AI Agent)
By Bala Priya C, KDnuggets Contributing Editor & Technical Content Specialist on November 30, 2026 in Artificial Intelligence

Most beginners start using language models through a chat interface: enter a prompt, get a response, and move on. An AI agent works differently. It decides what to do next, uses tools to carry out actions, evaluates the results, and repeats the process until the task is complete.
That sounds like it needs a heavyweight framework, but the idea is simple to code. The more interesting questions are: how do you keep the model's output well-formed, let it plan ahead and recover from mistakes, make it remember things across sessions, and stop it from doing something you would regret?
The five scripts below walk through those questions in order, from a super simple loop to a supervised agent. Every script has an offline --mock or --demo mode that runs with no API key, so you can watch the mechanics first and plug in any model of your choosing afterwards.
Agent frameworks hide the loop behind abstractions, which makes the first agent you build feel like a black box, and black boxes are hard to debug. When something goes wrong, you cannot tell whether the model reasoned badly, a tool failed, or the framework swallowed an error.
Implements the "reason, act, observe" pattern in plain Python. The model writes a thought and picks a tool, the script runs it, and the result is fed back as an observation. This repeats until the model produces a final answer or hits a step limit. It ships with three small tools: a calculator, a word counter, and a date lookup.
The model is instructed to reply in a strict Thought / Action / Action Input format. A stop sequence on Observation: prevents it from inventing tool results, so the script always supplies a valid one. Replies are parsed with regular expressions; if the model breaks format, it is told so and gets another chance. The calculator parses expressions with Python's ast module instead of calling eval, so the model can never execute arbitrary code through it. A hard max_steps cap guarantees the loop always terminates.
2. A Type-Safe Agent with Pydantic AI
Free-text output is fragile. If downstream code expects a priority of high and the model says urgent, or forgets a field, something breaks later and far from the cause. Parsing and re-prompting by hand is inefficient.
Triages customer support tickets into a strict Pydantic model: category, priority, summary, sentiment, an escalation flag, and tags. The result you get back is a real Python object, not a string you have to trust.
The agent is created with output_type=TicketTriage, and Pydantic AI passes that schema to the model and validates every reply. When validation fails, the error message goes back to the model so it can correct itself, up to a retry limit. A second layer, an @output_validator, enforces a rule a schema cannot express: critical tickets must be escalated. The offline mock deliberately returns two bad answers before a good one, so you can see both layers catch a problem and report how many retries were needed.
3. A Planner-Executor Agent That Re-Plans
A step-by-step loop like the ReAct loop above asks the model what to do next after every single action. That is flexible, but it costs a model call per step, and you cannot see what the agent intends to do until it has already done it. The opposite approach, planning everything up front, has its own problem: the plan is written before the agent has seen any data, so it will sometimes be wrong.
Analyzes a CSV file by writing a complete plan first, then running it. If a step fails, the model is shown what has been done and what went wrong, and writes a new plan for the remaining work. When every step has run, it writes a short report from the collected results. The offline demo plans a step with a column name that does not exist, so you can watch it fail, re-plan, and recover.
The planner returns its plan as a JSON array, and the script validates it before anything runs: known tools only, exactly the expected arguments, and a maximum number of steps. A malformed plan is sent back to the model once with the reason. The executor is ordinary Python and makes no model calls while running steps. Tool failures raise a specific error type that carries a helpful message, such as listing the columns that do exist, and that message is what lets the planner fix its mistake. Re-planning is capped at two attempts, and a global step limit stops the agent even if the model keeps producing bad plans. File access is confined to one workspace folder.
4. A Local Memory Manager
Language models are stateless, so a conversation only "remembers" what you resend. Resending everything is expensive and eventually overflows the context window. Dropping old messages makes the assistant forget your name halfway through.
Gives a chat assistant three layers of memory, stored in a JSON file that survives restarts: a window of recent messages, a running summary of older ones, and a list of long-term facts you can add with /remember.
Once the recent window exceeds a token budget, the oldest messages are folded into the summary and removed from the window; the cut point is moved so the window still starts on a user message, as the API requires. Facts are retrieved by keyword overlap with the current message, so only relevant ones are injected into the system prompt rather than all of them. Saves are atomic (write to a temp file, then replace), so a crash cannot corrupt the file. The summarizer is pluggable: a simple extractive version for the demo and an LLM-written one for real chats.
5. A Human-in-the-Loop Gatekeeper
The moment an agent can write files, send email or delete things, a mistaken tool call stops being a bad answer and becomes a real-world side effect. You want the agent's autonomy for the safe steps and a human's judgment for the risky ones.
Wraps every tool in a risk level. Safe tools run immediately, confirm-level tools pause for a y, n or a (always allow), high-risk tools require you to type yes, and blocked tools never run. Every decision lands in an audit log.
A gatekeeper sits between the model's request and the tool call. If the human denies an action, the denial, plus an optional note such as n: use a different filename, is returned to the model as a tool result so it can adapt instead of retrying blindly. The gate fails closed: if input is unavailable, the action is denied. File tools are confined to a workspace folder, and the email tool is simulated, writing to an outbox file, so you can experiment safely.
Here is a summary of all five scripts:
Show the core agent loop
Text parsing, stop sequences, safe calculator, step cap
Understanding how agents work before using a framework
Enforce structured output
Schema validation, retries, output validator
Feeding model output into other code reliably
Plan first, then execute
JSON plan validation, re-planning on failure, step caps
Multi-step tasks where you want to inspect the plan
Remember across turns and sessions
Rolling summary, fact recall, atomic saves
Long-running assistants and personal chatbots
Human-in-the-Loop Gatekeeper
Risk tiers, fail-closed, audit log, denial notes
Agents that write, send or delete
Start with the offline modes to understand the basics, then switch to a model of your choosing and change one thing at a time. Happy building!
Bala Priya is a developer, educator, and technical writer based in India. She writes about programming, data science, machine learning, and AI, with a focus on making complex technical ideas practical and approachable. She creates tutorials, how-to guides, and deep dives that help developers build, solve problems, and understand complex technical concepts. Her technical interests include LLM applications, agentic AI, graph algorithms, computer vision, explainable AI, and ML systems. When she’s not writing or coding, Bala is usually reading classic literature, epic fantasy, or speculative fiction. She also enjoys talking about books, learning new things, and sharing what she learns with the developer community.
原文为英文,正文由自动抓取并保留原文。
原文发布于 KDnuggets(5 Useful Python Scripts for Building Your First AI Agent),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。