Agent Development: A Practical Guide from Fundamentals to Production
This guide explains why AI agents are easy to demo but hard to run in production, then walks through the engineering layers required to ship them reliably. You will learn a minimal five-layer agent architecture, key principles for tool design and routing, techniques for context management, a plan-execute-validate loop for multi-step tasks, and the three dimensions of agent evaluation. It also includes a pre-launch checklist covering permissions, logging, monitoring, fallback, cost control, and data compliance, plus common anti-patterns and how to fix them.
1. Why Agents Are Easy to Demo but Hard to Ship
Most developers go through a similar curve the first time they build an agent: the demo looks impressive, but once it touches real business logic, it starts giving irrelevant answers, failing tool calls, or drifting off course in the middle of long tasks.
The root cause is that an agent is not “a bigger model plus a longer prompt.” It is a system engineering problem made up of a model, context, tools, state, and evaluation.
So instead of organizing this guide as a tool cheat sheet, it follows the real order of shipping to production: build the right mental model first, then layer in tool calling, context management, task planning, evaluation, and operations. Cloud capabilities mentioned here are described by generic category, such as object storage, message queues, container platforms, logging services, and monitoring and alerting, so you can map them to any compliant cloud environment.
2. The Minimal Viable Agent Architecture
A runnable agent typically has five layers:
- Model layer: handles reasoning and generation, and decides whether to call a tool and how to structure the answer.
- Context layer: holds system instructions, conversation history, retrieved snippets, and tool results.
- Tool layer: exposes external capabilities (queries, computation, file writes, internal API calls) in a structured way.
- State layer: stores task progress, intermediate artifacts, and retry information to support long-running flows and resume-from-checkpoint.
- Evaluation and observability layer: records the call chain, latency, and failure reasons to form a loop for continuous improvement.
If any one of these layers is missing, the system will show its weak spots under real traffic. For example, with only the model layer and a prompt, the agent “forgets what it is doing” on tasks that require multiple steps. Without a state layer, a long task that times out has to start over entirely.
3. Tool Calling: Turning “Talking” into “Doing”
Tool design is the dividing line between a demo and something usable. Four principles matter most in practice:
- The description is the contract: tool names and parameter descriptions must let the model choose correctly without guessing. Avoid vague “do-everything” tool designs.
- Moderate granularity: tools that are too coarse put too much responsibility in a single call and make errors hard to locate; tools that are too fine increase the number of rounds and latency.
- Trimmed return values: return only the fields needed to complete the task, reducing context bloat and noise.
- Explainable failures: error messages should include a readable reason and an actionable suggestion, not just a raw internal exception.
A skeleton tool declaration looks like this (pseudocode, structure only):
def tool_search_docs(query: str, top_k: int = 5) -> dict:"""Search internal docs by keyword and return a list of titles, snippets, and links.query: core keywords of the user's questiontop_k: number of results, default 5, max 10"""results = vector_index.search(query, limit=top_k)return {"items": [{"title": r.title, "snippet": r.snippet} for r in results]}
Once you have more than a dozen tools, consider a tool-routing approach: use a lightweight check to narrow the candidate set first, then let the main model choose from a small number of candidates. This can significantly reduce the wrong-tool call rate.
4. Context Management: The Hidden Variable That Determines Stability
Context is the most expensive resource an agent has. Three common techniques control its size and quality:
- Layered loading: keep system instructions resident, inject task-relevant information by stage, and summarize and compress conversation history.
- Retrieval instead of memory: when long-term knowledge is needed, retrieve first rather than stuffing all the material into the prompt.
- Structured placeholders: organize tool results into fixed fields to reduce ambiguity from free text.
A common mistake is keeping all historical messages verbatim. As the number of turns grows, the model’s attention is diluted and instruction-following drops. A safer approach is to keep four elements: the goal, completed steps, pending items, and key constraints, and write the rest of the details to the state layer to be fetched on demand.
5. Task Planning: From Single-Turn Q&A to Multi-Step Execution
For multi-step tasks, use a “plan-execute-validate” loop instead of generating all steps at once:
- Plan: break the user’s goal into verifiable subgoals and define the input and output of each step.
- Execute: advance one subgoal at a time and call tools to get real data.
- Validate: check results with both rules and the model; if validation fails, roll back and adjust the plan.
- Converge: set a maximum number of rounds and a timeout budget to avoid infinite loops that burn resources.
A sample control flow:
for step in range(MAX_STEPS):decision = model.decide(goal, state.summary(), available_tools)if decision.type == "tool":result = run_tool(decision.name, decision.args)state.record(step, decision, result)elif decision.type == "final":return validate(decision.answer, state)if state.budget_exhausted():return fallback_reply(state)
MAX_STEPS, timeouts, and budget control are mandatory. Without them, a multi-step agent will almost inevitably lose control of costs in production.
6. Evaluation: No Measurement, No Optimization
Agent evaluation should cover three dimensions:
- Result correctness: whether the final answer meets the user’s real intent, using rule-based assertions combined with manual spot checks.
- Process soundness: whether tool selection is appropriate, call parameters are correct, and there are no redundant steps.
- Engineering metrics: time to first token, end-to-end latency, number of calls per task, and failure rate.
Build a fixed evaluation set from day one, covering typical scenarios, edge cases, and historical failures. Run a regression after every change to prompts, tool descriptions, or planning strategy, so you don’t “fix one scenario and break three others.”
7. Pre-Launch Checklist
- Least privilege: grant tools minimal permissions; write operations require a second confirmation or an idempotent design.
- Full-chain logging: record inputs, tool calls, returns, and latency, and send logs to a logging service for easy search.
- Monitoring and alerting: set threshold alerts for failure rate, timeout rate, and abnormal round counts.
- Fallback strategy: when the model or a tool is unavailable, return a clear message instead of a blank response or a retry loop.
- Cost control: limit context length and maximum rounds, put static assets in object storage, and route asynchronous tasks through a message queue to smooth out peaks.
- Data compliance: mask sensitive fields before they enter the context, and define a data retention period.
8. Common Anti-Patterns and Fixes
- Anti-pattern 1: putting all logic into one very long prompt. Fix: split it into four layers: instructions, constraints, tool descriptions, and retrieved content.
- Anti-pattern 2: chasing full automation with no human confirmation step. Fix: add an approval checkpoint for irreversible operations.
- Anti-pattern 3: looking only at the demo and skipping regression evaluation. Fix: build a repeatable evaluation pipeline.
- Anti-pattern 4: returning raw large objects from tools. Fix: trim fields and paginate, and when necessary write to storage and pass a reference.
9. Conclusion
An agent’s competitiveness does not come from how many tools it connects to, but from whether the context is clean, the tool contracts are clear, planning can converge, and evaluation is sustainable. Fill in these layers step by step, and combine them with container platform deployment, logging service observability, and monitoring and alerting as a safety net, and developers can deliver stable, usable agent applications at a controllable cost. If you need more complete engineering support, you can build a standardized environment with the general cloud capabilities offered by Baidu AI Cloud (such as container platforms, logging services, monitoring and alerting, object storage, and message queues), so you can focus on business logic and evaluation.
