Why the smartest agent systems are classifying tasks at runtime and injecting only the context each one actually needs.


Every prompt engineer hits the same wall eventually. You're building a general-purpose agent — maybe a coding assistant, maybe a customer-support bot — and it needs to handle everything from "rename this variable" to "refactor the entire authentication module to support OAuth2 with PKCE." The easy task needs zero examples. The hard task needs schemas, worked examples, domain hints, maybe even a step-by-step reasoning template. So what do you do?

You stuff everything into the prompt. Every request gets the full library of scaffolding — four thousand tokens of SQL examples, refactoring templates, API schemas, and error-handling patterns — because some request might need them. Most requests don't. The model wades through irrelevant context, sometimes getting nudged toward wrong answers by examples that were never meant for the current task. Your token bill balloons. Your latency creeps up. And the hardest tasks still don't get enough scaffolding because you're afraid of making the prompt even longer.

This is the static-prompt trap, and it's one of the most wasteful anti-patterns in production agent systems today. A new pattern from the Agent Patterns Catalog — Dynamic Scaffolding — offers a way out. The idea is deceptively simple: instead of loading every scaffold for every request, classify the task at runtime and inject only what that specific task type needs. Easy tasks get a lean prompt. Hard tasks get the full treatment. Nothing is wasted, and nothing is under-served.

The Problem: One Prompt to Rule Them All (Badly)

Let's make the problem concrete. You're running a coding assistant that handles four task types:

  1. Rename operations — trivial, zero-shot is fine
  2. SQL generation — needs schema definitions and dialect-specific examples
  3. Code refactoring — needs exemplars showing before/after patterns
  4. Bug diagnosis — needs heuristics, common failure patterns, debugging strategies

A static prompt carries all four scaffolds on every request. For a rename, you're burning 3,000+ tokens on scaffolding the model doesn't need. For a complex refactor, you're giving it SQL examples that may actively confuse its output format. The model's attention is a finite resource, and irrelevant context competes with relevant context for that attention.

Research from the SkillsInjector team at Nanjing University and Shanghai AI Lab (arXiv 2605.29794) quantified this effect: as you inject more skills into an agent's context, performance degrades rather than improving. They call it "attention dispersion" — the model spreads its focus across too many irrelevant instructions and starts making worse decisions. Their all-injection baseline on tau2-bench collapsed as the candidate skill pool grew, while an adaptive approach stayed stable.

This isn't a minor optimization. It's a fundamental architectural problem with how most production agents are built today.

Dynamic Scaffolding: The Pattern

The Agent Patterns Catalog defines Dynamic Scaffolding (also called Adaptive Prompting or Just-in-Time Context) as follows:

Maintain a library of scaffolds (few-shot examples, schemas, hints) keyed by task type or feature. At runtime, classify the task and inject the matching scaffolds. Audit which scaffolds fired per request.

The pattern has three core components:

1. The Scaffold Library

This is your organized collection of context injections, each keyed to a task type. Think of it as a well-indexed reference shelf rather than a dump truck. Each scaffold might contain:

  • Few-shot examples: Worked demonstrations of the input-output pattern you want
  • Output schemas: JSON schemas, regex patterns, or format constraints
  • Domain hints: Rules of thumb, common pitfalls, terminology definitions
  • Reasoning templates: Step-by-step structures for complex multi-step tasks

The key principle is specificity. A scaffold for SQL generation should contain nothing about refactoring. A scaffold for bug diagnosis should contain nothing about SQL. Each scaffold is laser-focused on one task type.

2. The Lightweight Classifier

Before the main model processes the request, a lightweight classifier identifies the task type. This can be:

  • A small fine-tuned model (distilbert-sized, adds <10ms latency)
  • A rule-based classifier using keywords, intent detection, or regex patterns
  • A single LLM call with a minimal classification prompt
  • An embedding similarity search against known task-type prototypes

The classifier doesn't need to be perfect. Even a 90% accurate classifier dramatically reduces irrelevant context compared to injecting everything. Misclassification costs you a suboptimal scaffold, not a system failure — the base model still gets the core request, just without the optimal boost.

3. The Injection Mechanism

Once the task type is identified, the relevant scaffold is injected into the prompt. This is where the magic happens:

  • Easy tasks (renames, simple lookups, formatting): The classifier returns "no scaffold needed." The model gets a lean prompt with just the system instructions and the user request. Token count stays low. Latency stays low. Cost stays low.
  • Medium tasks (SQL generation, structured extraction): One targeted scaffold is injected. The model gets exactly the context it needs — schema definitions, dialect-specific syntax, a couple of examples — and nothing else.
  • Hard tasks (complex refactoring, multi-step debugging): Multiple relevant scaffolds can be composed. The model gets rich context, but only the rich context that matters for this specific task type.

The Research Backing

Dynamic Scaffolding isn't just a pattern — it's converging from multiple research directions simultaneously.

