Agent Design Patterns and Multi-Agent Development in Practice

    This article explains why production-grade agents need a runtime framework rather than prompt chaining alone, and how to build one. It covers the four core capabilities of a mature runtime, a neutral approach to environment setup and model access, and how to map business logic onto a graph of nodes, edges, and state. It then walks through conditional routing, nine agent design patterns, three multi-agent collaboration topologies, a content generation case study, and a production readiness checklist. Readers will learn how to design control flow and state so a prototype can move reliably into production.

    1. Why You Need a Runtime Framework, Not Just Prompt Orchestration

    Early LLM applications mostly stayed at the level of chained calls: one input, one output. As business complexity grows, developers quickly hit three walls: flows cannot loop back, state cannot persist, and failures cannot be recovered. The value of a production-grade agent runtime framework is that it turns these three concerns into first-class, programmable elements.

    A mature runtime typically provides four foundational capabilities:

    1. Graph-based flow orchestration that allows cycles between nodes, supporting repeated “think-act-observe” iterations.
    2. An explicit state object that converges conversation history, intermediate results, and tool return values into a serializable structure.
    3. Persistence and checkpoint recovery, so long-running tasks can continue after a process restart.
    4. Observability, making every branch decision and every tool call traceable.

    It is worth stressing that such frameworks do not replace the LLM, nor do they change the fundamentals of prompt engineering. What they change is ownership of the control flow: the next step is decided explicitly by code rather than implicitly by the model. This is the dividing line between an agent demo and an agent in production.

    2. Environment Setup and Neutral Model Access

    The goal of environment setup is not to pile up dependencies, but to establish a reproducible engineering baseline. A recommended layering:

    1. Language and virtual environment: use a mainstream scripting language with a lightweight environment manager, pin dependency versions, and avoid the “runs on my machine, fails on yours” problem.
    2. Tensor computation and inference dependencies: decide whether to install a deep learning framework based on your hardware. If you only call a remote model service, you can omit the local inference stack entirely and greatly reduce deployment complexity.
    3. Development tools: any AI coding tool with debugging, version control, and terminal support will do; what matters is the breakpoint debugging and log inspection experience.
    4. Model access: wrap authentication, retries, rate limiting, and usage accounting behind a unified model gateway. If you use Baidu AI Cloud’s LLM services, keep access credentials in environment variables or a key management service instead of hardcoding them.

    Illustrative code (pseudocode, structure only):

    1. # Unified model call wrapper: hides differences between providers
    2. def call_model(messages, tools=None, temperature=0.2):
    3. payload = build_payload(messages, tools, temperature)
    4. return gateway.invoke(payload) # handles auth, retries, rate limiting internally

    3. Programming Basics: Mapping Business Logic to a Graph

    A graph has three elements: nodes, edges, and state. Nodes carry computation or tool calls, edges determine transitions, and state is passed between nodes and progressively reduced. A minimal working structure:

    1. from typing import TypedDict, Annotated
    2. import operator
    3. class S(TypedDict):
    4. query: str
    5. notes: Annotated[list, operator.add] # reducer strategy: append instead of overwrite
    6. answer: str
    7. g = Graph()
    8. g.add_node("plan", plan_fn)
    9. g.add_node("act", act_fn)
    10. g.add_node("synth", synth_fn)
    11. g.add_edge("plan", "act")
    12. g.add_conditional_edges("act", route_fn, {"loop": "plan", "end": "synth"})
    13. g.set_entry_point("plan")
    14. app = g.compile(checkpointer=memory_saver)

    The thing beginners should pay most attention to is Annotated and the reducer function: it determines whether concurrent branches writing to the same field overwrite or merge. Ignoring this is the most common root cause of “lost results” in later multi-agent collaboration.

    4. Conditional Branching: Making Control Flow Truly Controllable

    The way to write a conditional branch is to decouple the decision function from state: the routing function only reads state and returns the name of the next node, without performing side effects directly. This design brings three benefits: branch logic can be unit tested; adding a branch requires no changes inside nodes; and when something goes wrong, the decision path can be reproduced from state alone.

    Engineering recommendations:

    • Keep routing functions pure; never call external APIs inside them.
    • Set a maximum iteration count for each branch to prevent a model that keeps second-guessing itself from looping forever.
    • Prepare a fallback answer for the “catch-all branch” instead of throwing an exception.

    5. Nine Design Patterns: Abstraction and Implementation Notes

    Pattern 1: ReAct-style action loop. The model emits “reasoning + action”, the runtime executes the tool and feeds the observation back, looping until convergence. What matters is the quality of tool descriptions and the truncation strategy for observations; overly long observations quickly eat up the context budget.

    Pattern 2: Memory systems. Short-term memory holds the current session window; long-term memory exists as vector retrieval or structured summaries. Writes need deduplication and importance scoring, and reads need reranking by relevance; otherwise the more memory you have, the more noise you get.

    Pattern 3: Planning and execution. Produce an explicit plan first (a step list or task graph), then execute step by step while allowing replanning. It suits tasks with many steps and strong dependencies; for simple tasks it is a burden, so choose based on complexity.

    Pattern 4: Context engineering. Context is a finite budget that must be prioritized across the system prompt, retrieved snippets, history summaries, and tool outputs. Practical points include segmented summarization, loading on demand, and annotating conflicting information with its source and timestamp.

    Patterns 5-9 in engineering terms. The remaining patterns generally revolve around routing and dispatch, parallel fan-out and aggregation, human-in-the-loop approval, and evaluation and reflection. The common rule: every pattern you add introduces a new class of state fields and a set of failure paths, so you must add timeouts, retries, and auditing alongside them.

    6. Three Multi-Agent Collaboration Topologies

    1. Lead agent driven (orchestrator-executor): the lead agent decomposes the task and dispatches it; sub-agents return structured results. The advantage is strong controllability and easy rate limiting; the difficulty is that the lead agent easily becomes a context bottleneck.
    2. Shared space driven (blackboard model): multiple agents read and write the same shared state, with field namespaces isolating write scopes. It suits parallel exploration, but you must design a conflict merge strategy.
    3. Pipeline/swarm collaboration: agents are chained by role, with the previous output serving as the next input. It is simple to implement, but errors amplify at each stage, so you need validation nodes between segments.

    Selection advice: prefer the lead agent topology when task boundaries are clear; choose the shared space when you need multiple perspectives generating candidate solutions in parallel; choose the pipeline when the flow is stable and roles are fixed.

    7. Case Study: Content Generation Balancing Long-Term and Short-Term Goals

    Suppose the business goal is to “satisfy the quarterly brand tone (long-term) while fitting the day’s trending topics (short-term)”. The graph can be designed as: a goal parsing node that produces long-term constraints and short-term variables; a retrieval node that fetches short-term material; parallel generation nodes that produce multiple candidates; a review node that scores them against the constraints; and a revision node that iterates once before converging on the output. The state explicitly holds four fields, long_term_constraints, short_term_signals, candidates, and scores, which makes replay and tuning easy.

    8. Production Readiness Checklist

    • Persistence: use a checkpoint mechanism to save state at every step, supporting human intervention and task recovery.
    • Observability: record node latency, token consumption, and tool success rate; connect to logging services and monitoring alerts.
    • Cost governance: set budget caps on model calls and a tiered model strategy, using small models for simple nodes.
    • Security: apply parameter whitelists and permission checks to tool calls, treat external content as untrusted input, and guard against prompt injection.
    • Evaluation: build an offline test set and regression baseline, and run the regression for any prompt or structural change.

    9. Conclusion

    The hard part of agent development has shifted from “can it call a model” to “how to design control flow and state”. Master the five cornerstones of graph orchestration, conditional branching, memory, planning, and context engineering, then choose a collaboration topology based on business complexity, and combine them with persistence, observability, and an evaluation system to move a prototype steadily into production. If you need elastic compute, managed deployment, and unified operations, you can build a complete pipeline on general capabilities such as Baidu AI Cloud’s container platform, object storage, and monitoring and alerting, letting your team focus on pattern design and business refinement.