Inferensys

Prompt

Context Drift Detection and Correction Prompt

A practical prompt playbook for detecting and correcting context drift in production AI agent workflows.
Developer reviewing multi-agent chat interface on laptop, agent conversation logs visible, casual coding session at WeWork desk.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Context Drift Detection and Correction Prompt.

This prompt is built for reliability engineers and agent infrastructure developers who need to catch and correct silent reasoning failures in long-running, multi-turn tool-use agents. The core job-to-be-done is automated state reconciliation: comparing the agent's current assumptions and planned actions against the ground-truth state returned by external tools, then producing a structured correction plan. The ideal user is someone operating an agent in production who has observed quality degradation over extended sessions—hallucinated tool results, repeated calls with stale arguments, or plans that no longer match reality—and needs a programmatic checkpoint to restore coherence without restarting the session.

Use this prompt when an agent has completed more than a handful of tool calls and you need to verify that its internal reasoning still aligns with the actual state of external systems. It is appropriate for agents interacting with databases, APIs, file systems, or MCP servers where tool outputs represent a source of truth. The prompt requires the following inputs to be effective: the agent's current stated assumptions or plan, a log of recent tool calls and their actual results, and the system's defined state schema or expected invariants. Do not use this prompt for single-turn tool calls, stateless transformations, or workflows where the cost of a full state comparison exceeds the risk of drift. It is also a poor fit for real-time, latency-sensitive loops where the detection and correction cycle would violate a strict timeout budget.

Before deploying this prompt into an automated harness, you must define what constitutes a drift event for your specific application. A generic prompt will flag too many false positives or miss domain-specific inconsistencies. Work with your engineering team to establish concrete drift categories—such as schema mismatch, stale version identifiers, missing dependencies, or contradictory facts—and encode them in the [DRIFT_CATEGORIES] placeholder. The prompt's value is proportional to the precision of these definitions. For high-risk domains like finance or healthcare, the correction plan this prompt generates must never be auto-applied. Route its output to a human review queue or a restricted sandbox where proposed corrections are validated against the original tool outputs before execution.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Context Drift Detection and Correction Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your operational environment before integrating it into an agent harness.

01

Good Fit: Long-Running Agent Sessions

Use when: agents execute multi-step tool workflows over minutes or hours where early tool results can become stale. Guardrail: trigger drift detection before each high-stakes tool call and after any state-changing operation to prevent cascading errors from outdated assumptions.

02

Bad Fit: Single-Turn Stateless Calls

Avoid when: the agent makes one tool call and terminates, or when all tool results are consumed immediately. Guardrail: skip drift detection for stateless interactions to avoid unnecessary latency and token overhead that adds no reliability benefit.

03

Required Input: Ground-Truth Tool State

Risk: the prompt cannot detect drift without access to current, authoritative tool state for comparison. Guardrail: wire the prompt to a state snapshot function that queries live tool state before each detection pass, and fail closed if the snapshot is unavailable.

04

Required Input: Explicit Assumption Log

Risk: the prompt cannot identify what the agent believes without a structured record of prior assumptions. Guardrail: maintain a running assumption register that logs each inference the agent makes from tool results, with timestamps and source citations for comparison.

05

Operational Risk: False Drift Alerts

Risk: the prompt flags benign state changes as drift, triggering unnecessary corrections that disrupt agent flow. Guardrail: implement a severity threshold that only escalates drift when the semantic meaning of state has changed, not when timestamps or non-functional metadata updates occur.

06

Operational Risk: Missed Corrections

Risk: the prompt fails to detect real drift because the assumption log is incomplete or the comparison criteria are too narrow. Guardrail: run periodic full-state reconciliation passes that compare all active assumptions against ground truth, not just the assumptions tied to the immediate next action.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that compares current agent assumptions against ground-truth tool state and corrects inconsistencies before they compound.

This prompt template is designed to be injected at regular intervals during long-running agent sessions, or triggered when a tool call fails, returns unexpected results, or when the agent's confidence in its current state drops below a threshold. It forces the agent to explicitly list its operating assumptions, compare them against the actual tool state retrieved from the system of record, and produce a corrected state block that replaces the drifted context. The template uses square-bracket placeholders so you can adapt it to your specific tool ecosystem, state schema, and risk tolerance without rewriting the core logic.

