From Gameplay Recordings to Training Samples: Building Long-Horizon Task Agents

    This article explains how to transform raw gameplay recordings into structured training samples for long-horizon task agents. It covers time alignment of frames and input events, layered intent annotation, data cleaning, mixed-source sampling by token ratio, evaluation strategies, and practical recommendations to help models move from single-step imitation to goal-directed planning.

    Why Operation Logs Are Not Enough for Long-Horizon Agents

    Keyboard and mouse logs record what the player did, but not why. The same turning action could mean avoiding an obstacle or moving toward a task target. If a model only learns a mapping from pixels to keystrokes, it captures surface patterns and fails to maintain goal consistency over long task chains.

    Long-horizon tasks—such as completing a main quest that involves multiple dialogues, fights, and explorations—require continuous decision-making for tens of minutes or even hours. The model must determine which subtask it is in, what to do next, and when to switch goals. Therefore, training data must contain three types of aligned information:

    • Observations: screen frames, UI text, character states, and other visual signals.
    • Actions: mouse movements, clicks, key presses, and combinations.
    • Intentions: the subgoal and task that the current action serves.

    Only when these three are aligned can the model transition from “imitating actions” to “executing based on goals.”

    Time Alignment: Putting Frames and Actions on the Same Timeline

    The first step in data processing is alignment. Recorded frames and input events are usually captured by different modules with different clocks and sampling rates. Directly concatenating them causes mismatches between actions and frames.

    A common approach:

    1. Record a unified timestamp for every frame and input event, using the same clock source.
    2. Sample frames at a fixed rate (e.g., 10 FPS).
    3. Merge input events within each time window into the corresponding frame.
    4. Check the latency distribution and remove segments with visible time drift.

    Below is a simplified merge example:

    1. def align_events(frames, events, fps=10):
    2. """Merge input events into corresponding frames by timestamp.
    3. frames: list of frames in chronological order
    4. events: list of input events sorted by timestamp, each with a "t" field (seconds)
    5. """
    6. aligned = []
    7. j = 0
    8. for i, frame in enumerate(frames):
    9. t = i / fps
    10. window = []
    11. while j < len(events) and events[j]["t"] <= t:
    12. window.append(events[j])
    13. j += 1
    14. aligned.append({"frame_id": i, "t": t, "actions": window})
    15. return aligned

    After alignment, each frame corresponds to a clear set of actions, providing a reliable basis for subsequent intent annotation.

    Reconstructing Task Progress from Behavior Segments

    Once aligned, the continuous action stream must be split into semantically meaningful segments and annotated with their goals. This step determines whether the model can learn long-range planning capabilities.

    Layered Annotation Structure

    A three-level structure is recommended for describing a recording:

    • Task: a complete goal, e.g., “complete a certain commission.”
    • Subgoal: a stage within the task, e.g., “go to the target location” or “talk to an NPC.”
    • Atomic action: the smallest operation unit, e.g., move, click, key press.
    1. {
    2. "episode_id": "ep_000123",
    3. "task": "Complete the current main quest",
    4. "subgoals": [
    5. {
    6. "name": "Reach the target location",
    7. "start_frame": 0,
    8. "end_frame": 1840,
    9. "actions": ["move_forward", "turn_left", "sprint"]
    10. },
    11. {
    12. "name": "Talk to the NPC",
    13. "start_frame": 1841,
    14. "end_frame": 2310,
    15. "actions": ["interact", "select_option"]
    16. }
    17. ]
    18. }

    Annotation Methods

    Intent annotation typically combines three approaches:

    • Rule-based assistance: use UI markers, quest log text, or state changes as segmentation signals—low cost and stable accuracy.
    • Model-based assistance: use an existing model to generate candidate labels for segments, then manually spot-check and correct.
    • Manual review: thoroughly inspect key tasks and boundary segments to ensure label consistency.

    Annotation guidelines must be defined in advance, including the granularity of subgoals, boundary conditions for segmentation, and how to handle “meaningless actions.” The clearer the guidelines, the higher the inter-annotator agreement.

    Data Sources and Cleaning

    Training data usually comes from multiple sources. Public game interaction datasets offer broad coverage and are useful for learning general operation patterns. Internal trajectories from a specific game better reflect the real structure of long-horizon tasks. When using public datasets, check their license terms to confirm permitted use.

    Cleaning mainly addresses the following issues:

    • Idle segments: long periods without action or static frames dilute effective signal and should be filtered by threshold.
    • Duplicate data: repeated segments from the same recording cause overfitting and should be deduplicated.
    • Abnormal inputs: transient misclicks or device latency can create abnormal events—detect and remove them after alignment.
    • Privacy and sensitive information: recordings may contain account names, in-game nicknames, or other personal data that must be anonymized.

    After cleaning, compute statistics on total duration, segment count, and task distribution to ensure adequate coverage across task types.

    Mixed Training: Sampling by Token Ratio

    During continued pretraining, game interaction data is usually mixed with general multimodal data. General data (e.g., image-text understanding, visual reasoning) helps maintain the model’s general visual capabilities and prevents it from becoming overly specialized to a single game interface.

    If the mix ratio is defined in terms of tokens—for example, 85% game data and 15% general multimodal data—simple sample-count sampling is insufficient because the average length of samples in each class may differ significantly. Let the target token ratio for class $i$ be $r_i$ and the average sample length be $L_i$. The probability of sampling from that class should satisfy:

    $p_i \propto \frac{r_i}{L_i}$

    Implementation example:

    1. import random
    2. def build_sampler(ratios, avg_lengths):
    3. """Compute sampling probabilities based on token ratios."""
    4. names = list(ratios)
    5. weights = [ratios[n] / avg_lengths[n] for n in names]
    6. total = sum(weights)
    7. probs = [w / total for w in weights]
    8. return names, probs
    9. def sample_source(names, probs):
    10. return random.choices(names, weights=probs, k=1)[0]
    11. names, probs = build_sampler(
    12. ratios={"game_trajectory": 0.85, "general_multimodal": 0.15},
    13. avg_lengths={"game_trajectory": 1800, "general_multimodal": 600},
    14. )

    Sampling weights should be checked against actual token statistics from the training log to confirm that the real proportions are close to the targets.

    Evaluation and Common Risks

    Evaluating a long-horizon agent requires more than per-action accuracy. Consider the following perspectives:

    • Per-step metrics: accuracy and latency of action prediction.
    • Subgoal completion rate: whether the model completes each stage in order.
    • Long-horizon success rate: the proportion of full tasks that achieve the final goal.
    • General capability retention: performance on general multimodal benchmarks to detect forgetting.

    Key risks to watch:

    1. Distribution shift: game version updates or UI changes can invalidate model behavior.
    2. Catastrophic forgetting: too high a proportion of game data may degrade general visual reasoning.
    3. Error accumulation: small mistakes early in a long task can cause later decisions to drift from the goal—evaluate error location separately.
    4. Annotation bias: model-assisted annotation may introduce systematic errors; perform regular spot checks.

    Practical Recommendations

    • Fix the time alignment and annotation guidelines before scaling up the data to avoid rework.
    • Store intent annotations separately from action data to allow independent corrections.
    • After each adjustment of the mix ratio, monitor both game-task metrics and general metrics to ensure they do not trade off against each other.
    • Keep a manifest of data versions and sampling configurations for every training run to ensure reproducibility.

    Following these steps, teams can gradually convert raw gameplay recordings into structured training samples, enabling models to move from single-step imitation to planning and execution in long-horizon tasks.