Как получить сводку текстовых строк с помощью LLM в пайплайне?
У вас отзывы клиентов, по записи на строку, и нужна короткая сводка. Ради одного вызова модели не хочется внедрять отдельный продукт для «ИИ-процессов», и шаг должен быть тестируемым.
Пайп ниже принимает записи и пишет обычный текст. Его провайдер — имитатор: он считает слова и не является языковой моделью. Он нужен, чтобы рецепт был повторяемым и бесплатным; о качестве какой-либо модели он ничего не говорит.
Пайп — шаг обработки данных с объявленными входами и выходами; пайплайн соединяет пайпы.
Что понадобится
- Команда
openflange, релиз v0.0.1:bashgo install github.com/openflange/openflange-go/cmd/openflange@v0.0.1 python3вPATH. Используется только стандартная библиотека: через pip ничего ставить не нужно.- Пустой каталог. Создайте в нём файлы, приведённые ниже, точно под этими именами и выполняйте все команды из этого каталога.
- Ни учётной записи, ни ключа. Данные не покидают вашу машину.
Шаги
1. Сохраните входной файл
Шесть отзывов с полями id и 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!"}Скопировано без изменений из examples/llm/feedback.ndjson в репозитории openflange-go.
2. Добавьте пайп для сводки
У выходного порта kind: text: пайп пишет текст UTF-8 по частям, а не записи. Манифест просит одно разрешение, subprocess, потому что запускает 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.Скопировано без изменений из examples/llm/llm-summarise/OPENFLANGE.md в репозитории openflange-go.
#!/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)Скопировано без изменений из examples/llm/llm-summarise/summarise.py в репозитории openflange-go.
3. Запустите
Записи на стандартном входе, сводка на стандартном выходе.
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 chunkПоследнее предложение печатает сам имитатор: модель не вызывалась.
4. Сводка только по части строк
Пайпы соединяются и в оболочке: std:filter оставляет две записи, где упомянуты возврат денег или опоздание, а пайп сводки читает его вывод.
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. Посмотрите, что будет без разрешения
Ничего не запускается, и раннер говорит, какого флага не хватает. Пайп с моделью, которому нужны сеть и ключ, будет отклонён точно так же, пока вы не выдадите каждое разрешение.
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. Протестируйте
Точный текст можно проверять только потому, что имитатор детерминирован. Второй тест показывает, что может проверять тест настоящей модели: длину и форму, а не формулировки.
# 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}Скопировано без изменений из examples/llm/llm-summarise/tests/llm-summarise.test.yaml в репозитории openflange-go.
2 feedback item(s). Most mentioned: late (2), arrived (1), box (1), broken (1), delivery (1). [mock summary - no model was called]Скопировано без изменений из examples/llm/llm-summarise/tests/expected.txt в репозитории openflange-go.
0 feedback item(s). [mock summary - no model was called]Скопировано без изменений из examples/llm/llm-summarise/tests/expected-empty.txt в репозитории openflange-go.
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)Настоящая модель: для этой страницы не запускалась
Настоящая модель: для этой страницы не запускалась
В репозитории есть вариант с теми же портами, работающий через Anthropic Messages API, — examples/llm/llm-summarise-anthropic, и вариант для локальной модели под Ollama. Ни один из них для этой страницы не запускался: платный API не вызывался и ключ не использовался, поэтому вывода нет. Репозиторий говорит то же самое о собственной сборке.
Команда ниже взята из README этого примера. Она отправляет провайдеру текст каждой записи, стоит денег и требует четырёх разрешений, одно из которых — на секрет с ключом:
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.ndjsonСкопировано без изменений из examples/llm/llm-summarise-anthropic/README.md в репозитории openflange-go.
Заменить имитатор на этот пайп — значит изменить одну ссылку на пайп: порты те же, отличаются только разрешения.
Ограничения
- Имитатор — не модель. Его вывод — подсчёт слов, и качество сводки здесь ничем не измеряется.
- У пайпа область действия «набор данных»: он читает все записи до первого слова на выходе и отправляет их одним запросом. Вход, который не помещается в контекстное окно модели, не разбивается; сводки по частям (map-reduce) здесь нет.
- С настоящим провайдером текст записей покидает вашу машину, а каждый запуск оплачивается. Прочитайте разрешения
remoteDataиsecretsпайпа, прежде чем их выдавать. - Настоящая модель не детерминирована. Тесты могут проверять структуру (длину, шаблон, схему), но не текст.
- Чтобы проверять структурированный вывод модели, поставьте за ней
std:validate-schemaи направьте несоответствующее вrejected.
Связанные страницы
- Стандартные пайпы в этом рецепте:
std:filter - Концепции, на которых он построен: Разрешения, Потоки
- Собираете это с помощью ИИ-агента? Дайте ему руководство для агентов: правила, раскладку файлов и команды, которыми он проверит собственную работу.
Все команды на этой странице выполнены в Linux с openflange 0.0.1 (go1.27.1 linux/amd64), собранным из коммита 11cf8cc5378d70858724b16aa937d7f3b98c085d репозитория openflange-go. Файлы и записанный вывод хранятся в репозитории сайта в каталоге sites/dev/test/fixtures/recipes/summarise-with-llm/, и тест побайтно сравнивает с ними эту страницу.