9行Python实现AI智能体:从基础循环到工程实践
如果你最近关注 AI 领域,可能会发现“Agent”这个词越来越频繁地出现。各种框架、工具层出不穷,但很多初学者面对复杂的架构和抽象的概念,往往不知道从何入手。今天要介绍的这个项目,用 9 行 Python 代码实现了一个基础 Agent,它或许不能解决复杂问题,但能帮你快速理解 Agent 的核心机制。
这个项目最大的价值在于极简。它剥离了工程化包装,直击 Agent 最本质的交互循环:接收输入、处理思考、执行动作、观察结果。对于想入门 Agent 开发却卡在概念层面的开发者来说,这段代码是一个清晰的起点。
本文将带你从这 9 行代码出发,逐步拆解 Agent 的核心原理,并在此基础上扩展出更实用的功能。你会看到:
- Agent 的基本工作循环是如何建立的
- 如何用最简单的代码实现思考-行动-观察的闭环
- 如何为这个微型 Agent 添加记忆、工具调用等能力
- 在实际项目中需要注意哪些边界情况
无论你是想快速理解 Agent 概念,还是希望为自己的项目加入自动化决策能力,这篇文章都会提供可落地的参考。
1. 这篇文章真正要解决的问题
很多开发者第一次接触 Agent 概念时,容易陷入两个误区:要么觉得它过于抽象,无法和实际代码关联;要么被复杂框架吓到,认为入门门槛很高。事实上,Agent 的核心思想并不复杂——它就是一个能够自主感知环境、做出决策并执行动作的程序实体。
这个 9 行 Python 的 Agent 项目,解决的正是在最小代码量下理解 Agent 核心循环的问题。它不依赖任何外部框架,只用标准库实现了一个完整的思考-行动循环。这对于教学和原型验证特别有价值。
在实际开发中,你可能需要处理更复杂的场景,比如:
- 需要持久化记忆的对话 Agent
- 能够调用外部 API 的工具使用 Agent
- 需要多步推理的任务分解 Agent
但所有这些复杂能力,都建立在基础循环之上。理解这个最小实现,相当于掌握了 Agent 开发的“第一性原理”。
2. Agent 基础概念与核心原理
2.1 什么是 Agent?
在 AI 领域,Agent(智能体)指的是能够感知环境、自主决策并执行动作的软件实体。与传统的程序不同,Agent 具有目标导向性,它不是为了执行固定流程,而是为了达成某个目标而主动采取行动。
关键区别在于:
- 传统程序:输入 → 处理 → 输出(固定流程)
- Agent:感知环境 → 分析目标 → 选择动作 → 观察结果 → 调整策略(动态循环)
2.2 Agent 的核心组件
一个完整的 Agent 通常包含以下组件:
| 组件 | 作用 | 在 9 行代码中的体现 |
|---|---|---|
| 感知模块 | 接收环境信息 | input()函数 |
| 决策模块 | 分析当前状态,选择最佳动作 | 简单的条件判断逻辑 |
| 执行模块 | 执行选择的动作 | print()输出动作 |
| 记忆模块 | 记录历史交互 | 可选扩展,基础版本无记忆 |
2.3 9 行代码的 Agent 核心原理
让我们先看看这 9 行代码的核心逻辑:
def simple_agent(): while True: # 感知环境 perception = input("What do you observe? ") # 简单决策逻辑 if "hello" in perception.lower(): action = "say_hello" elif "time" in perception.lower(): action = "tell_time" elif "quit" in perception.lower(): break else: action = "ask_clarification" # 执行动作 if action == "say_hello": print("Hello! How can I help you?") elif action == "tell_time": from datetime import datetime print(f"Current time: {datetime.now()}") elif action == "ask_clarification": print("I'm not sure what you want. Can you clarify?") print("Agent stopped.")这个实现虽然简单,但包含了 Agent 的核心循环:
- 感知:通过
input()获取环境输入 - 决策:基于规则的条件判断
- 执行:执行对应的输出动作
- 循环:持续运行直到退出条件触发
3. 环境准备与前置条件
3.1 Python 环境要求
这个基础 Agent 对环境要求极低:
- Python 版本:3.6+(推荐 3.8+ 以获得更好性能)
- 操作系统:Windows/macOS/Linux 均可
- 依赖库:仅需标准库,无额外依赖
3.2 验证环境配置
在开始编码前,先验证你的 Python 环境:
# 检查 Python 版本 python --version # 或 python3 --version # 启动 Python 交互环境测试基础功能 python -c "print('Environment OK')"3.3 代码编辑器选择
虽然任何文本编辑器都能写 Python,但推荐使用:
- VS Code:安装 Python 扩展后提供良好开发体验
- PyCharm:专业的 Python IDE,适合复杂项目
- Jupyter Notebook:适合实验性编码和逐步调试
4. 核心流程拆解
4.1 第一步:建立主循环结构
Agent 的核心是持续运行的循环,直到达到终止条件:
def agent_loop(): running = True while running: # 感知-决策-执行循环 perception = perceive_environment() action = decide_action(perception) running = execute_action(action)4.2 第二步:实现感知功能
感知模块负责从环境获取信息:
def perceive_environment(): """从用户输入获取环境信息""" try: user_input = input("Agent > What's your request? ") return user_input.strip() except KeyboardInterrupt: return "quit" # 处理 Ctrl+C 退出4.3 第三步:设计决策逻辑
决策模块是 Agent 的"大脑",这里使用规则引擎:
def decide_action(perception): """基于输入决定要执行的动作""" perception_lower = perception.lower() if perception_lower == "": return "wait" elif "hello" in perception_lower or "hi" in perception_lower: return "greet" elif "time" in perception_lower: return "get_time" elif "calculate" in perception_lower or "math" in perception_lower: return "calculate" elif "quit" in perception_lower or "exit" in perception_lower: return "quit" else: return "unknown"4.4 第四步:实现动作执行
执行模块将决策转化为具体行为:
def execute_action(action): """执行具体的动作""" if action == "wait": print("Agent > I'm listening...") return True elif action == "greet": print("Agent > Hello! Nice to meet you!") return True # 其他动作实现...5. 完整示例与代码实现
5.1 基础版 9 行 Agent
首先,让我们实现最基础的版本:
# simple_agent.py def simple_agent(): while True: perception = input("You: ") if "hello" in perception.lower(): print("Agent: Hello!") elif "time" in perception.lower(): from datetime import datetime print(f"Agent: It's {datetime.now().strftime('%H:%M')}") elif "bye" in perception.lower(): print("Agent: Goodbye!") break else: print("Agent: I don't understand") if __name__ == "__main__": simple_agent()这个版本确实只有 9 行有效代码(去掉空行和注释),实现了最基本的交互功能。
5.2 增强版:添加工具调用能力
现在让我们扩展基础版本,加入真正的工具调用功能:
# enhanced_agent.py import math from datetime import datetime class EnhancedAgent: def __init__(self): self.memory = [] # 简单的记忆存储 def perceive(self): """感知用户输入""" try: user_input = input("You: ").strip() self.memory.append(f"User: {user_input}") return user_input except EOFError: return "quit" def think(self, perception): """决策逻辑""" perception_lower = perception.lower() # 数学计算识别 if any(op in perception for op in ['+', '-', '*', '/', 'sqrt']): return "calculate", perception elif "time" in perception_lower: return "get_time", None elif "remember" in perception_lower: return "recall_memory", None elif "quit" in perception_lower: return "quit", None else: return "chat", perception def act(self, decision, data): """执行动作""" action_type, action_data = decision, data if action_type == "calculate": try: # 安全评估数学表达式 if any(cmd in action_data for cmd in ['import', 'exec', 'eval']): result = "I can't execute that for security reasons" else: # 替换 sqrt 为 math.sqrt expr = action_data.replace('sqrt', 'math.sqrt') result = eval(expr, {"math": math, "__builtins__": {}}) print(f"Agent: The result is {result}") except Exception as e: print(f"Agent: Calculation error: {e}") elif action_type == "get_time": current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") print(f"Agent: Current time is {current_time}") elif action_type == "recall_memory": if self.memory: print("Agent: Recent conversation:") for i, msg in enumerate(self.memory[-3:], 1): print(f" {i}. {msg}") else: print("Agent: No memory yet") elif action_type == "quit": print("Agent: Goodbye!") return False else: print(f"Agent: You said '{action_data}'") return True def run(self): """主循环""" print("Agent: Hello! I'm your enhanced agent. How can I help?") running = True while running: perception = self.perceive() decision, data = self.think(perception) running = self.act(decision, data) if __name__ == "__main__": agent = EnhancedAgent() agent.run()5.3 高级版:集成外部 API 调用
对于更实用的场景,我们可能需要调用外部服务:
# api_agent.py import requests import json class APIAgent: def __init__(self): self.available_actions = { "weather": self.get_weather, "news": self.get_news, "translate": self.translate_text } def get_weather(self, city): """获取天气信息(模拟实现)""" # 实际项目中这里会调用真实天气 API print(f"Agent: Getting weather for {city}...") return f"Weather in {city}: Sunny, 25°C" def get_news(self, category="general"): """获取新闻(模拟实现)""" print(f"Agent: Fetching {category} news...") return "Latest news: AI advancements continue..." def translate_text(self, text, target_lang="en"): """翻译文本(模拟实现)""" print(f"Agent: Translating to {target_lang}...") return f"Translation: {text} [in {target_lang}]" def run(self): print("Agent: I can help with weather, news, and translation!") while True: command = input("Your request: ").lower() if "quit" in command: break elif "weather" in command: # 提取城市名 city = command.replace("weather", "").strip() if not city: city = input("Which city? ").strip() result = self.get_weather(city) print(result) elif "news" in command: result = self.get_news() print(result) elif "translate" in command: text = input("What text to translate? ") result = self.translate_text(text) print(result) else: print("Agent: I can help with: weather, news, translation") if __name__ == "__main__": agent = APIAgent() agent.run()6. 运行结果与效果验证
6.1 测试基础 Agent
运行simple_agent.py,你应该看到类似这样的交互:
$ python simple_agent.py You: hello Agent: Hello! You: what time is it? Agent: It's 14:30 You: calculate 2+2 Agent: I don't understand You: bye Agent: Goodbye!6.2 测试增强版 Agent
运行enhanced_agent.py,体验更丰富的功能:
$ python enhanced_agent.py Agent: Hello! I'm your enhanced agent. How can I help? You: 2+2*3 Agent: The result is 8 You: what time is it? Agent: Current time is 2024-01-15 14:30:25 You: remember our chat Agent: Recent conversation: 1. User: 2+2*3 2. User: what time is it? 3. User: remember our chat You: quit Agent: Goodbye!6.3 验证关键功能点
在测试时,重点关注以下功能是否正常工作:
- 基本交互:输入输出是否流畅
- 数学计算:能否正确处理表达式
- 记忆功能:是否准确记录和回忆对话
- 错误处理:对异常输入是否有合理响应
- 退出机制:能否正常终止程序
7. 常见问题与排查思路
7.1 基础运行问题
| 问题现象 | 可能原因 | 排查方式 | 解决方案 |
|---|---|---|---|
| 程序立即退出 | Python 环境问题 | 检查 Python 版本和安装 | 重新安装 Python 或使用 python3 命令 |
| 输入无响应 | 代码逻辑错误 | 检查 while 循环条件 | 确保循环条件正确,添加调试打印 |
| 中文输入乱码 | 编码问题 | 检查系统终端编码 | 设置终端为 UTF-8 编码 |
7.2 功能异常问题
| 问题现象 | 可能原因 | 排查方式 | 解决方案 |
|---|---|---|---|
| 数学计算错误 | 表达式解析问题 | 检查 eval 安全性 | 使用更安全的表达式解析库 |
| 记忆功能不工作 | 列表操作错误 | 检查 memory 列表操作 | 确保正确使用 append() 和切片 |
| 动作执行混乱 | 决策逻辑重叠 | 检查条件判断顺序 | 优化判断逻辑,添加优先级 |
7.3 安全与性能问题
| 问题现象 | 可能原因 | 排查方式 | 解决方案 |
|---|---|---|---|
| 代码注入风险 | 使用 eval() | 检查输入过滤 | 使用 ast.literal_eval 或自定义解析器 |
| 内存泄漏 | 无限列表增长 | 检查记忆存储机制 | 添加记忆长度限制 |
| 响应缓慢 | 复杂计算阻塞 | 检查算法复杂度 | 对耗时操作添加超时机制 |
7.4 具体故障排除示例
问题:Agent 对所有输入都回复 "I don't understand"
排查步骤:
- 检查输入处理逻辑:
# 添加调试信息 print(f"Debug: Received input: '{perception}'") print(f"Debug: Lowercase version: '{perception.lower()}'")- 验证条件判断:
# 测试各个条件分支 test_inputs = ["hello", "time", "quit"] for test in test_inputs: result = decide_action(test) print(f"Input: {test} -> Action: {result}")- 检查字符串匹配逻辑:
# 确保包含性检查正常工作 print("hello" in "hello world") # 应该返回 True print("hello" in "HELLO") # 注意大小写问题8. 最佳实践与工程建议
8.1 代码组织规范
随着 Agent 功能扩展,良好的代码结构至关重要:
# agent_project/ # ├── agents/ # │ ├── base_agent.py # 基础 Agent 类 # │ ├── chat_agent.py # 对话专用 Agent # │ └── task_agent.py # 任务执行 Agent # ├── tools/ # │ ├── calculator.py # 计算工具 # │ ├── web_searcher.py # 网络搜索工具 # │ └── file_manager.py # 文件管理工具 # ├── memory/ # │ ├── short_term.py # 短期记忆 # │ └── long_term.py # 长期记忆 # └── main.py # 主入口文件8.2 安全实践
Agent 涉及用户输入处理,安全是首要考虑:
import ast import re def safe_calculate(expression): """安全的数学表达式计算""" # 移除危险字符 safe_expr = re.sub(r'[^0-9+\-*/().]', '', expression) try: # 使用 ast 安全评估 node = ast.parse(safe_expr, mode='eval') if any(isinstance(n, (ast.Call, ast.Attribute)) for n in ast.walk(node)): raise ValueError("Function calls not allowed") return eval(compile(node, '<string>', 'eval')) except Exception as e: return f"Error: {e}"8.3 性能优化建议
对于需要处理大量请求的 Agent:
from concurrent.futures import ThreadPoolExecutor import time class AsyncAgent: def __init__(self): self.executor = ThreadPoolExecutor(max_workers=3) def process_batch_requests(self, requests): """批量处理请求""" futures = [] for request in requests: future = self.executor.submit(self.process_single_request, request) futures.append(future) # 收集结果 results = [future.result() for future in futures] return results def process_single_request(self, request): """处理单个请求""" time.sleep(0.1) # 模拟处理时间 return f"Processed: {request}"8.4 配置化管理
将 Agent 行为参数化,便于调整:
import yaml class ConfigurableAgent: def __init__(self, config_path="agent_config.yaml"): self.load_config(config_path) def load_config(self, config_path): """从 YAML 文件加载配置""" with open(config_path, 'r', encoding='utf-8') as f: self.config = yaml.safe_load(f) self.response_templates = self.config['responses'] self.timeout = self.config['settings']['timeout'] def get_response(self, intent): """根据配置获取响应模板""" return self.response_templates.get(intent, "I'm not sure how to respond.")对应的配置文件agent_config.yaml:
responses: greeting: "Hello! How can I assist you today?" farewell: "Goodbye! Have a great day!" unknown: "I didn't understand that. Can you rephrase?" settings: timeout: 30 max_memory_entries: 1008.5 日志与监控
添加完善的日志记录,便于调试和监控:
import logging from datetime import datetime class LoggedAgent: def __init__(self): self.setup_logging() def setup_logging(self): """配置日志系统""" logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler(f'agent_{datetime.now().strftime("%Y%m%d")}.log'), logging.StreamHandler() ] ) self.logger = logging.getLogger('Agent') def process_request(self, request): """处理请求并记录日志""" self.logger.info(f"Received request: {request}") try: response = self.generate_response(request) self.logger.info(f"Sent response: {response}") return response except Exception as e: self.logger.error(f"Error processing request: {e}") return "Sorry, I encountered an error."9. 总结与后续学习方向
通过这个 9 行 Python 代码的 Agent 项目,我们看到了如何用最简化的方式实现智能体的核心循环。从基础版本到功能增强版,再到工程化的生产版本,这个过程展示了 Agent 开发的关键演进路径。
核心收获:
- Agent 的本质是感知-决策-执行的循环
- 简单的规则引擎也能实现有用的交互功能
- 安全性和错误处理是生产环境的关键
- 良好的代码结构让 Agent 更易维护和扩展
下一步学习建议:
- 框架学习:尝试 LangChain、AutoGPT 等成熟框架
- AI 集成:为 Agent 添加 LLM 能力,提升对话质量
- 工具扩展:集成更多外部 API 和工具调用
- 多 Agent 系统:学习多个 Agent 如何协作完成任务
- 评估优化:建立 Agent 性能评估体系,持续改进
这个微型 Agent 就像学习编程时的 "Hello World"——它简单,但包含了所有重要概念的基础。理解它,你就掌握了打开 Agent 开发大门的钥匙。建议收藏本文中的代码示例,在实际项目中根据需要选择合适的实现方案。
