Skip to content

API Reference

Complete reference for every public export in the accrue package. All types use Python 3.10+ syntax (X | None instead of Optional[X]).


Pipeline

from accrue import Pipeline

Pipeline(steps)

Pipeline(steps: list[Step])

Build a pipeline from an ordered list of steps. Validates on construction:

  • No duplicate step names.
  • Every depends_on reference points to an existing step.
  • No cycles in the dependency graph.

Raises PipelineError on validation failure.

pipeline.run(data, config?, hooks?, output_file?, confirm?, *, run_log?, display_key?, capture?)

pipeline.run(
    data: pd.DataFrame | list[dict[str, Any]],
    config: EnrichmentConfig | None = None,
    hooks: EnrichmentHooks | None = None,
    output_file: str | Path | None = None,
    confirm: bool = False,
    *,
    run_log: bool | str | Path = False,
    display_key: str | None = None,
    capture: str = "metadata",
) -> PipelineResult

Synchronous entry point. Wraps asyncio.run() internally. Raises RuntimeError if called from inside an existing event loop (use run_async in that case). Output type matches input type.

  • output_file -- save the enriched data before returning (.csv / .json / .parquet by extension).
  • confirm -- print a plan() preview and prompt y/n before the full run.
  • run_log -- write an append-only JSONL event stream for the run. True writes .accrue/runs/<run_id>.jsonl under the CWD; a str / Path names the file. User hooks still fire. See the run log guide.
  • display_key -- label column recorded in the run log (defaults to the first string column).
  • capture -- run-log capture tier: "metadata" (default; attempt metadata only), "prompts" (also persist rendered LLM prompt/response bodies to a <run>.prompts.jsonl sidecar), or "full" (currently behaves as "prompts"). Bodies are often PII, hence off by default. Raises ValueError on any other value. See capture tiers.

pipeline.run_async(data, config?, hooks?, output_file?, *, run_log?, display_key?, capture?)

await pipeline.run_async(
    data: pd.DataFrame | list[dict[str, Any]],
    config: EnrichmentConfig | None = None,
    hooks: EnrichmentHooks | None = None,
    output_file: str | Path | None = None,
    *,
    run_log: bool | str | Path = False,
    display_key: str | None = None,
    capture: str = "metadata",
) -> PipelineResult

Async variant. Use from FastAPI, Jupyter notebooks, or any async context. Same keywords as run() except confirm.

pipeline.plan(data, sample_size?, config?)

pipeline.plan(
    data: pd.DataFrame | list[dict[str, Any]],
    sample_size: int = 3,
    config: EnrichmentConfig | None = None,
) -> PipelinePlan

Dry run with a cost estimate. Runs the first sample_size rows for real (paid, but capped), then extrapolates their measured token usage to the full row count. Checkpointing is forced off for the sample, so it never writes or resumes the real run's checkpoint. Caching follows config, so cached sample rows are free in the full run and are left out of the extrapolation. run(..., confirm=True) prints the same preview and asks before running. See the plan mode guide.

pipeline.retry_failed(data, config?, hooks?, output_file?, *, rows?, steps?, run_log?, display_key?, data_identifier?)

pipeline.retry_failed(
    data: pd.DataFrame | list[dict[str, Any]],
    config: EnrichmentConfig | None = None,
    hooks: EnrichmentHooks | None = None,
    output_file: str | Path | None = None,
    *,
    rows: list[int] | None = None,
    steps: list[str] | None = None,
    run_log: bool | str | Path = False,
    display_key: str | None = None,
    data_identifier: str | None = None,
) -> PipelineResult

Re-run only the (step, row) cells the previous run recorded as errored, reading them from that run's checkpoint. Cells that succeeded are served from the checkpoint and never re-invoked, so a 5-failure retry over 10,000 rows costs 5 calls. Requires EnrichmentConfig(enable_checkpointing=True) -- pass the same config the original run used. Returns a PipelineResult over the whole dataset. Raises RuntimeError if called from inside an event loop, and PipelineError if checkpointing is off or no valid checkpoint exists.

  • rows -- restrict the retry to these row indices. Failures left out stay recorded for a later retry.
  • steps -- restrict the retry to these step names. A name the pipeline does not have raises PipelineError.
  • run_log -- path of the failed run's log to append to. The retry keeps that run's run_id and display_key (including a null one) and appends a retry_start ... retry_end segment; recovered cells arrive as ordinary row_complete records. See the run log guide.
  • data_identifier -- explicit checkpoint identifier. Defaults to the same id the run derived from the data (columns, row count, and a digest of the first and last five rows).

Steps the previous run never finished run in full -- without them there is no result to return. Downstream cells of a healed row are re-run, transitively through the DAG and only for those rows, so nothing is left holding an answer computed from the failure; see the checkpointing guide.

pipeline.retry_failed_async(data, config?, hooks?, output_file?, *, rows?, steps?, run_log?, display_key?, data_identifier?)

await pipeline.retry_failed_async(...)  # same signature as retry_failed

Async variant of retry_failed(). Use from FastAPI, Jupyter notebooks, or any async context.

pipeline.runner(config?)

pipeline.runner(config: EnrichmentConfig | None = None) -> Enricher

Returns a reusable Enricher instance bound to this pipeline and config. Use when you need repeated execution with checkpointing or want to manage the runner lifecycle in a server context.

from accrue import Enricher

Enricher(pipeline: Pipeline, config: EnrichmentConfig | None = None, hooks: Any = None)
enricher.run(df: pd.DataFrame, overwrite_fields: bool | None = None, data_identifier: str | None = None) -> pd.DataFrame
await enricher.run_async(df, overwrite_fields=None, data_identifier=None) -> pd.DataFrame

