Models, Retrieval, Tools, and Control Flow › The control program

Michael BrenndoerferDecember 2, 20265 min read
Language AI HandbookAll chapters
Part 64 of 67Compound AI System Design
Chapter 485Models, Retrieval, Tools, and Control Flow › The control program
Reading section 4 of 11 · The control program · 5 minSection 4 of 11 · 5 min

Section 4 of 11 · 5 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

A stub model behind an interface

The parser recognizes just enough of the example's language to identify Trail Runner queries, a whole-dollar exclusive “under” bound, and a whole-number size. It accepts at most one explicit size clause and one explicit price ceiling. It rejects repeated clauses and numeric continuations such as size 10.5, size 10 1/2, and size 10-1/2. The stub only tests a small set of written forms. It can miss constraints phrased outside that grammar. For availability it requires a size. The generator receives filtered catalog rows and renders each row's name and price. We can substitute controlled functions at those seams to test the failure paths.

PythonIn [6]
CollapseExpand
def parse_query(query: str) -> QueryPlan:
    text = query.lower()
    number_end = r"(?!\w|[.,]\d|\s*[./⁄–−-]\s*\d|\s+[\d¼½¾⅐-⅞])"
    size = re.search(rf"\bsize ([0-9]{{1,2}}){number_end}", text)
    limit = re.search(rf"\bunder \$([0-9]{{1,6}}){number_end}", text)
    size_mentions = len(re.findall(r"\bsize\b", text))
    limit_mentions = len(re.findall(r"\bunder\b", text))
    if (
        "trail runner" not in text
        or size_mentions > 1
        or limit_mentions > 1
        or (size_mentions == 1 and size is None)
        or (limit_mentions == 1 and limit is None)
    ):
        return QueryPlan(Intent.UNSUPPORTED, "", None, None)
    return QueryPlan(
        Intent.AVAILABILITY if "available" in text else Intent.CATALOG,
        "trail runner",
        size.group(1) if size else None,
        int(limit.group(1)) if limit else None,
    )

The validator checks whether the values are usable by the control program. The application can therefore reject a missing size before it tries to look up availability. The validation pass would still accept a correctly typed size the model misread. That failure belongs in tests for extraction, where you compare the returned field with a known expected value.

PythonIn [7]
CollapseExpand
def valid_plan(plan: object) -> bool:
    if not isinstance(plan, QueryPlan) or not isinstance(plan.intent, Intent):
        return False
    return (
        isinstance(plan.keywords, str)
        and (
            plan.size is None
            or (
                isinstance(plan.size, str)
                and plan.size.isascii()
                and plan.size.isdecimal()
            )
        )
        and (
            plan.price_limit_usd is None
            or (type(plan.price_limit_usd) is int and plan.price_limit_usd >= 0)
        )
        and (plan.intent is not Intent.AVAILABILITY or plan.size is not None)
    )
PythonIn [8]
CollapseExpand
def render_products(
    products: tuple[Product, ...],
) -> tuple[str, tuple[str, ...]]:
    text = ", ".join(f"{p.name} at ${p.price_usd}" for p in products)
    return text, tuple(product.id for product in products)

Retrieval as a separate component

Three fictional catalog rows make it possible to see both the filter and the inventory lookup work. The Trail Runner Pro costs 110andlistssize10.TheTrailRunnerLitecosts110 and lists size 10. The Trail Runner Lite costs 85 and lists sizes 8 and 9. The Summit Hiker costs $160 and lists sizes 9 and 10.

We rank product names with a small BM25 variant. For a query term, let NN count product names and dfd_f count names containing that term. The code uses Lucene's documented IDF, log⁡(1+(N−df+0.5)/(df+0.5))\log(1+(N-d_f+0.5)/(d_f+0.5)). It weights matches that appear in fewer catalog entries more heavily. Term frequencies saturate with k1=1.5k_1=1.5, and b=0.75b=0.75 controls length normalization using the mean tokenized catalog-name length. Equal scores preserve input order.

PythonIn [9]
CollapseExpand
CATALOG = (
    Product("p1", "Trail Runner Pro", 110, ("9", "10", "11")),
    Product("p2", "Trail Runner Lite", 85, ("8", "9")),
    Product("p3", "Summit Hiker", 160, ("9", "10")),
)

For this toy ranker, a document is the normalized product name alone. Tokenization lowercases the name and keeps alphabetic and numeric ASCII runs. The same tokenizer runs on the search keywords. We score terms independently, so “runner trail” behaves like “trail runner” in the retrieval step when both reach it. The example parser has its own narrower accepted phrasing.

PythonIn [10]
CollapseExpand
def tokens(text: str) -> list[str]:
    return re.findall(r"[a-z0-9]+", text.lower())


def bm25_rank(keywords: str, catalog: tuple[Product, ...]) -> tuple[str, ...]:
    terms = tuple(dict.fromkeys(tokens(keywords)))
    counts = [Counter(tokens(p.name)) for p in catalog]
    lengths = [sum(doc.values()) for doc in counts]
    if not terms or not sum(lengths):
        return ()
    n = len(catalog)
    avg_length = sum(lengths) / n
    doc_freq = {term: sum(term in doc for doc in counts) for term in terms}
    scores = []
    for product, counts_for_product, length in zip(catalog, counts, lengths):
        normalizer = 1.5 * (0.25 + 0.75 * length / avg_length)
        score = 0.0
        for term, df in doc_freq.items():
            count = counts_for_product[term]
            idf = log1p((n - df + 0.5) / (df + 0.5))
            score += idf * count * 2.5 / (count + normalizer)
        if score > 0:
            scores.append((score, product.id))
    scores.sort(key=lambda item: item[0], reverse=True)
    return tuple(product_id for _, product_id in scores)

For “trail runner,” both Trail Runner names contain each query term once. The Summit Hiker name contains neither. Both matched names have three tokens, so they receive identical scores. Input order puts the Pro first. This makes the next step especially easy to audit: a change in the price or size constraint can remove the first item without changing either BM25 score.

PythonIn [11]
CollapseExpand
def filter_products(
    plan: QueryPlan, ranked: tuple[str, ...], catalog: tuple[Product, ...]
) -> tuple[Product, ...]:
    by_id = {product.id: product for product in catalog}
    return tuple(
        by_id[pid]
        for pid in ranked
        if (plan.size is None or plan.size in by_id[pid].sizes)
        and (
            plan.price_limit_usd is None
            or by_id[pid].price_usd < plan.price_limit_usd
        )
    )

Ranking and filtering answer different questions. Ranking finds related names. Filtering applies rules to those names and removes products outside the requested size or exclusive price limit. Here every ranked ID comes from the same catalog and IDs are unique. Catalog sizes indicate which variants exist. The stock count comes from a separate lookup.

This ranker walks the full in-memory fixture on every request, then sorts positive-scoring rows. A production search index could serve the same ranked-ID contract. The size and price predicates could also be applied inside the index query. If you pre-filter there, test that the server still enforces any required eligibility or authorization independently of relevance ranking.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy