Inferensys

Prompt

Cost-Aware Task Routing Prompt for Agent Delegation

A practical prompt playbook for using Cost-Aware Task Routing Prompt for Agent Delegation in production AI workflows.
Engineer reviewing agent handoff workflow on laptop, task routing diagrams visible, technical office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for cost-aware task routing in multi-agent delegation.

This prompt is for platform operators and orchestration engineers who need to assign sub-tasks to a pool of specialized agents while balancing quality requirements against compute cost, latency budgets, and model tier constraints. The job-to-be-done is producing a cost-optimized assignment plan that justifies trade-offs and enforces budget guardrails—not just picking the cheapest or most capable agent. Use this when you have a decomposed task list, a known agent pool with priced capabilities, and a hard budget or latency ceiling that must be respected.

Do not use this prompt when the agent pool is homogeneous, when cost is irrelevant, or when every task must hit a fixed quality bar regardless of price. It is also inappropriate for single-agent workflows, tasks without clear input/output contracts, or situations where the orchestrator lacks visibility into agent pricing and current load. This prompt assumes you have already decomposed the work and defined sub-task contracts; it does not perform decomposition or capability discovery itself. If you need to discover agent capabilities dynamically, pair this with an agent capability discovery prompt before routing.

The ideal reader is an infrastructure or platform engineer wiring this into an agent orchestration layer. You should have access to a capability registry with per-agent pricing tiers, latency estimates, and quality benchmarks. Before using this prompt in production, validate the cost estimation accuracy against actual execution metrics and monitor for quality regression when cheaper agents are selected. If the task involves regulated data, safety-critical actions, or irreversible side effects, require human approval on the routing plan before dispatch.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Cost-Aware Task Routing Prompt delivers value and where it introduces unacceptable risk. Use this to decide whether to deploy the prompt, add guardrails, or choose a simpler routing approach.

01

Good Fit: Multi-Tier Model Pools

Use when: you operate a pool of agents backed by different model tiers (e.g., GPT-4 for complex reasoning, Claude Haiku for simple extraction) and need to route sub-tasks to the cheapest model that meets quality requirements. Guardrail: always include a quality regression check that compares budget-tier outputs against a premium baseline on a sample of tasks.

02

Good Fit: Latency-Sensitive Workloads

Use when: sub-tasks have explicit latency budgets and routing decisions must trade off speed against accuracy. Guardrail: define maximum acceptable latency per task type in the prompt constraints and validate that the routing plan does not assign slow models to time-critical steps.

03

Bad Fit: Single-Model Deployments

Avoid when: all agents use the same model with no tier differentiation. Cost-aware routing adds complexity without benefit when there is no cheaper alternative to route to. Guardrail: fall back to a static assignment plan if the model pool contains only one tier.

04

Bad Fit: Safety-Critical Tasks Without Review

Avoid when: sub-tasks involve clinical decisions, legal conclusions, or financial commitments where cost optimization must never override accuracy. Guardrail: hard-code premium-model assignment for any task tagged with a safety-critical classification and require human approval on the output.

05

Required Input: Accurate Cost and Latency Estimates

Risk: the prompt produces a cost-optimized plan based on estimated token counts and per-model pricing. If estimates are wrong, the plan may route expensive tasks to cheap models or vice versa. Guardrail: feed the prompt actual historical token usage and latency data per task type, not guesses. Track estimation error over time and recalibrate.

06

Operational Risk: Quality Drift Over Time

Risk: a cost-optimized routing plan that passes initial evaluation may silently degrade as task distributions shift or model behavior changes. Guardrail: run a continuous evaluation pipeline that samples routed outputs, compares them against a premium-model baseline, and alerts if quality drops below a defined threshold.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that routes sub-tasks to agents while balancing quality requirements against compute cost, latency budgets, and model tier constraints.

This template is designed to be dropped into an agent orchestrator that has already decomposed a complex task into sub-tasks. It takes a list of sub-tasks, a pool of available agents with their capabilities and cost profiles, and a set of budget constraints, then produces a cost-optimized assignment plan. The prompt forces the model to justify trade-offs explicitly rather than defaulting to the most capable agent for every task, which is the most common failure mode in production routing systems.

text
You are a cost-aware task router for a multi-agent system. Your job is to assign sub-tasks to agents while minimizing total compute cost, respecting latency budgets, and maintaining quality thresholds.

## AVAILABLE AGENTS
[AGENT_POOL]
<!-- Format: agent_id, capabilities, model_tier, cost_per_1k_tokens, avg_latency_ms, max_context_tokens, current_load_pct -->