text
You are a context integrity monitor for an agent system. Your job is to detect and correct context drift by comparing the agent's current assumptions against ground-truth tool state.

## CURRENT AGENT ASSUMPTIONS
[AGENT_ASSUMPTIONS]

## GROUND-TRUTH TOOL STATE
[TOOL_STATE]

## STATE SCHEMA
[STATE_SCHEMA]

## DRIFT DETECTION RULES
- Compare each field in the agent's assumptions against the corresponding field in the ground-truth tool state.
- Flag any field where the agent's value differs from the ground truth, is missing, or is hallucinated.
- Ignore fields that are intentionally null or undefined in both sources.
- For each flagged field, classify the drift severity as: CRITICAL (would cause downstream tool failure), MODERATE (would degrade output quality), or MINOR (cosmetic or non-blocking).

## CORRECTION RULES
- For CRITICAL and MODERATE drift, produce the corrected value from the ground-truth tool state.
- For MINOR drift, note the discrepancy but do not block execution.
- If the ground-truth tool state is incomplete or unavailable for a required field, mark it as UNRESOLVED and recommend a tool call to retrieve the missing data.
- Do not invent or assume values not present in the ground-truth tool state.

## OUTPUT FORMAT
Return a JSON object with the following structure:
{
  "drift_detected": boolean,
  "drift_summary": "One-sentence summary of findings",
  "drift_items": [
    {
      "field_path": "dot.notation.path.to.field",
      "assumed_value": "value from agent assumptions or null",
      "ground_truth_value": "value from tool state or null",
      "severity": "CRITICAL | MODERATE | MINOR",
      "correction": "corrected value or 'UNRESOLVED'",
      "recommended_action": "apply_correction | fetch_missing_data | ignore"
    }
  ],
  "corrected_state": {
    // Full corrected state object matching STATE_SCHEMA
  },
  "unresolved_fields": ["field_paths that need fetching"],
  "confidence": 0.0_to_1.0
}

## CONSTRAINTS
- Do not modify fields that match between assumptions and ground truth.
- If no drift is detected, return the original assumptions as the corrected_state.
- If [RISK_LEVEL] is HIGH, flag any UNRESOLVED field as CRITICAL and halt downstream execution.
- If [RISK_LEVEL] is LOW, allow execution to proceed with UNRESOLVED fields noted.

Adaptation guidance: Replace [AGENT_ASSUMPTIONS] with the agent's current working memory or state object, typically extracted from the last few turns of conversation or the agent's internal state store. [TOOL_STATE] should be populated by calling the authoritative tool or API immediately before invoking this prompt—do not rely on cached results older than the session's staleness threshold. [STATE_SCHEMA] must be a typed schema definition (JSON Schema, TypeScript interface, or structured field list) that defines required fields, optional fields, and their expected types. [RISK_LEVEL] should be set dynamically based on the downstream action: use HIGH for write operations, financial transactions, or clinical decisions; use LOW for read-only queries or informational outputs. For production use, wrap this prompt in a validation harness that checks the output JSON against the schema before the corrected state replaces the agent's working context.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Context Drift Detection and Correction Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[CURRENT_AGENT_ASSUMPTIONS]

The set of beliefs, inferred facts, or working state the agent currently holds about the session, user, or tool results

{"user_tier": "enterprise", "last_payment_status": "success", "active_tool_ids": ["search", "calc"]}

Must be a valid JSON object. Each key must be a string. Null values allowed but must be explicit. Schema check: compare keys against expected state schema for the session.

[GROUND_TRUTH_TOOL_STATE]

The authoritative state retrieved from tools, databases, or APIs that represents the actual current state

{"user_tier": "free", "last_payment_status": "failed", "active_tool_ids": ["search"]}

Must be a valid JSON object. Source provenance required: each value must be traceable to a specific tool call ID and timestamp. Null values indicate the tool returned no result. Schema must match [CURRENT_AGENT_ASSUMPTIONS] structure.

[SESSION_HISTORY_SUMMARY]

Compressed summary of prior turns, tool calls, and user interactions leading to the current state

Turn 1: user requested upgrade. Turn 2: agent called payment_status tool. Turn 3: agent assumed success based on 200 response.

