Files
pipewright/docs/agents.md
T

8.1 KiB

Authoring and debugging pipelines as an agent

pipewright is designed to be driven by a coding agent through the CLI (or the same operations over MCP: pw mcp). Use --json on every command; outputs are stable objects. Exit codes: 0 ok, 1 check/patch errors or a failed run, 2 usage/config error (with {"error": ...} in JSON mode).

1. Learn the vocabulary

pw nodes list --json                      # [{type, kind, summary}]
pw nodes describe llm.label --json        # inputs/outputs (+ item kinds), params_schema,
                                          # resources, cost_hint, example, example_yaml, example_python
pw patch --schema                         # JSON schema of graph patch ops

Prefer starting from a node's example and changing values, not writing params from scratch. Kinds you will meet: source, map, flatmap, filter (out/rejected), route (one port per route + default), join, retry, review (approved/rejected), sink.

2. Write the graph

Write Python with the builder (best for larger graphs) or YAML (best for patching). Reference upstream outputs as node (= node.out) or node.port.

from pipewright import Graph
g = Graph("my-pipeline")
src = g.add("records", "source.file", path="data/records.jsonl", kind="record")
lab = g.add("labels", "label.expr", input=src, labels={"long": "len(payload.text) > 500"})
g.add("export", "sink.jsonl", input=lab, path="out/labelled.jsonl")
graph = g

pw convert graph.py graph.yaml writes the file form. Model, sandbox and harness names (model: labeler, pool: docker, harness: mini) must exist in the project file (pipewright.yaml at or above the graph). For development point aliases at the fake provider: it returns schema-conforming JSON for structured requests, supports regex rules, scripted responses (script: module:function) and injected failures.

3. Check until clean

pw check graph.yaml --json

Each diagnostic: {level, code, node, port, message, hint}. Fix all errors. Codes:

code meaning usual fix
PW000 invalid node id no . in ids
PW001 unknown node type use the hint (closest match) or pw nodes list
PW002 invalid params (schema or semantic: expressions, templates, inner node types) compare with pw nodes describe
PW003 input refers to an unknown node fix the reference
PW004 unknown output port on the upstream node ports are in the hint
PW005 unknown input port / inputs on a source
PW006 required input not connected
PW007 item kind mismatch on an edge connect another port or add a converting map.expr (kind:)
PW008 cycle use retry.loop (bounded) or source.prior_run (across runs)
PW009 unconnected outputs (warning/info) add a sink, or ignore while debugging
PW011 missing model alias / sandbox pool / harness add it to pipewright.yaml or fix the name
PW012 project problem (unknown provider type, secret unavailable)
PW014 budget estimate (info) / estimate exceeds budget (warning) preview first, or raise budgets
PW016 plugin module failed to import

Expressions are Python syntax over payload, labels, key, kind, id, item; dict keys read as attributes and missing keys are None. Helpers: re, re_count, re_find, words, lines, mean, median, get, coalesce, json, len, min, max, sum, any, all, sorted. Templates: {{ expr }}.

4. Edit with patches

pw patch graph.yaml '[{"op": "add_node", "id": "summ", "type": "llm.generate",
  "inputs": {"in": "labels"}, "params": {"model": "labeler", "prompt": "Summarize: {{ payload.text }}",
  "output_field": "summary"}}, {"op": "connect", "from": "summ", "to": "export.in"},
  {"op": "disconnect", "from": "labels", "to": "export.in"}]' --json

The file is written only if the patched graph has no errors (written: true); otherwise you get the diagnostics and the file is untouched. --dry-run returns the patched graph without writing. Ops: add_node, remove_node (rewire: true connects its inputs to its consumers), rename_node, connect, disconnect, set_param (dotted path, or unset: true), set_node (type/timeout/retries/description).

5. Preview small, then run

pw preview graph.yaml --upto labels -n 3 --json      # items that came out of `labels`
pw run graph.yaml --limit 20 --json                   # first 20 items per source
pw run graph.yaml --json                              # everything; reuses all previous results

Previews and limited runs are memoized too, so the full run does not redo them. After editing one node, re-running recomputes only that node (and downstream items whose content changed). --force NODE ignores the memo for a node; --retry-errors recomputes memoized node errors with fresh model samples.

6. Debug

pw funnel graph.yaml --json            # nodes: {out: {port: n}, events: {ok, cached, error:<cat>, pending, parked}}
                                       # edges: [{from, to, items}]
pw status graph.yaml --json            # per-node in/ok/cached/errors/running/pending/parked, usage, budget, errors
pw items graph.yaml NODE --port rejected -n 5 --json     # what a filter dropped
pw items graph.yaml NODE --errors --json                  # failures + their input items
pw items graph.yaml NODE --sample -n 5 --full --json      # random sample, untruncated
pw lineage graph.yaml ITEM_ID_PREFIX --json               # which node produced what from what
pw report graph.yaml                                       # HTML for a human

Reading error categories: provider / infra are transient (rate limits, flaky sandboxes) and are retried automatically on the next pw run — do not change the graph for them unless they persist. node errors are about the item or the node's logic (bad LLM output, a failing expression) — look at pw items --errors.

Item counts that look wrong are usually a filter/route expression: check pw items NODE --port rejected / the route's other port, and remember missing keys are None (so labels.score > 0.5 on an item without score raises a node error; write (labels.score or 0) > 0.5).

7. Human review and loops

review.manual parks items (pw review graph.yaml NODE lists them; --approve ID… / --reject ID… records decisions; the next run moves them on). auto_approve / auto_reject expressions skip the human for clear cases. Use retry.loop for validate → fix → validate with a hard max_rounds.

8. Build on earlier results

  • Find what you want to reuse: pw query graph.py --of build --node bucket --port too_easy --where "labels.pass_rate >= 0.75"; the output ends with the equivalent store.query node, ready to paste into a new graph.
  • To consume another graph continuously, import it instead of copying data: up = g.import_graph("build", "graph_build.py"), then input=up.node("bucket").port("too_easy"). pw check validates the alias, node, port and item kind. Re-running only processes upstream items that are new.
  • Feedback across runs: g.import_graph("prev", "self") reads this graph's previous run (e.g. route failures to a port and feed it back into the generator) — no cycle needed.
  • Trace items: pw lineage graph.py ITEM --roots (where a variant came from), --descendants (everything derived from an item, across graphs).

9. Scale out

  • Sandboxes on remote machines: define a host pool under hosts: and set hosts: <pool> on a docker sandbox pool with the per-sandbox cpus/memory/requires. Check with pw hosts list; clean up with pw hosts down (and pw hosts orphans after a crash).
  • Many items: run pw run graph.py --shard I/N --group G in N processes, then one pw run graph.py to replay and write sinks; pw funnel graph.py --group G for totals.

Rules of thumb

  • Keep graphs generic; put domain logic in node types (a plugin pack) rather than in long expressions.
  • Bump a node type's version when you change its behaviour, so memoized results are invalidated.
  • Never put secrets in project files; use {env: VAR} or {file: path, var: KEY}.
  • Use flatmap.repeat + agent.run + join.group for k rollouts and pass rates.