DataFrame in, DataFrame out (no PipelineResult). overwrite_fields overrides the config for this call; data_identifier names the checkpoint.

pipeline.clear_cache(step?, cache_dir?)

pipeline.clear_cache(
    step: str | None = None,
    cache_dir: str | None = None,
) -> int

Delete cached results from the SQLite cache. cache_dir=None means the EnrichmentConfig default ($XDG_CACHE_HOME/accrue, else ~/.cache/accrue); pass the same cache_dir your config uses if you changed it. Pass step to scope deletion to a single step, or None to delete all entries. Returns the number of entries deleted.

pipeline.step_names

@property
step_names: list[str]

All step names in execution order (topological).

pipeline.execution_levels

@property
execution_levels: list[list[str]]

Topological execution levels. Returns a read-only copy. Steps within the same level run in parallel.

pipeline.get_step(name)

pipeline.get_step(name: str) -> Step

Look up a step by name. Raises KeyError if the name does not exist in this pipeline.


PipelineResult

from accrue import PipelineResult

Returned by Pipeline.run() and Pipeline.run_async().

Field Type Description
data pd.DataFrame \| list[dict[str, Any]] Enriched output. Matches the input type.
cost CostSummary Aggregated token usage across all steps.
errors list[RowError] Per-row errors from this pass. Empty if all rows succeeded.
row_status pd.DataFrame How each (step, row) cell ended: one column per step, aligned to data's index (RangeIndex for list[dict] input), values "ok" / "error" / "skipped". Covers the whole dataset after retry_failed(). See Error Handling.
pipeline_elapsed_seconds float Wall time for the whole run.
step_elapsed_seconds dict[str, float] Wall time per step.
field_specs dict[str, dict[str, Any]] Field specs collected from the steps; drives report() heuristics.
Property Type Description
success_rate float Fraction of rows that completed without error (0.0--1.0).
has_errors bool True if any rows produced errors.
Method Description
summary() -> str Short text summary of rows, errors, tokens and time.
report(output_format="markdown", path=None, disable=None) -> str Heuristic run report: enum collapse, numeric clipping, length anomalies, retry storms, cache thrash, refusal patterns, cost outliers. output_format="html" gives a self-contained page; path also writes it; disable takes heuristic codes to skip. See the report guide.
save(path: str \| Path) -> Path Write data to .csv, .json or .parquet by extension, creating parent directories. run(..., output_file=...) calls this before returning.

PipelinePlan

from accrue import PipelinePlan, StepPlan

Returned by Pipeline.plan(). Call summary() for a readable preview.

@dataclass
class PipelinePlan:
    steps: list[StepPlan]
    sample_rows: list[dict[str, Any]]
    sample_outputs: list[dict[str, Any]]
    sample_errors: list[RowError]
    total_rows: int
    sample_size: int
    sample_cost: CostSummary       # measured on the sample
    estimated_cost: CostSummary    # extrapolated to total_rows
    unestimated_steps: list[str]   # property: LLM steps with no successful sample row

@dataclass
class StepPlan:
    name: str
    kind: str                      # "llm", "function" or "other"
    depends_on: list[str] = []
    model: str | None = None
    system_prompt: str | None = None         # the static, cacheable half of the prompt
    response_format: dict[str, Any] | None = None

Both costs are token counts, not money. prompt_tokens excludes the cached system prompt, which is in cache_write_tokens and cache_read_tokens, so price all four token fields. The estimate treats gated (run_if / skip_if) steps as running on every row, sends batch steps through the Batch API, and counts already-cached rows as zero.


compare

from accrue import compare, ComparisonResult

compare(
    a: PipelineResult,
    b: PipelineResult,
    *,
    label_a: str = "A",
    label_b: str = "B",
) -> ComparisonResult

Diff two runs, for the prompt-iteration loop. They need not come from the same pipeline; only output fields present in both are compared. See the compare guide.

ComparisonResult member Description
summary() -> str Markdown readout of what changed.
changed_rows(field=None) -> pd.DataFrame Before/after values for rows that differ (one field, or any). A row that errored on one side counts as changed.
distribution_shift() -> dict[str, FieldChurn] Per-field churn: frequency tables for enums, mean/std for numbers, differs-count for the rest.
cost_delta() -> CostDelta Token, cache-hit-rate and wall-time deltas.
report(output_format="markdown", path=None) -> str Full comparison report ("html" also works).
result_a, result_b, label_a, label_b, fields The inputs and the compared field names.

merge_runs

from accrue import merge_runs, MergedResult, Candidate

merge_runs(
    runs: Sequence[PipelineResult],
    *,
    fields: Sequence[str] | None = None,
    key: Callable[[Any], Any] | Mapping[str, Callable[[Any], Any]] | None = None,
    resolve: Resolver | Mapping[str, Resolver | Rule] | Rule | None = None,
) -> MergedResult

Combine two or more independent runs of the same pipeline over the same rows into one answer per cell. Rows are aligned to run 0 as compare() aligns them. Each run whose row did not error casts one vote:

  • "majority" (default for enums, numbers, booleans, dates, JSON, lists and fields with no spec): a strict majority wins; otherwise the earliest of the largest groups is kept and the cell is flagged needs_review.
  • "first" (default for free-text String fields): run 0's answer, unflagged.

key normalises values before comparing (one callable, or per field). resolve is a rule name, a resolver (field, candidates: list[Candidate]) -> Candidate | None, or a mapping of field to either. Raises ValueError for fewer than two runs. Give each run its own cache_dir, or later runs replay the first from the cache. See the merge runs guide.

MergedResult fields: data (merged rows), agreement (one row per cell: row, field, value, votes, voters, agreed, needs_review, basis, values), errored_rows, cost (summed), elapsed_seconds, fields, rules, runs. Property needs_review (the flagged cells); method summary().

Candidate(run: int, value: Any, row: dict[str, Any]) is one run's answer as a resolver sees it; row is that run's whole output row.


LLMStep

from accrue import LLMStep

Calls an LLM provider to produce structured enrichment values. Provider-agnostic via the LLMClient protocol (OpenAI by default).

Constructor

LLMStep(
    name: str,
    fields: list[str] | dict[str, str | dict],
    depends_on: list[str] | None = None,
    model: str = "gpt-6-luna",
    temperature: float | None = None,
    max_tokens: int | None = None,
    system_prompt: str | None = None,
    system_prompt_header: str | None = None,
    api_key: str | None = None,
    base_url: str | None = None,
    client: LLMClient | None = None,
    schema: Type[BaseModel] = EnrichmentResult,
    max_retries: int = 2,
    cache: bool = True,
    structured_outputs: bool | None = None,
    grounding: bool | dict | GroundingConfig | None = None,
    sources_field: str | None = "sources",
    run_if: Callable | None = None,
    skip_if: Callable | None = None,
    batch: bool = False,
    provider_kwargs: dict[str, Any] | None = None,
    attachments: str | None = None,
    run_on_upstream_error: bool = False,
    outside_knowledge: bool = True,
)
Parameter Description
name Unique step name used in logs, cache keys, and depends_on references.
fields Fields this step produces. list[str] for names only; dict[str, str \| dict] for inline field specs (string values are shorthand for {"prompt": value}).
depends_on Names of steps whose outputs this step needs. Resolved as DAG edges.
model Model identifier passed to the LLM provider.
temperature Sampling temperature. Falls back to config.temperature, then 0.2.
max_tokens Maximum response tokens. Falls back to config.max_tokens, then 4000.
system_prompt Tier 3 -- fully replaces the auto-generated system prompt.
system_prompt_header Tier 2 -- injected as a # Context section in the dynamic prompt. Ignored when system_prompt is set.
api_key Provider API key. Falls back to the relevant environment variable (e.g. OPENAI_API_KEY).
base_url OpenAI-compatible base URL (Ollama, Groq, etc.). Disables structured-output auto-detection.
client Pre-configured LLMClient instance. Overrides api_key and base_url.
schema Pydantic model for response validation. Default EnrichmentResult works with dynamic field specs. With structured_outputs=True the model's JSON schema is sent as a strict json_schema response format; OpenAI's strict mode also needs every property required (no defaults) and rejects the request otherwise.
max_retries Parse/validation retry attempts per API call (inner retry loop).
cache Enable input-hash caching for this step.
structured_outputs Override structured-output auto-detection. True forces json_schema -- built from a custom schema= model when set, otherwise from the field specs; False forces json_object; None auto-detects (a custom schema= stays json_object).
grounding Enable provider-level web search. True for defaults, dict or GroundingConfig for fine-grained control. None/False disables.
sources_field Output field name for grounding citations. Set to None to disable citation injection. Not in cache key.
run_if Predicate (row, prior_results) -> bool. Step only runs for rows where it returns True. Mutually exclusive with skip_if.
skip_if Predicate (row, prior_results) -> bool. Step is skipped for rows where it returns True. Mutually exclusive with run_if.
batch Use provider Batch API for this step. Requires BatchCapableLLMClient. Mutually exclusive with grounding.
provider_kwargs Extra kwargs merged into the provider API call. Escape hatch for provider-specific features (e.g. {"output_config": {"effort": "low"}} for Claude 5.x). Part of the cache key, so changing it re-runs the step.
attachments Name of a row column holding per-row documents (a Document, a file path, raw bytes, or a list of them). Rendered as provider document blocks ahead of the user text and excluded from <row_data>. Anthropic, OpenAI and Gemini; not through base_url. Cache key hashes document bytes, not paths. See the attachments guide.
run_on_upstream_error Run this step on a row even when a depends_on step ended "error" or "skipped" there. Default False: such rows are skipped, the fields are None and the status is "skipped". See error handling.
outside_knowledge Whether the model may fill a value from what it knows when the row does not contain it. Default True. Set False for extraction: the model is then told to answer only from the row, prior results, attached documents and search results. This greatly reduces filling from memory but isn't a guarantee, so check extraction that matters. Changes the generated prompt and the cache key. Ignored when system_prompt is set. See the prompt accrue sends.

step.build_messages(ctx)

step.build_messages(ctx: StepContext) -> tuple[list[dict[str, Any]], dict[str, Any]]

Build messages and call kwargs for a single row. Returns (messages, call_kwargs) where call_kwargs contains model, temperature, max_tokens, response_format, tools, and provider_kwargs. Used by both realtime and batch execution paths.

A message's content is a plain string, or -- when attachments= is set and the row has documents -- a list of content blocks: one {"type": "document", "media_type", "data", "title"} per document (raw bytes; the provider adapter encodes them) followed by {"type": "text", "text": ...}.

step.parse_response(response)

step.parse_response(response: LLMResponse) -> StepResult

Parse and validate an LLM response. Performs JSON decoding, Pydantic validation, field filtering, default enforcement, and citation injection. Raises json.JSONDecodeError or pydantic.ValidationError on invalid responses.

step.is_batch_eligible

@property
is_batch_eligible: bool

True when batch=True and the resolved client is batch-capable in its current configuration (is_batch_capable). Implementing BatchCapableLLMClient is not sufficient on its own — OpenAIClient with a base_url has the methods but no batch endpoint behind them. When batch=True and the client cannot batch, this returns False, the step runs in realtime, and a warning is logged once.


FunctionStep

from accrue import FunctionStep

