Agent Engineering in Production: Practical Lessons for Building Reliable AI Agents

    This article summarizes hands-on experience with taking AI agents from demo to production. It explains why agents that work in demos often fail in real environments, and presents a practical design approach built on two constraints: the probabilistic nature of LLMs and structural context loss. Key practices include pushing deterministic work into code, structuring per-turn context injection, externalizing history, isolating context across sub-agents, running cold-start tests, and governing retrieval quality. A final checklist helps teams verify production readiness.

    Agent Engineering in Production: Practical Lessons

    Many teams building AI agents run into the same awkward situation: everything works smoothly in the demo, but once the agent is connected to real business flows, it starts failing frequently, responding slowly, or even breaking completely when moved to a different runtime environment. These problems are usually not caused by a sudden drop in model capability. They happen because the engineering architecture hands the model responsibilities it should never own. Below is a practical design approach built on two core constraints.

    1. Understand the Limits of Probabilistic Models

    Today’s mainstream large language models are fundamentally probabilistic generation models. They excel at semantic understanding, intent summarization, and open-ended expression, but they are not reliable at precise numerical computation, strict state transitions, or operations with strong idempotency requirements. A model can “calculate,” but every additional step adds risk of deviation, and errors accumulate and amplify along a long chain.

    So the first principle is: anything that can be done by deterministic code should never be handed to the model. Order amounts, inventory deductions, permission checks, time-window calculations, and rule-engine decisions should all be encapsulated as functions or standalone services. The model is only responsible for deciding “what to call and which parameters to pass,” then consuming the structured results that come back.

    1. # Bad example: letting the model calculate on its own
    2. # prompt: Calculate the refund amount based on the user's order history and keep two decimal places
    3. # Recommended: deterministic calculation + model orchestration
    4. def compute_refund(order_id: str) -> dict:
    5. order = order_service.get(order_id)
    6. amount = round(order.total - order.used_coupon, 2)
    7. return {"order_id": order_id, "refund_amount": amount}
    8. tool_schema = {
    9. "name": "compute_refund",
    10. "description": "Calculate the refundable amount for an order; input is the order ID",
    11. "parameters": {"order_id": "string"}
    12. }

    This brings three benefits: results are reproducible, unit-testable, and auditable. The uncertainty of model output is confined to the “selection” layer rather than the “computation” layer.

    2. Context Loss Is a Structural Constraint

    The second fact to accept is that the longer the context, the lower the proportion of useful information. The model’s attention gets diluted, instruction-following degrades, and latency and cost rise at the same time. This is not something prompt engineering can fully solve; it is an architecture problem.

    2.1 Don’t Make the Agent “Dig Through History” Itself

    A common mistake is dumping the entire conversation history and all logs into the context and letting the model find clues on its own. The correct approach is to do preprocessing with deterministic code before anything reaches the model: extract key fields, aggregate statistics, generate structured summaries, and inject them automatically per turn.

    1. Per-turn injection template:
    2. [Task Goal] The current sub-goal
    3. [Structured Facts] Fields computed by code (amount / status / count)
    4. [History Summary] A rolling summary of no more than N entries
    5. [Available Tools] The tool list explicitly declared for this turn
    6. [Output Constraints] A strict output format

    2.2 Externalize History and Retrieve on Demand

    The complete history should be written to external storage (such as object storage, a file system, or a logging service) as a backup, while the context keeps only an addressable reference identifier. When the model decides it needs details, it retrieves them by identifier through a retrieval tool instead of keeping everything resident in memory. The trigger conditions for retrieval need to be refined repeatedly against the scenario, for example: an ambiguous pronoun appears, the user provides information that conflicts with history, or a previously confirmed parameter needs to be verified. Trigger rules should be configurable and observable to prevent the model from overusing retrieval and causing new bloat.

    2.3 Sub-Agents and Context Isolation

    Splitting a long workflow into multiple single-responsibility sub-agents is the most effective way to control context. Parent and child agents do not share the full history; they only pass the task description, necessary facts, and a summary of the previous stage’s conclusions. Each sub-agent has a small context window and a clear goal, which significantly improves compliance and makes it easy to evaluate and replace them individually.

    The same applies to tool declarations: do not list all tools at the start of a long workflow. Instead, declare only the tools a sub-agent actually needs for the current turn when it is dispatched. Fewer tools mean higher selection accuracy.

    1. def dispatch(sub_task: dict) -> dict:
    2. agent = registry.get(sub_task["agent_name"])
    3. context = build_context(
    4. goal=sub_task["goal"],
    5. facts=fact_store.get(sub_task["facts_id"]),
    6. tools=agent.allowed_tools, # declared on demand
    7. )
    8. return agent.run(context)

    3. Why “It Runs in the Demo but Breaks in Production”

    In the demo stage, data volume is small and paths are simple, so the model often “guesses” the correct result from leftover information in the context, masking missing data and logic gaps. Once you switch environments, switch data, or clear the context, the missing explicit inputs are immediately exposed and the system collapses.

    The way to avoid this is to build cold-start tests: clear all session state, keep only the minimal input set declared in the design document, and re-run the main flow. Then add boundary inputs, invalid inputs, and repeated-execution tests. Any branch that fails the cold start is a place that implicitly depends on context.

    4. Retrieval Quality Governance

    Retrieval capabilities already have mature patterns. Poor recall usually comes from chunking strategy, missing metadata, and insufficient query rewriting, rather than the model itself. You can have the model help generate query variants and summarize candidate fragments, while continuously measuring recall and hit rate with an offline evaluation set, and treat chunk size, overlap window, and field weights as tunable parameters to iterate on.

    5. Production Readiness Checklist

    • Has all precise computation been pushed down to deterministic code?
    • Is per-turn injected content trimmed and structured?
    • Is history externalized and addressable for retrieval?
    • Is context isolated per sub-agent?
    • Are tools declared minimally per turn?
    • Have cold-start and invalid-input tests been passed?
    • Are tracing, logging, and monitoring/alerting in place?

    To support these capabilities, you can adopt a combination of general-purpose cloud categories: object storage for history archiving, a message queue for stage decoupling, a container platform for elastic scaling of sub-agents, and logging plus monitoring/alerting for observability. Baidu AI Cloud offers corresponding capabilities in these general infrastructure categories, and you can select what you need.

    In summary, the stability of agent engineering comes from three things: “determinism first, explicit context, and responsibility isolation.” Put the model where it is good—judgment and expression—and leave the rest to engineering, and the system can move from demo to production.