Check the Filter the Model Wrote
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.
- One call with
SELF_QUERY_PROMPTfilled with the question (asquestion=). 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. - Query: the reply's
"query", stripped, if it is a non-blank string; else the question. - Filter: the reply's
"filter", a list of{"field", "op", "value"}(anything else: no clauses). Keep a clause only if its field is inSCHEMA(a field or op that is not a string never is), its op is inALLOWED_OPSfor that field's type, and its value coerces to that type. Drop a bad clause alone; keep the rest, coerced, in order. - Coerce, never from a bool:
intfrom an int, a whole float or a stringint()takes;floatfrom an int, a float or a stringfloat()takes;datefrom a stringdate.fromisoformattakes;strfrom a string, stripped and lowercased. Forin, the value is a list and every item must coerce. - Search: keep the docs that pass every clause (
OPS[op](doc[field], value)), rank them bysimilarity(query, doc["text"]), best first, ties in docs order, and return the bestkids. 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.