## SUB-TASKS TO ASSIGN
[SUB_TASKS]
<!-- Format: task_id, description, required_capabilities, min_quality_tier, max_latency_ms, input_tokens_estimate, output_tokens_estimate, dependency_task_ids -->

## BUDGET CONSTRAINTS
- Total compute budget: [TOTAL_BUDGET_TOKENS]
- Per-task latency ceiling: [PER_TASK_LATENCY_MS]
- Minimum quality tier per task: [MIN_QUALITY_TIER]
- Parallel execution budget: [MAX_PARALLEL_AGENTS]

## ROUTING RULES
1. Assign each sub-task to exactly one agent.
2. An agent can handle multiple tasks if load permits, but do not exceed 80% utilization.
3. Prefer lower-cost agents when quality requirements allow it.
4. If a task's dependency has not completed, the assigned agent must wait. Account for dependency chains in latency estimates.
5. If no agent meets both quality and latency requirements, flag the task for escalation.
6. If total estimated cost exceeds the budget, identify which tasks can be downgraded to a lower tier with acceptable quality loss.

## OUTPUT SCHEMA
Return a JSON object with this structure:
{
  "assignments": [
    {
      "task_id": "string",
      "assigned_agent_id": "string",
      "estimated_cost_tokens": number,
      "estimated_latency_ms": number,
      "quality_tier": "string",
      "trade_off_justification": "string",
      "escalation_required": boolean,
      "escalation_reason": "string | null"
    }
  ],
  "total_estimated_cost_tokens": number,
  "budget_utilization_pct": number,
  "escalations": ["task_id"],
  "downgrade_recommendations": [
    {
      "task_id": "string",
      "current_tier": "string",
      "recommended_tier": "string",
      "quality_impact": "string",
      "cost_savings_tokens": number
    }
  ],
  "parallel_execution_groups": [["task_id"]],
  "critical_path_latency_ms": number,
  "unassignable_tasks": [
    {
      "task_id": "string",
      "blocking_constraint": "string"
    }
  ]
}

## CONSTRAINTS
- Do not assign tasks to agents that lack required capabilities.
- Do not exceed per-task latency ceilings on the critical path.
- If budget is insufficient even after downgrades, flag the shortfall explicitly.
- Justify every assignment where a cheaper agent was available but not chosen.
- For escalation flags, specify whether the issue is capability gap, latency violation, or quality risk.

Adapt this template by replacing the agent pool and sub-task formats with your actual internal schemas. If your system uses MCP servers or tool-based agent discovery, replace the static [AGENT_POOL] with a dynamically populated capability registry. The output schema should match whatever your orchestrator expects—if your orchestrator consumes protobuf or a different JSON shape, adjust the schema block accordingly. The routing rules section is where most teams need customization: add rules for data residency, compliance boundaries, or organizational policies that constrain which agents can handle which data. Test this prompt with edge cases where no agent meets all constraints, where the budget is unrealistically tight, and where dependency chains create latency cascades. These edge cases reveal whether the model will silently produce invalid assignments or correctly escalate.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Cost-Aware Task Routing Prompt. Each placeholder must be populated before the prompt is assembled and sent to the routing model. Incomplete or malformed variables will cause routing failures or budget violations.

PlaceholderPurposeExampleValidation Notes

[TASK_DESCRIPTION]

The original user request or work item that needs to be delegated to a sub-agent pool.

Generate a quarterly financial summary report from the attached CSV files and draft an executive email.

Must be non-empty string. Check for minimum 20 characters to ensure sufficient context for decomposition. Reject if only contains greetings or single words.

[AVAILABLE_AGENTS]

A structured list of agent definitions including their capabilities, model tiers, and estimated cost per invocation.

[{"agent_id": "analyst-gpt4", "capabilities": ["data-analysis", "report-generation"], "model_tier": "high", "cost_per_call_estimate": 0.15, "avg_latency_ms": 4500}]

Must be valid JSON array with at least one agent. Each agent object requires agent_id, capabilities, model_tier, and cost_per_call_estimate fields. Reject if capabilities array is empty or model_tier is not one of low, medium, high.

[BUDGET_CONSTRAINTS]

The maximum allowable cost, latency budget, and any tier restrictions for this specific task execution.

{"max_total_cost": 0.50, "max_latency_ms": 12000, "allowed_tiers": ["low", "medium"], "prefer_cheapest": true}

Must be valid JSON object. max_total_cost and max_latency_ms are required numeric fields. allowed_tiers must be a non-empty array of valid tier strings. Reject if max_total_cost is zero or negative.

[QUALITY_REQUIREMENTS]

The minimum acceptable quality threshold, criticality level, and any hard requirements that override cost optimization.

{"min_confidence_threshold": 0.85, "criticality": "high", "hard_requirements": ["output_must_be_cited", "requires_human_review"]}

Must be valid JSON object. min_confidence_threshold must be a float between 0.0 and 1.0. criticality must be one of low, medium, high, critical. Reject if hard_requirements contains unknown flags.

[TASK_CONTEXT]

Relevant background information, session history, user preferences, or domain-specific constraints that affect routing decisions.

User is a CFO who prefers concise bullet-point summaries. Previous analysis in this session used the Q3-2024 dataset. Output language must be English.

Optional string. Can be empty or null. If provided, check for length under 4000 tokens to avoid context pollution. Warn if context contains contradictory instructions to quality requirements.

[OUTPUT_SCHEMA]

The expected structure of the routing plan that the prompt must produce, defining the assignment format and required fields.

{"assignments": [{"sub_task_id": "string", "agent_id": "string", "rationale": "string", "estimated_cost": "number", "estimated_latency_ms": "number"}], "total_estimated_cost": "number", "trade_off_summary": "string"}

Must be valid JSON Schema or example structure. Each assignment must include sub_task_id, agent_id, rationale, and cost/latency estimates. Reject schemas that don't require cost justification fields.

[COST_ESTIMATION_MODEL]

The pricing data or cost function used to calculate per-agent invocation costs, including token pricing and any fixed overhead.

{"model_pricing": {"gpt-4": {"input_per_1k": 0.03, "output_per_1k": 0.06}, "claude-haiku": {"input_per_1k": 0.00025, "output_per_1k": 0.00125}}, "fixed_overhead_per_call": 0.002}

Must be valid JSON object mapping model identifiers to pricing structures. Input and output per-1k-token prices are required. Reject if pricing data is older than 30 days or contains zero-cost entries without explicit justification.

[PREVIOUS_ROUTING_OUTCOMES]

Historical routing decisions and their actual costs and quality outcomes, used for calibration and regression detection.

[{"task_signature": "report-generation", "routed_agent": "analyst-gpt4", "estimated_cost": 0.15, "actual_cost": 0.18, "quality_score": 0.92}]

Optional JSON array. Can be empty or null. If provided, each entry requires task_signature, routed_agent, estimated_cost, actual_cost, and quality_score. Flag entries where actual_cost exceeds estimated_cost by more than 20% for calibration review.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the cost-aware routing prompt into an agent orchestration pipeline with validation, budget enforcement, and quality regression detection.

The cost-aware routing prompt is not a standalone decision engine. It should sit inside an orchestration layer that enforces the budget constraints the prompt recommends, validates the assignment plan before dispatching agents, and logs every routing decision for cost attribution and quality regression analysis. The prompt produces a plan; the harness makes it executable, auditable, and safe.

Start by wrapping the prompt call in a pre-flight validation gate. Before the prompt runs, the harness should inject the current [BUDGET_REMAINING], [LATENCY_BUDGET_MS], and [AVAILABLE_MODEL_TIERS] from live infrastructure state—not stale config. After the prompt returns its assignment plan, run a schema validator that checks every sub-task assignment has a non-null agent_id, a model_tier that exists in the available pool, and an estimated_cost that sums to less than the remaining budget. Reject plans that exceed budget or reference unavailable models. If validation fails, either re-prompt with the specific violation as a [CONSTRAINT] update or escalate to a human operator with the failed plan and budget snapshot.

Cost estimation accuracy is the most common failure mode. The prompt's cost estimates are approximate; the harness must track actual token consumption and latency per sub-task and compare them against the prompt's estimates. Store these deltas in a structured log: {routing_id, sub_task_id, estimated_cost, actual_cost, estimated_latency_ms, actual_latency_ms, model_tier}. When actual costs consistently exceed estimates by more than 20%, trigger a quality regression alert and consider switching to a conservative cost-estimation model or adding a fixed overhead multiplier to the prompt's [CONSTRAINTS]. For high-stakes workflows, implement a hard budget kill switch: if cumulative actual spend reaches 90% of the allocated budget mid-execution, pause the remaining sub-tasks and escalate rather than silently overrunning.

Model choice matters here. The routing prompt itself should run on a fast, cheap model (e.g., GPT-4o-mini, Claude Haiku) because it's a classification-and-planning task that doesn't require deep reasoning. Reserve expensive models for the sub-tasks that the prompt routes to them. If the routing prompt produces inconsistent plans across repeated calls with the same inputs, upgrade it to a more capable model or add few-shot examples of correct routing decisions. Log routing plan hashes to detect non-determinism.

Retries and fallbacks need careful design. If a sub-task agent fails, do not blindly re-call the routing prompt for the entire plan. Instead, implement a targeted re-routing path: extract the failed sub-task's [INPUT] and [CONSTRAINTS], append the failure reason, and call a lightweight re-assignment prompt that selects a fallback agent or model tier for that single sub-task. Preserve the rest of the plan. If the fallback also fails, escalate the entire task to a human with the full execution trace, not just the final error. Avoid the trap of infinite retry loops by setting a hard limit of one re-assignment attempt per sub-task.

Observability is non-negotiable. Every routing decision should produce a structured audit record containing: the original task, the decomposed sub-tasks, the assigned agents and model tiers, the estimated and actual costs, the latency budget consumed, any validation failures, and the final outcome per sub-task. Use these records to build a dashboard that tracks cost-per-task, budget utilization rate, estimation accuracy, and escalation frequency. This data is essential for tuning the prompt's [CONSTRAINTS] and proving to stakeholders that the cost-aware routing is actually saving money without degrading quality.

IMPLEMENTATION TABLE

Expected Output Contract

Validate the cost-optimized assignment plan returned by the routing prompt. Each field must conform to the schema, budget constraints, and quality thresholds defined here before the orchestrator dispatches sub-tasks.

Field or ElementType or FormatRequiredValidation Rule

assignment_plan

Array of objects

Must be a non-empty array. Each element must match the sub_task_assignment schema.

sub_task_assignment.sub_task_id

String matching [TASK_ID]

Must exactly match a sub_task_id from the input decomposition. No orphaned or invented IDs allowed.

sub_task_assignment.agent_id

String matching [AGENT_ID]

Must reference an agent_id present in the input agent_pool. Validate against the pool snapshot.

sub_task_assignment.model_tier

Enum: [MODEL_TIER_OPTIONS]

Must be one of the allowed model tiers defined in [MODEL_TIER_OPTIONS]. Cannot exceed the agent's maximum available tier.

sub_task_assignment.estimated_cost

Number (float, 2 decimal places)

Must be a positive number. Sum of all estimated_cost values must not exceed [MAX_TOTAL_BUDGET].

sub_task_assignment.estimated_latency_ms

Integer

Must be a positive integer. Sum of all estimated_latency_ms values must not exceed [MAX_TOTAL_LATENCY_BUDGET_MS].

sub_task_assignment.trade_off_justification

String

Must be non-empty and between 20 and 300 characters. Must explicitly mention the cost-quality trade-off made for this assignment.

budget_guardrail_check.total_estimated_cost

Number (float, 2 decimal places)

Must equal the sum of all sub_task_assignment.estimated_cost values. Must be less than or equal to [MAX_TOTAL_BUDGET].

budget_guardrail_check.total_estimated_latency_ms

Integer

Must equal the sum of all sub_task_assignment.estimated_latency_ms values. Must be less than or equal to [MAX_TOTAL_LATENCY_BUDGET_MS].

quality_regression_flags

Array of objects or null

If not null, each object must contain sub_task_id, risk_level (enum: low, medium, high), and risk_description (string). Null allowed if no regressions detected.

PRACTICAL GUARDRAILS

Common Failure Modes

Cost-aware routing introduces failure modes where the model optimizes for the wrong objective, misestimates task complexity, or violates budget constraints. These cards cover the most common production failures and how to guard against them.

01

Cost Over Quality Collapse

What to watch: The router consistently selects the cheapest model tier even when task complexity demands higher reasoning capability, producing degraded outputs that pass basic validation but fail downstream consumers. Guardrail: Implement a minimum quality threshold per task type. Require the router to justify any cost-saving decision with a confidence score, and escalate to a human reviewer when quality-critical tasks are routed to low-tier models.

02

Latency Budget Exhaustion

What to watch: The router underestimates cumulative latency across chained sub-tasks, causing the overall workflow to exceed its time budget even though individual task estimates appeared valid. Guardrail: Track cumulative latency against the total budget at each routing decision. Add a hard stop rule that forces fallback to a faster model or cached result when remaining budget drops below a defined threshold.

03

Cost Estimation Drift

What to watch: The router's token consumption estimates are consistently optimistic, leading to actual costs that exceed the planned budget by 2-5x over repeated runs. This compounds across multi-agent workflows. Guardrail: Log estimated vs. actual token usage per routing decision. Trigger a recalibration prompt or model tier downgrade when estimation error exceeds a rolling average threshold over the last N runs.

04

Task Complexity Misclassification

