SimWorld 快速上手教程:用 Gym-like 接口打造 LLM 驱动导航智能体(附完整代码)

原创2026-10-26 21:36:35643 阅读

SimWorld 快速上手教程:用 Gym-like 接口打造 LLM 驱动导航智能体(附完整代码)

SimWorld 是一个基于 Unreal Engine 5 的开源仿真平台,专为在物理与社会世界中开发 LLM/VLM 智能体而设计。本教程将带你完成 SimWorld 快速上手:只需 3 步安装、约 100 行 Python 代码,即可用 Gym-like 接口(reset/step 循环) 打造一个由大语言模型驱动的导航智能体,让它在逼真 3D 城市中自主规划路线、走向目标位置。无论你是刚接触具身智能(Embodied AI)的新手,还是想快速验证 LLM Agent 想法的开发者,这篇文章都能让你在 30 分钟内跑通第一个导航任务。

SimWorld 仿真世界总览:基于 Unreal Engine 5UE的城市环境与智能体交互平台

一、为什么选择 SimWorld?

SimWorld 提供了三个对 LLM 智能体研究至关重要的能力:

  • 逼真的开放式世界:基于 UE5 的精确物理仿真与语言驱动的城市场景程序化生成;
  • 丰富的多模态接口:智能体可同时获取 RGB 图像、深度图、分割图等传感器数据,并用自然语言输出动作;
  • Gym-like 交互范式:熟悉强化学习 Gym 接口的同学会发现,reset() / step() 的心智模型完全一致,迁移成本极低。

整体架构分为三层:Unreal Engine 后端提供高保真场景与物理;Environment 层封装地图、交通、城市场景与 Gym 接口;Agent 层负责让 LLM/VLM 基于多模态观测进行推理并执行动作。

SimWorld 三层架构:UE后端、Environment层与Agent层通过UnrealCV+通信

二、安装前硬件要求

在开始之前,请确认你的设备满足以下最低要求(来自官方 installation.rst):

类别 最低要求 推荐配置
操作系统 Windows / Linux Windows / Linux
GPU 独立显卡 ≥ 6 GB 显存 ≥ 8 GB 显存
内存 32 GB 32 GB 以上
磁盘空间 50 GB(Base 包) 200 GB+(含扩展环境)

⚠️ 注意:需要 Python 3.10+,且客户端与 UE 服务器之间默认使用 9000 端口通信,请确保该端口可用。

三、一键安装步骤

第 1 步:安装 Python 客户端

git clone https://gitcode.com/gh_mirrors/sim/SimWorld
cd SimWorld
conda create -n simworld python=3.10
conda activate simworld
pip install -e .

第 2 步:下载 UE 服务端(Base 包)

Base 包含 2 个轻量城市场景和 1 张空地图,足够完成本教程的导航任务。按你的操作系统下载解压即可(下载链接见官方文档 installation.rst)。

第 3 步:启动 UE 服务器

在解压后的 UE 服务端目录下运行:

# Windows
./SimWorld.exe /Game/Maps/demo_1.umap

# Linux
./SimWorld.sh /Game/Maps/demo_1.umap

不指定地图参数时默认加载 /Game/Maps/demo_1。启动后保持运行,Python 端会自动通过 9000 端口与之连接。

四、Gym-like 接口核心拆解

官方示例 gym_interface_demo.ipynb 是整个项目的"最小完整闭环",结构如下:

组件 文件位置 职责
Agent 示例 notebook 内定义 用 LLM 决策导航动作
Environment 示例 notebook 内定义 Gym 接口:reset() / step()
LLM 基类 simworld/llm/base_llm.py 统一的 generate_text 接口,内置重试机制
人形智能体 simworld/agent/humanoid.py 封装 UE 中的人形角色状态
通信器 simworld/communicator/communicator.py 与 UE 服务端的指令交互入口

观测(Observation)长什么样?

每一步智能体收到的观测是一个字典,包含三个键:

  • position:2D 世界坐标(Vector);
  • direction:朝向单位向量;
  • ego_view:第一人称 RGB 图像(默认 640×480)。

SimWorld 的传感器系统远比一张 RGB 图丰富,你还可以获取分割图与深度图(见官方文档 ue_detail.rst),为 VLM 智能体提供更强的感知输入:

SimWorld 传感器输出示例:同一场景的RGB图像、语义分割图与深度图

动作空间(Action Space)

本教程中 LLM 只需输出三种命令之一:

动作格式 示例 含义
forward <duration> forward 2 向前行走 2 秒
rotate <angle> <left/right> rotate 45 left 向左旋转 45°
wait wait 原地等待 1 秒

奖励函数(reward)为到目标点的负距离——越接近目标得分越高。目标点设为 Vector(1700, -1700),智能体从原点 (0, 0) 出发。

具身智能体闭环:Language Model 与 Memory 驱动 Embodied Agent,接收 Observation 后输出动作

五、完整代码实现

5.1 初始化通信器

from simworld.config import Config
from simworld.communicator.communicator import Communicator
from simworld.communicator.unrealcv import UnrealCV
from simworld.llm.base_llm import BaseLLM
from simworld.map.map import Map
from simworld.agent.humanoid import Humanoid
from simworld.utils.vector import Vector

# 连接 UE 服务器(默认 9000 端口)
communicator = Communicator(UnrealCV())

import os
os.environ['OPENAI_API_KEY'] = '<your_openai_api_key>'

5.2 定义 LLM 导航智能体

Agent 类的核心思路:把当前位置、朝向、与目标的夹角差等信息拼进 prompt,让 LLM 只输出一个动作命令。

class Agent:
    def __init__(self):
        self.llm = BaseLLM("gpt-4o")
        self.system_prompt = """You are an intelligent agent in a 3D simulation world.
Your task is to navigate to the target position by choosing appropriate actions.
You can only output ONE of the following actions:
- "forward <duration>": Move forward for <duration> seconds (e.g., "forward 2")
- "rotate <angle> <direction>": Rotate <angle> degrees in <direction> (left/right)
- "wait": Do nothing for 1 second
Output ONLY the action command, nothing else."""

    def action(self, obs, target):
        position, direction = obs['position'], obs['direction']
        # 计算当前朝向 yaw 与目标夹角差(归一化到 [-180, 180])
        current_yaw = math.degrees(math.atan2(direction.y, direction.x))
        target_angle = math.degrees(math.atan2(target.y - position.y,
                                               target.x - position.x))
        angle_diff = target_angle - current_yaw
        # ... 归一化到 [-180, 180] ...

        prompt = f"""Current position: {position}
Current direction: {direction} (yaw: {current_yaw:.1f}°)
Target position: {target}
Distance to target: {position.distance(target):.1f}
Angle to target: {angle_diff:.1f}° (positive = turn left, negative = turn right)

Choose your next action to move closer to the target."""
        action, _ = self.llm.generate_text(
            system_prompt=self.system_prompt, user_prompt=prompt)
        return action

💡 小贴士:BaseLLM 默认支持 OpenAI 兼容接口,你也可以通过 provider='local' 接入 vLLM 等本地服务,详见 base_llm.py。

5.3 定义 Gym-like 环境

Environment 封装了 spawn(生成智能体)、动作执行与奖励计算,是标准 Gym 模式:

class Environment:
    def __init__(self, communicator, config=Config()):
        self.communicator = communicator
        self.config = config
        self.map = Map(config)
        self.map.initialize_map_from_file(
            roads_file='../data/example_city/demo_city_1/roads.json')
        self.agent = None
        self.agent_spawned = False

    def reset(self):
        """生成/重置人形智能体,返回初始观测。"""
        agent_bp = "/Game/TrafficSystem/Pedestrian/Base_User_Agent.Base_User_Agent_C"
        spawn_location, spawn_forward = Vector(0, 0), Vector(1, 0)

        if not self.agent_spawned:
            self.agent = Humanoid(communicator=self.communicator,
                                  position=spawn_location,
                                  direction=spawn_forward,
                                  config=self.config, map=self.map)
            # 在 UE 世界中生成人形智能体
            self.communicator.spawn_agent(self.agent, name=None,
                                         model_path=agent_bp, type="humanoid")
            self.communicator.humanoid_set_speed(self.agent.id, 200)
            self.agent_name = self.communicator.get_humanoid_name(self.agent.id)
            self.agent_spawned = True
        # ... 已有智能体则通过 set_location/set_orientation 重置 ...

        self.target = Vector(1700, -1700)
        time.sleep(5)  # 等待生成完成

        # 获取初始观测:位置、朝向、第一人称图像
        loc_3d = self.communicator.unrealcv.get_location(self.agent_name)
        position = Vector(loc_3d[0], loc_3d[1])
        yaw = self.communicator.unrealcv.get_orientation(self.agent_name)[1]
        direction = Vector(math.cos(math.radians(yaw)),
                           math.sin(math.radians(yaw)))
        ego_view = self.communicator.get_camera_observation(
            self.agent.camera_id, "lit")
        return {'position': position, 'direction': direction,
                'ego_view': ego_view}

    def step(self, action):
        """解析并执行动作,返回 (观测, 奖励, 是否成功)。"""
        action_lower = action.strip().strip('"').strip("'").lower()
        success = False
        if action_lower.startswith("forward"):
            match = re.search(r'forward\s+(\d+\.?\d*)', action_lower)
            if match:
                self.communicator.humanoid_step_forward(
                    self.agent.id, float(match.group(1)), direction=0)
                success = True
        elif action_lower.startswith("rotate"):
            match = re.search(r'rotate\s+(\d+\.?\d*)\s+(left|right)',
                              action_lower)
            if match:
                self.communicator.humanoid_rotate(
                    self.agent.id, float(match.group(1)), match.group(2))
                success = True
        elif action_lower == "wait":
            time.sleep(1)
            success = True

        # 更新状态并计算奖励(负距离,越近越好)
        position = self._update_position()
        ego_view = self.communicator.get_camera_observation(
            self.agent.camera_id, "lit")
        obs = {'position': position, 'direction': self._get_direction(),
               'ego_view': ego_view}
        reward = -position.distance(self.target)
        return obs, reward, success

