Paging and projection¶
A transport that serves an operation to an agent does two things to its output that an HTTP response does not. It serves a long list a page at a time, so one call cannot pour a whole table into a model's context. And it shapes each row for its reader: an identifier is passed to the next tool rather than read out, a choice is named by its display in the schema while the row keeps the stored value, and plumbing is not shown at all.
Both are functions a transport calls between dispatch and the wire. Neither is
applied by dispatch,
present, so a caller that
names no audience is not projected: no marking
applies to it, so it is served every field, each value as presented, and a
list as a bare array.
euros = ValueFormatter(
lambda amount: f"EUR {amount}",
produces="string",
schema={"examples": ["EUR 9.99"]},
)
@dataclass
class BookRow:
id: Annotated[int, FieldMarking.handle()]
title: Annotated[str, FieldMarking.label()]
status: Status
price: Annotated[Decimal, FieldMarking.formatted(euros)]
published_on: Annotated[date | None, FieldMarking.timestamp("%d %B %Y")]
author_id: Annotated[int, FieldMarking.hidden()]
def catalogue(*, user: Any) -> QuerySet[Book]:
return Book.objects.order_by("pk")
list_books_spec = SelectorSpec(
kind=SelectorKind.LIST,
selector=catalogue,
permissions=[IsSignedIn()],
presenter=DataclassPresenter(BookRow),
)
The output says who each field is for, with the
FieldMarkings
described under declaring an operation: id is a handle,
title names the record, author_id is plumbing, status is content
whose choices have displays, and price and published_on are content
rendered through a formatter.
Built once, where the transport registers¶
# The transport's own wording and bound, not the spec's.
HANDLE_DESCRIPTION = "An identifier to pass to other tools. Never read it out."
MAX_PAGE_SIZE = 50
# Built once, where the transport registers the spec: the projection a payload
# is shaped by and the schema it is advertised under, from one declaration.
projection = audience_projection_for_spec(list_books_spec, name="Tool 'list_books'")
output_schema = spec_output_schema(
list_books_spec,
paginate=True,
projection=projection,
handle_description=HANDLE_DESCRIPTION,
)
audience_projection_for_spec
reads the spec's Output into an
AudienceProjection:
each field's marking, the one field marked as the label, each choice field's
displays, and the same again for every nested output that has anything to
project. A second field marked as the label is refused here, naming both: a
record has one name.
spec_output_schema
takes that projection and describes what the projected payload will carry, and
paginate=True wraps the list in the page envelope. This is output_schema
above:
{
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"description": "An identifier to pass to other tools. Never read it out."
},
"title": {"type": "string"},
"status": {
"type": "string",
"oneOf": [
{"const": "draft", "title": "Draft"},
{"const": "published", "title": "Published"}
]
},
"price": {"type": "string", "examples": ["EUR 9.99"]},
"published_on": {"type": ["string", "null"], "examples": ["31 January 2026"]}
},
"required": ["id", "title", "status", "price", "published_on"]
}
},
"page": {"type": "integer"},
"totalPages": {"type": "integer"},
"hasNext": {"type": "boolean"}
},
"required": ["items", "page", "totalPages", "hasNext"]
}
Each change to the item is the mirror of one the payload undergoes:
author_idis gone from the properties and fromrequired.statuskeeps its stored values, and each carries its display as atitle: aoneOfof{"const": value, "title": display}, the{const, title}entries an input schema gives a labelled choice too. The row serves"published", and the schema tells the model to call it "Published".priceandpublished_onare described as what their formatters produce, and nothing they said about the value before survives: the"format"of a decimal and a date is gone, since"EUR 9.99"is neither."null"stays inpublished_on's type, because a null is never formatted. It stays however the property stated it - in a type list, as a{"type": "null"}member of ananyOf(how a dataclass field typedX | Noneis described), asNoneamong anenum's values (a nullable choice), or as a{"const": null}entry of aoneOf(a labelled one) - and is always written as the formatter's type followed by"null"; anenumin the formatter's own fragment listsNonetoo, and aconstbecomes anenumof that value andNone, so the two never disagree.idkeeps its values on both sides - a handle is passed to other tools, which take the stored value - and carrieshandle_description, the transport's sentence for a handle whose marking declares no description of its own. It defaults to nothing: what to do with an identifier is advice for one kind of reader, and only the transport knows which kind is reading.
The projection applies to the item, never to the array or the envelope around
it, whose keys belong to no Output.
A choice that is also an input¶
A choice an agent reads is often one it sends next: it lists the books, then
calls a tool that sets a book's status. So the projection never replaces a
choice's value with its display. The row carries the stored value, the value
an input declaring the same choices accepts, and the schema carries the
display as that value's title, which is how the input schema of such a tool
names it too. A model reads "Published", sends "published", and the call
passes the choices check. A display-only value would be refused there as
"not one of the available choices", since an input accepts values, never
displays.
This holds for every choice, marked or not; a HANDLE is not needed to keep
one sendable.
A transport whose reader is a person, a rendered page rather than a model,
shows the display instead. It calls
spoken_choices
on what project_payload returned, which replaces each choice's value with
its display at every depth, an array member by member, and leaves a HANDLE
and a formatted field as they are. Never on a payload an agent reads: no
tool accepts a display as input. A formatted field is the exception, since its formatter decides
what is served, so a field another tool takes as input is not formatted.
Formatting a value¶
A ValueFormatter
is a transform and the JSON type it produces, declared together, and a
FieldMarking
carries it. euros above is the generic form: render turns the presented
value - the decimal's string - into the string a reader is told, produces
is the type the schema states, and schema adds what the produced value
looks like. A fragment naming type is refused, so a formatter cannot
advertise one type and declare another.
FieldMarking.timestamp
is a formatter already written: a date-time as a local string, strftime's
fmt defaulting to day-first and 24-hour, with the example in the schema
rendered from that same format. A date-time is converted to Django's active
time zone, which is the only zone it can be rendered in: the projection is
built once, before any request, so a zone chosen per call would describe one
payload and serve another. A date, like published_on, is read as midnight,
which is why its format names no time. A string that is not a date-time, and
one shaped like a date-time that names no real moment (the thirtieth of
February), is served as stored: one row's bad data does not fail the page it is
on.
Both sides of the projection read one formatter, so the payload and the schema change together, and a formatter decides over the rest of the field's declaration:
- it wins over a choice's values and titles, being the transform an author wrote by hand: the row serves what it produces;
- it is never applied to a
HANDLE, which another tool takes as input, so a marking that declares both is honoured as the handle; - a null passes through it unformatted.
Serving a page¶
def list_books_tool(
user: Any, *, page: int | None = None, limit: int | None = None, **arguments: Any
) -> dict[str, Any]:
result = dispatch(list_books_spec, principal=user, arguments=arguments)
shaped = paginate_output(result.value, page=page, limit=limit, max_page_size=MAX_PAGE_SIZE)
rows = present_for_audience(
list_books_spec, replace(result, value=shaped.items), projection=projection
)
return shaped.envelope(rows)
page and limit are the tool's own arguments, not the spec's: they never
reach dispatch, whose argument set is closed.
paginate_output
slices a list result's value into one
OutputPage. page
defaults to 1 and limit to
DEFAULT_PAGE_SIZE.
Both are clamped at both ends - limit to between 1 and max_page_size,
page to between 1 and the last page that exists - and the clamp is reported
rather than silent: the envelope's page is the page actually served, and
totalPages and hasNext are counted at the limit actually used. A queryset
is counted with one COUNT before it is sliced, so a page past the end is
never an unbounded OFFSET, and no page is longer than the rows counted, so
a limit no max_page_size bounds, however large, still serves every row
where a LIMIT past 64 bits would be refused by the database. The envelope
reports the limit asked for.
Whether to page is read off the spec, never off the result's kind. A LIST
selector spec is paged, as is a write whose output selector is a LIST, and
spec_output_schema
describes either as the envelope under paginate=True. A many write, and
one declaring returns_many, come
back as kind="list" too, but their rows are what the service returned, all
of them, and they are never paged: their schema is a bare array whatever
paginate says, so a transport paging every "list" result would serve an
envelope its schema does not describe.
The names a caller pages by, and the ceiling, are the transport's. They are not arguments of the spec, whose argument set is closed, so the tool takes them off the call before dispatch sees the rest; and two mounts of one spec may well allow different page sizes.
present_for_audience
is present followed by the projection, and the page's rows are what it
presents. envelope
then wraps them. With three books, page 2 at a limit of 2 is:
{
"items": [
{
"id": 3,
"title": "A Wizard of Earthsea",
"status": "published",
"price": "EUR 9.99",
"published_on": "01 November 1968"
}
],
"page": 2,
"totalPages": 2,
"hasNext": false
}
include_total=True, passed to paginate_output and to spec_output_schema
alike, adds total after hasNext: the rows across every page, which is the
count already taken before the slice, so it costs no query. The schema lists the
integer total last in properties and required. It is off by default, and a
transport turns it on for both or for neither, so the schema never advertises a
key the envelope does not write.
The order matters. Paging first means only the page's rows are read and presented. Projecting before wrapping means the projection never walks the envelope's keys.
A selector spec declaring affordances
pages the same way. Dispatch answers them on the queryset before
paginate_output slices it, so each page's rows carry the affordances object
the whole list would have, and the projection passes that object through
whole, reason included. spec_output_schema puts it on the item inside the
envelope, with or without paginate=True and projection=.
From async code, present with
apresent, which runs the
queries in the executor, and project what it returns with
project_payload:
projecting reads only the presented data and the declaration, so it is safe on
the event loop.
One spec, two mounts¶
# A second mount whose callers do need the author, as a handle to pass on.
with_authors = audience_projection_for_spec(
list_books_spec,
overrides={"author_id": FieldMarking.handle()},
name="Tool 'books_with_authors'",
)
def books_with_authors_tool(user: Any) -> Any:
result = dispatch(list_books_spec, principal=user, arguments={})
return present_for_audience(list_books_spec, result, projection=with_authors)
overrides replaces the declared marking of the fields it names, for this
mount only. Here a tool whose callers go on to look up the author keeps
author_id, as a handle:
{
"id": 1,
"title": "The Dispossessed",
"status": "published",
"price": "EUR 9.99",
"published_on": "01 May 1974",
"author_id": 1
}
An override that leaves two fields marked as the label is refused in the
mount's name, and so is a declaration that marks two, with or without
overrides: the refusal calls the output by name where it gave one, and
Output where it did not.
A caller naming no audience¶
def books_over_http(user: Any) -> Any:
return present(list_books_spec, dispatch(list_books_spec, principal=user, arguments={}))
present applies no marking, so the same spec over HTTP still serves every
field, each choice as its stored value and each formatted field as it was
presented:
{
"id": 1,
"title": "The Dispossessed",
"status": "published",
"price": "9.99",
"published_on": "1974-05-01",
"author_id": 1
}
Render an agent's answer with the projection. A pipeline that feeds one
spec's output into the next keeps presenting with present, or the handles
the next step reads by will have been projected away.
Shaping each row by the call¶
Paging and projection are the transport's. What a caller may ask of the rows
themselves - which fields, a query over each - is the spec's, declared as its
shapes: Parameters beside its reads that no callable receives by name.
class ChosenFields(Presenter):
"""Each book with its handle and the fields the caller chose, or every field."""
def output(self) -> Output:
return Output(
(
OutputField("id", "integer"),
# Left out of a row whose caller did not choose them.
OutputField("title", "string", always_present=False),
OutputField("price", "string", always_present=False),
)
)
def present(self, value: Book) -> dict[str, Any]:
return {"id": value.pk, "title": value.title, "price": str(value.price)}
def presented(self, value: Book, context: PresentationContext | None) -> dict[str, Any]:
row = self.present(value)
chosen = context.shapes.get("fields") if context is not None else None
if chosen is None: # not sent: every field
return row
return {name: row[name] for name in ("id", *chosen)}
pick_books_spec = SelectorSpec(
kind=SelectorKind.LIST,
selector=catalogue, # never handed "fields"
permissions=[IsSignedIn()],
presenter=ChosenFields(),
shapes=Parameters.of(
Parameter(
"fields",
"array",
items="string",
choices=["title", "price"],
required=False,
json_schema_extra={"uniqueItems": True},
)
),
)
fields is an argument like any other to the caller: it is in
spec_input_schema, with its uniqueItems from json_schema_extra, it is
shape-checked, so a field not among its choices is refused before the
selector runs, and an undeclared argument beside it is still refused. It
never reaches the selector, which declares no fields and would fail if
handed one. What the caller sent reaches the presenter on the
PresentationContext
as shapes, by name and read-only, with an argument left out absent rather
than None, so ChosenFields renders every field unless the call chose some.
Every row of a list is handed the same context, and so the same shapes.
A selector that should load what the presenter will render reads the same
mapping by declaring the shapes seed,
never the shape by its own name. Here the author's row is joined only when
the caller chose author, or chose nothing, so each page is one query
whichever fields were asked for:
class ChosenFieldsAndAuthor(Presenter):
"""Each book with its handle and the fields the caller chose, its author among them."""
def output(self) -> Output:
return Output(
(
OutputField("id", "integer"),
OutputField("title", "string", always_present=False),
OutputField("price", "string", always_present=False),
OutputField("author", "string", always_present=False),
)
)
def present(self, value: Book) -> dict[str, Any]:
return self.presented(value, None)
def presented(self, value: Book, context: PresentationContext | None) -> dict[str, Any]:
chosen = context.shapes.get("fields") if context is not None else None
fields = {
"title": lambda: value.title,
"price": lambda: str(value.price),
# Read only when chosen: the author is a row of its own.
"author": lambda: value.author.name,
}
names = fields if chosen is None else chosen
return {"id": value.pk, **{name: fields[name]() for name in names}}
def catalogue_for(*, user: Any, shapes: Mapping[str, Any]) -> QuerySet[Book]:
books = Book.objects.order_by("pk")
if "author" in shapes.get("fields", ["author"]):
books = books.select_related("author")
return books
pick_books_and_authors_spec = SelectorSpec(
kind=SelectorKind.LIST,
selector=catalogue_for, # handed the "shapes" seed, never "fields"
permissions=[IsSignedIn()],
presenter=ChosenFieldsAndAuthor(),
shapes=Parameters.of(
Parameter(
"fields",
"array",
items="string",
choices=["title", "price", "author"],
required=False,
json_schema_extra={"uniqueItems": True},
)
),
)
A spec declaring shapes promises no field of a row. A shape is the
presenter's to apply, and the kernel cannot see which keys it leaves out: an
adapter's always_present follows its library's rendering rule, not the call.
So
spec_output_schema
lists no presenter field in any required, at any depth, wherever the item
sits: the item itself, an array's items, or a page's. Here even id, which
every row carries, is not required, and a client is never promised a key a
row may not carry. What the kernel writes around the item keeps its own: the
affordances object dispatch adds to each row, and a page's envelope. A spec
declaring no shapes keeps the required its presenter's always_present
states.
A shape is refused by its declaration, before the call runs, never by its
presenter: the choices on fields are what turns away a field the presenter
cannot render, and a presenter that raised on one would fail after the
selector had read the rows. The schema advertises the same choices, so a
client is told the line before it crosses it.
The pieces on their own¶
A transport with a schema or a payload that did not come from a spec uses the
two halves directly:
annotate_output_schema
applies a projection to an item schema, or to an array of them, and
project_payload
applies it to a presented value. Both return their input unchanged for an
empty projection, and neither modifies what it is given.