Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.2 — Rewriting the Query
RAG and Vector Search · Example 1 of 2

Rule-based rewrite, keeping the original

The "kept" line says rewritten when the rewrite scores the same or better, and original when it scores lower.

Rewriting turns the question the user typed into the question the retriever should see: first with plain rules (lower-case, drop greetings, fix known typos), then with a model for what rules cannot do. Keep the original, guard the model's reply, and count what the extra call costs.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write rewrite(question, drop, fix) that lower-cases the question, removes any word in drop, applies fix (a dict of replacements) and joins with spaces. Print the rewrite of "Hi pls where is my refnd" for drop = {"hi", "pls"} and fix = {"refnd": "refund"}.

02

Write accept(reply, original, max_words) that returns the reply when it is non-empty and has at most max_words words, otherwise the original. Print the result for an empty reply, a good reply and a long reply with max_words = 6.

Explain it without notes

01

What does a rule-based rewrite do, and what can it not do?

02

Why keep the original question when you have a rewrite?

03

What can go wrong when a model is asked to rewrite a query, and how do you guard against it?

04

How do you decide whether a model rewrite is worth its extra call?

Rule-based rewrite, keeping the original
Sign in to run this example in your browser.

Expected output

Q:         Hey pls how do I reset my pasword
rewritten: how do i reset my password
original:  D3 (1)
rewritten: D3 (2)
kept:      rewritten
Q:         are kids allowed without a helmat thx
rewritten: are kids allowed without a helmet
original:  none
rewritten: D4 (1)
kept:      rewritten
Q:         What does the monthly pass cost?
rewritten: what does the monthly pass cost
original:  D8 (2)
rewritten: D8 (2)
kept:      rewritten
Q:         charged if i am lte
rewritten: charged if i am late
original:  D5 (1)
rewritten: D6 (2)
kept:      rewritten
Q:         can I get a refnd
rewritten: can i get a refund
original:  none
rewritten: none
kept:      rewritten