Wraps any sync or async callable as a pipeline step. The callable receives a StepContext and must return dict[str, Any].

Constructor

FunctionStep(
    name: str,
    fn: Callable,
    fields: list[str],
    depends_on: list[str] | None = None,
    cache: bool = True,
    cache_version: str | None = None,
    run_if: Callable | None = None,
    skip_if: Callable | None = None,
    run_on_upstream_error: bool = False,
)
Parameter Description
name Unique step name used in logs, cache keys, and depends_on references.
fn Sync or async callable. Receives a StepContext, returns dict[str, Any] mapping field names to values.
fields Field names this step produces (list[str] only -- no dict field specs).
depends_on Names of steps whose outputs this step needs.
cache Enable input-hash caching for this step.
cache_version Bump to invalidate cached results when function logic changes (e.g. "v2").
run_if Predicate (row, prior_results) -> bool. Mutually exclusive with skip_if.
skip_if Predicate (row, prior_results) -> bool. Mutually exclusive with run_if.
run_on_upstream_error Run this step on a row even when a depends_on step ended "error" or "skipped" there. Default False: such rows are skipped, the fields are None and the status is "skipped". See error handling.

Step Protocol

from accrue import Step

The protocol all steps must satisfy. Implementations can be plain classes -- no inheritance required.

@runtime_checkable
class Step(Protocol):
    name: str
    fields: list[str]
    depends_on: list[str]

    async def run(self, ctx: StepContext) -> StepResult: ...

The pipeline also reads these optional attributes when a step has them: run_if / skip_if (predicates), cache (default True) and run_on_upstream_error (default False).


StepContext

from accrue import StepContext

Immutable dataclass passed to each step's run() method.

@dataclass(frozen=True)
class StepContext:
    row: dict[str, Any]
    fields: dict[str, dict[str, Any]]
    prior_results: dict[str, Any]
    config: EnrichmentConfig | None = None
    row_index: int | None = None
    capture: str = "metadata"
    on_attempt: Callable[[RowAttemptEvent], Awaitable[None]] | None = None
Field Description
row Original row data as dict[str, Any].
fields Resolved field specs for this step only. Always dict[str, dict], even when the constructor received list[str].
prior_results Merged outputs from all dependency steps for the current row.
config Optional EnrichmentConfig for reading runtime settings.
row_index Position of the row in the input.
capture The run's run-log capture tier ("metadata", "prompts", "full").
on_attempt Set by the pipeline when an on_row_attempt hook is registered; steps call it once per provider attempt.

StepResult

from accrue import StepResult

Output from a single step execution.

@dataclass
class StepResult:
    values: dict[str, Any]
    usage: UsageInfo | None = None
    metadata: dict[str, Any] = field(default_factory=dict)
Field Description
values Field name to produced value.
usage Token usage (LLM steps only).
metadata Arbitrary metadata for logging/debugging (e.g. raw_response, attempts).

EnrichmentConfig

from accrue import EnrichmentConfig

Configuration dataclass for pipeline execution. All fields have sensible defaults.

@dataclass
class EnrichmentConfig:
    # LLM
    max_tokens: int = 4000
    temperature: float = 0.2

    # Concurrency
    max_workers: int = 10

    # Fields
    overwrite_fields: bool = False

    # Reliability
    max_retries: int = 3
    retry_base_delay: float = 1.0
    on_error: str = "continue"

    # Logging
    log_level: str = "INFO"
    enable_progress_bar: bool = True

    # Checkpointing
    enable_checkpointing: bool = False
    checkpoint_dir: str = <state dir>  # absolute path: $XDG_STATE_HOME/accrue, else ~/.local/state/accrue
    auto_resume: bool = True
    checkpoint_interval: int = 0

    # Caching
    enable_caching: bool = True
    cache_ttl: int = 3600
    cache_dir: str = <cache dir>       # absolute path: $XDG_CACHE_HOME/accrue, else ~/.cache/accrue

    # Batch API
    batch_poll_interval: float = 60.0
    batch_timeout: float = 86400.0
    batch_max_requests: int = 50000
    batch_max_bytes: int | None = None
Field Default Description
max_tokens 4000 Maximum tokens for LLM output.
temperature 0.2 LLM temperature. Low values (0.1--0.3) are best for structured enrichment.
max_workers 10 Concurrent rows per step (semaphore bound). Production: 20--30.
overwrite_fields False Whether to overwrite existing field values in the DataFrame.
max_retries 3 Maximum retry attempts for API errors (429, 500, timeouts).
retry_base_delay 1.0 Base delay in seconds for exponential backoff. Actual: base * 2^attempt + jitter.
on_error "continue" "continue" collects errors and returns partial results; "raise" fails fast.
log_level "INFO" Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL).
enable_progress_bar True Show tqdm progress bar during execution.
enable_checkpointing False Save results after each step for crash recovery.
checkpoint_dir ~/.local/state/accrue Directory for checkpoint files. $XDG_STATE_HOME/accrue when that variable is set.
auto_resume True Automatically resume from checkpoint on re-run.
checkpoint_interval 0 Save partial step progress every N rows. 0 disables.
enable_caching True Enable input-hash SQLite cache to skip redundant API calls. Set False for one-off runs or when you need a guaranteed-fresh result.
cache_ttl 3600 Cache time-to-live in seconds. 0 means entries never expire.
cache_dir ~/.cache/accrue Directory for cache.db. $XDG_CACHE_HOME/accrue when that variable is set.
batch_poll_interval 60.0 Seconds between batch job status checks.
batch_timeout 86400.0 Maximum seconds to wait for a batch job (default: 24 hours).
batch_max_requests 50000 Maximum requests per batch submission. Larger sets are auto-chunked.
batch_max_bytes None Maximum estimated payload bytes per batch submission (base64 attachments included). None uses the client's max_batch_bytes.

