简介
开发者经常会购买内容全面的技术书籍,也会积累大量内部文档。然而,这些资料读过一遍后,往往很难记住,日后也难以快速查阅某个框架的具体用法。传统做法包括搜索原始 PDF,或把整本书放入 LLM 的上下文窗口,但这些方法要么无法给出精确答案,要么会产生“发现循环税”,浪费 token 并引发幻觉。
book-to-skill 改变了这一工作流程:它能把任何技术书籍、文档文件夹或资料集合提炼为结构化、按需加载的智能体技能,包括 SKILL.md 和模块化章节文件。这些技能符合跨智能体标准,可用于 GitHub Copilot CLI、Claude Code、OpenCode 和 IBM Bob。
这个项目最先吸引我的是它的智能提取策略,尤其是 Docling 集成。Docling 可深入提取文档信息。面对版式复杂的技术书籍,标准文本提取器往往力不从心,而 Docling 能完整保留 Markdown 表格、公式和代码块,处理速度约为 1.5 秒/页,确保代码示例和技术结构不会在转换过程中丢失。
book-to-skill 核心概念

图片来源:book-to-skill 的 GitHub 仓库
要理解它如何衔接文档提取与智能体能力,可以先了解 book-to-skill 项目规范中阐述的核心理念和工作机制:
- 要解决的问题 :技术书籍、架构决策记录和内部文档往往读过一次就被遗忘。常见的权宜做法包括对 PDF 进行关键词搜索、让缺乏指引的 LLM 回忆内容,或维护静态笔记,但这些做法容易引发幻觉、token 疲劳或文档闲置。
- “发现循环税” :传统的 PDF 阅读智能体每轮都会重新浏览目录、重新处理整个文件,造成资源浪费。book-to-skill 在转换阶段一次性完成结构整合;与直接灌输完整上下文相比,每次查询的 token 用量可减少 24~51 倍。
- 通用格式与智能体支持 :该工具可将 PDF、EPUB、DOCX、Markdown、HTML、RTF、MOBI 等格式的文件转换为符合标准的智能体技能(SKILL.md)。生成的技能在 GitHub Copilot CLI、Claude Code、Amp、Codex、Hermes Agent、OpenCode 和 OpenClaw 等主要开发宿主中获得原生支持。
- 细粒度产物布局 :生成的技能按组件拆分,可按需加载:
SKILL.md:主索引和核心框架,约 4,000 个 token。chapters/:独立的章节文件,严格按需加载,每个约 1,000 个 token。glossary.md、patterns.md和cheatsheet.md:分别提供按字母顺序排列的关键术语、设计模式,以及用于快速参考的决策启发式规则。
- 隐私与本地优先执行 :处理过程完全在用户的本地机器上运行,确保完整的数据主权,并遵守个人或企业隐私政策。
实现
免责声明:book-to-skill 虽然功能完备、开箱即用,但我在这里的主要目标,是把它的提取能力封装进精简、易用的界面。这个实现是一个个人沙盒,用来实践我对自动化文档智能和本地优先智能体工作流的构想。
为了通过现代 Web 界面使用 book-to-skill,我设计了一个本地优先的 FastAPI 后端,封装提取流水线,并编排自动化的两阶段处理流程:
- 第 1 阶段:提取。通过非阻塞子进程异步运行核心提取脚本,并将输出写入每个任务独立的目录(
output/<job_id>/)。 - 第 2 阶段:技能生成 。将基于 LLM 的技能生成任务交给线程池(ThreadPoolExecutor),生成核心心智模型、章节摘要、术语表、模式和速查表。
架构示意图

