Inferensys

Prompt

Cost Attribution for Agent Loops Prompt Template

A practical prompt playbook for using Cost Attribution for Agent Loops Prompt Template in production AI workflows.
Developer reviewing multi-agent chat interface on laptop, agent conversation logs visible, casual coding session at WeWork desk.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Cost Attribution for Agent Loops prompt.

This prompt is designed for agent developers and AI infrastructure engineers who need to understand the cost dynamics of multi-step autonomous workflows. The core job-to-be-done is tracing token consumption and compute cost back to individual iterations of an agent loop, identifying which steps drove the most spend and whether the agent exceeded its planned step budget. You should use this prompt when you have access to production trace data—specifically spans that capture model inference, tool calls, and step boundaries—and you need a structured, loop-level cost attribution report rather than a flat per-request summary.

The ideal user is someone who can query an observability backend (such as LangSmith, Arize, or a custom trace store) and feed a structured trace object into the prompt. Required context includes the agent's step budget, the cost-per-token rates for the models used, and the raw trace spans with their parent step identifiers. This prompt is not a replacement for real-time cost monitoring dashboards; it is a diagnostic tool for offline analysis of completed traces. Do not use it when you lack reliable step-boundary metadata in your traces, or when the agent's execution model does not produce discrete, numbered iterations—without clear loop boundaries, the attribution will be misleading.

Before running this prompt, ensure your trace data includes step_id or equivalent parent span identifiers, token counts per span, and model identifiers. If your traces are missing these fields, invest in instrumentation first. The output is a structured cost breakdown, not a real-time alert; pair it with a separate monitoring system for production guardrails. For high-cost or customer-facing agents, always review the output for unproductive loops—iterations that consumed tokens without advancing the task—and use the findings to tighten step budgets, improve tool descriptions, or add early-exit conditions to your agent logic.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Cost Attribution for Agent Loops prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your trace analysis workflow before wiring it into production.

01

Good Fit: Multi-Step Agent Traces

Use when: you have production traces from autonomous agents that execute tool calls, retrieval steps, and reasoning loops across multiple iterations. Why: the prompt is designed to reconstruct loop boundaries, attribute tokens and cost per iteration, and flag iterations that exceeded step budgets or entered unproductive cycles. Works best when traces include span-level metadata with step counts, token counts, and tool-call identifiers.

02

Bad Fit: Single-Step or Stateless Calls

Avoid when: analyzing traces from single-turn completions, stateless chat responses, or pipelines without iterative tool use. Why: the prompt expects loop structures with iteration boundaries. Applying it to flat traces produces meaningless loop counts, misattributed costs, and false positives for unproductive cycles. Use a per-request cost attribution prompt instead.

03

Required Inputs

Must have: trace spans with iteration_id, step_count, token_count (input and output), tool_call_name, duration_ms, and cost_per_token or a model pricing table. Without these: the prompt cannot reconstruct loop boundaries or attribute costs accurately. Guardrail: validate trace schema completeness before invoking the prompt. Reject traces missing iteration identifiers and emit a schema gap report instead of guessing.

04

Operational Risk: Phantom Loops

What to watch: the model may invent loop boundaries when iteration metadata is ambiguous or missing, creating phantom loops that inflate cost estimates. Guardrail: require the prompt to output a confidence field per loop and flag any loop with confidence below 0.8 for human review. Cross-reference loop counts against known agent step limits before accepting the output.

05

Operational Risk: Cost Calculation Drift

What to watch: token-to-cost conversion depends on model pricing tables that change over time. Stale pricing data produces inaccurate cost attribution. Guardrail: pass the pricing table as a structured input parameter rather than hardcoding it in the prompt. Version the pricing table and include a pricing_effective_date field in the output so reviewers can detect stale conversions.

06

Operational Risk: Unproductive Cycle False Positives

What to watch: the prompt may flag loops as unproductive when the agent legitimately retried a failed tool call or waited for an external system. Guardrail: require the prompt to distinguish between retry loops (productive recovery) and true unproductive cycles (no state change, no tool output consumed). Include a cycle_classification field with values productive, retry_recovery, or unproductive and route unproductive flags for human review before triggering cost alerts.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for attributing token consumption and cost to individual iterations within an agent loop trace.

