Skip to content

API Reference parrot.handlers.infographic_render

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.handlers.infographic_render

View source

Request/response models and dataset decoding for the deterministic infographic render endpoint (FEAT-327, Module 2).

InfographicTalk (handlers/infographic.py, TASK-1890) dispatches the bot-less POST /api/v1/agents/infographic/render branch through the helpers defined here:

  • :class:InlineDataset / :class:RenderRequest / :class:RenderResponse / :class:RenderJob — the Pydantic models carried over the wire (spec §2 Data Models). RenderRequest.descriptor embeds the FEAT-326 :class:~parrot.tools.infographic_sections.SectionDescriptor by import — it is never redefined here.
  • :func:decode_inline_datasets — decodes records/split inline payloads (plain JSON request) into {name: DataFrame}.
  • :func:parse_multipart_render_request — decodes a multipart body (one request JSON part + dataset:<name> parquet/CSV parts) into a RenderRequest plus {name: DataFrame}, enforcing a running total body-size cap BEFORE any oversized part is fully buffered.

Malformed input raises :class:RenderPayloadError (maps to 400 in the route, naming the offending part); exceeding the size cap raises :class:RenderBodyTooLargeError (maps to 413). Both mappings happen in the route (TASK-1890) — this module only decodes and raises.

Attribute DEFAULT_MAX_BODY_SIZE

Class InlineDataset

One dataset transported inline in the JSON body.

Fields:

Field Type Default Description
orient Literal['records', 'split'] "records" (list of row dicts) or "split" ({"columns": [...], "data": [...], "index": [...]}, pandas split orientation; index optional).
data Any The inline payload, shaped per orient.

Class RenderBodyTooLargeError

The running total body size exceeded the configured cap.

The route maps this to HTTP 413. Raised BEFORE the offending chunk is appended to the in-memory buffer — the cap is enforced pre-buffering.

Class RenderJob

Redis-stored job record (1-day TTL on terminal states; TASK-1891).

Fields:

Field Type Default Description
job_id str uuid4 job identifier.
status Literal['pending', 'running', 'done', 'failed'] Current job status.
result Optional[RenderResponse] None Populated when status == "done".
error Optional[dict] None Populated when status == "failed".
created_at str ISO-8601 creation timestamp.
deadline str ISO-8601 max-runtime watchdog deadline.

Class RenderOutcome

Result of :func:render_deterministic — everything the route needs.

Parameter Type Default Description
html str
artifact_id str
url Optional[str]
url_note Optional[str]
persisted bool
sections_validated int
timings Dict[str, float] dict()

Fields:

Field Type Default Description
html str The rendered HTML (spliced or Jinja-rendered).
artifact_id str Server-generated artifact identifier (always present, even when persisted=False — nothing is stored under it then).
url Optional[str] Resolved per the two-behavior rule; None when neither applies (local, non-public, or not persisted).
url_note Optional[str] Explanation for a None url (spec §2's "explanatory field").
persisted bool Whether the artifact was actually saved.
sections_validated int Number of descriptor sections that passed the gate.
timings Dict[str, float] dataclass_field(default_factory=dict) Named stage timings, in seconds.

Class RenderPayloadError

A request part is malformed — the route maps this to HTTP 400.

Parameter Type Default Description
part_name str
message str

Attributes:

Attribute Type Description
part_name The offending part's name ("request" or "dataset:<name>"), surfaced in the 400 response.

Class RenderRequest

Body of POST /render (JSON body, or the request multipart part).

Fields:

Field Type Default Description
datasets Dict[str, Optional[InlineDataset]] alias -> :class:InlineDataset, or None when the dataset is instead hydrated from a multipart part named dataset:<alias>.
template str Pre-registered template name ONLY (no inline template HTML).
descriptor SectionDescriptor The FEAT-326 :class:SectionDescriptor — imported, never redefined.
theme Optional[str] None Optional registered theme name.
marker_id str 'report-data' Data-splice marker id (ignored for jinja mode).
agent_id Optional[str] None Attribution; system default applied when absent.
session_id Optional[str] None Attribution; system default applied when absent.
persist bool True Whether to persist the render as an artifact (awaited).
public bool False When True, also publish under STATIC_DIR (two-behavior URL rule; resolved in spec §2).
async_ bool False async in the wire payload (Python keyword-safe alias).

Class RenderResponse

application/json response for a completed render.

Fields:

Field Type Default Description
artifact_id str Identifier of the persisted artifact (server-generated even when persisted=False — nothing is stored under it then).
url Optional[str] Resolved URL per the two-behavior rule, or None when none applies.
url_note Optional[str] None Set whenever url is None — a machine-readable explanation (e.g. "not persisted", "retrieve via the artifacts handler using artifact_id") distinguishing the reasons the spec calls out (§2 Overview: "url: null plus an explanatory field").
template str The template name used.
sections_validated int Number of descriptor sections that passed the gate.
persisted bool Whether persistence succeeded.
timings Dict[str, float] Named stage timings, in seconds.

Function assemble_section_payload

Assemble a data-splice/jinja payload dict from validated section datasets.

For each section with a non-empty datasets list, builds the target's value from its dataset — restricted to columns[alias] when given (else every column) — shaped per section.shape:

  • "records": list of row dicts (DataFrame.to_dict("records")).
  • "table": list of row lists (DataFrame.values.tolist()).
  • "mapping": the first row as a {column: value} dict.
  • "scalar": the first row's first column value.

Sections with an empty datasets list are skipped (their value is expected to come from descriptor.params or caller-side composition upstream — nothing to assemble here).

v1 scope note: a section naming MORE THAN ONE dataset alias needs a bespoke transformer (how to combine them is not generically defined) — the generic assembler here supports exactly one dataset per section and raises :class:RenderPayloadError naming the section otherwise, rather than guessing a combination strategy.

assemble_section_payload(descriptor: SectionDescriptor, frames: Mapping[str, pd.DataFrame]) -> Dict[str, Any]

Parameter Type Default Description
descriptor SectionDescriptor The section descriptor driving assembly.
frames Mapping[str, pd.DataFrame] {name: DataFrame} — every alias referenced by a single-dataset section MUST already be present (the FEAT-326 validation gate is expected to have run first).

Returns: Dict[str, Any] — The assembled payload dict, keyed per each section's target.

Raises:

  • RenderPayloadError — A section names more than one dataset, or has no rows available for a "mapping"/"scalar" shape.

Function decode_inline_datasets

Decode every inline dataset declared on request into a DataFrame.

Entries whose value is None are skipped — they are expected to be hydrated from a multipart dataset:<name> part instead (see :func:parse_multipart_render_request).

decode_inline_datasets(request: RenderRequest) -> Dict[str, pd.DataFrame]

Parameter Type Default Description
request RenderRequest The parsed RenderRequest.

Returns: Dict[str, pd.DataFrame] — A {name: DataFrame} mapping for every non-None entry.

Raises:

  • RenderPayloadError — A dataset's inline payload does not match its declared orient.

Function parse_json_render_request

Parse a plain-JSON render body into a RenderRequest + decoded frames.

Reads the body via capped chunked reads off request.content — never buffers past max_body_size — mirroring :func:parse_multipart_render_request's pre-buffering cap enforcement. This is necessary because the JSON transport is NOT covered by the framework's own client_max_size at the granularity this endpoint requires (spec: 50 MB, configurable, independent of any app-wide ceiling).

parse_json_render_request(request: Any, *, max_body_size: int = DEFAULT_MAX_BODY_SIZE) -> Tuple[RenderRequest, Dict[str, pd.DataFrame]]

Parameter Type Default Description
request Any An aiohttp web.Request-shaped object (reads request.content.iter_chunked(...)).
max_body_size int DEFAULT_MAX_BODY_SIZE Cap, in bytes, on the total body size.

Returns: Tuple[RenderRequest, Dict[str, pd.DataFrame]] — The parsed RenderRequest and a {name: DataFrame} mapping decoded from its inline datasets.

Raises:

  • RenderPayloadError — The body is not valid JSON, fails RenderRequest validation, or declares a null dataset (impossible to hydrate — a JSON-only request has no multipart parts at all).
  • RenderBodyTooLargeError — The body exceeds max_body_size.

Function parse_multipart_render_request

Parse a multipart render body into a RenderRequest + decoded frames.

Expects exactly one JSON part named "request" and zero-or-more dataset parts named "dataset:<name>" (parquet, dtype-preserving via pyarrow, or CSV — selected by Content-Type/filename). Enforces max_body_size as a running total across every part read from the stream: a part that would push the total over the cap is aborted mid-read (never fully buffered) and raises :class:RenderBodyTooLargeError.

parse_multipart_render_request(reader: Any, *, max_body_size: int = DEFAULT_MAX_BODY_SIZE) -> Tuple[RenderRequest, Dict[str, pd.DataFrame]]

Parameter Type Default Description
reader Any An aiohttp multipart reader (await request.multipart()), yielding BodyPartReader parts.
max_body_size int DEFAULT_MAX_BODY_SIZE Cap, in bytes, on the summed size of every part read.

Returns: Tuple[RenderRequest, Dict[str, pd.DataFrame]] — The parsed RenderRequest and a {name: DataFrame} mapping decoded from the dataset:<name> parts (inline-only datasets are NOT decoded here — call :func:decode_inline_datasets for those).

Raises:

  • RenderPayloadError — The request part is missing/malformed, a dataset part fails to decode, or a dataset declared with data: null in the JSON has no matching multipart part.
  • RenderBodyTooLargeError — The running total exceeds max_body_size.

Function publish_to_static_dir

Write html under STATIC_DIR and return its /static/ URL.

The filename is server-generated from artifact_id (never a caller-controlled path segment) — sanitisation is inherent since artifact_id is always produced by :func:uuid.uuid4. The write runs via loop.run_in_executor (blocking file I/O off the event loop).

publish_to_static_dir(html: str, artifact_id: str) -> str

Parameter Type Default Description
html str The rendered HTML to publish.
artifact_id str The artifact identifier backing the filename.

Returns: str — The relative /static/<filename> URL (served by the app's add_static("/static/", ...) route — navigator's AppHandler with staticdir=STATIC_DIR).

Function render_deterministic

Validate, render, and (conditionally) persist a RenderRequest.

Runs the FEAT-326 gate (via :class:AdhocDatasetAdapter) BEFORE any render/persist step, assembles the section payload, renders through the toolkit's low-level primitives (bypassing render_data_template/render_template's UNCONDITIONAL internal persistence — see the module docstring note below) so that persist and the caller's own user_id/agent_id/session_id attribution are both honored exactly, then resolves the response URL.

Deliberately bypasses InfographicToolkit.render_data_template / render_template: both persist unconditionally under a _bot-scope- derived (or "_anon", when bot-less) identity, with no persist switch — incompatible with this endpoint's caller-supplied attribution and optional persistence. Instead this function uses the toolkit's own lower-level, persist-free primitives (_template_engine + InfographicToolkit._splice_payload for data-splice mode; _template_engine.render for jinja mode — the exact same calls render_data_template/render_template make internally, per the spec's own §6 Codebase Contract, which explicitly lists _splice_payload as a verified signature) and persists directly via ArtifactStore.save_artifact with this call's own scope.

render_deterministic(parsed: RenderRequest, frames: Mapping[str, pd.DataFrame], *, toolkit: InfographicToolkit, artifact_store: Optional[ArtifactStore], user_id: str, agent_id: str, session_id: str) -> RenderOutcome

Parameter Type Default Description
parsed RenderRequest The parsed RenderRequest.
frames Mapping[str, pd.DataFrame] {name: DataFrame} — every dataset referenced by the descriptor (inline + multipart, already decoded).
toolkit InfographicToolkit The server-owned InfographicToolkit instance.
artifact_store Optional[ArtifactStore] The configured store, or None (persistence is then skipped regardless of parsed.persist).
user_id str Attribution — from the authenticated session.
agent_id str Attribution — from the request body, or a system default.
session_id str Attribution — from the request body, or a system default.

Returns: RenderOutcome — class:RenderOutcome.

Raises:

  • InfographicValidationError — Aggregated dataset/shape deficits (sections_unmet / payload_shape_mismatch), or TEMPLATE_UNKNOWN/TEMPLATE_ENGINE_UNSET when the toolkit's OWN template registry does not know parsed.template (a registry-configuration gap — see module docstring).
  • RenderPayloadError — The section assembler could not build the payload.

Function resolve_response_url

Resolve the response (url, url_note) per the two-behavior rule (spec §2 Overview).

  • persisted=False → NEVER publishes anywhere, regardless of public. persist=False is the caller's explicit "do not retain this" signal; honoring public=True on top of that would silently override it by writing the HTML to the world-readable STATIC_DIR anyway. url is always None here, with an explanatory url_note.
  • persisted=True and public=True → publish html under STATIC_DIR and return the static URL (irreversible-ish: the file remains until cleaned up).
  • persisted=True and public=False → try :meth:ArtifactStore.get_public_url (S3 presigned, ALWAYS — infographics are never hosted on public S3); on KeyError/ ValueError (inline artifact / local backend), url is None with a note — retrieval then goes through the artifacts handler.

resolve_response_url(*, html: str, public: bool, persisted: bool, artifact_store: Optional[ArtifactStore], user_id: str, agent_id: str, session_id: str, artifact_id: str) -> Tuple[Optional[str], Optional[str]]

Parameter Type Default Description
html str The rendered HTML (needed only for the public=True branch).
public bool The request's public flag.
persisted bool Whether the artifact was actually saved. Gates BOTH branches — nothing is published when this is False.
artifact_store Optional[ArtifactStore] The configured store (only consulted when persisted is True).
user_id str Owning user (storage scope).
agent_id str Producing agent (storage scope).
session_id str Owning session (storage scope).
artifact_id str The artifact identifier.

Returns: Tuple[Optional[str], Optional[str]] — A (url, url_note) tuple — url_note is set whenever url is None, explaining why (spec §2: "url: null plus an explanatory field").

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally