Persistent chat products must balance resource cleanup against the risk of interrupting active multi-step workflows. This prompt is designed for that decision point: it analyzes elapsed time, conversation state, and pending work to produce a structured timeout action—warn, pause, or terminate—along with a user-facing message and an internal state transition. The ideal user is a platform engineer or backend developer building a session management service that needs context-aware decisions, not just a simple countdown timer. Required context includes the full conversation summary, a list of unresolved actions, the elapsed idle time, and the platform's timeout policy thresholds.
Prompt
Session Timeout and Inactivity Handling Prompt

When to Use This Prompt
Defines the operational boundaries for the session timeout prompt, clarifying when an LLM-based decision is appropriate versus when application-layer timers should take over.
This prompt should be invoked by a session watchdog service when a user's idle time crosses a configurable threshold (e.g., 5 minutes of silence). The service must supply the [CONVERSATION_SUMMARY], [PENDING_ACTIONS], [ELAPSED_IDLE_TIME], and [TIMEOUT_POLICY] as structured inputs. The prompt's output is a machine-readable JSON decision that your application can parse to trigger the appropriate UI state change and database update. Do not use this prompt for real-time voice streams where sub-second decisions are required; that logic belongs in application-layer timers and WebSocket heartbeat handlers, not an LLM call. Similarly, do not use it for simple stateless APIs where there is no conversation state to evaluate.
Before integrating, define your platform's timeout tiers (e.g., warning at 5 min, pause at 10 min, termination at 30 min) and encode them in the [TIMEOUT_POLICY] input. The prompt's value comes from its ability to override a mechanical termination when it detects an active multi-step workflow—such as a user in the middle of a booking flow who is simply gathering documents. To validate this behavior, build an eval set that includes scenarios with open pending actions and verify that the prompt returns a warn or pause action rather than terminate. The next section provides the exact prompt template you can copy and adapt.
Use Case Fit
Where the Session Timeout and Inactivity Handling Prompt works and where it introduces operational risk.
Good Fit: Persistent Chat Products
Use when: you have a long-lived chat UI where users may walk away mid-task. The prompt reliably decides whether to warn, pause, or terminate based on elapsed time and conversation state. Guardrail: always pair the prompt's decision with a hard application-layer timeout that can force-terminate if the model call fails.
Bad Fit: Real-Time Critical Workflows
Avoid when: the system must respond to inactivity in sub-second timeframes or when a timeout decision cannot tolerate model latency. The prompt adds a full LLM round-trip, making it unsuitable for hard real-time control loops. Guardrail: use deterministic, rule-based timeouts for real-time systems and reserve this prompt for user-facing messaging and state transitions.
Required Inputs
What you must provide: elapsed time since last user action, conversation state summary, pending work indicators, and any active multi-step workflow flags. Guardrail: if any required input is missing or stale, the prompt must default to a conservative action (warn or pause) rather than terminating an active workflow.
Operational Risk: Inappropriate Termination
Risk: the model terminates a session while the user is still engaged in a multi-step workflow, causing data loss and frustration. Guardrail: implement a hard rule that sessions with active pending actions or uncommitted work cannot be terminated by the model alone—require explicit user confirmation or escalate to a human review queue.
Operational Risk: Warning Fatigue
Risk: the prompt generates too many low-value warnings, training users to ignore them. Guardrail: throttle warning frequency by tracking the last warning timestamp and suppressing repeat warnings within a configurable cooldown window. Only escalate to pause or terminate when the cooldown is exceeded.
Operational Risk: State Drift on Resume
Risk: after a pause, the restored session context is stale or contradictory, causing the assistant to make decisions on outdated information. Guardrail: always run a session continuity validation check after resuming from a paused state before allowing the assistant to act on restored context.
Copy-Ready Prompt Template
A production-ready prompt template for deciding whether to warn, pause, or terminate an idle session, with structured output and adaptation guidance.
The following prompt template is designed to be copied directly into your system prompt or a dedicated timeout-handling module. It accepts live session data through square-bracket placeholders that must be replaced before each invocation. The prompt produces a structured JSON decision—WARN, PAUSE, or TERMINATE—along with a user-facing message and an internal state transition record. This template assumes you have already instrumented your application to track elapsed idle time, conversation phase, and pending work items.
textYou are a session lifecycle manager for a persistent chat product. Your job is to decide how to handle an idle session based on elapsed time, conversation state, and pending work. ## INPUT - Current idle time: [IDLE_TIME_SECONDS] - Session duration: [SESSION_DURATION_SECONDS] - Conversation phase: [CONVERSATION_PHASE] # one of: ONBOARDING, ACTIVE_TASK, CLARIFICATION, WAITING_USER, IDLE - Pending actions: [PENDING_ACTIONS] # JSON array of incomplete tasks with descriptions and ages - Unresolved questions: [UNRESOLVED_QUESTIONS] # JSON array of unanswered questions with ages - Last user message timestamp: [LAST_USER_TIMESTAMP] - Last assistant message timestamp: [LAST_ASSISTANT_TIMESTAMP] - User type: [USER_TYPE] # one of: FREE, PRO, ENTERPRISE - Active multi-step workflow: [ACTIVE_WORKFLOW] # boolean - Workflow step count: [WORKFLOW_STEP_COUNT] - Completed workflow steps: [COMPLETED_WORKFLOW_STEPS] ## CONSTRAINTS - [CONSTRAINTS] # JSON object with timeout thresholds, e.g., {"warn_seconds": 300, "pause_seconds": 600, "terminate_seconds": 1800, "enterprise_grace_multiplier": 2.0} ## OUTPUT SCHEMA Return ONLY valid JSON with this exact structure: { "decision": "WARN" | "PAUSE" | "TERMINATE" | "NO_ACTION", "confidence": 0.0-1.0, "user_message": "string", "internal_state_transition": { "from_state": "string", "to_state": "string", "reason_code": "string", "preserved_context": ["list of context keys to retain"], "discarded_context": ["list of context keys to discard"] }, "escalation_required": boolean, "escalation_reason": "string or null" } ## DECISION RULES 1. If ACTIVE_WORKFLOW is true and WORKFLOW_STEP_COUNT > COMPLETED_WORKFLOW_STEPS, prefer WARN over PAUSE or TERMINATE. 2. If CONVERSATION_PHASE is WAITING_USER, treat idle time as expected; do not TERMINATE unless idle exceeds 2x the standard threshold. 3. If USER_TYPE is ENTERPRISE, apply the enterprise grace multiplier to all thresholds. 4. If PENDING_ACTIONS or UNRESOLVED_QUESTIONS are non-empty, include them in preserved_context. 5. If decision is TERMINATE, always set escalation_required to true and provide a reason. 6. If decision is PAUSE, serialize session state before transitioning. ## EXAMPLES [EXAMPLES] # Optional: few-shot examples of correct decisions with rationale ## RISK LEVEL [RISK_LEVEL] # HIGH, MEDIUM, or LOW; affects confidence threshold and escalation behavior
To adapt this template, start by replacing the square-bracket placeholders with live data from your session store. The [CONSTRAINTS] block should be populated with your product's specific timeout thresholds—these will vary by user tier, regulatory environment, and workflow criticality. The [EXAMPLES] block is optional but strongly recommended for production deployments; include 2-3 few-shot examples that demonstrate correct handling of edge cases such as active multi-step workflows, enterprise users near threshold boundaries, and sessions where the user appears to be composing a long response. The [RISK_LEVEL] parameter should be set based on the domain: use HIGH for healthcare, finance, or legal contexts where premature termination could cause harm, and LOW for casual chat products where re-engagement is trivial. After adapting, validate that your replacement logic handles missing or null fields gracefully—the prompt should still produce a safe default decision (NO_ACTION with low confidence) when input data is incomplete.
Prompt Variables
Each placeholder required by the Session Timeout and Inactivity Handling Prompt. Use these to wire the prompt into your application harness, validate inputs before inference, and log decisions for audit.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CURRENT_TIMESTAMP] | The wall-clock time when the timeout check runs, used to calculate elapsed idle time. | 2026-01-15T14:32:00Z | Must be ISO 8601 UTC. Reject if timestamp is in the future or older than the last known activity timestamp. |
[LAST_ACTIVITY_TIMESTAMP] | The timestamp of the most recent user message, tool call, or explicit keep-alive signal. | 2026-01-15T14:17:00Z | Must be ISO 8601 UTC. Reject if later than [CURRENT_TIMESTAMP]. Null allowed only for uninitialized sessions. |
[SESSION_STATE_SUMMARY] | A structured summary of the active conversation including pending actions, unresolved questions, and current workflow phase. | User is mid-checkout. Cart has 3 items. Awaiting shipping address. Payment not started. | Must be a non-empty string if the session is in an active multi-step workflow. Validate that pending actions are explicitly listed. |
[IDLE_TIMEOUT_SECONDS] | The configured idle duration after which the system should warn or terminate the session. | 900 | Must be a positive integer. Reject values below 60 seconds for production. Validate against the deployment's configured timeout policy. |
[WARNING_THRESHOLD_SECONDS] | The idle duration at which a warning message should be shown before hard termination. | 600 | Must be a positive integer less than [IDLE_TIMEOUT_SECONDS]. Reject if warning threshold equals or exceeds the hard timeout. |
[SESSION_POLICY] | The business rules governing timeout behavior: whether to warn, pause, or terminate, and any workflow exceptions. | Warn at 10 min idle. Terminate at 15 min idle. Never terminate during payment capture step. | Must be a non-empty string. Validate that policy references match known workflow step names in [SESSION_STATE_SUMMARY]. |
[OUTPUT_SCHEMA] | The expected JSON schema for the timeout action decision, including action type, user message, and state transition. | { action: 'warn' | 'pause' | 'terminate' | 'none', message: string, new_state: string } | Must be a valid JSON Schema object or TypeScript interface string. Reject if schema lacks required fields: action, message, new_state. |
Implementation Harness Notes
How to wire the session timeout prompt into a production chat application with validation, logging, and safe fallbacks.
This prompt is not called on every user message. Instead, wire it into a server-side inactivity timer that fires at configured intervals. Reset the timer on each user action—message sent, button clicked, tool approved—and invoke the prompt only when the timer expires. This keeps the model out of the hot path for active conversations and prevents unnecessary latency and cost. The timer interval should be set to a fraction of your overall session timeout window so the prompt has time to execute and, if needed, warn the user before a hard termination.
Validate the output JSON against the expected schema before acting on the decision. The prompt returns a structured object with an action field (warn, pause, terminate) and a user_message string. Reject any response that does not parse as valid JSON or that contains an unrecognized action. Log every timeout decision with the session ID, timestamp, elapsed inactivity duration, model rationale, and the raw and parsed output. This audit trail is essential for debugging false terminations and tuning thresholds. For high-risk workflows such as healthcare or finance, route any terminate decision to a human review queue before executing it—do not automatically end sessions that may contain incomplete clinical documentation or in-progress transactions.
Implement a circuit breaker for model failures. If the model returns invalid JSON three times consecutively, stop calling the prompt and fall back to a deterministic timeout based on [TIMEOUT_POLICY] thresholds alone. This prevents a broken model or upstream API outage from blocking session lifecycle management entirely. The fallback should still log the event and, if configured, notify an on-call channel. When the model begins returning valid responses again, automatically restore the prompt-driven path. Model choice matters here: prefer a fast, cheap model for this classification task—a small model with low latency is better than a large model that adds seconds to a timeout decision. The prompt is designed to work with compact instruction-following models that can produce reliable JSON without reasoning overhead.
Expected Output Contract
The structured JSON the prompt must return. Validate every field before acting on the decision.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
action | enum: warn | pause | terminate | none | Must be exactly one of the allowed enum values. Reject any other string. | |
action_reason | string | Must be non-empty and reference at least one of: elapsed time, conversation state, or pending work. | |
user_facing_message | string | Must be non-empty and appropriate for the action. For 'terminate', must include session closure language. For 'warn', must include time remaining. | |
internal_state_transition | object | Must contain 'from_state' and 'to_state' keys with valid session state enum values. Reject if states are identical unless action is 'none'. | |
elapsed_idle_seconds | integer | Must be a non-negative integer. If 0, action must be 'none'. Reject negative values. | |
pending_work_detected | boolean | Must be true or false. If true and action is 'terminate', require a 'pending_work_handling' field in the output. | |
confidence | number | If present, must be between 0.0 and 1.0 inclusive. If below 0.7, flag for human review before acting on 'terminate' or 'pause'. | |
context_snapshot_id | string | If action is 'pause' or 'terminate', this field is required. Must match the pattern 'snap_[timestamp]_[hash]'. Reject on format mismatch. |
Common Failure Modes
What breaks first when a session timeout prompt is deployed in a persistent chat product, and how to prevent it.
Inappropriate Termination During Active Workflows
What to watch: The prompt terminates a session while the user is in the middle of a multi-step transaction, such as a purchase or a complex configuration, because the idle timer expired. This causes data loss and extreme user frustration. Guardrail: Require the prompt to check for pending_actions or active_workflow_step in the conversation state before deciding. If a critical workflow is open, the only allowed actions are warn or extend, never terminate.
Silent State Mutation Without User Notification
What to watch: The prompt correctly decides to pause or terminate a session but fails to generate a clear, user-facing message explaining what happened and why. The user returns to a blank screen or a confusing state. Guardrail: The output schema must require a non-null user_message string for every decision except continue. Add an eval assertion that the message explains the reason for the timeout and the next steps for the user.
Brittle Time-Based Logic with Edge Cases
What to watch: The prompt misinterprets relative time descriptions like 'a few minutes ago' or fails when the last_active_timestamp is malformed, null, or in an unexpected timezone. This leads to premature termination or zombie sessions. Guardrail: Always pass an absolute, ISO 8601 formatted current_time and last_active_time in the prompt. Instruct the model to calculate the idle_duration_seconds explicitly before reasoning, and to default to the safest action (warn) if the calculation is ambiguous.
Ignoring Explicit User Intent to Pause
What to watch: A user says 'I'll be back in 10 minutes' but the prompt terminates the session after a standard 5-minute timeout, discarding the user's stated intent. Guardrail: The prompt must prioritize explicit user signals from the conversation history. Add a pre-processing step that extracts user-stated delay intentions and injects them as a user_declared_pause_until constraint, which overrides the default timeout logic.
Context Contamination on Resume
What to watch: After a timeout warning or pause, the model fails to properly re-establish context, treating the resumption as a new topic or losing critical prior instructions. Guardrail: The timeout decision output must include a resume_context_snapshot object containing the last active intent and key decisions. This snapshot is injected back into the prompt on the next user turn to ensure continuity.
High-Frequency Warning Spam
What to watch: The prompt generates a warning on every check cycle, flooding the user with 'Are you still there?' messages every minute. This is a nuisance that drives users away. Guardrail: Implement a last_warning_timestamp in the session state. The prompt instructions must include a rule to suppress a new warning if the previous one was sent within a configurable warning_cooldown_seconds period.
Evaluation Rubric
Run these checks against a golden dataset of 50+ session scenarios to validate the timeout action decision, user-facing message, and internal state transition before shipping.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Timeout Action Decision Accuracy | Action matches the labeled ground-truth action (warn, pause, terminate) for the given elapsed time, conversation state, and pending work. | Action misalignment: terminate chosen for active multi-step workflow, or warn chosen when hard timeout exceeded. | Run golden dataset through prompt; compare predicted action to expected action; compute exact-match accuracy and confusion matrix. |
User-Facing Message Tone Appropriateness | Message tone matches the action severity: polite for warn, informative for pause, conclusive for terminate. No alarmist language for warnings. | Alarmist termination language in a warning message, or casual tone in a termination message. | LLM-as-judge evaluation using a tone rubric; spot-check 20% of outputs manually for tone alignment with action. |
Pending Work Preservation | Pause and warn actions preserve all pending actions, unresolved questions, and active constraints in the internal state transition payload. | Pending action list is truncated or missing after a pause decision; unresolved questions dropped during a warning. | Schema validation on state transition payload; assert pending_actions and unresolved_questions arrays are non-empty when present in input context. |
Idle Time Calculation Correctness | Elapsed idle time in the decision rationale matches the difference between last_user_activity_timestamp and current_timestamp provided in [SESSION_CONTEXT]. | Rationale references an idle duration that does not match the provided timestamps, or uses a hardcoded value. | Parse rationale text for stated duration; compute expected duration from input timestamps; assert numeric equality within a 1-second tolerance. |
State Transition Schema Validity | Internal state transition payload is valid JSON and conforms to the [OUTPUT_SCHEMA] with all required fields present. | Missing required field (e.g., new_state, reason_code); invalid JSON; extra untyped fields that break downstream deserialization. | Automated schema validation against the expected JSON Schema; reject any output that fails structural validation. |
Reason Code Correctness | Reason code in the state transition matches the documented reason code taxonomy for the chosen action and trigger condition. | Generic reason code used when a specific code is available; reason code inconsistent with the action (e.g., USER_REQUESTED on a timeout). | Map predicted reason code to action and trigger; assert the code exists in the allowed taxonomy for that combination. |
No Premature Termination on Active Workflows | Terminate action is never selected when [PENDING_WORK] contains incomplete multi-step tasks or [UNRESOLVED_QUESTIONS] is non-empty, unless a hard deadline is explicitly exceeded. | Terminate action selected while pending_work array contains items with status 'in_progress' and no hard deadline override is present. | Filter golden dataset to active-workflow scenarios; assert terminate action rate is 0% for this subset. |
Re-engagement Path Clarity | Pause and terminate messages include a clear next step: how to resume, where to find saved state, or how to start a new session. | Pause message omits resume instructions; terminate message provides no path to recover or restart. | LLM-as-judge check for presence of a re-engagement instruction; manual review of 10% of pause/terminate outputs for actionability. |
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 elapsed-time check. Use a single [ELAPSED_SECONDS] variable and a hardcoded threshold. Skip the multi-factor scoring and state-transition logic. Return a flat JSON decision with action and message fields only.
codeYou are a session timeout monitor. The user has been inactive for [ELAPSED_SECONDS] seconds. The inactivity threshold is 300 seconds. If elapsed < 300, return {"action": "continue", "message": null}. If elapsed >= 300, return {"action": "warn", "message": "You've been idle for a while. Still there?"}.
Watch for
- No awareness of active multi-step workflows; will warn mid-task
- Hardcoded thresholds break across different session types
- Missing conversation state means pending actions are ignored

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