Inferensys

Prompt

Ambiguous Entity Resolution with Knowledge Base Prompt Template

A practical prompt playbook for resolving ambiguous entity references in RAG-augmented assistants using a knowledge base, with structured disambiguation and evaluation criteria.
Knowledge engineer constructing knowledge base on laptop, document hierarchy visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the precise job-to-be-done, ideal user, required context, and critical limitations for the ambiguous entity resolution prompt.

This prompt is designed for the clarification layer of a RAG-augmented assistant, specifically to resolve ambiguous entity references from user input against a structured knowledge base. The core job-to-be-done is to prevent the system from hallucinating a single, incorrect match when a user's query—containing a name, code, or term—returns multiple high-similarity records from your retrieval pipeline. The ideal user is an AI engineer or product developer building a copilot, support agent, or data-retrieval assistant where entity linking precision is critical for downstream task success. You should use this prompt only after your retrieval step has returned multiple candidates above a defined similarity threshold, and you have their associated metadata (e.g., IDs, descriptions, distinguishing attributes) ready to inject into the prompt's context.

The prompt's operational boundary is strict: it assumes you have already retrieved candidate entities with scores and metadata, and its sole function is to format them into a disambiguation question. Do not use this prompt when only one candidate exists above your threshold, or when the user's reference is unambiguous—in those cases, proceed directly to answer generation. In regulated domains like healthcare or finance, you must log the disambiguation decision, the evidence that supported each candidate, and the user's selection to maintain a complete audit trail. A common failure mode is using this prompt without a similarity threshold, which floods the context window with irrelevant options. Always pre-filter candidates with a minimum score (e.g., >0.75) to keep the prompt's input tight and the user's cognitive load low.

Before wiring this into your application, define your evaluation criteria for success: the model should never pick a winner on its own, and the disambiguation question must highlight the distinguishing attribute between the top candidates, not just re-list all metadata. If the model consistently fails to generate a useful distinguishing question, the problem is often upstream in your retrieval metadata quality, not in the prompt itself. Proceed to the prompt template section to copy the exact instructions, and then to the implementation harness to learn how to validate the output, handle retries, and log decisions before the user's selection is passed to the answer-generation layer.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and the operational preconditions required before deploying it into a production RAG pipeline.

01

Good Fit: High-Volume Entity Lookups

Use when: users frequently reference entities by partial names, synonyms, or ambiguous shorthand against a large, structured knowledge base. Guardrail: The prompt excels when the KB has clean, deduplicated entity records and a reliable similarity search backend. It reduces support tickets caused by 'not found' errors.

02

Bad Fit: Real-Time, Low-Latency Chat

Avoid when: the user expects sub-second responses in a live chat stream. Risk: The multi-candidate generation and LLM reasoning step adds unacceptable latency. Guardrail: Use a fast, non-LLM fuzzy matching algorithm for the primary lookup and reserve this prompt only for the fallback disambiguation step when multiple high-confidence matches exist.

03

Required Input: A Pre-Retrieved Candidate Set

Risk: Feeding the LLM the entire knowledge base or an empty context window guarantees hallucination or timeouts. Guardrail: This prompt is a re-ranker and disambiguator, not a retriever. A vector or keyword search must first supply a top-k candidate list (e.g., k=5) with similarity scores and key attributes for the LLM to reason over.

04

Operational Risk: Over-Clarification Fatigue

Risk: A similarity threshold set too high causes the assistant to ask disambiguating questions for trivial, low-stakes lookups, frustrating users. Guardrail: Implement a dynamic threshold. If the top candidate's score is dominant (e.g., >0.95) and the others are distant, bypass the LLM entirely and auto-resolve. Only invoke this prompt for a tight cluster of high-scoring candidates.

05

Bad Fit: Unstructured or Noisy KBs

Avoid when: the knowledge base contains duplicate entities with inconsistent attributes or free-text descriptions. Risk: The LLM cannot reliably distinguish between two identical or contradictory records. Guardrail: Run a deduplication and normalization pipeline on the KB before indexing. The prompt's effectiveness is directly proportional to the semantic clarity of the candidate records it receives.

06

Operational Risk: Prompt Leakage via Entity Names

Risk: A malicious user could craft an entity name containing prompt injection syntax (e.g., 'Ignore previous instructions...') that gets surfaced in the candidate set. Guardrail: Sanitize all entity names and attributes before inserting them into the prompt template. Wrap them in immutable delimiters and treat the entire candidate block as untrusted user data.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for resolving ambiguous entity references against a knowledge base, generating candidate matches and targeted disambiguation questions.

