Read a filter from a question and validate it
The model is a scripted stand-in whose replies include a bad year, an invented key and a reply that is not JSON. Real Java projects use Jackson (or Gson) instead of the course's Json helper.
"The 2024 policy" is a fact about metadata, not a meaning to embed. Read it out of the question as structured output, validate every field against what the index really contains, and apply it as an exact filter before ranking.
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.
Write valid_filter(data, allowed) that returns a dict with only the keys of data that are in allowed with a value in allowed[key]. Print the result for {"year": 2024, "topic": "x", "region": "uk"} with allowed = {"year": [2023, 2024], "topic": ["refund", "pass"]}.
Write apply_filter(policies, flt) where policies are dicts with id, year, topic. Return the ids matching every field of flt, and all ids if flt is empty. Print the ids for {"topic": "pass"} and for {}.
Explain it without notes
Why use a filter for "the 2023 refund rule" instead of relying on embeddings?
What can go wrong when a model extracts a filter, and how do you defend?
What should happen when the question names no year?
Why must security filters not come from the question?
Expected output
Q: What was the refund rule in 2023?
filter: year=2023 topic=refund
notes: none
searched: P1
Q: How much is the monthly pass?
filter: topic=pass
notes: none
searched: P3, P4
Q: pass price in 2019
filter: topic=pass
notes: dropped year=2019; dropped region=uk
searched: P3, P4
Q: refunds in 2024
filter: none
notes: reply is not JSON, no filter
searched: P1, P2, P3, P4