Community程式設計與開發github.com

書籍-SFT流水線

此技能用於書籍到SFT的流水線:ePub提取、文學分片、作者風格數據集建構、風格遷移訓練、LoRA工作流程以及語音複製的模型評估。

書籍-SFT流水線 是什麼?

這是一個完整的系統,將書籍轉換為SFT數據集並訓練風格遷移模型。它教導從原始ePub到能夠模仿作者風格進行寫作的模型的完整流程。此技能適用於Claude Code、Cursor、Codex等平台,支援Tinker等SFT訓練平台。其核心概念包括智能分片(150-400詞,保持語義完整)、多樣化指令生成(使用15+提示模板和5+系統提示以避免過擬合),以及風格優先於內容的訓練原則。流水線分為六個階段:文本提取(從ePub中提取段落)、智能分片(按自然邊界分割)、多樣指令生成(創建合成指令)、數據集建構(生成JSONL格式)、LoRA訓練(在Tinker上使用基礎模型)以及驗證(透過現代場景測試和原創性檢查)。已知問題包括角色名稱洩漏和模型逐字複製,解決方案為增加提示多樣性並限制訓練輪次。此技能與上下文工程技能集整合,採用監督者/協調者模式。

相容平台~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 → 文字   │ │ 文字 → 區塊   │ │ 區塊 →       │ │ 配對 →      │
│              │ │ 150-400 詞   │ │ 提示         │ │ JSONL       │
└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘
                       │
       ┌───────────────┴───────────────┐
       ▼                               ▼
┌──────────────┐               ┌──────────────┐
│  訓練代理     │               │  驗證代理     │
│ 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": "以作者風格寫:場景描述..."},
        {"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 "specific phrase from output" dataset.jsonl
# 應返回:No matches

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 rank32
適配器大小~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 詞)能比更大且稀釋的區塊產生更好的風格遷移。

兩層級策略與上下文壓縮評估相呼應:

  • 第一層:快速、確定性壓縮
  • 第二層:針對邊緣情況使用 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.

相關技能