Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Entity disambiguation and constraint preservation in query rewriting

Examining multiple rounds of reference, entity linking, clarification, and original constraint preservation.

Learning objectives: The purpose of rewriting is to express the known intention more retrievably and not to create missing facts. Entity, negation, time, and scope must have a source, and ambiguities affecting the answer need to be preserved or clarified.

Content checked: 2026-10-03 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Implementation · Build it. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Backend developers learning Agent applications.

Entity disambiguation and constraint preservation in query rewriting
The purpose of rewriting is to express the known intention more retrievably and not to create missing facts. Entity, negation, time, and scope must have a source, and ambiguities affecting the answer need to be preserved or clarified.

How does the mechanism work?

Step-by-step explanation
  1. What should I do if the two candidates are very similar?

    Move from resolving references to ambiguities that can change the answer.

  2. How can a user retain an entity that he just rejected in the last round?

    Multi-turn state must handle corrections, rather than merely accumulate related terms.

  3. How to deal with different definitions brought by query expansion?

    Even when broader coverage improves, prevent different business definitions from being merged.

Implementation · Build it

Implement the contract · Entity disambiguation and constraint preservation in query rewriting

Objectives of this level: Implement explicit selection, authorized candidate resolution and lossless constraints.

Visual guide · Resolve intent without adding facts

Resolve intent without adding facts

This function validates an already extracted intent, not a model rewrite. Preserve exclusions and dates; current access must be checked again at retrieval. Select the figure to open it at full size.

Same after-sales project

The after-sales user asks “Can it be returned, excluding gifts, during October?” after comparing two orders. This exercise validates a structured intent envelope from already extracted inputs; it does not parse natural language, generate a model rewrite or measure retrieval quality. The server’s current allowed_entities narrows candidates but mentioning an order does not grant access.

The existing capstone main-return creates a return application; it does not execute a refund. These manifests are independent fictional extensions or policy/evidence/counting exercises. They do not add real refunds, publication, model calls or Java execution to the capstone runtime.

Complete function contract

Implement build_query_plan(payload). text is nonempty string; candidates and allowed_entities are unique nonempty-string lists; selected_entity is null or a nonempty string already in candidates. constraints contains a unique nonempty-string exclude list and from_date/to_date in canonical YYYY-MM-DD calendar dates, with from_date <= to_date. Invalid dates, duplicate candidates, absent fields, wrong types or selection outside candidates raise ValueError:input; extras ignored. Empty lists valid. Return exactly status/entities/text/constraints; preserve text unchanged and both dates unchanged, sort exclude ascending into a NEW dict/list. If explicit selected_entity is allowed → search with only that entity; if explicitly selected but unauthorized → denied with no entities, never silently substitute another. Without a selection, take candidates∩allowed sorted: one → search, multiple → clarify, zero → missing. Other output containers must also be new; never mutate input. This envelope is not permission enforcement at the actual read tool and does not infer an entity from historical preference.

Every listed input key must exist; explicit null is not an absent key. All returns must be JSON-compatible fresh containers, with exact bool/int distinctions, and leave the input unchanged. Every invalid declared field uses exactly ValueError("input"); this includes malformed nested fields. Do not swallow NotImplementedError or return a self-declared passed flag.

Own blank implementation

Download the full local package, extract it and work in its lab_runner.py directory. Runner and this case manifest are alternatives: save the runner and cases/rag-query-rewrite.json with that exact directory layout. The manifest contains all public fixed inputs/expected outputs; it contains no general solution. It is not an unseen assessment. Python 3.9+ and standard library only; no model keys or network calls are needed while grading.

def build_query_plan(payload):
    raise NotImplementedError("Implement the documented contract yourself")
python3 lab_runner.py scaffold --course rag-query-rewrite --out student.py
python3 lab_runner.py grade --course rag-query-rewrite --module student.py --out report.json

The untouched scaffold must exit 1. Fill the function yourself and rerun; all 12 public checks must pass for exit 0. Submit student.py, the generated report.json, your source diff and one additional condition-changing test. The runner imports and calls your function on each actual payload, compares exact output/error, checks input preservation and container independence, and records runner/cases/student SHA. A manual passed flag is not accepted. Its 5-second process timeout is a hang guard, not an enterprise latency requirement.

code example

Deliver your own function and report

Implement build_query_plan(payload). text is nonempty string; candidates and allowed_entities are unique nonempty-string lists; selected_entity is null or a nonempty string already in candidates. constraints contains a unique nonempty-string exclude list and from_date/to_date in canonical YYYY-MM-DD calendar dates, with from_date <= to_date. Invalid dates, duplicate candidates, absent fields, wrong types or selection outside candidates raise ValueError:input; extras ignored. Empty lists valid. Return exactly status/entities/text/constraints; preserve text unchanged and both dates unchanged, sort exclude ascending into a NEW dict/list. If explicit selected_entity is allowed → search with only that entity; if explicitly selected but unauthorized → denied with no entities, never silently substitute another. Without a selection, take candidates∩allowed sorted: one → search, multiple → clarify, zero → missing. Other output containers must also be new; never mutate input. This envelope is not permission enforcement at the actual read tool and does not infer an entity from historical preference.

The exact function and complete inputs are in the main body. Implement from the blank starter, not by copying expected outputs into branches.

Acceptance task for this level

Implement the blank function and submit the real generated report, own code/diff and one changed-condition test; Java candidates additionally deliver their real Java patch/build. Contract: build_query_plan(payload).

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

May an unauthorized explicit choice fall back to another order?

Further explanations and practice

When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.

All linked explanations and exercises (1 )

Sources and verification scope

The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.