Presets

EnrichmentConfig.for_development()   # max_workers=5, DEBUG, caching on
EnrichmentConfig.for_production()    # max_workers=30, checkpointing + caching
EnrichmentConfig.for_server()        # max_workers=30, no progress bar, WARNING
EnrichmentConfig.for_batch()         # caching + checkpointing, 24h timeout
Preset Key settings
for_development() max_workers=5, log_level="DEBUG", enable_caching=True. Safe for Tier 1 accounts.
for_production() max_workers=30, enable_checkpointing=True, enable_caching=True, checkpoint_interval=100, max_retries=5.
for_server() max_workers=30, enable_progress_bar=False, log_level="WARNING", max_retries=5. For async server contexts.
for_batch() enable_caching=True, enable_checkpointing=True, batch_poll_interval=60.0, batch_timeout=86400.0, max_retries=5.

EnrichmentHooks

from accrue import EnrichmentHooks

Hook container passed to Pipeline.run() or run_async(). All fields are optional. Sync and async callables both work. Hook errors are caught and logged -- they never crash the pipeline.

@dataclass
class EnrichmentHooks:
    on_pipeline_start: Callable[[PipelineStartEvent], Any] | None = None
    on_pipeline_end: Callable[[PipelineEndEvent], Any] | None = None
    on_step_start: Callable[[StepStartEvent], Any] | None = None
    on_step_end: Callable[[StepEndEvent], Any] | None = None
    on_row_complete: Callable[[RowCompleteEvent], Any] | None = None
    on_row_attempt: Callable[[RowAttemptEvent], Any] | None = None

Event Types

from accrue import (
    PipelineStartEvent,
    PipelineEndEvent,
    StepStartEvent,
    StepEndEvent,
    RowCompleteEvent,
    RowAttemptEvent,
)

PipelineStartEvent

Fired once at the beginning of run_async().

Field Type
step_names list[str]
num_rows int
config EnrichmentConfig

PipelineEndEvent

Fired once at the end of run_async() (including on error).

Field Type
num_rows int
total_errors int
cost Any
elapsed_seconds float

StepStartEvent

Fired before a step begins processing rows.

Field Type Default
step_name str
num_rows int
level int
execution_mode str "realtime"

StepEndEvent

Fired after a step finishes all rows.

Field Type Default
step_name str
num_rows int
num_errors int
usage Any
elapsed_seconds float
execution_mode str "realtime"
batch_id str \| None None
batch_ids list[str] []

RowCompleteEvent

Fired after each row completes within a step.

Field Type Default
step_name str
row_index int
values dict[str, Any]
error BaseException \| None
from_cache bool
skipped bool False
usage Any \| None None
elapsed_ms float \| None None

usage (a UsageInfo) and elapsed_ms are populated on the realtime path when available, for failed rows too (usage covers every billed attempt); None in batch mode, for cache hits, skipped rows, and steps that emit no usage (e.g. FunctionStep).

RowAttemptEvent

Fired once per LLM provider attempt, inside LLMStep.run()'s retry loops — several precede a retrying cell's single RowCompleteEvent. Only LLM steps fire it.

Field Type Default
step_name str
row_index int
attempt int 1-based, across both loops
kind str "api" or "parse"
status str "ok", "rate_limited", "timeout", "api_error", "parse_error", "validation_error"
latency_ms float \| None
backoff_s float \| None sleep before the next attempt, else None
error BaseException \| None None
body dict \| None None — rendered {messages, response, parsed}, present only at capture >= "prompts"

read_prompt_ref

from accrue import read_prompt_ref

body = read_prompt_ref(sidecar_path: str | Path, off: int, len: int) -> dict

Resolves a row_attempt record's prompt_ref into the captured body stored in the prompt sidecar. Seeks to byte offset off, reads len bytes, and JSON-parses the one body there. A record's ref splats straight in: read_prompt_ref(sidecar, **rec["prompt_ref"]). Only meaningful for runs at capture >= "prompts" (at metadata, every prompt_ref is null).


JsonlRunLogger

from accrue import JsonlRunLogger

Writes the run-log contract v1 as append-only JSONL. A plain EnrichmentHooks consumer -- run(..., run_log=True) wires one up automatically, or drive it yourself:

JsonlRunLogger(
    path: str | Path,
    *,
    run_id: str | None = None,        # default: new_run_id() -- YYYY-MM-DD-HHMMSS-xxxxxx (UTC + random suffix)
    display_key: str | None = None,   # label column recorded in pipeline_start
    pipeline: Pipeline | None = None, # enables per-step level/mode/model metadata
    data: pd.DataFrame | list[dict] | None = None,  # enables row_complete.key
    segment: str = "run",             # "run" or "retry"
    t_offset: float = 0.0,            # seconds added to every record's t
    retry_cells: dict[str, list[int]] | None = None,  # cells recorded in retry_start
    capture: str = "metadata",        # "metadata" | "prompts" | "full"
)
Argument Type Description
data DataFrame \| list[dict] \| None The input rows. Without it every row_complete carries key: null — the log holds only step outputs, so the display value cannot be recovered from it later.
segment str "run" (default) frames the events as a whole run, pipeline_start … pipeline_end. "retry" frames them as a failed-only retry appended to an existing run: the wrapper records become retry_start / retry_end, so a consumer never mistakes the appended segment for a second run.
t_offset float Seconds added to every record's t. Set it to the existing file's last t (see read_run_context) when appending to a log, keeping t non-decreasing across the file. run(..., run_log=<existing path>) does this for you.
retry_cells dict[str, list[int]] \| None {step: [row_index, ...]} this retry will re-execute, recorded in retry_start so a UI can mark the cells in flight.
capture str Capture tier gating the prompt sidecar: "metadata" (default, no bodies), "prompts" / "full" append each captured LLM attempt body to <run>.prompts.jsonl and reference it from row_attempt via prompt_ref. See capture tiers.
Attribute Type Description
hooks EnrichmentHooks Pass to pipeline.run(data, hooks=logger.hooks).
run_id str Identifier written into the pipeline_start record.
path Path Destination .jsonl file (parents created on first write, mode 0600).

