Models, Retrieval, Tools, and Control Flow

Michael BrenndoerferDecember 2, 202622 min read

Build a compound AI assistant with models, retrieval, tools, and explicit control flow. Learn to separate catalog data from inventory and degrade gracefully.

Language AI HandbookAll chapters
Part 64 of 67Compound AI System Design
Chapter 485Models, Retrieval, Tools, and Control Flow
Reading the full chapter · 11 sections · 22 min11 sections · 22 min

All 11 sections · 22 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Models, Retrieval, Tools, and Control Flow

A shopper asks whether the Trail Runner is available in size 10 for under $120. A catalog can tell the assistant which products fit the request. A stock lookup can tell it whether the size is in stock. If that lookup fails, the assistant can still show matching products and their catalog prices. The inventory part of the answer then stays explicitly unknown.

Zaharia and colleagues use compound AI system for systems that solve a task with interacting components such as models, retrievers, and tools. Here we build a small version with explicit application control flow. A deterministic model stub proposes a query plan and formats an answer. Application code chooses the next step and checks what the stub proposed. The inventory fixture holds fictional counts in memory. Each example runs offline with the repository's Python 3.11 notebook runtime.

Why not just prompt harder

Put the titles and prices from a static catalog into a prompt and a model has enough input to attempt a catalog answer. The prompt stays tied to that snapshot. It carries no information about a sale that happened after the snapshot was taken. Put fresh stock in the same prompt and the freshness problem moves to whatever code fetched those counts. Someone still has to decide what to fetch, whose inventory to show, and what to do when the fetch returns late.

Separate the two questions early. “Which Trail Runners have a size 10 variant?” is a question about fields in product records. “Can I get one right now?” needs information from inventory. Conflating the two leads the interface to show “available” even if the source only reports a list of offered sizes. A scoped retrieval step lets the orchestrator ask for candidate records first, with the stock step deferred until there is a concrete product and size.

The example gives the parser and generator the shape of a model client, but both are small functions. That is useful when debugging the wiring. Give the parser a fixture input and inspect the query plan. Give the generator a particular candidate set and check the IDs its answer cites. If the complete result is wrong, keep the input fixed while swapping one component at a time. With two model calls, this also exposes which call had a bad input before you attribute its output to the model.

A worked system: the catalog assistant

A product record has a display name, an ID, a price, and a list of supported sizes. The catalog assistant resolves the ID before it asks for stock for a particular size. We keep those product attributes and the stock data in two different fixtures to make their provenance visible in the code.

In the example, an assistant can offer a description and catalog price. It can also report the toy stock count that was available to it for the requested variant. The last feature is recording a simulated decision about a reservation. We therefore need two different interfaces for the last two operations: a reading operation that observes stock, and an optional decision record separate from the catalog answer. The decision record is generated entirely inside the notebook.

Each boundary passes a different kind of information.

  • Data. The parser returns a query plan, retrieval returns ranked IDs, and the inventory lookup returns a count.
  • Decision. The application chooses whether to continue, return partial results, or decline.
  • Status. The example records stage labels such as “Checking stock” and returns them alongside a completed outcome. A live interface would have to emit these labels as work progresses.
  • Effect gate. Both caller permission and an explicit product and size must match before the demo records a simulated reservation.

An ordered trace gives the tests a way to check decisions. We also keep the reader-facing status separate from the trace. An application can use the latter for diagnostics without turning its internal branch names into shopper-facing text.

PythonIn [3]
CollapseExpand
import re
from collections import Counter
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from enum import Enum
from math import log1p


class Intent(Enum):
    CATALOG = "catalog"
    AVAILABILITY = "availability"
    UNSUPPORTED = "unsupported"


class Outcome(Enum):
    COMPLETE = "complete"
    PARTIAL = "partial"
    ABSTAIN = "abstain"

Records at the parser, catalog, and answer boundaries

The intent names the product operation the parser recognized. The outcome names what the assistant delivered. A request with availability intent can therefore end with any of the three outcomes. The application can put the outcome and progress status in fixed UI fields and render the text next to them.

PythonIn [4]
CollapseExpand
@dataclass(frozen=True)
class QueryPlan:
    intent: Intent
    keywords: str
    size: str | None
    price_limit_usd: int | None


@dataclass(frozen=True)
class Product:
    id: str
    name: str
    price_usd: int
    sizes: tuple[str, ...]


@dataclass(frozen=True)
class Reservation:
    product_id: str
    size: str
PythonIn [5]
CollapseExpand
@dataclass(frozen=True)
class Answer:
    outcome: Outcome
    text: str
    product_ids: tuple[str, ...]
    status: tuple[str, ...]
    trace: tuple[str, ...]
    simulated_reservation: Reservation | None = None

The records convey shape and intent. The parser's return annotation alone cannot establish that the query plan is valid or that it matches the user's request. The local program checks the fields it branches on. A separate Reservation arrives from the caller and identifies a product and size explicitly. Neither the parser nor the answer generator supplies it.

The control program

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.

The full control program

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,
    )

Running it on a real query

The availability query below leaves the size-matching Trail Runner Pro. The stocked fixture reports two units. The second run uses the same query, catalog, parser and generator with the inventory fixture unavailable. You can see the distinction between a matching catalog product and an observable stock count.

PythonIn [13]
CollapseExpand
QUERY = "Is the Trail Runner available in size 10 under $120?"
STOCK = {("p1", "10"): 2}

available = run_assistant(QUERY, STOCK)
partial = run_assistant(QUERY, None)
for answer in (available, partial):
    print(f"{answer.outcome.value}: {answer.text}")
    print("Trace:", " → ".join(answer.trace))
ConsoleOut [13]
CollapseExpand
complete: Trail Runner Pro at $110. Size 10: p1: 2 in stock.
Trace: parse → retrieve → filter → generate → validate → lookup
partial: Trail Runner Pro at $110. Stock is unknown.
Trace: parse → retrieve → filter → generate → validate → lookup → stock_unknown

The display text for an availability question includes a product ID next to the count. A UI may already have a name-to-ID mapping from retrieval. Here we keep the literal ID in the output so it is clear which fixture entry supplied the number. The trace on the available run has the same initial stages as the trace on the unavailable run. Its last entry differs because the unavailable run records the separate stock-unknown decision.

PythonIn [14]
CollapseExpand
print("Status:", ", ".join(available.status))
print("Cited catalog rows:", available.product_ids)
print("Partial path final stage:", partial.trace[-1])
ConsoleOut [14]
CollapseExpand
Status: Searching the catalog, Checking stock
Cited catalog rows: ('p1',)
Partial path final stage: stock_unknown

Testing failure boundaries

Each fixture changes one condition. The unsupported query ends before retrieval. A deliberately incorrect generator loses its answer when the citation names a product that retrieval found but the size filter removed. The empty catalog returns no results. A price limit equal to a catalog price also gives no match under the exclusive rule.

We then exercise the reservation gate. An availability question does not propose a reservation. The same reservation is declined without permission, gets recorded with permission and stock, and cannot get recorded with unknown stock. The fixture still reports two units afterward.

PythonIn [15]
CollapseExpand
def cite_filtered_product(
    products: tuple[Product, ...],
) -> tuple[str, tuple[str, ...]]:
    return "Trail Runner Lite", ("p2",)
PythonIn [16]
CollapseExpand
reservation = Reservation("p1", "10")
unsupported = run_assistant("Tell me a joke", STOCK)
rejected = run_assistant(QUERY, STOCK, generate=cite_filtered_product)
assert unsupported.trace == ("parse", "parse_rejected")
assert rejected.trace[-1] == "attribution_rejected"
assert rejected.outcome is Outcome.ABSTAIN
assert set(bm25_rank("trail runner", CATALOG)) == {"p1", "p2"}

The same stock entry can exist when a catalog search has no candidates, including the empty-catalog case. An early return means that a later inventory stage never gets a product ID it could use. The tests also treat a whole-dollar amount equal to the item's price as out of scope for the request. Change “under” to “at most” in a production language contract and update both the predicate and the equality-boundary test.

PythonIn [17]
CollapseExpand
assert run_assistant(QUERY, STOCK, catalog=()).product_ids == ()
assert run_assistant(QUERY.replace("$120", "$110"), STOCK).product_ids == ()
PythonIn [18]
CollapseExpand
assert available.simulated_reservation is None
assert (
    run_assistant(
        QUERY, STOCK, reserve_requested=reservation
    ).simulated_reservation
    is None
)
assert (
    run_assistant(
        QUERY, STOCK, reserve_requested=reservation, allow_effects=True
    ).simulated_reservation
    == reservation
)
assert (
    run_assistant(
        QUERY, None, reserve_requested=reservation, allow_effects=True
    ).simulated_reservation
    is None
)

Two negative controls make the permission check more useful. Allowing the effect does not allow changing the requested size. And with an available inventory fixture, a missing stock entry represents zero and prevents the record. With no fixture at all, the availability state is instead unknown and the entire decision exits through partial service.