This prompt template is designed to analyze a multi-step agent trace and produce a loop-level cost attribution report. It takes raw trace spans—including model inferences, tool calls, and metadata—and breaks down token consumption and estimated cost for each iteration of the agent's reasoning loop. The output is a structured table that highlights iterations exceeding planned step budgets or entering unproductive cycles, enabling FinOps and engineering teams to pinpoint cost drivers in autonomous workflows.

text
You are an AI cost analyst reviewing a production trace from an autonomous agent loop. Your task is to attribute token consumption and cost to each iteration of the agent's reasoning cycle.

## INPUT
[AGENT_TRACE]

## CONSTRAINTS
- Analyze the trace as a sequence of iterations. An iteration is defined by a complete cycle of: model reasoning → tool call(s) → tool response(s) → model reasoning.
- For each iteration, calculate:
  - `iteration_number`: The 1-based index of the loop.
  - `model_input_tokens`: Total tokens in the model request (system prompt + context + tool results).
  - `model_output_tokens`: Tokens generated by the model (reasoning + tool call arguments).
  - `tool_call_count`: Number of distinct tool invocations in this iteration.
  - `tool_output_tokens`: Total tokens returned by all tool calls in this iteration.
  - `total_tokens`: Sum of input, output, and tool output tokens.
  - `estimated_cost_usd`: Cost calculated using the pricing model specified in [PRICING_MODEL].
  - `planned_step_budget`: The expected step budget for this task from [PLANNED_BUDGET].
  - `budget_status`: `within_budget` if iteration_number <= planned_step_budget, `over_budget` otherwise.
  - `cycle_assessment`: `productive` if the iteration made observable progress toward the goal, `unproductive` if it repeated actions, corrected itself without progress, or looped without new information.
- Flag any iteration where `cycle_assessment` is `unproductive` AND `budget_status` is `over_budget` as a `critical_cost_risk`.
- If the trace contains no clear iteration boundaries, state that attribution is not possible and explain why.

## OUTPUT_SCHEMA
Return a JSON object with the following structure:
{
  "trace_id": "string",
  "total_iterations": number,
  "total_cost_usd": number,
  "planned_budget_steps": number,
  "budget_compliance": "within_budget" | "over_budget",
  "critical_cost_risks": number,
  "iterations": [
    {
      "iteration_number": number,
      "model_input_tokens": number,
      "model_output_tokens": number,
      "tool_call_count": number,
      "tool_output_tokens": number,
      "total_tokens": number,
      "estimated_cost_usd": number,
      "budget_status": "within_budget" | "over_budget",
      "cycle_assessment": "productive" | "unproductive",
      "assessment_rationale": "string"
    }
  ],
  "summary": "string"
}

## PRICING_MODEL
[PRICING_MODEL]

## PLANNED_BUDGET
[PLANNED_BUDGET]

## EXAMPLES
[EXAMPLES]

## RISK_LEVEL
[RISK_LEVEL]

To adapt this template, replace the square-bracket placeholders with concrete values. [AGENT_TRACE] should contain the raw trace data, typically in JSON or a structured log format that captures model requests, responses, and tool call spans with token counts. [PRICING_MODEL] must specify the per-token or per-request pricing for each model involved (e.g., gpt-4o: $2.50/1M input tokens, $10.00/1M output tokens). [PLANNED_BUDGET] is the expected maximum number of iterations for the task, drawn from your agent's design specification or runbook. [EXAMPLES] should include one or two annotated trace snippets with correct cost attributions to guide the model's output format and judgment. [RISK_LEVEL] should be set to high if the cost data will be used for financial reporting or departmental chargeback, triggering additional validation requirements.

Before deploying this prompt, validate the output against a golden set of manually annotated traces to ensure iteration boundary detection and cost calculations are accurate. For high-risk financial workflows, route outputs through a human review step before ingestion into billing systems. Common failure modes include misidentifying iteration boundaries when tool calls are asynchronous or overlapping, applying incorrect pricing when multiple models are used in a single trace, and classifying self-correction steps as unproductive when they were necessary for task completion. Test with traces that contain parallel tool calls, empty tool responses, and edge cases where the agent terminates early or exceeds the planned budget by a wide margin.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Cost Attribution for Agent Loops prompt. Each placeholder must be populated from production trace data before the prompt is executed. Missing or malformed inputs will cause the prompt to hallucinate costs or misattribute loop boundaries.

