Community编程与开发github.com

书籍到SFT流水线

该技能应用于书籍到SFT(监督微调)流水线:包括ePub提取、文学分段、作者风格数据集构建、风格迁移训练、LoRA工作流以及用于声音复制的模型评估。

书籍到SFT流水线 是什么?

书籍SFT流水线是一个完整的系统,用于将书籍转化为SFT数据集并训练风格迁移模型。该技能专为使用Tinker等SFT平台从文学作品构建微调数据集的开发者设计,支持创建作者风格模型。其核心架构基于三个支柱:智能分段(150-400字语义完整块)、多样化指令生成(15+提示模板和5+系统提示)和风格优先于内容。流水线包括六个阶段:从ePub提取文本(使用`epub2`和`BeautifulSoup`)、智能分段(使用重叠保持语义连贯)、多样化指令生成(使用低成本LLM如Gemini Flash生成描述)、数据集构建(生成结构化JSONL数据,每块变体2个)、在Qwen/Qwen3-8B-Base上使用Tinker进行LoRA训练(rank=32,约350MB适配器),以及通过现代场景测试(如关于咖啡师或气候变化的提示)和AI检测器进行验证。该技能还整合了上下文工程的技能,如项目开发(分段幂等架构)、上下文压缩(信息密度优化)、多智能体模式(监督者/编排者架构)和评估(端态评估模式)。

兼容平台~Claude Code~Codex CLI~Cursor✓Gemini CLI
npx skills add https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering/tree/main/examples/book-sft-pipeline

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

书籍 SFT 流水线

一个完整的系统,用于将书籍转换为 SFT 数据集并训练风格迁移模型。本技能教授从原始 ePub 到能够以任何作者风格写作的模型的完整流水线。

何时激活

在以下场景激活此技能:

  • 从文学作品中构建微调数据集
  • 创建作者风格或风格迁移模型
  • 为 Tinker 或类似 SFT 平台准备训练数据
  • 设计长文本的分段流水线
  • 在有限数据上训练小模型(8B 或更小)

核心概念

书籍 SFT 的三大支柱

1. 智能分段 文本块必须在语义上连贯。在句子中间断开会教导模型产生碎片化的输出。目标:每块 150-400 词,始终在自然边界断开。

2. 多样化指令生成 使用多个提示模板和系统提示以防止过拟合。单一的提示样式会导致记忆化。使用 15+ 个提示模板和 5+ 个系统提示。

3. 风格优先于内容 目标是学习作者的节奏和词汇模式,而不是记忆情节。合成指令描述发生了什么,但不直接引用文本。

流水线架构

┌─────────────────────────────────────────────────────────────────┐
│                    编排器代理                                  │
│  协调流水线阶段,管理状态,处理失败                              │
└──────────────────────┬──────────────────────────────────────────┘
                       │
       ┌───────────────┼───────────────┬───────────────┐
       ▼               ▼               ▼               ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│  提取代理    │ │  分段代理    │ │  指令代理    │ │  数据集构建器 │
│ ePub → 文本  │ │ 文本 → 块   │ │ 块 → 提示    │ │ 对 → JSONL  │
│              │ │ 150-400 词   │ │              │ │              │
└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘
                       │
       ┌───────────────┴───────────────┐
       ▼                               ▼
┌──────────────┐               ┌──────────────┐
│  训练代理    │               │  验证代理    │
│ Tinker 上的  │               │ AI 检测器    │
│ LoRA         │               │ 原创性检查   │
└──────────────┘               └──────────────┘

阶段 1:文本提取

关键规则

  1. 始终优先使用 ePub 而非 PDF - OCR 错误会成为学习模式
  2. 使用段落级别提取 - 从 <p> 标签提取以保留段落分隔
  3. 移除前言和后语 - 版权信息和目录会污染数据集
# 从 ePub 段落中提取文本
from epub2 import EPub
from bs4 import BeautifulSoup

def extract_epub(path):
    book = EPub(path)
    chapters = []
    for item in book.flow:
        html = book.get_chapter(item.id)
        soup = BeautifulSoup(html, 'html.parser')
        paragraphs = [p.get_text().strip() for p in soup.find_all('p')]
        chapters.append('\n\n'.join(p for p in paragraphs if p))
    return '\n\n'.join(chapters)

阶段 2:智能分段

更小的块 + 重叠

更小的块(150-400 词)比更大的块(250-650 词)能产生更多训练样本和更好的风格迁移。

def segment(text, min_words=150, max_words=400):
    paragraphs = text.split('\n\n')
    chunks, buffer, buffer_words = [], [], 0
    
    for para in paragraphs:
        words = len(para.split())
        if buffer_words + words > max_words and buffer_words >= min_words:
            chunks.append('\n\n'.join(buffer))
            # 保留最后一段以实现重叠
            buffer = [buffer[-1], para] if buffer else [para]
            buffer_words = sum(len(p.split()) for p in buffer)
        else:
            buffer.append(para)
            buffer_words += words
    
    if buffer:
        chunks.append('\n\n'.join(buffer))
    return chunks

预期结果

对于一本 86,000 词的书籍:

  • 旧方法(250-650 词):约 150 个块
  • 新方法(150-400 + 重叠):约 300 个块
  • 每块有 2 个变体:600+ 个训练样本

阶段 3:多样化指令生成

关键见解

使用单一的提示模板会导致记忆化。多样化的模板能教导底层的风格。

SYSTEM_PROMPTS = [
    "你是一位擅长模仿特定文学风格的创意写作专家。",
    "你是一位对经典散文风格有深刻理解的文学作家。",
    "你是一位擅长模仿独特作者声音的创意作家。",
    "你写的散文捕捉了现代主义文学的精髓。",
    "你是一位才华横溢的作家,能够传达经典美国作家的风格。",
]

PROMPT_TEMPLATES = [
    "以{ author }的风格写一段文字:{ desc }",
    "用{ author }的声音写关于:{ desc }",
    "用{ author }独特的散文风格描述:{ desc }",
    "像{ author }那样写这个场景:{ desc }",
    "使用{ author }的重复技巧描述:{ desc }",
    "在以下段落中捕捉{ author }的节奏:{ desc }",
    "像{ author }一样写作:{ desc }",
    "用{ author }的声音写:{ desc }",
    "这是一次文学练习。像{ author }一样写作:{ desc }",
    "你能以{ author }的风格写作吗?{ desc }",
]

指令生成

INSTRUCTION_PROMPT = """用 2-3 句话描述这段摘录中发生了什么。
关注:出现的人物、动作、情感、场景。
不要直接引用文本。

摘录:
{ text }
"""

# 使用快速、便宜的 LLM(例如 Gemini Flash)
instruction = llm_call(INSTRUCTION_PROMPT.format(text=chunk))

阶段 4:数据集构建

消息格式

{
    "messages": [
        {"role": "system", "content": "你是一位创意写作专家..."},
        {"role": "user", "content": "以 Author 的风格写作:场景描述..."},
        {"role": "assistant", "content": "来自块的书籍实际文本..."}
    ]
}

每块多个变体

def build_examples(chunk, instruction, author, variants=2):
    examples = []
    for i in range(variants):
        system = SYSTEM_PROMPTS[i % len(SYSTEM_PROMPTS)]
        template = PROMPT_TEMPLATES[(chunk.id + i) % len(PROMPT_TEMPLATES)]
        user = template.format(author=author, desc=instruction)
        examples.append({"messages": [
            {"role": "system", "content": system},
            {"role": "user", "content": user},
            {"role": "assistant", "content": chunk.text}
        ]})
    return examples

阶段 5:在Tinker上的LoRA训练

配置

