This prompt is designed for platform operators and AI cost engineers who need to generate a structured, per-session or per-task resource consumption report from raw agent execution traces. It takes a trace log containing token counts, tool call metadata, latency measurements, and session identifiers, and produces a summary with total tokens consumed, tool calls broken down by type, cumulative latency, estimated cost, and attribution to the correct session. Use this when you need to feed consumption data into internal dashboards, chargeback systems, or cost optimization reviews.
Prompt
Agent Resource Consumption Summary Prompt Template

When to Use This Prompt
Defines the ideal use case, required inputs, and operational boundaries for the Agent Resource Consumption Summary prompt.
The ideal input is a structured trace log, not a raw stream of unstructured events. The prompt expects fields like session_id, timestamp, tool_name, tokens_in, tokens_out, latency_ms, and model_id to be present and normalized before the prompt is invoked. If your traces are missing these fields, you must pre-process them. The prompt will not reliably infer missing identifiers or correct inconsistent timestamp formats. For high-stakes financial reporting, always validate the output against a known source of truth, such as your model provider's official usage dashboard, before feeding it into a chargeback pipeline.
Do not use this prompt for real-time budget enforcement during active agent execution; it is a post-hoc reporting tool, not an in-line circuit breaker. It is also unsuitable for generating per-user invoices that require legal-grade accuracy without human review. If you are operating in a multi-tenant environment where session IDs could collide across organizations, ensure your trace data includes a tenant identifier and that the prompt's attribution logic is tested against cross-tenant contamination scenarios. The next section provides the copy-ready template you can adapt to your specific trace schema and cost model.
Use Case Fit
Where the Agent Resource Consumption Summary prompt template delivers reliable value and where it introduces operational risk.
Good Fit: Post-Session Cost Attribution
Use when: you need a structured, per-session summary of tokens, tool calls, latency, and estimated cost for chargebacks or usage audits. Guardrail: ensure the agent execution trace is complete and immutable before invoking the summary prompt.
Bad Fit: Real-Time Budget Enforcement
Avoid when: you need to stop an agent mid-execution before it exceeds a spend cap. This prompt summarizes after the fact. Guardrail: pair this with a pre-execution budget allocation prompt or a circuit breaker that checks spend between tool calls.
Required Input: Structured Execution Trace
Risk: the prompt hallucinates costs or misses tool calls if fed unstructured logs or incomplete traces. Guardrail: provide a strict JSON trace schema with tool name, tokens consumed, latency, and cost per call. Validate the trace before summarization.
Operational Risk: Concurrent Session Attribution
Risk: cost attribution errors when multiple agent sessions share a user or tenant ID and traces are not properly segmented. Guardrail: require a unique session identifier in the trace input and validate that the summary output references only that session's calls.
Good Fit: Multi-Tenant Chargeback Reports
Use when: platform operators need to generate per-tenant usage summaries for billing or internal cost allocation. Guardrail: include tenant metadata in the trace input and verify that the summary output correctly isolates tenant-level aggregates.
Bad Fit: Unpriced or Custom Tool Calls
Avoid when: tool costs are not known in advance or depend on dynamic pricing that the trace does not capture. Guardrail: if cost metadata is missing, the prompt should flag the gap rather than estimating. Require a cost lookup step before summarization.
Copy-Ready Prompt Template
Paste this prompt and replace the square-bracket placeholders with your trace data and pricing configuration.
This template instructs the model to produce a structured resource consumption summary from raw agent execution traces. It is designed for platform operators who need per-session or per-task reports that attribute token usage, tool calls, latency, and estimated cost to specific agent actions. The prompt enforces a strict output schema so the summary can be ingested directly into billing systems, cost dashboards, or audit logs without manual reformatting.
textYou are an AI cost auditor. Generate a resource consumption summary from the agent trace data and pricing configuration provided below. [TRACE_DATA] [PRICING_CONFIG] [OUTPUT_SCHEMA] [CONSTRAINTS] [EXAMPLES]
Replace each placeholder with your operational data. [TRACE_DATA] should contain the raw execution log, including timestamps, model names, token counts, tool names, and call durations. [PRICING_CONFIG] must specify per-token and per-call costs for each model and tool in the trace. [OUTPUT_SCHEMA] defines the exact JSON structure you expect—include fields for session_id, total_tokens, total_tool_calls, total_latency_ms, estimated_cost, and a line_items array with per-action attribution. [CONSTRAINTS] should list rules such as rounding precision, currency format, and how to handle missing pricing data. [EXAMPLES] should contain one or two correct input-output pairs to anchor the model's behavior.
Before wiring this into production, validate the output against your schema in a test harness. Common failure modes include misattributing tool calls to the wrong session when traces contain interleaved concurrent sessions, double-counting tokens when a tool call's prompt and completion are logged separately, and applying incorrect pricing tiers when models have graduated rates. Run the prompt against at least 20 real production traces and compare the summaries to your existing cost accounting. If the variance exceeds 2%, add more explicit attribution rules to [CONSTRAINTS] and retest. For high-stakes billing workflows, always route summaries with cost anomalies above a threshold to a human reviewer before they reach downstream systems.
Prompt Variables
Define these variables before invoking the prompt. Each placeholder must be populated with concrete values from your agent execution trace, cost ledger, or platform configuration. Missing or null variables will cause the prompt to hallucinate costs or omit critical attribution data.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[SESSION_ID] | Unique identifier for the agent session or task run being summarized | sess_9a4b2c_2026-01-15 | Must match the session key in your trace store. Reject if null or empty string. |
[TOOL_CALL_LOG] | Structured array of tool invocations with name, arguments, start_time, end_time, status, and token counts | [{"tool":"search","start":"2026-01-15T10:03:00Z","end":"2026-01-15T10:03:02Z","status":"success","tokens_in":120,"tokens_out":340}] | Validate JSON schema before insertion. Each record must have non-null tool name and timestamps. Reject if array is empty without explicit empty-session flag. |
[TOKEN_USAGE] | Total input and output tokens consumed across the session, including tool call overhead | {"input": 4520, "output": 12800, "cache_read": 2100, "cache_write": 0} | Must be a valid object with numeric input and output fields. Cache fields optional but recommended. Reject if input or output is negative or exceeds platform maximum. |
[COST_RATES] | Per-model and per-tool pricing map used to calculate estimated cost | {"gpt-4o": {"input_per_1k": 0.0025, "output_per_1k": 0.01}, "search_tool": {"per_call": 0.005}} | Validate that all models and tools referenced in [TOOL_CALL_LOG] have corresponding rate entries. Missing rates produce incomplete cost summaries. Reject if rates are zero without explicit free-tier flag. |
[LATENCY_MS] | Total wall-clock latency for the session in milliseconds | 18450 | Must be a positive integer. Reject if negative or zero. Compare against sum of tool call durations to detect measurement gaps. |
[CONCURRENT_SESSIONS] | Number of other agent sessions running concurrently that share the same cost center or rate limit pool | 3 | Must be a non-negative integer. Used for attribution accuracy. Set to 0 if session was isolated. Reject if null. |
[COST_CENTER_TAG] | Chargeback or attribution label for the team, project, or customer responsible for this session | "customer-success-prod" | Must be a non-empty string matching your cost allocation taxonomy. Reject if null or whitespace-only. Mismatched tags cause billing attribution errors. |
Implementation Harness Notes
How to wire the Agent Resource Consumption Summary prompt into an application or workflow.
This prompt is designed to be called at the end of an agent session or task, consuming structured trace data to produce a human-readable and machine-parseable summary. The primary integration point is your agent framework's on_session_end or on_task_complete hook. You will need to aggregate raw telemetry—token counts, tool call records with timestamps and latency, and any cost metadata—into a structured [TRACE_DATA] object before invoking the model. Do not pass raw log lines; the prompt expects pre-aggregated fields to minimize token waste and hallucination risk.
Input assembly: Build [TRACE_DATA] as a JSON object containing session_id, start_time, end_time, models_used (array of {model_name, total_prompt_tokens, total_completion_tokens, estimated_cost}), tool_calls (array of {tool_name, call_count, total_latency_ms, total_tokens, estimated_cost}), and rate_limit_events (array of {tool_name, retry_count, total_wait_ms}). If your platform uses per-call pricing, pre-calculate estimated_cost fields before prompt assembly. For multi-tenant systems, include a tenant_id or chargeback_tag in the trace object. Validation gate: Before calling the LLM, validate that total_tokens across models and tools sums to a non-zero value and that start_time precedes end_time. Reject malformed traces with a structured error rather than asking the model to fix them.
Model choice and output handling: Use a fast, cost-efficient model (e.g., GPT-4o-mini, Claude Haiku) for this summarization task—the reasoning demand is low, and you want to avoid spending significant compute on cost reporting. Set temperature=0 to ensure deterministic output. Request a JSON output mode with a strict schema. After receiving the response, validate that total_cost in the summary matches the sum of estimated_cost fields from your input trace within a 1% tolerance. If validation fails, log the mismatch, append the validator error to [TRACE_DATA], and retry once. If the retry also fails, emit a partial summary with a validation_warning flag set to true and route for human review. Logging: Store the raw trace, the generated summary, and the validation result in your observability platform for audit and spend anomaly detection.
Multi-session and concurrency considerations: When summarizing across concurrent agent sessions, ensure each session's trace is isolated by session_id. Do not batch multiple sessions into a single prompt call unless you explicitly include a sessions array in [TRACE_DATA] and adjust the output schema to produce per-session summaries. For high-throughput systems, consider asynchronous generation: enqueue completed traces to a summary worker pool, generate summaries out-of-band, and store results for later retrieval. This avoids adding LLM latency to the user-facing session close path. What to avoid: Never pass raw API response logs or unaggregated event streams as [TRACE_DATA]; the model will miscount tokens, hallucinate costs, or miss rate-limit events. Always pre-compute aggregates in your application layer before prompt assembly.
Expected Output Contract
Fields and validation rules for the structured resource consumption summary produced by the prompt. Use this contract to parse, validate, and store the output in downstream cost dashboards or billing systems.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
session_id | string (UUID v4) | Must match the [SESSION_ID] input exactly. Reject on mismatch or missing field. | |
report_period | ISO 8601 interval (start/end) | Start must be before end. Duration must not exceed [MAX_REPORT_WINDOW_HOURS]. | |
total_tokens | object { input: int, output: int, total: int } | total must equal input + output. All values must be non-negative integers. Reject if total > [MAX_EXPECTED_TOKENS]. | |
tool_calls | array of objects | Each object must include tool_name (string), call_count (int >= 0), total_latency_ms (int >= 0), estimated_cost (float >= 0). Array may be empty but must not be null. | |
estimated_total_cost | float (USD) | Must be >= 0. Must equal sum of tool_calls[].estimated_cost plus token cost estimate. Reject if deviation > 0.01. | |
rate_limit_events | array of objects | If present, each object must include tool_name (string), retry_after_seconds (int >= 0), timestamp (ISO 8601). Null allowed if no rate limits encountered. | |
attribution_tags | object (string key-value pairs) | Keys must match [ATTRIBUTION_TAG_KEYS] if provided. Values must be strings. Null allowed. Reject unknown keys if strict mode enabled. | |
completeness_score | float between 0.0 and 1.0 | Self-reported estimate of data completeness. Reject if outside [0.0, 1.0]. Flag for human review if < [COMPLETENESS_THRESHOLD]. |
Common Failure Modes
Resource consumption summaries fail when attribution is wrong, costs are incomplete, or concurrent sessions bleed into each other. These are the most common production failure modes and how to prevent them.
Cross-Session Cost Contamination
What to watch: When multiple agent sessions share infrastructure, tool call costs and token usage from one session leak into another's summary. This produces inflated or deflated per-task cost reports that mislead budgeting decisions. Guardrail: Require explicit session ID tagging on every tool call and token count. Validate that all logged events in the summary window match the target session ID before aggregation.
Missing Tool Call Cost Attribution
What to watch: Some tool providers don't return cost metadata, or the agent invokes tools through a proxy that strips pricing headers. The summary silently undercounts actual spend, making cost reports unreliable for chargebacks. Guardrail: Maintain a cost lookup table for all registered tools with default per-call estimates. Flag any tool call without confirmed cost metadata as 'estimated' in the summary output.
Token Counting Drift Across Model Versions
What to watch: Tokenizers change between model versions, so token counts reported by the API may not match the cost calculation basis used in your billing system. Summaries become inconsistent when models are upgraded mid-session. Guardrail: Record the model version and tokenizer identifier alongside every token count. Recalculate costs using the billing system's tokenizer, not the model's reported count, when discrepancies exceed 5%.
Latency Attribution Without Causality
What to watch: Summaries that report total latency without breaking it down by tool, model inference, and network round-trip time hide the real bottleneck. Operators optimize the wrong component. Guardrail: Require structured latency spans with start timestamps, end timestamps, and a category tag for each segment. The summary must include a breakdown table, not just a single duration number.
Incomplete Session Boundary Detection
What to watch: Long-running agent sessions with pauses, reconnections, or async callbacks produce fragmented logs. The summary generator picks an arbitrary cutoff and misses tool calls that complete after the summary window closes. Guardrail: Define explicit session lifecycle events. The summary must only finalize after receiving a session-closed signal or after a configurable quiet period with no pending tool calls.
Cost Estimation for Cached vs. Uncached Calls
What to watch: Many model providers charge differently for cached prompts versus fresh inference. A summary that applies a flat rate to all tokens overcharges or undercharges depending on cache hit ratios. Guardrail: Capture cache hit metadata from API responses. Apply the correct pricing tier in the summary calculation and surface cache hit rate as a separate metric so operators can optimize prompt prefix design.
Evaluation Rubric
Use this rubric to test the Agent Resource Consumption Summary Prompt before shipping. Each criterion targets a specific failure mode observed in production resource reporting.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Token Attribution Accuracy | Total tokens reported for each agent session match the sum of per-step token counts within ±2% tolerance | Reported total differs from step-level sum by more than 2%, or tokens attributed to wrong session ID | Run 10 concurrent sessions with known token counts; compare report totals against ground-truth instrumentation logs |
Tool Call Completeness | Every tool invocation from the execution trace appears in the summary with correct tool name, count, and latency | Missing tool calls, duplicated entries, or tool names that don't match the registered tool registry | Feed a trace with 50 tool calls across 5 tools; verify 1:1 mapping between trace events and summary rows |
Cost Estimation Consistency | Estimated cost per session matches the formula: (input_tokens × [INPUT_COST_RATE]) + (output_tokens × [OUTPUT_COST_RATE]) + sum(tool_call_costs) | Cost total off by more than 5% from computed ground truth, or cost assigned to wrong cost center tag | Compute expected cost from raw token and tool data; compare against summary output for 20 sessions |
Session Boundary Integrity | Each session summary contains only events from that session; no cross-session leakage or merged sessions | Events from session A appearing in session B's summary, or two distinct sessions reported as one | Run 5 concurrent sessions with overlapping timestamps; verify each summary isolates only its own session events |
Latency Reporting Precision | Per-step and total latency values match trace timestamps within ±50ms for synchronous calls | Latency values that are negative, zero for non-zero-duration calls, or off by more than 500ms | Compare reported latency against span duration from OpenTelemetry traces for 100 tool calls |
Concurrent Session Handling | All N concurrent sessions produce N distinct summaries with no dropped sessions when N ≤ [MAX_CONCURRENT_SESSIONS] | Fewer summaries than active sessions, or summary count exceeds active session count | Launch 8 concurrent agent sessions; assert exactly 8 summaries produced with unique session IDs |
Rate Limit Event Documentation | Every 429 response or rate-limit backoff event appears in the summary with timestamp, tool name, and retry delay | Rate limit events present in trace but absent from summary, or retry delay values that don't match Retry-After headers | Inject 5 rate-limit responses into a trace; verify all 5 appear in summary with correct delay values parsed from headers |
Output Schema Compliance | Summary output validates against the declared [OUTPUT_SCHEMA] with zero schema violations | Missing required fields, wrong types, extra fields not in schema, or malformed JSON | Validate output with jsonschema against the expected schema definition; reject on any validation error |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base template and a single session trace. Use loose schema validation—accept any structured output that includes token counts, tool call counts, and an estimated cost field. Skip attribution accuracy checks initially. Focus on getting a readable summary per session.
Prompt modification
Remove strict [OUTPUT_SCHEMA] constraints. Replace with: "Return a JSON object with fields: session_id, total_tokens, total_tool_calls, estimated_cost, and a human-readable summary paragraph."
Watch for
- Missing cost estimation when model pricing isn't provided in [PRICING_TABLE]
- Overlapping session boundaries when traces aren't clearly delimited
- Tool calls counted but not categorized by type

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us