Reinforcement Learning Recipes and Cost Practices for Long-Horizon Agents

    Long-horizon agent tasks require complex multi-turn tool usage, state maintenance, and error recovery, posing unique challenges for reinforcement learning (RL). Drawing from a public experiment that trained a 300-billion parameter model using 64 GPUs in under 5 days to achieve a 46.2% success rate with an average cost of $0.72 per task, this article abstracts a reusable RL recipe for long-horizon agents. We explore a five-stage closed-loop system covering task and environment construction, trajectory filtering, reward design, stable full-parameter updates, and cost evaluation. By addressing sparse rewards, credit assignment, and non-linear cost growth, this guide helps practitioners transition agent training from occasional successes to robust engineering systems.

    Long-horizon agent tasks are becoming a critical benchmark for model engineering capabilities. Unlike single-turn Q&A, these tasks require multi-turn tool calls, cross-step state maintenance, failure retries, and result verification. A single trajectory can span tens or even hundreds of turns. The model must not only “answer correctly” but also maintain goal consistency, ensure error recovery, and control costs throughout the long chain. A notable public experiment trained a 300-billion parameter model using full-parameter RL. It completed training in under 5 days using 64 accelerator cards, achieving a 46.2% score on a terminal agent benchmark. The disclosed average cost per task was about $0.72, compared to roughly $22.02 for a high-effort configuration. This article does not discuss specific products but abstracts a reusable RL recipe for long-horizon agents from this public experiment.

    1. Why Long-Horizon Tasks Are Difficult

    The core challenge of long-horizon agent tasks is not single-step reasoning but “long-chain stability.” First, rewards are sparse. Success is often only verified at the final step, leaving intermediate steps without explicit supervision, causing the model to lose direction midway. Second, credit assignment is difficult. A final failure might stem from an early erroneous tool call, but RL must determine which step deserves the penalty. Third, environmental noise is high. Tool timeouts, format changes, empty results, and permission errors shift the trajectory distribution. Fourth, costs grow non-linearly with the number of turns. More turns mean higher sampling, verification, and retry costs; without filtering, training is dragged down by a large volume of low-value trajectories. Therefore, an RL recipe for long-horizon agents must solve both “learning correctly” and “learning affordably.”

    2. Recipe Overview: A Five-Stage Closed Loop

    A complete recipe can be divided into five stages: Task and Environment Construction, Trajectory Sampling and Filtering, Reward and Verification, Full-Parameter RL Update, and Cost and Evaluation Loop. These stages are not a sequential pipeline but a continuously iterating closed loop. The task environment determines trajectory distribution; trajectory filtering dictates training signal quality; reward design sets the optimization direction; the training strategy ensures stability; and cost accounting determines if the solution can scale. Let’s break them down.

    3. Task and Environment Construction: Ensure Reproducibility First

    Long-horizon tasks must be reproducible first. Define explicit goal states, available toolsets, maximum turns, timeout strategies, and success verification rules for each task. The environment should support deterministic resets and log every turn’s inputs, tool returns, model actions, and intermediate states. For multi-turn tool calls, structure tool returns to avoid natural language ambiguity. Encapsulate timeouts, empty returns, and format errors into recognizable error types to help the model learn recovery strategies. Task sets should be layered: short-chain tasks for cold starts, medium-chain tasks for stable training, and long-chain tasks for final improvement. Curriculum learning isn’t just a simple easy-to-hard progression; it should be multi-dimensionally layered by “turns, tool count, error recovery difficulty, and final verification strictness” to prevent the model from falling into long-tail failures prematurely.

    4. Trajectory Sampling and Filtering: Quality Over Quantity

    Sampling is expensive in long-horizon tasks, so you cannot blindly accumulate trajectories. Use a “multi-sampling + validation filtering + layered retention” strategy. Sample multiple trajectories in parallel per task. Pre-filter with lightweight rules (e.g., discard if turn limits are exceeded, repeated actions occur, tool parameters are clearly missing, or the final state is unchanged). Then, post-filter with a validator to retain successful trajectories, near-successes, and representative failures. Near-successes are particularly important as they provide finer credit signals than pure failures. After filtering, track trajectory length, tool call distribution, and failure type distribution to prevent the training set from being dominated by a certain type of short task. Upsample long-tail tasks appropriately but set upper limits to avoid cost overruns.

    5. Reward and Verification: Terminal Rewards + Process Constraints

    Reward design should combine a “terminal main reward + process auxiliary constraints.” The terminal reward comes from an executable validator (e.g., was the target file generated? Did the API return as expected? Did the state reach the goal?). Process constraints shouldn’t reward “looking reasonable” but penalize clear errors (e.g., illegal tool calls, repeated invalid actions, exceeding budget turns, corrupting intermediate states). For decomposable tasks, add stage checkpoints, but keep stage reward weights low to prevent the model from farming stage points while ignoring the final goal. Credit assignment can use masked trajectory-level advantage estimation: calculate advantages only for valid actions, excluding tool return turns and padding turns from updates. Normalize long trajectories in segments to avoid reward scale over-amplification. Validators must be executable and reproducible to reduce the noise of human scoring.

    6. Full-Parameter RL Update: Stability First

    Full-parameter RL fully leverages base model capabilities but demands higher stability. Start with a smaller learning rate, combined with gradient clipping, advantage normalization, and reference policy constraints to prevent policy drift in long trajectories. During training, use dynamic batching grouped by task difficulty: large batches for short tasks, small batches for long tasks, controlling the total turns per batch. For task groups with excessively high failure rates, downsample first, then gradually recover to avoid diluting signals with zero-reward trajectories. If tool call formatting collapses, prioritize checking format constraints in rewards and sampling temperature rather than blindly increasing batch size. For update pacing, use a small-step cycle of “sample—filter—update—quick eval,” monitoring four metrics each cycle: success rate, average turns, invalid action rate, and per-task cost.

    7. Engineering System: Parallelism, Fault Tolerance, and Observability

    Completing training in under 5 days on 64 accelerator cards proves that engineering efficiency is a key variable. Engineering must solve three things: parallel sampling, fault tolerance, and observability. Parallel sampling should isolate environments by task, set timeouts and retry limits for tool calls, and return failed trajectories quickly rather than hanging. The training side must support checkpoint resumption and trajectory caching to prevent global pauses caused by isolated environment exceptions. For observability, log every action, tool return summaries, reward components, verification results, and cost tags. Use log services to aggregate execution records, monitoring alerts to catch long-tail timeouts and abnormal failure rates, object storage to save trajectories and verification artifacts, and container platforms to manage parallel environments. General cloud capabilities like Baidu AI Cloud’s object storage, log services, monitoring alerts, and container platforms can be used here, but the core design must center on task reproducibility and cost traceability.

    8. Cost Accounting: Break Down Per-Task Costs

    The public experiment disclosed an average per-task cost of about $0.72, compared to roughly $22.02 for a high-effort configuration. This gap shows that the “effort budget” must be explicitly managed. Cost accounting shouldn’t just look at total training time but must be broken down into sampling costs, validation costs, retry costs, and training update costs. Per-task cost = (average turns × per-turn sampling cost) + validation cost + failure retry amortization. Optimization directions include: limiting max turns, early termination for low-value tasks, caching reusable tool results, quickly classifying failed trajectories, and allocating sampling budgets by task difficulty. Record costs during evaluation as well to avoid unsustainable solutions that trade more turns for higher scores.

    9. Evaluation and Risk Control

    Evaluation should simultaneously look at success rate, average turns, invalid action rate, recovery success rate, and per-task cost. For long-horizon tasks, pay special attention to “long-tail failures”: a few ultra-long trajectories can inflate overall costs, and minor format errors can cause widespread failures. Set up a layered evaluation suite covering short-chain, medium-chain, long-chain, and exception recovery scenarios. For risk control, prevent validators from being exploited for reward hacking by periodically auditing trajectories manually. Avoid large discrepancies between training and real environments—tool return formats and timeout strategies should mirror reality. Avoid chasing benchmark scores at the expense of cost; the final solution must strike a balance between success rate and cost.

    10. Reusable Pseudocode Skeleton

    Below is a framework-agnostic training loop illustration:

    1. for iteration in range(max_iters):
    2. tasks = sample_tasks(curriculum)
    3. trajectories = parallel_rollout(policy, tasks, max_turns)
    4. valid_trajs = filter_by_rules(trajectories)
    5. rewards, masks = verify(valid_trajs)
    6. advantages = normalize_advantage(rewards, masks)
    7. update_policy(policy, valid_trajs, advantages, clip, kl_coef)
    8. metrics = evaluate(policy, eval_suite, cost_tracker)
    9. adjust_curriculum(metrics)

    The key here isn’t the code itself but four constraints: trajectories must be filtered, advantages must be masked, updates must be constrained, and evaluations must include cost. Implementing these four points is what transitions long-horizon agent RL from “occasional success” to “stable reusability.”

    Conclusion

    Reinforcement learning for long-horizon agents is a system engineering challenge involving task construction, trajectory filtering, reward validation, stable updates, and cost control—not just stacking parameters or compute. The real value of the public experiment’s figures (64 accelerator cards, under 5 days, 46.2%, and $0.72) lies in reminding us: using reproducible environments to generate high-quality trajectories, executable validators to provide reliable rewards, and cost metrics to constrain training strategies is what truly moves long-horizon agent tasks from demos to engineering practice.