PlaceholderPurposeExampleValidation Notes

[TRACE_SPANS]

Complete array of trace spans from a single agent session, including span_id, parent_span_id, operation_name, start_time, end_time, and token counts

JSON array of OpenTelemetry-compatible span objects with model.usage and tool.call attributes

Validate JSON parse succeeds. Check that span_id and parent_span_id fields are present and non-null. Reject if fewer than 2 spans exist.

[LOOP_IDENTIFIER_FIELD]

Field name used to group spans into logical loops or iterations within the agent trace

iteration_id

Must be a string matching a field present in every span. Validate field existence across all spans. Reject if field is missing in more than 10% of spans.

[TOKEN_COST_RATES]

Cost per 1K tokens for each model endpoint used in the trace, keyed by model name

{"gpt-4o": {"input": 0.0025, "output": 0.01}, "claude-3-opus": {"input": 0.015, "output": 0.075}}

Validate JSON parse succeeds. Check that every model referenced in [TRACE_SPANS] has a corresponding rate entry. Reject if any model is missing a rate.

[STEP_BUDGET_PER_LOOP]

Maximum expected number of tool-call or reasoning steps per loop before flagging as over-budget

5

Must be a positive integer. Validate type check. Warn if value is 0 or exceeds 50 without explicit justification.

[UNPRODUCTIVE_CYCLE_THRESHOLD]

Number of consecutive loops with no state change or new information before flagging as unproductive

3

Must be a positive integer. Validate type check. Recommend default of 3 if not specified. Reject if value is 0.

[OUTPUT_SCHEMA]

Expected JSON schema for the cost attribution report, defining loop-level fields and types

{"type": "object", "properties": {"loop_id": {"type": "string"}, "tokens_in": {"type": "integer"}, "tokens_out": {"type": "integer"}, "cost": {"type": "number"}, "steps": {"type": "integer"}, "over_budget": {"type": "boolean"}, "unproductive": {"type": "boolean"}}}

Validate JSON parse succeeds. Check that required fields include loop_id, cost, and at least one boolean flag field. Reject if schema is not valid JSON Schema draft-07 or later.

[CURRENCY]

ISO 4217 currency code for cost reporting

USD

Must be a valid 3-letter ISO 4217 code. Validate against known currency list. Default to USD if null or missing. Reject if value is not a string.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the cost attribution prompt into an observability pipeline with validation, retries, and actionable outputs.

The Cost Attribution for Agent Loops prompt is designed to operate on structured trace data, not raw log streams. Before calling the prompt, extract the relevant spans from your observability store (e.g., LangSmith, Arize, Datadog LLM Observability, or a custom trace database). Filter traces to isolate a single agent session, then serialize the loop iterations as a JSON array where each element contains: loop_id, step_number, model (with provider and version), prompt_tokens, completion_tokens, tool_call_tokens (if tracked separately), latency_ms, tool_calls_made (array of tool names), and step_outcome (completed, failed, timed_out, retried). The prompt expects this as the [TRACE_DATA] input. If your observability platform does not natively track cost, precompute cost estimates using your provider's published pricing per 1K tokens before passing data to the prompt—the model should not be asked to memorize or guess pricing tables.

Wire the prompt into a batch analysis job or an on-demand diagnostic endpoint. For batch use, run the prompt nightly against sessions that exceeded a step-count threshold (e.g., more than 10 agent iterations) or a cost threshold (e.g., sessions above $2.00). For on-demand use, expose it behind an internal tool that accepts a session_id or trace_id, fetches the relevant spans, assembles the [TRACE_DATA] payload, and calls the LLM. Validate the output against a JSON schema that requires: a loops array with loop_id, total_tokens, total_cost, step_count, exceeded_budget (boolean), unproductive_cycles (array of step ranges), and cost_per_step; plus a summary object with total_session_cost, loops_over_budget, estimated_waste, and recommendations (array of strings). If validation fails, retry once with the validation error message appended to [CONSTRAINTS]. If the second attempt also fails, log the raw response and alert the on-call channel with the trace ID for manual review.