PythonIn [19]
CollapseExpand
assert (
    run_assistant(
        QUERY,
        STOCK,
        reserve_requested=Reservation("p1", "9"),
        allow_effects=True,
    ).simulated_reservation
    is None
)
assert (
    run_assistant(
        QUERY, {}, reserve_requested=reservation, allow_effects=True
    ).simulated_reservation
    is None
)
assert STOCK == {("p1", "10"): 2}

A parser can also return a record that is structurally present but unusable. These two cases exercise validation and the documented exception boundary separately. Both fail before retrieval. Adapters that connect to an external model are outside this example and would translate transport or decoding failures into the local interface's supported outcomes.

PythonIn [20]
CollapseExpand
def missing_size(_: str) -> QueryPlan:
    return QueryPlan(Intent.AVAILABILITY, "trail runner", None, 120)


def malformed_parse(_: str) -> QueryPlan:
    raise ValueError("unreadable plan")
PythonIn [21]
CollapseExpand
assert (
    run_assistant(QUERY, STOCK, parse=missing_size).trace == unsupported.trace
)
assert (
    run_assistant(QUERY, STOCK, parse=malformed_parse).trace
    == unsupported.trace
)
assert (
    run_assistant(QUERY.replace("$120", "$120.50"), STOCK).outcome
    is Outcome.ABSTAIN
)
assert (
    run_assistant(QUERY.replace("size 10", "size 10.5"), STOCK).trace
    == unsupported.trace
)
assert run_assistant("Trail Runner size 10.5", STOCK).trace == unsupported.trace
for unsupported_size in ("10 1/2", "10-1/2", "10 ½"):
    mixed_size = QUERY.replace("size 10", f"size {unsupported_size}")
    assert run_assistant(mixed_size, STOCK).trace == unsupported.trace
for unsupported_price in ("120 1/2", "120-1/2", "120 ½"):
    mixed_price = QUERY.replace("$120", f"${unsupported_price}")
    assert run_assistant(mixed_price, STOCK).trace == unsupported.trace
assert (
    run_assistant("Trail Runner size 10 or size 10.5", STOCK).trace
    == unsupported.trace
)
assert (
    run_assistant("Trail Runner under $120 or under $110.50", STOCK).trace
    == unsupported.trace
)

assert (
    run_assistant("Is the Trail Runner available in size 10.", STOCK).outcome
    is Outcome.COMPLETE
)

Where each path stops

The matrix marks whether each fixture visited a component. The rejected-citation path reaches validation and stops before the stock lookup. The partial path reaches the lookup, then returns its reduced outcome. The available and partial rows have the same visited stages. Read the outcome or inspect the trace to distinguish success from unavailability at the last stage.

PythonIn [22]
CollapseExpand
stages = ("parse", "retrieve", "filter", "generate", "validate", "lookup")
fixtures = (
    ("Unsupported", unsupported),
    ("Rejected citation", rejected),
    ("Available", available),
    ("Stock unknown", partial),
)
visited = [
    [int(stage in answer.trace) for stage in stages] for _, answer in fixtures
]
VisualizationOut [23]
CollapseExpand
Visited stages for unsupported, rejected citation, available, and stock-unknown paths.
The unsupported fixture visits only parsing. The rejected citation stops after validation. The available and stock-unknown fixtures reach inventory lookup, with distinct outcomes.

Partial results and graceful degradation

A partial answer promises a narrower result. The assistant can explain which catalog rows matched the constraints even when it cannot answer whether a physical unit is in stock. A stock count of zero in the fixture is a complete result about availability. A stock state of unknown is a partial result. A query with no eligible catalog candidates abstains from making a recommendation.

The UI can check the outcome before showing a stock indicator. For the partial result, show the matched product and mark stock unknown. For the zero-stock result, show the count from the available fixture. The trace still gives you enough detail to diagnose whether the missing component was search, generation validation, or inventory.

PythonIn [24]
CollapseExpand
zero_stock = run_assistant(QUERY, {})
assert zero_stock.outcome is Outcome.COMPLETE
assert zero_stock.product_ids == partial.product_ids
assert "0 in stock" in zero_stock.text
print(zero_stock.outcome.value, zero_stock.text)
print(partial.outcome.value, partial.text)
ConsoleOut [24]
CollapseExpand
complete Trail Runner Pro at $110. Size 10: p1: 0 in stock.
partial Trail Runner Pro at $110. Stock is unknown.

Limitations & impact

The parser deliberately recognizes a tiny vocabulary, whole-dollar amounts, and whole-number sizes. A correctly shaped query plan can still misread a constraint. Validate extraction against labeled questions and evaluate generation against the source records when replacing the stubs. The toy generator returns well-formed tuples. The wrapper assumes that shape and leaves generator exceptions to its caller. A production adapter can validate the wire payload and convert recognized execution errors into the outcomes its application supports.