Must be a non-empty string. Should include turn numbers, tool call IDs, and key outcomes. Truncation check: if history exceeds [MAX_HISTORY_TOKENS], validate that summary was generated by a prior summarization step and not raw truncation.

[DRIFT_DETECTION_RULES]

Explicit rules defining what constitutes a drift, including tolerance thresholds and severity levels

["Mismatch in user_tier is CRITICAL drift", "Mismatch in cached_timestamp > 300s is WARNING drift", "Missing key in assumptions is INFO drift"]

Must be a non-empty array of strings. Each rule must specify a field or condition and a severity level (CRITICAL, WARNING, INFO). Parse check: confirm severity values match allowed enum. Ambiguous rules should be rejected before prompt assembly.

[CORRECTION_POLICY]

Instructions for how the agent should correct detected drift, including escalation and rollback rules

{"auto_correct": ["INFO", "WARNING"], "require_approval": ["CRITICAL"], "rollback_on_failure": true}

Must be a valid JSON object with keys: auto_correct (array of severity strings), require_approval (array of severity strings), rollback_on_failure (boolean). Schema check: severity values must match those in [DRIFT_DETECTION_RULES]. Missing keys should use safe defaults (no auto-correction).

[OUTPUT_SCHEMA]

The expected structure for the drift detection output, including required fields for drift report and correction plan

{"drift_detected": boolean, "drifts": [{"field": string, "assumed_value": any, "actual_value": any, "severity": string, "rule_triggered": string}], "correction_plan": [{"action": string, "tool_call": string, "args": object}]}

Must be a valid JSON Schema or example object. Required fields: drift_detected, drifts, correction_plan. Validation: confirm output can be parsed against this schema after generation. Missing required fields in generated output is a hard failure.

[MAX_RETRIES]

Maximum number of correction attempts before escalating to human review or aborting

3

Must be a positive integer. Range check: 1-10. Values above 10 should trigger a review gate. Null not allowed. Default to 3 if unset but log a warning.

[SESSION_ID]

Unique identifier for the current session, used for logging, trace correlation, and audit

sess_4f8a2b1c-9d3e-4f5a-8b2c-1d3e4f5a6b7c

Must be a non-empty string. Format check: should match UUID or org-specific session ID pattern. Used to correlate drift events in observability systems. Missing or malformed session ID should block prompt execution.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Context Drift Detection and Correction Prompt into an agent monitoring pipeline with validation, retries, and human review gates.

The Context Drift Detection and Correction Prompt is designed to run as a sidecar evaluation step, not as part of the primary agent loop. It should be invoked by a monitoring service or a scheduled checkpoint within a long-running agent session. The prompt compares the agent's current working assumptions against a ground-truth snapshot of tool state, session metadata, and prior confirmed decisions. The output is a structured drift report that downstream systems can use to decide whether to pause the agent, inject a correction, or escalate for human review. This prompt is not a replacement for state validation at the tool-call level; it is a higher-order consistency check that catches reasoning drift that accumulates across multiple turns.

To wire this into an application, build a drift-check trigger that fires after every N tool calls, before high-risk actions, or when a session exceeds a time or token threshold. The harness must assemble two inputs: the agent's current belief state (extracted from conversation history, intermediate reasoning, or a dedicated state object) and the ground-truth tool state (pulled from a persistent store, tool result cache, or direct API query). Pass these into the prompt as [AGENT_BELIEF_STATE] and [GROUND_TRUTH_STATE]. The output must conform to a strict JSON schema with fields for drift_detected (boolean), drift_items (array of objects with field, believed_value, actual_value, severity), and correction_plan (array of recommended actions). Validate this schema before acting on the result. If the output fails schema validation, retry once with a stricter format instruction; if it fails again, log the failure and escalate to a human operator rather than silently continuing.

For high-stakes domains such as healthcare, finance, or infrastructure operations, always insert a human review gate when drift severity is critical or when the correction plan includes irreversible actions. Log every drift detection event with the full prompt input, output, schema validation result, and the action taken (ignore, auto-correct, escalate). This audit trail is essential for debugging false positives, tuning severity thresholds, and proving governance compliance. Avoid running this prompt on every turn in latency-sensitive paths; instead, batch drift checks or run them asynchronously. The most common production failure mode is a false drift alert caused by a stale ground-truth snapshot—always verify that the ground-truth state is fresher than the agent's last belief update before flagging a drift.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, format, and validation rules for the context drift detection and correction prompt output. Use this contract to parse, validate, and act on the model response before applying corrections to agent state.

Field or ElementType or FormatRequiredValidation Rule

drift_detected

boolean

Must be true or false. If true, corrections array must contain at least one entry. If false, corrections must be empty.

drift_summary

string

Non-empty string when drift_detected is true. Must reference at least one specific assumption and one specific tool state field. Null allowed when drift_detected is false.

corrections

array of objects

Must be a valid JSON array. Each element must match the correction_object schema. Array length must be 0 when drift_detected is false, and 1-20 when true.

corrections[].assumption

string

Must quote or paraphrase the agent's current assumption. Must not be empty. Should match a claim found in the [AGENT_CONTEXT] input.

corrections[].ground_truth

string or object

Must reference a specific field or value from [TOOL_STATE]. If the ground truth is a structured value, return the exact value. If it is a document or free text, quote the relevant passage.

corrections[].source_tool

string

Must match a tool name present in [TOOL_STATE]. Must be the tool whose output provides the ground truth. Validation: check against the tool_names list in the input.

corrections[].severity

string

Must be one of: critical, high, medium, low. Critical means the drift would cause an incorrect action or decision. Low means cosmetic or non-material difference.

corrections[].confidence

number

Float between 0.0 and 1.0. Values below 0.7 should trigger human review before applying the correction. Values below 0.5 should be treated as uncertain and not auto-applied.

PRACTICAL GUARDRAILS

Common Failure Modes

Context drift silently corrupts agent reasoning over long sessions. These are the most common failure modes when detecting and correcting drift between agent assumptions and ground-truth tool state.

01

False Drift Alerts on Benign Updates

What to watch: The drift detector flags every state change as a correction event, even when the change is expected (e.g., a timestamp increment or a status progressing normally). This floods the agent with unnecessary correction cycles and breaks execution flow. Guardrail: Include an allowlist of expected state transitions in the prompt. Only flag drift when the delta violates the expected transition graph or when a field value contradicts a prior tool result.

02

Missed Drift from Silent Tool Failures

What to watch: A tool call returns a partial success or an empty result without an explicit error code. The agent treats the response as authoritative, but critical fields are missing or defaulted. The drift detector never fires because it trusts the tool output shape. Guardrail: Require the drift prompt to validate tool output completeness against a required-field schema before comparing to agent assumptions. Flag missing fields as drift even when the tool call appears successful.

03

Correction Loop Instability

What to watch: The drift detector identifies an inconsistency and triggers a correction, but the correction itself introduces a new inconsistency that triggers another correction. The agent oscillates between two states indefinitely. Guardrail: Add a correction depth counter in the prompt. After N correction cycles on the same field within a single turn, stop correcting and escalate to a human or log the conflict for offline review. Never allow unbounded correction loops.

04

Stale Comparison Baseline

What to watch: The drift prompt compares current agent assumptions against a tool state snapshot that is itself stale. The detector reports drift that doesn't exist or misses real drift because the baseline is outdated. Guardrail: Require the prompt to timestamp every state snapshot and reject comparisons where the baseline age exceeds a configured TTL. Force a fresh tool call before running drift detection when the baseline is expired.

05

Over-Correction Destroying Valid Context

What to watch: The correction step replaces the entire agent context block with the new tool state, discarding intermediate reasoning, user preferences, or partial results that were still valid. Guardrail: Design the correction prompt to perform field-level patching, not full context replacement. Only overwrite fields that are explicitly flagged as drifted. Preserve all other context unless it transitively depends on a corrected field.

06

Drift Detection on Irrelevant Fields

What to watch: The detector compares every field in the tool state against agent assumptions, including metadata, debug fields, or internal identifiers that have no bearing on reasoning. This generates noise and wastes context window budget. Guardrail: Define a relevance mask in the prompt that lists which fields matter for decision-making. Only compare fields in the mask. Ignore everything else unless it appears in a dependency chain for a masked field.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the Context Drift Detection and Correction Prompt before production deployment. Each row defines a pass standard, a failure signal, and a concrete test method to validate the prompt's ability to detect and correct inconsistencies between agent assumptions and ground-truth tool state.

