Documents and files
Choose how to read a file, extract fields with citations, and pass the resulting artifacts or page images to the next step.
Choose how to read a file, extract fields with citations, and pass the resulting artifacts or page images to the next step.
Read, search, and extract documents
| Intent | Operation |
|---|---|
| Learn a file’s format, size and page count | describe_file |
| Read an unfamiliar document | read_pages, continuing with pages_not_returned |
| Find specific evidence | search_document |
| Fill missing coverage | parse_document on pages_needing_parse, then read the returned handle |
| Inspect layout | render_pages |
| Read a whole text or JSON value | read_artifact |
read_pages reads pages in order: omit pages to start at page 1 and pass
pages_not_returned to continue. A direct agent receives up to 25 pages or
100,000 characters per call. Steps and code-mode cells receive every
requested page up to 4,000,000 characters, so one call reads most documents
whole; loop on pages_not_returned for larger ones. A page longer than the
budget comes back once, cut, with truncated=True; search it with
search_document or read it in a step. Raw-file reads and
searches extract native text for free and report pages_needing_parse:
scanned pages and complex layouts whose text is missing or unreliable. Parse
those pages once with parse_document, then read and search the returned
handle. structured_extract declines a document while any selected page needs
parsing and names the pages. Search hits and reads share source page numbers;
when search is truncated, narrow the query or page selection. Extract from a
document by passing it with the selected pages rather than text assembled
from reads: its citations then name the document’s pages, while inline text is
cited by its own logical pages. Images from render_pages can be passed to
structured_extract(images=...); prefer reusable text when it is sufficient.
from pydantic import BaseModel
from andon_dsl.agents import StepContext
from andon_dsl.errors import UserReadableError
from andon_dsl.resources import FileRef, StructuredExtractionResult
from andon_dsl.workflows import step, workflow
class DocumentInput(BaseModel):
file: FileRef
query: str
class Clause(BaseModel):
clause: str | None
@step
async def extract_matching_clauses(ctx: StepContext, inputs: DocumentInput) -> StructuredExtractionResult:
document = await ctx.parse_document(inputs.file)
found = await ctx.search_document(
document.ref, inputs.query
)
if found.truncated:
raise UserReadableError("Too many search matches. Use a more specific query.")
pages = {hit.page_number for hit in found.matches}
if not pages:
return StructuredExtractionResult(
extracted_data={"clause": None}, field_metadata={}, source=None, errors=[]
)
return await ctx.structured_extract(
schema=Clause.model_json_schema(),
document=document.ref,
pages=",".join(map(str, sorted(pages))),
)
@workflow
def document_clauses(inputs: DocumentInput) -> None:
extract_matching_clauses(inputs)
Platform tool guidance: structured_extract
Steps receive a StructuredExtractionResult: use result.extracted_data,
result.source, result.errors, and result.field_metadata. The metadata map
uses JSON Pointers such as /items/0/name, the same paths errors[].path
uses; each FieldMetadata has confidence and citations. result.at(path)
returns the data under a pointer in its own nesting, each value merged with its
metadata as {"value": ..., "confidence": ..., "citations": [...]}, and raises
KeyError for a path that names nothing. Read a field with
result.at("/total"), a record with result.at("/items/0"), the whole result
with result.at(), and every value with
for path in result.field_metadata: result.at(path). An authored object can
have the keys value, confidence and citations too, so read a subtree by
its schema rather than by looking for those keys.
Code-mode cells receive the same fields as JSON dictionaries, without at.
json_validate returns JsonValidationResult with valid and errors; each
error has a JSON Pointer path and message. It accepts any JSON value.
Strings are validated as strings, so parse serialized JSON before calling.
An invalid schema or a reference that fails during validation is rejected with
correction guidance; repair the schema argument. Extraction independently checks
for an explicit object root, resolvable references, transport support, and
provider limits before making any model call. Its limits apply after extraction
metadata and schema references are expanded.
andon platform-tools show structured_extract reads this tool’s contract.
Add --offline to read the installed signature and description. The schema
and call choices below affect extraction quality on long contracts.
- Model an inventory as a list, a narrative as a string. Ranges are
extracted separately and combined: list fields concatenate and keep every
item verbatim, while a string field with several candidates is reconciled
into one text by a model call. Declare obligations, conditions, rows and
findings as
list[str]orlist[Model]; reserve a string for a field you want as one reconciled narrative. - Records that span ranges are reassembled. A record larger than a range is emitted once per range that holds part of it; a review folds those pieces back into one record, concatenating its lists and reconciling its strings. Items one range emitted are always kept as separate occurrences, and identical content across ranges is treated the same way. Give records an identifying field (name, number, date) with a description so the review can tell pieces of one entity from distinct entities, or model records at a granularity smaller than a range.
- Batch size trades recall for calls.
max_batch_tokensdefaults to 10,000. On a long agreement with dense obligation lists, 5,000 recalled markedly more and 2,500 did not improve on it, at higher cost; those are observations from one document, not rules. For list-heavy documents, evaluate 5,000 against your own files and measure recall and cost before settling on a value. - Choose the model family for the document, not the agent.
model_family="large"routes extraction and reconciliation calls to the large model; boundary selection always uses the small one. Leave it unset to inherit the agent’s model or the platform default. - Field descriptions are the extraction prompt. The model sees every
description; say what counts as an item, what to preserve (periods, amounts,
parties, exceptions) and what to exclude. Put document-wide rules in
instructions, field rules in descriptions. - Name each field’s subject in a bundle of documents. Every range decides from its own pages whether it evidences a field, so an unscoped field is filled from any document that holds a look-alike: a contract bundled with a parent plan’s registration takes that plan’s status as the lot’s. When one extraction covers several documents, every field description names its subject, for example “the purchaser’s deposit under this contract”.
- Citations are per leaf value. Every scalar, including each list item,
carries its own confidence and citations in
field_metadata. The model cites labeled source blocks (paragraphs, headings, list items, table rows) by page and line rather than copying text, so eachPageCitationis a cited passage: its page,start/endoffsets and exacttext. A passage is one block, the part of it in one batch, or the blocks a value cites that are adjacent on the page, such as a whole list or consecutive table rows. A value that several ranges agree on cites one of those ranges, not every place the document repeats it; a value reconciled from ranges that disagree cites the passages the reconciling model selected as supporting it. The result’ssourcenames the document once, andread_pages(source)returns the page text the offsets index. Do not re-extract because metadata looks thin; judgeextracted_data. - Check
errorsbefore usingextracted_data. Each entry names a JSON Pointer, a kind and a message.validationmeansextracted_dataviolates your schema there, typically a non-nullable field without a default that no range evidenced, leftnull. An unevidenced field with a default takes that default.invalid_citationmeans none of the evidence the model cited for a value could be found in the source; the value is kept without citations. Decide how your step handles each before validating the data with your own model.
Artifacts and page images
ctx.write_artifact(value, filename=...) stores a run-scoped file and returns
FileRef[T]; ctx.read_artifact(ref) returns the typed value again. Each
artifact written or read in step code is limited to 300 MiB. The step holds the
value and its serialized bytes in sandbox memory together; hosted sandboxes
have 512 MiB, so text and JSON values above about 200 MiB exhaust memory before
the limit. The payload kind is recorded on the stored file:
value |
Stored as | read_artifact(ref) returns |
|---|---|---|
str |
text | str |
bytes |
bytes | bytes |
BaseModel or @dataclass instance |
JSON plus the class key | an instance of that class |
JSON-native dict/list/scalars |
JSON | the same JSON value |
Bytes written without filename= or content_type= are named from their
content: a PDF becomes artifact.pdf and an image artifact.png, .jpg,
.gif or .tiff, so document tools can read them. Other bytes are
artifact.bin; name a generated Office file yourself, such as
filename="report.xlsx".
Other typed JSON values need value_type= on write (list[Claim] is a list
of dataclasses, not a JSON-native value), and the recorded key then drives
reads:
ref = await ctx.write_artifact(claims, filename="claims.json", value_type=list[Claim])
claims = await ctx.read_artifact(ref)
read_artifact(ref, value_type=...) overrides the recorded type: validate a
plain JSON payload into a model, or read a JSON artifact whose recorded class
no longer imports (renamed or moved). Text and bytes payloads apply
value_type= as a validator. A file that write_artifact did not produce,
such as an upload or a rendered page image, reads by its format when its
bytes are UTF-8: JSON returns its value and other text formats (plain text,
CSV, Markdown, HTML, email) return str. Anything else returns bytes. Read a
parse_document handle with ctx.read_pages. ctx.describe_file(ref)
reports a file’s format, payload kind, size and page count without reading it.
The agent-facing read_artifact(file) returns a text or JSON value and
declines binary files and parse handles. A direct agent receives at most
100,000 characters; a code-mode cell receives files up to 8 MiB.
write_artifact(content, ...) stores a string as text and any other JSON value
as JSON; a string with content_type="application/json" must be serialized
JSON and is stored as that value. Render typed data an agent needs in full
into its prompt with {{json field}}; hand larger JSON over as a FileRef
for read_artifact in a code-mode cell.
Page images feed a vision-capable agent as ImageContent(file=ref) parts in
the same prompt list as text; text parts are Handlebars templates, image and
document parts pass through unchanged:
from andon_dsl.agents import ImageContent, StepContext
@step
async def compare_signatures(ctx: StepContext, input: ContractInput) -> SignatureReview:
pages = await ctx.render_pages(input.contract, pages="1,12")
return await reviewer.run(
input,
attachments=[ImageContent(file=page) for page in pages],
)
reviewer is a module-level Agent(...) with output_type=SignatureReview
and prompt="Compare the signature blocks on the attached pages.".
DocumentContent(file=ref) attaches a whole document the same way. Text,
Markdown, HTML and JSON artifacts reach the model as text. CSV is read as a
spreadsheet, and the model sees only its first 1,000 rows. A PDF reaches it
whole: the model receives every page’s text and image, billed as input tokens,
so attach selected page text from read_pages or page images from
render_pages for long documents. Documents attached to one prompt are limited
to 50 MB in total.