Python进阶共 3 步分步检查

实验 2:规则模拟大模型的多轮 ReAct 工具调用具身智能体

实现具身室内环境工具分发器与规则模拟模型的 Thought-Action-Observation 多轮 ReAct 闭环,掌握物品定位、移动抓取搬运以及异常拦截与最大步数熔断机制。

ReAct 框架工具调用具身智能体Observation 反馈熔断保护
上机实验入口

本实验归属于《大模型与具身智能体》课程空间。在独立隔离环境中真实编译运行并逐项核验,步骤通过前不泄露参考代码。

分步实践任务说明

共 3 个核验步骤
01

步骤 1:实现具身工具分发器与结构化 Observation

从标准输入读取 JSON 环境配置,包含 `mode`(`tool` 或 `react`)、`robot_room`、`holding`、`max_steps`、`objects`、`rooms`,当 `mode="tool"` 时按顺序执行 `actions` 列表中的 `[tool_name, arg]` 并逐行打印返回值。 实现 `execute_tool(state, tool_name, arg)`: 1. `locate(obj)`:若正在手持返回 `OBS locate: holding`,若在某房间返回 `OBS locate: in <room>`,否则返回 `ERR_NOT_FOUND: <obj>`; 2. `move_to(room)`:若房间合法则更新 `robot_room` 并返回 `OBS move_to: arrived <room>`,否则返回 `ERR_INVALID_ROOM: <room>`; 3. `pick(obj)`:若空手、物品存在且与机器人在同一房间,则从 `objects` 移除并置入 `holding`,返回 `OBS pick: picked <obj>`; 4. `place(room)`:若正手持物品、房间合法且机器人位于该房间,则放下物品更新 `objects`,返回 `OBS place: placed <obj> in <room>`。

02

步骤 2:实现规则模拟模型的 ReAct 多轮搬运循环

当 `mode="react"` 时,解析自然语言任务(如 `把 cup 从 kitchen 搬到 study` 或 `把 cup 搬到 study`),在 `run_react(state, task_text)` 中执行最多 `max_steps` 轮 Thought -> Action -> Observation 循环。 每步按优先级决策并输出 `STEP <k> | THOUGHT: <thought> | ACTION: <tool>(<arg>) | OBS: <obs>`: 1. 已手持目标物品:若不在目标房间则 `thought=move_to_target` 调用 `move_to(target)`,否则 `thought=place_object` 调用 `place(target)`; 2. 尚未定位目标物品:`thought=locate_object` 调用 `locate(obj)`(若查明已在目标房间则直接输出 `FINISH: <obj> in <target>`); 3. 手中握有其他物品:先 `thought=release_holding` 调用 `place(robot_room)` 释放夹爪; 4. 机器人不在物品所在房间:`thought=move_to_object` 调用 `move_to(obj_room)`; 5. 机器人已在物品所在房间且空手:`thought=pick_object` 调用 `pick(obj)`。 成功将目标物品放入目标房间后,追加输出一行 `FINISH: <obj> in <target>` 并结束。

03

步骤 3:异常动作拦截与最大步数熔断保护

完善异常拦截与熔断机制: 1. 工具层异常返回格式: - 物品不存在:`ERR_NOT_FOUND: <obj>`; - 未到达物品所在房间就抓取:`ERR_WRONG_ROOM: robot in <robot_room>, <obj> in <obj_room>`; - 手上已有物品时重复抓取:`ERR_HAND_FULL: holding <holding_obj>`; - 空手放置:`ERR_HAND_EMPTY: nothing to place`; 2. ReAct 循环层熔断: - 若 `locate` 返回 `ERR_NOT_FOUND`,立即输出 `ABORT_NOT_FOUND: <obj>` 并终止; - 若执行满 `max_steps` 步仍未完成搬运,输出 `ABORT_MAX_STEPS` 并终止。

起步代码框架预览

Python
import json
import re
import sys


def execute_tool(state, tool_name, arg):
    """具身工具分发器:支持 locate、move_to、pick、place,返回结构化 Observation 字符串。"""
    # TODO 1: 实现 locate(obj)、move_to(room)、pick(obj)、place(room) 与异常拦截
    raise NotImplementedError("请补全 execute_tool")


def parse_task(task_text):
    """从自然语言搬运指令中提取 (物品名, 目标房间)。"""
    m = re.search(r"把\s*(\S+)\s*(?:从\s*\S+\s*)?搬到\s*(\S+)", task_text)
    if not m:
        return None, None
    return m.group(1), m.group(2)


def run_react(state, task_text):
    """基于规则模拟大模型执行 Thought -> Action -> Observation 多轮循环,返回输出行列表。"""
    # TODO 2: 实现 ReAct 多轮推理与工具调用循环,并在完成时输出 FINISH
    # TODO 3: 实现物品不存在与超过 max_steps 时的 ABORT_MAX_STEPS 熔断保护
    raise NotImplementedError("请补全 run_react")


def main():
    raw = sys.stdin.read().strip()
    if not raw:
        return
    cfg = json.loads(raw)
    state = {
        "robot_room": cfg["robot_room"],
        "holding": cfg.get("holding"),
        "max_steps": int(cfg.get("max_steps", 10)),
        "objects": dict(cfg.get("objects", {})),
        "rooms": list(cfg.get("rooms", [])),
    }
    mode = cfg.get("mode", "react")
    if mode == "tool":
        for tool_name, arg in cfg.get("actions", []):
            print(execute_tool(state, tool_name, arg))
    else:
        for line in run_react(state, cfg.get("task", "")):
            print(line)


if __name__ == "__main__":
    main()