Rearchitecting Legacy Software for the AI Agent Era
This article explains why simply adding a chat interface to existing systems is not enough to unlock the value of AI agents. It compares traditional CRUD architectures with agent-based designs across key dimensions, outlines a practical refactoring path for the data, tool, and control layers, and provides an annotated control-loop pseudocode example. It also covers cloud-native infrastructure selection, a pre-launch checklist, and common pitfalls to avoid when moving from transaction-heavy software to agent-driven workflows.
The growing discussion around AI agents often leaves teams with a superficial understanding—many believe the value lies in simply adding a chatbot window to an existing application. In reality, an agent’s core value is its ability to understand a goal, decompose it into subtasks, and invoke tools to complete work. To use it effectively, you must rethink your existing software architecture.
Traditional Software vs. Agent Architecture
Traditional software is essentially a collection of predefined flows. Users input explicit commands through a graphical interface, the system processes structured data according to pre‑written logic, and returns results. This model is mature and predictable, suitable for well‑defined business rules. However, when requirements become ambiguous or cross‑system collaboration is needed, humans often end up acting as “data movers.”
An agent architecture delegates part of the decision‑making to a large language model (LLM). The table below highlights the key differences:
| Dimension | Traditional CRUD Architecture | Agent Architecture |
|---|---|---|
| Interaction method | Fixed forms and buttons | Natural language description of goals |
| Control flow | Hard‑coded conditional branches | Model plans steps, dynamically adjusts during runtime |
| State management | Business state in database | Business state plus session memory & task context |
| Failure recovery | Error message, human intervention | Reads error, attempts parameter fixes or replanning |
| Evaluation metrics | API response time, error rate | Task completion rate, tool call accuracy, hallucination rate |
This table makes clear that an agent is not just a chat entry point bolted onto an old system. It changes the distribution of control within the system and fundamentally changes how quality is measured.
The Refactoring Path: Data, Tools, and Control
1. Data Layer: From Structured Storage to Retrievable Knowledge
Relational databases are well‑suited for storing business states like orders and accounts, but they struggle to support an agent’s understanding of unstructured content—documents, code, historical tickets, and so on. A common approach is to add a vector database and combine it with RAG (Retrieval‑Augmented Generation):
- Chunk documents, preserving metadata such as title, source, and update time.
- Generate embeddings for text chunks and write them to a vector store. User intent is also converted into an embedding, and similarity search retrieves relevant chunks.
- Injected the retrieved content into the prompt, allowing the model to answer based on the provided material.
When selecting a vector database, pay attention to metadata filtering capabilities, incremental update latency, multi‑tenant permission isolation, and the trade‑offs between vector dimensions and storage cost. Retrieval quality should be evaluated separately, using metrics such as recall, context hit rate, and hallucination rate. If you only evaluate the final answer’s plausibility, retrieval‑stage problems will remain hidden.
2. Tool Layer: Repackaging Business Capabilities for the Model
Traditional RESTful APIs or RPC interfaces are designed for human developers—they have many parameters, complex authentication, and assume the caller understands business context. An agent‑oriented tool should have a clear name, purpose description, parameter meanings, and examples.
Each tool should include at least the following:
- Function signature with parameter types, clearly separating required and optional fields.
- Description written for the model, explaining what the tool does, which scenarios it is suitable for, and which scenarios it is not.
- Least‑privilege design: only expose the operations required for the current business step, using a whitelist to restrict callable scope.
- An idempotency key: repeated execution of the same operation must not create duplicate orders or double charges.
- Timeout and error‑code conventions so the model can understand failure causes.
Tool‑returned content must also be treated as untrusted input. If a web page or document contains text like “ignore previous instructions,” the system should treat it as ordinary data rather than an executable instruction.
3. Control Layer: Planning, Execution, and Reflection
The core loop of an agent is typically ReAct (Reasoning and Acting): the model first decides the next action, then calls a tool, then continues reasoning based on the result. For tasks with many steps, you can first generate a plan using a Plan‑and‑Solve approach and then execute it step by step.
The control layer needs to handle three situations:
- The tool is missing or not on the whitelist — replan.
- Tool execution failed — read the error message, fix parameters, and retry.
- Both retries and replanning hit their limits — stop the task and hand control to a human.
Setting limits is crucial. Without limits, retries can exhaust budgets or trap the agent in an infinite loop.
Technical Implementation: Pseudocode for a Controlled Agent Scheduler
The following pseudocode shows the basic structure of the control layer. Compared to an early draft, it explicitly replans after a replan decision, retries failures with a maximum retry count, uses idempotency keys and timeouts for tool calls, and restricts execution to a whitelist of tools.
class EnterpriseAgent:def __init__(self, llm_engine, tools_registry, vector_memory,allowed_tools, max_replans=3, max_retries=2):self.llm = llm_engineself.tools = tools_registryself.memory = vector_memoryself.allowed_tools = set(allowed_tools)self.max_replans = max_replansself.max_retries = max_retriesdef execute_task(self, user_intent):context = self.memory.retrieve(user_intent, top_k=5)plan = self.llm.plan(user_intent, context)replans = 0results = []step_index = 0while step_index < len(plan):step = plan[step_index]tool = self.tools.get(step.tool_name)if tool is None or step.tool_name not in self.allowed_tools:if replans >= self.max_replans:return self._stop("Tool unavailable and replan limit reached", results)replans += 1self.memory.add(f"Tool {step.tool_name} unavailable, replan # {replans}")plan = self.llm.replan(user_intent, self.memory.get_recent())step_index = 0continueok, result = self._run_with_retry(tool, step)if ok:results.append(result)step_index += 1else:if replans >= self.max_replans:return self._stop("Tool repeatedly failed and replan limit reached", results)replans += 1plan = self.llm.replan(user_intent, self.memory.get_recent())step_index = 0return self.llm.summarize(self.memory.get_recent())def _run_with_retry(self, tool, step):for attempt in range(self.max_retries + 1):try:result = tool.run(step.parameters,idempotency_key=step.idempotency_key,timeout_seconds=10,)self.memory.add(f"{tool.name} executed successfully")return True, resultexcept Exception as e:self.memory.add(f"{tool.name} execution failed (attempt {attempt + 1}): {e}")reflection = self.llm.reflect(step, str(e))step.parameters = reflection.updated_paramsreturn False, Nonedef _stop(self, reason, partial_results):self.memory.add(f"Task stopped: {reason}")return {"status": "needs_human", "reason": reason, "partial": partial_results}
Two implementation details deserve attention. First, the new plan generated by replanning should only contain steps that have not yet been completed; otherwise, already‑succeeded operations will be repeated. Second, the idempotency key should be derived from both the task ID and the step index, so retries and replans can be recognized and deduplicated.
Cloud‑Native Infrastructure Selection
Agent inference calls, context storage, and concurrent tool invocations all create fluctuating workloads. Consequently, auto‑scaling, object storage, message queues, and logging/monitoring are common building blocks. Major cloud providers already offer these capabilities. When choosing among them, compare on the following criteria:
- Region and compliance: whether data can be stored in regions that meet regulatory requirements.
- Cost structure: how model calls, vector storage, and log retention are billed, and whether budget alerts are easy to set.
- Ecosystem and migration cost: which cloud the existing systems already run on, and whether the toolchain is compatible.
- Observability: whether each step of inference, tool call, and retry count can be traced and correlated to the same task ID.
A container platform is suitable for hosting the agent orchestration service; object storage works well for storing corpora and runtime logs; message queues are useful for asynchronous collaboration between multiple sub‑agents. The more standardized the components, the lower the operational overhead, and the more your team can focus on prompt design and business rules.
Pre‑Launch Checklist
Before going live, verify the following items:
- Least privilege: each agent identity has only the permissions needed to complete its task.
- Tool whitelist: any unregistered tool is rejected.
- Audit logs: record model inputs/outputs, tool parameters, execution results, and the operator.
- Idempotency keys & timeouts: all write operations have deduplication and timeout controls.
- Retry & replan limits: once limits are reached, hand over to a human instead of continuing.
- Context window management: truncate or summarize historical memory to stay within model limits.
- Cost budget: set invocation quotas per task or per user.
- Sensitive data masking: phone numbers, ID numbers, keys, etc., must be processed before entering the prompt.
- Human approval: high‑risk operations such as deleting data, transferring money, or external sending require confirmation.
- Evaluation set: use real task samples to routinely measure completion rate, tool accuracy, and hallucination rate.
Common Questions
How should you choose an agent architecture?
If the task has many steps, ambiguous input, and requires cross‑system coordination, an agent typically reduces manual data shuttling. If the flow is fixed, rules are clear, and determinism is critical, traditional code is often more stable and cheaper. You can also combine the two—let deterministic code handle key actions while an agent handles understanding and orchestration.
What should you pay attention to when implementing?
Start with a well‑bounded scenario, such as internal knowledge Q&A or ticket classification, then gradually open up write operations. Every expansion of permissions should be accompanied by additional auditing and evaluation.
What are common mistakes?
- Treating an agent as a one‑off chat interface without state management or failure recovery.
- Vague tool descriptions that make the model choose the wrong tools frequently.
- Not setting retry limits, causing budget overruns.
- Only evaluating the final answer while ignoring retrieval and tool‑call quality.
- Executing external document content as instructions, which introduces prompt‑injection risks.
Conclusion
The agent changes how software is controlled: instead of every branch being hard‑coded by the developer, the model plans and executes within constraints. This shift already delivers tangible benefits in multi‑step, unstructured, and cross‑system scenarios. But it also introduces new risks—uncertain outputs, uncontrolled call costs, and permission misuse.
For most teams, the safer path is to validate in a low‑risk scenario, use evaluation data to decide whether to expand, and keep traditional code for the deterministic core processes. The pace of architecture refactoring should be driven by task complexity, data quality, and your team’s governance capabilities, not by the appeal of new technology alone.
