Optimizing Models for AI Agent Execution: Training, Context, and Recovery Practices

    This article presents a general methodology for optimizing models in agent execution scenarios, where success depends on completing multi-step tool workflows rather than producing good single-turn answers. It covers redesigning training objectives around trajectory quality and tool contracts, managing context in layers to prevent degradation over long workflows, building failure recovery with pre-validation, bounded retries, idempotency, and least privilege, and replacing subjective impressions with layered metrics such as end-to-end success rate, step efficiency, format validity, recovery rate, and safety violations. It also outlines an integration order and the general cloud capabilities that support it.

    1. Background: The Bottleneck Has Shifted from Answering to Doing

    Over the past two years, LLM evaluation has mostly focused on single-turn question answering and content generation. Once a model is placed in a real business workflow, where it must call multiple tools in sequence, read intermediate results, and correct its actions based on errors, the evaluation criteria change completely. What developers complain about is often not that the model is not smart enough, but three engineering-level defects:

    1. Unstable action formats: the generated call structure is occasionally invalid, causing parsing failures and breaking the entire workflow.
    2. Forgetting in long workflows: as the number of steps grows, early constraints get diluted and the model starts to drift from the original rules.
    3. Unrecoverable failures: after one step returns an error, the model does not retry or switch paths but repeats the same wrong action.

    The recent industry trend is therefore to stop optimizing only for answer quality and instead treat execution success rate, step efficiency, and recoverability as first-class goals, improving both training and inference. Note that this article does not evaluate any specific product; it abstracts a general methodology for this kind of execution-oriented model optimization.

    2. Redesigning Training Objectives: From Text Likelihood to Trajectory Quality

    Traditional pretraining and alignment objectives focus on the likelihood of the next token, but correctness in execution tasks shows up at the level of the entire trajectory. Common practices include:

    • Trajectory-level supervision: use the complete task trajectory (observation, decision, action, feedback) as the sample unit instead of a single instruction-response pair.
    • Negative sample construction: use real failure trajectories such as parsing failures, out-of-range parameters, and infinite loops as negative examples to reinforce the boundary of what not to do.
    • Tool contract alignment: inject the input and output schemas of tools as hard constraints during training, so the model treats format validity as a strict rule rather than a style preference.

    An illustrative way to organize training samples (pseudocode, structure only):

    1. trajectory = {
    2. "goal": "Create a job on the data platform and configure daily scheduling",
    3. "tools": [{"name": "create_job", "schema": {...}}],
    4. "steps": [
    5. {"thought": "Confirm the fields first", "action": "query_schema", "observation": "..."},
    6. {"thought": "Fill in the required fields", "action": "create_job", "observation": "ok"},
    7. ],
    8. "label": 1.0, # Trajectory-level reward: success with a reasonable number of steps
    9. }

    The key point is that reward design must also penalize success achieved by detours. If a trajectory completes in 20 steps a task that could be done in 5, that means higher latency and cost in a real system, so step efficiency belongs in the reward function.

    3. Context Engineering: The Core of Not Degrading in Long Workflows

    Even a highly capable model will see its success rate drop significantly with poor context management. Engineering practice usually handles this in three layers:

    1. Compression layer: summarize early observations, keeping only structured key fields (status, identifiers, error codes) and discarding verbose raw text.
    2. Retrieval layer: write historical trajectories to searchable storage and fetch them by relevance when needed, instead of stuffing everything into the window.
    3. State layer: maintain an explicit task state machine (pending, completed, retry count on failure) so the model can see where it is at every step.

    A simplified state injection template:

    1. [Task goal] ...
    2. [Completed] Step 2, Step 3
    3. [Current constraints] Read-only access; deletion prohibited
    4. [Retries remaining] 2
    5. [Tool list] name(args_schema) ...

    Writing hard constraints such as “deletion prohibited” explicitly is more reliable than repeating reminders in a long conversation, because they appear in the same position every turn and attention allocation stays more stable.

    4. Failure Recovery and Controllability: Keeping Uncertainty in a Cage

    Production environments must assume that tools will time out, permissions will be insufficient, and responses will be dirty. Practical strategies include:

    • Pre-action validation: intercept invalid parameters with schema validation before the actual call, avoiding wasted quota on ineffective requests.
    • Bounded retries with backoff: distinguish retryable errors (timeouts, rate limiting) from non-retryable ones (parameter errors, insufficient permissions); the latter must switch paths or escalate to a human.
    • Idempotency design: introduce a business-side idempotency key for write operations to prevent duplicate creation caused by retries.
    • Sandboxing and least privilege: the execution environment has no external network access and read-only mounts by default, with permissions granted temporarily on demand.
    1. def safe_call(tool, args, retry=2):
    2. validate(args, tool.schema) # Pre-validation
    3. for i in range(retry + 1):
    4. r = tool.invoke(args, idempotency_key=args.get("key"))
    5. if r.ok or not r.retryable:
    6. return r
    7. sleep(backoff(i)) # Exponential backoff
    8. return escalate_to_human(r) # Fall back to a human

    5. Evaluation: Replacing Subjective Impressions with Quantifiable Metrics

    If “how it feels in practice” is judged only from isolated demos, the conclusions are unreliable. A layered evaluation is recommended:

    • End-to-end success rate: the proportion of tasks ultimately achieved, and the primary metric.
    • Step efficiency: average number of steps and redundant call rate, which directly affect latency and cost.
    • Format validity rate: the proportion of actions that can be parsed, reflecting contract adherence.
    • Recovery rate: the proportion of injected faults the model corrects on its own.
    • Safety violation rate: the number of times prohibited or unauthorized operations are touched.

    The evaluation set should include real dirty data and fault injection, for example randomly making a tool return an error code to see whether the model enters an infinite loop. Results from a clean environment alone usually cannot predict production behavior.

    6. Implementation Advice and How It Fits with General Cloud Capabilities

    To integrate this kind of capability into your own system, proceed in this order: first solidify tool contracts and the permission model, then add the state machine and context compression, and finally complete monitoring and replay. General-purpose cloud capabilities are usually enough to support this: a container platform hosts the execution sandbox, object storage holds trajectories and replay data, a message queue decouples tasks and smooths peaks, and logging and monitoring with alerting handle anomaly localization and metrics dashboards. Baidu AI Cloud offers corresponding product categories for these general capabilities, which can be combined as needed; the architecture above can be built without relying on any proprietary interface.

    7. Conclusion

    Optimizing models for execution scenarios is essentially about moving uncertainty out of the model and into an engineering structure that is observable, verifiable, and rollback-capable. On the training side, the emphasis is on trajectory-level objectives and tool contracts; on the inference side, on layered context and failure recovery; on the evaluation side, on quantifiable metrics and fault injection. Once these three form a closed loop, developers can evaluate a new model without relying on demo videos, using success rate, step efficiency, and recovery rate to reach reproducible conclusions.