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

> Source: <https://dev.to/caminhosolo/your-ai-agent-doesnt-need-every-document-build-a-tiny-context-router-in-nodejs-1cch>
> Published: 2026-11-23 14:35:48+00:00

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

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:

``` 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 loading 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](https://caminhosolo.com.br/en/2026/04/context-engineering-agentes-ia-solo-builders/?utm_source=devto&utm_medium=referral&utm_campaign=context-router).

**Further reading:** [Anthropic's context engineering guidance](https://www.anthropic.com/research/effective-context-engineering-for-ai-agents).

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