Evaluating AI Agents in Real-World Scenarios: Two Core Metrics and Engineering Optimizations
The evaluation of large language model capabilities is shifting from static benchmarks to real-world, long-cycle agentic tasks. For developers, understanding the metrics behind these evaluations provides greater engineering value than simply looking at rankings. This article breaks down two core metrics in real-world agent tasks—Bash Reliability and Steerability—and provides actionable engineering methods, including code examples and implementation checklists, to optimize agent performance in production environments.
Evaluating Large Language Model (LLM) capabilities is shifting from static benchmarks toward real-world, long-cycle agentic tasks. For developers, understanding the metrics behind these evaluations offers more engineering value than merely looking at rankings. This article does not compare specific brands or models; instead, it deconstructs two core metrics of agents in real-world tasks and provides actionable implementation methods.
1. From Static Benchmarks to Long-Term Evaluation
Traditional natural language processing benchmarks primarily focus on knowledge reserves, logical reasoning, or text generation, typically involving single-turn, stateless Q&A. Agents operate differently. The model acts as the “brain,” calling external tools, reading environmental feedback, and continuously correcting itself across multi-turn interactions. Static benchmarks cannot reflect these capabilities, leading to the emergence of long-term evaluations based on real-world task sessions.
These evaluations have two main characteristics: tasks originate from real users, and the process spans multiple steps. Before reading the leaderboards, verify the following criteria:
- Source and version of the task set: Does it cover scenarios like coding, DevOps, and chat?
- Sample size and distribution across different scenarios.
- Metric definitions: Are failed sessions included in the denominator?
- What exactly are the numerator and denominator, and is the data deduplicated?
- Time windows and model versions: Are they consistent?
For metrics like the “Net Improvement Rate,” if the calculation methodology is not public, it is difficult to determine whether the gap between two models stems from actual capability or sample variance. Numbers are only comparable under the same task set and statistical criteria.
2. Overview of Two Core Metrics
In coding and automated DevOps scenarios, Shell command execution reliability and course correction capability have the most significant impact on outcomes. The table below summarizes these two metrics.
| Metric | Meaning | Common Failures | Optimization Actions |
|---|---|---|---|
| Bash Reliability | Whether the generated command executes successfully in the sandbox and can recover from errors | Path or dependency assumption errors; destructive commands; excessively long output crowding the context | Command pre-validation, sandbox isolation, output truncation, limited retries |
| Steerability | Whether the agent can adjust its strategy promptly when encountering negative feedback or mid-task user instruction changes | Local loops; initial minor deviations getting amplified; forgetting the original goal | External state machine, forced reflection, history compression, loop detection |
Reading guide: To improve command success rate and safety, see Section 3. To reduce local loops and goal drift, see Section 4.
3. Bash Reliability: How to Improve Shell Command Execution Reliability
Shell command execution failures typically occur in three areas.
First, environment assumption mismatches. Models often generate commands based on general environments from their training data, while the actual sandbox’s paths, permissions, and dependencies may be entirely different. The solution is to explicitly specify the working directory, tool versions, and permission scopes in the system prompt, allowing the model to generate commands based on the real environment.
Second, irreversible side effects. Commands like rm -rf can wipe out the entire task directory once executed. Security controls cannot rely solely on the model’s self-awareness; they must be implemented at the execution layer. Use a dry-run to preview the impact scope before execution, back up directories before modification, and mount read-only data directories in read-only mode.
Third, output blowing up the context. Long commands generate massive amounts of standard output and standard error. Feeding this back into the context as-is makes it easy for the model to forget its initial goal. You should only retain the tail end of the output and critical error lines, setting a total length limit.
Command Pre-Validation Checklist
- Working directory: Declared before each execution; paths in commands must be under this directory.
- Tool versions: List versions for tools like
python3,git,pytestin the system prompt. - Permission scope: The sandbox user is non-root; writing to paths outside the workspace is prohibited.
- Program whitelist: Only allow programs necessary for the task. The example here includes
ls,cat,grep,find,python3,pytest,git. - Metacharacter rejection: Semicolons, pipes, backticks, redirections, etc., are rejected; execute commands sequentially instead.
- Timeout: Default to 60 seconds; terminate the process upon timeout.
- Retry limit: Maximum of 2 retries, only for timeouts or transient errors.
- Output truncation: Retain the last 40 lines of stdout, up to 20 critical lines of stderr, and a total length not exceeding 4000 characters.
- Desensitization: Uniformly replace fields like
token,password, andapi_keyin logs with***.
Execution Layer Reference Code
The following code assumes a Python 3.10+ runtime environment. The sandbox object must provide a run(argv, timeout) method, returning a dictionary with four fields: stdout, stderr, exit_code, and timed_out. The code does not invoke the shell directly; instead, it parses the command into an argument list and executes it directly to prevent command injection. Exceptions thrown by the sandbox itself are caught by the caller.
import loggingimport reimport shlexlogger = logging.getLogger("agent.shell")ALLOWED_BINARIES = {"ls", "cat", "grep", "find", "python3", "pytest", "git"}DENIED_ARGS = {"-delete", "-exec", "--force", "--hard"}SHELL_META_CHARS = set(";|&`$<>\n\r")TRANSIENT_MARKERS = ("Temporary failure", "Connection reset", "Resource temporarily unavailable")MAX_RETRIES = 2TIMEOUT_SECONDS = 60TAIL_LINES = 40MAX_ERROR_LINES = 20MAX_CHARS = 4000SECRET_PATTERN = re.compile(r"(api[_-]?key|token|password)\s*[=:]\s*\S+", re.IGNORECASE)class CommandRejected(Exception):"""Command failed pre-validation and will not enter the sandbox."""def redact(text: str) -> str:return SECRET_PATTERN.sub(lambda m: f"{m.group(1)}=***", text)def validate(command: str) -> list[str]:if not command.strip():raise CommandRejected("Empty command")if any(ch in SHELL_META_CHARS for ch in command):raise CommandRejected("Contains shell metacharacters")try:argv = shlex.split(command)except ValueError as exc:raise CommandRejected(f"Unable to parse: {exc}") from excif argv[0] not in ALLOWED_BINARIES:raise CommandRejected(f"Program not in whitelist: {argv[0]}")if DENIED_ARGS.intersection(argv[1:]):raise CommandRejected("Contains high-risk arguments")return argvdef summarize_output(stdout: str, stderr: str) -> str:out_tail = stdout.splitlines()[-TAIL_LINES:]err_lines = [line for line in stderr.splitlines() if line.strip()][-MAX_ERROR_LINES:]text = "\n".join(["[stdout tail]", *out_tail, "[stderr key lines]", *err_lines])return redact(text)[-MAX_CHARS:]def is_transient(result: dict) -> bool:if result["timed_out"]:return Truereturn any(marker in result["stderr"] for marker in TRANSIENT_MARKERS)def execute(command: str, sandbox) -> dict:"""Returns {"ok": bool, "observation": str}, observation can be written directly into the context."""try:argv = validate(command)except CommandRejected as exc:logger.warning("Rejected command: %s, reason: %s", redact(command), exc)return {"ok": False, "observation": f"Command rejected: {exc}. Please use programs within the whitelist."}for attempt in range(MAX_RETRIES + 1):result = sandbox.run(argv, timeout=TIMEOUT_SECONDS)if result["exit_code"] == 0:return {"ok": True, "observation": summarize_output(result["stdout"], result["stderr"])}if not is_transient(result) or attempt == MAX_RETRIES:breaklogger.info("Transient failure, retrying attempt %d: %s", attempt + 1, redact(command))logger.error("Command failed, exit_code=%s: %s", result["exit_code"], redact(command))return {"ok": False, "observation": summarize_output(result["stdout"], result["stderr"])}
Three points need clarification regarding the code. First, the whitelist and denied arguments table only intercepts common risks and cannot exhaustively cover all dangerous usages; for example, git clean -fdx might still delete untracked files. Second, the true security boundary lies in the sandbox. Third, after a failed result is returned to the model, the model should change its strategy or report to the user, rather than blindly repeating the execution.
Sandbox Isolation Essentials
- Mount source code and data directories as read-only; write only within the designated workspace.
- Run as a non-root user, limiting process count, CPU, memory, and disk quotas.
- Deny network access by default; if access is required, only allow explicitly listed domains.
- Perform a
dry-runfor modification operations, output the impact scope, and require manual confirmation before execution. - Log the command, exit code, and execution time after each run for post-mortem analysis.
4. Steerability: How to Improve Course Correction Capability
Failures in Steerability often happen gradually. An initial minor deviation goes unnoticed, and subsequent steps amplify it. Alternatively, the model might toggle back and forth between two solutions without making progress. These issues are difficult to solve relying on the model’s self-awareness; they require structured constraints at the program layer.
External State Machine
Break the task into explicit states: PLAN (formulate plan), ACT (execute one step), OBSERVE (read results), REFLECT (reflect on deviations), DONE (completed), and ABORT (abort and report). State transitions are controlled by the program, and the model is only responsible for generating output within each state. For instance, if two consecutive OBSERVE states show failure, the program forces a transition to REFLECT, preventing the model from deciding whether to stubbornly continue running.
Forced Reflection Output
When entering the REFLECT state, require the model to output a fixed-structure JSON with the following fields:
goal: The original goal, restated verbatim.last_result: The conclusion of the previous step, in one sentence.deviation: The gap between current progress and the original goal; write “None” if there is no deviation.next_step: The plan for the next step; must be a single action.need_user_confirm: Whether user confirmation is needed, boolean.
The program checks whether fields are complete and requires the model to rewrite if missing or incorrectly formatted. The goal field must match the original goal saved in the state machine; if not, it directly falls back to PLAN.
History Compression
In long tasks, the context continuously expands, and the original goal can easily be pushed out of the window. When compressing, retain the following:
- Original goal: Pinned at the top of every turn, not subject to compression.
- The last 3 steps of complete records: Retain commands, truncated outputs, and conclusions.
- Earlier steps: Compress each into a one-line summary, e.g., “Step 4: pytest failed due to missing dependency numpy.”
- Unresolved errors: Retain error signatures until explicitly resolved.
The trigger condition can be set to when context usage exceeds 60% of the window. Compression is executed by the program, not left to the model to summarize, to prevent critical constraints from being lost during summarization.
Loop Detection
The same command repeatedly yielding the same error usually indicates the model is stuck in a local loop. The following detector is only called upon failure, counting occurrences of the “command plus error signature”. The error signature replaces numbers with placeholders to avoid missing matches due to changing line numbers.
import refrom collections import Counterclass LoopDetector:"""Returns True when the same command plus the same error signature repeats up to the threshold. Only called upon command failure."""def __init__(self, max_repeat: int = 3):self.max_repeat = max_repeatself.counter: Counter[str] = Counter()def record(self, command: str, observation: str) -> bool:first_error = next((line for line in observation.splitlines() if "error" in line.lower()), "")signature = re.sub(r"\d+", "N", first_error.strip())key = f"{command}|{signature}"self.counter[key] += 1return self.counter[key] >= self.max_repeat
Upon detecting a loop, the program should do three things: write the looping fact into the state machine and force a transition to REFLECT; list the already attempted commands in the reflection prompt; if there is still no progress, transition to ABORT and explain the sticking point to the user.
Mid-Task User Instruction Changes
When a user changes requirements, do not let the model silently modify the old goal. The correct approach is to update explicitly via the state machine: upon receiving a new instruction, return to PLAN, write the new goal, and archive the old goal into history. This ensures subsequent reflections and compressions are based on the new goal, and makes it easier to post-mortem whether the model followed the user’s intent.
5. Implementation Checklist and Conclusion
Before implementation, you can verify item by item using the following checklist:
- The system prompt explicitly specifies the working directory, tool versions, and permission scope.
- Each command passes whitelist, metacharacter, and argument validation.
- The sandbox uses read-only mounts, runs as non-root, and restricts resources and network.
- Timeout, retry limits (max 2), and output truncation parameters are configured and tested.
- Failed results are returned as truncated observations and desensitized.
- The state machine includes REFLECT and ABORT states, with failure transitions controlled by the program.
- The reflection output uses a fixed JSON structure, and the
goalfield is validated. - History compression retains the original goal and unresolved errors.
- The loop detector is integrated, with a threshold of 3 repetitions for the same error.
- User instruction changes update the goal via the state machine, rather than implicit rewriting.
Bash Reliability addresses whether “commands can execute successfully and recover from errors.” Steerability addresses whether “the agent can promptly detect deviations and return to the goal.” Both metrics rely on engineering constraints at the execution and state layers, not just the model’s inherent capabilities. When reading leaderboards, first ensure the evaluation criteria are consistent; when implementing, write the constraints into the code before discussing model selection.
