> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/example-multi-agent/javascript-typescript.md). Agents can also search and read this documentation through its [MCP server](https://dnotifier.gitbook.io/product-docs/~gitbook/mcp).

# JavaScript / TypeScript

Self-contained **blog article writer** workflow with three sequential agents.

## Complete runnable example

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

function extractAiContent(aiResponse) {
  return (
    aiResponse?.data?.content ??
    aiResponse?.content ??
    (typeof aiResponse === "string" ? aiResponse : JSON.stringify(aiResponse))
  );
}

// ── Agent 1: Content creator ────────────────────────────────────────

const contentCreatorAgent = DNotifier.defineAgent({
  name: "content-creator",
  async run(ctx) {
    const brief = ctx.input;
    const keywords = Array.isArray(brief?.keywords) ? brief.keywords : [];

    if (!brief?.topic) {
      throw new DNotifier.WorkflowError("content-creator: topic is required", {
        agentName: "content-creator",
      });
    }

    const aiResponse = await ctx.sendAI({
      message: {
        useKnowledgeBase: false,
        messages: [
          {
            role: "system",
            content: `You are an expert blog writer. Write a complete first-draft article in markdown.
Requirements:
- Target audience: ${brief?.audience ?? "general"}
- Tone: ${brief?.tone ?? "neutral"}
- Approximate length: ${brief?.wordCount ?? 800} words
- Include an engaging introduction, clear H2/H3 headings, and a conclusion.
Return only the article body in markdown.`,
          },
          {
            role: "user",
            content: `Topic: ${brief.topic}${
              keywords.length ? `\nSuggested keywords: ${keywords.join(", ")}` : ""
            }`,
          },
        ],
      },
      saveHistory: false,
      label: "Blog content creation",
    });

    const content = extractAiContent(aiResponse);
    ctx.state.draft = content;
    return { content, stage: "content_creation" };
  },
});

// ── Agent 2: Clarity editor ─────────────────────────────────────────

const clarityEditorAgent = DNotifier.defineAgent({
  name: "clarity-editor",
  async run(ctx) {
    const draft = ctx.input?.content ?? ctx.state.draft;
    if (!String(draft ?? "").trim()) {
      throw new DNotifier.WorkflowError("clarity-editor: no draft to refine", {
        agentName: "clarity-editor",
      });
    }

    const aiResponse = await ctx.sendAI({
      message: {
        useKnowledgeBase: false,
        messages: [
          {
            role: "system",
            content: `You are an editorial clarity specialist. Improve the draft for readability and flow.
Preserve facts and markdown formatting. Return only the revised article.`,
          },
          { role: "user", content: String(draft) },
        ],
      },
      saveHistory: false,
      label: "Blog clarity editing",
    });

    const content = extractAiContent(aiResponse);
    ctx.state.refined = content;
    return { content, stage: "clarity" };
  },
});

// ── Agent 3: SEO optimizer ──────────────────────────────────────────

const seoOptimizerAgent = DNotifier.defineAgent({
  name: "seo-optimizer",
  async run(ctx) {
    const article = ctx.input?.content ?? ctx.state.refined;
    const topic = ctx.input?.topic ?? ctx.state.blogBrief?.topic ?? "";
    const keywords = ctx.input?.keywords ?? ctx.state.blogBrief?.keywords ?? [];

    if (!String(article ?? "").trim()) {
      throw new DNotifier.WorkflowError("seo-optimizer: no article to optimize", {
        agentName: "seo-optimizer",
      });
    }

    const aiResponse = await ctx.sendAI({
      message: {
        useKnowledgeBase: false,
        messages: [
          {
            role: "system",
            content: `You are an SEO content optimizer. Return JSON only:
{
  "content": "optimized markdown article",
  "metaTitle": "string",
  "metaDescription": "string",
  "slug": "string",
  "keywords": ["string"]
}`,
          },
          {
            role: "user",
            content: `Topic: ${topic}\nTarget keywords: ${
              keywords.length ? keywords.join(", ") : "derive from topic"
            }\nArticle: ${article}`,
          },
        ],
      },
      saveHistory: false,
      label: "Blog SEO optimization",
    });

    const raw = extractAiContent(aiResponse);
    let parsed;
    try {
      parsed = JSON.parse(raw);
    } catch {
      parsed = {
        content: raw,
        metaTitle: topic,
        metaDescription: "",
        slug: topic.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, ""),
        keywords,
      };
    }

    const content = parsed?.content ?? raw;
    ctx.state.final = content;
    return {
      content,
      metaTitle: parsed?.metaTitle ?? topic,
      metaDescription: parsed?.metaDescription ?? "",
      slug: parsed?.slug ?? "",
      keywords: Array.isArray(parsed?.keywords) ? parsed.keywords : keywords,
      stage: "seo",
    };
  },
});

// ── Workflow entry ──────────────────────────────────────────────────

async function blogArticleEntry(ctx) {
  const brief = ctx.input;
  ctx.state.blogBrief = brief;

  const creation = await ctx.runAgent("content-creator");
  ctx.state.stage = "content_creation";

  const clarity = await ctx.runAgent("clarity-editor", {
    input: { content: creation.content },
  });
  ctx.state.stage = "clarity";

  const seo = await ctx.runAgent("seo-optimizer", {
    input: {
      content: clarity.content,
      topic: brief.topic,
      keywords: brief.keywords,
    },
  });
  ctx.state.stage = "seo";

  return {
    article: seo.content,
    seo: {
      metaTitle: seo.metaTitle,
      metaDescription: seo.metaDescription,
      slug: seo.slug,
      keywords: seo.keywords,
    },
    stages: {
      contentCreation: creation.content,
      clarity: clarity.content,
      seo: seo.content,
    },
  };
}

const blogArticleWorkflow = new DNotifier.Workflow({
  name: "blog-article-writer",
  description: "Three-step blog pipeline: create, clarify, SEO",
  observability: true,
  entry: blogArticleEntry,
}).registerAgents({
  "content-creator": contentCreatorAgent,
  "clarity-editor": clarityEditorAgent,
  "seo-optimizer": seoOptimizerAgent,
});

// ── Runner ──────────────────────────────────────────────────────────

const USER_ID = "blog-pipeline";

const notifier = new DNotifier({
  appId: process.env.DNOTIFIER_APP_ID,
  secret: process.env.DNOTIFIER_SECRET,
  transport: "http",
  userId: USER_ID,
  onConnected: () => console.log("Connected"),
  onMessage: () => {},
  onDisconnected: () => {},
});

await notifier.connect();

const run = await notifier.runWorkflow({
  workflow: blogArticleWorkflow,
  input: {
    topic: "How to build deterministic AI workflows with DNotifier",
    keywords: ["workflow", "sdk", "observability"],
    audience: "software developers",
    tone: "professional",
    wordCount: 900,
  },
});

console.log("Execution:", run.executionId);
console.log("Meta title:", run.result?.seo?.metaTitle);
console.log("Article preview:", run.result?.article?.slice(0, 300));
```

## Learn more

* [**Workflow observability**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/observability.md)
* [**WorkflowContext reference**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/workflow-context.md)