This prompt template is designed for RAG-augmented assistants that must resolve ambiguous entity references from user input against a structured knowledge base. It takes a user query containing an ambiguous entity mention, a set of candidate entities retrieved from your knowledge base, and a similarity threshold. The prompt instructs the model to either link to the best match when confidence is high or generate a precise disambiguation question when multiple candidates exceed the threshold. The output is a structured JSON object containing the resolution decision, candidate matches, and, if necessary, a clarification question that highlights the distinguishing feature between the top candidates.

text
You are an entity resolution assistant for a knowledge base. Your job is to resolve ambiguous entity references in user queries.

## INPUT
User Query: [USER_QUERY]
Candidate Entities (from knowledge base): [CANDIDATE_ENTITIES_JSON]
Similarity Threshold: [SIMILARITY_THRESHOLD]

## TASK
1. Compare the ambiguous entity mention in the user query against each candidate entity.
2. If exactly one candidate has a similarity score above the threshold, link to that entity.
3. If multiple candidates exceed the threshold, generate a targeted disambiguation question that highlights the key distinguishing feature between the top candidates.
4. If no candidate exceeds the threshold, indicate that no match was found.

## OUTPUT SCHEMA
Return a JSON object with this exact structure:
{
  "resolution_type": "linked" | "clarification_needed" | "no_match",
  "linked_entity": {
    "id": "string | null",
    "name": "string | null",
    "confidence": "number | null"
  },
  "candidates": [
    {
      "id": "string",
      "name": "string",
      "similarity_score": "number",
      "distinguishing_feature": "string"
    }
  ],
  "clarification_question": "string | null",
  "reasoning": "string"
}

## CONSTRAINTS
- Never fabricate entity IDs or names not present in the candidate list.
- The clarification question must be a single sentence that helps the user distinguish between the top candidates without repeating all their attributes.
- If resolution_type is "linked", the clarification_question field must be null.
- If resolution_type is "clarification_needed", the linked_entity fields must be null.
- Base your decision on the similarity scores provided; do not re-score candidates.

Adapt this template by replacing the square-bracket placeholders with data from your retrieval pipeline. [USER_QUERY] should contain the raw user message. [CANDIDATE_ENTITIES_JSON] must be a pre-serialized JSON array of candidate objects, each with at least an id, name, and similarity_score field produced by your retrieval system. [SIMILARITY_THRESHOLD] is a float between 0 and 1 that you tune based on your eval results. If your knowledge base includes additional metadata such as entity type, department, or location, add those fields to the candidate objects and update the output schema accordingly. For high-stakes domains like healthcare or finance, add a [RISK_LEVEL] placeholder and include instructions to escalate to human review when the top candidate scores fall within a marginal band below the threshold. Always validate the model's output against the schema before surfacing the clarification question to the user; a malformed JSON response should trigger a retry or fallback to a generic disambiguation prompt.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to work reliably. Validate each before assembly.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The raw user turn containing an ambiguous entity reference

I need the latest report on Apple.

Must be a non-empty string. Check for potential injection patterns before passing to the prompt.

[KNOWLEDGE_BASE_CONTEXT]

Retrieved passages from the knowledge base that may contain matching entities

{"doc_id": "123", "text": "Apple Inc. reported record Q4 earnings..."}

Must be a valid JSON array of objects with 'doc_id' and 'text' fields. Minimum 1 passage required; null triggers a fallback response.

[ENTITY_CANDIDATES]

Pre-extracted entity mentions from the knowledge base with similarity scores

[{"name": "Apple Inc.", "type": "ORG", "score": 0.95}]

Must be a JSON array. Each object requires 'name', 'type', and 'score' fields. Score must be a float between 0.0 and 1.0.

[SIMILARITY_THRESHOLD]

The minimum score for an entity candidate to be considered a match

0.75

Must be a float between 0.0 and 1.0. Defaults to 0.75 if not provided. Lower values increase clarification frequency.

[MAX_CANDIDATES]

The maximum number of candidate entities to present for disambiguation

3

Must be a positive integer. Defaults to 3. Values above 5 degrade user experience with excessive options.

[CONVERSATION_HISTORY]

Prior turns in the session for coreference resolution

[{"role": "user", "content": "Tell me about AAPL."}]

Must be a valid JSON array of message objects with 'role' and 'content' fields. Null allowed for first-turn interactions.

[OUTPUT_SCHEMA]

The expected JSON structure for the resolved entity or clarification question

{"resolution_type": "resolved|clarification_needed"}

Must be a valid JSON Schema object. Schema check required before prompt assembly. Reject if 'resolution_type' enum is missing.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Ambiguous Entity Resolution prompt into a RAG application with validation, retries, and human review.

