cd /news/ai-agents/your-ai-agent-doesn-t-need-every-doc… · home › topics › ai-agents › article
[ARTICLE · art-174752] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=↑ positive

Your AI Agent Doesn't Need Every Document: Build a Tiny Context Router in Node.js

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.

recommendation

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.

more in playbook: Designing agent systems
by read3 min views14 publishedNov 23, 2026

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.

Before adding a vector database or switching models, try a smaller design question:

Can you decide which information the next request actually needs?

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

Imagine a tiny shop with these two reference documents:

These are illustrative policies, not advice about actual consumer obligations. Our goal is to see which document belongs in the context of each question.

A simple baseline attaches both documents to every request. We will compare that approach with a router that selects the documents first.

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

Create a file named context-router.mjs and run it with Node.js:

const documents = {
  shipping: "Fictional store policy: delivery takes five business days.",
  returns: "Fictional store policy: request returns within seven days.",
};

const routes = [
  { name: "shipping", pattern: /\b(ship|shipping|delivery|tracking)\b/i },
  { name: "returns", pattern: /\b(return|returns|refund|exchange)\b/i },
];

function selectContext(question) {
  const selected = routes
    .filter((route) => route.pattern.test(question))
    .map((route) => route.name);

  // Unknown questions go to review, not a speculative answer.
  if (selected.length === 0) {
    return { selected: [], needsReview: true, context: "" };
  }

  return {
    selected,
    needsReview: false,
    context: selected
      .map((name) => `## ${name}\n${documents[name]}`)
      .join("\n\n"),
  };
}

const examples = [
  "When will my order ship?",
  "Can I return an item?",
  "Can I change my account email?",
];

for (const question of examples) {
  const result = selectContext(question);
  console.log({
    question,
    documents: result.selected,
    needsReview: result.needsReview,
    contextBytes: Buffer.byteLength(result.context),
  });
}

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

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

Selective gives you a place to make choices explicit:

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

And document selection is not access control. Enforce authorization at the data boundary before allowing retrieval, regardless of what a model or classifier requests.

Start with a table of expected document selections:

Question Expected source
When will my order ship? Shipping
Can I return an item? Returns
Can I return something that never arrived? Shipping + returns, or review
Can I change my email? Review

Then compare two variants on the same question set:

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

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

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

That gives you a concrete baseline for the harder parts of context engineering: changing policies, tool permissions, conversation summaries, and retrieval.

For the broader picture—including when to load instructions, summarize history, or use RAG—read the Context Engineering guide on Caminho Solo.

Further reading: Anthropic's context engineering guidance.

Editorial disclosure: AI-assisted drafting. This article is prepared for editorial review.

── more in #ai-agents 4 stories · sorted by recency
── more on @node.js 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/your-ai-agent-doesn-…] indexed:0 read:3min 2026-11-23 · —