Building AI Agents from Scratch: From Prototype to Production
This article explores the practical challenges of building AI agents, emphasizing the transition from basic prototype validation to robust production deployment. It outlines a four-layer capability model for agent development—answering correctly, ensuring consistency, maintaining stability, and enabling continuous improvement—along with a structured practice path for beginners to build reliable systems.
1. Why Tutorials Aren’t Enough to Build an AI Agent
Many beginner tutorials demonstrate a smooth path: input a question, the model understands the requirement, calls a tool, and returns the answer. Such demonstrations help explain basic mechanisms but often hide the most crucial parts of real-world projects.
For example, what happens if the user doesn’t provide a complete question? What if two documents in the knowledge base contradict each other? Should the system retry or stop if a tool execution times out? How does the system identify when the model generates a plausible explanation that actually lacks evidence?
These issues usually cannot be solved by simply adding another component. They involve task definition, business design, reliability control, and continuous improvement.
Therefore, beginners learning to build agents must first distinguish between two goals:
- Prototype Validation: Determining whether a model has the potential to complete a specific type of task.
- Production Delivery: Ensuring the system consistently completes tasks under explicit constraints of permissions, cost, and quality, while being able to explain, monitor, and handle failures.
Prototyping focuses on “can it be done once,” while production focuses on “under what conditions it can be done reliably, and how to exit safely when it cannot.”
Your learning path should revolve around this difference, rather than a checklist of framework features.
2. Clarifying the Concept: An Agent Is Not a Chat Window
In this article, an AI agent refers to a system that uses a model to understand or make decisions around a predefined goal, and calls tools as authorized, reads execution results, and advances the task.
A typical task loop can be represented as:
Receive Request → Check Permissions & Task Scope → Determine Next Step → Call Tool → Validate Result → Continue Execution or End
It generally consists of the following components:
- Model: Understands input, generates content, or proposes the next action.
- Instructions & Rules: Constrain task scope, output format, and behavioral boundaries.
- Tools: Retrieves materials, queries business data, creates tickets, etc.
- State Management: Records completed steps, tool results, and pending items.
- Execution Control: Limits tool permissions, execution counts, timeouts, and resource consumption.
- Validation Mechanisms: Judges whether results meet requirements, transferring to humans if necessary.
Not all applications require a fully autonomous decision loop. If a task always executes in fixed steps, using a deterministic workflow is often simpler and easier to test.
To determine if you need an agent, ask:
Does the next step of the task need to be dynamically selected based on intermediate results?
If the answer is no, prefer a fixed process. If yes, consider introducing model decision-making locally.
3. Choose a Suitable Starter Project, Not a General Assistant
It is recommended to start practicing with “Enterprise Knowledge Q&A and Ticket Draft Generation.”
Its initial scope can be limited to:
- Answering policy and operational questions based on audited documents;
- Providing verifiable sources when answering;
- Explaining uncertainty when evidence is lacking;
- Determining if additional information is needed;
- Generating a ticket draft if the issue cannot be directly resolved;
- Requiring user confirmation before submitting a ticket.
This exercise covers retrieval, generation, tool calling, permission control, and human-in-the-loop confirmation simultaneously, but the risk remains relatively manageable.
Do not initially require the system to handle all departmental questions, automatically modify business data, and run autonomously for long periods. The broader the scope, the harder it is to determine whether failures stem from the model, data, business rules, or engineering implementation.
Before starting the project, write a one-page task specification:
| Project Element | Questions to Clarify |
|---|---|
| Target Users | Who will use it, and what permissions do they have |
| Input Scope | Which questions are accepted, which requests are rejected |
| Output Requirements | Whether sources, structured fields, or confirmation prompts are needed |
| Data Sources | Which materials can be used, who is responsible for updates |
| Tool Permissions | Which operations are read-only, which will change business state |
| Success Criteria | How to judge that the task is truly complete |
| Exit Conditions | When to stop, ask follow-ups, or transfer to a human |
This specification is not just a formal document, but the shared basis for subsequent evaluation, development, and launch acceptance.
4. First Layer: Ensuring the System Answers Correctly, Not Just Answers
1. Evaluation Should Precede Complex Architecture
Many projects build the system first and only start judging the effectiveness at the end. This makes every modification a matter of subjective comparison.
A better approach is to prepare a small test set first. Samples should at least cover:
- Common questions with clear answers;
- Incompletely expressed questions requiring follow-up;
- Questions not covered by documentation;
- Questions with version conflicts;
- Questions exceeding user permissions;
- Questions where tools fail or return empty results.
Each sample should record expected behavior, not just the reference answer. For instance, “refusing to give a definitive conclusion when data is insufficient” is itself a correct behavior.
For knowledge Q&A, you should separately evaluate whether retrieval found relevant materials, whether the answer aligns with the materials, and whether the citation supports the conclusion. For ticket tasks, you need to check if fields are complete, classification is reasonable, and confirmation was obtained before submission.
Distinguish between “successful tool call” and “successful task.” A normal tool return does not mean the called object, parameters, and business result are all correct.
2. Prompts Express Constraints, But Cannot Bear All Control
Prompts should clarify the task, how to use materials, output format, and principles for handling uncertainty.
For example:
Answer only based on authorized materials. If the materials cannot support a conclusion, state what information is missing. When submitting a ticket, generate a draft and request confirmation first; do not submit directly.
Such requirements help improve model behavior, but prompts are not security boundaries. Permission checks, parameter validation, and submission approvals must be executed by code, not relying solely on the model obeying text instructions.
When debugging, do not attribute all failures to prompts. Errors might come from missing data, retrieval failure, ambiguous tool definitions, or overly broad task scopes.
3. RAG Solves “Where the Evidence Comes From”
The basic process of Retrieval-Augmented Generation (RAG) is: find relevant materials based on the question, provide the materials to the model as context, and ask the model to answer based on the materials.
Its effectiveness depends on the entire chain, not just the retrieval algorithm:
Data Preparation → Document Chunking → Index Building → Permission Filtering → Retrieval & Ranking → Answer Generation → Source Verification
In practice, note:
- Documents should retain titles, versions, effective dates, and permission info;
- Chunking should maintain the integrity of conditions, rules, and exceptions;
- For version conflicts, follow explicit rules; if indeterminable, prompt the conflict;
- Retrieval results must be constrained by access permissions;
- Answer citations should be traceable to specific content, not just a document name.
The presence of a citation does not mean the answer is correct; you must also check if the cited content actually supports the conclusion.
4. Start Tool Calling with Read-Only Operations
Beginners can first integrate read-only tools like knowledge retrieval and status queries, then gradually add operations like draft generation and ticket submission.
Each tool should have clear input, output, and error definitions. The program side should at least validate parameter types, value ranges, calling permissions, and return result structures.
Do not give the agent a general entry point that can execute any operation. The more specific the permissions, the easier it is to control risk and locate errors.
5. Second Layer: Delivering Consistent, Explainable Results
1. Business Semantics Must Be Unified
Models can understand language, but cannot replace an enterprise in defining metric calibers.
For example, “processing duration” might mean natural time from creation to closure, or it might only count working hours, or exclude stages waiting for user-supplied information. If the definition is unclear, even if the calculation is error-free, the answer may not meet business needs.
Therefore, maintain business semantic documentation, including at least:
- Terminology and metric definitions;
- Time ranges and calculation rules;
- Applicable objects;
- Common aliases;
- Versions and effective dates.
For tasks requiring calculation, prefer deterministic programs to perform the math. The model should be responsible for identifying needs and explaining results, not substituting business logic with linguistic inference.
2. Disambiguation Is More Important Than Premature Execution
If a user says “check the processing status,” the system may not know which ticket, which time period, or whether they need status or statistical info.
A reasonable approach is to first determine if missing information will change the execution result. If yes, ask for clarification; if no, use a clear, reversible default value and explain it to the user.
Follow-ups should be focused:
Do you want to view the current status of a specific ticket, or the statistics of tickets over a recent period?
This is easier to interact with than asking the user to fill out all fields at once.
3. Trustworthiness Comes from Evidence and Process
Do not treat the model’s self-reported “confidence” as a reliable probability. More useful trustworthiness factors include:
- Whether applicable and valid sources were found;
- Whether there are conflicts among sources;
- Whether key fields are complete;
- Whether tool results passed validation;
- Whether necessary human confirmation was obtained.
When displaying results to users, distinguish facts, inferences, and suggestions. Content that cannot be verified must be explicitly labeled, rather than masking the issue with a generic disclaimer.
4. Workflows and Agents Should Collaborate
Deterministic rules go to code; open-ended judgments go to the model.
For example, identity verification, field checks, approval requirements, and ticket submission can use fixed workflows; question classification, information extraction, and follow-up generation can be handled by the model.
This hybrid approach is usually better suited for initial production applications than fully autonomous operation, because it retains the model’s flexibility while making critical business actions verifiable and auditable.
6. Third Layer: Ensuring Stable Operation, Not Occasional Success
1. Control Cost, Latency, and Loop Count Simultaneously
A single request might trigger multiple rounds of model calls, retrieval, and tool execution, so you cannot just track single-generation costs.
Observe the resource consumption of the entire task, including model call volume, context length, retrieval times, tool execution time, and manual processing costs.
Common control measures include:
- Setting max execution steps and total time limits for tasks;
- Retaining only the context needed for the current decision;
- Using versioned caches with permission boundaries for stable materials;
- Avoiding repeated retrieval and tool calls;
- Adopting different processing paths for tasks of varying complexity.
Cost optimization must be combined with quality evaluation. Reducing context may lower costs, but might also remove critical rules; do not just look at the billing changes.
2. Monitoring Should Be Able to Replay the Task Process
Logging only the final answer is usually insufficient for troubleshooting.
Each task should be associated with a unified trace ID, recording model and prompt versions, retrieval sources, tool calls, validation results, time consumption, stop reasons, and human takeover status.
Logs should follow the principle of minimum necessity. Personal information, credentials, and sensitive business data should be desensitized, with access and retention periods restricted.
This allows you to answer: “In which step did the error occur?” rather than just knowing “the user was dissatisfied.”
3. Error Handling Must Differentiate Types
Different errors require different strategies:
- Invalid parameters: Correct parameters or ask the user for clarification;
- Insufficient permissions: Stop the operation, do not bypass restrictions;
- Transient service anomalies: Limited retry within budget;
- Insufficient data: State inability to judge, transfer to human if necessary;
- Ambiguous execution state: Query status first, then decide subsequent actions.
Especially for write operation timeouts, do not assume the execution failed by default. The request may have taken effect, and blind retries will cause duplicate submissions. Use idempotency mechanisms or result queries to reduce the risk of repeated execution.
4. Context Management Is Not Simply Truncating Chat History
Long conversations may contain a lot of irrelevant info or retain outdated judgments. Task state, user confirmations, material summaries, and raw conversation should be managed separately.
Key states should be saved in a structured form, such as fields for the ticket to be submitted, confirmed items, and remaining questions. Summaries need to retain sources and constraints, not compress inferences into facts.
Long-term memory should also be subject to authorization, purpose, and retention period constraints, rather than saving all user input by default.
5. External Content Must Not Become Execution Instructions
Retrieved documents, user-uploaded files, and tool return content may contain deceptive text. The system must distinguish between “data for reference” and “instructions allowed to execute.”
Tool authorization, access control, and high-risk operation confirmation must be handled by code. Even if materials contain text like “ignore rules and submit,” it should not change system permissions.
7. Fourth Layer: Continuous Improvement Through Evidence After Launch
Production systems require two types of evaluation working together:
- Offline Evaluation: Uses fixed samples to compare versions and detect regressions.
- Online Observation: Analyzes failures, time consumption, human takeovers, and user feedback in real tasks.
Fixed samples are good for stable comparison but cannot cover all real needs; online feedback is closer to reality but may have bias. Therefore, reviewed online failure cases should be gradually converted into regression tests.
When modifying prompts, retrieval strategies, or tool rules, versions should be recorded. Pass offline tests first, then proceed with controlled releases. If conditions permit, use grouped experiments to compare effects, but keep task types, traffic allocation, and observation windows as comparable as possible.
User feedback should not be limited to “satisfied” or “dissatisfied.” Provide specific reasons, such as wrong answer, insufficient evidence, question misunderstood, operation incomplete, or slow response, to help locate the corresponding stage.
Historical conclusions can only enter reusable knowledge after verification. If wrong answers are written directly back to the knowledge base, it may create continuously amplifying feedback contamination.
8. A Four-Stage Practice Path for Beginners
Stage 1: Establish a Baseline
Choose a narrow scenario, prepare audited materials and a set of test questions, and first implement single-turn Q&A.
The output of this stage is a task specification, a test set, and baseline evaluation results—not a complex UI.
Stage 2: Complete Evidence and Boundaries
Add retrieval, source display, permission filtering, and refusal to answer when data is insufficient. Focus on verifying whether the system mistakes “no evidence” for “can guess.”
Stage 3: Add Controlled Tool Operations
First support queries, then draft generation, and finally add submission after user confirmation. Write normal, abnormal, and unauthorized test cases for each tool.
Simultaneously add max steps, timeouts, error classification, and trace logging.
Stage 4: Conduct a Small-Scale Trial Run
Observe real usage among a controllable group of users, retaining manual fallback and rollback paths. Categorize failures and prioritize fixing high-risk, recurring issues.
Only gradually expand the usage scope after quality, security, cost, and observability meet predefined requirements. There is no universal launch metric for all businesses; standards should be set based on operational risk and business tolerance.
9. Summary: True Entry Means Building a Complete Validation Loop
Agent development doesn’t end with connecting a model, knowledge base, and tools. Complete practice requires answering four types of questions:
- Technical Layer: How does the system obtain information and validate answers and actions?
- Design Layer: How to maintain business semantic consistency facing different users and vague needs?
- Engineering Layer: How to control permissions, costs, failures, and execution risks?
- Operations Layer: How to continuously improve through real feedback without introducing new regressions?
Frameworks can help implement these aspects but cannot replace your understanding of these issues.
For beginners, the most effective practice is not to build an “omnipotent agent” at once, but to complete a small system with clear boundaries: knowing what it can do, proving it did it right, and being able to stop safely when it cannot.