This prompt is designed to sit inside a retrieval-augmented generation (RAG) pipeline, not as a standalone chat interaction. The application layer is responsible for executing the initial knowledge base search, passing the top-k candidate entities and their metadata into the prompt's [CANDIDATE_ENTITIES] placeholder, and then parsing the structured output. The prompt itself does not perform the search; it reasons over the results you provide. This separation is critical because it allows you to control retrieval quality, latency, and cost independently from the LLM's disambiguation logic.

The implementation harness should enforce a strict contract around the prompt's output. Expect a JSON object with a decision field set to either link, clarify, or no_match. If link, the harness must validate that the linked_entity_id exists in the provided candidates. If clarify, the harness must confirm that the clarification_question is non-empty and that the candidate_options array contains at least two distinct IDs from the input. A post-processing validation layer should reject any response that violates this schema and trigger a single retry with the validation error injected into the [CONSTRAINTS] block. After one failed retry, the system should escalate to a no_match state or a human review queue rather than looping indefinitely.

For high-stakes domains like healthcare or finance, the clarify path should never autonomously execute a destructive action. Instead, surface the clarification question to the user in the UI and pause the workflow. Log the full prompt, the retrieved candidates, the model's raw output, and the validation result for every disambiguation event. This audit trail is essential for debugging retrieval gaps, identifying when the similarity threshold needs tuning, and proving to reviewers that the system did not silently guess an entity. When deploying, start with a high similarity threshold for candidate inclusion and monitor the ratio of clarify to link decisions to find the right balance between precision and user friction.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured JSON object the model must return after resolving an ambiguous entity against the knowledge base. Use this contract to validate the response before surfacing it to the user or routing to downstream systems.

Field or ElementType or FormatRequiredValidation Rule

resolved_entity

object

Must be a single object. If no resolution is possible, the object must contain a null id and a non-empty clarification_question.

resolved_entity.id

string | null

Must match the canonical ID from the provided knowledge base entries or be null. If non-null, must pass a regex check for the expected ID format (e.g., UUID, KB-XXXX).

resolved_entity.name

string

Must exactly match the 'name' field of the resolved knowledge base entry. If id is null, this must be an empty string.

candidate_matches

array

Must contain 0 to 5 objects. If the array is empty, resolved_entity.id must be non-null. If it contains multiple objects, a clarification_question is required.

candidate_matches[].id

string

Must be a valid ID from the provided knowledge base entries. No fabricated IDs allowed.

candidate_matches[].name

string

Must exactly match the 'name' field of the corresponding knowledge base entry.

candidate_matches[].similarity_score

number

Must be a float between 0.0 and 1.0. Represents the model's confidence in the match based on the user's ambiguous input.

clarification_question

string

Required if the length of candidate_matches is greater than 1 or if resolved_entity.id is null. Must be a single, concise question that highlights the distinguishing feature between the top candidates. Must not be an open-ended 'How can I help?' prompt.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when resolving ambiguous entities against a knowledge base and how to guard against it.

01

Over-Clarification on High-Confidence Matches

What to watch: The prompt asks for clarification even when a single entity match has a very high similarity score, wasting a turn and frustrating users. Guardrail: Implement a strict confidence threshold in the application layer. If the top candidate score exceeds 0.95 and the gap to the next candidate is > 0.15, bypass the clarification prompt and proceed with the top match, optionally disclosing the assumption in the response.

02

Hallucinated Entity Attributes in Disambiguation Options

What to watch: When generating the short descriptions for candidate entities in the clarification question, the model fabricates a distinguishing detail not present in the knowledge base, misleading the user. Guardrail: Constrain the prompt to force verbatim extraction of the differentiating attribute from the retrieved context. Validate that every word in the disambiguation option's description has a direct source span in the knowledge base chunk before showing it to the user.

03

Context Window Exhaustion from Large Candidate Lists

What to watch: A vague query returns dozens of potential entity matches from the vector store. Packing all candidates into the prompt for resolution consumes the context budget and causes the model to lose focus or truncate. Guardrail: Enforce a hard limit on the number of candidates passed to the prompt (e.g., top 5). If the similarity scores form a long tail, the application layer should pre-filter before calling the model, not rely on the prompt to do it.

04

Failure to Resolve Coreferences Across Turns

What to watch: The user says "the first one" or

05

Ambiguity Loop on Synonym-Heavy Domains

