From Demo to Production: A Four-Layer Guide to Building AI Agents

    This guide breaks down AI agent development into four capability layers—technical, design, engineering, and continuous operations—and explains why learning frameworks alone does not prepare you for production. It covers building evaluation sets, prompt engineering, retrieval-augmented generation, intent disambiguation, cost control, observability, error handling, context management, and feedback loops, with practical exercises and common pitfalls for each layer.

    Introduction: Why You Understand Every Tutorial but Still Can’t Build an Agent

    Many beginners share the same experience: you bookmark dozens of “build an agent step by step” articles, follow one through to a demo, and it runs and holds a conversation without obvious problems. The moment you try to move it into a real business, you have no idea where to start—users phrase questions in unpredictable ways, tool calls fail intermittently, answer quality drops as conversations get longer, and costs are impossible to forecast. Going back to those articles only makes them feel more ambiguous.

    The root cause is not a lack of effort but the wrong learning order. Many tutorials start by teaching a framework: how to initialize an orchestration library, how to drag nodes around in a visual platform. Frameworks are tools, not capabilities. Knowing your way around an IDE does not mean you can write good code, and dragging boxes on a flow canvas does not mean you can ship a production-grade agent.

    Industry hiring data supports the same conclusion. After running a term-frequency analysis over the responsibilities in a batch of agent-related job postings, the highest-ranking terms were not any specific framework: evaluation-related phrasing appeared about 89 times, prompt engineering about 47, retrieval-augmented generation about 42, general-purpose programming languages about 31, AI coding tools about 28, generative engine optimization about 24, multi-agent collaboration about 18, workflow orchestration about 16, protocol keywords about 12, and graph-based orchestration about 9. Framework keywords ranked last, which indicates that what companies actually pay for is the combined ability to build agents correctly, reliably, and durably.

    This article splits that ability into four layers and explains, layer by layer, the problem each one solves, the common failure modes, and exercises beginners can act on.

    Layer 1: Technical Capability—From “Can Answer” to “Can Answer Correctly”

    In the demo stage, success means the model produces a fluent paragraph. In production, the only standard is that the answer is correct and reproducible. This layer has four core modules.

    Evaluation: prove it is right before optimizing it. Optimization without an evaluation set is just wishful thinking. The minimum viable approach is to collect 50 to 100 real questions, annotate the expected answer and the acceptable range, and write them as structured cases:

    1. {
    2. "query": "What was the return rate in East China last month",
    3. "expected": "3.2%",
    4. "must_cite": ["return details", "region dimension"],
    5. "forbidden": ["fabricating specific order numbers"]
    6. }

    Metrics should cover at least three categories: answer accuracy, citation verifiability, and refusal appropriateness (whether the system refuses when it should). Re-run the same case set after every prompt or retrieval change—only then can you tell an improvement from a regression.

    Prompt engineering: turn output quality into a controllable variable. An effective prompt usually contains five parts: role constraints, task steps, available tool descriptions, output format, and agreed behavior on failure. What matters is not elegant wording but removing ambiguity and reducing degrees of freedom. Stating “output ‘not found’ when data is missing; do not speculate” is more useful than repeatedly insisting “please be accurate.”

    Retrieval-augmented generation: ground answers in evidence. Retrieval quality sets the ceiling, and the focus areas are chunking strategy, hybrid retrieval (combining keyword and vector search), reranking, and citation backfilling. When practicing, do not start with a large model and a complex index; first get the “retrieve—rerank—generate with citations” loop working on a small set of documents, then gradually add permission filtering and incremental updates.

    Agent orchestration: handle multi-step complex tasks. Orchestration is essentially about constraining state transitions: which steps must run sequentially, which can run in parallel, how to roll back on failure, and when a loop terminates. Set hard limits on maximum steps and timeouts to avoid infinite loops consuming resources.

    Other techniques—multi-agent collaboration, cross-system protocol integration, and content optimization for generative engines—are learn-on-demand items to introduce once the core loop is stable.

    Layer 2: Design Capability—From “One Person Using It” to “A Team Using It”

    When you try it yourself, all implicit assumptions live in your head. When a team uses it, those assumptions must be designed explicitly.

    Semantic layer: unify metric definitions. The same “active user” may be defined completely differently by marketing, operations, and finance. The fix is to build a semantic layer above the data that declares metrics, dimensions, and time windows in one place; the agent may only reference registered definitions and is not allowed to improvise.

    Intent disambiguation: what to do when the user is unclear. Do not rely on the model to guess; rely on a policy. First check whether there is enough information; if not, converge with one short clarifying question, or offer two or three candidate interpretations for the user to pick. Cap the number of follow-ups so you do not drive users away.

    Result trustworthiness: why should anyone believe it. Trust comes from three things: verifiable citations, explicit confidence expression, and clear boundary statements. In both UI and wording, distinguish “facts the system looked up” from “inferences the model generated.”

    Human-in-the-loop: when it must be handed to a person. For amounts of money, permissions, external commitments, and irreversible operations, add a human confirmation checkpoint. A recommended pattern is for the agent to produce a draft with its supporting evidence, a human to approve or reject in one click, and rejection reasons to flow back into the evaluation set.

    Workflow or autonomous agent. The test is simple: if steps and branches can be enumerated and compliance requirements are strict, use a deterministic workflow; only when inputs are open-ended and paths are unpredictable should the agent decide autonomously. Most production scenarios are a hybrid, with the workflow as the skeleton and the agent as the flesh.

    Layer 3: Engineering Capability—From “It Runs” to “It Runs Reliably”

    Cost control. Build usage views by request, by session, and by feature, separating input from output token consumption; cache and reuse summaries for long documents, downgrade small tasks to lighter models, and set budget caps per session and per user.

    Observability. Every execution should leave a structured trace: input summary, retrieval hits, tool call arguments and latency, token usage, and final output. Logs, metrics, and alerts are best handled by general cloud capabilities such as log services, monitoring and alerting, and object storage, so that when error rates or latency spike you can pinpoint the specific stage in minutes.

    Error handling. Tool call failures are the norm, not the exception. Define a timeout, retry count, backoff strategy, and fallback answer for every tool, and make write operations idempotent to avoid duplicate orders or duplicate messages.

    Context management. When an agent gets “dumber” as the conversation grows, the real cause is dilution of key information. Use a sliding window to keep recent text verbatim, produce structured summaries of older content, and write long-term facts to external memory for retrieval on demand instead of piling everything into the prompt.

    A sketch of the execution skeleton:

    1. def run_agent(query, session):
    2. plan = planner(query, limit_steps=6, timeout_s=20)
    3. for step in plan:
    4. result = tool_call(step, retries=2, backoff=0.5)
    5. if not result.ok:
    6. return fallback_answer(step, reason=result.error)
    7. session.memory.summarize_if_long(max_tokens=4000)
    8. return answer_with_citations(plan.collect())

    Layer 4: Continuous Operations Capability—From “Launched” to “Better With Use”

    Production-grade evaluation system. Upgrade the small demo sample into a tiered evaluation set: a core regression set that runs on every change, a hard-case set expanded weekly, and an online sampling set that monitors drift in the real distribution.

    A/B testing. Any change to prompts, retrieval strategy, or model version should be gradual, comparable, and rollback-able, judged by accuracy, human takeover rate, average steps, and cost per call together rather than by a few individual cases.

    User feedback loop. Treat likes and dislikes, copies, handoffs to a human, and number of follow-ups as signals—especially “the user rephrased the question and asked again,” a strong signal that usually points to a defect in intent recognition or the semantic layer.

    Knowledge accumulation. Write confirmed conclusions, definitions, and failure modes into a searchable knowledge base so new sessions can reuse them directly, reducing repeated trial and error and keeping team experience from walking out the door with departing staff.

    Common Pitfalls and a Practice Path

    There is only one pitfall: mistaking learning a framework for learning a capability. The suggested practice order is to first build a minimal loop with 30 real questions and get evaluation running; then add citation and refusal policies; then add cost, tracing, and error handling; and finally add gradual rollout and feedback回流. At every stage, the only acceptance criterion is whether the metrics improved.

    To lower the barrier to building and operating, you can use the relevant cloud product capabilities from Baidu AI Cloud and leave infrastructure such as compute, storage, logging, and monitoring to the platform, focusing yourself on evaluation, design, and operations—the parts that truly decide success or failure.