{"slug": "7-ai-agent-design-patterns-with-code-you-can-run", "title": "7 AI agent design patterns, with code you can run", "summary": "A developer published a hands-on guide to seven recurring multi-agent design patterns, including sequential pipelines, parallel fan-out with a combiner, routing, and capped draft-review loops, each illustrated with runnable DNotifier JavaScript SDK code. The examples emphasize failure modes such as overlong chains, hidden dependencies between supposedly parallel agents, and unbounded retry loops that should escalate to a human after three attempts.", "body_md": "Most multi-agent systems are built from a handful of patterns. Once you can name them, it gets much easier to look at a messy agent and say what it should be. Here are the seven I see most often, each with a small example.\n\nThe code uses the DNotifier JavaScript SDK because that's what I work with, but the shapes carry over to LangGraph, CrewAI or plain functions. Every example runs inside your own Node app.\n\n``` js\nimport { DNotifier } from \"@dnotifier-realtime/dnotifier\";\n\nconst notifier = new DNotifier({\n  appId: process.env.DNOTIFIER_APP_ID,\n  secret: process.env.DNOTIFIER_SECRET, // server only, never in a browser bundle\n  transport: \"http\",\n  userId: \"patterns-demo\",\n});\nawait notifier.connect();\n\n// sendAI returns the model reply; this pulls out the text\nconst text = (res) => res?.data?.content ?? res?.content ?? \"\";\n\n// a small agent that answers with one system prompt\nconst promptAgent = (name, system) =>\n  DNotifier.defineAgent({\n    name,\n    async run(ctx) {\n      const res = await ctx.sendAI({\n        input: {\n          messages: [\n            { role: \"system\", content: system },\n            { role: \"user\", content: JSON.stringify(ctx.input) },\n          ],\n        },\n        label: name,\n      });\n      return { text: text(res) };\n    },\n  });\n```\n\nOne agent's output is the next agent's input. Use it when the steps have a natural order: research, then draft, then edit.\n\n``` js\nconst workflow = new DNotifier.Workflow({\n  name: \"draft-then-edit\",\n  observability: true,\n  entry: async (ctx) => {\n    const draft = await ctx.runAgent(\"writer\", { input: ctx.input });\n    const edited = await ctx.runAgent(\"editor\", { input: { draft: draft.text } });\n    return edited;\n  },\n}).registerAgents({\n  writer: promptAgent(\"writer\", \"Write a short product update from these notes.\"),\n  editor: promptAgent(\"editor\", \"Tighten this draft. Keep every fact.\"),\n});\n\nconst run = await notifier.runWorkflow({ workflow, input: { notes: \"...\" } });\n```\n\n**Watch out for:** long chains. Every step adds latency and another place to fail. If a step only reformats text, it probably isn't an agent.\n\nIndependent work runs at the same time, then something combines it.\n\n``` js\nentry: async (ctx) => {\n  const { results } = await ctx.runAgents([\n    { name: \"market\", input: ctx.input },\n    { name: \"technical\", input: ctx.input },\n  ]);\n  const [market, technical] = results;\n  return ctx.runAgent(\"summary\", { input: { market: market.text, technical: technical.text } });\n},\n```\n\n**Watch out for:** agents that quietly depend on each other. If \"technical\" needs what \"market\" found, they aren't parallel.\n\nA cheap first step decides which specialist handles the request.\n\n``` js\nentry: async (ctx) => {\n  const route = await ctx.runAgent(\"router\", { input: ctx.input });\n  const intent = route.text.trim().toLowerCase(); // \"billing\", \"technical\" or \"other\"\n  const agent = [\"billing\", \"technical\"].includes(intent) ? intent : \"general\";\n  return ctx.runAgent(agent, { input: ctx.input });\n},\n```\n\nThe router's prompt should ask for one word from a fixed list, and the code should never trust it blindly: anything unexpected goes to the general agent.\n\n**Watch out for:** routers that grow into a 40-way classifier. If you have that many routes, you have a search problem.\n\nOne agent drafts, another checks against rules, and the draft goes back until it passes or you run out of attempts.\n\n``` js\nentry: async (ctx) => {\n  let draft = await ctx.runAgent(\"writer\", { input: ctx.input });\n  for (let attempt = 1; attempt <= 3; attempt++) {\n    const review = await ctx.runAgent(\"reviewer\", { input: { draft: draft.text } });\n    if (review.text.startsWith(\"PASS\")) return draft;\n    draft = await ctx.runAgent(\"writer\", {\n      input: { ...ctx.input, previous: draft.text, feedback: review.text },\n    });\n  }\n  return { ...draft, needsHuman: true };\n},\n```\n\n**Watch out for:** loops with no cap. Three attempts is plenty. After that, hand it to a person.\n\nThe run stops before a risky action and waits for a person.\n\n``` js\nconst refundAgent = DNotifier.defineAgent({\n  name: \"refund\",\n  async run(ctx) {\n    ctx.state.proposed = { orderId: ctx.input.orderId, amount: ctx.input.amount };\n    const msg = await ctx.waitForMessage({ timeoutMs: 15 * 60_000 });\n    const reply = msg.payload.toJSON();\n    if (!reply?.ok) return { refunded: false, reason: \"not approved\" };\n    // call your payment API here, with an idempotency key\n    return { refunded: true };\n  },\n});\n```\n\n`waitForMessage` waits for the next realtime message to this agent's client, so the agent has to run on a client connected with `transport: \"ws\"` (in Node, pass the `ws` package as `WebSocketImpl`). The approver's app unblocks it with a normal message to that client's `userId`:\n\n```\nawait approver.send({\n  senderId: \"ops-dashboard\",          // the approver client's own userId\n  receiverId: \"svc-refunds\",          // the userId the waiting agent's client connected with\n  data: { type: \"approval\", ok: true },\n});\n```\n\n**Watch out for:** approvals with no timeout, and approval messages that don't say exactly what's being approved. Show the amount and the order, not \"Approve?\".\n\nWhen step four of five fails, retry from the last good step instead of the beginning.\n\n``` js\nconst first = await notifier.runWorkflow({ workflow, input, sessionId: \"order-1001\" });\n\n// later, after fixing whatever failed:\nconst retried = await notifier.runWorkflow({\n  workflow,\n  input,\n  sessionId: \"order-1001\",\n  mode: \"retry\",\n});\n```\n\n**Watch out for:** side effects. A checkpoint tells you a step finished, not whether the email it sent went out twice. Give anything that sends, pays or deletes an idempotency key.\n\nThe agent calls your functions. Permissions are declared, and your code does the work.\n\n``` js\nconst lookup = notifier.tools.register({\n  name: \"orders.lookup\",\n  description: \"Look up an order by id. Returns status and ETA.\",\n  inputSchema: {\n    type: \"object\",\n    properties: { orderId: { type: \"string\" } },\n    required: [\"orderId\"],\n  },\n  execute: async ({ orderId }) => findOrder(orderId), // your own data access\n});\n\nconst agent = DNotifier.defineAgent({\n  name: \"order-help\",\n  instructions: \"Answer order questions. Use tools for facts.\",\n  provider: \"open_ai\",\n  model: \"gpt-4o\",\n  observability: true,\n  tools: [lookup],\n  permissions: { \"orders.lookup\": [\"execute\"] },\n});\n\nconst result = await notifier.runAgent(agent, { input: \"Where is order A-1042?\", maxToolRounds: 4 });\n```\n\n**Watch out for:** tools that do too much. \"orders.lookup\" and \"orders.refund\" should be two tools with two permissions, not one tool with a mode flag.\n\nMost real systems combine two or three: a router in front, a sequential chain behind it, a reviewer loop on the risky output and an approval step before anything irreversible. Start with the simplest pattern that works and add the next one when a real failure asks for it.\n\nWorkflow docs, with the same patterns in Python and Dart: [https://dnotifier.gitbook.io/product-docs/build-agents/workflows?utm_source=devto&utm_medium=social&utm_campaign=dec26-d06](https://dnotifier.gitbook.io/product-docs/build-agents/workflows?utm_source=devto&utm_medium=social&utm_campaign=dec26-d06)", "url": "https://wpnews.pro/news/7-ai-agent-design-patterns-with-code-you-can-run", "canonical_source": "https://dev.to/john_doe_1d1caee4c77f76a0/7-ai-agent-design-patterns-with-code-you-can-run-5819", "published_at": "2026-12-06 18:11:11+00:00", "updated_at": "2026-12-06 18:14:29.067484+00:00", "lang": "en", "topics": ["ai-agents", "artificial-intelligence", "large-language-models", "ai-tools"], "entities": ["DNotifier", "LangGraph", "CrewAI", "Node.js"], "also_reported_by": [], "takeaway": "Cap draft-review loops at about three attempts and route anything unexpected to a general agent rather than trusting a router's output blindly.", "recommendation": {"advice": "Cap agent retry loops at three attempts before escalating to a human, and validate router output against a fixed list so unexpected values fall back to a general agent.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/7-ai-agent-design-patterns-with-code-you-can-run", "markdown": "https://wpnews.pro/news/7-ai-agent-design-patterns-with-code-you-can-run.md", "text": "https://wpnews.pro/news/7-ai-agent-design-patterns-with-code-you-can-run.txt", "jsonld": "https://wpnews.pro/news/7-ai-agent-design-patterns-with-code-you-can-run.jsonld"}}