This prompt is for agent runtime developers and operators who need a deterministic, programmatic fallback when an agent's context window is nearly full mid-execution. The job-to-be-done is to produce a compressed state summary, a prioritized list of remaining steps, and a binary decision: continue with summarization or abort with partial results. The ideal user is an engineering lead integrating this into an agent harness that tracks token consumption in real time and can inject this prompt as a preflight check before the next tool call or reasoning step. Required context includes the current plan, completed steps with outputs, remaining steps, and the exact token budget remaining. Do not use this prompt for general context management, initial plan generation, or when the agent has not yet consumed 70%+ of its budget; it is a last-resort circuit breaker, not a routine compression tool.
Prompt
Token Budget Exhaustion Fallback Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Token Budget Exhaustion Fallback Prompt.
This prompt is designed to be wired into a token-budget monitor that fires when remaining_tokens < (estimated_next_step_tokens * 2). The harness should provide the model with a precise budget ceiling for the compressed output itself, typically 15-25% of the original remaining budget, to prevent the fallback from consuming the very resource it is trying to preserve. The output must be machine-parseable JSON with a decision field (continue or abort), a compressed_state object, and a prioritized_remaining_steps array. Validation must check that the compressed state is strictly smaller than the original state representation and that no completed steps are re-listed as remaining. Human review is not required for the fallback decision itself, but the harness should log the full pre-compression state and the compressed output for post-hoc audit. If the model fails to produce valid JSON or exceeds the output token budget, the harness must default to abort with a structured partial-results handoff.
Do not use this prompt when the agent is operating under a stateless retry model where a fresh context is cheaper than compression, or when the remaining steps include irreversible external actions that require full context fidelity. The primary failure mode is over-compression that drops critical constraints or dependency information, causing the agent to execute remaining steps with corrupted state. Mitigate this by requiring the compressed state to include an explicit lost_detail_flags array that lists any information the model knowingly omitted. Next, wire the output into your agent's execution loop with a post-compression validation step that diffs the original and compressed task lists for completeness. If the decision is continue, the agent should resume with the compressed state as its new working memory and a reduced token budget. If abort, the harness must assemble a user-facing partial completion summary using the structured output from this prompt.
Use Case Fit
Where the Token Budget Exhaustion Fallback Prompt delivers value and where it introduces unacceptable risk. Use these cards to decide whether to embed this prompt in your agent runtime.
Good Fit: Long-Running Autonomous Agents
Use when: agents execute multi-step plans where context windows are a hard constraint and losing all intermediate state is unacceptable. Guardrail: wire the prompt to a budget monitor that triggers before the model API returns a context-length error, leaving headroom for the summarization step itself.
Bad Fit: Low-Latency User-Facing Chat
Avoid when: the primary user experience is a sub-second conversational turn. The compression and re-prioritization step adds latency that violates user expectations. Guardrail: use sliding-window summarization or shorter context limits instead of mid-turn budget recovery.
Required Input: Accurate Token Budget Tracker
Risk: the prompt produces dangerous output if the reported remaining budget is inaccurate. An overestimated budget causes mid-summarization truncation; an underestimated budget wastes tokens on unnecessary compression. Guardrail: the harness must track token consumption from the model's own usage fields, not from client-side estimation alone.
Operational Risk: Silent Information Loss
Risk: the compressed state summary may drop facts, constraints, or completed subtask details that later steps depend on. The agent continues executing with an incomplete understanding of prior work. Guardrail: include a mandatory lost_information field in the output schema and log it. If critical facts are flagged as lost, escalate rather than continue.
Operational Risk: Premature Abort Decisions
Risk: the model may recommend aborting with partial results when a better compression strategy would allow completion. This wastes the work already done and forces a human restart. Guardrail: require the prompt to output at least two continuation options before permitting an abort recommendation, and log the alternatives for review.
Variant: Checkpoint Before Compression
Use when: the workflow is high-value and losing state is unacceptable even with a summary. Guardrail: persist the full agent state to external storage before invoking the fallback prompt. If the compressed continuation produces anomalous results, the operator can restore from the checkpoint and manually triage.
Copy-Ready Prompt Template
A reusable prompt template that compresses agent state, prioritizes remaining steps, and decides whether to continue with summarization or abort with partial results when token limits are approached.
The following prompt template is designed to be injected into an agent's execution loop when a token budget monitor detects that remaining context space is critically low. It forces the model to produce a structured fallback decision—either a compressed continuation plan or a partial abort with a handoff summary—before the context window overflows and loses state silently. Use this template as the final pre-exhaustion checkpoint in your agent harness.
textSYSTEM: You are an agent execution monitor. Your context window is nearly full. You must produce a structured fallback decision immediately. Do not continue executing tasks. Do not call tools. Output only the decision object. CURRENT STATE: - Completed steps: [COMPLETED_STEPS] - Remaining steps with priorities: [REMAINING_STEPS] - Active tool results pending: [PENDING_RESULTS] - Original goal: [ORIGINAL_GOAL] - Tokens used: [TOKENS_USED] / [TOKEN_LIMIT] - Tokens remaining: [TOKENS_REMAINING] CONSTRAINTS: - [CONSTRAINTS] DECISION RULES: 1. If the highest-priority remaining step can be completed with a compressed summary of prior state, output a CONTINUE decision with a compressed state summary and the single next step. 2. If multiple high-priority steps remain and compression would lose critical context, output an ABORT decision with a partial results summary and handoff instructions. 3. If any step involves [IRREVERSIBLE_ACTION_TYPES], prefer ABORT unless the step is already in progress and can be safely completed. OUTPUT SCHEMA: { "decision": "CONTINUE" | "ABORT", "compressed_state_summary": "string (max 500 tokens, only if CONTINUE)", "next_step": { "step_id": "string", "action": "string", "tool": "string", "args": {} }, "partial_results_summary": "string (only if ABORT)", "handoff_instructions": "string (only if ABORT)", "reasoning": "string (brief justification for the decision)" } RISK LEVEL: [RISK_LEVEL]
To adapt this template, replace each square-bracket placeholder with values from your agent runtime. [COMPLETED_STEPS] and [REMAINING_STEPS] should be structured lists with step IDs, descriptions, and priority scores. [IRREVERSIBLE_ACTION_TYPES] is a list of action categories your system considers too risky to compress or continue without full context—such as database writes, external API mutations, or user-facing messages. [RISK_LEVEL] should be set to HIGH if any remaining step involves irreversible actions, and LOW otherwise, which can be used by downstream validation to decide whether a human review is required before acting on the ABORT or CONTINUE decision.
After copying this template, wire it into your agent harness so it is only invoked when [TOKENS_REMAINING] drops below a threshold you define (typically 15-20% of the total context window). Do not call this prompt on every step—it is a circuit breaker, not a planning prompt. Validate the output against the schema before acting on it, and log every invocation with the token state at the time of the decision for postmortem analysis.
Prompt Variables
Required inputs for the Token Budget Exhaustion Fallback Prompt. Each placeholder must be populated before the prompt is assembled and sent. Validation checks prevent silent failures from missing or malformed inputs.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CURRENT_PLAN_STEPS] | Ordered list of remaining plan steps with status (pending, in_progress, completed) | ["step_4: generate_report (in_progress)", "step_5: validate_output (pending)", "step_6: deliver_results (pending)"] | Must be a valid JSON array of strings. Each string must contain step_id, description, and status. Empty array allowed if no steps remain. |
[COMPLETED_STEPS_SUMMARY] | Concise summary of steps already completed and their outputs | "Steps 1-3 completed: data fetched (200 records), cleaned (180 valid), analyzed (3 insights generated)" | String, max 500 characters. Must not be empty if [CURRENT_PLAN_STEPS] contains completed items. Null allowed only if no steps completed. |
[TOKEN_BUDGET_TOTAL] | Total token budget allocated for this agent session | 128000 | Integer, must be greater than 0. Represents the model's context window limit minus reserved output tokens. |
[TOKENS_USED_SO_FAR] | Cumulative tokens consumed in the current session including prompt, completion, and tool call tokens | 112500 | Integer, must be less than or equal to [TOKEN_BUDGET_TOTAL]. Must be greater than or equal to 0. Source from API usage metadata or token counter. |
[TOKENS_RESERVED_FOR_OUTPUT] | Tokens reserved for the model's response and any required tool call outputs | 4000 | Integer, must be greater than 0 and less than [TOKEN_BUDGET_TOTAL]. Typically 5-10% of total budget. |
[CRITICALITY_LEVEL] | Business or operational criticality of the overall task | "high" | Must be one of: "critical", "high", "medium", "low". Determines abort threshold strictness. Critical tasks bias toward summarization over abort. |
[MINIMUM_VIABLE_COMPLETION] | Minimum set of steps that must complete for the result to be considered useful | ["step_4", "step_5"] | Must be a JSON array of step_ids from [CURRENT_PLAN_STEPS]. Empty array means any partial result is acceptable. Used to decide abort vs. continue-with-compression. |
[SESSION_START_TIMESTAMP] | ISO 8601 timestamp when the agent session began | "2025-01-15T14:30:00Z" | Must be valid ISO 8601 UTC string. Used for latency-aware decisions and log correlation. Null allowed for stateless invocations. |
Implementation Harness Notes
How to wire the token budget exhaustion fallback prompt into an agent runtime with budget tracking, validation, and safe state handoff.
This prompt is designed to be invoked by an agent runtime monitor, not by the agent's primary reasoning loop. The runtime must track cumulative token consumption across all LLM calls, tool outputs, and retrieved context within a session. When the remaining budget drops below a configured threshold (e.g., 15% of the model's context window), the runtime should inject this prompt as a system-level interrupt, passing the current plan state, completed steps, and remaining tasks. The prompt is not a suggestion—it is a forced decision point that produces a compressed state summary and an explicit continue/abort directive.
The implementation harness requires three components. First, a token budget tracker that sums prompt_tokens and completion_tokens from each API response, adds estimated overhead for tool call schemas and retrieval chunks, and compares the running total against a configurable max_budget (typically 80-90% of the model's context limit to leave room for the fallback prompt itself and a final response). Second, a state serializer that converts the agent's internal execution state—completed steps with outputs, pending steps with dependencies, tool call history, and any accumulated evidence—into a structured [CURRENT_STATE] block for the prompt. Third, a decision validator that parses the model's output, confirms it contains a valid decision field (continue_summarized or abort_partial), and enforces the directive: if abort_partial, the runtime must stop further LLM calls and return the partial results to the caller; if continue_summarized, the runtime must replace the full conversation history with the compressed summary before resuming execution.
For production safety, implement these guardrails. Budget threshold hysteresis: don't re-trigger the fallback prompt immediately after a continue_summarized decision—wait until at least 20% of the remaining budget is consumed or a minimum number of steps complete. Output schema enforcement: use structured output mode (JSON mode or function calling) to parse the compressed_state, prioritized_remaining_steps, and decision fields; if parsing fails, default to abort_partial with a logged error rather than risking unbounded execution. Logging and observability: record every fallback trigger event with the pre-compression token count, the compressed state size, the decision, and the post-compression token count to measure compression ratio and detect budget tracking drift. Human review for high-stakes workflows: if the agent is operating on mutable resources (database writes, API mutations, file system changes), route abort_partial decisions to a review queue with the partial results and remaining steps rather than silently discarding incomplete work.
Model choice matters here. This prompt requires strong instruction-following and structured output discipline. Use models with native JSON mode support (GPT-4o, Claude 3.5 Sonnet, Gemini 1.5 Pro) and avoid models under ~7B parameters that may struggle with the dual task of compression and prioritization. If using a smaller model for cost reasons, split the prompt into two sequential calls: first compression, then decision, validating the compression output before the decision step. Do not use this prompt with streaming-only endpoints that cannot guarantee complete structured output.
Before deploying, test the harness with simulated budget exhaustion scenarios. Create test cases where the agent is 50%, 75%, and 95% through a known task list when the budget threshold triggers. Verify that continue_summarized decisions produce compressed states that preserve critical context (task dependencies, tool outputs needed for remaining steps) and that abort_partial decisions correctly halt execution and return honest partial results. Measure compression ratio (pre-compression tokens / post-compression tokens) and set a minimum acceptable threshold—if the model fails to compress below 50% of the original state size, the fallback may not buy enough headroom to be useful, and you should consider architectural changes like external state storage or earlier checkpointing.
Expected Output Contract
Defines the structure, types, and validation rules for the compressed state summary and continuation decision produced by the Token Budget Exhaustion Fallback Prompt. Use this contract to parse and validate the model's output before routing to the agent's execution loop or human operator.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
budget_consumed_percent | number (0-100) | Must be a float between 0 and 100. Parse check: ensure value is not negative and does not exceed 100. If null, fail validation. | |
remaining_tokens_estimate | integer | Must be a non-negative integer. Parse check: confirm integer type. If negative, fail. If null and budget_consumed_percent > 95, fail with 'critical budget unknown'. | |
compressed_state_summary | string | Must be a non-empty string with length > 20 characters. Schema check: reject empty strings or whitespace-only values. If null, fail validation. | |
prioritized_remaining_steps | array of objects | Must be a non-empty array. Each object must contain 'step_id' (string), 'description' (string), and 'criticality' (enum: critical|high|medium|low). Schema check: reject if any required field is missing or criticality is not in the enum. | |
continuation_decision | enum: continue_summarized|abort_partial|escalate_human | Must be exactly one of the three allowed values. Parse check: case-sensitive match. If missing or invalid, retry prompt with stricter enum constraint. | |
abort_rationale | string | Required only if continuation_decision is 'abort_partial' or 'escalate_human'. If present, must be a non-empty string. If missing when required, fail with 'rationale required for abort/escalate'. | |
partial_results_payload | object | Required only if continuation_decision is 'abort_partial'. Must be a valid JSON object containing 'completed_steps' (array) and 'artifacts' (array). Schema check: reject if fields are missing or types mismatch. | |
confidence_score | number (0.0-1.0) | Must be a float between 0.0 and 1.0 inclusive. Parse check: reject values outside range. If null, fail. If score < 0.5 and continuation_decision is 'continue_summarized', flag for human review. |
Common Failure Modes
Token budget exhaustion is a silent killer of agent reliability. When an agent runs out of context mid-execution, it loses state, drops subtasks, or fabricates completions. These cards cover the most common failure patterns and how to guard against them before they reach production.
Silent State Truncation
What to watch: The model's context window fills up, and older messages—including critical task state, completed steps, or tool outputs—are silently dropped by the platform before the model sees them. The agent continues executing as if nothing is missing, producing confident but incorrect results based on incomplete history. Guardrail: Implement a token budget tracker that estimates total context usage before each call and triggers the fallback prompt when remaining budget drops below a safety threshold (e.g., 20% of window). Never rely on the model to self-detect truncation.
Infinite Summarization Loops
What to watch: The fallback prompt compresses state, but the compression itself consumes tokens. If the compressed summary plus new tool outputs still exceeds the budget, the agent triggers another summarization, then another, burning tokens without making progress. Guardrail: Set a hard limit on the number of summarization passes allowed per workflow (typically 1-2). After the limit, force a decision: continue with partial results and explicit caveats, or abort with a structured handoff. Track summarization count in agent state.
Priority Inversion in Step Selection
What to watch: When budget runs low, the fallback prompt must decide which remaining steps to keep, defer, or drop. A naive priority ranking can elevate low-impact steps while dropping critical dependencies, causing the agent to complete cosmetic work while skipping the core objective. Guardrail: Require the fallback prompt to output explicit dependency reasoning before step selection. Each remaining step must be tagged with a criticality score and upstream dependencies. The harness should validate that no step marked as a dependency for a kept step has been dropped.
Fabricated Completion Status
What to watch: Under budget pressure, the model may mark steps as 'complete' or 'summarized' when they were never executed, especially if the prompt implies that all steps must be accounted for. This produces a clean-looking state summary that hides real gaps. Guardrail: The fallback prompt must distinguish between 'executed and verified,' 'executed but unverified,' 'partially executed,' and 'not started.' The harness should cross-reference the fallback output against the original plan's step IDs and flag any step claimed as complete that lacks a corresponding tool-call record in the trace.
Loss of Grounding Citations
What to watch: When compressing evidence and tool outputs to save tokens, the fallback prompt may drop source citations, quote anchors, or retrieval metadata. Downstream steps then reason from ungrounded summaries, increasing hallucination risk and breaking audit trails. Guardrail: The compression schema must preserve a minimum viable citation for each evidence item: source ID, retrieval timestamp, and a content hash or short quote. The harness should validate that every claim in the compressed state references at least one preserved citation. If citations cannot fit, the agent must flag reduced confidence rather than silently dropping them.
Budget Miscalculation from Tool Output Variability
What to watch: The token budget tracker estimates remaining capacity based on expected tool output sizes, but actual outputs can be much larger—a search returns 50KB of HTML, a database query returns unexpected rows, or a file read pulls in a massive log. The agent blows past its budget before the fallback prompt can activate. Guardrail: Implement pre-flight output size checks where possible (e.g., row counts, content-length headers). Use a pessimistic budget model that reserves headroom for 2-3x expected output size. Trigger the fallback prompt early when any single tool output exceeds a per-call token cap, rather than waiting for cumulative exhaustion.
Evaluation Rubric
Use this rubric to test the Token Budget Exhaustion Fallback Prompt before deploying it in a production agent harness. Each criterion targets a specific failure mode common to budget-aware summarization and decision prompts.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Budget Adherence | Output does not exceed the remaining token budget specified in [REMAINING_BUDGET]. | Output length exceeds budget; model ignores budget constraint and continues full generation. | Parse output token count. Assert count <= [REMAINING_BUDGET]. |
State Compression Completeness | Compressed state summary includes all critical fields from [AGENT_STATE]: current goal, completed steps, pending steps, and unresolved blockers. | Missing one or more critical state fields; summary omits a pending step or unresolved blocker. | Schema check: verify presence of |
Prioritization Correctness | Remaining steps are reordered by priority, with dependencies respected. The highest-priority executable step is listed first. | Priority order violates known dependency constraints; a blocked step is listed before its prerequisite. | Dependency graph check: for each step, assert its dependencies appear earlier in the list or are marked complete. |
Decision Justification | The | Decision reason is generic (e.g., 'based on analysis') or missing; model defaults to abort without justification. | String match for required justification fields. Assert length > 20 chars and contains reference to budget or step status. |
Partial Result Honesty | If aborting, the | Partial results include fabricated or hallucinated output for steps that were never completed. | Diff check: compare |
No Silent Data Loss | All completed step outputs present in [AGENT_STATE] are preserved in the compressed summary or partial results. | A completed step output is dropped from the summary without explicit flagging as excluded. | Key enumeration: extract all completed step IDs from [AGENT_STATE] and assert each appears in output or exclusion list. |
Actionable Handoff | If aborting, output includes | Recommended action is vague ('review and continue') or requires full context reconstruction. | Human eval spot-check: can a reviewer understand the next action using only the output? Pass if yes for 5/5 test cases. |
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
Use the base prompt with a hardcoded budget threshold and simple output schema. Skip the budget-tracking harness and rely on manual inspection of the compressed summary.
codeYou are approaching the token limit. Summarize the conversation state, list remaining steps in priority order, and decide: CONTINUE_WITH_SUMMARY or ABORT_WITH_PARTIAL. Current state: [CONVERSATION_HISTORY] Remaining steps: [TASK_LIST]
Watch for
- Missing budget tracking: the model doesn't know its actual remaining tokens
- Overly aggressive summarization that drops critical context
- CONTINUE_WITH_SUMMARY decisions that immediately hit the limit again

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