0Pricing
AI Agents · 강의

세계 모델과 예측 계획

행동하기 전에 미래 상태를 시뮬레이션하는 에이전트: 인공지능을 위한 심적 시뮬레이션.

세계 모델과 예측 계획은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.

월드 모델이란 무엇입니까?

월드 모델은 환경에 대한 에이전트의 내부 표현입니다. 어떤 객체가 존재하는지, 객체의 상태가 어떤지, 객체가 어떻게 변하는지를 지배하는 규칙은 무엇인지, 에이전트가 객체에 영향을 주기 위해 무엇을 할 수 있는지를 나타냅니다. 이는 에이전트가 세계를 머릿속으로 시뮬레이션한 것입니다.

월드 모델이 없으면 에이전트는 관찰에만 반응할 수 있습니다. 월드 모델이 있으면 예측하고 계획을 세울 수 있습니다.

월드 상태 표현

월드 상태는 특정 시점의 환경에 관한 모든 관련 사실을 한데 담은 스냅샷입니다. IoT 에이전트의 경우 현재 센서 판독값과 기기 상태가 이에 해당할 수 있습니다. 소프트웨어 에이전트의 경우 관리하는 파일, API, 데이터베이스의 상태가 이에 해당할 수 있습니다.

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에 요청합니다. 이렇게 하면 정밀도와 일반성을 맞바꾸게 됩니다. 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)

반사실적 추론

세계 모델을 사용하면 반사실적 추론이 가능해집니다. '행동 B 대신 행동 A를 했다면 무슨 일이 일어났을까?' 이는 실수를 반복하지 않고도 실수에서 배우게 해 주므로 강력합니다. 에이전트는 반사실적 상황을 시뮬레이션하여 자신의 선택이 왜 최적이 아닌 결과로 이어졌는지 이해할 수 있습니다.

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: 형식화하기 어려운 영역에서 효과적입니다
  • 불확실성: 단일 추정값이 아니라 분포를 유지하고, 불확실성이 높을 때는 행동을 피합니다
  • 최신성 저하: 모델이 오래되었다면 위험도가 높은 행동 전에 다시 관찰합니다

다음 주제는 정렬 과제입니다. 진정으로 유익한 자율 에이전트를 만들기 어려운 이유를 살펴봅니다.

자주 묻는 질문

“세계 모델과 예측 계획” 강의는 무료인가요?

네 — “세계 모델과 예측 계획” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.

“세계 모델과 예측 계획”에서 뭘 배우나요?

행동하기 전에 미래 상태를 시뮬레이션하는 에이전트: 인공지능을 위한 심적 시뮬레이션. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Agents을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“세계 모델과 예측 계획” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 도우미에서 자율 에이전트로
  2. 세계 모델과 예측 계획
  3. 자율 에이전트의 정렬 과제
  4. 연구의 최전선: AGI와 그 너머
← AI Agents(으)로 돌아가기