This prompt is for agent developers and platform engineers who need to compress an agent's active working memory into a compact summary that fits within a constrained context window. The job-to-be-done is lossy but task-preserving compression: you must reduce token usage while retaining the goals, decisions, partial results, and open questions the agent needs to continue its work without repeating steps or losing critical context. The ideal user is building a multi-agent system, a long-running autonomous agent, or any loop where the agent's internal scratchpad grows too large for the model's context limit and must be summarized before the next reasoning step.
Prompt
Agent Working Memory Summarization Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Agent Working Memory Summarization Prompt.
Use this prompt when an agent's working memory—its current plan, recent observations, tool outputs, and pending actions—exceeds a defined token budget and you need a structured summary that preserves task-critical information. The prompt expects a structured input containing the agent's current goal, recent memory entries, and a list of information categories that must be preserved. It produces a compressed summary with importance scores, explicit loss markers for discarded information, and a confidence estimate. Do not use this prompt for summarizing final outputs to users, for compressing immutable system instructions, or for long-term memory consolidation. It is specifically designed for the working memory buffer that sits between the agent's reasoning steps.
Before deploying this prompt, define your token budget, your task-critical information categories, and your evaluation criteria for information retention. The prompt includes a structured output schema that forces the model to declare what it kept, what it dropped, and why. Wire this into your agent loop with a pre-summary token check, a post-summary validation step that verifies the output schema, and an eval harness that tests whether the agent can still complete its task after summarization. The most common failure mode is dropping a constraint, a partial result, or an open question that the agent needs later—your eval must catch this before it compounds across multiple summarization cycles.
Use Case Fit
Where the Agent Working Memory Summarization Prompt delivers value and where it introduces risk. Use these cards to decide whether this prompt fits your agent architecture before integrating it into a production pipeline.
Good Fit: Long-Running Agent Sessions
Use when: your agent accumulates extensive conversation history, tool outputs, or retrieved documents that exceed context window limits. Guardrail: apply this prompt before each major reasoning step to compress prior context while preserving task-critical facts, active goals, and unresolved dependencies.
Bad Fit: Real-Time, Low-Latency Pipelines
Avoid when: your system requires sub-100ms response times or operates on streaming data where summarization latency would break the user experience. Guardrail: use a simpler truncation or sliding window strategy for latency-sensitive paths, reserving this prompt for batch or background memory consolidation.
Required Inputs: Structured Agent State
What to watch: the prompt requires a well-formed input containing agent goals, recent actions, tool results, and active constraints. Missing fields produce summaries that omit critical context. Guardrail: validate input schema completeness before calling the prompt, and reject or flag summaries generated from incomplete state objects.
Operational Risk: Silent Information Loss
What to watch: the summarization is inherently lossy. Task-critical details such as error codes, exact user preferences, or pending approval IDs can be dropped without warning. Guardrail: always run the paired eval prompt after summarization to verify that task-critical items are preserved, and escalate to human review if the retention score falls below your threshold.
Operational Risk: Recency Bias Amplification
What to watch: the importance scoring mechanism may overweight recent events and underweight older but still-relevant context, causing the agent to forget long-term constraints. Guardrail: include explicit importance tags on long-lived facts in the input state and verify through eval that high-importance older items survive summarization.
Bad Fit: Single-Turn or Stateless Agents
Avoid when: your agent completes tasks in a single request-response cycle without carrying state forward. Guardrail: skip memory summarization entirely for stateless agents. Introducing unnecessary compression adds latency and risk without any benefit to task completion.
Copy-Ready Prompt Template
A reusable prompt template for compressing agent working memory into a compact, task-preserving summary with importance scoring.
This template is designed to be dropped into an agent's context management loop when the working memory buffer exceeds a token threshold. It instructs the model to act as a memory compressor, producing a lossy but task-preserving summary. The prompt forces explicit importance scoring and requires the model to justify what it retains and what it discards, which is critical for downstream debugging and eval. Use this template when you need a structured, auditable summary rather than a generic conversation summarization.
textYou are an agent memory compression module. Your task is to compress the provided [WORKING_MEMORY] into a compact summary that preserves all information critical to completing the current [TASK_GOAL]. ## Input [WORKING_MEMORY] ## Task Goal [TASK_GOAL] ## Constraints - Maximum output length: [MAX_TOKENS] tokens. - Prioritize facts, decisions, unresolved questions, and active constraints over conversational filler. - Preserve exact values for identifiers, error codes, file paths, and configuration parameters. - If a piece of information is directly required by [TASK_GOAL], it must be retained. ## Output Schema Return a JSON object with the following structure: { "summary": "A dense, factual narrative of the compressed memory.", "retained_items": [ { "item": "The specific fact, decision, or context retained.", "importance_score": 0.0-1.0, "relevance_to_goal": "Why this item is critical for [TASK_GOAL]." } ], "discarded_items": [ { "item": "A brief description of what was removed.", "discard_reason": "Why this item is not relevant to [TASK_GOAL] or is redundant." } ], "unresolved_questions": [ "Any open questions that must be answered to complete [TASK_GOAL]." ] } ## Risk Level [RISK_LEVEL] If [RISK_LEVEL] is "high", you must flag any discarded item that could potentially be relevant under a broader interpretation of [TASK_GOAL] in a `flagged_for_review` field within each discarded item.
To adapt this template, start by defining a clear, narrow [TASK_GOAL]. A vague goal like "fix the bug" will cause the compressor to retain too much or too little. Instead, use a specific goal such as "Resolve the NullPointerException in UserService.createUser() by identifying the root cause and applying a fix." Set [MAX_TOKENS] based on your model's context window budget for memory—typically 20-40% of the total window. For [RISK_LEVEL], use "high" for production debugging, security incidents, or financial operations where information loss is costly; use "low" for exploratory or conversational agent sessions. After generation, validate the output JSON against the schema and run an eval that checks whether all items with an importance_score above 0.8 are actually present in the summary text. If the summary fails this consistency check, retry with a lower [MAX_TOKENS] or a more explicit [TASK_GOAL].
Prompt Variables
Required and optional inputs for the Agent Working Memory Summarization Prompt. Validate each placeholder before assembly to prevent silent context loss.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[WORKING_MEMORY_ENTRIES] | Array of memory objects to compress. Each entry must include content, timestamp, and source agent ID. | [{"id":"mem-01","content":"User requested Q3 sales report...","timestamp":"2025-01-15T14:30:00Z","source_agent":"analyst-agent"}] | Check array is non-empty. Each object must have id, content, timestamp, source_agent keys. Reject if timestamp is missing or unparseable. |
[TASK_CONTEXT] | Current task description the agent is executing. Used to score memory relevance. | "Generate a summary of Q3 sales performance with regional breakdowns." | Must be a non-empty string. Check length under 2000 characters. If null, importance scoring defaults to recency-only weighting. |
[MAX_OUTPUT_TOKENS] | Token budget for the compressed summary. Controls lossiness. | 1500 | Must be a positive integer. Validate range 200-4000. If below 200, warn that critical information may be dropped. If above 4000, warn that compression benefit is minimal. |
[IMPORTANCE_WEIGHTS] | Optional object tuning recency, task_relevance, and uniqueness scoring dimensions. | {"recency":0.3,"task_relevance":0.5,"uniqueness":0.2} | Weights must sum to 1.0 within 0.01 tolerance. Each weight must be between 0 and 1. If null, use default equal weights. |
[RETENTION_RULES] | Array of rules specifying which memory types must be preserved regardless of score. | ["user_directives","error_events","pending_actions"] | Each rule must match a known memory category tag. Validate against allowed category list. If empty array, no forced retention applied. |
[OUTPUT_SCHEMA] | Expected JSON schema for the compressed summary output. | {"summary":"string","retained_entry_ids":["string"],"dropped_entry_ids":["string"],"importance_scores":{"mem-01":0.85}} | Must be a valid JSON Schema object. Check for required fields: summary, retained_entry_ids, dropped_entry_ids. Reject if schema allows dropping all entries without explicit flag. |
[AGENT_ID] | Identifier of the agent requesting the summarization. Used for source attribution in output. | "analyst-agent-7" | Must be a non-empty string matching agent naming convention. Validate against agent registry if available. Reject if contains only whitespace. |
[SESSION_ID] | Current session identifier for traceability and audit logging. | "sess-2025-01-15-0042" | Must be a non-empty string. Validate format matches session ID pattern. If null, output omits session-level traceability metadata. |
Implementation Harness Notes
How to wire the working memory summarization prompt into an agent loop with validation, retries, and evals.
This prompt is designed to be called inside an agent's context management loop, typically when the working memory buffer exceeds a token threshold or a fixed number of turns. The application layer should track the current working memory entries, their timestamps, and any associated importance scores before invoking the summarization prompt. The prompt expects a structured list of memory entries as [WORKING_MEMORY_ENTRIES], each containing at minimum a content field and optionally timestamp, source, and importance fields. The application is responsible for assembling this list from the agent's runtime state store before each call.
Wire the prompt into a dedicated summarization step within the agent's orchestration code. Before calling the model, validate that the input payload is not empty and that the total token count of [WORKING_MEMORY_ENTRIES] exceeds your configured compression threshold. After receiving the model response, parse the JSON output and validate it against the expected schema: a list of summary objects, each with summary, retained_facts, discarded_details, and importance_score fields. If validation fails, implement a single retry with the validation error message appended to the prompt as additional [CONSTRAINTS]. Log both the original and retry attempts for observability. For high-stakes agent workflows where information loss could cause incorrect actions, route summaries with importance_score below a configurable threshold (e.g., 0.7) to a human review queue before the agent acts on the compressed memory.
Model choice matters here. Use a model with strong instruction-following and JSON output capabilities, such as Claude 3.5 Sonnet or GPT-4o, and enable structured output mode if available. Set temperature to 0 or a low value (0.1–0.2) to maximize consistency across repeated summarization calls. The prompt should be treated as a cached system instruction prefix where possible to reduce latency and cost on repeated calls. Store the output summary alongside the original memory entries with a version marker and timestamp, enabling audit trails and rollback if the agent later exhibits behavior that suggests critical information was lost during compression. Integrate the eval rubric from this playbook into your CI pipeline: run the prompt against a golden set of memory entries and verify that retained_facts preserves all task-critical items defined in your test cases before deploying any prompt changes.
Expected Output Contract
Fields, types, and validation rules for the working memory summary object. Use this contract to parse, validate, and store summaries before passing them to downstream agents or context windows.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
summary_id | string (UUID v4) | Must parse as valid UUID v4. Reject on format mismatch. | |
timestamp | string (ISO 8601 UTC) | Must parse as valid ISO 8601 datetime in UTC. Reject if missing timezone or unparseable. | |
compressed_memory | string | Must be non-empty and between 50 and 2000 characters. Reject if length out of bounds. | |
key_facts | array of strings | Must contain 3-10 items. Each string must be non-empty and under 280 characters. Reject if array is empty or exceeds max items. | |
active_goals | array of objects | Each object must contain goal_id (string) and status (enum: active, blocked, completed). Reject if any object fails schema check. | |
importance_scores | object | Must contain task_relevance (float 0.0-1.0), recency (float 0.0-1.0), uniqueness (float 0.0-1.0). Reject if any score out of range or missing. | |
lost_detail_warnings | array of strings | If present, each string must be non-empty. Null or empty array is acceptable. Reject if array contains empty strings. | |
source_agent_id | string | Must be non-empty and match agent ID pattern from session roster. Reject if missing or unknown agent ID. |
Common Failure Modes
What breaks first when compressing agent working memory and how to prevent critical information loss in production.
Task-Critical Detail Omission
What to watch: The summarizer drops a pending action, unresolved dependency, or user constraint that is essential for the next agent step. This happens when the prompt prioritizes brevity over task-preservation. Guardrail: Include a pre-summarization extraction step that lists all open tasks, constraints, and dependencies before compression. Validate the summary against this checklist with a separate verification call.
Importance Scoring Collapse
What to watch: The model assigns uniformly high or medium importance scores to all memory entries, making the scoring useless for budget allocation. This occurs when the scoring criteria are vague or the model hedges. Guardrail: Force a forced-distribution constraint in the prompt (e.g., top 20% must be high, bottom 50% must be low). Calibrate with a few-shot example showing decisive, differentiated scoring.
Temporal Ordering Corruption
What to watch: The summary reorders events, causing the downstream agent to act on stale information or execute steps out of sequence. This is common when the model paraphrases aggressively. Guardrail: Require the summary to preserve a numbered, chronological event log as a separate section. Post-process to verify that timestamps or sequence markers are monotonically increasing.
Source Attribution Loss
What to watch: Facts from different agents or tools are merged without provenance, making it impossible to resolve contradictions or assess reliability later. Guardrail: Mandate inline source tags (e.g., [Agent:Planner], [Tool:DBLookup]) for every claim in the summary. Run a regex validator to confirm every sentence or bullet has an attribution marker.
Negative Information Stripping
What to watch: The summary omits what the agent tried and failed, what tools are unavailable, or what paths were ruled out. The next agent wastes time repeating dead ends. Guardrail: Add a dedicated "Blockers and Ruled-Out Paths" section to the output schema. Use a separate eval prompt that checks whether all logged failures from the raw memory appear in the summary.
Context Window Budget Overshoot
What to watch: The summarization prompt itself, plus the raw memory, plus the generated summary exceed the target token budget, defeating the purpose of compression. Guardrail: Calculate the available budget before calling the model. Truncate raw memory to fit within budget - prompt_tokens - expected_summary_tokens. If truncation is required, log a warning and prioritize the most recent entries.
Evaluation Rubric
Criteria for evaluating the quality of a working memory summary before it replaces the original context window. Use these checks to gate the summarization step in an agent loop.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Task-Critical Information Retention | All explicitly stated goals, constraints, and active sub-tasks from [ORIGINAL_MEMORY] are present in the summary. | A stated goal or active constraint from the source is missing or altered in the summary. | Diff the set of goals and constraints extracted from [ORIGINAL_MEMORY] against those in [SUMMARY_OUTPUT]. Require 100% recall. |
Importance Score Calibration | Items scored above the [IMPORTANCE_THRESHOLD] are task-relevant. Items scored below are demonstrably less critical to the current goal. | A clearly irrelevant detail receives a high score, or a core task constraint receives a low score. | Sample 10 scored items. Have an LLM judge or human reviewer label them as critical/non-critical. Compute precision and recall against the threshold. |
Factual Fidelity | No fact, figure, or entity in the summary contradicts the [ORIGINAL_MEMORY]. | A date, name, status, or value is changed or hallucinated in the summary. | Extract all atomic claims from the summary. For each, check entailment against [ORIGINAL_MEMORY] using an NLI model. Flag any contradiction. |
Lossy Compression Ratio | The summary token count is less than or equal to [MAX_SUMMARY_TOKENS] and represents a meaningful reduction from the original. | The summary is longer than the budget or is trivially shorter by only removing whitespace. | Run a tokenizer on both [ORIGINAL_MEMORY] and [SUMMARY_OUTPUT]. Assert summary_tokens <= [MAX_SUMMARY_TOKENS] and summary_tokens < 0.5 * original_tokens. |
Schema Compliance | [SUMMARY_OUTPUT] is valid JSON and contains all required fields: | Output is not parseable JSON or a required key is missing. | Validate [SUMMARY_OUTPUT] against the expected JSON schema. Reject on parse error or missing required fields. |
Discarded Item Justification | Every item in | A discarded item has a reason like 'not important' without linking to the current task context. | For each discarded item, check that the |
Uncertainty Preservation | If [ORIGINAL_MEMORY] contains hedged or low-confidence information, the summary preserves that uncertainty language. | A hedged statement in the source ('might be', 'unconfirmed') becomes a definite statement in the summary ('is', 'confirmed'). | Extract hedged claims from [ORIGINAL_MEMORY]. Verify that corresponding claims in [SUMMARY_OUTPUT] retain a hedging marker or explicit uncertainty flag. |
Idempotency Check | Summarizing the summary produces an output semantically equivalent to the first summary. | Re-summarization introduces new distortions or drops additional critical information. | Run the summarization prompt with [SUMMARY_OUTPUT] as the input. Compare the new output to the original summary using semantic similarity. Require score > 0.95. |
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 prompt and a simple importance scoring heuristic (recency × task relevance). Use a single-pass summarization without iterative refinement. Accept the model's native output format without strict schema enforcement.
codeSummarize the following agent working memory entries. Focus on information most relevant to the current task: [TASK_DESCRIPTION]. Memory entries: [MEMORY_ENTRIES] Return a compact summary preserving task-critical details.
Watch for
- Hallucinated details not present in source memory entries
- Over-compression that drops task-critical constraints or partial results
- No mechanism to verify information preservation before discarding original entries

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