From Chatting to Execution: Key Design Decisions for AI Agents in Production

    AI applications are shifting from answering questions to taking actions that change external state—editing code, running tests, querying databases, and adjusting device behavior. This article defines what makes an agent "capable of execution" and walks through the design decisions that determine whether such agents work reliably: context engineering, tool and action-primitive design, planning and loop control, memory, evaluation, and runtime engineering. It also covers security and compliance, common pitfalls, and a phased path from a minimal working version to production-scale operation—showing why engineering the runtime matters more than simply chasing a stronger model.

    From Chatting to Execution: Key Design Decisions for AI Agents in Production

    1. Background: AI Applications Are Moving from Q&A to Execution

    Several recent developments point to the same trend:

    • Mainstream AI coding tools are being deeply integrated with general-purpose chat products. Users describe a goal in natural language, and the system directly edits code, runs tests, and reports back results.
    • In healthcare research, AI is being used to “translate” one physiological signal (such as respiration) into another (such as brain activity during sleep), offering an interpretable approximation for metrics that are hard to measure directly.
    • In the brain-computer interface field, the first clinical retrospective spanning twenty years has reached a cautiously optimistic conclusion.
    • Neurosurgeons, meanwhile, must confront the ethical questions raised by implanted devices that can “learn on their own,” including data ownership, responsibility allocation, long-term safety, and explainability.

    Put together, these seemingly scattered developments reveal three common threads:

    1. From “completion” to “delivery”: The unit of output is no longer a character or a paragraph, but a series of verifiable actions.
    2. From “single-shot Q&A” to “multi-step closed loops”: Tasks are decomposed into multiple steps that must be carried forward through maintained state.
    3. From “capability demos” to “responsibility constraints”: Once a system starts changing the state of the external world—files, code repositories, experiment parameters, device behavior—reliability, safety, and traceability become first-class requirements on par with model capability.

    For developers, this leads to a practical conclusion: building AI applications that “can execute” shifts the focus from “tuning the model” to “designing the runtime.”

    2. What Makes an Agent “Capable of Execution”

    Before going further, let’s define the term. An agent is widely understood as a system that uses a large language model as its decision-making core and can perceive inputs, plan steps, call external tools, refine its approach based on feedback, and keep running under certain constraints.

    What distinguishes it from an ordinary “LLM plus prompt” application comes down to three things:

    • It has state: Tasks span multiple rounds of calls and require storing intermediate results and plans.
    • It has tools: It can take actions that change the external world—reading and writing files, running commands, querying databases, calling business APIs.
    • It has constraints: Every action operates within boundaries defined by permissions, budgets, and auditing.

    It’s worth stressing that an agent is not a natural byproduct of “the model getting stronger.” It is a systems-engineering effort: the model provides reasoning, while engineering provides the boundaries, memory, and feedback loops.

    3. A Layered Architecture: Five Layers of an Agent

    1. Model layer: Understands intent, decomposes tasks, selects tools, generates structured parameters, and produces brief intermediate conclusions. Model capability sets the ceiling, but it is not everything.
    2. Tool and integration layer: Wraps external systems into “action primitives” that are readable, callable, and verifiable by the model. This is the true source of an agent’s capabilities.
    3. Context and memory layer: Manages state across long tasks and decides “which information to put in the model’s view for the next round.”
    4. Orchestration and runtime layer: Handles loop control, retries, concurrency, budgets, permissions, and recoverability.
    5. Evaluation and observability layer: Measures task completion, tool-call correctness, and failure modes, and keeps a record of online behavior.

    The next four sections dive into context engineering, tool calling, planning and state, and memory design—the four areas that “don’t look like model problems” yet most affect success rates.

    4. Key Design 1: Context Engineering

    Context is an agent’s only “working memory.” In a long task, the available information often far exceeds the context window, so deciding “what to include, what to exclude, and in what form” is the core design work.

    1. Layered assembly strategy

    • System instruction layer: Role, behavioral rules, and prohibitions—kept short and stable for cache reuse.
    • Task state layer: The current goal, completed steps, and confirmed conclusions, stored in a structured form (such as JSON) so the model doesn’t have to re-derive them from long text.
    • Retrieval layer: Injects only the fragments relevant to the current sub-task, annotated with source and last-updated time.
    • Tool result layer: Keeps only the minimum necessary fields and strips out irrelevant noise.

    2. Three frequent problems and their fixes

    • Context bloat: Information keeps accumulating as the task progresses, drowning out key details. The fix is to periodically “compress”—collapse long dialogue into summaries of key points and clear history before entering a new phase.
    • Historical drift: Old conclusions become invalid once new information appears. The fix is to annotate each conclusion with its basis and validity window, and when conflicts arise, explicitly have the model arbitrate rather than defaulting to the old result.
    • Retrieval noise: Injecting irrelevant documents actually lowers accuracy. The fix is “little, precise, sourced”—better to give less.

    3. A practical rule of thumb

    • Keep the per-round context increment within a controllable share of the total budget (in practice, one to two tenths is reasonably safe).
    • Carry key information (goal, constraints, to-dos) in structured fields, and treat long text only as reference material.
    • Set a “lifetime” for each type of information: information that becomes invalid once the task is done should not be carried into later phases.

    5. Key Design 2: Tool Calling and Action Primitives

    The quality of tool design directly determines whether an agent’s “hands actually work.”

    1. Write tool descriptions like API documentation

    • Name and description: State clearly “what it does, when to use it, and when not to use it.”
    • Parameters: Type, whether required, allowed range, and default value, described with a verifiable schema.
    • Return: Structured output with stable fields, including a status code and human-readable error messages.
    • Boundaries: Make explicit that the tool produces no side effects, or clearly state the scope of its side effects.
    1. # Illustrative code: structured tool definition with pre-call validation
    2. TOOL_SPEC = {
    3. "name": "query_metric",
    4. "description": "Query monitoring metrics by time range and dimension; read-only, no side effects.",
    5. "parameters": {
    6. "type": "object",
    7. "properties": {
    8. "metric": {"type": "string", "enum": ["cpu", "latency", "error_rate"]},
    9. "start": {"type": "string", "description": "ISO8601 start time"},
    10. "end": {"type": "string", "description": "ISO8601 end time"},
    11. "group_by": {"type": "array", "items": {"type": "string"}}
    12. },
    13. "required": ["metric", "start", "end"]
    14. }
    15. }
    16. def validate_args(spec, args) -> list:
    17. """Lightweight validation: missing fields, type mismatches, and out-of-enum
    18. values are all caught here, so we avoid calling with bad arguments."""
    19. errors, schema = [], spec["parameters"]
    20. for key in schema.get("required", []):
    21. if key not in args:
    22. errors.append(f"missing required field: {key}")
    23. for key, rule in schema.get("properties", {}).items():
    24. if key not in args:
    25. continue
    26. if "enum" in rule and args[key] not in rule["enum"]:
    27. errors.append(f"{key} not in allowed values: {rule['enum']}")
    28. return errors

    This example illustrates one principle: validation should happen before the call, not after the downstream API returns an error and the model has to guess and retry. The earlier parameter errors surface, the less likely the task drifts off course.

    2. Idempotency and failure handling

    • Tools with side effects must support idempotency keys to avoid duplicate submissions causing double charges or duplicate writes.
    • Network calls should uniformly set timeouts and a limited number of retries, retrying only errors that are safe to retry.
    • On failure, return a decidable error type (such as “invalid parameter,” “no permission,” “resource unavailable,” or “transient failure”) so the model can choose to fix or escalate rather than blindly retrying.

    3. Least privilege and sandboxing

    • Least privilege: Restrict write operations to designated directories or namespaces; forbid arbitrary paths and arbitrary commands.
    • Tiered dangerous operations: Irreversible actions (deletion, migration, changing production configuration) must require human confirmation or at least a second check.
    • Sandbox isolation: Run the execution environment isolated from the host, limit network egress and resource quotas, and prevent privilege escalation and resource exhaustion.

    4. A small, precise toolset

    The number of tools is negatively correlated with selection accuracy: the more similar-sounding tools there are, the higher the chance the model picks the wrong one. A practical approach is to split the toolset by task domain and expose only the few tools relevant to the current phase, loading the rest when needed. Stating “counter-examples” (what the tool is not for) in the description is often more effective than piling on positive descriptions.

    6. Key Design 3: Planning, Loops, and State

    1. Prefer a single agent

    Most tasks don’t need multi-agent division of labor. The gains from multi-role collaboration are often outweighed by fragmented context, overlapping responsibilities, and coordination costs. Start with “one planner plus a set of tools,” and introduce sub-task decomposition only when the task genuinely requires parallelism and the sub-tasks are truly independent.

    2. Loops and termination conditions

    The most common production failure for an agent isn’t “answering wrong”—it’s “not stopping.” Every loop must have hard constraints:

    • A maximum step limit;
    • A token budget and timeout;
    • No-progress detection (terminate and report after N consecutive rounds without new information);
    • Clear human take-over points.

    3. State persistence

    Long tasks should be “recoverable”: write the plan, executed actions, and key artifacts to persistent storage so that after a crash or interruption the system can resume from the checkpoint rather than rerun from scratch. This is especially critical in batch tasks—it directly determines the cost of retries.

    4. Structured output first

    Task instructions should include a verifiable “definition of done”—for example, “generate a change set, all tests pass, and each review comment has been addressed.” Writing acceptance criteria into the prompt lets the model know what “done” means during self-verification, which significantly reduces cases of “looks finished but actually incomplete.”

    7. Key Design 4: Memory and Knowledge

    • Short-term memory: Steps and intermediate results within the current task, cleared when the task ends.
    • Session memory: User preferences and constraints across dialogue turns, which must be explicitly written in rather than relying on the model to recall them.
    • Long-term memory: Requires a full lifecycle of “write—index—retrieve—update—evict.” Retrieval typically combines vector search with structured filtering, and keeps source and timestamp for auditability.
    • Conflict and forgetting: When new information overrides old information, the override should be explicit to prevent old conclusions from contaminating decisions over the long run.

    One often-overlooked detail: writing to memory needs quality control. Letting low-value, overly granular, or easily outdated content into the long-term store only raises retrieval noise and cost.

    8. Evaluation: No Measurement, No Optimization

    1. Offline evaluation sets

    • Build a layered evaluation set by task type: simple queries, multi-step tasks, requests that should be refused, and boundary or abnormal inputs.
    • Track four categories of metrics:
      • Task completion rate (judged against preset acceptance criteria);
      • Tool-call correctness (right tool chosen, correct parameters);
      • Step efficiency (number of calls needed to complete the same task);
      • Safety metrics (trigger rate for privilege escalation, boundary violations, and dangerous actions).
    • Key practice: evaluation must include “negative cases” and “dangerous-action samples.” Looking only at the positive pass rate hides risk.

    2. Online evaluation

    • Sampling: Draw samples from real requests for human or automated review, and track distribution drift.
    • User feedback: Adoption rate, retry rate, and mid-way abandonment rate are all valid signals.
    • Shadow comparison: Run a new version on shadow traffic first, compare key metrics, and then ramp up.

    3. Failure attribution

    Online failures fall into roughly four categories: instruction misunderstanding, tool-selection or parameter errors, insufficient or stale context, and model capability limits. These four require completely different fixes—the first calls for better prompts and state management, the second for better tool descriptions and validation, the third for better retrieval and memory, and the fourth for a stronger model or task decomposition. Do the attribution first, then optimize; this avoids treating an engineering problem as a model problem.

    9. Runtime Engineering: Deployment, Cost, and Stability

    1. Deployment shape

    • Deploy stateless parts (the orchestrator, tool gateways) on a container platform and scale horizontally by replicas.
    • Decouple long tasks through a message queue for asynchronous execution and callback, avoiding request timeouts.
    • Store large files and artifacts in object storage, send logs and call traces to a logging service, and route metrics into a monitoring and alerting system to form an observable closed loop.

    2. Cost control

    • Model tiering: Use small models for simple intent recognition and classification, and strong models for complex planning and coding, routing by confidence.
    • Cache reuse: Cache system instructions, long-document summaries, and retrieval results to reduce repeated inference.
    • Context slimming: In multi-round tasks, keep only structured state and necessary evidence.
    • Budget guardrails: Set a token and cost cap per task; terminate and report when exceeded, preventing runaway loops from blowing up costs.

    3. Stability

    • Tiered timeouts and retries: Distinguish retryable from non-retryable errors.
    • Circuit breaking and degradation: When a downstream tool is unavailable, return a clear degraded result rather than letting the model retry endlessly.
    • Idempotency and deduplication: Duplicate submissions must not produce duplicate side effects.
    • Canary and rollback: Ramp up a new version by traffic share and roll back quickly on anomalies.

    10. Security and Compliance: Treat AI as an Untrusted Input Source

    This is the most underestimated part. As long as a system has execution capability, you must assume that inputs are untrusted and model outputs are not fully trustworthy.

    • Prompt-injection defense: Treat all external content (web pages, documents, code comments, tool return values) as data rather than instructions; isolate and label instructional content, and validate parameters for privilege violations before any tool call.
    • Tiered permissions: Distinguish “read-only queries” from “write operations”; write operations require explicit authorization or human confirmation.
    • Output validation: Run static checks and tests on generated code, review diffs for configuration changes, and sanity-check numerical results.
    • Audit trail: Record every tool call, its parameters, its results, and the basis for each decision, so events can be reconstructed afterward.
    • Privacy and compliance: Desensitize sensitive data before it enters the model, strictly isolate across tenants, and follow the principle of data minimization.

    11. Common Pitfalls

    1. Believing a stronger model solves everything. Many failures stem from confused context, vague tool descriptions, and missing validation—problems no model, however strong, can rescue.
    2. Thinking more tools is better. Toolset bloat directly lowers selection accuracy; splitting by domain and loading on demand is more practical.
    3. Testing only positive cases. Evaluation without negative cases and dangerous-action samples cannot reflect real risk.
    4. Missing hard constraints. An agent without step and budget limits can fall into long loops under abnormal inputs.
    5. Ignoring recoverability. When long tasks aren’t recoverable, retry costs scale exponentially.

    12. A Phased Rollout Path

    • Phase 1 (minimum viable): A single agent with a few read-only tools, structured state, and clear termination conditions and audit logs.
    • Phase 2 (reliability): Add tool validation, idempotency, timeouts and retries, budget guardrails, and a layered evaluation set.
    • Phase 3 (scale): Model-tiered routing, asynchronous task orchestration, caching and canary releases, and a complete observability system.
    • Phase 4 (governance): Tiered permissions, human take-over mechanisms, compliance auditing, and regular red-team testing.

    13. Summary

    Moving from “chatting” to “execution” is, at its core, connecting a large model’s reasoning ability to real engineering constraints. The model sets an agent’s ceiling, while context management, tool design, planning and loop control, the evaluation system, and runtime engineering together determine whether it can reliably cross the “usable” threshold. Doing the engineering well in four directions—budget, permissions, observability, and evaluation—will yield a far higher deployment success rate than simply pursuing a stronger model. If your team is preparing to build such systems on a platform like Baidu AI Cloud, you can also prioritize reusing mature general-purpose capabilities (such as container platforms, object storage, message queues, logging services, and monitoring and alerting) and focus your energy on task design, tool definition, and the evaluation system—the areas where you truly differentiate.