CONFIG = {
    "model_name": "Qwen/Qwen3-8B-Base",  # 基础版,非指令版
    "lora_rank": 32,                      # 352MB适配器
    "learning_rate": 5e-4,                # LoRA更高的学习率
    "batch_size": 4,
    "epochs": 3,
}

为什么使用基础模型?

使用基础(预训练)模型,而非指令微调版本:

  • 基础模型对新风格更具可塑性
  • 指令模型具有抵抗覆盖的模式
  • 风格是一种低级模式,基础模型能更好地捕捉

训练循环

import tinker
from tinker import types

training_client = await service_client.create_lora_training_client_async(
    base_model="Qwen/Qwen3-8B-Base",
    rank=32
)

for epoch in range(3):
    for batch in batches:
        await training_client.forward_backward_async(batch, loss_fn="cross_entropy")
        await training_client.optim_step_async(types.AdamParams(learning_rate=5e-4))

result = await training_client.save_weights_for_sampler_async(name="final")

阶段 6:验证

现代场景测试

使用原书中不可能出现的场景进行测试:

TEST_PROMPTS = [
    "写一段关于咖啡师制作拿铁的文字",
    "描述一对情侣通过短信交流",
    "写一段关于某人担心气候变化的故事",
]

如果模型将风格标记应用于现代场景,则说明它学到了风格,而非内容。

原创性验证

# 在训练数据中搜索输出短语
grep "output中的特定短语" dataset.jsonl
# 应返回:无匹配

AI检测器测试

使用 GPTZero、Pangram 或 ZeroGPT 测试输出。

已知问题及解决方案

角色名泄露

症状:模型在新场景中使用原角色名。 原因:单本书的角色名多样性有限。 解决方案:在多本书上训练或添加合成样本。

模型重复精确短语

症状:输出中包含训练数据中的精确句子。 原因:提示变体太少或训练轮次过多。 解决方案:使用 15+ 个模板,限制为 3 个轮次。

碎片化输出

症状:句子感觉不完整。 原因:分段不佳,在思路中间断开。 解决方案:始终在段落边界断开。

指南

  1. 始终优先使用 ePub 而非 PDF - OCR 错误会成为学习模式
  2. 绝不在句子中间断开 - 边界必须在语法上完整
  3. 使用多样化提示 - 15+ 个模板,5+ 个系统提示
  4. 使用基础模型 - 而非指令版本
  5. 使用更小的块 - 150-400 词以获得更多样本
  6. 保留测试集 - 至少 50 个样本
  7. 在现代场景上测试 - 证明风格迁移而非记忆化
  8. 验证原创性 - 在训练数据中搜索输出短语

预期结果

指标值
训练样本数每本书 500-1000
模型Qwen/Qwen3-8B-Base
LoRA 秩32
适配器大小~350 MB
训练时间~15 分钟
损失降低90%+
风格迁移成功率~50% 完美

成本估算

组件成本
LLM(指令生成)~$0.50
Tinker 训练(15 分钟)~$1.50
总计~$2.00

与上下文工程技能的集成

此示例应用了来自 Agent Skills for Context Engineering 集合的多个技能:

project-development

流水线遵循分阶段、幂等的架构模式:

  • 获取:从 ePub 提取文本
  • 准备:分拆为训练块
  • 处理:生成合成指令
  • 解析:构建消息格式
  • 渲染:输出 Tinker 兼容的 JSONL
  • 训练:LoRA 微调
  • 验证:现代场景测试

每个阶段都可以恢复,并生成用于调试的中间产物。

context-compression

分段是训练的一种上下文压缩形式。来自 context-compression 的核心见解同样适用:信息密度比信息数量更重要。较小且连贯的块(150-400 词)能比更大、稀释的块产生更好的风格迁移。

双层级策略反映了上下文压缩的评估:

  • 第 1 层:快速、确定性的压缩
  • 第 2 层:LLM 辅助处理边缘情况

multi-agent-patterns

流水线使用监督者/编排器模式:

  • 编排器协调阶段并管理状态
  • 专门的代理(提取、分段、指令、构建器)拥有隔离的上下文
  • 每个代理仅接收其任务所需的信息

