Metadata-Version: 2.5
Name: accrue
Version: 1.8.0
Summary: A composable pipeline engine for structured data enrichment using LLMs
Project-URL: Homepage, https://github.com/matt-house-e/accrue
Project-URL: Bug Reports, https://github.com/matt-house-e/accrue/issues
Project-URL: Source, https://github.com/matt-house-e/accrue
Project-URL: Documentation, https://matt-house-e.github.io/accrue/
Author-email: Matthew House <matt.house.e@gmail.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: openai>=1.66.0
Requires-Dist: pandas>=2.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: tqdm>=4.65.0
Provides-Extra: all
Requires-Dist: anthropic>=0.40.0; extra == 'all'
Requires-Dist: google-genai>=1.46.0; extra == 'all'
Requires-Dist: ipykernel>=6.0; extra == 'all'
Requires-Dist: pre-commit>=4.0; extra == 'all'
Requires-Dist: pytest-asyncio>=0.25.0; extra == 'all'
Requires-Dist: pytest-cov>=5.0; extra == 'all'
Requires-Dist: pytest-mock>=3.10; extra == 'all'
Requires-Dist: pytest>=7.0; extra == 'all'
Requires-Dist: ruff>=0.14.0; extra == 'all'
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.40.0; extra == 'anthropic'
Provides-Extra: dev
Requires-Dist: ipykernel>=6.0; extra == 'dev'
Requires-Dist: pre-commit>=4.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.25.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest-mock>=3.10; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff>=0.14.0; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material<10,>=9.5; extra == 'docs'
Requires-Dist: mkdocs>=1.6; extra == 'docs'
Provides-Extra: google
Requires-Dist: google-genai>=1.46.0; extra == 'google'
Provides-Extra: ui
Requires-Dist: accrue-ui>=0.1; extra == 'ui'
Description-Content-Type: text/markdown

<p align="center">
  <strong>Accrue</strong><br>
  <em>LLM enrichment for tables and documents, in Python.</em>
</p>

<p align="center">
  <a href="https://pypi.org/project/accrue/"><img src="https://img.shields.io/pypi/v/accrue?color=blue" alt="PyPI"></a>
  <a href="https://pypi.org/project/accrue/"><img src="https://img.shields.io/pypi/pyversions/accrue" alt="Python"></a>
  <a href="https://github.com/matt-house-e/accrue/blob/main/LICENSE"><img src="https://img.shields.io/github/license/matt-house-e/accrue" alt="License"></a>
</p>

<p align="center"><a href="https://matt-house-e.github.io/accrue/"><b>Documentation</b></a></p>

---

Accrue uses an LLM to fill in structured fields across a table of records or a folder of documents. You describe each field once, point it at a DataFrame, and get typed columns back: categories, scores, extracted values, short summaries.

It's built for jobs of a few hundred to tens of thousands of rows, where the cost, the reruns and checking the results all matter. For example:

- tagging or classifying free text: support tickets, survey answers, reviews
- comparing hundreds of products or supplier offers on the same criteria
- pulling the same fields out of a pile of contracts, papers or reports
- researching and scoring a list of companies

```python
from accrue import Pipeline, LLMStep

pipeline = Pipeline([
    LLMStep("extract", fields={
        "category": {"prompt": "What the product is", "enum": ["chair", "desk", "lamp", "storage"]},
        "unit_price_gbp": {"prompt": "Price per single item ex VAT, in pounds", "type": "Number"},
        "warranty_years": {"prompt": "Warranty in years", "type": "Number"},
        "fire_rated": {"prompt": "Is it fire rated?", "enum": ["yes", "no", "unknown"]},
    }),
])

# Runs the first rows, prints the prompt, schema and token estimate, then asks before the rest
result = pipeline.run(listings_df, confirm=True)  # DataFrame in, DataFrame out
print(result.data.head())
```

On 5,000 supplier listings like these, `plan()` measured 5 rows and estimated about 3.1M input and 310K output tokens. On the default model, `gpt-6-luna`, that's about 50 cents, or about 25 cents with `batch=True`. It's an estimate, not a quote ([prices](https://github.com/matt-house-e/accrue/blob/main/.claude/skills/accrue/references/providers.md)).

<p align="center">
  <a href="#watch-it-run"><img src="https://raw.githubusercontent.com/matt-house-e/accrue/main/docs/assets/watch-overview.png" alt="Accrue Watch, Overview tab: a live 5,000-row enrichment run with its pipeline steps, models, produced fields, and cost" width="100%"></a>
  <br><sub>A 5,000-row run in <a href="#watch-it-run"><b>Accrue Watch</b></a>: every step, model, field and dollar, read live from the run log.</sub>
</p>

Using Claude Code? The [`/accrue` skill](#using-it-with-claude-code) builds this for you from a sentence:

```
> /accrue I have 5,000 supplier listings in listings.csv. Pull out category, unit price,
  warranty and fire rating. Try it on 5 rows and show me the cost, then run the rest.
```

## Install

Requires Python 3.10+.

```bash
pip install accrue
```

Set your API key:

```bash
export OPENAI_API_KEY=sk-...
```

OpenAI is the default provider, with [structured outputs](https://platform.openai.com/docs/guides/structured-outputs) switched on. Anthropic and Google are optional extras:

```bash
pip install "accrue[anthropic]"  # Claude
pip install "accrue[google]"     # Gemini
```

You're not tied to those three. Any API that speaks the OpenAI format works through `base_url`, including local models, so your data can stay on your own machine:

```python
LLMStep("extract", fields={...}, model="llama3", base_url="http://localhost:11434/v1")  # Ollama
```

That covers OpenRouter (one key for hundreds of models), Ollama, vLLM, Groq, Together, Fireworks and others. The provider batch APIs aren't available through these. For anything else, a custom provider is one async method. [Providers guide](docs/guides/providers.md)

## Using it with Claude Code

Accrue has a `/accrue` skill for [Claude Code](https://claude.ai/claude-code). Describe the job and it designs the fields, tries them on a few rows, estimates the cost and writes the script for you to review and run. Install it in the project you're working in:

```
/plugin install accrue --marketplace matt-house-e/accrue
```

For other agents, or without the plugin: `npx skills add matt-house-e/accrue --skill accrue`.

```
> /accrue
> I have 500 companies in accounts.csv, I need to qualify them for ICP fit.
  Try it on 5 rows first and show me the results.
```

See [Using the accrue skill](docs/getting-started/claude-code-skill.md).

## Why Accrue

There are two usual ways to do this job. You can write a loop over an LLM SDK, or you can use a platform like Clay. A loop leaves you to build retries, rate limits, caching, progress and crash recovery, and to do it again for the next job. A platform does that for you, but you pay a monthly plan plus credits for each run, your pipeline lives in their UI rather than your repo, and your data goes through them.

Accrue sits between the two: a library that does the plumbing, runs on your own API keys, and keeps the pipeline in your code.

| | Loop over an SDK | Accrue | Clay |
|---|---|---|---|
| **Multi-step** | Wire it up yourself | Steps with dependencies, run in parallel | Columns in a table UI |
| **Caching** | Build it yourself | Built in, invalidated when a prompt changes | Managed by the platform |
| **Crash recovery** | Start over | Resumes from the last finished row | Managed by the platform |
| **Changing a prompt** | Re-run everything | Re-runs only the affected step and rows | Re-run the column |
| **Cost** | API costs | API costs | Monthly plan, credits and per-run actions |
| **Version control** | Yes | Yes | No |

## Why not a loop or an agent script?

A coding agent will write you a loop over the OpenAI SDK in a minute, and for a one-off job of 50 rows that's fine. The trouble starts when the job comes back: new rows next month, a tweaked prompt, a cheaper model, someone asking why row 212 says what it says. Each time the agent writes a slightly different script, so the results don't line up and nothing carries over.

With accrue the job is a definition, not a script: your fields, prompts and steps in one short Python file that lives in git. Run it again and you get the same columns with the same types, and the framework around it does the rest.

- You know the cost before you run. `pipeline.plan(df, sample_size=3)` runs a few rows for real, shows you the prompt and schema it will send, and estimates the tokens for the full run. `run(..., confirm=True)` does the same and asks before going on.
- The output has a fixed shape. Field specs (prompt, type, enum, examples) become a strict schema, so every run fills the same typed columns instead of whatever the model felt like returning.
- Re-runs only redo what changed. Results are cached against the row and the prompt, so new rows or an edited prompt cost only what's new. A crashed run picks up where it stopped, and `retry_failed()` re-runs just the rows that errored.
- Batch pricing is one flag. `LLMStep(batch=True)` sends rows through the OpenAI and Anthropic batch APIs at about half price.
- Runs can be compared. `accrue.compare(before, after)` shows which rows and fields changed after a prompt or model change, and what it did to the cost, without needing labelled data.
- Repeated runs can be combined. For work someone will check, run it three times and `accrue.merge_runs()` gives one answer per cell plus the cells where the runs disagreed. That list is your review queue.
- Every run is recorded. `run_log=True` writes each row's outputs, errors and token use to a log you can open in Accrue Watch, so you can answer "why does row 212 say that?" weeks later.

## More examples

Read PDFs directly. Each row's documents go to the model as files, so there's no text extraction step (Anthropic models only for now):

```python
pipeline = Pipeline([
    LLMStep("read_contract",
        fields={
            "counterparty": "Name of the counterparty",
            "term_months": {"prompt": "Contract term in months", "type": "Number"},
            "governing_law": "Governing law of the contract",
        },
        model="claude-sonnet-5-5",
        attachments="documents",
    ),
])

result = pipeline.run([
    {"deal": "Acme", "documents": "contracts/acme.pdf"},
    {"deal": "Beta", "documents": ["contracts/beta.pdf", "contracts/beta-amendment.pdf"]},
])
```

Chain steps with `depends_on`, and use `web_search()` to ground answers in live data:

```python
from accrue import Pipeline, FunctionStep, LLMStep, web_search

pipeline = Pipeline([
    FunctionStep("research",
        fn=web_search("Research {company}: market position, competitors, recent news"),
        fields=["__web_context", "sources"],
    ),
    LLMStep("analyze",
        fields={
            "market_size": "Estimate TAM in billions USD",
            "competitors": {"prompt": "List top 3 competitors", "type": "List[String]"},
            "investment_thesis": "One-paragraph investment thesis",
        },
        depends_on=["research"],
    ),
])

result = pipeline.run(companies_df)
```

## Watch It Run

**Accrue Watch** ([accrue-ui](https://github.com/matt-house-e/accrue-ui)) is a local dashboard for a pipeline run. It shows rows against steps as a live grid, each cell's values and errors, failures grouped by cause, and cost by step. It reads the run log accrue writes, so there's nothing else to set up. The Overview tab is at the top of this page; this is the run grid:

<p align="center">
  <img src="https://raw.githubusercontent.com/matt-house-e/accrue/main/docs/assets/watch-datagrid.png" alt="Accrue Watch, run grid in data view: one produced field per step, with retrying and failed cells highlighted in place" width="100%">
  <br><sub><b>Run grid, data view</b>: one field per step, filling in as rows complete. Retries and failures show in place.</sub>
</p>

Turn on the run log, then open the dashboard:

```python
result = pipeline.run(companies_df, run_log=True)  # writes .accrue/runs/<run_id>.jsonl
```

```bash
pip install "accrue[ui]"   # the dashboard, alongside the engine
accrue watch               # opens the latest run in your browser
```

Add `--pipeline module:attr` to retry failed rows from the dashboard with one click. [Run log guide](docs/guides/run-log.md)

## Features

- **Multi-step pipelines.** Chain LLM steps and Python function steps. Accrue works out the order from their dependencies and runs independent steps in parallel. [Quickstart](docs/getting-started/quickstart.md)

- **Any of the main providers.** OpenAI, Anthropic (with automatic prompt caching) and Google are built in. Any OpenAI-compatible API works through `base_url`, and a custom provider is one async method. [Providers guide](docs/guides/providers.md)

- **Field specs.** Describe each output field with `prompt`, `type`, `format`, `enum`, `examples`, `bad_examples` and `default`. Accrue turns them into a structured-output schema and validates every answer. [Field specs guide](docs/guides/field-specifications.md)

- **Caching and checkpoints.** A local SQLite cache keyed on each row and prompt, cleared automatically when the prompt changes. Progress is saved after each step so a crashed run can resume. [Caching guide](docs/guides/caching.md)

- **Batch API.** `LLMStep(batch=True)` uses the OpenAI and Anthropic batch endpoints for about half the price. It works with the cache, splits large jobs and falls back to normal calls for rows that fail. [Batch guide](docs/guides/batch-api.md)

- **Web search.** `grounding=True` uses the provider's own web search (OpenAI, Anthropic, Google) and returns cited sources. `web_search()` runs the search as its own step, so the analysis can use batch pricing and cached research. [Web search guide](docs/guides/web-search.md)

- **Attachments.** `LLMStep(attachments="documents")` sends each row's PDFs to the model as documents, so you don't extract the text first. Cached by file content. Anthropic only for now. [Attachments guide](docs/guides/attachments.md)

- **Conditional steps.** `run_if` and `skip_if` decide per row whether a step runs. Skipped rows get defaults and cost nothing. [Conditional steps guide](docs/guides/conditional-steps.md)

- **Hooks.** Typed events at each stage of a run, for logging and monitoring. A failing hook never stops the pipeline. [Hooks guide](docs/guides/hooks.md)

- **Run logs.** `run(..., run_log=True)` writes the run as a JSONL file you can `tail -f`: each step and row with its status, errors and token use. [Run log guide](docs/guides/run-log.md)

- **Comparing runs.** `accrue.compare(result_a, result_b)` shows what changed between two runs, for example before and after a prompt tweak: changed rows, how much each field moved, and the cost difference. [Compare guide](docs/guides/compare.md)

- **Merging repeated runs.** `accrue.merge_runs([run_a, run_b, run_c])` combines several runs over the same rows into one answer per cell by majority vote. You get the agreement for each cell, the cells that need review, and the total cost. You can plug in your own rule per field, such as "prefer the run that quoted its source". [Merge guide](docs/guides/merge-runs.md)

- **`provider_kwargs`.** Pass provider-specific options, such as extended thinking, straight through without waiting for accrue to support them.

## How big a job?

Accrue is built for **100 to 50,000 rows**: too many to do by hand or one call at a time, too few to need big-data infrastructure. Cost depends mostly on the model and how much text each row carries, so run `pipeline.plan()` on your own data for a real estimate, and price it from the [model and price table](https://github.com/matt-house-e/accrue/blob/main/.claude/skills/accrue/references/providers.md). `batch=True` halves the API cost, and cached steps re-run in seconds.

## Documentation

| Section | Description |
|---------|-------------|
| [Getting Started](docs/getting-started/quickstart.md) | Installation, first pipeline, core concepts |
| [The accrue skill](docs/getting-started/claude-code-skill.md) | Installing the skill and building pipelines with `/accrue` |
| [Guides](docs/guides/) | Field specs, providers, caching, batch API, web search, attachments, hooks, run logs, errors, configuration |
| [Cookbook](docs/cookbook/) | End-to-end examples: [company enrichment](docs/cookbook/company-enrichment.md), [lead scoring](docs/cookbook/lead-scoring.md), [content analysis](docs/cookbook/content-analysis.md), [batch processing](docs/cookbook/batch-processing.md) |
| [API Reference](docs/reference/api.md) | Every public export |

## Contributing

```bash
git clone https://github.com/matt-house-e/accrue.git
cd accrue
pip install -e ".[dev]"
pytest
```

## License

MIT
