This prompt is a diagnostic and corrective tool for agent observability systems that monitor autonomous agent trajectories. Its primary job is to programmatically detect when an agent's current action path has diverged from its stated plan and to produce a structured, machine-readable assessment with a re-aligned next step. The ideal user is an AI reliability engineer or agent-framework builder integrating this prompt into a runtime harness, not an end-user interacting with a chat interface. You should use this prompt when your agent runtime has access to both the original plan and the sequence of completed actions, and you need an automated recovery signal to prevent cascading failures without restarting the entire agent loop.
Prompt
Agent Drift Detection and Correction Prompt

When to Use This Prompt
Identifies the specific production scenarios where the Agent Drift Detection and Correction Prompt provides reliable, programmatic recovery, and clarifies when it should not be used.
Concretely, deploy this prompt inside a drift_check function that is called after every N actions or when a heuristic monitor flags a potential divergence. The function must provide the prompt with the original [PLAN], the [ACTION_HISTORY], and the [CURRENT_OBSERVATION]. The expected output is a JSON object containing a drift_detected boolean, a drift_assessment string, and a corrected_next_action object. This structured output allows the agent harness to branch logic: if drift_detected is true, the harness replaces the current next action with the corrected one; if false, it continues. This prompt is not a replacement for a planner. It corrects local drift, not a fundamentally flawed plan. Do not use it for generating initial plans, for agents without a traceable action history, or for evaluating the quality of a final answer to a user.
Avoid using this prompt in isolation without evaluation guards. False-positive drift flags can cause an agent to unnecessarily second-guess a valid path, leading to thrashing. Implement a cooldown or a minimum action threshold before re-invoking the drift check to prevent over-correction. In high-stakes environments where a corrected action could have irreversible side effects (e.g., sending an email, modifying a database record), always route the corrected_next_action to a human approval queue before execution. The next step after integrating this prompt is to build a set of evaluation cases with known drift and non-drift trajectories to calibrate your detection threshold and ensure the prompt's assessment aligns with your operational definition of a plan deviation.
Use Case Fit
Where the Agent Drift Detection and Correction Prompt works and where it introduces new risks. Use these cards to decide if this prompt fits your agent architecture before integrating it into a production harness.
Good Fit: Multi-Step Autonomous Agents
Use when: Your agent executes plans spanning 5+ tool calls where subtle trajectory drift accumulates and causes downstream failures. Why: The prompt re-anchors the agent to the original goal without restarting from scratch, preserving completed work while correcting course.
Bad Fit: Single-Step Tool Calls
Avoid when: The agent makes exactly one tool call per user request with no plan to deviate from. Why: Drift detection adds latency and token overhead without benefit. A simple retry-on-failure pattern is sufficient for atomic operations.
Required Inputs
Must provide: The original plan with ordered steps, the agent's completed actions with tool outputs, the current trajectory state, and the stated goal. Guardrail: If any of these inputs are missing or stale, the drift assessment will be unreliable. Validate input completeness before invoking the prompt.
Operational Risk: False-Positive Drift Flags
What to watch: The model flags acceptable plan adaptations as drift, triggering unnecessary re-planning that discards valid progress. Guardrail: Implement a severity threshold in the harness. Only act on drift assessments when the divergence score exceeds a calibrated minimum. Log all drift flags for human review during the first 100 production runs.
Operational Risk: Over-Correction Cascades
What to watch: The correction prompt generates a new plan that conflicts with completed steps, causing the agent to undo work or enter a correction loop. Guardrail: Include completed-and-verified actions as immutable context in the prompt. Add a harness-level check that prevents the agent from re-executing steps marked as done.
Operational Risk: Drift Detection Latency
What to watch: Running drift detection after every tool call adds 500ms-2s per step, making the agent feel sluggish in interactive use cases. Guardrail: Trigger drift detection on a cadence (every N steps) or on exception signals (unexpected tool output, empty result, repeated action) rather than after every single step.
Copy-Ready Prompt Template
A copy-ready template for detecting agent plan drift and producing a re-aligned next step.
This template is designed to be injected into an agent harness when an observability system flags a potential divergence from the stated plan. It forces the model to compare the original objective and planned trajectory against the actual actions taken, then produce a structured drift assessment and a single, corrected next step. The prompt is self-contained and can be used as a standalone correction call or as a system-level instruction that persists across turns.
textYou are an agent trajectory auditor. Your task is to detect and correct plan drift. [ORIGINAL_OBJECTIVE] [OBJECTIVE] [ORIGINAL_PLAN] [PLAN_STEPS] [ACTUAL_TRAJECTORY] [COMPLETED_ACTIONS] [DRIFT_THRESHOLD] [THRESHOLD_DESCRIPTION] [CONSTRAINTS] [CONSTRAINTS] [OUTPUT_SCHEMA] { "drift_detected": boolean, "drift_severity": "none" | "minor" | "major" | "critical", "drift_evidence": [ { "planned_step": string, "actual_action": string, "divergence_description": string } ], "goal_still_achievable": boolean, "recovery_action": { "action_type": "continue" | "correct" | "rollback" | "replan" | "escalate", "corrected_next_step": string, "rollback_target_step_index": number | null, "revised_sub_plan": [string] | null, "escalation_reason": string | null }, "confidence": number } [EXAMPLES] [FEW_SHOT_EXAMPLES] [RISK_LEVEL] [RISK_LEVEL] Instructions: 1. Compare each step in [ORIGINAL_PLAN] against the actions in [ACTUAL_TRAJECTORY]. 2. If any action deviates from the plan, assess whether the deviation serves the original objective or represents drift. 3. Classify drift severity using [DRIFT_THRESHOLD]. 4. If drift is detected, produce exactly one recovery action. Do not propose multiple alternatives. 5. If the goal is no longer achievable, set recovery_action.action_type to "escalate" and provide a clear escalation_reason. 6. If the trajectory is on track, set drift_detected to false and recovery_action.action_type to "continue". 7. Output valid JSON matching [OUTPUT_SCHEMA] exactly. No additional text.
To adapt this template, replace each square-bracket placeholder with runtime values from your agent harness. [ORIGINAL_OBJECTIVE] should contain the user's original request or goal statement. [ORIGINAL_PLAN] should list the planned steps in order. [ACTUAL_TRAJECTORY] should include the sequence of actions the agent actually took, including tool calls, responses, and any errors encountered. [DRIFT_THRESHOLD] defines what constitutes minor, major, and critical drift for your use caseāfor example, 'minor: action order swapped but goal unaffected; major: skipped a required verification step; critical: goal no longer achievable.' [CONSTRAINTS] should include any hard rules the agent must follow, such as 'never modify production data without confirmation.' [FEW_SHOT_EXAMPLES] should provide 2-3 examples of drift detection and correction to calibrate the model's judgment. [RISK_LEVEL] should be set to 'low', 'medium', 'high', or 'critical' to guide the model's conservatism. After receiving the output, validate the JSON against the schema before acting on the recovery_action. For high-risk or critical workflows, route the drift assessment to a human reviewer before executing any rollback or replan action.
Prompt Variables
Required inputs for the Agent Drift Detection and Correction Prompt. Each placeholder must be populated by the agent harness before the prompt is assembled and sent to the model. Missing or malformed variables will cause the drift assessment to fail silently or produce false-positive corrections.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[ORIGINAL_GOAL] | The agent's stated objective and constraints from the initial plan | Book a round-trip flight from SFO to JFK for March 12-15 under $500, window seat preferred | Must be a non-empty string. Compare against [CURRENT_TRAJECTORY] to detect semantic drift. Null or truncated goals produce false drift flags. |
[CURRENT_TRAJECTORY] | The last N actions, tool calls, and observations executed by the agent | [{"step":3,"action":"search_flights","params":{"origin":"SFO","destination":"LAX"},"observation":"3 results found"}] | Must be a valid JSON array of action-observation pairs. Minimum 3 steps required for drift detection. Empty array triggers an insufficient-data escalation. |
[PLAN_STEPS] | The original ordered list of planned actions the agent was expected to follow | [{"step":1,"action":"search_flights","params":{"origin":"SFO","destination":"JFK"}},{"step":2,"action":"filter_by_price","params":{"max":500}}] | Must be a valid JSON array with step, action, and params fields. Compare each step against [CURRENT_TRAJECTORY] for deviation. Missing params fields are treated as unconstrained steps. |
[DRIFT_THRESHOLD] | The severity score (0.0-1.0) above which a deviation is flagged as drift requiring correction | 0.7 | Must be a float between 0.0 and 1.0. Lower values increase sensitivity and false-positive risk. Higher values risk missing genuine drift. Default 0.7 if not provided. |
[MAX_RETRY_BUDGET] | The remaining number of correction attempts allowed before escalation to human review | 2 | Must be a non-negative integer. If 0, the prompt must produce an escalation summary instead of a correction. Negative values are invalid and must be rejected by the harness. |
[TOOL_CATALOG] | The list of available tools with their schemas and capabilities the agent can use for correction | [{"name":"search_flights","params":["origin","destination","date"]},{"name":"book_flight","params":["flight_id","seat_preference"]}] | Must be a valid JSON array of tool definitions. Missing tools that appear in the original plan will cause correction proposals to fail. Validate tool availability before prompt assembly. |
[OBSERVATION_LOG] | Full log of tool outputs, errors, timeouts, and partial results from the current trajectory | [{"tool":"search_flights","status":"success","result":"3 flights found"},{"tool":"filter_by_price","status":"error","error":"timeout after 5s"}] | Must be a valid JSON array with tool, status, and result or error fields. Incomplete logs cause the drift assessment to miss failure-driven deviations. Null allowed if no errors occurred. |
[STATE_SNAPSHOT] | The current agent state including completed steps, pending actions, and any saved checkpoints | {"completed_steps":[1,2],"pending_steps":[3,4],"last_checkpoint":2,"checkpoint_data":{"flights_found":3}} | Must be a valid JSON object with completed_steps, pending_steps, and optional checkpoint_data. Used to determine whether correction requires rollback or forward continuation. Null allowed if no checkpoint system is in use. |
Implementation Harness Notes
How to wire the drift detection prompt into an agent observability system with validation, retries, and escalation controls.
The drift detection prompt is not a standalone artifact; it is a component inside an agent observability harness that compares the agent's current trajectory against the stated plan at configurable intervals. Wire this prompt into your agent runtime as a sidecar evaluation step that fires after every N tool calls, after high-risk actions, or when a trajectory monitor detects semantic divergence from the plan embedding. The harness should supply the prompt with the original plan, the action history, the current state, and any tool outputs that triggered the drift check. The prompt returns a drift assessment and a re-aligned next step, but the harness is responsible for deciding whether to apply that correction, request human review, or escalate.
Build the harness with three guard layers. First, validate the prompt output schema: the drift severity score must be a float between 0.0 and 1.0, the drift_detected field must be a boolean, and the corrected_next_action must include a tool name, arguments, and a justification string. If the output fails schema validation, retry once with a stricter format instruction appended to the prompt. Second, implement a false-positive drift check: if the drift severity exceeds your threshold but the corrected action is identical to the agent's current intended action, suppress the correction and log the event for threshold tuning. Third, enforce an over-correction guard: compare the corrected action's goal alignment score against the original plan's goal embedding. If the corrected action would discard more than 20% of completed progress without clear justification, route to a human reviewer instead of applying the correction automatically. Log every drift check with the plan version, trajectory snapshot, severity score, correction applied, and whether human review was triggered.
For model choice, use a fast instruction-following model with low latency for the drift check pathāthis prompt runs frequently and must not become a bottleneck. Reserve larger reasoning models for the correction path only when drift severity exceeds 0.7 or when the harness detects a pattern of repeated low-severity drift flags across consecutive checks. Track a drift budget per agent session: if more than three corrections are applied within a single task, stop autonomous correction and escalate the full trajectory to a human operator with the accumulated drift log. Never allow the drift prompt to modify the original plan directly; it may only suggest re-aligned next actions within the existing plan's constraints. The harness must preserve the original plan as the source of truth and append corrections as annotated deviations.
Expected Output Contract
Fields, format, and validation rules for the agent drift detection and correction response. Use this contract to parse, validate, and route the model output in your agent harness.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
drift_detected | boolean | Must be true or false. If null or missing, retry with stricter boolean constraint. | |
drift_severity | string enum: none | minor | major | critical | Must match one of the allowed enum values. If drift_detected is false, severity must be none. | |
drift_evidence | array of objects with fields: observation (string), timestamp (string or null), source_step (string) | true if drift_detected is true | Each observation must be a non-empty string. source_step must reference a step from the original plan. If drift_detected is false, array must be empty. |
original_goal | string | Must be a non-empty string that matches the goal provided in [ORIGINAL_PLAN]. Validate via semantic similarity threshold > 0.85 against the input goal. | |
deviation_summary | string | true if drift_detected is true | Must be a non-empty string describing how the agent trajectory diverged. If drift_detected is false, value must be null. |
re_aligned_next_action | object with fields: action (string), tool (string or null), arguments (object or null), rationale (string) | true if drift_detected is true | action must be non-empty. tool must match an available tool in [AVAILABLE_TOOLS] or be null for internal actions. arguments must conform to the tool schema if tool is specified. rationale must be non-empty. If drift_detected is false, value must be null. |
requires_escalation | boolean | Must be true if drift_severity is critical or if re_aligned_next_action cannot be determined. Otherwise false. | |
escalation_reason | string | true if requires_escalation is true | Must be a non-empty string explaining why human intervention is needed. If requires_escalation is false, value must be null. |
Common Failure Modes
Agent drift detection prompts fail in predictable ways. These are the most common production failure modes and the guardrails that prevent them.
False-Positive Drift Flags
What to watch: The prompt flags legitimate plan adaptations as drift. Agents that dynamically reorder steps or substitute equivalent tools get incorrectly corrected, causing unnecessary replanning and latency. Guardrail: Require the drift prompt to distinguish between plan deviation (acceptable adaptation) and plan violation (breaking constraints or skipping required steps). Include explicit examples of acceptable adaptations in the prompt.
Over-Correction to Original Plan
What to watch: The correction prompt forces the agent back to the original plan even when new evidence shows the original plan is now suboptimal or invalid. The agent loses progress and context gained during execution. Guardrail: Include a staleness check in the drift prompt. Before re-anchoring, ask whether the original plan assumptions still hold. If not, trigger a re-plan rather than a correction.
Drift Accumulation Across Turns
What to watch: Small deviations compound over multiple agent turns until the trajectory is unrecognizable. Single-turn drift detection misses the cumulative effect. Guardrail: Track a drift score across turns using a lightweight metric (e.g., cosine similarity between current trajectory embedding and plan embedding). Escalate when the cumulative score crosses a threshold, not just on single-turn flags.
Correction Loop Instability
What to watch: The correction prompt produces a new action that itself gets flagged as drift on the next turn, creating a ping-pong loop between the agent and the correction system. Guardrail: Enforce a retry budget on corrections. After two consecutive corrections, stop the loop and escalate to a human or trigger a full re-plan. Log the correction chain for post-mortem analysis.
Goal Misinterpretation in Re-Anchoring
What to watch: The re-anchoring prompt condenses the original goal into a summary that loses critical constraints, edge cases, or success criteria. The agent then pursues a simplified or incorrect version of the goal. Guardrail: Include the full original goal and constraints in the re-anchoring prompt context. Ask the model to explicitly list which constraints remain active before proposing the next action.
Context Window Exhaustion from Drift History
What to watch: The drift detection prompt includes the full agent trajectory for analysis, consuming significant context window space and pushing out other critical instructions or tool schemas. Guardrail: Summarize the trajectory before passing it to the drift prompt. Include only the plan, the last N actions, and key state changes. Use a separate summarization step if the trajectory is long.
Evaluation Rubric
Use this rubric to test the Agent Drift Detection and Correction Prompt before shipping. Each criterion targets a known failure mode in drift assessment and re-alignment. Run these checks against a golden set of trajectory logs with known drift and non-drift cases.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Drift Classification Accuracy | Correctly flags true drift events with >= 90% recall and correctly ignores non-drift trajectory variations with >= 90% specificity | False positives on benign exploration steps or false negatives on clear goal abandonment | Run against a labeled dataset of 50 trajectory segments with ground-truth drift labels; compute precision, recall, and F1 |
Goal Preservation in Re-Alignment | The corrected next step advances the original goal stated in [ORIGINAL_PLAN] without introducing new sub-goals or dropping constraints | Re-aligned step pursues a different objective, drops a required constraint from [CONSTRAINTS], or restarts completed work unnecessarily | Compare the re-aligned step's intent against the original goal and constraints using an LLM judge with a pairwise goal-alignment rubric |
Over-Correction Avoidance | The prompt does not trigger a full plan restart when only a minor trajectory adjustment is needed; completed progress is preserved | Output proposes discarding all prior actions and restarting from step 1 when only the current branch is off-track | Inject drift scenarios where 80% of prior steps are still valid; verify the output references and preserves completed work |
Drift Evidence Citation | Every drift flag includes a specific reference to the plan step, action, or constraint that was violated, quoted from [TRAJECTORY_LOG] | Drift is asserted without citing which plan element was violated or quotes a non-existent log entry | Parse the output for citation fields; verify each citation exists in the input trajectory log using exact string match |
Re-Alignment Action Feasibility | The proposed next action uses tools and parameters available in [AVAILABLE_TOOLS] and respects [RESOURCE_LIMITS] | Proposed action references a tool not in the available set, exceeds token or time budgets, or requires unavailable permissions | Validate the proposed action against the tool schema and resource constraints using a schema validator; flag any tool name or parameter mismatch |
Uncertainty Expression When Ambiguous | When the trajectory shows ambiguous drift (could be exploration or deviation), the output includes an uncertainty qualifier and optionally requests clarification | Output asserts high-confidence drift for ambiguous cases or proposes irreversible corrective actions without qualification | Feed borderline trajectory segments where drift is debatable; check that the output includes uncertainty language or an escalation flag |
Escalation Threshold Respect | When drift severity exceeds [ESCALATION_THRESHOLD], the output triggers escalation rather than attempting autonomous correction | Output attempts to self-correct severe drift that should have been escalated to a human or supervisor agent | Inject drift scenarios with severity scores above the configured threshold; verify the output contains an escalation payload and no autonomous correction |
Output Schema Compliance | The output strictly matches [OUTPUT_SCHEMA] with all required fields present and correctly typed | Missing required fields, extra fields not in schema, or type mismatches that break downstream parsers | Validate the raw output against the JSON schema; reject any response that fails structural validation before evaluating content |
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) and manual review of drift assessments. Skip the formal eval harness initially. Focus on getting the drift detection logic right before adding schema enforcement.
code[DRIFT_DETECTION_PROMPT] You are analyzing an agent's trajectory for plan deviation. Original Plan: [ORIGINAL_PLAN] Completed Steps: [COMPLETED_STEPS] Current Action: [CURRENT_ACTION] Next Planned Step: [NEXT_PLANNED_STEP] Assess whether the agent has drifted from the plan. Return your assessment as: - drift_detected: true/false - drift_severity: "none" | "minor" | "major" | "critical" - explanation: brief reasoning - re_aligned_next_step: suggested correction (null if no drift)
Watch for
- Overly sensitive drift flags on acceptable exploration
- Missing severity calibration for minor vs. major deviations
- No distinction between goal-preserving adaptation and true drift

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