close() closes the file handle; it is called automatically when pipeline_end is written.


Schemas

FieldSpec

from accrue import FieldSpec

Pydantic model for the 7-key field specification. Unknown keys are rejected (extra="forbid").

class FieldSpec(BaseModel):
    prompt: str                           # Required. Extraction instruction.
    type: VALID_TYPES = "String"          # "String" | "Number" | "Boolean" | "Date" | "List[String]" | "JSON"
    format: str | None = None             # Output format pattern (e.g. "YYYY-MM-DD").
    enum: list[str] | None = None         # Constrained value list.
    examples: list[str] | None = None     # Good output examples.
    bad_examples: list[str] | None = None # Anti-patterns to avoid.
    default: Any = None                   # Fallback when data is insufficient.

Use "default" in spec.model_fields_set to detect whether default was explicitly provided. A field with default set to None explicitly is nullable in the structured-output schema.

describe_from_specs

from accrue import describe_from_specs

describe_from_specs(
    model: type[BaseModel],
    field_specs: dict[str, FieldSpec | str | dict[str, Any]],
) -> type[BaseModel]

Returns model with each matching field spec written into the property's JSON schema description (prompt, format and examples, as build_json_schema writes them): a same-named subclass when anything changes, the model itself when nothing does. Use it with LLMStep(schema=..., structured_outputs=True): the constrained decoder reads those descriptions, and a custom schema doesn't get the spec text otherwise (accrue warns when it is missing). Fields whose description already contains the prompt are left alone; names with no matching field are ignored; the input model is not modified.

Document

from accrue import Document

A single binary document attached to one row's LLM call, for LLMStep(attachments=...).

@dataclass(frozen=True)
class Document:
    data: bytes                            # Raw file bytes; the provider encodes them.
    media_type: str = "application/pdf"    # IANA media type.
    title: str | None = None               # Optional title passed to the provider.
Document.from_path(path, title=None, media_type=None) -> Document
document.sha256 -> str                     # Hex digest of the bytes; the cache identity.

from_path() defaults title to the file name and guesses media_type via mimetypes, falling back to application/pdf. It raises StepError on an unreadable path. repr() shows title, media type, and byte count -- never the bytes. See the attachments guide.

GroundingConfig

from accrue import GroundingConfig

Configuration for provider-level web search grounding. Pass to LLMStep(grounding=...).

class GroundingConfig(BaseModel):
    allowed_domains: list[str] | None = None
    blocked_domains: list[str] | None = None
    user_location: dict[str, str] | None = None
    max_searches: int | None = None
    provider_kwargs: dict[str, Any] | None = None
Field Description
allowed_domains Only include results from these domains. OpenAI and Anthropic only.
blocked_domains Never include results from these domains. OpenAI (filters.blocked_domains), Anthropic and Google (exclude_domains). Anthropic rejects both lists in one request.
user_location Dict with keys: country (ISO 3166-1 alpha-2), region, city, timezone (IANA).
max_searches Maximum searches per LLM call. Anthropic only (max_uses).
provider_kwargs Provider-specific kwargs merged into native tool config (e.g. OpenAI search_context_size).

CostSummary

from accrue import CostSummary

Aggregated cost/usage across all pipeline steps. Available as PipelineResult.cost.

class CostSummary(BaseModel):
    total_prompt_tokens: int = 0
    total_completion_tokens: int = 0
    total_tokens: int = 0
    total_cache_write_tokens: int = 0
    total_cache_read_tokens: int = 0
    steps: dict[str, StepUsage] = {}

Token counts only; there are no money fields.

StepUsage

Per-step aggregated token usage. Accessed via CostSummary.steps["step_name"].

class StepUsage(BaseModel):
    prompt_tokens: int = 0
    completion_tokens: int = 0
    total_tokens: int = 0
    cache_write_tokens: int = 0
    cache_read_tokens: int = 0
    rows_processed: int = 0
    rows_skipped: int = 0
    model: str = ""
    cache_hits: int = 0
    cache_misses: int = 0
    execution_mode: str = "realtime"
    batch_id: str | None = None   # first batch submitted
    batch_ids: list[str] = []     # every batch submitted, in order
Property Type Description
cache_hit_rate float cache_hits / (cache_hits + cache_misses), or 0.0 if no rows.

UsageInfo

from accrue.schemas.base import UsageInfo

Token usage from a single LLM call.

class UsageInfo(BaseModel):
    prompt_tokens: int = 0
    completion_tokens: int = 0
    total_tokens: int = 0
    model: str = ""
    cache_write_tokens: int = 0
    cache_read_tokens: int = 0

Providers

from accrue.providers import (
    LLMClient,
    LLMResponse,
    LLMAPIError,
    OpenAIClient,
    AnthropicClient,
    GoogleClient,
)

LLMClient Protocol

The protocol all LLM provider adapters must satisfy.

@runtime_checkable
class LLMClient(Protocol):
    async def complete(
        self,
        messages: list[dict[str, Any]],
        model: str,
        temperature: float,
        max_tokens: int,
        response_format: dict[str, Any] | None = None,
        tools: list[dict[str, Any]] | None = None,
        provider_kwargs: dict[str, Any] | None = None,
    ) -> LLMResponse: ...

BatchCapableLLMClient Protocol

from accrue import BatchCapableLLMClient

Extended protocol for providers that support batch API operations. The pipeline decides the execution path with is_batch_capable(client) rather than a bare isinstance, since a runtime_checkable Protocol only checks that the methods exist — it cannot tell native OpenAI from a gateway that has no batch endpoint.

@runtime_checkable
class BatchCapableLLMClient(LLMClient, Protocol):
    async def submit_batch(
        self,
        requests: list[BatchRequest],
        metadata: dict[str, str] | None = None,
    ) -> str: ...

    async def poll_batch(
        self,
        batch_id: str,
        poll_interval: float = 60.0,
        timeout: float = 86400.0,
    ) -> BatchResult: ...

    async def cancel_batch(self, batch_id: str) -> None: ...
Method Description
submit_batch Submit a list of BatchRequest objects. Returns the provider batch ID.
poll_batch Poll until the batch completes or timeout. Returns BatchResult. Raises StepError on failure/expiry.
cancel_batch Best-effort cancel a running batch job.

LLMResponse

@dataclass
class LLMResponse:
    content: str
    usage: UsageInfo | None = None
    citations: list[Citation] = field(default_factory=list)

BatchRequest

from accrue import BatchRequest

A single request within a batch submission.

@dataclass
class BatchRequest:
    custom_id: str
    messages: list[dict[str, Any]]
    model: str
    temperature: float
    max_tokens: int
    response_format: dict[str, Any] | None = None
    tools: list[dict[str, Any]] | None = None
    provider_kwargs: dict[str, Any] | None = None

BatchResult

from accrue import BatchResult

Aggregated result from a completed batch job.

@dataclass
class BatchResult:
    responses: dict[str, LLMResponse] = field(default_factory=dict)
    failed_ids: list[str] = field(default_factory=list)
    batch_id: str = ""
    errors: dict[str, str] = field(default_factory=dict)
Field Description
responses Mapping of custom_id to the provider LLMResponse.
failed_ids custom_id values for requests that failed.
batch_id Provider batch job identifier.
errors Mapping of custom_id to error message for failed requests.

OpenAIClient

from accrue.providers import OpenAIClient

OpenAIClient(
    api_key: str | None = None,
    base_url: str | None = None,
    http_client: Any | None = None,
)

Default adapter. Native OpenAI (no base_url) uses the Responses API with web search, structured outputs, and inline citations. Third-party providers with a base_url (Ollama, Groq, DeepSeek, Together, Fireworks, vLLM, Mistral, LM Studio) use Chat Completions for compatibility.

Sends LLMStep(attachments=...) PDFs on native OpenAI, realtime and batch. With base_url they raise StepError.

Implements BatchCapableLLMClient, but reports supports_batch = False when base_url is set — gateways expose chat completions without the batch endpoints. Calling submit_batch() / poll_batch() on a base_url client raises StepError.

AnthropicClient

from accrue.providers import AnthropicClient

AnthropicClient(
    api_key: str | None = None,
    http_client: Any | None = None,
    timeout: float | None = None,
    max_pause_continuations: int = 5,
)

Adapter for Anthropic Claude models. Requires pip install "accrue[anthropic]". Falls back to ANTHROPIC_API_KEY env var. Supports web_search_20250305 server tool for grounding, with the strict schema kept. Automatic prompt caching via cache_control on system messages. Sends LLMStep(attachments=...) documents as document blocks.

timeout (seconds) is forwarded to AsyncAnthropic. Set it when max_tokens exceeds roughly 21,000 -- the SDK refuses a non-streaming request of that estimated duration unless a non-default timeout was configured.

max_pause_continuations caps how many times a search turn that ends with stop_reason: "pause_turn" is resumed (0 turns it off). Usage and sources are summed across the requests. See Long searches on Anthropic.

Implements BatchCapableLLMClient via the Anthropic Message Batches API.

GoogleClient

from accrue.providers import GoogleClient

GoogleClient(
    api_key: str | None = None,
    http_client: Any | None = None,
)

Adapter for Google Gemini models. Requires pip install "accrue[google]". Falls back to GOOGLE_API_KEY env var. Supports the google_search grounding tool. With grounding, structured outputs fall back to JSON mode.

Sends LLMStep(attachments=...) PDFs as inline data.

Does not implement BatchCapableLLMClient.

LLMAPIError

from accrue.providers import LLMAPIError

LLMAPIError(
    message: str,
    *,
    status_code: int | None = None,
    retry_after: float | None = None,
    is_rate_limit: bool = False,
    retryable: bool | None = None,
)

Provider-agnostic API error for retry logic. Wraps provider-specific errors so LLMStep retry logic does not need to know about specific SDKs.

Attribute Type Description
status_code int \| None HTTP status code (e.g. 429, 500, 408).
retry_after float \| None Seconds to wait before retrying (from Retry-After header).
is_rate_limit bool True if this is a rate limit error.
retryable bool Whether accrue retries the call. Defaults from the status code (429, 5xx and timeouts retry) unless set explicitly.

Utilities

from accrue import web_search

Factory returning an async callable for use with FunctionStep. Runs the search through Anthropic, OpenAI or Google, picked from the model name (claude-*, gemini-*, anything else OpenAI) or from client. See the web search guide.

web_search(
    query: str,
    *,
    model: str | None = None,
    search_context_size: str = "medium",
    api_key: str | None = None,
    include_sources: bool = True,
    user_location: dict[str, str] | None = None,
    allowed_domains: list[str] | None = None,
    blocked_domains: list[str] | None = None,
    tool_type: str = "web_search",
    client: LLMClient | None = None,
    max_searches: int | None = None,
    max_tokens: int = 8192,
    provider_kwargs: dict[str, Any] | None = None,
) -> Callable[[StepContext], Awaitable[dict[str, Any]]]
Parameter Description
query Template string with {field} placeholders, formatted with ctx.row and ctx.prior_results.
model Search model; picks the provider. Default gpt-6-luna (OpenAI), claude-haiku-5-5 (Anthropic) or gemini-3.1-flash-lite (Google); OpenAI when neither model nor client is set.
search_context_size OpenAI only: "low" / "medium" / "high".
api_key Provider API key. Falls back to OPENAI_API_KEY, ANTHROPIC_API_KEY or GOOGLE_API_KEY.
include_sources Return the cited URLs in sources.
user_location Geographic bias dict with keys country, city, region, timezone. OpenAI and Anthropic.
allowed_domains Restrict results to these domains. OpenAI (tool_type="web_search" only) and Anthropic.
blocked_domains Never return results from these domains. OpenAI (tool_type="web_search" only), Anthropic and Google. Anthropic takes one list or the other, not both (ValueError).
tool_type OpenAI only: "web_search" (GA) or "web_search_preview" (legacy).
client Adapter to run the search with. A built-in adapter also sets the provider; a custom one needs model.
max_searches Anthropic only: searches per row (max_uses).
max_tokens Output cap for the search call, thinking and reasoning included.
provider_kwargs Merged into the provider call, as on LLMStep.

Options a provider doesn't support are dropped with a warning. Returns {"__web_context": str, "sources": list[str]}. Rate limits, timeouts and 5xx errors are retried twice; after that it logs a warning and returns empty context.

setup_logging()

from accrue import setup_logging

setup_logging(
    level: str = "INFO",
    format_type: Literal["console", "json"] = "console",
    include_timestamp: bool = True,
) -> None

Configure logging for the application: coloured console output or JSON lines. Accrue itself only attaches a NullHandler, so call this (or configure logging yourself) to see its logs.


Field specs from CSV

from accrue.data import load_fields, FieldManager

load_fields()

load_fields(csv_path: str, category: str | None = None) -> dict[str, dict[str, Any]]

Load field specs from a CSV, ready for LLMStep(fields=...). category keeps only that category's fields.

FieldManager

FieldManager(fields_categories_path: str)
FieldManager.from_csv(csv_path: str) -> FieldManager

Loads field categories from a CSV and gives structured access: get_categories() -> list[str], get_category_fields(category) -> dict[str, dict[str, Any]], get_field_count(category=None) -> int, validate_category(category) -> bool.


Errors

Exception Hierarchy

EnrichmentError
  +-- FieldValidationError
  +-- ConfigurationError
  +-- StepError
  +-- PipelineError

All exceptions inherit from EnrichmentError and are importable from accrue.

EnrichmentError

from accrue import EnrichmentError

EnrichmentError(
    message: str,
    row_index: int | None = None,
    field: str | None = None,
)

Base exception for all enrichment-related errors.

Attribute Type Description
message str Human-readable error description.
row_index int \| None Row that triggered the error.
field str \| None Field name involved.

FieldValidationError

from accrue import FieldValidationError

Raised when field definitions are invalid. Same constructor as EnrichmentError. Common causes: unknown keys in a field spec, missing prompt, invalid type or enum values.

ConfigurationError

from accrue.core.exceptions import ConfigurationError

Raised when configuration is invalid. Same constructor as EnrichmentError.

StepError

from accrue import StepError

Raised when a pipeline step fails after exhausting retries.

StepError(
    message: str,
    step_name: str | None = None,
    **kwargs,
)
Attribute Type Description
step_name str \| None Name of the step that failed.

PipelineError

from accrue import PipelineError

Raised when pipeline construction or execution fails. Same constructor as EnrichmentError. Common causes: duplicate step names, missing dependency references, dependency cycles.

RowError

from accrue import RowError

Per-row failure record for partial result tracking. Dataclass, not an exception.

@dataclass
class RowError:
    row_index: int
    step_name: str
    error: BaseException
    error_type: str = ""  # Auto-set to type(error).__name__

Exports

from accrue import ...

from accrue import (
    # Primary API
    Pipeline,
    PipelineResult,
    PipelinePlan,
    StepPlan,
    LLMStep,
    FunctionStep,
    EnrichmentConfig,
    compare,
    ComparisonResult,
    merge_runs,
    MergedResult,
    Candidate,

    # Hooks
    EnrichmentHooks,
    PipelineStartEvent,
    PipelineEndEvent,
    StepStartEvent,
    StepEndEvent,
    RowCompleteEvent,
    RowAttemptEvent,

    # Run log
    JsonlRunLogger,
    read_prompt_ref,

    # Step protocol
    Step,
    StepContext,
    StepResult,

    # Attachments
    Document,

    # Schemas
    FieldSpec,
    GroundingConfig,
    describe_from_specs,

    # Utilities
    setup_logging,
    web_search,

    # Batch API
    BatchCapableLLMClient,
    is_batch_capable,
    BatchRequest,
    BatchResult,

    # Results & errors
    CostSummary,
    RowError,
    EnrichmentError,
    FieldValidationError,
    StepError,
    PipelineError,

    # Internal runner (power users)
    Enricher,
)

accrue.__all__ is the authoritative list, and tests/public_api_snapshot.json pins every signature.

from accrue.data import ...

from accrue.data import FieldManager, load_fields

from accrue.providers import ...

from accrue.providers import (
    LLMClient,
    LLMResponse,
    LLMAPIError,
    OpenAIClient,
    AnthropicClient,
    GoogleClient,
)