For sequential calls that all run, stage latencies add. Adding a second model or a remote dependency therefore consumes part of the same request deadline. Returning early avoids later stages. Timing and costs should be measured on representative complete, partial, and rejected paths because the stage sequence varies with the request.

The program demonstrates a simulated policy check. Live inventory writes require a verified caller identity, authorization, and a transaction or another mechanism that accounts for concurrency and duplicate requests. Here the lookup only observes the supplied in-memory mapping and the reservation stays an output record.

Keep tests aimed at the contract. A catalog test can require that filtering implements a strict upper bound. A trace test can require that stock is queried only after an answer passes its reference check. A separate evaluation set would measure whether a real parser understands colloquial requests. Pass those resulting constraints through the same filter before comparing them with the expected output. This distinguishes a parser error, where the wrong limit was extracted, from a filter error, where the right limit was interpreted incorrectly.

A diagnostic trace is useful because it describes a particular path. It also has limits. The example has deterministic, locally measured fixtures and no concurrency. Two production calls may overlap in time, and a list of stages in one process would then lack timing for work performed in another service. Recording structured inputs and outcomes at component boundaries will make that later instrumenting job clearer. The following chapters add an evaluation plan and a way to connect timing and outcomes across dependencies.

A useful test harness stubs one dependency per failure case. To exercise the syntax check, return a plan whose intent is availability and whose size is missing. To exercise the attribution check, keep the query plan valid and give the generator an ID that filtering removed. To exercise partial service, retain the catalog answer and make inventory unavailable. If you change all three boundaries in one test, the first rejection can mask failures further downstream. The trace helps verify that the intended stage ran before the assertion.

A similar approach works for the positive path. A fixture where the only product is in stock confirms the caller can observe that count. A separate fixture asks for a reservation and checks the returned decision. The second assertion belongs next to an assertion that the mapping has its original count. That is the point at which the example's simulation boundary is enforced. A real inventory service would own any writes, and its tests would check that the persisted stock count changes once for the authorized operation and remains consistent when another request is processed concurrently.

Summary

  • Retrieval gathers candidates, and a deterministic filter applies concrete catalog rules.
  • The orchestrator owns sequencing. It checks the query plan and candidate references at the boundary where they are used.
  • A catalog match can remain useful when stock is unknown. Return a partial outcome and describe the information that is missing.
  • An explicit caller request and permission are separate inputs to the simulated reservation gate. Trace records make that boundary testable.

The next chapter applies the same structure to routing, fallbacks, and graceful degradation.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about models, retrieval, tools, and control flow in compound AI systems.

Models, Retrieval, Tools, and Control Flow

Question 1 of 80 of 8 completed
According to the chapter, why is it insufficient to put a static catalog snapshot into a prompt instead of using a separate retrieval step?
Join the discussionAsk a question or share what you learned.

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!

A different angle
All writing
Language AI Handbook · Vol. 20

Reliability and Cost Engineering

Design reliable, cost-aware AI services with SLOs, retries, idempotency, Little's law, caching, and fault injection under real deadlines.

29 min read
Language AI Handbook · Vol. 20

Evaluation-Driven Development

Build an offline evaluation harness for language systems: versioned task suites, traces, slice scores, and regression gates that block hidden drops.

27 min read
Language AI Handbook · Vol. 20

Versioning Models, Prompts, Data, and Tools

Version AI systems with typed manifests, compatibility checks, canary rollouts, and lineage records that connect requests to their recorded configurations.

28 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026modelsretrieval, author = {Michael Brenndoerfer}, title = {Models, Retrieval, Tools, and Control Flow}, year = {2026}, url = {https://mbrenndoerfer.com/writing/models-retrieval-tools-control-flow-compound-ai-systems}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Models, Retrieval, Tools, and Control Flow. Retrieved from https://mbrenndoerfer.com/writing/models-retrieval-tools-control-flow-compound-ai-systems
MLAAcademic
Michael Brenndoerfer. "Models, Retrieval, Tools, and Control Flow." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/models-retrieval-tools-control-flow-compound-ai-systems>.
CHICAGOAcademic
Michael Brenndoerfer. "Models, Retrieval, Tools, and Control Flow." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/models-retrieval-tools-control-flow-compound-ai-systems.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Models, Retrieval, Tools, and Control Flow'. Available at: https://mbrenndoerfer.com/writing/models-retrieval-tools-control-flow-compound-ai-systems (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Models, Retrieval, Tools, and Control Flow. https://mbrenndoerfer.com/writing/models-retrieval-tools-control-flow-compound-ai-systems
Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy