# 7 AI agent design patterns, with code you can run

> Source: <https://dev.to/john_doe_1d1caee4c77f76a0/7-ai-agent-design-patterns-with-code-you-can-run-5819>
> Published: 2026-12-06 18:11:11+00:00

**Recommendation:** 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.
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>

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.

The 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.

``` js
import { DNotifier } from "@dnotifier-realtime/dnotifier";

const notifier = new DNotifier({
  appId: process.env.DNOTIFIER_APP_ID,
  secret: process.env.DNOTIFIER_SECRET, // server only, never in a browser bundle
  transport: "http",
  userId: "patterns-demo",
});
await notifier.connect();

// sendAI returns the model reply; this pulls out the text
const text = (res) => res?.data?.content ?? res?.content ?? "";

// a small agent that answers with one system prompt
const promptAgent = (name, system) =>
  DNotifier.defineAgent({
    name,
    async run(ctx) {
      const res = await ctx.sendAI({
        input: {
          messages: [
            { role: "system", content: system },
            { role: "user", content: JSON.stringify(ctx.input) },
          ],
        },
        label: name,
      });
      return { text: text(res) };
    },
  });
```

One agent's output is the next agent's input. Use it when the steps have a natural order: research, then draft, then edit.

``` js
const workflow = new DNotifier.Workflow({
  name: "draft-then-edit",
  observability: true,
  entry: async (ctx) => {
    const draft = await ctx.runAgent("writer", { input: ctx.input });
    const edited = await ctx.runAgent("editor", { input: { draft: draft.text } });
    return edited;
  },
}).registerAgents({
  writer: promptAgent("writer", "Write a short product update from these notes."),
  editor: promptAgent("editor", "Tighten this draft. Keep every fact."),
});

const run = await notifier.runWorkflow({ workflow, input: { notes: "..." } });
```

**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.

Independent work runs at the same time, then something combines it.

``` js
entry: async (ctx) => {
  const { results } = await ctx.runAgents([
    { name: "market", input: ctx.input },
    { name: "technical", input: ctx.input },
  ]);
  const [market, technical] = results;
  return ctx.runAgent("summary", { input: { market: market.text, technical: technical.text } });
},
```

**Watch out for:** agents that quietly depend on each other. If "technical" needs what "market" found, they aren't parallel.

A cheap first step decides which specialist handles the request.

``` js
entry: async (ctx) => {
  const route = await ctx.runAgent("router", { input: ctx.input });
  const intent = route.text.trim().toLowerCase(); // "billing", "technical" or "other"
  const agent = ["billing", "technical"].includes(intent) ? intent : "general";
  return ctx.runAgent(agent, { input: ctx.input });
},
```

The 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.

**Watch out for:** routers that grow into a 40-way classifier. If you have that many routes, you have a search problem.

One agent drafts, another checks against rules, and the draft goes back until it passes or you run out of attempts.

``` js
entry: async (ctx) => {
  let draft = await ctx.runAgent("writer", { input: ctx.input });
  for (let attempt = 1; attempt <= 3; attempt++) {
    const review = await ctx.runAgent("reviewer", { input: { draft: draft.text } });
    if (review.text.startsWith("PASS")) return draft;
    draft = await ctx.runAgent("writer", {
      input: { ...ctx.input, previous: draft.text, feedback: review.text },
    });
  }
  return { ...draft, needsHuman: true };
},
```

**Watch out for:** loops with no cap. Three attempts is plenty. After that, hand it to a person.

The run stops before a risky action and waits for a person.

``` js
const refundAgent = DNotifier.defineAgent({
  name: "refund",
  async run(ctx) {
    ctx.state.proposed = { orderId: ctx.input.orderId, amount: ctx.input.amount };
    const msg = await ctx.waitForMessage({ timeoutMs: 15 * 60_000 });
    const reply = msg.payload.toJSON();
    if (!reply?.ok) return { refunded: false, reason: "not approved" };
    // call your payment API here, with an idempotency key
    return { refunded: true };
  },
});
```

`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`:

```
await approver.send({
  senderId: "ops-dashboard",          // the approver client's own userId
  receiverId: "svc-refunds",          // the userId the waiting agent's client connected with
  data: { type: "approval", ok: true },
});
```

**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?".

When step four of five fails, retry from the last good step instead of the beginning.

``` js
const first = await notifier.runWorkflow({ workflow, input, sessionId: "order-1001" });

// later, after fixing whatever failed:
const retried = await notifier.runWorkflow({
  workflow,
  input,
  sessionId: "order-1001",
  mode: "retry",
});
```

**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.

The agent calls your functions. Permissions are declared, and your code does the work.

``` js
const lookup = notifier.tools.register({
  name: "orders.lookup",
  description: "Look up an order by id. Returns status and ETA.",
  inputSchema: {
    type: "object",
    properties: { orderId: { type: "string" } },
    required: ["orderId"],
  },
  execute: async ({ orderId }) => findOrder(orderId), // your own data access
});

const agent = DNotifier.defineAgent({
  name: "order-help",
  instructions: "Answer order questions. Use tools for facts.",
  provider: "open_ai",
  model: "gpt-4o",
  observability: true,
  tools: [lookup],
  permissions: { "orders.lookup": ["execute"] },
});

const result = await notifier.runAgent(agent, { input: "Where is order A-1042?", maxToolRounds: 4 });
```

**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.

Most 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.

Workflow 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)
