{"slug": "your-ai-agent-doesn-t-need-every-document-build-a-tiny-context-router-in-node-js", "title": "Your AI Agent Doesn't Need Every Document: Build a Tiny Context Router in Node.js", "summary": "A developer published a dependency-free Node.js context router that uses regex rules to select which reference documents are attached to an agent's prompt, falling back to a needsReview flag when a question matches no route. The example compares always attaching every document against selective loading, printing context bytes rather than tokens or accuracy, and warns that document selection is not access control and that regex rules are not a general-purpose intent classifier.", "body_md": "A support agent answers a delivery question. Its prompt includes shipping rules, return policies, billing instructions, old product notes, and a long conversation history. Everything is technically available, but only one document may matter to the next answer.\n\nBefore adding a vector database or switching models, try a smaller design question:\n\n**Can you decide which information the next request actually needs?**\n\nThis is one piece of *context engineering*: choosing what gets passed to a model, when, and why. We'll build a minimal, dependency-free router that selects documents before an agent ever sees them.\n\nImagine a tiny shop with these two reference documents:\n\nThese are illustrative policies, not advice about actual consumer obligations. Our goal is to see which document belongs in the context of each question.\n\nA simple baseline attaches both documents to every request. We will compare that approach with a router that selects the documents first.\n\nFor two short files, the difference is negligible. For a larger collection of manuals, policies, and tool instructions, controlling what is loaded becomes an architectural decision.\n\nCreate a file named `context-router.mjs` and run it with Node.js:\n\n``` js\nconst documents = {\n  shipping: \"Fictional store policy: delivery takes five business days.\",\n  returns: \"Fictional store policy: request returns within seven days.\",\n};\n\nconst routes = [\n  { name: \"shipping\", pattern: /\\b(ship|shipping|delivery|tracking)\\b/i },\n  { name: \"returns\", pattern: /\\b(return|returns|refund|exchange)\\b/i },\n];\n\nfunction selectContext(question) {\n  const selected = routes\n    .filter((route) => route.pattern.test(question))\n    .map((route) => route.name);\n\n  // Unknown questions go to review, not a speculative answer.\n  if (selected.length === 0) {\n    return { selected: [], needsReview: true, context: \"\" };\n  }\n\n  return {\n    selected,\n    needsReview: false,\n    context: selected\n      .map((name) => `## ${name}\\n${documents[name]}`)\n      .join(\"\\n\\n\"),\n  };\n}\n\nconst examples = [\n  \"When will my order ship?\",\n  \"Can I return an item?\",\n  \"Can I change my account email?\",\n];\n\nfor (const question of examples) {\n  const result = selectContext(question);\n  console.log({\n    question,\n    documents: result.selected,\n    needsReview: result.needsReview,\n    contextBytes: Buffer.byteLength(result.context),\n  });\n}\n```\n\nThe router can choose one policy, both policies if both patterns match, or neither when it cannot classify a question. It only builds the *input context*; it does not authorize a refund, look up an order, or generate an AI answer.\n\nNotice the deliberate fallback: an unfamiliar question such as changing an account email produces `needsReview: true`. In a real service that could lead to clarification, another controlled retrieval step, or human escalation.\n\nSelective loading gives you a place to make choices explicit:\n\nRegex rules are enough for this small demonstration, not a general-purpose intent classifier. A production router also needs evaluation cases for ambiguous phrasing, multilingual inputs, and questions that span multiple subjects.\n\nAnd **document selection is not access control**. Enforce authorization at the data boundary before allowing retrieval, regardless of what a model or classifier requests.\n\nStart with a table of expected document selections:\n\n| Question | Expected source | \n|---|---|\n| When will my order ship? | Shipping | \n| Can I return an item? | Returns | \n| Can I return something that never arrived? | Shipping + returns, or review | \n| Can I change my email? | Review | \n\nThen compare two variants on the same question set:\n\nLog the selected sources, routing mistakes, response correctness, and tokens sent to the model if you later connect one. Our Node.js example prints **bytes of context**, not tokens, accuracy scores, or monetary savings. Smaller input alone does not prove a better answer.\n\nIf you expand beyond two documents, an index or retrieval service may help. It should solve a measured retrieval problem rather than become the starting point by default.\n\nUse this router with a small collection of *non-sensitive* test documents. Write ten realistic questions, including ambiguous ones. Check source selection manually before connecting a language model or an external tool.\n\nThat gives you a concrete baseline for the harder parts of context engineering: changing policies, tool permissions, conversation summaries, and retrieval.\n\nFor the broader picture—including when to load instructions, summarize history, or use RAG—read [the Context Engineering guide on Caminho Solo](https://caminhosolo.com.br/en/2026/04/context-engineering-agentes-ia-solo-builders/?utm_source=devto&utm_medium=referral&utm_campaign=context-router).\n\n**Further reading:** [Anthropic's context engineering guidance](https://www.anthropic.com/research/effective-context-engineering-for-ai-agents).\n\n*Editorial disclosure: AI-assisted drafting. This article is prepared for editorial review.*", "url": "https://wpnews.pro/news/your-ai-agent-doesn-t-need-every-document-build-a-tiny-context-router-in-node-js", "canonical_source": "https://dev.to/caminhosolo/your-ai-agent-doesnt-need-every-document-build-a-tiny-context-router-in-nodejs-1cch", "published_at": "2026-11-23 14:35:48+00:00", "updated_at": "2026-11-23 14:44:07.295113+00:00", "lang": "en", "topics": ["ai-agents", "large-language-models", "ai-tools", "developer-tools"], "entities": ["Node.js"], "also_reported_by": [], "takeaway": "Route questions to a small set of documents with explicit rules and send unmatched questions to review instead of guessing, but enforce authorization at the data boundary since document selection is not access control.", "recommendation": {"advice": "Add a rule-based context router that selects only the documents a request needs and flags unmatched questions for review, then measure routing mistakes and context size before trusting it.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/your-ai-agent-doesn-t-need-every-document-build-a-tiny-context-router-in-node-js", "markdown": "https://wpnews.pro/news/your-ai-agent-doesn-t-need-every-document-build-a-tiny-context-router-in-node-js.md", "text": "https://wpnews.pro/news/your-ai-agent-doesn-t-need-every-document-build-a-tiny-context-router-in-node-js.txt", "jsonld": "https://wpnews.pro/news/your-ai-agent-doesn-t-need-every-document-build-a-tiny-context-router-in-node-js.jsonld"}}