这符合子代理的主要目的是隔离上下文而非模拟角色的原则。

evaluation

验证遵循端态评估模式:

  • 功能测试:输出是否匹配预期的风格标记?
  • 原创性验证:内容是否真正生成?
  • 外部验证:AI 检测器得分

“现代场景”测试是一种分布外评估,用于证明泛化能力。

context-fundamentals

提示多样性防止注意力在单一模式上塌缩。当使用相同的提示结构进行训练时,模型会记忆指令-响应映射。多样化的模板强制注意力关注风格模式本身。

参考文献

内部参考:

来自 Agent Skills for Context Engineering 的相关技能:

  • project-development - 流水线架构模式
  • context-compression - 压缩策略
  • multi-agent-patterns - 代理协调
  • evaluation - 评估框架
  • context-fundamentals - 注意力和信息密度

外部资源:


技能元数据

创建时间:2025-12-26 最后更新:2025-12-28 作者:Muratcan Koylan 版本:2.0.0 独立性:是(与主上下文工程集合分离)

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

advanced-evaluation

This skill should be used for advanced LLM evaluation: LLM-as-judge systems, direct scoring, pairwise comparison, rubric calibration, evaluator bias mitigation, confidence scoring, and automated quality assessment.

bdi-mental-states

This skill should be used when modeling agent mental states with BDI concepts: beliefs, desires, intentions, RDF-to-belief transformations, rational agency traces, cognitive agents, BDI ontologies, and neuro-symbolic AI integration.

compaction-control-profiling

This skill should be used when deciding, for a specific model and workload, whether the harness or the model should control compaction, and when qualifying or calibrating that choice with measurements: context-budget sweeps that compare harness-driven and model-driven compaction on one harness, the context-pressure regime where delegation pays, a per-model compaction behavior profile (interface uptake, compression factor per call, reopen rate of archived content, context fill at first compaction, response to pressure warnings), context anxiety and timing-instruction calibration, reversible collapse-and-archive interfaces, and re-qualification after a model or prompt change. Route the editable-file protocol, harness invariants, and edit-position cache cost of self-editing agents to self-managed-context, summary content to context-compression, harness thresholds and cache layout to context-optimization, and general evaluation design to evaluation.

comprehensive-research-agent

Ensure thorough validation, error recovery, and transparent reasoning in research tasks with multiple tool calls

context-compression

This skill should be used when long-running agent sessions need context compression, structured summarization, compaction, token-per-task optimization, or durable handoff summaries that preserve decisions, files, risks, and next actions.

context-degradation

This skill should be used for diagnosing and mitigating context degradation: lost-in-middle failures, context poisoning, context clash, context confusion, attention-pattern issues, and agent performance degradation caused by accumulated or conflicting context.

context-fundamentals

This skill should be used to explain or reason about the foundational concepts of context engineering: what context is, the anatomy of a context window, how attention mechanics work, the U-shaped attention curve, why context quality matters more than quantity, and the mental models needed to interpret every other context-engineering decision. Use this for conceptual explanation, onboarding, and background reading. Route operational work to the specialized skills: debugging attention failures goes to context-degradation, token-efficiency work goes to context-optimization, conversation summarization goes to context-compression, and project-shape decisions go to project-development.

context-optimization

This skill should be used for improving context efficiency: context budgeting, observation masking, prefix or KV-cache strategy, partitioning, token-cost reduction, retrieval scoping, and extending effective context capacity without lowering answer quality.

evaluation

This skill should be used when building agent evaluation systems: deterministic checks, regression suites, multi-dimensional rubrics, quality gates, production monitoring, baseline comparison, and outcome measurement for agent pipelines.

filesystem-context

This skill should be used when agent work needs file-backed context: durable scratchpads, tool-output offloading, just-in-time discovery, cross-agent handoff files, filesystem memory, or cleanup policies for context stored outside the prompt.

