Inferensys

Prompt

Task Granularity Optimization Prompt Template

A practical prompt playbook for using the Task Granularity Optimization Prompt Template in production AI workflows.
Product manager reviewing autonomous task execution dashboard on laptop, completed tasks visible, casual work session.
PROMPT PLAYBOOK

When to Use This Prompt

Define when to apply the Task Granularity Optimization Prompt and when to avoid it.

This prompt is for agent framework developers and orchestration engineers who need to decide whether a complex task should be split into smaller sub-tasks or executed as a single unit. The core job-to-be-done is balancing the overhead of decomposition and agent handoffs against the benefits of parallel execution and specialized agent assignment. Use this prompt when you have a task that could plausibly be broken down, and you need a structured recommendation that accounts for context budget, latency, compute cost, and the risk of over-decomposition. The ideal user has a working understanding of their agent pool's capabilities, the approximate token costs of their models, and the latency tolerance of their application.

The prompt requires several concrete inputs to produce a useful recommendation. You must provide the full task description, the available agent pool with their capabilities and costs, the total context window budget, and the target latency or cost constraints. Without these, the model will produce generic advice that cannot be actioned in a production system. The prompt is designed to output a structured granularity plan with a split-or-keep decision, a breakdown of sub-tasks if splitting is recommended, cost and latency estimates for each option, and explicit flags for over-decomposition and under-decomposition risks. This output should be validated against actual execution metrics over time to calibrate the model's estimates.

Do not use this prompt for trivial tasks where decomposition overhead clearly outweighs any benefit, or for tasks that are already atomic and cannot be meaningfully split. Avoid it when the agent pool is unknown or when cost and latency constraints are undefined, because the recommendation will lack the grounding needed for a production decision. This prompt is also not a substitute for a full orchestration engine; it provides a recommendation, not an execution plan. After receiving the output, you should wire the recommendation into your task dispatch logic, log the decision alongside actual execution outcomes, and periodically review whether the granularity decisions are improving throughput or adding unnecessary handoff complexity.

PRACTICAL GUARDRAILS

Use Case Fit

Task Granularity Optimization is a meta-prompt for agent orchestrators. It decides whether a task should be split further or kept whole. Use it when decomposition decisions affect cost, latency, and context budgets. Avoid it when the task is trivially simple or when the orchestrator already has fixed, hard-coded decomposition rules.

01

Good Fit: Complex Multi-Step Workflows

Use when: A user request requires multiple distinct capabilities, external tool calls, or reasoning steps that could reasonably be executed by different specialized agents. Guardrail: The prompt should output a granularity score and a specific split recommendation, not just a yes/no. Validate that each proposed sub-task has a clear, independent output contract.

02

Bad Fit: Trivially Atomic Tasks

Avoid when: The task is a single, simple lookup, a direct question-answering turn, or a stateless transformation with no organizational benefit to splitting. Guardrail: Implement a pre-check that bypasses the granularity optimizer for tasks below a complexity threshold (e.g., estimated steps < 2) to save latency and cost.

03

Required Inputs

What to watch: The prompt requires a structured description of the task, the available agent pool with their capabilities, and current context budget limits. Missing any of these leads to generic, unsafe recommendations. Guardrail: The application layer must enforce a schema on the input, ensuring fields like available_agents, task_description, and context_budget_remaining are populated before the prompt is called.

04

Operational Risk: Over-Decomposition

Risk: Splitting a task into too many tiny sub-tasks explodes orchestration overhead, increases cumulative latency from handoffs, and fragments the context, causing each agent to have an incomplete picture. Guardrail: The prompt must estimate the orchestration tax (handoff latency, context packing cost) and compare it against the parallelism gain. Reject splits where overhead exceeds 30% of the total estimated execution time.

05

Operational Risk: Under-Decomposition

Risk: Keeping a task too large creates a monolithic agent call that hits context limits, mixes incompatible tool requirements, or prevents parallel execution of independent work. Guardrail: The prompt must flag tasks that exceed 70% of the available context window or require tools not available on a single agent, forcing a decomposition recommendation.

06

Cost and Latency Trade-off