5.4 主循环:观测 → 决策 → 执行

agent = Agent()
env = Environment(communicator)
obs = env.reset()

for i in range(100):
    action = agent.action(obs, env.target)          # LLM 决策
    print(f"Step {i+1}: Action = '{action}'")
    obs, reward, success = env.step(action)          # 执行并观测
    if success and obs['position'].distance(env.target) < 200:
        print("Target reached! 🎉")
        break

communicator.disconnect()   # 记得断开连接

这就是完整的"观测-决策-执行"闭环:智能体每步读取位置、朝向与第一人称视角,由 LLM 输出一条动作命令,环境在 UE 中执行后返回新观测与奖励,直到距离目标小于 200 单位判定成功。

SimWorld 场景中的街道设施示例:城市广告牌等可交互场景资产

六、常见问题排查(FAQ)

问题 可能原因 解决办法
No OpenAI API key provided 未设置 API Key 运行 export OPENAI_API_KEY="<your_api_key>" 或在代码中 os.environ 设置
连接 UE 失败 / 无响应 服务器未启动或端口被占用 确认 UE 服务器已运行,检查 9000 端口;如改过端口,可用 --cvport 参数或修改 unrealcv.ini
智能体生成后静止不动 reset() 后未等待 保留 time.sleep(5),确保 UE 侧生成完成
LLM 返回动作解析失败 模型输出了多余文字 检查 system prompt 约束;step() 已内置引号剥离与正则容错
图像分辨率不符预期 默认 640×480 使用 set_camera_resolution() 自定义

七、配置与进阶:让智能体更强

自定义配置文件

SimWorld 使用 YAML 控制全局参数。复制模板后按需修改(见 config/example.yaml):

cp config/example.yaml config/your_config.yaml
from simworld.config import Config
config = Config('/path/to/config/your_config.yaml')

核心参数速查(完整参考见 configuration.rst):

参数 类型 说明
seed int 随机种子,默认 42,用于复现实验
dt float 仿真时间步长(秒),默认 0.1
user.llm_model_path str 智能体使用的 LLM 模型名
user.speed float 用户智能体移动速度

下一步探索方向

  • 🗺️ 换一张地图:把 reset() 中的目标点改到别处,或加载其他示例地图,见 map.ipynb;
  • 🚦 加入交通流:调用交通控制器生成车辆与信号灯,让导航更真实,见 traffic_simulation.ipynb;
  • 🏙️ 程序化生成城市:随机生成路网、建筑与街景元素,见 layout_generation.ipynb;
  • 📷 多传感器观测:获取深度图与分割图喂给 VLM,见 camera.ipynb;
  • 🎭 自定义环境与资产:打包你自己的 UE 场景为 .pak 文件导入 SimWorld,见 make_your_own_pak.rst。

全部示例代码集中在 examples/ 目录,配套的完整 API 说明可查阅 ue_command.ipynb。

八、总结

通过本教程,你已经完成了 SimWorld 快速上手的全流程:

  1. 安装 Python 客户端 + 下载 UE Base 服务端并启动;
  2. 构建 Agent(LLM 决策)与 Environment(Gym-like reset/step)两大核心类;
  3. 跑通 观测 → 决策 → 执行的最小导航闭环,并掌握常见报错的排查方式。

SimWorld 的价值在于把"高保真世界 + LLM 推理 + Gym 交互范式"三者无缝结合。从这里出发,你可以轻松扩展出更复杂的任务:多智能体协作、长程规划、基于视觉的目标检索……具身智能的探索之旅,现在正式启程 🚀

登录后查看全文
SimWorld