Model choice matters here. Use a model with strong structured output support (GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro) and enable structured output mode or function calling to enforce the schema. Avoid models smaller than ~70B parameters for this task—the prompt requires cross-loop comparison, budget arithmetic, and pattern recognition that smaller models handle unreliably. Set temperature=0 to maximize consistency across runs. For high-volume environments, consider caching the prompt prefix (the instructions and schema are static) to reduce per-request cost. If your agent runs hundreds of sessions daily, sample the top 5% by cost or step count rather than analyzing every session—this catches the expensive outliers without overwhelming your analysis budget.

The output of this prompt should feed directly into your FinOps dashboard and your agent reliability monitoring. Pipe loops_over_budget and estimated_waste into cost-tracking metrics. Route unproductive_cycles to the agent engineering team as candidate loops for step-limit tightening or early-termination rules. Flag any session where exceeded_budget is true and unproductive_cycles contains more than two entries for immediate human review—these are likely agent loops that entered a degenerate state. Do not use this prompt's output to automatically modify agent configurations in production; the cost attribution is diagnostic, not prescriptive. Human review is required before adjusting step budgets, tool timeout thresholds, or loop-termination policies based on these findings.

IMPLEMENTATION TABLE

Expected Output Contract

The prompt must return a structured JSON object. Validate each field before ingesting the output into cost dashboards or alerting systems.

Field or ElementType or FormatRequiredValidation Rule

loop_attribution

Array of objects

Must be a non-empty array. Each object must match the loop_entry schema.

loop_entry.iteration_id

String

Must match the iteration identifier from the input trace span. Regex: ^[a-zA-Z0-9_-]+$

loop_entry.start_timestamp

ISO 8601 datetime

Must parse as a valid datetime. Must be before or equal to loop_entry.end_timestamp.

loop_entry.end_timestamp

ISO 8601 datetime

Must parse as a valid datetime. Must be after or equal to loop_entry.start_timestamp.

loop_entry.total_tokens

Integer

Must be a non-negative integer. Sum of input_tokens and output_tokens for the iteration.

loop_entry.cost_estimate

Number (float)

Must be a non-negative float. Validate against a known cost-per-token rate for the model_id used.

loop_entry.exceeded_step_budget

Boolean

Must be true if the iteration count exceeds the planned step budget defined in [PLANNED_STEP_BUDGET], otherwise false.

loop_entry.unproductive_cycle_flag

Boolean

Must be true if the iteration produced no state change, tool call result, or new information, otherwise false. Requires evidence from trace spans.

summary.total_loop_cost

Number (float)

Must equal the sum of all loop_entry.cost_estimate values. Tolerance for floating point: +/- 0.01.

PRACTICAL GUARDRAILS

Common Failure Modes

Cost attribution for agent loops fails in predictable ways. These are the most common failure modes encountered in production and the guardrails that prevent them.

01

Unbounded Loop Cost Explosion

What to watch: An agent enters a retry or self-correction cycle that consumes tokens without making progress. The cost attribution prompt reports high total cost but fails to flag that iterations 4-12 produced no state change. Guardrail: Add a step-budget constraint in the agent harness and configure the cost attribution prompt to compare iteration count against a planned maximum. Flag any loop exceeding the budget as a cost anomaly regardless of per-step token efficiency.

02

Tool Call Cost Misattribution

What to watch: The prompt attributes all cost to the model inference step and ignores the token overhead of large tool definitions, verbose schemas, or repeated function call formatting. This hides the true cost of tool-heavy agents. Guardrail: Require the prompt to separate tool definition tokens, function call formatting tokens, and tool output tokens into distinct line items. Validate that tool overhead is never zero when tools are present in the trace.

03

Context Window Accumulation Blindness

What to watch: Each loop iteration appends to the context window, causing per-step token consumption to grow silently. The cost attribution prompt reports average or total cost but misses the per-iteration growth curve. Guardrail: Instruct the prompt to output a per-iteration token delta column. Flag any iteration where token consumption increased by more than 20% over the previous step as a context accumulation warning.

04

Failed Tool Call Cost Amnesia

What to watch: The agent calls a tool that returns an error or empty result, then retries with slightly modified arguments. The cost attribution prompt counts these as normal iterations, hiding the waste from failed calls. Guardrail: Require the prompt to label each iteration with a tool-call outcome status (success, error, empty, timeout). Sum the cost of all non-success iterations separately and surface it as wasted spend.