Risk: The optimization may favor maximum parallelism to reduce wall-clock time but at a significantly higher token cost due to duplicated context across parallel agents. Guardrail: The prompt output must include a cost multiplier estimate and a latency profile for both the split and whole-task approaches, allowing the orchestrator to choose based on a predefined cost/latency policy.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for optimizing task granularity with square-bracket placeholders for direct integration into agent orchestration pipelines.

The following prompt template is designed to be embedded directly into an agent orchestrator or planning node. It forces the model to reason about the trade-off between splitting a task further (parallelism, specialization) and keeping it whole (lower overhead, fewer handoffs). The template uses square-bracket placeholders for all dynamic inputs, making it safe to inject into code without accidental template resolution. Before using this prompt, ensure you have defined the task description, available agent capabilities, and the current context budget. The prompt is structured to produce a machine-readable JSON output that can be validated by your orchestration engine before any sub-tasks are dispatched.

text
You are a task granularity optimizer for a multi-agent system. Your job is to analyze a candidate task and recommend whether it should be executed as a single unit or decomposed into smaller sub-tasks. You must balance parallelism benefits against coordination overhead, context transfer costs, and agent capability constraints.

## INPUT

**Task Description:**
[TASK_DESCRIPTION]

**Available Agents and Capabilities:**
[AGENT_CAPABILITIES]

**Current Context Budget Remaining (tokens):**
[CONTEXT_BUDGET]

**Maximum Parallel Sub-Tasks Allowed:**
[MAX_PARALLEL_TASKS]

**Latency Budget (milliseconds):**
[LATENCY_BUDGET]

**Risk Level for Incorrect Output:**
[RISK_LEVEL]

## CONSTRAINTS

[CONSTRAINTS]

## OUTPUT SCHEMA

Return a single JSON object with the following structure:

{
  "recommendation": "keep_whole" | "decompose",
  "confidence": 0.0-1.0,
  "reasoning": "string explaining the trade-off analysis",
  "estimated_cost_current": number,
  "estimated_cost_decomposed": number,
  "estimated_latency_current_ms": number,
  "estimated_latency_decomposed_ms": number,
  "context_budget_consumed_current": number,
  "context_budget_consumed_decomposed": number,
  "sub_tasks": [
    {
      "id": "string",
      "description": "string",
      "assigned_agent": "string",
      "input_contract": {},
      "output_contract": {},
      "dependencies": ["task_id"],
      "estimated_tokens": number,
      "can_parallelize": boolean
    }
  ],
  "risks": ["string describing specific risks"],
  "escalation_triggers": ["condition that should trigger human review"]
}

## RULES

1. If the task is simple, has no internal parallelism, or decomposition overhead exceeds 30% of total cost, recommend "keep_whole".
2. If decomposition enables parallel execution that reduces latency by more than 40%, recommend "decompose".
3. If the context budget is insufficient for all sub-tasks, flag this in risks and recommend "keep_whole" or reduce sub-task count.
4. If [RISK_LEVEL] is "high" or "critical", require at least one escalation trigger.
5. Every sub-task must have a clear input/output contract and an assigned agent from [AGENT_CAPABILITIES].
6. Do not create sub-tasks that have no agent capable of executing them.
7. If confidence is below 0.7, include specific uncertainty markers in the reasoning field.

## EXAMPLES

[EXAMPLES]

Return only the JSON object. Do not include any text outside the JSON.

To adapt this template for your system, replace each square-bracket placeholder with values from your orchestration context. The [AGENT_CAPABILITIES] placeholder should contain a structured description of available agents, their skills, and current load. The [CONSTRAINTS] field is where you inject policy rules such as "never send PII to external agents" or "financial calculations require dual-agent verification." The [EXAMPLES] placeholder is optional but strongly recommended for few-shot conditioning—include at least two examples showing correct decomposition and one showing a correct keep-whole decision. After the model returns the JSON, validate it against the schema before using the sub_tasks array to dispatch work. If the confidence field is below your system's threshold, route the recommendation to a human reviewer or a supervisor agent before execution.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Task Granularity Optimization Prompt Template. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to check that the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[TASK_DESCRIPTION]

The full natural-language description of the complex task to be analyzed for granularity optimization

Generate a quarterly compliance report for all EU subsidiaries, including risk scores, remediation plans, and executive summary