CriterionPass StandardFailure SignalTest Method

True Drift Detection

Prompt correctly flags a discrepancy when [AGENT_ASSUMPTION] contradicts [GROUND_TRUTH_TOOL_STATE] by more than one field.

Prompt returns 'no drift detected' when a factual contradiction exists in the provided context.

Inject a prepared context pair with a known contradiction in a critical field (e.g., user role changed from 'admin' to 'viewer'). Assert the output contains a drift flag and identifies the specific field.

False Drift Avoidance

Prompt returns 'no drift detected' when [AGENT_ASSUMPTION] and [GROUND_TRUTH_TOOL_STATE] are semantically equivalent but syntactically different.

Prompt flags a drift alert for inconsequential formatting differences (e.g., '2024-01-01' vs 'Jan 1, 2024') or null vs. empty string.

Run a batch of 20 semantically equivalent state pairs with varying date formats, casing, and whitespace. Assert a false-positive rate below 5%.

Correction Action Specificity

The generated [CORRECTION_PLAN] contains a specific, actionable step to overwrite the stale field in the agent's working context.

The correction plan is vague (e.g., 'update the state') or suggests a full context reset instead of a targeted field update.

Provide a drift alert for a single stale field. Parse the [CORRECTION_PLAN] output and assert it contains the exact field path and the new value from [GROUND_TRUTH_TOOL_STATE].

Multi-Field Drift Handling

Prompt identifies all 3 contradictory fields in a complex state object and generates a correction for each without hallucinating new fields.

Prompt misses one or more contradictions or suggests correcting a field that is already consistent.

Inject a state object with 3 known stale fields and 2 consistent fields. Assert the output lists exactly the 3 stale fields and proposes correct values for each.

Uncertainty Flagging

Prompt correctly identifies an ambiguous state where [GROUND_TRUTH_TOOL_STATE] is missing a required field and outputs an [UNCERTAINTY_FLAG] instead of a forced correction.

Prompt hallucinates a value for the missing field or confidently marks it as 'no drift'.

Provide a ground-truth state with a null value for a critical field. Assert the output contains an [UNCERTAINTY_FLAG] and does not contain a fabricated value.

Schema Adherence

Output strictly conforms to the defined [OUTPUT_SCHEMA] with all required fields present and correctly typed.

Output is missing the [DRIFT_DETECTED] boolean or the [CORRECTION_PLAN] array, or contains extra untyped fields.

Validate the raw output string against the [OUTPUT_SCHEMA] using a JSON Schema validator. Assert no validation errors are thrown.

Tool Output Grounding

Every correction value in [CORRECTION_PLAN] can be traced back to a specific key-value pair in the provided [GROUND_TRUTH_TOOL_STATE].

A correction value appears in the plan that does not exist in the provided ground-truth input.

Parse the [CORRECTION_PLAN] and cross-reference each suggested value against the input [GROUND_TRUTH_TOOL_STATE] object. Assert a 100% match rate.

Latency Budget Compliance

Prompt execution completes within the [MAX_LATENCY_MS] threshold for a context block under [MAX_CONTEXT_TOKENS].

Processing time exceeds the budget, causing a timeout in the agent's main execution loop.

Run the prompt 10 times with a context block at 80% of [MAX_CONTEXT_TOKENS]. Measure the 95th percentile latency and assert it is less than [MAX_LATENCY_MS].

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add strict JSON output schema, confidence scoring per drift item, and a correction block. Include retry logic for malformed outputs and log every detection event with trace IDs.

code
Compare [AGENT_CONTEXT] against [TOOL_STATE].
Return JSON:
{
  "drifts": [
    {
      "field": "string",
      "assumed_value": "any",
      "actual_value": "any",
      "severity": "critical|warning|info",
      "confidence": 0.0-1.0,
      "correction": "string"
    }
  ],
  "no_drift_detected": boolean,
  "correction_summary": "string"
}
Only flag drifts where confidence > 0.7.

Watch for

  • Silent format drift when the model drops fields under context pressure
  • Missing human review gates for critical severity drifts
  • Correction loops that introduce new inconsistencies
Prasad Kumkar

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.