Skip to content

< CollectionsAll the RAGs · 15 of 42 ·119 · Level 03, RAG

Check the Filter the Model Wrote

medium · implement · Embeddings & Retrieval

A model splits a question into a search query and a metadata filter; apply only the parts your schema allows. Implement self_query(question, write, docs, k=3), returning {"query", "filter": [(field, op, value), ...], "ids"}. write(prompt) is the model; each doc has an id, a text and metadata.

  1. One call with SELF_QUERY_PROMPT filled with the question (as question=). The JSON is the reply from its first { to its last }. If there is no such span or it does not parse to an object, there is no filter and the query is the question: plain search.
  2. Query: the reply's "query", stripped, if it is a non-blank string; else the question.
  3. Filter: the reply's "filter", a list of {"field", "op", "value"} (anything else: no clauses). Keep a clause only if its field is in SCHEMA (a field or op that is not a string never is), its op is in ALLOWED_OPS for that field's type, and its value coerces to that type. Drop a bad clause alone; keep the rest, coerced, in order.
  4. Coerce, never from a bool: int from an int, a whole float or a string int() takes; float from an int, a float or a string float() takes; date from a string date.fromisoformat takes; str from a string, stripped and lowercased. For in, the value is a list and every item must coerce.
  5. Search: keep the docs that pass every clause (OPS[op](doc[field], value)), rank them by similarity(query, doc["text"]), best first, ties in docs order, and return the best k ids. None pass: [].

The catch. The filter is model output, as untrusted as user input. A field the model names is not one you offer, even when the docs carry it (they have an internal cost), and an op name is not code: only SCHEMA and ALLOWED_OPS decide what reaches the docs.