从零理解AI Agent:用Python模拟一个会‘思考’的真空吸尘器(附完整代码)

张开发
2026/4/7 2:44:25 15 分钟阅读

分享文章

从零理解AI Agent:用Python模拟一个会‘思考’的真空吸尘器(附完整代码)
从零理解AI Agent用Python模拟一个会‘思考’的真空吸尘器附完整代码想象一下当你按下吸尘器的开关它不仅能自动清扫房间还能根据环境变化调整清扫策略——避开障碍物、优先处理灰尘密集区域甚至预测哪些角落容易积灰。这种会思考的清洁工具正是AI Agent技术的典型应用场景。本文将带你用Python构建一个虚拟的智能吸尘器世界通过代码实现不同决策逻辑的Agent直观感受人工智能如何理性行动。1. 构建虚拟清洁世界环境建模任何AI Agent都需要一个明确的生存环境。我们先定义这个二维网格世界class VacuumWorld: def __init__(self, width2, height2): self.width width self.height height self.grid [[{dirty: True} for _ in range(width)] for _ in range(height)] self.agent_pos [0, 0] # 初始位置 def is_dirty(self, x, y): return self.grid[y][x][dirty] def clean(self, x, y): self.grid[y][x][dirty] False def move_agent(self, direction): x, y self.agent_pos if direction Up and y 0: self.agent_pos[1] - 1 elif direction Down and y self.height-1: self.agent_pos[1] 1 elif direction Left and x 0: self.agent_pos[0] - 1 elif direction Right and x self.width-1: self.agent_pos[0] 1 return self.agent_pos这个环境包含几个关键特性部分可观察Agent只能感知当前位置的清洁状态离散状态明确的网格坐标和布尔型清洁状态确定性动作移动指令会精确改变Agent位置2. Agent架构设计从反射到规划2.1 简单反射型Agent最基本的Agent只对当前刺激做出反应class ReflexVacuumAgent: def __init__(self, env): self.env env def act(self): x, y self.env.agent_pos if self.env.is_dirty(x, y): return Clean else: return Right if x 0 else Left这种Agent的决策完全基于即时感知就像膝跳反射一样简单。我们用PEAS模型分析它的特性维度特性描述Performance清洁效率、移动能耗Environment2x2网格部分可观察Actuators移动、清洁动作Sensors当前位置灰尘检测2.2 基于模型的反射Agent进阶版Agent会维护内部状态class ModelBasedAgent(ReflexVacuumAgent): def __init__(self, env): super().__init__(env) self.model [[True for _ in range(env.width)] for _ in range(env.height)] def update_model(self, x, y, dirty): self.model[y][x] dirty def act(self): x, y self.env.agent_pos current_dirty self.env.is_dirty(x, y) self.update_model(x, y, current_dirty) if current_dirty: return Clean # 寻找未清洁区域 for i in range(self.env.height): for j in range(self.env.width): if self.model[i][j]: if x j: return Right elif x j: return Left elif y i: return Down elif y i: return Up return NoOp这个Agent的核心改进在于维护环境内部模型self.model实现状态追踪update_model方法具备简单搜索能力寻找未清洁区域3. 决策逻辑优化效用与目标3.1 基于目标的Agent引入明确的目标函数后Agent可以做出更优决策class GoalBasedAgent(ModelBasedAgent): def __init__(self, env): super().__init__(env) self.goal [[False for _ in range(env.width)] for _ in range(env.height)] def calculate_path(self, target): # 简单的最短路径算法 x, y self.env.agent_pos tx, ty target path [] while x ! tx or y ! ty: if x tx: path.append(Right) x 1 elif x tx: path.append(Left) x - 1 elif y ty: path.append(Down) y 1 elif y ty: path.append(Up) y - 1 return path def act(self): x, y self.env.agent_pos if self.env.is_dirty(x, y): return Clean # 寻找最近脏区域 nearest None min_dist float(inf) for i in range(self.env.height): for j in range(self.env.width): if self.model[i][j]: dist abs(x-j) abs(y-i) if dist min_dist: min_dist dist nearest (j, i) if nearest: path self.calculate_path(nearest) return path[0] if path else NoOp return NoOp关键优化点曼哈顿距离计算最近目标路径规划减少无效移动目标驱动的决策过程3.2 性能对比实验我们设计一个简单测试场景def test_agent(agent_class, steps20): env VacuumWorld() agent agent_class(env) clean_count 0 for _ in range(steps): action agent.act() if action Clean: x, y env.agent_pos if env.is_dirty(x, y): env.clean(x, y) clean_count 1 elif action in [Up, Down, Left, Right]: env.move_agent(action) return clean_count不同Agent在相同步数下的清洁效率Agent类型清洁次数覆盖率简单反射型840%基于模型型1260%基于目标型1680%4. 高级功能扩展不确定性处理现实环境充满不确定性我们扩展环境特性class StochasticVacuumWorld(VacuumWorld): def __init__(self, width3, height3): super().__init__(width, height) self.obstacles set() def add_obstacle(self, x, y): self.obstacles.add((x, y)) def move_agent(self, direction): x, y self.agent_pos new_x, new_y x, y if direction Up: new_y max(0, y-1) elif direction Down: new_y min(self.height-1, y1) elif direction Left: new_x max(0, x-1) elif direction Right: new_x min(self.width-1, x1) if (new_x, new_y) not in self.obstacles: self.agent_pos [new_x, new_y] return self.agent_pos应对不确定性的Agent改进策略概率地图维护class ProbabilisticAgent(GoalBasedAgent): def __init__(self, env): super().__init__(env) self.dirt_prob [[0.5 for _ in range(env.width)] for _ in range(env.height)] def update_probabilities(self, x, y, dirty): # 更新当前格子概率 self.dirt_prob[y][x] 0.1 if not dirty else 0.9 # 扩散影响邻近格子 for dx, dy in [(0,1),(1,0),(0,-1),(-1,0)]: nx, ny xdx, ydy if 0 nx self.env.width and 0 ny self.env.height: if dirty: self.dirt_prob[ny][nx] min(1.0, self.dirt_prob[ny][nx] 0.2) else: self.dirt_prob[ny][nx] max(0.0, self.dirt_prob[ny][nx] - 0.1)决策树优化def decide_action(self): x, y self.env.agent_pos if self.env.is_dirty(x, y): return Clean # 选择最高概率的未清洁区域 max_prob 0 target None for i in range(self.env.height): for j in range(self.env.width): if self.dirt_prob[i][j] max_prob and \ (j, i) not in self.env.obstacles: max_prob self.dirt_prob[i][j] target (j, i) if target and max_prob 0.3: path self.calculate_path(target) return path[0] if path else NoOp return NoOp性能度量函数def performance_measure(self): clean_score sum(not cell[dirty] for row in self.env.grid for cell in row) move_penalty -0.1 * self.move_count obstacle_penalty -1 * self.bump_count return clean_score move_penalty obstacle_penalty完整项目应包含以下模块/vacuum_agent │── /env │ ├── world.py # 环境模拟 │ └── visualization.py# 可视化界面 │── /agents │ ├── base.py # Agent基类 │ ├── reflex.py # 反射型Agent │ ├── model_based.py # 基于模型Agent │ └── goal_oriented.py# 目标导向Agent └── main.py # 演示入口运行演示from env.world import StochasticVacuumWorld from agents.goal_oriented import ProbabilisticAgent world StochasticVacuumWorld(5, 5) world.add_obstacle(2, 2) agent ProbabilisticAgent(world) for _ in range(100): action agent.decide_action() # 执行动作并更新显示...

更多文章