世界模型与预测性规划
在行动前模拟未来状态的代理:人工智能的心理模拟。
世界模型与预测性规划 是 CoddyKit 上的免费 AI Agents 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。
什么是世界模型
世界模型是智能体对环境的内部表示:有哪些对象存在,它们处于什么状态,哪些规则决定它们如何变化,以及智能体可以采取哪些行动来影响它们。它是智能体对世界进行的心理模拟。
没有世界模型,智能体只能对观察结果做出反应。有了世界模型,它就能够预测和规划。
世界状态表示
世界状态是在某个时间点对环境中所有相关事实的快照。对于物联网智能体,这可能包括当前的传感器读数和设备状态。对于软件智能体,这可能包括它所管理的文件、应用程序接口和数据库的状态。
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
@dataclass
class WorldState:
timestamp: str = ''
entities: dict = field(default_factory=dict) # entity_id -> attributes
relationships: list = field(default_factory=list)
agent_position: str = 'idle'
pending_actions: list = field(default_factory=list)
def __post_init__(self):
if not self.timestamp:
self.timestamp = datetime.utcnow().isoformat()
def update_entity(self, entity_id: str, attributes: dict):
current = self.entities.get(entity_id, {})
self.entities[entity_id] = {**current, **attributes}
def snapshot(self) -> dict:
return {
'timestamp': self.timestamp,
'entities': dict(self.entities),
'agent_position': self.agent_position
}
# Example:
world = WorldState()
world.update_entity('server_room', {'temp_c': 22.5, 'humidity': 55})
world.update_entity('hvac_unit_1', {'status': 'off', 'setpoint': 22})
print(world.snapshot())转移模型
转移模型定义世界状态如何响应某个行动而发生变化:next_state = transition(current_state, action)。它可以让智能体预测采取某个行动后世界会呈现什么样子,而无需真正执行该行动。
import copy
def transition(state: WorldState, action: dict) -> WorldState:
"""
Predict next state given current state and action.
Returns a new WorldState (does not modify original).
"""
next_state = copy.deepcopy(state)
action_type = action.get('type')
target = action.get('target')
params = action.get('params', {})
if action_type == 'TURN_ON_HVAC':
next_state.update_entity(target, {
'status': 'on',
'setpoint': params.get('setpoint', 22)
})
# Simulate temperature effect (simplified linear model)
room = action.get('room', 'server_room')
current_temp = next_state.entities.get(room, {}).get('temp_c', 25)
next_state.update_entity(room, {
'temp_c': max(current_temp - 2, params.get('setpoint', 22))
})
elif action_type == 'SEND_ALERT':
next_state.pending_actions.append({'alert_sent': True})
return next_state
# Predict effect of turning on HVAC:
action = {'type': 'TURN_ON_HVAC', 'target': 'hvac_unit_1',
'room': 'server_room', 'params': {'setpoint': 20}}
next_world = transition(world, action)
print('After action:', next_world.entities.get('server_room'))前瞻式规划
前瞻式规划会在决定采取某个行动之前,模拟未来的 N 个步骤。智能体会探索多个行动序列,评估每个序列产生的状态,并选择能够带来最佳预测结果的序列。
def evaluate_state(state: WorldState) -> float:
"""
Compute a scalar utility score for a world state.
Higher = better for the agent's goals.
"""
score = 1.0
server_room = state.entities.get('server_room', {})
temp = server_room.get('temp_c', 25)
# Penalty for high temperature
if temp > 30:
score -= (temp - 30) * 0.2
# Penalty for very low temperature (over-cooling)
if temp < 18:
score -= (18 - temp) * 0.1
return max(0.0, score)
def lookahead(state: WorldState, possible_actions: list, depth: int = 3) -> dict:
"""Evaluate top-level actions by simulating depth steps ahead."""
best_action = None
best_score = -float('inf')
for action in possible_actions:
simulated = transition(state, action)
# Simulate depth more steps (simplified: no branching)
for _ in range(depth - 1):
simulated = transition(simulated, {'type': 'NOOP'})
score = evaluate_state(simulated)
if score > best_score:
best_score = score
best_action = action
return {'best_action': best_action, 'expected_score': round(best_score, 3)}作为世界模型的 LLM
对于复杂且难以形式化的环境,LLM 本身可以充当世界模型。您可以要求它预测智能体采取某个特定行动后会发生什么。这种方法以精确性换取通用性——LLM 可以对任意领域进行推理。
import anthropic
import json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
def llm_predict(
current_state: dict,
proposed_action: dict,
domain_description: str = ''
) -> dict:
prompt = (
f'Domain: {domain_description}\n\n'
f'Current state: {json.dumps(current_state, indent=2)}\n\n'
f'Proposed action: {json.dumps(proposed_action, indent=2)}\n\n'
'Predict the next world state after this action. '
'Consider direct effects and second-order effects.\n'
'Return JSON: {"predicted_state": dict, '
'"confidence": float, "side_effects": [str]}'
)
response = client.messages.create(
model='claude-opus-4-5', max_tokens=512,
messages=[{'role': 'user', 'content': prompt}]
)
return json.loads(response.content[0].text)基于模型与无模型规划
基于模型:智能体拥有明确的世界模型,能够模拟未来状态并进行规划。样本利用率更高,泛化能力更强。无模型:智能体无需模型,而是从经验中学习行动与价值之间的对应关系。方法更简单,但需要更多交互才能学会策略。
# Comparison table
COMPARISON = {
'model_based': {
'pros': [
'Can plan before acting (lookahead)',
'Works well with limited data',
'Interpretable — you can inspect the world model',
'Can simulate counterfactuals'
],
'cons': [
'Model can be wrong (model mismatch)',
'Complex to build for arbitrary domains',
'Planning is computationally expensive'
],
'examples': 'AlphaGo, MCTS, agent with explicit WorldState'
},
'model_free': {
'pros': [
'No need to model the world explicitly',
'Learns from raw experience',
'Simpler architecture'
],
'cons': [
'Requires many interactions to learn',
'Poor generalisation to new scenarios',
'Cannot reason about unseen situations'
],
'examples': 'Q-learning, policy gradient, basic RLHF'
}
}
for approach, info in COMPARISON.items():
print(f'{approach}: {info["examples"]}')世界模型中的不确定性
世界模型都是近似模型。请通过维护可能状态的概率分布,而不是单个点估计,来考虑不确定性。当不确定性较高时,请采取保守行动,或在行动前收集更多信息。
from statistics import mean, stdev
@dataclass
class UncertainState:
entity_id: str
attribute: str
samples: list # multiple estimates
def mean(self) -> float:
return mean(self.samples) if self.samples else 0.0
def uncertainty(self) -> float:
if len(self.samples) < 2:
return float('inf')
return stdev(self.samples)
def should_gather_more_data(self, threshold: float = 2.0) -> bool:
return self.uncertainty() > threshold
# Example: uncertain temperature estimate from multiple sensors
temp_state = UncertainState(
entity_id='server_room',
attribute='temp_c',
samples=[22.1, 22.8, 21.9, 34.5, 22.3] # one outlier
)
print(f'Mean temp: {temp_state.mean():.1f}C')
print(f'Uncertainty (stdev): {temp_state.uncertainty():.2f}')
print(f'Gather more data: {temp_state.should_gather_more_data()}')更新世界模型
每次行动后,智能体都会观察实际结果并更新其世界模型。如果预测有误,模型就会得到更新,从而变得更加准确。这就是推动基于模型的智能体学习的观察—更新—规划循环。
class WorldModelAgent:
def __init__(self):
self.world = WorldState()
self.prediction_errors = []
def act(self, action: dict) -> dict:
# 1. Predict next state
predicted = transition(self.world, action)
# 2. Take the action in the real world
actual_observation = self._execute_action(action)
# 3. Measure prediction error
for entity_id, attrs in actual_observation.items():
for attr, actual_val in attrs.items():
predicted_val = predicted.entities.get(entity_id, {}).get(attr)
if predicted_val is not None:
error = abs(actual_val - predicted_val)
self.prediction_errors.append(error)
# 4. Update world model with actual observation
for entity_id, attrs in actual_observation.items():
self.world.update_entity(entity_id, attrs)
return actual_observation
def _execute_action(self, action: dict) -> dict:
# Placeholder — in production this calls real APIs/sensors
return {'server_room': {'temp_c': 23.0}}
def model_accuracy(self) -> float:
if not self.prediction_errors:
return 1.0
return max(0.0, 1.0 - mean(self.prediction_errors) / 10)使用 LLM 进行规划:模拟 3 个步骤
对于自然语言领域,请要求 LLM 在执行计划前模拟拟议计划的 3 个步骤。LLM 会评估每一步的预测结果,并标记潜在问题,从而防止智能体采取可能导致不良预测后果的行动。
import anthropic
import json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
def simulate_plan_steps(goal: str, proposed_steps: list) -> dict:
steps_str = json.dumps(proposed_steps, indent=2)
prompt = (
f'Goal: {goal}\n\n'
f'Proposed plan steps:\n{steps_str}\n\n'
'Simulate executing each step in order. For each step predict:\n'
'- What changes in the world?\n'
'- What could go wrong?\n'
'- Is this step reversible?\n\n'
'Return JSON: {"step_simulations": [{"step": int, '
'"predicted_outcome": str, "risks": [str], "reversible": bool}], '
'"plan_safe": bool, "recommendation": str}'
)
response = client.messages.create(
model='claude-opus-4-5', max_tokens=1024,
messages=[{'role': 'user', 'content': prompt}]
)
result = json.loads(response.content[0].text)
if not result['plan_safe']:
print(f'Plan safety concern: {result["recommendation"]}')
return result何时可以信任世界模型
世界模型的质量取决于其转移函数和初始状态的准确性。在快速变化的环境中,模型会很快过时。请设置一个过时阈值:如果模型在 N 秒内未更新,并且某项操作风险很高,请先重新观察环境。
from datetime import datetime, timedelta
class StaleAwareWorldModel:
def __init__(self, max_age_seconds: int = 60):
self.state = WorldState()
self.max_age = timedelta(seconds=max_age_seconds)
self.last_observation_time = datetime.utcnow()
def is_stale(self) -> bool:
age = datetime.utcnow() - self.last_observation_time
return age > self.max_age
def refresh(self, observation_fn):
new_observations = observation_fn()
for entity_id, attrs in new_observations.items():
self.state.update_entity(entity_id, attrs)
self.last_observation_time = datetime.utcnow()
print(f'World model refreshed')
def plan_action(self, action: dict, observation_fn) -> dict:
if self.is_stale():
print('World model stale — refreshing before planning')
self.refresh(observation_fn)
return lookahead(self.state, [action], depth=3)反事实推理
世界模型支持反事实推理:“如果我采取了行动 A 而不是行动 B,会发生什么?”这对于从错误中学习而不重蹈覆辙非常有用——智能体可以模拟这一反事实情境,从而理解自己的选择为何导致了次优结果。
import anthropic
import json
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
def counterfactual_analysis(
actual_state_before: dict,
action_taken: dict,
actual_outcome: dict,
alternative_action: dict
) -> dict:
prompt = (
'Analyse a counterfactual scenario:\n\n'
f'Initial state: {json.dumps(actual_state_before, indent=2)}\n'
f'Action taken: {json.dumps(action_taken, indent=2)}\n'
f'Actual outcome: {json.dumps(actual_outcome, indent=2)}\n\n'
f'Alternative action considered: {json.dumps(alternative_action, indent=2)}\n\n'
'What would likely have happened with the alternative action?\n'
'Return JSON: {"counterfactual_outcome": str, '
'"better_choice": str, "lesson": str}'
)
response = client.messages.create(
model='claude-opus-4-5', max_tokens=512,
messages=[{'role': 'user', 'content': prompt}]
)
return json.loads(response.content[0].text)知识检查
与无模型智能体相比,基于模型的智能体的主要优势是什么?
回顾:世界模型与预测性规划
做得很好!关键要点:
- 世界状态:某一时刻所有相关实体属性的快照
- 转移模型:
next_state = transition(state, action)——预测影响 - 前瞻:模拟未来 N 步,评估结果并选择最佳行动
- 作为世界模型的 LLM:适用于难以形式化的领域
- 不确定性:维护概率分布,而不是单点估计;避免在不确定性很高时采取行动
- 过时问题:如果模型已经陈旧,在高风险操作前重新观察环境
接下来:对齐挑战——为什么构建真正有益的自主智能体很困难。
常见问题解答
「世界模型与预测性规划」课时是免费的吗?
是的 — 「世界模型与预测性规划」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。
「世界模型与预测性规划」这节课中我会学到什么?
在行动前模拟未来状态的代理:人工智能的心理模拟。 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Agents 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「世界模型与预测性规划」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Agents 课中编写并运行代码吗?
能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 从助手到自主智能体
- 世界模型与预测性规划
- 自主智能体的对齐挑战
- 研究前沿:AGI 及 beyond