This prompt is designed for plan library systems that need to find the closest archived plan to a new goal. It takes a new goal description and a set of candidate archived plans, then produces a ranked list with similarity scores and rationale. Use this when your agent framework maintains a library of previously successful plans and you want to reduce planning latency, cost, and variance by reusing proven workflows instead of generating plans from scratch. This prompt belongs in the retrieval-and-ranking stage of a plan reuse pipeline, after candidate plans have been fetched from a vector store or metadata index but before a plan is adapted for execution.
Prompt
Plan Similarity Matching Prompt for Reuse Candidates

When to Use This Prompt
Determine the right conditions for deploying plan similarity matching in your agent's retrieval-and-ranking pipeline.
The ideal user is an AI engineer or agent architect building a plan reuse system. You need a structured, repeatable way to compare a new goal against archived plans and decide which ones are worth adapting. The prompt requires two inputs: a clear description of the new goal, including any constraints and success criteria, and a set of candidate plans retrieved from your plan library. Each candidate should include its original goal, steps, tools used, and any recorded outcomes or failure modes. The prompt works best when candidates have been pre-filtered by domain or tool availability to reduce noise before ranking.
Do not use this prompt when the new goal is fundamentally novel with no reasonable archived analogues, when the plan library is empty or contains only deprecated plans, or when the cost of adapting a similar plan exceeds the cost of generating a new one from scratch. This prompt is also insufficient on its own for high-risk domains such as healthcare, finance, or safety-critical operations—always add a human review step before executing a reused plan in those contexts. The prompt ranks similarity but does not validate that the top-ranked plan is safe to execute; pair it with a downstream plan gap analysis or confidence scoring prompt before committing to reuse.
Before wiring this into production, define your similarity thresholds. A score above 0.8 might trigger automatic adaptation, while scores between 0.5 and 0.8 might require human review, and scores below 0.5 should fall back to fresh plan generation. Log every ranking result with the new goal, candidate IDs, scores, and the rationale provided by the model. This trace data becomes your evaluation dataset for tuning retrieval quality and detecting ranking drift over time. Start with a small set of hand-labeled goal-to-plan pairs to calibrate whether the model's similarity judgments match your team's expectations before scaling to automated reuse.
Use Case Fit
Where this prompt works and where it does not. Plan similarity matching is a retrieval-and-ranking task that depends on structured plan representations and clear similarity criteria. Use it when you have a library of archived plans and need to find the best starting point for a new goal. Avoid it when plans are unstructured, goals are radically novel, or the cost of a bad match exceeds the cost of generating a fresh plan.
Good Fit: Mature Plan Libraries
Use when: you have 50+ archived plans with consistent structure, tool annotations, and outcome labels. The prompt excels at surfacing the top 3-5 candidates from a large catalog. Avoid when: your library has fewer than 10 plans or plans lack consistent metadata—ranking quality degrades without sufficient signal.
Good Fit: Repeated Workflow Domains
Use when: your organization runs similar workflows repeatedly—deployment checks, incident response, data pipeline repairs, compliance reviews. Reuse reduces latency and variance. Avoid when: every goal is genuinely novel or one-off; the matching overhead adds cost without benefit.
Required Inputs: Structured Plan Representations
Risk: garbage-in, garbage-out ranking. The prompt requires each archived plan to have a goal description, step list, tool references, and constraint tags. Guardrail: validate that your plan serialization pipeline produces complete records before feeding them to the similarity matcher. Missing fields cause silent ranking failures.
Bad Fit: Radically Different Tool Environments
Risk: the top-ranked plan uses tools that don't exist in the target environment, producing a false-positive match that looks relevant but can't execute. Guardrail: always run a downstream plan gap analysis prompt after similarity matching to catch tool incompatibility before execution begins.
Operational Risk: Over-Reliance on Similarity Scores
Risk: teams treat the top-ranked match as authoritative without reviewing the rationale. Similarity scores can be misleading when goal phrasing differs from plan structure. Guardrail: expose the rationale and confidence breakdown to a human reviewer or require a confirmation step before adapting the matched plan.
Operational Risk: Stale Plan Contamination
Risk: archived plans referencing deprecated APIs, retired tools, or outdated constraints pollute the candidate pool and produce dangerous recommendations. Guardrail: run a plan deprecation prompt on your library before similarity matching, or filter candidates by last-validated date and tool availability.
Copy-Ready Prompt Template
A reusable prompt for ranking archived plans by similarity to a new goal, with structured output and evaluation hooks.
This prompt template is designed to be pasted directly into your agent orchestrator, evaluation harness, or plan library service. It accepts a new goal description and a set of candidate archived plans, then returns a ranked list with similarity scores and rationale. Replace each square-bracket placeholder with real data before execution. The template includes explicit output schema constraints, evaluation criteria, and failure mode handling to make it production-ready.
textYou are a plan similarity analyst for an agent workflow system. Your task is to compare a new goal against a set of archived plans and identify the best reuse candidates. ## INPUT New Goal: [NEW_GOAL_DESCRIPTION] Archived Plans: [ARCHIVED_PLANS_LIST] Each archived plan includes: - plan_id: unique identifier - goal: original goal description - steps: ordered list of step descriptions - tools_used: list of tool names invoked - constraints: list of constraints that applied - success_criteria: how success was measured - failure_modes: known failure modes from execution logs (if available) ## OUTPUT_SCHEMA Return a JSON object with this exact structure: { "candidates": [ { "plan_id": "string", "similarity_score": 0.0-1.0, "rank": integer starting at 1, "rationale": "string explaining why this plan is similar, what matches, and what differs", "matched_aspects": ["list of specific aspects that match the new goal"], "gaps": ["list of aspects from the new goal not covered by this plan"], "adaptation_effort": "low" | "medium" | "high", "reuse_confidence": 0.0-1.0 } ], "no_suitable_match": false, "analysis_notes": "optional summary of overall matching landscape" } ## CONSTRAINTS - Rank by similarity_score descending. - If no plan scores above [MINIMUM_SIMILARITY_THRESHOLD], set no_suitable_match to true and return an empty candidates array. - similarity_score must reflect goal alignment, tool overlap, constraint compatibility, and step structure similarity. - reuse_confidence must account for known failure modes and adaptation effort. - Do not fabricate plan details. Only reference information present in the input. - If fewer than [MINIMUM_CANDIDATES] plans are provided, return all of them ranked. ## EVALUATION CRITERIA - Goal similarity: Does the archived plan address the same type of objective? - Tool overlap: Are the required tools available in the current environment? - Constraint compatibility: Do the original constraints conflict with current constraints? - Step structure: Is the sequence of steps logically applicable to the new goal? - Failure mode relevance: Are known failure modes likely to recur? ## FAILURE MODE HANDLING - If a plan has known failure modes that match the new goal's risk profile, reduce reuse_confidence proportionally. - If tool overlap is below [MINIMUM_TOOL_OVERLAP], set adaptation_effort to "high" and cap reuse_confidence at 0.5. - If constraint conflicts are detected, flag them in gaps and reduce similarity_score. ## EXAMPLES [FEW_SHOT_EXAMPLES] Return only the JSON object. No additional text.
To adapt this template, replace each placeholder with production data. [NEW_GOAL_DESCRIPTION] should be the user's stated objective, cleaned and normalized. [ARCHIVED_PLANS_LIST] should be a JSON array of plan objects retrieved from your plan library. Set [MINIMUM_SIMILARITY_THRESHOLD] based on your tolerance for false positives—start at 0.4 and tune with eval data. Set [MINIMUM_CANDIDATES] to control how many plans must be present before ranking proceeds. [FEW_SHOT_EXAMPLES] should include 2-3 annotated examples showing correct scoring for high-similarity, partial-match, and no-match cases. [MINIMUM_TOOL_OVERLAP] should reflect your environment's tool availability tolerance.
Before deploying, validate that the output JSON parses correctly and that similarity_score values are monotonically decreasing by rank. Run this prompt against a golden dataset of known goal-to-plan pairs where you have ground-truth relevance judgments. Measure ranking quality with NDCG or recall@k. Watch for false positives where the model assigns high scores to structurally similar but semantically irrelevant plans. If your plan library is large, pre-filter candidates with a lightweight retrieval step before invoking this prompt to stay within context limits.
Prompt Variables
Inputs the Plan Similarity Matching Prompt needs to work reliably. Validate each before sending to avoid garbage rankings and false-positive reuse candidates.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[NEW_GOAL] | The user's current objective to match against archived plans | Generate a weekly sales pipeline summary from Salesforce opportunities and send to #sales-standup Slack channel | Must be non-empty string with at least one verb and one noun. Reject if only punctuation or fewer than 10 characters. Check for goal-completeness: contains action, target, and context. |
[PLAN_LIBRARY] | JSON array of archived plan records to search for similarity matches | [{"plan_id": "p-042", "goal": "Generate daily sales report from HubSpot", "steps": [...], "tools": ["hubspot_api", "slack_post"], "tags": ["sales", "reporting", "daily"]}] | Must be valid JSON array with at least one plan object. Each plan object must contain plan_id and goal fields. Reject if empty array. Validate schema before sending: required fields present, no null plan_id values. |
[SIMILARITY_THRESHOLD] | Minimum similarity score (0.0 to 1.0) for a plan to be considered a reuse candidate | 0.65 | Must be a float between 0.0 and 1.0 inclusive. Default to 0.5 if not provided. Values below 0.3 produce too many false positives; values above 0.85 may miss valid adaptations. Log a warning if threshold is outside 0.4-0.8 range. |
[MAX_CANDIDATES] | Maximum number of ranked candidates to return | 5 | Must be a positive integer between 1 and 20. Default to 5 if not provided. Values above 10 increase token cost without proportional value. Reject if 0 or negative. |
[MATCH_DIMENSIONS] | Weighted dimensions the model should consider when computing similarity | ["goal_semantic_similarity:0.4", "tool_overlap:0.25", "domain_match:0.2", "constraint_compatibility:0.15"] | Must be a non-empty array of strings in format 'dimension_name:weight'. Weights must sum to 1.0 ± 0.01. Reject if any dimension name is unrecognized or weights don't sum correctly. Supported dimensions: goal_semantic_similarity, tool_overlap, domain_match, constraint_compatibility, step_structure_similarity, success_rate. |
[OUTPUT_FORMAT] | Desired structure for the ranked candidate list | json | Must be one of: 'json', 'json_with_rationale'. Default to 'json_with_rationale' for auditability. 'json' returns scores only; 'json_with_rationale' includes per-dimension breakdowns and match reasoning. Reject unrecognized values. |
[EXCLUDE_PLAN_IDS] | Plan IDs to exclude from matching, such as already-rejected candidates or deprecated plans | ["p-011", "p-023"] | Must be a JSON array of plan_id strings, or null. If provided, each ID must exist in [PLAN_LIBRARY] or log a warning. Empty array is valid and means no exclusions. Validate that excluded IDs are not the only candidates remaining. |
[MIN_TOOL_OVERLAP] | Minimum number of shared tools required for a plan to be considered, regardless of semantic similarity | 2 | Must be a non-negative integer. Default to 1 if not provided. Set to 0 to disable tool-overlap gating. Useful for preventing matches against plans that use entirely unavailable tool ecosystems. Validate that value does not exceed the tool count in [NEW_GOAL]'s available tool set. |
Implementation Harness Notes
How to wire the Plan Similarity Matching Prompt into a production plan library system with validation, retries, and evaluation.
The Plan Similarity Matching Prompt is designed to be called from a plan library service, not used as a standalone chat. The typical integration pattern is a retrieval-augmented generation (RAG) pipeline: a lightweight embedding-based retrieval step first narrows the candidate pool from thousands of archived plans to a manageable top-N (e.g., 20–50), then this prompt performs the high-precision semantic ranking and rationale generation. This two-stage approach keeps latency and token costs predictable while preserving ranking quality. The prompt expects a structured [NEW_GOAL] object and a [CANDIDATE_PLANS] array, both of which should be assembled by the application layer before the model call.
Validation is critical because the output drives downstream reuse decisions. Implement a post-processing validator that checks: (1) the response is valid JSON matching the [OUTPUT_SCHEMA]; (2) every plan_id in the ranked list exists in the input candidate set; (3) similarity scores are within the declared range (e.g., 0.0–1.0); and (4) each entry includes a non-empty rationale string. If validation fails, retry once with the same prompt plus the validation error message appended as a [CONSTRAINTS] amendment. After two failures, log the raw response and candidate set for manual review and return a degraded result—either an empty ranking or the embedding-based ordering as a fallback. For high-stakes reuse (e.g., plans that trigger financial transactions or infrastructure changes), require human approval on any match below a configurable similarity threshold, typically 0.7.
Model choice matters for ranking consistency. Use a model with strong instruction-following and structured output capabilities, such as GPT-4o, Claude 3.5 Sonnet, or equivalent. Avoid smaller or older models that may collapse scores toward the middle of the range or omit rationales. Set temperature=0 for deterministic rankings. If your plan library exceeds 100 candidates even after embedding pre-filtering, consider batching: split candidates into groups of 25–30, rank each group independently, then run a second merge-ranking pass with the top 5 from each batch. Log every similarity query with the goal fingerprint, candidate count, model version, and top-3 results for observability. This log becomes the foundation for offline evaluation—periodically sample queries and have domain experts rate the top-3 relevance to calibrate your similarity threshold and detect ranking drift after model updates.
For evaluation, maintain a golden test set of 20–50 goal-to-plan pairs with known relevance judgments (highly relevant, partially relevant, not relevant). Run this prompt against the golden set on every prompt or model change and measure Precision@3, Recall@3, and the false-positive rate at your production similarity threshold. A false positive here means recommending a plan that a human reviewer would reject as irrelevant—these are more costly than false negatives because they waste downstream adaptation effort. Set a release gate: if Precision@3 drops below 0.85 or the false-positive rate exceeds 0.15, block the change and investigate. Pair this with a periodic human review sample of production matches to catch distribution shifts that your golden set doesn't cover.
Expected Output Contract
The model must return a ranked list of candidate plans. Each candidate must include a similarity score, a rationale, and a reference to the source plan. Use this contract to validate the response before passing it to a downstream reuse or adaptation step.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
candidates | Array of objects | Array length must be >= 1. If no suitable candidates exist, return an empty array with a null rationale in a top-level 'no_match' object. | |
candidates[].plan_id | String | Must match an existing plan ID from the provided [PLAN_LIBRARY]. Regex check: ^plan-[a-z0-9]+$. | |
candidates[].similarity_score | Number (0.0 to 1.0) | Must be a float between 0.0 and 1.0 inclusive. Scores below [MIN_CONFIDENCE_THRESHOLD] should be excluded from the array. | |
candidates[].rationale | String | Must contain a concise explanation (<= 200 chars) referencing specific shared steps, constraints, or goal keywords from the [NEW_GOAL] and the candidate plan. | |
candidates[].matched_elements | Array of strings | Must list the specific step IDs or constraint keys from the candidate plan that match the [NEW_GOAL]. Cannot be empty. | |
candidates[].adaptation_notes | String or null | If provided, must describe known gaps or required modifications. If null, it signals a direct match with no known adaptation needed. | |
no_match | Object or null | If candidates array is empty, this object must exist with a 'reason' string field. Otherwise, it must be null. |
Common Failure Modes
When matching new goals against archived plans, these failure modes degrade ranking quality, waste retrieval budget, and surface unsafe reuse candidates. Each card explains what breaks and how to guard against it.
Surface-Level Goal Matching
What to watch: The prompt ranks plans by keyword overlap or superficial goal phrasing rather than structural similarity, returning plans that sound related but have incompatible step sequences, tool requirements, or constraints. Guardrail: Require the prompt to decompose both the new goal and each candidate plan into structural features—step count, dependency graph shape, tool categories, constraint types—before computing similarity. Add a structural similarity sub-score that gates the final ranking.
False-Positive Reuse on Deprecated Plans
What to watch: The similarity prompt returns high-confidence matches for archived plans that reference retired tools, deprecated API versions, or unsafe patterns, making them dangerous reuse candidates despite structural similarity. Guardrail: Include a plan status field in the input schema and add an explicit instruction to deprioritize or exclude plans marked as deprecated. Add a post-ranking filter that removes any candidate with a deprecation flag before returning results to the caller.
Ignoring Constraint Mismatches
What to watch: The prompt ranks plans highly based on goal similarity while ignoring critical constraint differences—rate limits, latency budgets, permission scopes, or data schema requirements—that would cause the reused plan to fail in the target environment. Guardrail: Require the prompt to extract and compare constraints from both the new goal specification and each candidate plan. Add a constraint compatibility score as a required ranking factor, and flag any plan with unresolved constraint conflicts for human review before reuse.
Over-Ranking from Vague Rationale
What to watch: The prompt generates similarity scores and rationale that sound plausible but lack specific, verifiable evidence from the plan structures, making it impossible to audit why one plan was ranked above another. Guardrail: Require the output schema to include a per-candidate rationale field that cites specific structural features, tool overlaps, and constraint alignments. Add an eval check that verifies each rationale sentence references a concrete plan element rather than generic similarity language.
Missing Tool Availability Check
What to watch: The similarity prompt returns plans that match the goal structure but depend on tools, APIs, or capabilities that are unavailable in the current agent environment, producing reuse candidates that cannot execute. Guardrail: Include the current tool manifest as a required input to the similarity prompt. Add an explicit instruction to compare each candidate plan's tool requirements against the available tool list and downgrade plans with missing tool coverage. Add a tool-gap field to the output for each candidate.
Ranking Collapse on Near-Duplicate Plans
What to watch: When the plan library contains multiple near-duplicate plans from similar past runs, the prompt assigns nearly identical scores to all of them, providing no useful differentiation and forcing the caller to make an arbitrary selection. Guardrail: Add a deduplication instruction that detects near-duplicate candidates and returns only the highest-quality representative from each cluster, with a note listing the excluded duplicates. Include a cluster-id field in the output so the caller can expand the cluster if needed.
Evaluation Rubric
How to test output quality before shipping. Run these checks against a labeled dataset of at least 50 goal-to-plan pairs with known reuse outcomes.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Top-1 Relevance | Top-ranked candidate is the correct reuse plan for ≥80% of queries | Top-1 accuracy below 80% on held-out test set | Compare top-ranked [CANDIDATE_PLAN_ID] against ground-truth label in test set |
Ranking Quality (NDCG@3) | NDCG@3 ≥ 0.85 on labeled dataset | NDCG@3 below 0.85; relevant plans appear below rank 3 | Compute normalized discounted cumulative gain at rank 3 using relevance judgments |
False-Positive Rejection | No candidate with similarity score ≥ [SIMILARITY_THRESHOLD] when ground-truth label is 'no reuse' | High-similarity candidates returned for goals labeled 'no suitable reuse' | Measure max similarity score for negative examples; flag if any exceed threshold |
Similarity Score Calibration | Mean similarity score for true-positive pairs ≥ 0.7; mean for true-negative pairs ≤ 0.3 | Score distributions overlap significantly between positive and negative pairs | Plot score distributions; compute separation metric (e.g., Cohen's d) between distributions |
Rationale Grounding | ≥90% of rationale strings reference specific plan fields (steps, tools, constraints, goal type) | Rationale contains generic statements without field-level references | Human or LLM-as-judge review of 50 rationale samples for field citation presence |
Output Schema Compliance | 100% of outputs parse as valid JSON matching [OUTPUT_SCHEMA] | JSON parse failure or missing required fields in any output | Automated schema validation on all test outputs; reject on first failure |
Ranking Stability | Top-3 candidates unchanged for ≥95% of queries when re-run with identical input | Ranking order changes on re-run for same [GOAL_DESCRIPTION] and [PLAN_LIBRARY] | Re-run each test query 3 times; measure Jaccard similarity of top-3 sets across runs |
Edge Case: Empty Library | Returns empty candidates array and appropriate status when [PLAN_LIBRARY] is empty | Returns hallucinated plans or non-empty candidates when library is empty | Unit test with empty plan library input; assert candidates array length is 0 |
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 small plan library (<100 plans) and a single model call. Skip the ranking calibration step. Accept raw similarity scores without normalization. Store plans as plain text summaries rather than structured JSON.
code[GOAL_DESCRIPTION] [CANDIDATE_PLAN_SUMMARIES] Return a ranked list with plan IDs and similarity scores from 0-100.
Watch for
- Over-ranking plans that share surface keywords but differ in structure
- Missing false-positive rejection when no plan is truly similar
- Similarity scores that cluster in a narrow band (e.g., all 70-80), making ranking arbitrary

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