DEV Community

Caminho Solo
Caminho Solo

Posted on AI-assisted

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

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.

Start with two fictional policies

Imagine a tiny shop with these two reference documents:

  • Shipping: Orders have a five-business-day delivery rule.
  • Returns: A return request must be made within seven days.

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.

Build the smallest router that could work

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),
  });
}
Enter fullscreen mode Exit fullscreen mode

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.

Why not send everything every time?

Selective loading gives you a place to make choices explicit:

  1. Relevance: Which document answers this kind of question?
  2. Freshness: Is it the current version of the policy?
  3. Permission: Is this user or workflow allowed to receive it?
  4. Traceability: Which sources were selected for this answer?
  5. Fallback: What happens when routing is uncertain?

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.

Measure the right thing

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:

  • Baseline: provide both fictional policies.
  • Routed: provide only the selected policies, escalating unknown cases.

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.

The next step for a solo builder

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.

Top comments (0)