Refactoring an AI Agent System with AI Coding: From Rigid Workflows to Modular Skills and Planning

    This article explains how to refactor an AI Agent system from rigid low-code workflow orchestration into a layered architecture built on modular skills, intelligent planning, and standardized protocol interoperability, using AI-assisted coding to speed up the migration. It breaks down the capabilities required to turn a single natural-language request into a structured output, describes the target architecture and skill contracts, and shows how a goal-plan-execute-reflect loop handles branching and retries. It also covers multi-agent collaboration, retrieval-augmented generation for trustworthy content, persistence and state management, observability, and an incremental, rollback-safe refactoring process that can reach production in days.

    1. Introduction: Why Agent Architecture Replaces Workflow Orchestration

    In AI-driven e-commerce operations, an operator often wants to describe a complete shopping scene in a single natural-language sentence: an attractive title, a scene description, primary and secondary tags, and automatically matched, highly relevant products, all producing structured data that can be consumed directly by a venue builder. This looks like “generate a page from one sentence,” but underneath it is a complex chain that spans multiple models and multiple external systems.

    Early solutions typically relied on low-code workflow orchestration: intent recognition, content generation, product retrieval, information completion, and relevance filtering were drawn as a fixed node graph. This is efficient when requirements are stable, but as business complexity grows, models iterate faster, and more external systems are integrated, fixed orchestration exposes three bottlenecks:

    • Rigid flow: it cannot make dynamic decisions based on intermediate results.
    • Module coupling: a single-point change ripples through the entire chain.
    • Fragmented protocols: every external capability needs separate adaptation, making reuse expensive.

    This article therefore discusses a more sustainable engineering path: a modular skill system to carry atomic capabilities, intelligent planning for dynamic decisions, and standardized protocols to interconnect tools and external agents, with AI-assisted coding accelerating the refactor and rollout. Note that this discussion is not tied to any specific third-party product; it is abstracted into general technical methods and engineering practices.

    2. Breaking Down the Requirements: Six Capabilities Behind One Sentence

    To reliably turn a single natural-language sentence into a usable venue, the system needs at least the following capabilities:

    1. Multi-turn dialogue: operators rarely specify every constraint at once, so the system must support incremental additions and corrections while understanding context.
    2. Intent recognition and content generation: recognize the intent to “create a shopping scene,” extract key information such as category, audience, style, and price range, and generate the title, description, and tags.
    3. Multi-agent collaboration: capabilities such as product information completion and product relevance filtering can be handled by independent agents that cooperate through standard protocols to ensure both richness and precision.
    4. Tool and knowledge access: connect tools such as product search and cache writes through a standard model context protocol; use retrieval-augmented generation to query a trending-topics knowledge base and extract and rework link content so the output stays current.
    5. Persistence and state management: save scenes, products, and workflow state, and support integration with the venue builder.
    6. Enterprise deployment and observability: multi-node deployment, log querying, and trace tracking are all required.

    Cramming all of these into a single orchestration graph makes the node count explode and makes reuse difficult. A layered approach is more reasonable.

    3. Target Architecture: Modular Skills + Intelligent Planning + Protocol Interconnection

    3.1 Layered Design

    • Access layer: session management, context maintenance, permissions, and rate limiting.
    • Planning layer: a planner agent decomposes the user goal into executable steps and adjusts the plan dynamically based on intermediate results.
    • Skill layer: atomic capabilities are packaged into skill modules that can be tested and deployed independently, such as scene generation, tag expansion, product retrieval, content completion, and relevance filtering.
    • Protocol layer: a unified internal skill invocation contract, and standardized protocols externally to connect tools and external agents.
    • Infrastructure layer: general cloud categories such as object storage, message queues, container platforms, logging services, and monitoring and alerting carry runtime and operations.

    The key benefit of this layering: the planning layer does not depend on specific implementations, the skill layer does not depend on a specific flow, and the protocol layer shields external differences. This turns “changing the flow” into “changing the plan,” and “integrating a system” into “adding a protocol adapter.”

    3.2 Example Skill Contract

    Every skill should have a clear input/output contract so the planning layer can compose them:

    1. {
    2. "skill": "scene.generate",
    3. "input": {
    4. "user_utterance": "camping gear, refined style, budget 300-800",
    5. "context": {"session_id": "s-001"}
    6. },
    7. "output": {
    8. "title": "A Hundred Ways to Enjoy Refined Camping",
    9. "description": "...",
    10. "tags": {"l1": "Outdoor", "l2": ["camping", "portable coffee"] }
    11. }
    12. }

    Once contracts are stable, the planning layer can orchestrate skills like building blocks without caring whether a skill is implemented with rules, a small model, or a large model.

    4. Intelligent Planning: Making the Flow “Think”

    The weakness of fixed orchestration is that it cannot handle branching and rollback. The planning layer can adopt a “goal-plan-execute-reflect” loop:

    1. Goal parsing: convert natural language into a structured goal, such as scene theme, audience, style, and budget.
    2. Plan generation: output a sequence of steps, for example generate the scene first, then expand secondary tags, then retrieve products, and finally filter and complete.
    3. Execution and validation: after each step, run a lightweight check, such as whether tags are empty, whether the product count meets the target, or whether relevance falls below a threshold.
    4. Reflection and retry: if there are too few products, fall back to the tag expansion step and broaden keywords; if relevance is insufficient, adjust the filtering threshold or switch the retrieval strategy.

    Illustrative pseudocode:

    1. plan = planner.build(goal)
    2. while not done(plan):
    3. step = plan.next()
    4. result = skill.invoke(step)
    5. if not validate(result):
    6. plan.replan(step, reason=result.error)

    The value of the planning layer is turning exception handling from hard-coded branches into explainable plan adjustments. This matters especially for multi-turn interaction: when the user says “make it cheaper,” the planning layer only needs to modify the goal parameters and rerun the affected steps.

    5. Multi-Agent Collaboration and Protocol Decoupling

    Product relevance and information completeness are often not something a single model can handle well at the same time. A more robust approach is to let multiple agents each do their own job:

    • Information completion agent: fills in missing fields such as product titles, selling points, and attributes.
    • Relevance filtering agent: judges how well a product matches the scene tags, audience, and style.
    • Diversity control agent (optional): avoids homogeneous results.

    Agents communicate through a unified message format to avoid point-to-point coupling. Meanwhile, external tools are integrated through a standard model context protocol, so capabilities such as “product search” and “cache write” are registered and discovered in a plugin-like way. The direct benefit: adding an external capability only requires implementing a protocol adapter, with no changes to planning or skills.

    A shopping scene needs to feel current, which requires external knowledge. Retrieval-augmented generation handles three tasks here:

    1. Trending knowledge base query: obtain recent popular trends and campaign themes and inject them into the generation prompt.
    2. Link content extraction: extract key points from a reference page provided by the operator as generation constraints.
    3. Rework: rewrite the content into scene copy while preserving facts, reducing copyright and factual risk.

    Engineering practice should annotate sources and grade confidence for retrieval results, and enforce a hard constraint at generation time that nothing is output without a source, reducing the business impact of hallucination.

    7. Persistence and State: Supporting Multi-Turn and Enterprise Integration

    Multi-turn interaction requires session state, plan state, and intermediate artifacts to be recoverable. A three-part setup works well: session storage plus workflow state storage plus artifact storage. Sessions save the dialogue and context summaries; workflow state saves the current plan and completed steps; artifact storage saves the scene and product structures for direct consumption by the venue builder. For frequently read tags and retrieval results, a cache layer can reduce latency.

    8. Accelerating the Refactor with AI Coding: The Key to Shipping in Days

    An architectural leap sounds heavy, but AI-assisted coding tools can significantly compress the timeline. The key is to break the refactor into verifiable small steps:

    1. Define contracts first, then implement: define skills and protocols with unified interfaces, and let the tools batch-generate skeletons and unit tests.
    2. Migrate in parallel: peel skills out of the old flow one by one, running old and new side by side to compare outputs.
    3. Automate regression: build a regression set from historical real inputs and automatically compare key fields after each migration.
    4. Observability first: wire in logging and trace tracking before migration so problems are locatable.

    This makes refactoring not a “stop-the-world rewrite” but a gradual process that can be canaried and rolled back.

    9. Observability and Deployment

    An enterprise system must answer “why was this generation poor.” Recommended unified instrumentation: the plan tree for each planning run, input/output summaries for each skill, and the latency and status of each tool call. Combined with logging services and monitoring alerts, you can quickly identify whether quality dropped because retrieval returned nothing, filtering was too strict, or the generation prompt was missing. For deployment, use a container platform with multiple nodes and replicas, and scale skills and protocol adapters independently.

    10. Conclusion

    Moving from monolithic workflow orchestration to “modular skills + intelligent planning + standardized protocol interconnection” essentially delegates uncertainty to planning, reuse to skills, and differences to protocols. With AI-assisted coding tools, a team can complete the refactor and rollout in days and reduce the cost of future iterations to the granularity of “add a skill, change a plan.” For teams building enterprise-grade agents, this path balances speed, flexibility, and operability.