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

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

Section 5 of 11 · 3 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

The main function keeps the branch order in one place. It validates the query plan before retrieval. After generation it checks that every cited product belongs to the filtered candidate set. This checks membership only. In a real assistant a valid ID can still accompany an unsupported factual statement.

The distinction between an ID from retrieval and an ID offered to generation matters. Suppose retrieval returns Pro and Lite, then the size filter removes Lite. A generator that names Lite from its own prior context could still produce an ID from the retrieved set. Verifying against the filtered set makes that mistake visible. The boundary would still permit an incorrect claim about Pro, such as an unsupported durability claim. In this toy generator, the displayed price comes directly from the selected record.

An inventory mapping models successful stock lookup when supplied. A missing key is zero stock in that fixture. Passing None signals a failed lookup and yields a partial answer with the catalog match and an explicit “stock unknown” message. We only attempt a reservation when the caller allows it, identifies a specific validated product and size, and the fixture reports a positive count. The simulated action is recorded in the returned answer and trace. It never mutates stock or makes an external call.

Three choices become test inputs. The caller can provide a stock snapshot or mark it unavailable with None. It can substitute parser and generator functions. It can also request a simulated reservation. The default request does not ask for one. Holding the query and catalog fixed while varying a single choice lets the test exercise the corresponding branch.

PythonIn [12]
CollapseExpand
def run_assistant(
    query: str,
    stock: Mapping[tuple[str, str], int] | None,
    *,
    catalog: tuple[Product, ...] = CATALOG,
    parse: Callable[[str], QueryPlan] = parse_query,
    generate: Callable[
        [tuple[Product, ...]], tuple[str, tuple[str, ...]]
    ] = render_products,
    reserve_requested: Reservation | None = None,
    allow_effects: bool = False,
) -> Answer:
    trace = ["parse"]
    status = []

    def finish(outcome, text, ids=(), reservation=None):
        return Answer(
            outcome, text, ids, tuple(status), tuple(trace), reservation
        )

    try:
        plan = parse(query)
    except (TypeError, ValueError):
        trace.append("parse_rejected")
        return finish(Outcome.ABSTAIN, "I couldn't understand the request.")
    if not valid_plan(plan) or plan.intent is Intent.UNSUPPORTED:
        trace.append("parse_rejected")
        return finish(Outcome.ABSTAIN, "I couldn't understand the request.")

    status.append("Searching the catalog")
    trace.append("retrieve")
    ranked = bm25_rank(plan.keywords, catalog)
    trace.append("filter")
    products = filter_products(plan, ranked, catalog)
    if not products:
        return finish(Outcome.ABSTAIN, "No matching catalog products found.")

    trace.append("generate")
    text, cited_ids = generate(products)
    eligible = {product.id for product in products}
    trace.append("validate")
    if not cited_ids or any(pid not in eligible for pid in cited_ids):
        trace.append("attribution_rejected")
        return finish(Outcome.ABSTAIN, "I couldn't ground the catalog answer.")

    if plan.intent is Intent.CATALOG:
        return finish(Outcome.COMPLETE, text, cited_ids)

    status.append("Checking stock")
    trace.append("lookup")
    if stock is None:
        trace.append("stock_unknown")
        return finish(Outcome.PARTIAL, text + ". Stock is unknown.", cited_ids)

    availability = {pid: stock.get((pid, plan.size), 0) for pid in cited_ids}
    summary = ", ".join(
        f"{pid}: {count} in stock" for pid, count in availability.items()
    )
    reservation = None
    if reserve_requested is not None:
        trace.append("reservation_gate")
        if (
            allow_effects
            and reserve_requested.size == plan.size
            and availability.get(reserve_requested.product_id, 0) > 0
        ):
            reservation = reserve_requested
        trace.append(
            "reservation_recorded" if reservation else "reservation_rejected"
        )
    return finish(
        Outcome.COMPLETE,
        f"{text}. Size {plan.size}: {summary}.",
        cited_ids,
        reservation,
    )

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