What to watch: The router misclassifies a complex, multi-step reasoning task as a simple lookup or classification, assigning it to a lightweight model that hallucinates or produces incomplete results. Guardrail: Add a pre-routing complexity assessment step that scores task difficulty before model selection. Require high-complexity scores to bypass cost optimization and route directly to capable models with human review options.

05

Budget Silo Violation

What to watch: The router optimizes per-task cost without awareness of the total workflow budget, causing early tasks to consume disproportionate resources and starving later, equally important tasks. Guardrail: Pass the total remaining workflow budget as a constraint in every routing prompt. Require the router to report remaining budget after each assignment and reject routing decisions that would leave insufficient budget for remaining mandatory tasks.

06

Quality Regression After Model Downgrade

What to watch: A previously reliable task begins failing after the router downgrades its model tier to save cost, but no automated check detects the subtle quality drop until users report issues. Guardrail: Maintain per-task-type quality baselines from prior runs. Run automated eval checks on a sample of downgraded outputs and trigger re-routing to the original model tier if quality scores drop below the baseline by a defined margin.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the cost-aware routing prompt before deployment. Each row defines a pass standard, a failure signal, and a concrete test method. Run these checks against a golden set of 20-30 routing scenarios with known optimal assignments and cost ceilings.

CriterionPass StandardFailure SignalTest Method

Budget compliance

Total estimated cost across all assignments does not exceed [MAX_BUDGET] by more than 5%

Plan exceeds budget by more than 5% without an explicit override justification

Parse the cost estimate from the output and sum across all sub-tasks. Compare against [MAX_BUDGET]. Flag if over threshold and no [OVERRIDE_REASON] present.

Latency SLA adherence

Every sub-task assigned to a model tier whose p95 latency is within [MAX_LATENCY_MS] for that task's priority level

A high-priority task is assigned to a slow tier without a documented trade-off in the justification block

Cross-reference each assignment's model tier against a latency lookup table. Check that priority field matches latency constraint. Flag mismatches.

Quality threshold maintenance

No task with [MIN_QUALITY_SCORE] above 0.8 is downgraded to a tier known to score below threshold on that task type

A quality-sensitive task is routed to a cheap model with no quality guard annotation

Maintain a quality-score-by-tier reference. For each assignment, verify that the selected tier's known quality floor meets or exceeds the task's minimum. Flag violations.

Cost estimation accuracy

Estimated cost per sub-task is within 30% of actual cost when executed against the assigned model

Estimate differs from actual by more than 50% on three or more sub-tasks in a batch

Execute the plan in a sandbox with token counting enabled. Compare estimated vs. actual cost per task. Calculate mean absolute percentage error. Flag if MAPE exceeds 0.5.

Trade-off justification presence

Every assignment that violates a default constraint includes a non-empty [TRADE_OFF_JUSTIFICATION] field

A downgrade or constraint violation appears with an empty or boilerplate justification

Scan the output for any assignment where selected tier does not match the default tier for that task type. Assert that [TRADE_OFF_JUSTIFICATION] is present and has more than 20 characters.

Fallback tier specification

Every assignment includes a [FALLBACK_TIER] that differs from the primary assignment and is capable of executing the task

Fallback tier is identical to primary tier, missing, or references an unavailable model

For each sub-task assignment, check that [FALLBACK_TIER] is non-null, differs from [PRIMARY_TIER], and exists in the [AVAILABLE_TIERS] list.

Quality regression detection

Output includes a [REGRESSION_RISK] flag set to true when any task is assigned to a tier below its historical quality baseline

A known regression scenario produces [REGRESSION_RISK] = false or the field is absent

Inject 5 scenarios where the assigned tier is known to underperform on the task type. Assert that [REGRESSION_RISK] is true for each. Measure false-negative rate across the golden set.

Output schema validity

The full output parses against the [OUTPUT_SCHEMA] with zero validation errors

Schema validation returns errors for missing required fields, wrong types, or malformed enum values

Run the output through a JSON Schema validator configured with [OUTPUT_SCHEMA]. Assert zero errors. Automate as a CI gate.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a hardcoded agent pool of 3-5 agents with known capabilities and per-token costs. Replace [AGENT_POOL] with a static JSON array. Use [TASK_DESCRIPTION] as free-text input. Skip cost estimation accuracy tracking and quality regression detection. Run 10-20 manual test cases and spot-check routing decisions for reasonableness.

Watch for

  • The model routing everything to the cheapest agent regardless of quality requirements
  • Ignoring latency budget constraints when they conflict with cost minimization
  • Hallucinated agent capabilities not present in your [AGENT_POOL] definition
  • No structured output, making it hard to programmatically consume the assignment plan
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.