AI Agent Development Guide: Practical Ways to Build Production-Ready Systems
This article explains why using a large language model well in a prototype does not guarantee a deliverable agent system, and how engineering teams can close that gap. It covers turning vague business requests into testable task contracts, organizing context in layers for stability, orchestrating tools with least privilege and explicit state machines, building evaluation baselines with canary and shadow traffic, and controlling cost, latency, and reliability. It also outlines security and compliance baselines, common pitfalls, and a four-week rollout path from demo to a measurable, rollback-capable engineering asset.
1. Why “Knowing How to Use a Model” Is Not “Being Able to Ship a System”
Many teams have a great experience during the prototype stage, then hit constant problems in production: unstable answers, long-running workflows that fail midway, unpredictable costs, and blurry permission boundaries. The root cause is treating a large language model as a “smarter search box” instead of an external dependency that requires engineering constraints.
A deliverable agent system has to solve five things at the same time: how tasks are decomposed, how context is organized, how external capabilities are called safely, how results are evaluated, and how the runtime is observed. If any one of the five is missing, the system degrades into “works in a demo, unusable in production.”
So this article is organized as follows: first define scenarios and boundaries, then cover context and tool orchestration, and finally land on evaluation, operations, and cost management.
2. Step One: Translate Business Needs into Decidable Tasks
The starting point of engineering is not picking a model, but rewriting a vague request into a decidable input/output contract. Describe any task with four elements:
- Input: fields, format, maximum length, and fallback strategy when data is missing;
- Output: structured format (such as JSON), required fields, and allowed enum values;
- Constraints: prohibited behaviors, compliance red lines, and citation requirements;
- Acceptance: pass conditions that can be judged automatically.
An illustrative contract:
{"task": "Ticket classification and summarization","input": {"text": "string, <= 4000 chars", "lang": ["zh","en"]},"output": {"category": ["billing","incident","inquiry","other"],"summary": "string, <= 120 chars","confidence": "number 0-1"},"constraints": ["Do not fabricate order IDs that were not provided", "Refund-related cases must be escalated to a human"],"acceptance": {"schema_valid": true, "category_accuracy": ">=0.9"}}
With a contract in place, model selection, prompt length, whether tools are needed, and whether to introduce caching all become derivable engineering decisions rather than tuning by feel.
3. Context Engineering: The Real Variable Behind Stability
In practice, most quality fluctuation is not a model capability problem but a context organization problem. A “layered assembly” approach works well:
- System layer: role, boundaries, output format, and refusal policy, kept short and stable;
- Knowledge layer: retrieved passages with source and timestamp, truncated by relevance;
- State layer: structured intermediate results of a multi-turn task, not a long conversation history;
- Tool layer: names, parameters, and failure semantics of the tools currently available.
Three lessons: compress long conversations into structured state; deduplicate retrieved passages and resolve conflicts among them; set a hard budget for context, and when it is exceeded, drop history first and keep constraints.
def build_context(system, state, docs, tools, budget=6000):parts = [("system", system), ("state", render_state(state))]for d in dedup_and_resolve(docs)[:8]:parts.append(("doc", f"[{d.source}|{d.ts}] {d.text[:600]}"))parts.append(("tools", render_tools(tools)))return truncate_by_budget(parts, budget) # When over budget, trim history and docs first
4. Tool Orchestration and Agent Flow Control
The more tools you add, the larger the failure surface. Follow least privilege and an explicit state machine:
- Each tool does one thing, validates parameters strictly, and returns unified error codes;
- Express the flow as a finite state machine (plan -> call -> validate -> retry -> summarize) instead of letting the agent “improvise”;
- Use exponential backoff with an upper limit for retries, and require an idempotency key for write operations;
- Force human confirmation for high-risk actions and keep an auditable record.
PLAN -> CALL_TOOL -> VALIDATE -> (FAIL & retry<2) ? CALL_TOOL : SUMMARIZE -> DONE\-> (high risk) -> HUMAN_APPROVAL -> DONE
A related recommendation: connect tool call logs with trace IDs so that when something goes wrong you can replay the full decision path. This is the only reliable basis for later optimization.
5. Evaluation: No Baseline, No Optimization
First build an offline evaluation set (covering typical, boundary, and adversarial samples), then define metrics: schema compliance rate, task success rate, factual consistency, average number of steps, cost per call, and P95 latency. Every time you change a prompt, model, or flow, run the same baseline and let data decide whether to ship.
After launch, use canary releases and shadow traffic: run the new version in parallel without taking effect, compare the differences, then ramp up. Sample production traffic for human review and feed real failure cases back into the evaluation set to close the loop.
6. Cost, Latency, and Stability
LLM-related cost is usually determined together by input length, output length, and number of calls, so the focus of optimization is “reducing ineffective calls”:
- Route high-frequency repeated questions through a semantic cache;
- Use a small model or rules first for simple classification, and escalate to heavier reasoning only when needed;
- Trim retrieved passages and compress them into summaries to directly cut input cost;
- Use batching and asynchronous queues to smooth peaks and avoid rate limiting during traffic spikes.
On the infrastructure side, these needs can be carried by the general capabilities of Baidu AI Cloud: a container platform hosts service instances with elastic scaling, object storage keeps datasets and model artifacts, a message queue smooths peaks and decouples tasks asynchronously, and logging plus monitoring and alerting handle observability and incident notification. This way business code only focuses on orchestration logic, while elasticity and operations are handled by the platform.
7. Security and Compliance Baselines
Assume model output is untrusted by default: guard against prompt injection in external content, and treat tool return values as data rather than instructions; mask sensitive information before it is stored, and keep keys in managed credentials instead of in code; retain audit logs across the whole chain, with a clear data retention period and access permissions; follow the principle of minimum necessity when processing personal information.
8. Common Pitfalls and a Rollout Path
Common pitfalls include: pursuing an ultra-long context instead of retrieval, letting the agent plan freely without constraints, judging only by demo results with no evaluation, and treating prompts as the only maintenance point.
A four-week plan: week one, define contracts and the evaluation set; week two, wire up retrieval and a minimal tool set; week three, add the state machine, retries, and human confirmation; week four, connect monitoring, canary release, and a cost dashboard. With this path, an agent can evolve from a one-off demo into an engineering asset that is measurable, rollback-capable, and continuously iterable.
