DataFlow Pipeline Code Generator
Goal
This skill is used when users provide:
- Target: What the pipeline should achieve
- Sample Data File: Path to a JSONL file containing 1-5 representative data samples
The skill must:
- Read and analyze the JSONL file at the provided path
- Infer data structure, field types, and content characteristics
- Determine task type based on file content (document processing, text transformation, multi-field composition)
- Select appropriate operators from preferred primitives
- Validate field dependencies
- Output intermediate operator decision summary
- Generate standard DataFlow pipeline code with
first_entry_file_name set to the user-provided file path
User Input Format
Users provide:
Target: [Clear task description]
Sample file: [Path to JSONL file, e.g., ./data/input.jsonl]
Important: The sample file is a JSONL file (one JSON object per line), not a JSON array.
Preferred Operator Strategy
Six Core Primitives (high-coverage operators for most data science tasks):
PromptedGenerator - Single-field LLM generation
FormatStrPromptedGenerator - Multi-field template generation
Text2MultiHopQAGenerator - Multi-hop QA pair construction
PromptedFilter - LLM-based quality filtering
GeneralFilter - Rule-based filtering
- KBC trio (always used together in order):
FileOrURLToMarkdownConverterFlash → KBCChunkGenerator → KBCTextCleaner
These are preferred primitives, not fixed workflows. They can be used repeatedly and combined flexibly.
Operator Selection Priority Rule (MANDATORY)
When a specialized operator exists for the task, it MUST be used over generic operators. Do NOT use PromptedGenerator to replicate functionality that a dedicated operator already provides.
Decision table (check in order, use the first match):
| Task / Scenario |
Required Operator |
Do NOT use |
| Generate QA pairs from text |
Text2MultiHopQAGenerator |
PromptedGenerator with QA prompt |
| Convert file path / URL to text |
KBC trio (FileOrURLToMarkdownConverterFlash → KBCChunkGenerator → KBCTextCleaner) |
PromptedGenerator to summarize files |
| Score / evaluate using multiple fields |
FormatStrPromptedGenerator + GeneralFilter |
PromptedFilter (single input_key only) |
| Filter by deterministic rule on existing fields |
GeneralFilter |
PromptedFilter |
| Generate new content from a single field |
PromptedGenerator |
— |
| Generate new content from multiple fields |
FormatStrPromptedGenerator |
Multiple PromptedGenerator steps |
Key principle: PromptedGenerator is the fallback for generic single-field generation. If the target mentions "QA", "question-answer", "问答" — always reach for Text2MultiHopQAGenerator first.
Field Flow Rules (MANDATORY)
- Inspect record content first: Read representative records and identify the
semantic role and fitness of their content; field names and presence alone do
not establish that content is suitable for the target.
- Design from the target contract: Select source and generated fields based
on the content required by the target, including improved semantic
counterparts when existing content does not fit that contract.
- Keep execution ordered: Every field consumed by an operator must be
available from the input or produced by an earlier operator.
- Never reference before creation: Create a generated field before any
downstream operator evaluates, filters, or transforms it.
✗ WRONG: Filter by "quality_score" before generating it
✓ CORRECT: Generate "quality_score" first, then filter by it
Grounded Field Generation Pattern (RECOMMENDED)
When constructing improved training fields from records that already contain a
source instruction, answer, implementation, or other target-bearing content,
ground each generated stage in the source semantics. A useful reference flow is:
source content + source answer
-> generate an improved question/instruction
improved question/instruction + source answer
-> generate or revise the answer
improved question/instruction + source answer + generated answer
-> evaluate semantic consistency and target fitness
Adapt the field names and operators to the task. This is a reference pattern,
not a requirement to generate every role on every dataset. Its purpose is to
prevent an answer generator from seeing only a rewritten question and freely
inventing behavior that is unsupported by the source answer. The final quality
evaluation should reject generated answers that omit supported behavior or add
unsupported contracts, constraints, edge cases, exception handling, or other
observable semantics, even when the generated question and answer are mutually
consistent.
Before expensive LLM generation, prefer multiple applicable non-LLM filtering
operators when the source pool is large enough to support meaningful attrition.
Use deterministic checks for defects that can be established reliably, such as
parseability, required content shape, empty or truncated content, duplicates,
unsafe patterns, invalid values, and task-specific structural invariants. Keep
these filters content-aware and avoid treating familiar field names or mere
field presence as evidence of quality. The goal is to reduce generation load
while retaining enough valid and diverse source records for the downstream
target.
For vertical domains whose target capability inherently requires reasoning,
the pipeline MUST use operators to distinguish records that contain suitable
chain-of-thought (CoT) content from those that do not. For a record without
suitable CoT, assess the problem's difficulty and either retain it by routing
that branch through an appropriate reasoning-generation operator to construct
CoT, or filter it out when generating useful reasoning is unwarranted or
unreliable.
Prompted Operator Usage Policy (MANDATORY)
- Don't mechanically create one prompted operator per tiny requirement. If one operator can handle multiple related transformations, prefer that over splitting.
- Multiple prompted operators are allowed when the task genuinely requires distinct semantic transformations. If using multiple, justify each step's role, input field, and output field.
KBC Usage Constraint (MANDATORY)
The KBC trio must always be used in this exact order:
FileOrURLToMarkdownConverterFlash — converts file path / URL → Markdown text (field: text_path)
KBCChunkGenerator — splits Markdown into chunks (field: raw_chunk)
KBCTextCleaner — LLM-cleans each chunk (field: cleaned_chunk)
Rules:
- All three steps are required; never skip one.
- Input to step 1 must be a file path or URL, never plain text content.
- Each step's
output_key becomes the next step's input_key.
- Use the default field names (
text_path, raw_chunk, cleaned_chunk) unless explicitly requested otherwise.
GeneralFilter Field Safety Rule (MANDATORY)
GeneralFilter lambda rules must ONLY reference fields that exist in sample data or are produced by upstream steps.
Multi-Field Filtering Pattern (MANDATORY)
PromptedFilter only accepts a single input_key. For multi-field evaluation (e.g., scoring QA pairs), use FormatStrPromptedGenerator to score + GeneralFilter to filter.
Important caveat for Text2MultiHopQAGenerator output: The QA_pairs column is a nested list of dicts, not separate question/answer columns. You cannot directly pass question or answer as kwargs to FormatStrPromptedGenerator after Text2MultiHopQAGenerator. To score or filter individual QA pairs, use post-processing (explode the list into rows, then optionally score/filter in a second pipeline or in Python code).
Output Contract (MANDATORY)
Two-stage output required:
Stage 1: Intermediate Operator Decision (JSON)
Output this first:
{
"ops": ["OperatorA", "OperatorB", "OperatorC"],
"field_flow": "field_a -> field_b -> field_c",
"reason": "Why this ordered operator chain satisfies the target, how field dependencies are satisfied, and why prompted operators are or are not used."
}
Stage 2: Complete Response (5 sections)
- Field Mapping: Map sample fields to semantic roles, identify fields to generate
- Ordered Operator List: List operators in execution order with justification
- Reasoning Summary: Explain operator selection, field flow, why this design
- Complete Standard Pipeline Code: Full executable Python following repository style
- Adjustable Parameters / Caveats: Tunable parameters, fallback strategies, debugging tips
Standard Code Generation Rule (MANDATORY)
All generated Python code must follow the standard pipeline organization shown in the examples/ folder of this skill package.
Input Data Format:
first_entry_file_name MUST be set to the user-provided file path (the JSONL sample file)
- File extension must be
.jsonl (one JSON object per line, NOT an array)
- DO NOT create new file paths - use the exact path the user provided
Required structure: __init__ (storage + llm_serving + operators) → forward (sequential operator.run(storage=self.storage.step(), ...)) → if __name__ == "__main__" entry point.
DO NOT: generate custom runtime executors, forward(plan) style frameworks, or dynamic dispatch engines.
Operator Parameter Signature Rule (MANDATORY)
Use repository-valid constructor/run signatures only. Never invent parameter names.
Base Components
FileStorage
FileStorage(
first_entry_file_name="...jsonl",
cache_path="./cache",
file_name_prefix="dataflow_cache_step",
cache_type="jsonl"
)
APILLMServing_request
APILLMServing_request(
api_url="...",
key_name_of_api_key="DF_API_KEY", # defaults to DF_API_KEY; set to e.g. "OPENAI_API_KEY" if needed
model_name="gpt-4o",
max_workers=10
)
Six Core Operators: Signatures + Key Requirements
1) PromptedGenerator
- Constructor:
PromptedGenerator(llm_serving, system_prompt="You are a helpful agent.", user_prompt="", json_schema=None)
- Run:
run(storage=self.storage.step(), input_key="raw_content", output_key="generated_content")
input_key column must exist. Generated rows written to output_key.
2) FormatStrPromptedGenerator
- Constructor:
FormatStrPromptedGenerator(llm_serving, system_prompt="You are a helpful agent.", prompt_template=FormatStrPrompt(...), json_schema=None)
- Run:
run(storage=self.storage.step(), output_key="generated_content", **input_keys)
**input_keys: each kwarg maps a template variable name (key) to a dataframe column name (value). Internally does row[input_keys[key]] per row, then prompt_template.build_prompt(need_fields, **key_dict).
- Kwarg keys must match
{placeholder} names in FormatStrPrompt.f_str_template. Kwarg values must be existing dataframe columns.
prompt_template cannot be None (raises ValueError). Must pass an instantiated FormatStrPrompt(f_str_template="...").
- Import:
from dataflow.prompts.core_text import FormatStrPrompt
3) Text2MultiHopQAGenerator
- Constructor:
Text2MultiHopQAGenerator(llm_serving=self.llm_serving, seed=0, lang="en", prompt_template=None, num_q=5)
llm_serving — LLM serving instance (required)
seed (int, default 0) — random seed for reproducibility
lang (str, default "en") — language for generation prompt; controls sentence splitting ("." for "en", "。" for "zh")
prompt_template — custom DIYPromptABC instance; pass None to use default Text2MultiHopQAGeneratorPrompt
num_q (int, default 5) — maximum number of QA pairs to keep per input row (truncates the generated list; actual generation count depends on sentence triples in the text)
- Run:
run(storage, input_key="cleaned_chunk", output_key="QA_pairs", output_meta_key="QA_metadata")
input_key must exist (cleaned text chunk column)
output_key — column containing a nested list of QA dicts per row. Each dict has keys: question (str), reasoning_steps (list of {step: str}), answer (str), supporting_facts (list of str), type (str)
output_meta_key — column containing metadata dict per row with keys: source, timestamp, complexity
- Output column named by
output_key / output_meta_key must NOT pre-exist.
- Each input row produces one row with a nested list in the
output_key column. The list items are dicts — question, answer, etc. are NOT separate dataframe columns. Downstream operators like FormatStrPromptedGenerator cannot directly reference question or answer as column names. To use individual QA pairs downstream, you must post-process (explode the list into separate rows) outside the operator chain.
- Input text constraints (texts failing these checks produce empty
qa_pairs: []):
- Length: 100–200,000 characters
- Must contain at least 2 sentences (2+
. or 2+ 。)
- Special character ratio must be ≤ 30%
4) PromptedFilter
- Constructor:
PromptedFilter(llm_serving, system_prompt="...", min_score=1, max_score=5)
- Run:
run(storage=self.storage.step(), input_key="raw_content", output_key="eval")
input_key must exist. output_key is numeric score column; rows outside [min_score, max_score] are filtered out.
5) GeneralFilter
- Constructor:
GeneralFilter([lambda df: df["score"] >= 4, ...])
- Run:
run(storage=self.storage.step())
- Each rule must return boolean
pd.Series. Referenced fields must already exist.
6) KBC Trio (always used in this order)
Step 1 — FileOrURLToMarkdownConverterFlash
- Constructor:
FileOrURLToMarkdownConverterFlash(intermediate_dir="../example_data/KBCleaningPipeline/flash/", mineru_model_path="opendatalab/MinerU2.5-2509-1.2B", batch_size=4, replicas=1, num_gpus_per_replica=1.0, engine_gpu_util_rate_to_ray_cap=0.9)
- Does NOT take
llm_serving — this operator has no LLM dependency.
mineru_model_path is required — passing None raises ValueError. Use a HuggingFace model ID or local path.
- Run:
run(storage=self.storage.step(), input_key="source", output_key="text_path")
- Input must be a file path or URL (
.pdf, .png, .jpg, .jpeg, .webp, .gif, .html, .xml, .txt, .md).
Step 2 — KBCChunkGenerator
- Constructor:
KBCChunkGenerator(chunk_size=512, chunk_overlap=50, split_method="token", min_tokens_per_chunk=100, tokenizer_name="bert-base-uncased")
- Run:
run(storage=self.storage.step(), input_key="text_path", output_key="raw_chunk")
split_method options: "token", "sentence", "semantic", "recursive".
Step 3 — KBCTextCleaner
- Constructor:
KBCTextCleaner(llm_serving, lang="en")
- Run:
run(storage=self.storage.step(), input_key="raw_chunk", output_key="cleaned_chunk")
- LLM-cleans each chunk; output is ready for downstream QA generation.
Correct Import Paths (MANDATORY)
# Base components
from dataflow.utils.storage import FileStorage
from dataflow.serving import APILLMServing_request
# Operators
from dataflow.operators.core_text import PromptedGenerator, FormatStrPromptedGenerator, Text2MultiHopQAGenerator, PromptedFilter, GeneralFilter
from dataflow.operators.knowledge_cleaning import FileOrURLToMarkdownConverterFlash, KBCChunkGenerator, KBCTextCleaner
Extended Operator Reference: core_text Skill
The sibling skill core_text (located at ../core_text/) provides detailed per-operator API documentation that supplements the summary signatures above.
Each operator directory contains:
SKILL.md — Full English reference: constructor signature, run() signature, execution logic, mandatory rules, return value semantics
SKILL_zh.md — Chinese translation of the reference
examples/good.md — Best-practice pipeline example
examples/bad.md — Common mistakes and failure cases
When to consult core_text:
- When generating pipeline code that uses an operator beyond the 6 core primitives (e.g.,
BenchAnswerGenerator, ChunkedPromptedGenerator, EmbeddingGenerator, RetrievalGenerator, RandomDomainKnowledgeRowGenerator)
- When you need to verify edge-case behavior, return value semantics, or error conditions for any operator
- When debugging generated pipeline code — the
bad.md examples document the most frequent mistakes
Note: The 6 core primitives documented above in "Operator Parameter Signature Rule" remain the primary reference for standard pipeline generation. The core_text skill provides deeper detail and covers additional operators not in the core set.
Generate Operators
Path: ../core_text/generate/
Available operator references (8 operators):
| Operator |
Subdirectory |
Description |
PromptedGenerator |
prompted-generator/ |
Single-field LLM generation — full execution logic, skip-falsy rules |
FormatStrPromptedGenerator |
format-str-prompted-generator/ |
Multi-field template generation — placeholder-to-column mapping details,@prompt_restrict validation |
Text2MultiHopQAGenerator |
text2multihopqa-generator/ |
Multi-hop QA pair construction — text filtering thresholds (100–200k chars), output structure, row-count behavior |
BenchAnswerGenerator |
bench-answer-generator/ |
Benchmark answer generation —eval_type variants, conditional field requirements |
ChunkedPromptedGenerator |
chunked-prompted-generator/ |
Long document chunk-by-chunk processing — token-based splitting, file I/O conventions |
EmbeddingGenerator |
embedding-generator/ |
Text vectorization — supported serving backends,/v1/embeddings endpoint usage |
RandomDomainKnowledgeRowGenerator |
random-domain-knowledge-row-generator/ |
Domain-specific row generation — seed dataframe requirements,generation_num constraints |
RetrievalGenerator |
retrieval-generator/ |
Async RAG generation —LightRAGServing.create() async initialization, await run() requirement |
Eval Operators
Path: ../core_text/eval/
Available operator references (5 operators):
| Operator |
Subdirectory |
Description |
BenchDatasetEvaluator |
bench-dataset-evaluator/ |
Benchmark answer comparison —match (math verification) and semantic (LLM-based) modes |
BenchDatasetEvaluatorQuestion |
bench-dataset-evaluator-question/ |
Extended benchmark evaluator — adds question context and subquestion support over BenchDatasetEvaluator |
PromptedEvaluator |
prompted-evaluator/ |
LLM-based row scoring — writes score into new column without removing rows |
Text2QASampleEvaluator |
text2qa-sample-evaluator/ |
QA pair quality evaluation — 4 dimensions, 8 output columns (grades + feedbacks per dimension) |
UnifiedBenchDatasetEvaluator |
unified-bench-dataset-evaluator/ |
Unified benchmark evaluation — 6 eval_type variants, writes 4 output columns |
Filter Operators
Path: ../core_text/filter/
Available operator references (3 operators):
| Operator |
Subdirectory |
Description |
GeneralFilter |
general-filter/ |
Rule-based row filtering — lambda conditions combined with AND, removes rows only, adds no new columns |
KCenterGreedyFilter |
kcentergreedy-filter/ |
Diversity-based downsampling — K-Center Greedy algorithm, requires pre-computed embedding vectors |
PromptedFilter |
prompted-filter/ |
LLM semantic filtering — internally uses PromptedEvaluator, retains rows with scores in [min_score, max_score] |
Refine Operators
Path: ../core_text/refine/
Available operator references (2 operators):
| Operator |
Subdirectory |
Description |
PandasOperator |
pandas-operator/ |
Custom DataFrame transformation — applies a sequential list of functions, no LLM calls |
PromptedRefiner |
prompted-refiner/ |
LLM text refinement — rewrites text in-place, overwrites original column with refined results |
Input File Content Analysis Rule (MANDATORY)
Analyze sample data content to determine task nature:
File path fields (e.g., pdf_path, image_path, doc_path):
- → KBC trio in order:
FileOrURLToMarkdownConverterFlash → KBCChunkGenerator → KBCTextCleaner (supports .pdf, .png, .jpg, .jpeg, .webp, .gif, .html, .xml, .txt, .md)
- → Document/file processing workflow
Plain text fields (e.g., text, content, review_text):
- → Use
PromptedGenerator, PromptedFilter, Text2MultiHopQAGenerator, FormatStrPromptedGenerator, GeneralFilter
- → Do NOT use KBC
Multiple semantic fields (e.g., instruction, output, question, answer):
- → Use
FormatStrPromptedGenerator for combining fields
- → Use
GeneralFilter for field-based rules
Examples
See examples/ folder for complete workflows:
examples/basic_generate_and_filter.md — PromptedGenerator + PromptedFilter (simplest pattern)
examples/multifield_scoring.md — FormatStrPromptedGenerator with multi-field scoring
examples/multi_stage_pipeline.md — Multiple PromptedGenerator stages + GeneralFilter
examples/kbc_pdf_to_qa.md — KBC trio (FileOrURLToMarkdownConverterFlash + KBCChunkGenerator + KBCTextCleaner) + Text2MultiHopQAGenerator + PromptedFilter (scores nested QA_pairs column per chunk)
examples/reasoning_math_pipeline.md — High-quality math reasoning workflow using native question screening/synthesis, difficulty and category evaluation, ReasoningAnswerGenerator, and format/length/ground-truth/ngram validation
examples/reasoning_general_pipeline.md — General or mixed-domain reasoning generation with reference-aware model judging and n-gram filtering
examples/reasoning_math_fusion_pipeline.md — Embedding-grounded sequential, parallel, and condition fusion for synthesizing harder math questions, followed by solvability evaluation
examples/reasoning_pretrain_pipeline.md — Math reasoning generation and filtering followed by explicit SFT-to-pretraining text conversion
examples/reasoning_diy_pipeline.md — Native reasoning operators with custom vertical-domain filter, synthesis, and answer prompt contracts
examples/reasoning_cpu_clean_pipeline.md — CPU-only format, mathematical ground-truth, and n-gram cleaning for existing reasoning answers
examples/agentic_rag_text_pipeline.md — Atomic and verified multi-hop QA over retrieved text, including grounding, shortcut, reasoning, and final-answer checks
examples/code_text_pipelines.md — Code-to-SFT and seed-to-code generation with quality scoring and sandbox execution, plus CPU code-text cleaning
examples/chemistry_smiles_text_pipeline.md — Chemistry-text SMILES extraction followed by molecular-equivalence evaluation
examples/function_call_text_pipeline.md — Scenario, task, function-schema, multi-turn tool-conversation synthesis and evaluation
examples/text2qa_pipeline.md — Diversity-aware text selection, QA generation, and multidimensional QA evaluation
examples/text2sql_text_pipelines.md — Executable Text-to-SQL generation, refinement, VectorSQL construction, CoT voting, and difficulty classification
examples/text_synthesis_and_quality_pipelines.md — Conversation, SFT, and PT text synthesis plus deterministic and learned quality-filtering chains
examples/text_benchmark_eval_pipelines.md — Direct and question-aware semantic or deterministic answer evaluation
These are strategy guidance, not templates to copy blindly. Generated code must follow standard pipeline structure.
1---2name: generating-dataflow-pipeline-33description: Reasoning-guided pipeline planner that generates standard DataFlow pipeline code4---5# DataFlow Pipeline Code Generator67## Goal89This skill is used when users provide:1011- **Target**: What the pipeline should achieve12- **Sample Data File**: Path to a JSONL file containing 1-5 representative data samples1314The skill must:15161. **Read and analyze the JSONL file** at the provided path172. Infer data structure, field types, and content characteristics183. Determine task type based on file content (document processing, text transformation, multi-field composition)194. Select appropriate operators from preferred primitives205. Validate field dependencies216. Output intermediate operator decision summary227. Generate standard DataFlow pipeline code with `first_entry_file_name` set to the user-provided file path2324## User Input Format2526Users provide:2728```29Target: [Clear task description]30Sample file: [Path to JSONL file, e.g., ./data/input.jsonl]31```3233**Important**: The sample file is a JSONL file (one JSON object per line), not a JSON array.3435## Preferred Operator Strategy3637**Six Core Primitives** (high-coverage operators for most data science tasks):38391. `PromptedGenerator` - Single-field LLM generation402. `FormatStrPromptedGenerator` - Multi-field template generation413. `Text2MultiHopQAGenerator` - Multi-hop QA pair construction424. `PromptedFilter` - LLM-based quality filtering435. `GeneralFilter` - Rule-based filtering446. KBC trio (always used together in order): `FileOrURLToMarkdownConverterFlash` → `KBCChunkGenerator` → `KBCTextCleaner`4546These are **preferred primitives**, not fixed workflows. They can be used repeatedly and combined flexibly.4748## Operator Selection Priority Rule (MANDATORY)4950When a specialized operator exists for the task, it MUST be used over generic operators. Do NOT use `PromptedGenerator` to replicate functionality that a dedicated operator already provides.5152**Decision table** (check in order, use the first match):5354| Task / Scenario | Required Operator | Do NOT use |55| ----------------------------------------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------ |56| Generate QA pairs from text | `Text2MultiHopQAGenerator` | `PromptedGenerator` with QA prompt |57| Convert file path / URL to text | KBC trio (`FileOrURLToMarkdownConverterFlash` → `KBCChunkGenerator` → `KBCTextCleaner`) | `PromptedGenerator` to summarize files |58| Score / evaluate using multiple fields | `FormatStrPromptedGenerator` + `GeneralFilter` | `PromptedFilter` (single input_key only) |59| Filter by deterministic rule on existing fields | `GeneralFilter` | `PromptedFilter` |60| Generate new content from a single field | `PromptedGenerator` | — |61| Generate new content from multiple fields | `FormatStrPromptedGenerator` | Multiple `PromptedGenerator` steps |6263**Key principle**: `PromptedGenerator` is the fallback for generic single-field generation. If the target mentions "QA", "question-answer", "问答" — always reach for `Text2MultiHopQAGenerator` first.6465## Field Flow Rules (MANDATORY)66671. **Inspect record content first**: Read representative records and identify the68 semantic role and fitness of their content; field names and presence alone do69 not establish that content is suitable for the target.702. **Design from the target contract**: Select source and generated fields based71 on the content required by the target, including improved semantic72 counterparts when existing content does not fit that contract.733. **Keep execution ordered**: Every field consumed by an operator must be74 available from the input or produced by an earlier operator.754. **Never reference before creation**: Create a generated field before any76 downstream operator evaluates, filters, or transforms it.7778```79✗ WRONG: Filter by "quality_score" before generating it80✓ CORRECT: Generate "quality_score" first, then filter by it81```8283## Grounded Field Generation Pattern (RECOMMENDED)8485When constructing improved training fields from records that already contain a86source instruction, answer, implementation, or other target-bearing content,87ground each generated stage in the source semantics. A useful reference flow is:8889```text90source content + source answer91 -> generate an improved question/instruction9293improved question/instruction + source answer94 -> generate or revise the answer9596improved question/instruction + source answer + generated answer97 -> evaluate semantic consistency and target fitness98```99100Adapt the field names and operators to the task. This is a reference pattern,101not a requirement to generate every role on every dataset. Its purpose is to102prevent an answer generator from seeing only a rewritten question and freely103inventing behavior that is unsupported by the source answer. The final quality104evaluation should reject generated answers that omit supported behavior or add105unsupported contracts, constraints, edge cases, exception handling, or other106observable semantics, even when the generated question and answer are mutually107consistent.108109Before expensive LLM generation, prefer multiple applicable non-LLM filtering110operators when the source pool is large enough to support meaningful attrition.111Use deterministic checks for defects that can be established reliably, such as112parseability, required content shape, empty or truncated content, duplicates,113unsafe patterns, invalid values, and task-specific structural invariants. Keep114these filters content-aware and avoid treating familiar field names or mere115field presence as evidence of quality. The goal is to reduce generation load116while retaining enough valid and diverse source records for the downstream117target.118119For vertical domains whose target capability inherently requires reasoning,120the pipeline MUST use operators to distinguish records that contain suitable121chain-of-thought (CoT) content from those that do not. For a record without122suitable CoT, assess the problem's difficulty and either retain it by routing123that branch through an appropriate reasoning-generation operator to construct124CoT, or filter it out when generating useful reasoning is unwarranted or125unreliable.126127## Prompted Operator Usage Policy (MANDATORY)128129- Don't mechanically create one prompted operator per tiny requirement. If one operator can handle multiple related transformations, prefer that over splitting.130- Multiple prompted operators are allowed when the task genuinely requires distinct semantic transformations. If using multiple, justify each step's role, input field, and output field.131132## KBC Usage Constraint (MANDATORY)133134The KBC trio must always be used in this exact order:1351361. `FileOrURLToMarkdownConverterFlash` — converts file path / URL → Markdown text (field: `text_path`)1372. `KBCChunkGenerator` — splits Markdown into chunks (field: `raw_chunk`)1383. `KBCTextCleaner` — LLM-cleans each chunk (field: `cleaned_chunk`)139140Rules:141142- All three steps are required; never skip one.143- Input to step 1 must be a file path or URL, never plain text content.144- Each step's `output_key` becomes the next step's `input_key`.145- Use the default field names (`text_path`, `raw_chunk`, `cleaned_chunk`) unless explicitly requested otherwise.146147## GeneralFilter Field Safety Rule (MANDATORY)148149`GeneralFilter` lambda rules must ONLY reference fields that exist in sample data or are produced by upstream steps.150151## Multi-Field Filtering Pattern (MANDATORY)152153`PromptedFilter` only accepts a single `input_key`. For multi-field evaluation (e.g., scoring QA pairs), use `FormatStrPromptedGenerator` to score + `GeneralFilter` to filter.154155**Important caveat for `Text2MultiHopQAGenerator` output**: The `QA_pairs` column is a nested list of dicts, not separate `question`/`answer` columns. You **cannot** directly pass `question` or `answer` as kwargs to `FormatStrPromptedGenerator` after `Text2MultiHopQAGenerator`. To score or filter individual QA pairs, use **post-processing** (explode the list into rows, then optionally score/filter in a second pipeline or in Python code).156157## Output Contract (MANDATORY)158159**Two-stage output required**:160161### Stage 1: Intermediate Operator Decision (JSON)162163Output this first:164165```json166{167 "ops": ["OperatorA", "OperatorB", "OperatorC"],168 "field_flow": "field_a -> field_b -> field_c",169 "reason": "Why this ordered operator chain satisfies the target, how field dependencies are satisfied, and why prompted operators are or are not used."170}171```172173### Stage 2: Complete Response (5 sections)1741751. **Field Mapping**: Map sample fields to semantic roles, identify fields to generate1762. **Ordered Operator List**: List operators in execution order with justification1773. **Reasoning Summary**: Explain operator selection, field flow, why this design1784. **Complete Standard Pipeline Code**: Full executable Python following repository style1795. **Adjustable Parameters / Caveats**: Tunable parameters, fallback strategies, debugging tips180181## Standard Code Generation Rule (MANDATORY)182183**All generated Python code must follow the standard pipeline organization shown in the `examples/` folder of this skill package.**184185**Input Data Format**:186187- `first_entry_file_name` MUST be set to the **user-provided file path** (the JSONL sample file)188- File extension must be `.jsonl` (one JSON object per line, NOT an array)189- **DO NOT create new file paths** - use the exact path the user provided190191**Required structure**: `__init__` (storage + llm_serving + operators) → `forward` (sequential `operator.run(storage=self.storage.step(), ...)`) → `if __name__ == "__main__"` entry point.192193**DO NOT**: generate custom runtime executors, `forward(plan)` style frameworks, or dynamic dispatch engines.194195## Operator Parameter Signature Rule (MANDATORY)196197Use repository-valid constructor/run signatures only. Never invent parameter names.198199### Base Components200201**`FileStorage`**202203```python204FileStorage(205 first_entry_file_name="...jsonl",206 cache_path="./cache",207 file_name_prefix="dataflow_cache_step",208 cache_type="jsonl"209)210```211212**`APILLMServing_request`**213214```python215APILLMServing_request(216 api_url="...",217 key_name_of_api_key="DF_API_KEY", # defaults to DF_API_KEY; set to e.g. "OPENAI_API_KEY" if needed218 model_name="gpt-4o",219 max_workers=10220)221```222223### Six Core Operators: Signatures + Key Requirements224225**1) `PromptedGenerator`**226227- Constructor: `PromptedGenerator(llm_serving, system_prompt="You are a helpful agent.", user_prompt="", json_schema=None)`228- Run: `run(storage=self.storage.step(), input_key="raw_content", output_key="generated_content")`229- `input_key` column must exist. Generated rows written to `output_key`.230231**2) `FormatStrPromptedGenerator`**232233- Constructor: `FormatStrPromptedGenerator(llm_serving, system_prompt="You are a helpful agent.", prompt_template=FormatStrPrompt(...), json_schema=None)`234- Run: `run(storage=self.storage.step(), output_key="generated_content", **input_keys)`235- `**input_keys`: each kwarg maps a **template variable name** (key) to a **dataframe column name** (value). Internally does `row[input_keys[key]]` per row, then `prompt_template.build_prompt(need_fields, **key_dict)`.236- Kwarg keys must match `{placeholder}` names in `FormatStrPrompt.f_str_template`. Kwarg values must be existing dataframe columns.237- `prompt_template` cannot be `None` (raises `ValueError`). Must pass an instantiated `FormatStrPrompt(f_str_template="...")`.238- Import: `from dataflow.prompts.core_text import FormatStrPrompt`239240**3) `Text2MultiHopQAGenerator`**241242- Constructor: `Text2MultiHopQAGenerator(llm_serving=self.llm_serving, seed=0, lang="en", prompt_template=None, num_q=5)`243 - `llm_serving` — LLM serving instance (required)244 - `seed` (int, default `0`) — random seed for reproducibility245 - `lang` (str, default `"en"`) — language for generation prompt; controls sentence splitting (`"."` for `"en"`, `"。"` for `"zh"`)246 - `prompt_template` — custom `DIYPromptABC` instance; pass `None` to use default `Text2MultiHopQAGeneratorPrompt`247 - `num_q` (int, default `5`) — **maximum** number of QA pairs to **keep** per input row (truncates the generated list; actual generation count depends on sentence triples in the text)248- Run: `run(storage, input_key="cleaned_chunk", output_key="QA_pairs", output_meta_key="QA_metadata")`249 - `input_key` must exist (cleaned text chunk column)250 - `output_key` — column containing a **nested list** of QA dicts per row. Each dict has keys: `question` (str), `reasoning_steps` (list of `{step: str}`), `answer` (str), `supporting_facts` (list of str), `type` (str)251 - `output_meta_key` — column containing metadata dict per row with keys: `source`, `timestamp`, `complexity`252 - Output column named by `output_key` / `output_meta_key` must NOT pre-exist.253- Each input row produces **one row** with a nested list in the `output_key` column. The list items are dicts — `question`, `answer`, etc. are **NOT** separate dataframe columns. Downstream operators like `FormatStrPromptedGenerator` cannot directly reference `question` or `answer` as column names. To use individual QA pairs downstream, you must **post-process** (explode the list into separate rows) outside the operator chain.254- **Input text constraints** (texts failing these checks produce empty `qa_pairs: []`):255 - Length: 100–200,000 characters256 - Must contain at least 2 sentences (2+ `.` or 2+ `。`)257 - Special character ratio must be ≤ 30%258259**4) `PromptedFilter`**260261- Constructor: `PromptedFilter(llm_serving, system_prompt="...", min_score=1, max_score=5)`262- Run: `run(storage=self.storage.step(), input_key="raw_content", output_key="eval")`263- `input_key` must exist. `output_key` is numeric score column; rows outside `[min_score, max_score]` are filtered out.264265**5) `GeneralFilter`**266267- Constructor: `GeneralFilter([lambda df: df["score"] >= 4, ...])`268- Run: `run(storage=self.storage.step())`269- Each rule must return boolean `pd.Series`. Referenced fields must already exist.270271**6) KBC Trio (always used in this order)**272273**Step 1 — `FileOrURLToMarkdownConverterFlash`**274275- Constructor: `FileOrURLToMarkdownConverterFlash(intermediate_dir="../example_data/KBCleaningPipeline/flash/", mineru_model_path="opendatalab/MinerU2.5-2509-1.2B", batch_size=4, replicas=1, num_gpus_per_replica=1.0, engine_gpu_util_rate_to_ray_cap=0.9)`276- **Does NOT take `llm_serving`** — this operator has no LLM dependency.277- `mineru_model_path` is **required** — passing `None` raises `ValueError`. Use a HuggingFace model ID or local path.278- Run: `run(storage=self.storage.step(), input_key="source", output_key="text_path")`279- Input must be a file path or URL (`.pdf`, `.png`, `.jpg`, `.jpeg`, `.webp`, `.gif`, `.html`, `.xml`, `.txt`, `.md`).280281**Step 2 — `KBCChunkGenerator`**282283- Constructor: `KBCChunkGenerator(chunk_size=512, chunk_overlap=50, split_method="token", min_tokens_per_chunk=100, tokenizer_name="bert-base-uncased")`284- Run: `run(storage=self.storage.step(), input_key="text_path", output_key="raw_chunk")`285- `split_method` options: `"token"`, `"sentence"`, `"semantic"`, `"recursive"`.286287**Step 3 — `KBCTextCleaner`**288289- Constructor: `KBCTextCleaner(llm_serving, lang="en")`290- Run: `run(storage=self.storage.step(), input_key="raw_chunk", output_key="cleaned_chunk")`291- LLM-cleans each chunk; output is ready for downstream QA generation.292293### Correct Import Paths (MANDATORY)294295```python296# Base components297from dataflow.utils.storage import FileStorage298from dataflow.serving import APILLMServing_request299300# Operators301from dataflow.operators.core_text import PromptedGenerator, FormatStrPromptedGenerator, Text2MultiHopQAGenerator, PromptedFilter, GeneralFilter302from dataflow.operators.knowledge_cleaning import FileOrURLToMarkdownConverterFlash, KBCChunkGenerator, KBCTextCleaner303```304305## Extended Operator Reference: core_text Skill306307The sibling skill **`core_text`** (located at `../core_text/`) provides detailed per-operator API documentation that supplements the summary signatures above.308309**Each operator directory contains**:310311- `SKILL.md` — Full English reference: constructor signature, `run()` signature, execution logic, mandatory rules, return value semantics312- `SKILL_zh.md` — Chinese translation of the reference313- `examples/good.md` — Best-practice pipeline example314- `examples/bad.md` — Common mistakes and failure cases315316**When to consult `core_text`**:317318- When generating pipeline code that uses an operator beyond the 6 core primitives (e.g., `BenchAnswerGenerator`, `ChunkedPromptedGenerator`, `EmbeddingGenerator`, `RetrievalGenerator`, `RandomDomainKnowledgeRowGenerator`)319- When you need to verify edge-case behavior, return value semantics, or error conditions for any operator320- When debugging generated pipeline code — the `bad.md` examples document the most frequent mistakes321322**Note**: The 6 core primitives documented above in "Operator Parameter Signature Rule" remain the primary reference for standard pipeline generation. The `core_text` skill provides deeper detail and covers additional operators not in the core set.323324---325326### Generate Operators327328**Path**: `../core_text/generate/`329330**Available operator references** (8 operators):331332| Operator | Subdirectory | Description |333| ------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |334| `PromptedGenerator` | `prompted-generator/` | Single-field LLM generation — full execution logic, skip-falsy rules |335| `FormatStrPromptedGenerator` | `format-str-prompted-generator/` | Multi-field template generation — placeholder-to-column mapping details,`@prompt_restrict` validation |336| `Text2MultiHopQAGenerator` | `text2multihopqa-generator/` | Multi-hop QA pair construction — text filtering thresholds (100–200k chars), output structure, row-count behavior |337| `BenchAnswerGenerator` | `bench-answer-generator/` | Benchmark answer generation —`eval_type` variants, conditional field requirements |338| `ChunkedPromptedGenerator` | `chunked-prompted-generator/` | Long document chunk-by-chunk processing — token-based splitting, file I/O conventions |339| `EmbeddingGenerator` | `embedding-generator/` | Text vectorization — supported serving backends,`/v1/embeddings` endpoint usage |340| `RandomDomainKnowledgeRowGenerator` | `random-domain-knowledge-row-generator/` | Domain-specific row generation — seed dataframe requirements,`generation_num` constraints |341| `RetrievalGenerator` | `retrieval-generator/` | Async RAG generation —`LightRAGServing.create()` async initialization, `await run()` requirement |342343---344345### Eval Operators346347**Path**: `../core_text/eval/`348349**Available operator references** (5 operators):350351| Operator | Subdirectory | Description |352| --------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------ |353| `BenchDatasetEvaluator` | `bench-dataset-evaluator/` | Benchmark answer comparison —`match` (math verification) and `semantic` (LLM-based) modes |354| `BenchDatasetEvaluatorQuestion` | `bench-dataset-evaluator-question/` | Extended benchmark evaluator — adds question context and subquestion support over `BenchDatasetEvaluator` |355| `PromptedEvaluator` | `prompted-evaluator/` | LLM-based row scoring — writes score into new column without removing rows |356| `Text2QASampleEvaluator` | `text2qa-sample-evaluator/` | QA pair quality evaluation — 4 dimensions, 8 output columns (grades + feedbacks per dimension) |357| `UnifiedBenchDatasetEvaluator` | `unified-bench-dataset-evaluator/` | Unified benchmark evaluation — 6 `eval_type` variants, writes 4 output columns |358359---360361### Filter Operators362363**Path**: `../core_text/filter/`364365**Available operator references** (3 operators):366367| Operator | Subdirectory | Description |368| ----------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------- |369| `GeneralFilter` | `general-filter/` | Rule-based row filtering — lambda conditions combined with AND, removes rows only, adds no new columns |370| `KCenterGreedyFilter` | `kcentergreedy-filter/` | Diversity-based downsampling — K-Center Greedy algorithm, requires pre-computed embedding vectors |371| `PromptedFilter` | `prompted-filter/` | LLM semantic filtering — internally uses `PromptedEvaluator`, retains rows with scores in `[min_score, max_score]` |372373---374375### Refine Operators376377**Path**: `../core_text/refine/`378379**Available operator references** (2 operators):380381| Operator | Subdirectory | Description |382| ------------------- | --------------------- | ---------------------------------------------------------------------------------------------- |383| `PandasOperator` | `pandas-operator/` | Custom DataFrame transformation — applies a sequential list of functions, no LLM calls |384| `PromptedRefiner` | `prompted-refiner/` | LLM text refinement — rewrites text in-place, overwrites original column with refined results |385386## Input File Content Analysis Rule (MANDATORY)387388Analyze sample data content to determine task nature:389390**File path fields** (e.g., `pdf_path`, `image_path`, `doc_path`):391392- → KBC trio in order: `FileOrURLToMarkdownConverterFlash` → `KBCChunkGenerator` → `KBCTextCleaner` (supports `.pdf`, `.png`, `.jpg`, `.jpeg`, `.webp`, `.gif`, `.html`, `.xml`, `.txt`, `.md`)393- → Document/file processing workflow394395**Plain text fields** (e.g., `text`, `content`, `review_text`):396397- → Use `PromptedGenerator`, `PromptedFilter`, `Text2MultiHopQAGenerator`, `FormatStrPromptedGenerator`, `GeneralFilter`398- → Do NOT use KBC399400**Multiple semantic fields** (e.g., `instruction`, `output`, `question`, `answer`):401402- → Use `FormatStrPromptedGenerator` for combining fields403- → Use `GeneralFilter` for field-based rules404405## Examples406407See `examples/` folder for complete workflows:4084091. **`examples/basic_generate_and_filter.md`** — `PromptedGenerator` + `PromptedFilter` (simplest pattern)4102. **`examples/multifield_scoring.md`** — `FormatStrPromptedGenerator` with multi-field scoring4113. **`examples/multi_stage_pipeline.md`** — Multiple `PromptedGenerator` stages + `GeneralFilter`4124. **`examples/kbc_pdf_to_qa.md`** — KBC trio (`FileOrURLToMarkdownConverterFlash` + `KBCChunkGenerator` + `KBCTextCleaner`) + `Text2MultiHopQAGenerator` + `PromptedFilter` (scores nested QA_pairs column per chunk)4135. **`examples/reasoning_math_pipeline.md`** — High-quality math reasoning workflow using native question screening/synthesis, difficulty and category evaluation, `ReasoningAnswerGenerator`, and format/length/ground-truth/ngram validation4146. **`examples/reasoning_general_pipeline.md`** — General or mixed-domain reasoning generation with reference-aware model judging and n-gram filtering4157. **`examples/reasoning_math_fusion_pipeline.md`** — Embedding-grounded sequential, parallel, and condition fusion for synthesizing harder math questions, followed by solvability evaluation4168. **`examples/reasoning_pretrain_pipeline.md`** — Math reasoning generation and filtering followed by explicit SFT-to-pretraining `text` conversion4179. **`examples/reasoning_diy_pipeline.md`** — Native reasoning operators with custom vertical-domain filter, synthesis, and answer prompt contracts41810. **`examples/reasoning_cpu_clean_pipeline.md`** — CPU-only format, mathematical ground-truth, and n-gram cleaning for existing reasoning answers41911. **`examples/agentic_rag_text_pipeline.md`** — Atomic and verified multi-hop QA over retrieved text, including grounding, shortcut, reasoning, and final-answer checks42012. **`examples/code_text_pipelines.md`** — Code-to-SFT and seed-to-code generation with quality scoring and sandbox execution, plus CPU code-text cleaning42113. **`examples/chemistry_smiles_text_pipeline.md`** — Chemistry-text SMILES extraction followed by molecular-equivalence evaluation42214. **`examples/function_call_text_pipeline.md`** — Scenario, task, function-schema, multi-turn tool-conversation synthesis and evaluation42315. **`examples/text2qa_pipeline.md`** — Diversity-aware text selection, QA generation, and multidimensional QA evaluation42416. **`examples/text2sql_text_pipelines.md`** — Executable Text-to-SQL generation, refinement, VectorSQL construction, CoT voting, and difficulty classification42517. **`examples/text_synthesis_and_quality_pipelines.md`** — Conversation, SFT, and PT text synthesis plus deterministic and learned quality-filtering chains42618. **`examples/text_benchmark_eval_pipelines.md`** — Direct and question-aware semantic or deterministic answer evaluation427428These are strategy guidance, not templates to copy blindly. Generated code must follow standard pipeline structure.