harness-engineering

This skill should be used when designing autonomous agent harnesses: research loops, evaluation scaffolds, locked and editable surfaces, durable logs, novelty gates, pruning, rollback, PR preparation, and human approval boundaries.

hosted-agents

This skill should be used when designing hosted or background agent infrastructure: sandboxed execution, remote coding environments, warm pools, session persistence, multiplayer collaboration, self-spawning agents, or Modal-style sandboxes.

instruction-surface-security

Hardens agent runtimes against persistent prompt injection or unauthorized changes to instructions and permissions. Use to audit what agents auto-load, design reviewed activation for project rules, skills, memory, or tool configuration, and test whether trust boundaries hold after reload, restart, or delegation.

latent-briefing

This skill should be used when the user asks to "share memory between agents", "KV cache compaction for multi-agent", "orchestrator worker context", "latent briefing", "reduce worker tokens", "cross-agent memory without summarization", or discusses Attention Matching compaction, recursive language models with workers, or token explosion in hierarchical agents.

long-horizon-prompting

This skill should be used when writing, enhancing, or evaluating the launch prompt for a long-running autonomous agent or a parallel multi-agent orchestration attacking a hard problem: pseudo-formal task briefs that define terms and an exact success predicate linguistically, enumerate non-counting outcomes, set persistence rules with explicit stop and return conditions and effort floors, manage a diverse portfolio of parallel approaches with an approach registry and blocked-route bookkeeping, and gate the return on adversarial audit. Route agent topology and coordination protocols to multi-agent-patterns, runtime control surfaces and loop governance to harness-engineering, evaluator and quality-gate construction to evaluation, judge design to advanced-evaluation, and compaction or memory mechanics to context-compression and memory-systems.

memory-systems

This skill should be used for persistent semantic memory in agent systems: cross-session knowledge retention, entity tracking, temporal validity, graph or vector retrieval, memory consolidation, and memory benchmark selection. Route file-backed scratchpads to filesystem-context, handoff summaries to context-compression, and token-efficiency tactics to context-optimization.

multi-agent-patterns

This skill should be used when designing multi-agent systems that need context isolation, supervisor or swarm coordination, explicit handoffs, parallel execution, or a decision on whether multiple agents are justified.

project-development

This skill should be used for project-level decisions about LLM-powered systems: whether an LLM is the right primitive for the task at hand, the shape of a multi-stage batch or agent pipeline, token and cost estimation, choosing between single-agent and multi-agent at the project level, structured output design for downstream parsing, and structuring agent-assisted iteration. Use this when the unit of work is a whole project or a multi-stage pipeline. Route individual tool design to tool-design and individual skill-loading or context-budget tactics to context-optimization.

self-improvement-loops

This skill should be used when the harness, scaffold, workflow, or optimizer itself is the optimization target: recursive self-improvement (RSI) loops, meta-harnesses, self-improving harnesses that mine their own failures and propose bounded edits, evolutionary or population-based search over agent scaffolds, acceptance gates for self-modifying systems, and agentic context evolution where the mechanism that produces context is versioned and evolved. Route governance of a single autonomous loop (locked surfaces, durable logs, rollback, novelty gates, approval boundaries) to harness-engineering, measurement and quality-gate design to evaluation, judge design to advanced-evaluation, and remote sandbox infrastructure to hosted-agents.

self-managed-context

This skill should be used when a model gets read-write control over its own live context window instead of a harness-scheduled compaction policy: the context exposed as an editable file the model rewrites with code tools, model-driven eviction and in-place updates, the harness invariants that keep self-editing safe (pinned prefix, edit gate, edit receipts, budget readouts, rollback on overflow), the prefix-cache cost of mid-context edits, and steering or training the model's own context-editing strategy. Route note content and fixed-threshold summarization to context-compression, cache-stable layout under harness control to context-optimization, file offloading to filesystem-context, and loop governance to self-improvement-loops.

相关技能