Guide to LLM Agent Architecture and Deployment for Knowledge-Intensive Applications
This guide covers the core architecture and run loop of LLM agents. It explains how to choose a foundation model, when to use RAG or fine-tuning, and how to build agents safely with tool allowlists, step limits, and human confirmation. It also covers evaluation metrics, common deployment mistakes, and the limits of agent use in finance, legal, and education.
1. Basic Architecture of an Agent
An agent is a software system that understands a goal, breaks it into steps, calls external tools, and returns results. It usually has three parts: an understanding and planning module (the LLM), a knowledge retrieval module (search and databases), and an action module (tool calls and code execution).
A typical run loop receives a request, generates a plan, retrieves relevant material, executes the steps one by one, verifies the results, and then returns an answer. Any step can fail, so the loop needs a step limit, timeouts, and exception handling. Do not assume the model will plan correctly every time.
2. Choosing a Foundation Model
Do not decide based only on the overall leaderboard score. A more reliable approach is to focus on the following factors:
- Task-specific evaluation: Check the name, version number, and test date of the benchmark, and confirm that it is close to your own business scenario.
- Context length: Note the relationship between tokens and Chinese characters. One Chinese character usually corresponds to one to two tokens, depending on the tokenizer. The advertised context window therefore does not equal the number of Chinese characters that fit into it.
- Inference cost: Measure the input and output token counts for a single request, and measure response latency under concurrent load.
- Deployment method: Weigh data privacy, operational capability, and cost when choosing between a cloud API and a private deployment.
- Compliance requirements: Confirm whether your data may be sent to an external service.
Run a small comparison on a sample of your real business data. Send the same set of questions to every candidate model, and record the accuracy and cost of each.
3. Choosing Between RAG and Fine-Tuning
Retrieval-augmented generation (RAG) suits scenarios where knowledge changes often and answers must cite verifiable sources, such as policy documents, product manuals, and internal regulations. Its advantage is that updating the knowledge base takes effect immediately, without retraining.
Fine-tuning suits teaching a model to follow a fixed output format, writing style, or domain terminology consistently. It is not a good fit for factual knowledge that changes frequently, because after the model’s parameters are updated, outdated knowledge may still persist.
The two can be combined: fine-tuning handles format and terminology, and RAG handles facts and sources. To make the choice, consider four questions: How often does the knowledge change? Must answers include source citations? Is there enough labeled data? Does the team have the capacity to maintain the system over the long term?
4. Core Pseudocode and Engineering Considerations
The framework below extends the basic loop with a tool allowlist, a step limit, manual confirmation, and retry logic. The helper methods must be implemented according to the specific system.
class LLMAgent:def __init__(self, llm, tools, kb, allowed_tools, max_steps=8):self.llm = llmself.tools = toolsself.kb = kbself.allowed_tools = set(allowed_tools)self.max_steps = max_stepsdef run(self, user_query, user_id):plan = self.llm.plan(user_query, available_tools=list(self.allowed_tools))context = self.kb.search(plan.keywords, top_k=5)for step_no, step in enumerate(plan.steps):if step_no >= self.max_steps:return self._fallback("Step limit exceeded. Execution stopped.")if step.requires_tool:if step.tool_name not in self.allowed_tools:return self._fallback("Unauthorized tool requested.")if step.is_risky and not self._confirm(user_id, step):return self._fallback("Waiting for manual confirmation.")result = self._call_with_retry(step, timeout=10, retries=2)else:result = self.llm.generate(step.prompt, context=context)plan.update_context(result)return self.llm.summarize(plan.executed_steps)
When you implement this in practice, keep the following points in mind. Grant tools under least privilege, and require separate approvals for read-only and write operations. Mask sensitive fields such as phone numbers and ID numbers in logs. Keep the source and update time of every retrieved result so the model does not treat outdated content as current rules. Set a timeout on every external call.
5. How to Evaluate an Agent
Evaluating an agent should not rely only on whether its answers read smoothly. Build a fixed test set, and track at least the following metrics:
- Task completion rate: whether the final result meets the user’s goal.
- Tool-call accuracy: whether the parameters are complete and the correct tool was chosen.
- Retrieval recall: whether the required material was retrieved.
- Factual accuracy: whether the key facts in an answer can be found in the sources.
- Response time and token cost per task.
- Manual review pass rate: the share of samples that qualified experts pass in spot checks.
Rerun the test set after every change to the prompts, the model, or the knowledge base, and compare the metrics. Without regression testing, it is hard to tell whether a change made the system better or worse.
6. Common Deployment Mistakes
- Excessive tool permissions. An agent that can access the entire database may read unrelated data if it is manipulated by malicious input.
- No limits on timeouts or retries. When the model repeatedly calls the same tool, costs can spiral and the service can stall.
- Logs that store complete user input, which may contain sensitive personal information.
- Retrieved results without timestamps or sources, leading the model to cite repealed regulations.
- No manual confirmation step for operations such as deletion, sending, or payment.
- Tests that cover only normal cases, without checking edge cases, ambiguous instructions, or malicious input.
7. Application Boundaries in Knowledge-Intensive Industries
Finance: Agents can help organize public materials, summarize financial data, draft analyses, and flag risk points. The output does not constitute investment advice. The data should come from authorized sources, and compliance staff should review it before external use.
Legal: Agents can help search for similar cases, outline the key disputed issues, and draft document outlines. The output does not constitute formal legal advice. Lawyers must verify the original texts and current regulations, and they remain responsible for the final documents.
Education: Agents can provide question-based tutoring, support preliminary grading of assignments, and analyze learning progress. Follow the principle of data minimization. Information about minors requires guardian consent and encrypted storage. Teachers keep the final decision on written feedback.
8. Conclusion
The results of an agent project depend on the quality of the knowledge base, tool design, the evaluation system, and the manual review process. The model is only one part of the system. Start with a pilot in a scenario with clear boundaries, establish evaluation and monitoring, and then gradually expand permissions and service scope.