SkillsInjector (Nanjing University / Shanghai AI Lab, arXiv 2605.29794) demonstrates the full pipeline: a context planner that learns execution-grounded skill preferences and admits an adaptive number of skills per task, plus a set-aware renderer that tailors descriptions relative to co-injected neighbors. Across three benchmarks (tau2-bench, SkillsBench, ALFWorld), it beats the strongest baseline by 3.9, 6.1, and 7.3 percentage points respectively. The key insight: which skills you expose, how many you include, and how you present them together all matter independently.

Prompt Codebooks (arXiv 2605.28360) takes a compositional approach: recasting prompt optimization as discrete learning over a finite vocabulary of reusable "instincts." Each input is routed to a small subset via an LLM encoder. The codebook approach beats the strongest baseline (GEPA) by +3.34 on HotpotQA and +1.11 aggregate, while cutting deployed prompt length by up to 14.1x versus MIPROv2. The routing is learned, not hand-specified, but the principle is the same: don't give every input the same context.

DiSR (Decomposing Prompts into reusable Scaffolds and task-specific Residuals, ICLR 2026) splits prompts into a domain-invariant Instructional Scaffold (reusable across tasks) and a Task-specific Residual (fine-grained adaptation). Inspired by the Minimum Description Length principle, it achieves competitive accuracy with better-calibrated confidence — especially on large models and professional domains. DiSR formalizes what Dynamic Scaffolding operationalizes: some context is universal, some is task-specific, and conflating the two is wasteful.

Adaptive Prompt Structure Factorization (arXiv 2604.06699) extends the idea further: a framework for self-discovering and optimizing compositional prompt programs. Rather than hand-crafting scaffolds, the system learns which compositional structures work best and factorizes them for reuse.

And from the cognitive scaffolding side, Cognitive Tool Scaffolding (tianpan.co, April 2026) shows that running a standard 70B model through four structured cognitive operations (decompose, retrieve, synthesize, verify) approaches reasoning-model accuracy at a fraction of the cost. The scaffolding substitutes for model capability when the scaffold is explicit. The implication is clear: the right scaffold at the right time can make a smaller model competitive with a much larger one.

The Economics: Why This Matters Now

Token costs are the silent killer of agent deployments. If you're running a general-purpose agent at scale — say, 100,000 requests per day — and 60% of those requests are simple tasks that don't need scaffolding, you're wasting tokens on 60,000 requests per day. At GPT-4-class pricing, that's real money.

But the cost argument is actually the least important one. Here's what matters more:

Quality improves. When the model doesn't have to sift through irrelevant examples, it focuses on the task at hand. SkillsInjector's ablation studies show that skill selection, adaptive budgeting, and set-aware rendering each contribute independently to quality gains. Removing irrelevant context doesn't just save tokens — it makes the model better.

Latency drops. Fewer input tokens means faster time-to-first-token. For interactive applications, this is the difference between a responsive assistant and one that makes users wait.

Observability improves. When you audit which scaffolds fire per request, you get a natural taxonomy of your workload. You learn what task types your users actually send, which scaffolds are most valuable, and where your scaffold library has gaps. Static prompts give you none of this visibility.

Compositional safety. Dynamic Scaffolding makes it straightforward to add guardrails per task type. SQL generation gets injection-prevention rules. Code generation gets security checklists. Document transformation gets PII-redaction reminders. You don't pollute every prompt with every guardrail — you apply the right guard to the right task.

Implementation Patterns

Here's how to implement Dynamic Scaffolding in practice, from simplest to most sophisticated:

Level 1: Rule-Based Routing

Start with explicit rules. If the user's request contains SQL keywords, inject the SQL scaffold. If it mentions "refactor" or "restructure," inject the refactoring scaffold. If neither matches, skip all scaffolding.

SCAFFOLDS = {
    "sql": load_scaffold("sql_generation.json"),
    "refactor": load_scaffold("code_refactoring.json"),
    "debug": load_scaffold("bug_diagnosis.json"),
}

def classify_task(request: str) -> str | None:
    request_lower = request.lower()
    sql_keywords = {"select", "insert", "update", "delete", "join", "where", "sql"}
    refactor_keywords = {"refactor", "restructure", "rewrite", "clean up", "simplify"}
    debug_keywords = {"bug", "error", "crash", "exception", "debug", "fix"}
    
    if any(kw in request_lower for kw in sql_keywords):
        return "sql"
    if any(kw in request_lower for kw in refactor_keywords):
        return "refactor"
    if any(kw in request_lower for kw in debug_keywords):
        return "debug"
    return None

def build_prompt(system: str, request: str) -> str:
    task_type = classify_task(request)
    scaffold = SCAFFOLDS.get(task_type, "")
    if scaffold:
        return f"{system}\n\n{ scaffold}\n\nUser: {request}"
    return f"{system}\n\nUser: {request}"

This is 80% of the value with 5% of the effort. Start here.

Level 2: Embedding-Based Classification

Replace keyword rules with embedding similarity. Create a prototype embedding for each task type by averaging embeddings of representative examples. At runtime, embed the incoming request and find the nearest prototype. If the similarity is above a threshold, inject the matching scaffold.

import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")