Must be non-empty and contain a verb phrase. Reject if length < 20 characters or contains only a noun phrase.

[AVAILABLE_AGENTS]

List of specialized agents with their capabilities, context window limits, and per-call cost estimates

Agent A: legal-document-review (128k ctx, $0.03/call); Agent B: financial-analysis (64k ctx, $0.02/call)

Must be a valid JSON array of objects with name, capability, context_limit_tokens, and cost_per_call fields. Reject if empty or missing required fields.

[CONTEXT_BUDGET_TOTAL]

Total token budget available for the entire task execution across all sub-tasks

200000

Must be a positive integer. Reject if null, zero, negative, or exceeds model maximum context. Warn if < 4 * number_of_agents.

[LATENCY_BUDGET_MS]

Maximum acceptable end-to-end latency in milliseconds for the complete task

30000

Must be a positive integer. Reject if null or zero. Warn if < 1000 * estimated_sequential_steps to flag unrealistic budgets.

[PARALLELIZATION_PREFERENCE]

Boolean or enum indicating whether the system should prefer parallel execution, sequential execution, or balanced optimization

balanced

Must be one of: parallel, sequential, balanced. Reject any other value. Default to balanced if null.

[COST_BUDGET_USD]

Maximum acceptable total cost in USD for all agent calls combined

0.50

Must be a positive float. Reject if null or zero. Warn if < sum(min_cost_per_agent) to flag infeasible budgets.

[OUTPUT_SCHEMA]

Expected structure for the granularity recommendation output, defining required fields and their types

See output contract: granularity_plan with sub_tasks array, merge_strategy, cost_estimate, latency_estimate, risk_flags

Must be a valid JSON Schema object or reference to a named schema. Reject if missing required fields: sub_tasks, cost_estimate, latency_estimate.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Task Granularity Optimization prompt into an agent orchestration pipeline with validation, retries, and cost guardrails.

This prompt is designed to sit inside an agent orchestrator's planning phase, not as a standalone chat interface. It should be called before task decomposition is finalized, receiving a candidate task breakdown and returning a granularity assessment. The orchestrator should treat the output as a structured recommendation that can trigger re-decomposition, merging, or further splitting before any sub-tasks are dispatched to worker agents. Because this prompt influences resource allocation and latency, it must execute quickly and deterministically enough to avoid becoming a bottleneck in the orchestration loop.

Wire the prompt into a pre-dispatch validation step. The orchestrator sends a payload containing the proposed sub-tasks, their dependency graph, estimated token budgets, and target latency constraints. The model returns a JSON object with a granularity_score, recommendation (one of split_further, merge, keep_as_is), cost_estimate, latency_estimate, and a risks array. Validate the output schema strictly: reject any response where granularity_score is outside 0.0-1.0, where recommendation is not one of the three allowed values, or where cost_estimate and latency_estimate are missing. On validation failure, retry once with a stricter schema reminder appended to the prompt. If the retry also fails, default to keep_as_is and log the failure for offline analysis. For high-stakes workflows where over-decomposition could cause state corruption or duplicate side effects, route split_further recommendations to a human reviewer with the original task graph and the model's justification before applying the change.

Model choice matters here. Use a model with strong structured output support and low latency—this is a gating decision, not a generative task. GPT-4o or Claude 3.5 Sonnet with JSON mode enabled are good defaults. Avoid models that struggle with numeric estimates or that hallucinate schema fields. Log every granularity decision with the input task graph, the model's recommendation, the validation result, and whether the recommendation was applied or overridden. This log becomes essential for tuning the decomposition strategy over time. The most common production failure is the model recommending splits that create tasks too small to carry enough context, producing agents that fail silently. Monitor for sub-task failure rate spikes after granularity changes and set an alert if the rate exceeds a threshold within a deployment window.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the granularity recommendation output. Use this contract to parse, validate, and route the model's response before passing it to an orchestrator or human reviewer.

Field or ElementType or FormatRequiredValidation Rule

granularity_recommendation

string (enum)

Must be one of: 'keep_whole', 'split', 'merge'. Check exact string match.

confidence_score

number (0.0-1.0)

Must be a float between 0.0 and 1.0 inclusive. Reject if out of range or non-numeric.

rationale_summary