两阶段处理流水线
处理流水线的运行方式如下:
User selects file + options (generate_skill: true/false)
│
▼
POST /api/process { file_path, mode, skill_name, generate_skill }
│
▼
FastAPI creates job_id, stores {
status: "pending",
skill_status: null
}
│
▼
─────────────────────────────────────────────
PHASE 1 — EXTRACTION (asyncio subprocess)
─────────────────────────────────────────────
background task sets BOOK_SKILL_WORKDIR=output/<job_id>/
asyncio.create_subprocess_exec(extract.py …)
│
├─ stdout → job["stdout"]
├─ stderr → job["stderr"]
└─ on exit (rc=0):
parse output/<job_id>/metadata.json
read output/<job_id>/full_text.txt
job["metadata"] / ["extracted_text"] populated
job["status"] = "done"
│
▼
─────────────────────────────────────────────
PHASE 2 — SKILL GENERATION (thread pool)
─────────────────────────────────────────────
(only if generate_skill=True and extraction succeeded)
job["skill_status"] = "running"
loop.run_in_executor(thread_pool, generate_skill, …)
│
├─ probe LLM endpoint (8 s timeout)
│ reachable → use _chat() for each artifact
│ unreachable → use stub generators
│
├─ generate per-chapter summaries → chapters/ch01-*.md …
├─ generate glossary → glossary.md
├─ generate patterns → patterns.md
├─ generate cheatsheet → cheatsheet.md
└─ generate master SKILL.md → SKILL.md
job["skill_status"] = "done" | "error"
job["skill_result"] = {
skill_name, skill_dir, files[], chapters,
generated_at, llm_available, error
}
│
▼
Frontend polls GET /api/jobs/{id} every 1.5 s
status == "done" → populate Results tab, switch tab
skill_status == "running" → keep polling + refresh skill files card live
skill_status == "done" → render "Generated Skill Files" card
│
▼
GET /api/jobs/{id}/skill
├─ _resolve_skill_dir():
│ 1. skill_result["skill_dir"] if set and exists on disk (normal path)
│ 2. scan output/<job_id>/skill/*/ for first subdir (server-restart fallback)
├─ auto-heal: skill_status "running" → "done" if .md files found on disk
├─ synthesise skill_result from disk when skill_result was null
│ (llm_available = null → UI shows "🔍 recovered from disk")
└─ return { skill_status, skill_result, files[] }
GET /api/jobs/{id}/skill/download/… → serve individual .md files
└─ also uses _resolve_skill_dir() — works without skill_result in memory
应用架构与代码摘录


以下代码摘自 FastAPI 后端(backend/main.py),展示了如何使用 asyncio.create_subprocess_exec 异步执行提取,同时通过 BOOK_SKILL_WORKDIR 为每个任务保留独立的工作目录:
"""
Book-to-Skill Web Application Backend
FastAPI server that wraps the book-to-skill library's extraction pipeline
and triggers LLM-based skill generation after extraction completes.
"""
import asyncio
import json
import logging
import os
import sys
import uuid
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from pathlib import Path
from typing import List, Optional
from fastapi import FastAPI, HTTPException, BackgroundTasks, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
# ─────────────────────────────── Helpers (time) ──────────────────────────────
def _now_iso() -> str:
"""Return current UTC time as an ISO-8601 string."""
return datetime.now(timezone.utc).isoformat()
# ─────────────────────────────── Logging ─────────────────────────────────────
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger("book_to_skill_app")
# ─────────────────────────────── Config ──────────────────────────────────────
BASE_DIR = Path(__file__).resolve().parent.parent
INPUT_DIR = BASE_DIR / "input"
OUTPUT_DIR = BASE_DIR / "output"
SKILLS_DIR = Path(os.environ.get("SKILLS_DIR", Path.home() / ".agents" / "skills"))
_thread_pool = ThreadPoolExecutor(max_workers=4)
BOOK_TO_SKILL_REPO = BASE_DIR / "book_to_skill_repo"
# File-size cap for uploads — configurable via UPLOAD_MAX_MB in .env (0 = unlimited)
_upload_max_mb = int(os.environ.get("UPLOAD_MAX_MB", "100"))
MAX_UPLOAD_BYTES = _upload_max_mb * 1024 * 1024 if _upload_max_mb > 0 else 0
# Supported upload extensions (mirrors what book-to-skill accepts)
ALLOWED_UPLOAD_EXTENSIONS = {
".pdf", ".epub", ".docx", ".html", ".htm", ".rtf",
".mobi", ".azw", ".azw3", ".txt", ".md", ".rst", ".adoc",
}
# Ensure required directories exist
INPUT_DIR.mkdir(exist_ok=True)
OUTPUT_DIR.mkdir(exist_ok=True)
# In-memory job store {job_id: JobResult}
_jobs: dict[str, dict] = {}
# ─────────────────────────────── Models ──────────────────────────────────────
class ProcessRequest(BaseModel):
file_path: str
mode: str = "text" # "text" | "technical"
skill_name: Optional[str] = None
output_dir: Optional[str] = None
generate_skill: bool = True # set False to skip LLM skill generation
class DirectoryListRequest(BaseModel):
directory: str = str(INPUT_DIR)
class JobStatus(BaseModel):
job_id: str
status: str # "pending" | "running" | "done" | "error"
file_path: str
started_at: Optional[str] = None
finished_at: Optional[str] = None
stdout: str = ""
stderr: str = ""
extracted_text: Optional[str] = None
metadata: Optional[dict] = None
error: Optional[str] = None
skill_status: Optional[str] = None # "pending" | "running" | "done" | "error" | None
skill_result: Optional[dict] = None # SkillGenerationResult.to_dict()
# ─────────────────────────────── App ─────────────────────────────────────────
...
async def _run_extraction(
job_id: str,
file_path: Path,
mode: str,
skill_name: Optional[str],
generate_skill: bool = True,
) -> None:
_jobs[job_id]["status"] = "running"
_jobs[job_id]["started_at"] = _now_iso()
try:
script = _resolve_script()
except FileNotFoundError as exc:
_jobs[job_id]["status"] = "error"
_jobs[job_id]["error"] = str(exc)
return
job_workdir = OUTPUT_DIR / job_id
job_workdir.mkdir(parents=True, exist_ok=True)
cmd: List[str] = [sys.executable, str(script), str(file_path), "--mode", mode]
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env={
**os.environ,
"PYTHONIOENCODING": "utf-8",
"BOOK_SKILL_WORKDIR": str(job_workdir),
},
)
stdout_bytes, stderr_bytes = await asyncio.wait_for(proc.communicate(), timeout=300)
# ... handles completion and triggers Phase 2 skill generation ...
此外,技能生成器(backend/skill_generator.py)包含优雅降级机制和模型探测功能。即使 LLM 端点(如 Ollama 或 llama.cpp)离线,应用也能输出可用的桩结构:
"""
Skill Generator
===============
Reads extraction output (full_text.txt + metadata.json) produced by the
book-to-skill extractor and calls an OpenAI-compatible LLM to generate a
structured agent skill following the SKILL.md spec:
output/<job_id>/skill/<skill_name>/
SKILL.md – master index + core frameworks (~4 000 tokens)
glossary.md – alphabetical key-term definitions
patterns.md – techniques & design patterns
cheatsheet.md – decision rules & quick-reference tables
chapters/
ch01-<slug>.md – per-chapter summary
...
The generator degrades gracefully when no LLM is configured: it produces
stub files so the application always has something to show.
Environment variables (all optional — defaults work with Ollama):
LLM_BASE_URL – OpenAI-compatible base URL (default: http://localhost:11434/v1)
LLM_API_KEY – API key (default: "ollama" — Ollama ignores it)
LLM_MODEL – Model name (default: llama3.2:latest).
Must exactly match a model installed in Ollama (use
`ollama list` to check). Legacy alias "llama3" was removed
from Ollama; the current default is "llama3.2:latest".
LLM_TIMEOUT – Per-request timeout in seconds (default: 120)
"""
from __future__ import annotations
import json
import logging
import os
import re
import textwrap
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import List, Optional, Tuple
logger = logging.getLogger("book_to_skill_app.skill_generator")
# ─────────────────────────────── LLM config ───────────────────────────────────
# Values are read lazily on every call via _cfg() so that editing .env while
# the server is running takes effect immediately — no restart required.
from dataclasses import dataclass as _dataclass # local alias avoids shadowing
@_dataclass(frozen=True)
class _LLMConfig:
base_url: str
api_key: str
model: str
timeout: int
def _cfg() -> _LLMConfig:
"""Return the current LLM configuration, re-reading .env on every call.
Uses python-dotenv with override=True so values written to .env after
server startup are immediately visible to the next request without a
restart. The .env file is located relative to this file's project root.
"""
from dotenv import load_dotenv
from pathlib import Path as _Path
_env_path = _Path(__file__).resolve().parent.parent / ".env"
load_dotenv(_env_path, override=True)
return _LLMConfig(
base_url = os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
api_key = os.environ.get("LLM_API_KEY", "ollama"),
model = os.environ.get("LLM_MODEL", "llama3.2:latest"),
timeout = int(os.environ.get("LLM_TIMEOUT", "120")),
)
# ─────────────────────────────── Result dataclass ─────────────────────────────
...
def _llm_available() -> bool:
"""Quick probe: returns True when the LLM endpoint answers a tiny request."""
try:
models_req = urllib.request.Request(
f"{LLM_BASE_URL.rstrip('/')}/models",
headers={"Authorization": f"Bearer {LLM_API_KEY}"},
method="GET",
)
with urllib.request.urlopen(models_req, timeout=8):
pass
return True
except Exception as exc:
logger.debug("LLM server not reachable: %s", exc)
return False
应用配置
应用可通过环境配置设置文档处理阈值,以及是否启用 LLM。

# ─── Book-to-Skill Web App — Environment Configuration ───────────────────────
# Copy this file to .env and fill in your values.
# Host and port the FastAPI server listens on
APP_HOST=0.0.0.0
APP_PORT=8080
# Upload size limit in MB (default: 100). Set to 0 for unlimited.
# UPLOAD_MAX_MB=100
# Override where generated skills are stored (default: ~/.agents/skills)
# SKILLS_DIR=/path/to/custom/skills
# Override the path to the book_to_skill_repo clone
# BOOK_TO_SKILL_REPO=/path/to/book-to-skill
# Set to "development" to enable FastAPI auto-reload
ENV=production
# ─── LLM / Skill generation ───────────────────────────────────────────────────
# OpenAI-compatible endpoint for skill generation.
# Default points to local Ollama. Change LLM_BASE_URL for llama.cpp:
# LLM_BASE_URL=http://localhost:9931/v1
# Or any OpenAI-compatible service (e.g. OpenAI, Groq, Mistral).
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
# LLM_MODEL must exactly match a model installed in Ollama (run `ollama list`).
# "llama3" is a legacy alias removed in newer Ollama releases — use "llama3.2:latest".
LLM_MODEL=llama3.2:latest
# Per-LLM-request timeout in seconds (default: 120)
# LLM_TIMEOUT=120
API 可访问性
原始代码可通过命令行调用。在此基础上,应用还提供了 API,可以使用 curl 命令发起请求。

处理与测试输出

后端通过两阶段流水线处理输入文档时,会结合 Docling 或特定格式的解析器与 LLM 生成能力,构建结构化的输出层级。下面是一个生成的章节摘要示例,展示了系统如何记录技术小节和核心思想:
# Chapter 30 — Chapter 15: Direct Connect Public Virtual Interface (p. 303)
> **Note:** This file was originally generated as a stub because the LLM detection
> mechanism returned `False` even though Ollama was running. The root cause has
> been fixed (see summary below); this file has been updated to reflect that Ollama
> **is** detected and available.
---
## LLM Detection Status
| Field | Value |
|-------|-------|
| `llm_available` | **`true`** |
| LLM endpoint | `http://localhost:11434/v1` |
| Model detected | `llama3.2:latest` |
| Detection method | Two-step probe (GET /models → POST /chat/completions) |
---
## Chapter Summary
**Chapter 15: Direct Connect — Public Virtual Interface**
This chapter covers the AWS Direct Connect Public Virtual Interface (VIF), which
provides dedicated private connectivity from on-premises infrastructure to AWS
public services (S3, DynamoDB, CloudFront, etc.) without traversing the public internet.
### Key Concepts
- **Public VIF** — a logical interface over a Direct Connect link that advertises
AWS public IP prefixes via BGP; traffic to AWS public services exits through
the Direct Connect circuit rather than over NAT/internet.
- **BGP peering** — each VIF requires a BGP session; the customer advertises their
public IP prefixes and AWS advertises all AWS public service CIDRs.
- **Route filtering** — AWS enforces strict prefix filters; only globally routable
(non-RFC 1918) customer prefixes are accepted.
- **Multi-region reach** — a single Public VIF can reach AWS public endpoints in
**all AWS regions** (not just the Direct Connect location region).
- **Hosted vs. dedicated** — Public VIFs can be provisioned on both dedicated
(1 Gbps / 10 Gbps) and hosted (sub-1 Gbps) Direct Connect connections.
### Design Patterns
| Pattern | When to use |
|---------|-------------|
| Single Public VIF | Simplest; adequate for non-critical workloads |
| Redundant Public VIFs (two DX locations) | HA + failover for production |
| Public VIF + Site-to-Site VPN fallback | Cost-effective HA when second DX is too expensive |
| LAG (Link Aggregation Group) | Increase bandwidth + redundancy on a single DX location |
### Common Exam Traps
1. **Public VIF ≠ internet access** — traffic stays on the AWS backbone; it does
not give clients internet egress.
2. **Public VIF ≠ Private VIF** — Private VIF reaches VPCs; Public VIF reaches
AWS public service endpoints.
3. **BGP AS path** — Direct Connect uses BGP; you must have a public ASN (or use
the 64512–65534 private ASN range in specific hosted scenarios).
4. **Prefix advertisement** — customers must advertise at least one public IP block;
you cannot advertise `0.0.0.0/0` on a Public VIF.
流水线验证与 LLM 探测

为确保生成过程可靠,系统通过 _llm_available() 提供两步探测机制:先通过 GET /models 验证端点,再通过 POST /chat/completions 检查模型。例如,对 AWS Direct Connect 章节等技术文档进行验证,可以确认模型能正确响应并正常生成产物:
- LLM 检测状态:已验证处于活动状态(
true),llama3.2:latest通过http://localhost:11434/v1连接。 - 测试套件结果 :运行 pytest 测试套件,确认模块化提取器和回退处理器各环节的流水线完整性:
43 passed, 1 warning in 64.44s[cite: 13]
结论
这一实现为 book-to-skill 构建了完整的本地优先 Web UI 和编排层。主要成果包括:
- 文档提取 :使用 Docling 准确解析技术 PDF,同时保留代码格式、表格和结构层级。
- 异步非阻塞架构 :通过 FastAPI、后台任务和线程池,流畅处理繁重的解析与 LLM 推理任务。
- 状态管理 :通过磁盘扫描回退和任务状态自动修复,使生成的技能在服务器重启后仍可访问。
- 智能体集成:将静态书籍页面转换为结构化、按需加载的智能体技能,包括 SKILL.md、
glossary.md、patterns.md、cheatsheet.md和章节文件,大幅减少开发工作流中的 token 开销。
参考链接: