How do I summarise rows of text with an LLM in a pipeline?
You have customer feedback, one record per line, and you want a short summary. You do not want to adopt a separate "AI workflow" product for one model call, and you want the step to be testable.
The pipe below takes records and writes plain text. Its provider is a mock: it counts words and is not a language model. It is here so that the recipe is repeatable and free; it says nothing about the quality of any model.
A pipe is a data-processing step with declared inputs and outputs; a pipeline connects pipes.
What you need
- The
openflangecommand, release v0.0.1:bashgo install github.com/openflange/openflange-go/cmd/openflange@v0.0.1 python3onPATH. Only the standard library is used: nothing to install with pip.- An empty directory. Create the files below in it under exactly these names and run every command from that directory.
- No account and no key. Nothing leaves your machine.
Steps
1. Save the input file
Six feedback records with an id and a text.
{"id":1,"text":"Great service, I love the new dashboard!"}
{"id":2,"text":"The delivery was late and the box arrived broken."}
{"id":3,"text":"It arrived on Tuesday."}
{"id":4,"text":"Fast delivery, but the support was terrible."}
{"id":5,"text":"Not good at all, I want a refund."}
{"id":6,"text":"Excellent quality, fast and friendly support. Thank you!"}Copied without changes from examples/llm/feedback.ndjson in the openflange-go repository.
2. Add the summariser pipe
The output port has kind: text: the pipe writes UTF-8 text piece by piece instead of records. The manifest asks for one permission, subprocess, because it starts python3.
---
spec: openflange.org/pipe/v0.1
id: llm-summarise
version: 0.1.0
title: LLM summarise (mock provider)
description: Summarises feedback records as streamed plain text. Ships with a deterministic mock provider.
license: Apache-2.0
keywords: [llm, ai, summarisation, text, streaming, mock, example]
maturity: experimental
scope: dataset
inputs:
feedback:
description: 'Feedback records: {"id", "text"}; `text` must be a string.'
outputs:
summary:
kind: text
description: The summary as UTF-8 text, streamed as it is generated.
implementation:
type: script
language: python
path: summarise.py
usage: true
permissions:
subprocess: true
---
# LLM summarise (mock provider)
Implements the [OpenFlange](https://openflange.org/) specification.
Generative AI as an ordinary pipe: records in, **text out** (`kind: text`,
`text/plain; charset=utf-8`), written piece by piece as it is generated. See
[../README.md](../README.md).
- The provider in [`summarise.py`](summarise.py) is a **mock**: deterministic,
offline, free. It counts words; it is not a language model. Because it is
deterministic its tests can compare text exactly — a real model's cannot.
- Dataset scope: a summary needs every record before the first word.
- A record without a string `text` fails the run (`E_RUNTIME`).
- **Usage** (counts only; texts are never logged) is reported to the runner's
usage endpoint — the manifest says `usage: true` — and appears under
`usage` in the run report. Without the endpoint it is one `usage {...}`
line on stderr.
- Real providers with this same contract: `../llm-summarise-anthropic`
(opt-in, costs money, sends data) and `../llm-summarise-ollama` (local).
Permissions: `subprocess` (it starts `python3`). No network, no secrets.Copied without changes from examples/llm/llm-summarise/OPENFLANGE.md in the openflange-go repository.
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""llm-summarise — summarises feedback records as streamed text.
NDJSON records in; plain UTF-8 text out, written piece by piece as the
"model" produces it. The provider here is a deterministic MOCK (no network,
no key, no cost). The real-provider variants in ../llm-summarise-anthropic
and ../llm-summarise-ollama have the same contract.
"""
import json
import os
import sys
from collections import Counter
STOPWORDS = {"the", "and", "was", "but", "a", "an", "i", "it", "at", "all", "to", "of", "on", "in", "is", "my", "we", "for"}
def complete(texts):
"""MOCK provider: yields the summary in small pieces, like a streaming model."""
words = Counter()
for text in texts:
for word in "".join(c.lower() if c.isalnum() else " " for c in text).split():
if word not in STOPWORDS and len(word) > 2:
words[word] += 1
top = sorted(words.items(), key=lambda kv: (-kv[1], kv[0]))[:5]
summary = f"{len(texts)} feedback item(s)."
if top:
summary += " Most mentioned: " + ", ".join(f"{w} ({n})" for w, n in top) + "."
summary += " [mock summary - no model was called]\n"
for piece in summary.split(" "):
yield piece if piece.endswith("\n") else piece + " "
def report_usage(usage):
"""Reports usage counters to the runner (CLI protocol, usage endpoint).
Counts and labels only — never prompts, replies or records. The runner
offers the endpoint because the manifest says `usage: true`; the counters
then appear under `usage` in the run report. Without the endpoint (run by
hand, or by a runner that does not offer it) the fallback is one
`usage {...}` line on stderr.
"""
try:
import urllib.request
with open(os.environ["OPENFLANGE_CONFIG"], encoding="utf-8") as f:
cfg = json.load(f)
request = urllib.request.Request(
cfg["usage"]["url"], data=json.dumps(usage).encode(), method="POST",
headers={"Authorization": "Bearer " + cfg["token"], "Content-Type": "application/json"})
urllib.request.urlopen(request, timeout=5).close()
except (KeyError, OSError, ValueError):
print("usage " + json.dumps(usage, separators=(",", ":")), file=sys.stderr)
def main() -> int:
texts = []
for n, line in enumerate(sys.stdin, 1): # a summary needs every record
record = json.loads(line)
text = record.get("text") if isinstance(record, dict) else None
if not isinstance(text, str):
print(f"llm-summarise: item {n} has no text", file=sys.stderr)
return 1
texts.append(text)
usage = {"provider": "mock", "model": "mock-summary-1", "requests": 1,
"inputTokens": sum(len(t.split()) for t in texts), "outputTokens": 0}
for piece in complete(texts):
sys.stdout.write(piece)
sys.stdout.flush() # text streaming: piece by piece
usage["outputTokens"] += 1
report_usage(usage) # counts only — never the texts
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except BrokenPipeError:
sys.exit(0)Copied without changes from examples/llm/llm-summarise/summarise.py in the openflange-go repository.
3. Run it
Records on standard input, the summary on standard output.
openflange run ./llm-summarise --grant subprocess < feedback.ndjson6 feedback item(s). Most mentioned: arrived (2), delivery (2), fast (2), support (2), box (1). [mock summary - no model was called]
completed in 69ms — summary: 1 chunkThe last sentence is printed by the mock itself: no model was called.
4. Summarise only some rows
Pipes compose in the shell too: std:filter keeps the two records that mention a refund or a delay, and the summariser reads its output.
openflange run std:filter --quiet --param 'expr="refund" in item["text"] or "late" in item["text"]' < feedback.ndjson | openflange run ./llm-summarise --grant subprocess --quiet2 feedback item(s). Most mentioned: arrived (1), box (1), broken (1), delivery (1), good (1). [mock summary - no model was called]5. See what happens without the grant
Nothing runs, and the runner says which flag is missing. A model pipe that needs the network and a key is refused the same way until you grant each of them.
openflange run ./llm-summarise < feedback.ndjsonE_PERMISSION: node "llm-summarise": pipe "llm-summarise" needs permissions that were not granted: subprocess (llm-summarise/OPENFLANGE.md, at nodes.llm-summarise)
hint: grant it with `--grant subprocess` (or `grants:` on the node), or run with `--trusted`
E_PERMISSION: node "llm-summarise": pipe "llm-summarise" runs a subprocess, which was not granted (llm-summarise/OPENFLANGE.md, at nodes.llm-summarise)
hint: grant it with `--grant subprocess` (or `grants: {subprocess: true}` on the node), or run with `--trusted`
2 errors in 1 file6. Test it
Exact text can be asserted only because the mock is deterministic. The second test shows what a test of a real model can assert: length and shape, not wording.
# requires: python3
spec: openflange.org/test/v0.1
tests:
# Exact text can be asserted only because the mock provider is deterministic.
- name: the mock summary is deterministic text
grants: {subprocess: true}
inputs:
feedback:
values:
- {id: 2, text: "The delivery was late and the box arrived broken."}
- {id: 7, text: "My order was late."}
expect:
outputs:
summary: {file: expected.txt}
# What a test of a REAL model can assert: structure, not wording. The
# summary is some text of a sensible length that states how many items it
# covers (minLength, maxLength count code points; pattern is unanchored).
- name: the summary has the expected shape (structural text assertions)
grants: {subprocess: true}
inputs:
feedback:
values:
- {id: 2, text: "The delivery was late and the box arrived broken."}
- {id: 7, text: "My order was late."}
expect:
outputs:
summary:
minLength: 20
maxLength: 2000
pattern: '^2 feedback item\(s\)\.'
- name: no records still gives a summary
grants: {subprocess: true}
inputs:
feedback: {values: []}
expect:
outputs:
summary: {file: expected-empty.txt}
- name: a record without text fails the run
grants: {subprocess: true}
inputs:
feedback: {values: [{id: 1}]}
expect:
status: failed
error: {code: E_RUNTIME}
- name: without the subprocess grant the pipe is refused
inputs:
feedback: {values: []}
expect:
status: failed
error: {code: E_PERMISSION}Copied without changes from examples/llm/llm-summarise/tests/llm-summarise.test.yaml in the openflange-go repository.
2 feedback item(s). Most mentioned: late (2), arrived (1), box (1), broken (1), delivery (1). [mock summary - no model was called]Copied without changes from examples/llm/llm-summarise/tests/expected.txt in the openflange-go repository.
0 feedback item(s). [mock summary - no model was called]Copied without changes from examples/llm/llm-summarise/tests/expected-empty.txt in the openflange-go repository.
openflange test ./llm-summarisellm-summarise/tests/llm-summarise.test.yaml
ok the mock summary is deterministic text
ok the summary has the expected shape (structural text assertions)
ok no records still gives a summary
ok a record without text fails the run
ok without the subprocess grant the pipe is refused
ok 5 tests passed in 1 file (235ms)A real model: not run for this page
A real model: not run for this page
The repository has a variant with the same ports backed by the Anthropic Messages API, examples/llm/llm-summarise-anthropic, and one for a local model under Ollama. Neither was run for this page: no paid API was called and no key was used, so no output is shown. The repository states the same about its own build.
The command below is quoted from that README. It sends the text of every record to the provider, costs money, and needs four grants, one of them for the secret that holds the key:
export ANTHROPIC_API_KEY=... # your own key; do not put it in a file in this repository
openflange run ./examples/llm/llm-summarise-anthropic --grant subprocess --grant network=api.anthropic.com:443 --grant remoteData=api.anthropic.com --grant secrets=ANTHROPIC_API_KEY < examples/llm/feedback.ndjsonCopied without changes from examples/llm/llm-summarise-anthropic/README.md in the openflange-go repository.
Swapping the mock for it is a change of one pipe reference: the ports are the same, only the permissions differ.
Limits
- The mock is not a model. Its output is a word count, and nothing here measures the quality of a summary.
- The pipe has dataset scope: it reads every record before the first word comes out, and sends them in one request. Input that exceeds the context window of a model is not split; there is no map-reduce summarisation here.
- With a real provider, record text leaves your machine and every run is billed. Read the
remoteDataandsecretspermissions of the pipe before granting them. - A real model is not deterministic. Tests can assert structure (length, a pattern, a schema), not the text.
- To check structured output of a model, put
std:validate-schemabehind it and route what does not match torejected.
Related pages
- Standard pipes used here:
std:filter - Concepts behind it: Permissions, Streams
- Building this with an AI agent? Give it the guide for agents: the rules, the file layout and the commands to check its own work.
Every command on this page was run on Linux with openflange 0.0.1 (go1.27.1 linux/amd64), built from openflange-go commit 11cf8cc5378d70858724b16aa937d7f3b98c085d. The files and the recorded output are kept in the site repository under sites/dev/test/fixtures/recipes/summarise-with-llm/, and a test compares this page with them byte for byte.