05

Model Routing Cost Opacity

What to watch: The agent loop routes different steps to different models with different pricing. The cost attribution prompt applies a single blended rate, producing inaccurate cost figures that mislead FinOps decisions. Guardrail: Require the prompt to extract the model identifier from each trace span and apply the correct per-model pricing table. Flag any span where the model cannot be determined as unpriced and exclude it from totals with a warning.

06

Loop Termination Reason Omission

What to watch: The prompt reports cost per loop but omits why the loop ended—task complete, step budget exhausted, timeout, or explicit stop signal. Without termination context, high-cost loops that failed are indistinguishable from high-cost loops that succeeded. Guardrail: Require the prompt to include a termination reason field for every loop analyzed. Sort cost reports by termination reason so failed and timed-out loops surface first in cost investigations.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Cost Attribution for Agent Loops prompt before deploying it into a production monitoring pipeline. Each criterion targets a specific failure mode common in loop-level cost analysis.

CriterionPass StandardFailure SignalTest Method

Loop Boundary Detection

Every agent loop in the trace is identified with a unique [LOOP_ID] and correct start/end timestamps.

Loops are merged, missing, or include steps from adjacent workflows.

Inject a trace with 3 known loops and verify exactly 3 loop records are returned with non-overlapping spans.

Token Attribution Accuracy

Sum of tokens attributed to all loops equals total trace tokens within a 2% margin.

Token sum mismatch >2% or tokens attributed to 'unaccounted' category exceed threshold.

Calculate total tokens from raw trace spans and compare against sum of loop-level token fields in output.

Cost Calculation Correctness

Cost per loop matches (input_tokens * [INPUT_COST_PER_1K] + output_tokens * [OUTPUT_COST_PER_1K]) within rounding tolerance.

Cost values are zero, negative, or deviate from manual calculation by more than $0.001.

Hardcode known token counts and pricing rates in a test trace; assert output cost matches expected value exactly.

Step Budget Violation Flagging

Loops exceeding [MAX_STEPS_PER_LOOP] are flagged with exceeded_step_budget: true and a severity level.

A loop with 15 steps when budget is 10 shows exceeded_step_budget: false or is missing the field entirely.

Provide a trace with one loop at 9 steps and one at 12 steps; verify only the 12-step loop is flagged.

Unproductive Cycle Detection

Loops with repeated identical tool calls or no state change across 3+ consecutive steps are marked as unproductive_cycle: true with a pattern description.

A loop retrying the same failed tool call 5 times is not flagged, or a productive loop is incorrectly flagged.

Inject a trace with a loop containing 4 identical failed tool calls; assert unproductive_cycle: true and pattern field is populated.

Cost per Iteration Breakdown

Each iteration within a loop includes its own token count and cost, and iteration costs sum to the loop total.

Iteration-level costs are missing, or the sum of iteration costs does not equal the parent loop cost.

Parse the output and sum all iteration_cost fields within a loop; assert equality with the loop-level total_cost field.

Output Schema Compliance

Output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and correct types.

Output is missing loop_id, total_tokens, or cost fields; field types are string instead of number; JSON is malformed.

Validate output against the JSON Schema definition; reject any response that fails structural validation.

Anomaly Severity Classification

Loops with cost or step anomalies receive a severity of low, medium, high, or critical based on defined thresholds.

A loop consuming 10x the average cost is classified as low severity, or severity field is null for anomalous loops.

Provide traces with known cost multipliers (2x, 5x, 10x, 20x average); assert severity escalates correctly per threshold config.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single trace file. Remove strict schema requirements initially—ask for a markdown table instead of JSON. Use a smaller sample of loop iterations (e.g., first 10 steps) to validate the attribution logic before scaling.

code
Analyze the following agent trace and produce a loop-level cost breakdown as a markdown table. Include iteration number, tokens consumed, estimated cost, and whether the loop exceeded [STEP_BUDGET] steps.

[TRACE_JSON]

Watch for

  • The model conflating tool-call tokens with output tokens
  • Missing cost estimates when pricing data isn't embedded in the trace
  • Overly broad summaries that skip per-iteration detail
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.