Agentic Application Refactoring: A Practical Guide to Building Reliable AI Agents

    This guide explains how to refactor applications from single-turn generative AI assistance to agentic systems that can plan, use tools, and self-correct. It covers a six-layer architecture, context engineering, tool design and planning, a three-tier evaluation system, security and cost controls, and a phased rollout roadmap. The goal is to turn general-purpose model capabilities into stable business value through solid engineering foundations.

    1. Why Applications Need to Move from Assistance to Collaboration

    Over the past two years, generative models in products have mostly remained at the level of single-point assistance: completion, summarization, and rewriting. They share a common pattern: the user sends a request, the model returns a piece of content, and the flow ends. The value is clear, but so is the ceiling—the model does not hold task state, does not understand business constraints, and cannot correct itself after a failure.

    Agentic capabilities change this premise. Instead of treating the model as a one-shot text function, they treat it as an execution entity that can plan, call tools, read intermediate results, and continuously revise. This shift in role can be summarized in three points:

    1. From passive response to active progress: the system can break down goals, arrange steps, and proactively query when information is missing.
    2. From single-turn output to multi-turn closed loops: results must go through validation, retries, and convergence rather than being delivered after one generation.
    3. From generic advice to constrained execution: all actions happen within permission, budget, and compliance boundaries.

    It is important to emphasize that this shift is not a natural result of a single improvement in model capability, but the result of engineering system refactoring. Without supporting architecture, agents only upgrade “answering wrong” into “doing wrong.”

    2. Overall Layered Architecture for Refactoring

    A maintainable agent system can usually be split into six layers, each with clear responsibilities and the ability to evolve independently:

    • Access layer: handles sessions, authentication, rate limiting, and multi-device consistency, shielding terminal differences.
    • Orchestration layer: task planning, step scheduling, state machine progression, and failure fallback; it is the core of the system.
    • Capability layer: exposes deterministic capabilities such as retrieval, computation, database access, and transaction commits in the form of tools.
    • Model layer: handles reasoning and generation, with multi-model routing and fallback through a unified gateway.
    • Data layer: vector indexes, structured storage, caches, and logs that support context and observability.
    • Governance layer: permission checks, auditing, cost quotas, content safety, and evaluation regression.

    The key design principle is: keep deterministic things deterministic. Anything that can be precisely done with code (sorting, summation, state transitions, permission checks) should never be handed to the model; the model only handles semantic understanding, intent clarification, and solution selection.

    3. Context Engineering: The Invisible Infrastructure That Determines Success

    Unstable agent behavior is usually not a model problem but a context organization problem. In practice, it is recommended to divide context into four types and govern them separately:

    1. Instruction context: role, boundaries, and output format; it should be short and stable, avoiding frequent changes that cause behavior drift.
    2. Task context: current goal, completed steps, and hypotheses to be validated; it should be stored in a structured way rather than relying on conversation history.
    3. Knowledge context: injected on demand through retrieval, controlling the number of fragments and the relevance threshold; fewer but more accurate is better.
    4. Tool context: the list of available tools, parameter schemas, and return structures, dynamically trimmed per scenario.

    An illustrative context assembly logic is as follows (pseudocode, expressing structure only):

    1. def build_context(session, query):
    2. return {
    3. "instruction": SYSTEM_PROMPT, # stable and unchanged
    4. "task": session.task_state.to_dict(), # structured task state
    5. "knowledge": retriever.top_k(query, k=5), # retrieval on demand
    6. "tools": tool_registry.schema_for(session.scene),
    7. "budget": {"steps": 8, "tokens": 12000}
    8. }

    The budget field is especially important. Setting upper limits on steps and tokens is the most effective way to prevent agents from falling into loops and losing control of costs.

    4. Tool Calling and Planning: Caging Uncertainty

    The quality of tool design directly determines the ceiling of an agent. Four guidelines can be followed:

    • Single semantics: one tool does one thing, with naming and descriptions readable by the model.
    • Strict schemas: parameters use strongly typed schema validation, rejecting ambiguous input.
    • Idempotency first: write operations should support idempotency keys to avoid duplicate submissions caused by retries.
    • Readable errors: return structured error codes and fixable hints so the model knows how to adjust the next step.

    For planning strategy, it is recommended to adopt “narrow first, then wide”: first use a small-step plan to validate feasibility, then gradually open up parallelism and autonomy. For high-risk actions, introduce human confirmation nodes to form a Human-in-the-loop mechanism.

    1. {
    2. "tool": "query_order_status",
    3. "arguments": {"order_id": "A10086", "idempotency_key": "req-7f3"},
    4. "on_error": {"strategy": "replan", "max_retry": 2}
    5. }

    5. Evaluation System: Agents Without Regression Cannot Go Live

    Traditional unit tests cannot cover the behavior space of agents; a three-tier evaluation system is needed:

    1. Tool-layer evaluation: given an input, verify the correctness of tool selection and parameters.
    2. Trajectory-layer evaluation: assess whether the step sequence is reasonable and whether there is redundancy or infinite looping.
    3. Result-layer evaluation: scored jointly by rules and models, focusing on factual consistency, constraint compliance, and usability.

    In engineering, the evaluation set should be incorporated into continuous integration, and any change to prompts, model versions, or tool schemas should trigger regression. At the same time, a failure sample library should be retained, feeding online problems back into test cases to form a closed loop.

    6. Security, Cost, and Observability

    • Least privilege: tool credentials are tiered by scenario, with separate authorization for write and read operations.
    • Bidirectional input/output protection: isolate injection-style instructions and desensitize sensitive information in outputs.
    • Full-chain tracing: record planning, tool calls, token consumption, and latency to help locate bottlenecks.
    • Cost control: set step and call quotas per scenario, combined with caching and tiered model routing to reduce overhead.

    If deployed in the cloud, you can combine container platforms to host orchestration services, message queues for asynchronous task decoupling, object storage to save trajectories and evaluation samples, and logging services with monitoring and alerting to ensure observability. These are common industry capability categories that can be freely combined according to your own architecture.

    7. Phased Implementation Roadmap

    • Phase 1 (2–4 weeks): choose a high-frequency, low-risk scenario with automatically verifiable results, and only do “retrieval + single tool call,” first connecting evaluation and tracing.
    • Phase 2 (1–2 months): expand the toolset, introduce structured task state and failure replanning, and add human confirmation nodes.
    • Phase 3 (quarter level): open multi-scenario orchestration and parallel execution, establish cost quotas and a governance dashboard, and accumulate a reusable tool library.

    8. Conclusion

    The real change brought by agents is not that models answer questions more fluently, but that the way software engineering is organized has shifted: requirement description expands from interface definitions to goal definitions, testing expands from asserting outputs to verifying trajectories, and operations expands from monitoring metrics to monitoring decision processes. Whoever first makes the three pieces of infrastructure—context, tools, and evaluation—solid can stably convert general model capabilities into business value. Baidu AI Cloud also has corresponding practices in these common capabilities, which can serve as a reference for architecture selection.