# Pre-computed from representative examples per task type
PROTOTYPES = {
    "sql": model.encode(["write a query to find...", "select all users where...", ...]).mean(axis=0),
    "refactor": model.encode(["refactor this function to...", "clean up this module..."]).mean(axis=0),
    "debug": model.encode(["this function throws an error...", "why does this crash..."]).mean(axis=0),
}

def classify_task_embedding(request: str, threshold: float = 0.6) -> str | None:
    embedding = model.encode([request])[0]
    best_type, best_sim = None, threshold
    for task_type, prototype in PROTOTYPES.items():
        sim = np.dot(embedding, prototype) / (np.linalg.norm(embedding) * np.linalg.norm(prototype))
        if sim > best_sim:
            best_type, best_sim = task_type, sim
    return best_type

This handles paraphrases, typos, and implicit intent much better than keyword rules. The cost is one embedding call per request (~5ms with a local model).

Level 3: Learned Selection with Adaptive Budgeting

The SkillsInjector approach: train a context planner that learns execution-grounded skill preferences. The planner doesn't just pick which scaffold to inject — it decides how many to inject, based on how much context this specific task can exploit. Some tasks benefit from three examples; others need seven. The planner learns this from actual execution outcomes, not from heuristics.

This level requires training data (task trajectories with success/failure labels) and a training pipeline, but it's where the biggest gains live. SkillsInjector's results show that adaptive budgeting alone — without even touching description rendering — already outperforms fixed-budget retrieval.

Level 4: Set-Aware Rendering

The most sophisticated level: when multiple scaffolds are injected, don't just concatenate them. Render each scaffold's description relative to its neighbors. If you're injecting both the SQL scaffold and the debugging scaffold (because the task involves debugging a SQL query), clarify the role boundaries. "Use scaffold A for query generation, scaffold B for error diagnosis." Without this rendering, co-injected scaffolds can confuse the model about which context applies when.

When Not to Use Dynamic Scaffolding

This pattern isn't universal. Three cases where you should stick with static prompts:

  1. Single-task agents. If your agent only does one thing (say, SQL generation), there's nothing to classify. Inject the SQL scaffold every time. Dynamic Scaffolding solves the multi-task problem.
  1. Low-latency hard requirements. The classifier adds a small but non-zero latency. If you're operating at the absolute latency floor (real-time trading, game rendering), even 10ms of classification overhead may be too much. In practice, most agents are nowhere near this constraint.
  1. Insufficient task diversity. If you have only two task types and one is 95% of your traffic, the classification overhead isn't worth it. Just build two separate prompts and route at the API level.

The Bigger Picture: Context as a First-Class Concern

Dynamic Scaffolding is part of a broader shift in how we think about LLM context. For the first two years of the GPT era, context was something you stuffed — more examples, more instructions, more caveats. The model had a 4K token window, then 8K, then 32K, then 128K, and each expansion was treated as license to dump more content in.

The emerging consensus is the opposite. Context is a scarce resource, even at 128K tokens, because attention is finite. Every irrelevant token in the prompt competes with every relevant token for the model's limited capacity. The question isn't "how much context can we fit?" It's "what is the minimum context that maximizes task performance?"

This is what makes Dynamic Scaffolding more than an optimization trick. It's an architectural principle: context should be earned, not assumed. Each token in the prompt should justify its presence by contributing to the task at hand. If it doesn't, it shouldn't be there.

The parallel research streams — Prompt Codebooks routing inputs to compositional instincts, DiSR decomposing prompts into reusable scaffolds and task-specific residuals, SkillsInjector learning which skills to expose and how many — are all converging on this same principle from different angles. The static prompt is dead. Long live the dynamic prompt.

Getting Started

If you're running a multi-task agent today, here's a pragmatic path:

  1. Audit your current prompt. How many tokens of scaffolding does it carry? How many are relevant to any given request? You'll probably find that 60-80% of your prompt content is irrelevant to most requests.
  1. Decompose your prompt into a scaffold library. Break it apart by task type. Each scaffold should be self-contained — no cross-references to other scaffolds.
  1. Build a minimal classifier. Start with keyword rules (Level 1 above). You don't need machine learning to get started.
  1. Measure. Track tokens per request by task type. Track quality by task type. You should see token costs drop on easy tasks and quality improve on hard tasks within the first week.
  1. Iterate. Replace keyword rules with embedding similarity. Add adaptive budgeting. Eventually, move to learned selection.

The Agent Patterns Catalog entry for Dynamic Scaffolding is marked as Emerging maturity — this is a pattern that's proven in research and early production but hasn't yet become standard practice. The research is clear. The economics are clear. The implementation is straightforward. The question is whether you'll keep wasting tokens on easy tasks and starving hard ones, or whether you'll let your agent carry exactly the context it needs, exactly when it needs it.

Your prompt isn't a bucket. It's a precision instrument. Start treating it like one.


Dynamic Scaffolding is cataloged in the Agent Patterns Catalog under Routing & Composition. Related research: SkillsInjector (arXiv 2605.29794), Prompt Codebooks (arXiv 2605.28360), DiSR (ICLR 2026, OpenReview WrTjCHs2tS), Adaptive Prompt Structure Factorization (arXiv 2604.06699), Cognitive Tool Scaffolding (tianpan.co).