> 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-intent-router/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 intent router — copy into a single file or split by agent.

## Complete runnable example

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

// ── Agents ──────────────────────────────────────────────────────────

const intentAgent = DNotifier.defineAgent({
  name: "intent-agent",
  async run(ctx) {
    const text =
      typeof ctx.input === "string"
        ? ctx.input
        : ctx.input?.text ?? ctx.input?.question ?? "";

    if (!String(text).trim()) {
      throw new DNotifier.WorkflowError("intent-agent: empty input", {
        agentName: "intent-agent",
      });
    }

    const aiResponse = await ctx.sendAI({
      message: {
        useKnowledgeBase: false,
        messages: [
          {
            role: "system",
            content:
              'Classify the user message. Reply with JSON only: {"intent":"search"} for documentation/product lookup questions, or {"intent":"general"} for general chat.',
          },
          { role: "user", content: String(text) },
        ],
      },
      saveHistory: false,
      label: "Intent classification",
    });

    const content =
      aiResponse?.data?.content ??
      aiResponse?.content ??
      JSON.stringify(aiResponse);

    let parsed;
    try {
      parsed = JSON.parse(content);
    } catch {
      parsed = {
        intent: String(content).toLowerCase().includes("search")
          ? "search"
          : "general",
      };
    }

    const intent = parsed?.intent === "search" ? "search" : "general";
    ctx.state.lastIntent = intent;
    return { intent, raw: parsed };
  },
});

const generalAgent = DNotifier.defineAgent({
  name: "general-agent",
  async run(ctx) {
    const question =
      typeof ctx.input === "string"
        ? ctx.input
        : ctx.input?.question ?? JSON.stringify(ctx.input);

    const aiResponse = await ctx.sendAI({
      message: {
        useKnowledgeBase: false,
        messages: [
          { role: "system", content: "You are a helpful assistant. Answer concisely." },
          { role: "user", content: String(question) },
        ],
      },
      saveHistory: false,
      label: "General Q&A",
    });

    const answer =
      aiResponse?.data?.content ??
      aiResponse?.content ??
      JSON.stringify(aiResponse);

    ctx.state.generalAnswer = answer;
    return { answer };
  },
});

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

async function intentRouterEntry(ctx) {
  const intentResult = await ctx.runAgent("intent-agent");
  const intent = intentResult?.intent ?? "general";
  ctx.state.intent = intent;

  if (intent === "search") {
    const query =
      typeof ctx.input === "string"
        ? ctx.input
        : ctx.input?.query ?? ctx.input?.text ?? "";
    const hits = await ctx.search({
      query: String(query),
      limit: 10,
      minSimilarity: 0.3,
      filterbySource: "help-center",
      label: "Semantic search",
    });
    ctx.state.searchResults = hits;
    return { branch: "search", intent: intentResult, hits };
  }

  const enrichedInput = {
    question:
      typeof ctx.input === "string"
        ? ctx.input
        : ctx.input?.question ?? ctx.input,
    intentMeta: intentResult,
  };
  const generalResult = await ctx.runAgent("general-agent", {
    input: enrichedInput,
  });

  return { branch: "general", intent: intentResult, answer: generalResult };
}

const intentRouterWorkflow = new DNotifier.Workflow({
  name: "support-intent-router",
  description: "Classify intent then search or general chat",
  observability: true,
  entry: intentRouterEntry,
}).registerAgents({
  "intent-agent": intentAgent,
  "general-agent": generalAgent,
});

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

const USER_ID = "workflow-runner";

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

await notifier.connect();

const searchRun = await notifier.runWorkflow({
  workflow: intentRouterWorkflow,
  input: "How do refunds work?",
});
console.log("Search branch:", searchRun.result?.branch, searchRun.executionId);

const generalRun = await notifier.runWorkflow({
  workflow: intentRouterWorkflow,
  input: "What is your name?",
});
console.log("General branch:", generalRun.result?.branch, generalRun.executionId);
```

## Index sample docs (optional)

```js
await notifier.addDocument({
  senderId: USER_ID,
  recordId: "faq-refund",
  content: "Refunds are processed within 5 business days.",
  metadata: { source: "help-center" },
});
```

## Learn more

* [**Define an agent**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/define-agent/javascript-typescript.md)
* [**RAG bot example**](https://dnotifier.gitbook.io/product-docs/ai/example-rag-bot/javascript-typescript.md)