string

Must be 1-3 sentences. Reject if empty or >500 characters. No markdown allowed.

sub_tasks

array of objects

Required if recommendation is 'split'. Must be an array with 2-10 items. Reject if empty when recommendation is 'split'.

sub_tasks[].task_id

string

true (if sub_tasks present)

Must be a unique slug within the array. Format: lowercase alphanumeric with hyphens. Check for duplicates.

sub_tasks[].description

string

true (if sub_tasks present)

Must be 1-2 sentences describing the sub-task. Reject if empty or >300 characters.

sub_tasks[].estimated_latency_ms

integer

true (if sub_tasks present)

Must be a positive integer. Reject if negative or zero. Flag if >60000 for human review.

sub_tasks[].estimated_cost_tokens

integer

true (if sub_tasks present)

Must be a positive integer. Reject if negative or zero. Flag if >16000 for budget review.

sub_tasks[].context_budget_tokens

integer

true (if sub_tasks present)

Must be a positive integer. Sum of all sub-task budgets must not exceed [MAX_CONTEXT_WINDOW]. Reject if exceeded.

sub_tasks[].parallelizable

boolean

true (if sub_tasks present)

Must be true or false. Reject if string, null, or missing.

sub_tasks[].depends_on

array of strings

If present, each string must match a task_id in the sub_tasks array. Reject if referencing non-existent task_id.

overhead_analysis

object

Must contain 'coordination_cost_tokens' and 'context_duplication_tokens' as positive integers. Reject if missing fields.

overhead_analysis.coordination_cost_tokens

integer

Must be a positive integer. Flag if >5000 for high-overhead alert.

overhead_analysis.context_duplication_tokens

integer

Must be a positive integer. Flag if >[MAX_CONTEXT_WINDOW] * 0.3 for duplication risk.

risk_flags

array of strings

If present, each string must be from allowed set: 'over_decomposition', 'under_decomposition', 'context_exhaustion', 'dependency_cycle', 'resource_contention'. Reject unknown flags.

alternative_recommendation

object

If present, must contain 'recommendation' and 'rationale_summary' fields with same rules as top-level fields. Used for runner-up option.

PRACTICAL GUARDRAILS

Common Failure Modes

Task granularity optimization fails in predictable ways. These are the most common failure modes when deciding whether to split a task further or keep it whole, with concrete guardrails to catch them before they reach production.

01

Over-Decomposition into Trivial Sub-Tasks

What to watch: The optimizer splits a task into sub-tasks so small that orchestration overhead exceeds execution cost. Each sub-task requires a full context window, handoff serialization, and validation, but the actual work is a single trivial operation. Guardrail: Set a minimum estimated compute threshold per sub-task. If a proposed sub-task's estimated work is below the orchestration cost floor, reject the split and keep the work merged.

02

Under-Decomposition of Bottleneck Tasks

What to watch: A large, sequential task is kept whole when it could be parallelized, creating a latency bottleneck that blocks downstream agents. The optimizer underestimates the parallelism opportunity because it focuses on logical cohesion rather than execution time. Guardrail: Require latency estimates for each proposed sub-task and flag any single sub-task whose estimated duration exceeds a configurable fraction of the total workflow budget. Force re-evaluation of parallelization for flagged tasks.

03

Context Budget Exhaustion from Excessive Splits

What to watch: Each sub-task receives a context package with overlapping instructions, shared state, and handoff metadata. When too many sub-tasks are created, the cumulative context budget across agents exceeds the available token limit, causing truncation or incomplete execution. Guardrail: Implement a context budget allocator that sums projected token usage across all sub-tasks before dispatch. If the total exceeds the budget, force consolidation of the most context-heavy sub-tasks or apply compression before splitting further.

04

Dependency Chain Fragility from Fine-Grained Splits

What to watch: Fine-grained decomposition creates long dependency chains where each sub-task depends on the exact output of the previous one. A single sub-task failure or unexpected output shape cascades through the entire chain, requiring full re-execution. Guardrail: Limit dependency chain depth to a configurable maximum. When a proposed decomposition exceeds the limit, require intermediate merge points or checkpoints that can serve as recovery boundaries, reducing blast radius on failure.

05

Cost Estimation Drift Between Plan and Execution

What to watch: The granularity optimizer produces cost estimates that are systematically optimistic, ignoring handoff serialization costs, retry overhead, and validation compute. Actual execution costs exceed estimates by 2-5x, making the decomposition economically worse than a single-agent approach. Guardrail: Track estimation accuracy over time by comparing planned vs. actual costs per sub-task. If drift exceeds a threshold, apply a calibrated overhead multiplier to future estimates or trigger re-decomposition with corrected cost models.

06

Semantic Coherence Loss Across Split Boundaries

What to watch: A task that requires cross-cutting reasoning is split along structural boundaries that break semantic coherence. Each sub-agent solves its piece correctly but the combined output is inconsistent, contradictory, or misses cross-cutting constraints that no single sub-task owned. Guardrail: After decomposition, run a cross-task coherence check that validates the combined outputs against the original request's holistic constraints. If coherence violations are detected, merge the conflicting sub-tasks or add a reconciliation step before final output assembly.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of a task granularity optimization output before integrating it into an agent orchestration pipeline. Each criterion targets a specific failure mode common in decomposition decisions.

CriterionPass StandardFailure SignalTest Method

Granularity Balance

Each sub-task is the smallest unit of work that can be independently assigned, executed, and validated without requiring further decomposition for clarity.

Output contains a sub-task described as 'process the data' or 'handle the request' without a specific input/output contract.

Manual review: For each proposed sub-task, ask 'Can a single agent execute this with only the provided context?' If no, it is under-decomposed.

Over-Decomposition Check

No sub-task exists solely to pass a value from one step to another without transformation, validation, or a decision boundary.

Output includes a sub-task like 'Send result X to Agent Y' as a distinct step with no logic applied.

Automated check: Count sub-tasks that have zero transformation steps in their description. Flag any count greater than zero.

Cost Estimate Reasonableness

Estimated token cost and latency for each sub-task fall within the provided [BUDGET_CONSTRAINTS] and are justified by the task's complexity.

A sub-task labeled 'simple extraction' is estimated to consume 50% of the total context budget.

Schema check: Parse cost estimates. Assert each estimate is less than [MAX_PER_TASK_BUDGET]. Flag violations for human review.

Dependency Validity

All declared dependencies reference sub-task IDs that exist in the plan and produce the required output field as defined in their contract.

A sub-task declares a dependency on 'customer_sentiment_score' but no prior sub-task outputs that field.

Automated graph check: Build a dependency graph from the output. Assert all referenced inputs exist as outputs of prior tasks.

Context Budget Adherence

The sum of estimated context windows for all parallel execution groups does not exceed the total [CONTEXT_BUDGET] at any point.

The plan schedules three parallel sub-tasks each requiring 40% of the context budget.

Automated calculation: Group sub-tasks by parallel execution phase. Sum max(context_estimate) per phase. Assert total <= [CONTEXT_BUDGET].

Parallelization Safety

Sub-tasks marked for parallel execution have no write-write or read-write conflicts on shared state or resources.

Two parallel sub-tasks are both instructed to update a shared 'user_profile' object.

Static analysis: For each parallel group, compare output write targets. Flag any overlap as a conflict. Require explicit lock or merge strategy.

Contract Completeness

Every sub-task has a defined [OUTPUT_SCHEMA] with required fields, types, and validation rules before execution.

A sub-task output is described as 'the analysis results' with no schema.

Schema parse check: Attempt to validate a mock output against the provided schema. Fail if schema is missing or unparseable.

Escalation Path Definition

Every sub-task with a confidence score below [CONFIDENCE_THRESHOLD] has a defined escalation target or re-decomposition strategy.

A sub-task with confidence 0.4 has no fallback agent or human review flag.

Threshold scan: Filter sub-tasks where confidence < [CONFIDENCE_THRESHOLD]. Assert each has a non-null escalation_target field.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base template with a frontier model and manual review of each recommendation. Remove the cost estimation fields and focus on the decomposition logic. Replace [COST_MODEL] with a simple qualitative label (low/medium/high).

Watch for

  • Over-decomposition of simple tasks into too many sub-tasks
  • Missing the context budget impact when splitting
  • No validation of dependency chains between proposed sub-tasks
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.