What to watch: The user's term and the knowledge base's canonical term are synonyms, but the vector similarity score falls just below the threshold. The system asks for clarification, the user rephrases with the same synonym, and the loop repeats. Guardrail: Add a synonym expansion step before vector retrieval, or include a rule in the prompt that if the user's clarification simply restates the original query, the system should assume the top match is correct and proceed with a transparency note.

06

Leaking Internal IDs or Scores to the User

What to watch: The prompt accidentally instructs the model to output raw entity IDs, similarity scores, or internal metadata in the clarification question, creating a confusing and unprofessional user experience. Guardrail: Use a strict [OUTPUT_SCHEMA] that defines the user-facing text field separately from the machine-readable resolution log. Validate the final output with a regex to strip any internal identifiers before rendering the message to the user.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these checks on a golden dataset of ambiguous entity queries with known correct resolutions. Each criterion targets a specific failure mode in entity resolution and clarification dialogue.

CriterionPass StandardFailure SignalTest Method

Entity Linking Precision

Top-ranked candidate matches the ground-truth entity ID for queries where a single correct resolution exists

Correct entity appears below rank 1 or is absent from candidate list

Compare resolved entity ID against golden dataset labels; measure Precision@1 across 50+ ambiguous queries

Clarification Necessity Rate

Clarification question is generated only when no candidate exceeds the [SIMILARITY_THRESHOLD] or when top-2 candidates are within [TIE_MARGIN]

Clarification triggered for queries with a clear single candidate above threshold; or no clarification when candidates are tied

Run 30 queries with known ambiguity levels; measure false-positive and false-negative clarification rates against labeled necessity ground truth

Candidate List Completeness

All ground-truth candidate entities present in the returned candidate list when multiple valid resolutions exist

Ground-truth entity missing from candidates while other lower-similarity entities appear

Check recall of golden dataset entity IDs in the candidate list; flag any missing known-good entity

Disambiguation Question Specificity

Clarification question references the distinguishing attribute between top candidates rather than re-asking the original query

Question is generic (e.g., 'Which one did you mean?') or repeats the user's original ambiguous input without new discriminating information

Human review or LLM judge rates question specificity on a 1-5 scale; pass threshold is 4+ on distinguishing-attribute presence

Source Attribution Accuracy

Each candidate entity includes a source citation that maps to the correct knowledge base record

Citation points to wrong record, hallucinated source, or missing when entity is from knowledge base

Validate each candidate's [SOURCE] field against knowledge base IDs; flag mismatches or fabricated citations

Confidence Score Calibration

Confidence scores for top candidates correlate with empirical resolution accuracy; tied candidates have scores within [TIE_MARGIN] of each other

High-confidence scores on incorrect resolutions; or large score gaps between equally valid candidates

Plot confidence vs. accuracy across 100 queries; check that score deltas between tied candidates fall within configured margin

Output Schema Compliance

Response matches [OUTPUT_SCHEMA] with all required fields present and correctly typed

Missing [CANDIDATES] array, malformed [CLARIFICATION_QUESTION], or extra fields that violate schema contract

Validate output against JSON Schema; reject any response that fails structural validation before content evaluation

Context Budget Impact

Clarification question and candidate list together consume fewer than [MAX_CLARIFICATION_TOKENS] tokens

Clarification output exceeds token budget, crowding out conversation history or retrieved evidence in subsequent turns

Count tokens in clarification portion of output; fail if exceeds configured budget threshold

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add strict output schema validation with retries, structured logging of resolution decisions, and eval cases for precision and recall. Implement a two-pass approach: first pass returns candidates above a primary threshold, second pass generates a disambiguation question only when multiple candidates exceed a higher confidence threshold. Include a no_match sentinel and an abstain path when confidence is too low.

code
[SYSTEM]
You are an entity resolution system. Given [USER_QUERY] and [KNOWLEDGE_BASE_ENTITIES]:
1. Identify candidate entities with similarity > [PRIMARY_THRESHOLD].
2. If exactly 1 candidate exceeds [CONFIDENCE_THRESHOLD], return it as resolved.
3. If 2+ candidates exceed [CONFIDENCE_THRESHOLD], generate a targeted disambiguation question that highlights the distinguishing attribute.
4. If no candidates exceed [PRIMARY_THRESHOLD], return {"status": "no_match"}.
5. If best candidate is between thresholds, return {"status": "uncertain", "candidate": ...}.

Return JSON matching [OUTPUT_SCHEMA].

Watch for

  • Silent format drift across model versions breaking downstream parsers
  • Missing human review gate for high-stakes entity resolution (e.g., patient records, financial accounts)
  • Disambiguation questions that are too open-ended, causing follow-up loops
  • Logging that omits the evidence spans used for matching, making debugging impossible
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.