This prompt is designed for developers and infrastructure engineers building autonomous or semi-autonomous agents that conduct extended, multi-turn tool-use sessions. Its primary job is to compress a verbose history of tool calls, their arguments, outcomes, and errors into a dense, structured context block. This summary is then injected into a subsequent prompt to maintain the agent's situational awareness without exceeding context window limits. The ideal user is someone integrating this into an agent harness where context budgets are tight and the cost of lost detail is high—such as a coding agent working through a multi-file refactor or a research agent synthesizing data from dozens of API calls.
Prompt
Session Summary Generation Prompt for Long Conversations

When to Use This Prompt
Define the job, ideal user, and constraints for the Session Summary Generation Prompt.
Use this prompt when a conversation or tool-use session has exceeded a predefined token threshold, when preparing a handoff summary for another agent, or when creating a checkpoint before a high-risk operation. It is specifically built for sessions where the sequence of tool calls and their results is the critical information to preserve. Do not use this prompt for simple chat history summarization where tool use is absent, or for summarizing creative writing. It is also inappropriate for real-time, low-latency applications where the cost of an extra summarization step outweighs the context savings. The prompt assumes the input is a structured log of tool interactions, not a free-form dialogue.
Before implementing this prompt, ensure your harness can reliably extract the full tool call history, including arguments and raw results. The primary failure mode is the omission of a critical detail—like a specific error code or a returned file path—that downstream tool calls depend on. Therefore, this prompt is a component in a larger system that should include an evaluation step to check the summary against the original history for completeness. If your workflow involves high-stakes actions like database writes, code commits, or financial transactions, a human review step on the generated summary is a required control before it re-enters the agent's active context.
Use Case Fit
Where the Session Summary Generation Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your agent architecture before integrating it into a production harness.
Good Fit: Long-Running Agent Sessions
Use when: your agent executes 20+ tool calls across multiple turns and the full history exceeds the context budget for the next step. Guardrail: trigger summary generation automatically when tool call history exceeds a token threshold, and validate that the compressed output preserves all pending actions and unresolved errors.
Bad Fit: Real-Time, Low-Latency Pipelines
Avoid when: the agent must respond in under 500ms and the summarization step adds unacceptable latency. Guardrail: benchmark summary generation time against your latency budget, and fall back to a sliding window truncation strategy when the summarization call would violate the SLA.
Required Input: Structured Tool Call Logs
Risk: the prompt produces hallucinated tool results if the input history is unstructured or missing error codes. Guardrail: require a typed tool call log with fields for tool name, arguments, status code, output schema, and error messages before invoking the summary prompt. Reject malformed inputs at the harness level.
Operational Risk: Critical Detail Loss
Risk: the summary omits a failed tool call that requires retry, causing the agent to proceed with incomplete state. Guardrail: run a post-summary eval that checks for the presence of every error status and pending action from the original history. Escalate to human review if the eval fails before the compressed context is used.
Operational Risk: Hallucinated Tool Outcomes
Risk: the model invents successful tool results for calls that actually failed, corrupting downstream reasoning. Guardrail: include explicit instructions in the prompt to preserve original status codes and error messages verbatim. Validate the summary against the source log using exact string matching on status fields.
Good Fit: Session Handoff Between Agents
Use when: transferring work from one agent to another and the receiving agent needs compact, decision-relevant context. Guardrail: pack the summary with only the state, tool results, and pending actions the receiving agent requires. Validate that no sensitive data leaks across agent boundaries before the handoff completes.
Copy-Ready Prompt Template
A reusable prompt template with square-bracket placeholders that compresses long tool-use conversations into a structured, verifiable session summary.
This template is the core instruction set for generating a structured session summary from an extended, multi-turn tool-use conversation. It is designed to be dropped into your agent's context assembly pipeline when the conversation history exceeds your context budget or when a downstream agent or human reviewer needs a compact, trustworthy record of what happened. The prompt forces the model to extract tool calls, outcomes, errors, and pending actions into a typed schema, rather than producing a vague prose summary that hides critical details.
textYou are a session summarizer for an AI agent that uses external tools. Your job is to compress the provided conversation history into a structured summary object. The summary must be accurate, lossless regarding critical tool outcomes, and must never invent tool results that are not present in the history. ## INPUT - Conversation History: [CONVERSATION_HISTORY] - Current Session State: [SESSION_STATE] - Pending Actions Queue: [PENDING_ACTIONS] ## OUTPUT_SCHEMA Return a valid JSON object with the following structure: { "session_id": "string, the session identifier", "summary_timestamp": "string, ISO 8601 timestamp of summary generation", "user_intent": "string, concise summary of the user's original and evolved goals", "key_decisions": [ { "decision": "string, what was decided", "rationale": "string, why it was decided based on tool outputs", "turn": "integer, the conversation turn where the decision was made" } ], "tool_call_log": [ { "tool_name": "string", "arguments": "object, the arguments passed", "result_summary": "string, condensed but accurate summary of the result", "status": "success | failure | timeout | pending", "error_details": "string | null, error message if status is failure or timeout", "turn": "integer" } ], "data_artifacts": [ { "artifact_id": "string, unique identifier for the data", "source_tool": "string, which tool produced it", "summary": "string, what the artifact contains", "expiry_turn": "integer | null, turn after which this data may be stale" } ], "pending_actions": [ { "action": "string, what needs to happen next", "depends_on": ["string, artifact_id or tool_call that must complete first"], "priority": "high | medium | low" } ], "errors_and_anomalies": [ { "description": "string, what went wrong", "severity": "blocking | degraded | warning", "turn": "integer" } ], "context_health": { "stale_artifacts": ["string, artifact_ids that may be outdated"], "missing_dependencies": ["string, required data not yet retrieved"], "budget_remaining_tokens": "integer | null, estimated remaining context tokens" } } ## CONSTRAINTS - Do not hallucinate tool results. If a tool call's output is not in the history, set status to "unknown" and note it in errors_and_anomalies. - Preserve exact argument values where they are critical for debugging (e.g., IDs, query strings). - If the conversation history is truncated, note the truncation point in context_health. - Prioritize recent turns but do not drop decisions or errors from earlier turns. - If [RISK_LEVEL] is "high", flag any irreversible actions taken in key_decisions and require human review before the summary is used as source-of-truth. ## EXAMPLES [FEW_SHOT_EXAMPLES] Now, generate the session summary for the provided conversation history.
To adapt this template, replace the square-bracket placeholders with your application's runtime values. [CONVERSATION_HISTORY] should be the full or truncated message array. [SESSION_STATE] is your application's structured state object. [PENDING_ACTIONS] is the queue of tool calls the agent intends to make next. [FEW_SHOT_EXAMPLES] should contain 1-3 examples of correctly formatted summaries for your specific tool set, which dramatically improves schema adherence. [RISK_LEVEL] should be set to "high" if the session includes destructive actions like database writes, payment processing, or user data modification; this triggers the human-review flag in the output. Before deploying, validate the output against the schema in your application layer and run eval checks for hallucinated tool results, dropped errors, and missing pending actions. If the summary will be used to rehydrate agent state later, pair this prompt with the Session Rehydration from Persistent Store Prompt Template to close the loop.
Prompt Variables
Required and optional inputs for the Session Summary Generation Prompt. Each placeholder must be populated before the prompt is assembled and sent. Validation notes describe how to verify the input is well-formed before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CONVERSATION_HISTORY] | Full transcript or message array of the session to summarize, including user messages, assistant responses, and tool call/result pairs | {"messages": [{"role": "user", "content": "Run the deployment"}, {"role": "assistant", "tool_calls": [{"id": "call_1", "function": {"name": "deploy_service", "arguments": "{"env": "staging"}"}}]}, {"role": "tool", "tool_call_id": "call_1", "content": "{"status": "success", "version": "v2.4.1"}"}]} | Must be a valid JSON array of message objects with role, content, and optional tool_calls/tool_call_id fields. Reject if empty or if tool_call_ids are missing corresponding tool result messages. Max 200 messages before truncation warning. |
[SESSION_METADATA] | Context about the session itself: start time, session ID, user ID, agent version, and active tool registry snapshot | {"session_id": "sess_9a7b", "started_at": "2025-03-15T14:22:00Z", "user_id": "usr_442", "agent_version": "3.1.0", "tool_registry_hash": "a3f2c1"} | Must include session_id and started_at at minimum. Validate ISO 8601 timestamp. Reject if session_id is null or empty. Tool registry hash is optional but recommended for debugging stale tool descriptions. |
[SUMMARY_SCHEMA] | JSON Schema or type definition that constrains the output structure of the summary | {"type": "object", "properties": {"session_id": {"type": "string"}, "summary": {"type": "string"}, "tool_calls_made": {"type": "array", "items": {"type": "object", "properties": {"tool_name": {"type": "string"}, "status": {"enum": ["success", "failed", "timeout"]}, "key_result": {"type": "string"}}}}, "pending_actions": {"type": "array", "items": {"type": "string"}}, "unresolved_questions": {"type": "array", "items": {"type": "string"}}}, "required": ["session_id", "summary", "tool_calls_made", "pending_actions"]} | Must be valid JSON Schema draft-07 or later. Parse and validate schema before prompt assembly. Reject schemas missing required fields for tool call tracking. Test schema against expected output shape with a dry-run validator. |
[MAX_SUMMARY_LENGTH] | Token or word budget for the generated summary to prevent context bloat when the summary is injected into future turns | 500 | Must be a positive integer. Validate range: 100-2000 tokens. Reject values below 100 as insufficient for meaningful tool-call compression. Warn if above 2000 as summary may defeat context-budgeting purpose. |
[PRIORITY_WEIGHTS] | Optional tuning parameters that bias the summary toward specific content types: tool outcomes, user intent, errors, or pending work | {"tool_outcomes": 0.4, "user_intent": 0.3, "errors": 0.2, "pending_actions": 0.1} | If provided, weights must sum to 1.0 within 0.01 tolerance. All keys must be from allowed set: tool_outcomes, user_intent, errors, pending_actions, unresolved_questions. Null allowed; prompt uses default equal weighting when absent. |
[EXCLUDED_TOOL_NAMES] | List of tool names whose calls and results should be omitted from the summary, typically for noisy or high-volume read-only tools | ["ping_health", "get_timestamp", "list_directory"] | Must be a JSON array of strings. Validate each string against the active tool registry to confirm the tool exists. Empty array is valid and means no exclusions. Reject if any tool name is not found in registry to catch typos. |
[REQUIRED_FIDELITY_FIELDS] | Fields that must be preserved verbatim from tool results, such as version numbers, commit SHAs, or error codes | ["deploy_service.version", "run_migration.migration_id", "error.code"] | Must be a JSON array of dot-notation field paths. Validate each path against the tool output schemas in the registry. Reject paths that reference non-existent fields. Null allowed; prompt skips fidelity enforcement when absent. |
[PREVIOUS_SUMMARY] | The summary from the prior summarization step, if this is an incremental or rolling summary update | {"session_id": "sess_9a7b", "summary": "User requested staging deployment. Deploy_service succeeded with v2.4.0. No pending actions.", "tool_calls_made": [{"tool_name": "deploy_service", "status": "success", "key_result": "Deployed v2.4.0 to staging"}], "pending_actions": []} | If provided, must conform to the same [SUMMARY_SCHEMA] as the current output. Validate schema conformance before use. Null allowed for first summarization in a session. Reject if session_id does not match [SESSION_METADATA].session_id. |
Implementation Harness Notes
How to wire the session summary prompt into a production agent loop with validation, retries, and state management.
The session summary prompt is not a standalone utility; it is a state-compression function inside a larger agent harness. It should fire when the context window approaches a configured threshold (e.g., 80% of the model's limit) or when a tool-call turn count is exceeded. The harness must supply the full conversation transcript, tool-call history with arguments and results, and any pending action items as the [FULL_SESSION_TRANSCRIPT] input. The [SUMMARY_SCHEMA] placeholder should be populated with a strict JSON schema that includes fields for decisions_made, pending_actions, tool_results_summary, key_facts, and open_questions. Do not call this prompt on every turn; doing so adds latency and risks summary drift where errors compound across successive compressions.
Wire the prompt into an application as a pre-call middleware function. Before the next user or tool turn, check the token count of the current context. If it exceeds the threshold, extract the full transcript, inject it into the prompt template, and call a model with structured output enforcement (e.g., response_format or a JSON mode flag). Validate the returned summary against the [SUMMARY_SCHEMA] using a JSON schema validator. If validation fails, retry once with the validation error appended to the prompt as a correction hint. If the retry also fails, log the failure, fall back to a simpler truncation strategy (e.g., keep the last N messages), and alert the operations team. Store the validated summary in the session state object and replace the compressed portion of the conversation with a single system message containing the summary text.
For high-stakes domains such as healthcare or finance, insert a human review step before the summary replaces live context. The harness should serialize the proposed summary and the original transcript segment into a review queue, pause the agent's autonomous execution, and wait for approval or correction. Log every summary generation event with the pre-compression token count, the post-compression token count, the model used, the validation result, and a hash of the input transcript for later audit. Avoid the common failure mode of summarizing tool results without preserving error codes or exact values; the schema must require that tool errors and quantitative results are carried forward verbatim, not paraphrased. The next step after implementing this harness is to build an eval pipeline that compares summary fidelity against the original transcript using an LLM judge, checking for dropped decisions, hallucinated tool results, and missing pending actions.
Expected Output Contract
Fields, types, and validation rules for the structured session summary object. Use this contract to parse, validate, and store the summary before injecting it into the next turn's context window.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
summary_id | string (UUID v4) | Must parse as valid UUID v4. Reject on format mismatch. | |
session_span | object | Must contain start_timestamp and end_timestamp as ISO 8601 strings. end_timestamp must be >= start_timestamp. | |
tool_call_log | array of objects | Each element must have tool_name (string), call_timestamp (ISO 8601), status (enum: success | failure | timeout | cancelled), and result_summary (string, max 200 chars). Array length must be >= 1. | |
pending_actions | array of strings | Each string must be non-empty and <= 150 chars. Null or empty array allowed only if no actions remain. Reject if contains duplicate strings. | |
key_decisions | array of objects | Each object must have decision (string, max 300 chars), rationale (string, max 300 chars), and supporting_tool_call_ids (array of UUID strings referencing tool_call_log entries). Array length must be >= 1. | |
unresolved_questions | array of strings | Each string must be non-empty and <= 200 chars. If absent, default to empty array. Reject if contains markdown or code blocks. | |
context_warnings | array of strings | Each string must be non-empty and <= 200 chars. Must only contain warnings about stale data, missing dependencies, or conflicting results. Reject if contains hallucinated tool results. | |
compression_metadata | object | Must contain original_turn_count (integer, >= 1), summary_turn_count (integer, >= 1), and fidelity_score (float, 0.0 to 1.0). fidelity_score below 0.7 triggers human review flag. |
Common Failure Modes
Session summaries compress long tool-use histories into compact context blocks. These failures surface when compression drops critical details, hallucinates tool results, or misrepresents pending actions.
Critical Detail Omission
What to watch: The summary drops a failed tool call, an error code, or a dependency that downstream steps require. The agent proceeds with incomplete context and makes incorrect decisions. Guardrail: Require the summary to explicitly list all tool calls with their status (success/failure/pending) and preserve error messages verbatim. Validate with a diff check against the original history.
Hallucinated Tool Results
What to watch: The model fabricates tool outputs, status codes, or data fields that never appeared in the actual tool response. This corrupts all downstream reasoning. Guardrail: Ground every summarized tool result against the original tool output. Use a structured schema that separates observed results from inferred conclusions. Run a factuality eval comparing summary claims to source tool responses.
Pending Action Erasure
What to watch: The summary omits actions the agent committed to but hasn't executed yet, such as follow-up calls, user confirmations, or scheduled retries. The agent forgets its obligations. Guardrail: Include a dedicated pending_actions field in the summary schema. Before finalizing, scan the conversation for commitment language and verify each pending item appears in the summary.
Temporal Ordering Collapse
What to watch: The summary flattens multi-step sequences into an unordered list, losing the dependency chain. The agent can't determine which result depends on which prior call. Guardrail: Structure the summary with a numbered sequence preserving call order and explicit dependency annotations. Validate that prerequisite calls appear before their dependents in the summary.
Context Window Overflow During Generation
What to watch: The conversation is so long that the summary prompt plus history exceeds the model's context window, causing truncation before summarization completes. The output is cut off mid-JSON. Guardrail: Chunk the history and summarize incrementally. Set a hard token budget for input and abort with a partial-summary fallback if the window is exceeded. Monitor input token counts before calling the model.
Schema Drift Under Pressure
What to watch: When the conversation is complex or error-heavy, the model abandons the required output schema and returns unstructured text or malformed JSON. Downstream parsers break. Guardrail: Use strict JSON mode or structured output constraints. Validate the summary against the schema immediately after generation. On failure, retry with a simplified prompt that reinforces the schema and reduces the history scope.
Evaluation Rubric
Use this rubric to evaluate the quality of session summaries generated from long tool-use conversations. Each criterion targets a specific failure mode common in context compression for multi-turn agents.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Critical Detail Preservation | All tool calls marked as 'pending' or 'requires_follow_up' in the source conversation appear in the summary's [PENDING_ACTIONS] block with their original intent preserved. | A pending tool call from the source is missing from the summary, or its required arguments are altered. | Diff the source conversation's unresolved tool calls against the summary's [PENDING_ACTIONS] list. Fail if any source pending call is absent or has mutated arguments. |
Hallucinated Tool Results | The summary contains zero tool results that were not present in the original conversation history. | The summary includes a successful tool result for a call that actually failed, timed out, or was never executed in the source. | Parse all tool result assertions in the summary. Cross-reference each against the source tool call log. Fail on any fabricated success or fabricated data. |
Error State Fidelity | Every tool error present in the source conversation is represented in the summary with its error type and the action taken (retry, fallback, abort). | A source error is summarized as a success, omitted entirely, or its error type is changed. | Extract all error events from the source log. Verify each maps to an entry in the summary's [ERRORS_AND_FALLBACKS] block with matching type. Fail on omission or type mismatch. |
State Mutation Accuracy | The summary's [STATE_CHANGES] block correctly reflects the net effect of all completed tool calls on session state variables. | A state variable is reported as updated when the corresponding tool call failed, or a state change is attributed to the wrong tool call. | Replay the sequence of successful tool calls from the source. Compute the expected final state. Compare against the summary's [STATE_CHANGES]. Fail on any discrepancy. |
Schema Compliance | The output is valid JSON matching the defined summary schema with all required fields present and correctly typed. | The output is missing a required field, contains an extra field not in the schema, or has a field with an incorrect type. | Validate the output against the JSON Schema for the session summary contract. Fail on any schema violation. |
Token Budget Adherence | The generated summary is under the specified [MAX_OUTPUT_TOKENS] limit while including all required sections. | The summary exceeds the token budget, or critical sections are truncated mid-sentence to fit. | Count output tokens. Fail if count exceeds [MAX_OUTPUT_TOKENS]. Also fail if any required section is incomplete due to truncation. |
Source Grounding | Every factual statement in the summary can be traced back to a specific turn or tool call in the source conversation. | The summary includes a claim about user intent, tool capability, or conversation outcome that has no corresponding evidence in the source. | For each sentence in the summary, require a citation to a source turn ID. Fail if any sentence lacks a valid source mapping. |
Irrelevance Filtering | The summary excludes conversational filler, redundant tool call logs, and successful intermediate steps that do not affect final state or pending actions. | The summary includes verbose restatements of tool call arguments and results that were already superseded by later calls. | Check for duplicate or superseded information. Fail if the summary repeats details from a tool call whose result was later overwritten or invalidated. |
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 frontier model (GPT-4o, Claude 3.5 Sonnet). Remove strict schema enforcement and rely on the model's native JSON mode. Accept markdown-wrapped JSON and parse it loosely in application code. Drop the eval harness initially and spot-check summaries manually against 5-10 long conversations.
Watch for
- Hallucinated tool results when the model compresses gaps in tool call history
- Missing
pending_actionsarray when the conversation ends mid-task - Summary drift toward narrative prose instead of structured fields

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