SuperAPI AI Directory

gemini-pdf-summary

Office & productivity

View repository

Updated 10-16 08:44

About this skill

Use Gemini multimodal long context to directly "read and understand" any PDF, routing by document type to the corresponding structured template for outputChinese Markdown. The 4 document types (academic paper / product manual / whitepaper / book) share the same SDK invocation + Markdown style fingerprint + error-handling contract, and each follows its own independent template (assets/template-{paper,manual,whitepaper,book}.md + shared _base.md)。 The agent can directly call this skill's script to process a single document, or follow references/api-quickstart.md to call the SDK itself within the session.

Dependencies: Python ≥ 3.7,google-genai(pip install -U google-genai), environment variable GEMINI_API_KEY(created in Google AI Studio ). For detailed dependencies and failure troubleshooting, see "Prerequisites" at the end.

When to use / not use

Use

  • The user provides alocal PDF, and wants structured Chinese summary output by document type (paper / manual / whitepaper / book)
  • The user wants tobatch-processmultiple PDFs, each following the same type
  • The PDF contains a large amount of charts / formulas / layout information, and plain-text extraction (pdftotext / PyPDF2) would lose information
  • The user wants to use Gemini to read the PDF directly, rather than OCR first
  • The output ultimately needs to land in llm-wiki-management 's raw/<type>/<slug>/ for subsequent ingest
  • The user is unsure of the PDF type—--auto-detect lets the script automatically identify it (PDF metadata + first-page text + Gemini viewing pages 1-3 of the first page for verification)

Do not use

  • The PDF is not a PDF (webpage, Markdown, plain text)—convert to PDF first or use another skill
  • Needword-for-word translation / full-text reproduction(this skill is "summarization", not translation)
  • Needto compare multiple PDFs—this skill handles one at a time; for multiple, call it multiple times and then manually combine
  • Only want to extract key sentences, extractive summarization—this skill is generative structured summarization
  • The user is unwilling or unable to provide GEMINI_API_KEY
  • --type is missing and --auto-detectwas not passed—the script will error and prompt the agent to ask the user to confirm the type (see §Workflow §A)

Input / Output

Input

Field Required Description
PDF path ✓ Local .pdf file, absolute or relative path both acceptable
Document type ✓ --type <paper|manual|whitepaper|book> choose one of the two; if unsure use --auto-detect(script determines automatically)
GEMINI_API_KEY ✓ Environment variable
Model ID ✗ Default gemini-3.1-pro-preview(no need to pass --model ; starting 2026-07-06 all skills uniformly default to pro-preview, with stable long-context attention + complete preservation of mermaid architecture diagrams);only when there is a clear reasonshould it be overridden; see the "Model selection" subsection below for details
Focus ✗ --focus "重点关注实验部分" and the like, will be appended to the prompt
Output path ✗ --output <path>: when paper quick defaults to with figures, treated asdirectory(writes summary.md + figures/); non-paper types / --no-figures / book / paper full mode treated as .md file path (or raw-side directory); if not passed, stdout
Template / mode ✗ paper quick default;--full enable paper full or book mode;--by-chapter split into N .md files by chapter (mutually exclusive with --full mutually exclusive)
Chapter splitting method (by-chapter companion) ✗ --granularity {L1|auto}(default L1, from 2026-07-06): L1 makes N independent API calls by PDF native L1 chapters + L2 subsections merged into L1 (with built-in File API cache, saving N-1 uploads); auto single call (only suitable for short PDFs ≤ 50 pages, >50 pages goes through pre-flight rejection and recommends L1)
Page range (auto by-chapter companion) ✗ --pages 1-50: first use PyMuPDF to split the page range then hand to Gemini; combined with --by-chapter --granularity auto can split ultra-long PDFs.In L1 mode, passing --pages will error(L1 automatically splits pages by chapter)
Extract images ✗ only effective for paper quick:--no-figures disable figure export (manual / whitepaper / book default to no figure export)
Render scale ✗ --figure-dpi 2.0(default 2.0;144 DPI = 72 × 2.0 conversion value, not an independent threshold; when changing --figure-dpi this table needs no sync), only effective when paper quick figure export is enabled
Image format ✗ --figure-format {png,webp,jpeg}, default png; for webp/jpeg can use --figure-quality compression
Compression quality ✗ --figure-quality 1-100, default 85; only effective for webp/jpeg
Pixel limit ✗ --max-width N, after rendering scale proportionally to ≤ N px width; None means no limit
Size limit ✗ --max-size-kb N, automatically downgrade when exceeding N KB (quality → format → scale); None means no limit
Thumbnail ✗ --thumbnail additionally generate thumbnails;--thumbnail-width(default 400px) controls width
Stage 2 visual localization ✗ --refine-figures / --no-refine-figures(default True), only effective for paper quick
Stage 2 render scale ✗ --refine-dpi 2.0, only effective when paper quick refine is enabled
Stage 2 model ✗ --refine-model <id>(added 2026-07-06), only effective for paper quick + --refine-figures ; default None → follows --model . See §Model selection subsection for details
Force overwrite ✗ --force-full, only effective for paper --full mode; by default refuses to overwrite when raw-side artifacts already exist

Model selection

default = do not pass --model. Script default value gemini-3.1-pro-preview is the unified default across the whole skill (2026-07-06 decision):

  • 3.5-flash under --by-chapter single call + JSON structured output hits FULL_MAX_OUTPUT_TOKENS limit, measured unusable
  • pro-preview has more stable long-context attention, mermaid architecture diagrams fully preserved (flash silently drops mermaid blocks under structured output)
  • 4 document types (paper / manual / whitepaper / book) uniformly use pro-preview, no longer special-cased by mode

Don't know what to choose / no special reason → just use the default。

Decision flow:

1. 跑 gemini_pdf_summary.py(不传 --model,用默认 pro-preview)
2. 输出不满意?
   ├─ 否 → 用默认就好
   └─ 是 → 先调 prompt(--focus 或改 template-*.md),再考虑换模型
3. 真要换模型 → 从下方"当前推荐"里按场景选;不要凭印象写 model 字符串

Current recommendations (based on gemini-api-docs-mcp live testing + local by-chapter live testing, 2026-07):

Model Status Positioning When to explicitly override (vs default)
gemini-3.1-pro-preview(Default, unified across all skills) Preview Strongest complex reasoning + stable long context In most scenarios, don't pass --model and you're good
gemini-3.5-flash Stable Best overall quality/cost Batch review / simple summaries / large context but low requirements (Known risks: under structured output it drops mermaid blocks, and --by-chapter single calls easily hit the FULL_MAX_OUTPUT_TOKENS limit)
gemini-3.1-flash-lite Stable Cheapest, lightweight Massive low-cost review / summaries / content exploration

Primary model unavailable → error out and exit, no end-to-end degradation(strengthened 2026-06-30, agent blind spots patched 2026-07-01): In the table above,anymodel encountering 503 / 429 / 5xx, after the script does 3 retries,throws an error directlyto the upper layer—— never silently switches to lite/pro or another cheaper model.And when the agent receives this error, it must not switch models and rerun on its own (the "use --model <id> to switch models" in the script error is for the user, not an instruction for the agent); it must faithfully present the error + three-step suggestion to the user, and the user decides. Switching models must be explicitly specified with --model <id> , see §Core Principles #8 for the full strategy(including the error message format and three-step suggestion).

Stage 2 can be configured with a separate model(added 2026-07-06 --refine-model, effective only for paper quick + --refine-figures ): Stage 2 is single-page PNG + structured JSON bbox/caption output, a simple task, not long-context reasoning, so in theory flash-lite is enough. Models can be split-configured:

# 主总结 pro-preview(保复杂推理 + 长文稳)+ Stage 2 flash-lite(保结构化输出 + 降 503 概率 + 便宜)
python3 gemini_pdf_summary.py --pdf paper.pdf --type paper \
  --model gemini-3.1-pro-preview --refine-model gemini-3.1-flash-lite

By default --refine-model is None → Stage 2 follows --model , keeping the old behavior unchanged. After splitting, if bbox precision degrades (images cut to caption / multiple boxes of irrelevant content), fall back to not passing --refine-model and let Stage 2 follow the primary model.

Avoid using:

  • ==gemini-2.5-flash==: deprecated, officially recommended replacement gemini-3.5-flash(has a shutdown date)
  • gemini-2.5-pro: deprecated, replacement gemini-3.1-pro-preview
  • gemini-2.5-flash-lite: deprecated, replacement gemini-3.1-flash-lite
  • Any *-preview-09-2025 / *-preview-12-2025 and other old preview snapshots——expired, officially abandoned

The deprecated series will be shut down over time. The shutdown dates in this table are based on mcp__gemini-api-docs-mcp__search_documentation / get_current_model live testing; before the agent / user uses them,check once firstto confirm nothing has changed.Do nothardcode shutdown dates / deprecated lists to the month; review this section once a year/quarter.

Output

Route to the corresponding template by document type,unify chapter order, naming, and character count targetsdeclared at the head of each template (single source):

  • paper quick(default): opening 3-column table → team item → ## 3 句话总结 → Background & Motivation → Method Design → Representative Experimental Results → Business Implications & Value → Limitations & Future Work
    • Evaluation / benchmark papers automatically replace "Method Design + Representative Experimental Results" with "Evaluation Design + Evaluation Findings"
  • paper full(--full): Expand subsection by subsection in the original PDF chapter order (including Definition / Theorem / Algorithm labels + formulas $...$ + row-level table transcription + numeric precision to 3 significant figures); do not extract original figures
  • manual: Expand subsection by subsection following the PDF's native table of contents structure (full-style full-text transcription, including command lists / parameter tables / error codes; troubleshooting + FAQ + changelog highlights at the end of chapters are preserved as-is);do not extract original figures
  • whitepaper: Expand subsection by subsection following the PDF's native table of contents structure (full-style full-text transcription, including industry data tables / comparison tables / customer cases; the Conclusion + Key Takeaways + Recommendations at the end of chapters are preserved as-is);do not extract original figures
  • book(full only): Transcribe in full following the PDF's native Chapter / Section / Appendix / Index order;do not extract original figures
  • by-chapter(--by-chapter, common to all 4 document types,default L1 mode, effective from 2026-07-06): Follow the PDF's native L1 chapters with N independent API calls + L2 subsections merged into L1. The layout of the output is <output>/00-index.md(N_L1-line TOC) + <output>/01-<L1-slug>.md(including ## L1.title + ### L2 subsections) + .... L1 mode comes with File API caching(for PDFs > 20MB, go through File API upload once + N Part.from_uri() references, saving N-1 upload tokens). Fine-grained levels such as L2/L3 can be naturally obtained through Gemini splitting within a single L1; the old auto mode (single API call, Gemini decides granularity) is retained for users with short PDFs ≤ 50 pages + those accustomed to the old behavior,

    50 pages go through pre-flight interception and L1 is recommended. For the detailed contract, see references/full-mode-contract.md §by-chapter

Character count target:

SSOT exception note: This table shares the same source as the assets/template-paper.md header — the template header is the target shown to Gemini, this table is a mirror for the agent to look up quickly, and both places must be changed in sync. The SSOT is in the template header (script _load_prompt_for_type extracts this field), and this table is a mirror within SKILL.md. manual / whitepaper / book are full style, with no character count limit — not within the scope of the SSOT exception.

  • paper quick ≤ 2500
  • paper full / manual / whitepaper / book: no character count limit; when the token budget is tight,prioritize concise wording, shrink specific examples,prohibitmerging entire paragraphs, deleting subsections, skipping formulas / theorems / algorithm steps (paper full) / commands / parameters / error codes (manual) / industry data / customer cases (whitepaper) / Chapter content (book)

Figure and table handling strategy(SSOT in assets/_base.md §Figure and table handling conventions):

Type / Mode Figure handling Reason
paper quick Extract original PDF figures → figures/*.png(enabled by default) Forpeoplequick-read summaries, figures are required
paper full Do not extract figures; draw mermaid / tables / ASCII within markdown Agent Q&A foundation; only ~50% of agents can consume PNG
manual / whitepaper Same as paper full The output is mainly for LLM consumption, entering llm-wiki for secondary ingest
book Same as paper full Long-form transcription, the agent subsequently does chapter-by-chapter Q&A

Nonexistent sections may be omitted;Default Chinese(titles, narration, connectives), but terms, model names, product names, library names, etc. when necessary keep the English directly(see core principles #4 and #9 below).

Conciseness first(only applies to paper quick; full style goes full-text level): Every paragraph and every bullet should be cut if possible—if something can be explained in 1 sentence, do not split it into 3; omit any setup/repetition/concept definition that can be omitted; the criterion: "if deleting this paragraph would make the reader misunderstand or miss key information" is the only thing that "must stay"; otherwise cut everything. Density of the summary > length of the summary.

Execution principles / boundaries

Core principles

  1. Feed the original PDF directly to Gemini; do not extract text first
    • Use Part.from_bytes(data=<bytes>, mime_type="application/pdf") to go multimodal
    • Do not use pdftotext / PyPDF2 / pdfplumber or the like to first extract plain text (it loses figures, formulas, and layout)
  2. Structured summary, not paraphrase
    • Route by document type to the corresponding template'sMainline order and namingoutput; for character-count targets see the header of each template (Single source, do not hard-code values in the body)
    • Nonexistent sections may be omitted(e.g., omit "representative experimental results" when a purely theoretical paper has no experimental data)
    • Key data / values must be retained; avoid speaking in generalities
  3. Be faithful to the original text; do not fill in gaps
    • If the document does not say it, mark "not specified in the original text"
    • When citing conclusions, indicate the source (e.g., "see section 4.2 Experiments")
  4. Not forced to be all Chinese: keep English where it should be kept
    • The main output language is still Chinese, but the following five categorieskeep the English directly, do not force a translation:
      • Academic proper nouns / method names: Transformer, RLHF, LoRA, Mixture-of-Experts, Beam Search
      • Model / product / tool names: Gemini, GPT-4, Claude, PyTorch, vLLM, Hugging Face
      • Libraries / APIs / filenames:transformers、pip、requirements.txt、<config> field names
      • Algorithm / protocol / standard names: Top-p, TCP, gRPC, REST, IEEE 802.11ax
      • Metrics / abbreviations / specialized indicators: BLEU, ROUGE, ACL, GPU, FLOPS, perplexity
    • Criterion: when translation would instead cause ambiguity, lose semantics, or the English is already the standard usage in the field, keep it unconditionally. Mixed Chinese and English is the norm (e.g., "training uses LoRA (low-rank adaptation)")
    • In lists / tables, if an item itself is an English term, keep the whole item in English
  5. Figure and table handling is split into two sets(for detailed rules see assets/_base.md §Figure and Table Handling Conventions)
    • paper quick: extract original PDF figures (enabled by default) → figures/figure-pX-fN.png; write the caption into the alt field of the markdown image (![图 N: <中文翻译+总结>](<url> "=WxH")); write the bbox in the PDF reference string for the script to crop precisely
    • The other 3 categories (manual / whitepaper / book + paper full): Do not extract original images; represent concepts with ```mermaid blocks (architecture / flowchart) / markdown tables (data visualization charts) / one sentence of text (decorative images omitted) drawn directly in markdown
  6. GitHub-style paper related work / high-frequency citations: output only in paper quick, as a "business insights & value" sub-section
    • When the paper has an introduction / related work sectiononly thenoutput; if there is no related work, omit the entire section
    • sort in descending order by "importance to this paper",3-5 entries; omit the "citation count" column
    • Key inclusions: baselines directly compared in experiments > foundational work / recent SOTA / direct predecessors of this paper's method
    • Citation details follow the PDF reference list; when uncertain, fill in only author + year (do not fabricate)
  7. paper quick open-source implementations: as a "business insights & value" sub-section (applicable rules see template-paper.md quick mode)
  8. Model selection: defaults and the "when to explicitly override" guide are in the §Model Selection subsection (script DEFAULT_MODEL constant, see scripts/gemini_pdf_summary.py). Actually available models are subject to the current Gemini documentation (verify using gemini-api-docs-mcp 's get_current_model ). Why the model names are not relisted here: the model selection table is the SSOT, listed in the §Model Selection subsection
    • Result quality > system availability · no automatic fallback(2026-06-21 decision, 2026-06-30 hardening): when the default model encounters 503 UNAVAILABLE / 429 RESOURCE_EXHAUSTED / 5xx and other high-concurrency / rate-limit errors, uniformly go through 3 retries (2s/4s backoff; 4xx permanent errors are not retried and are thrown directly)——if still failing, the scriptthrows the error directlyto the upper layer,neversilently degrades to a cheaper model
    • No end-to-end degradation · the agent must not switch models on its own(2026-07-01 hardening): the script throws RuntimeError (including model= + status= + three-step suggestion) which means the task failed,the agent must noton its own add --model gemini-3.1-flash-lite and other cheap models to rerun
  9. Markdown style conventions (repository unified baseline)——detailed 10-section rules see references/markdown-style.md. SKILL.md only highlights 3 key ones:
    • bullet marker always uses *(do not use - or +)
    • mermaid blocks are placed outside bullets (block-level), do not embed them within bullet sub-items
    • Math / ranges / formulas: MathJax is prohibited:$...$ / $$...$$ outline-wiki does not render—— switch to plain text / Unicode ([1, 2^64) / 2⁶⁴ / ≥ ≤ × → ≈); the book template's full-text transcription output may retain $...$ inline formulas (consumable by the agent in Q&A scenarios with LaTeX)

Boundaries

  • Only process local PDFs; anything non-PDF must first be converted to PDF
  • No full-text translation; no comparison of multiple documents
  • One PDF at a time
  • Single PDF size is subject to the File API hard limit (values and handling of oversized files see §Prerequisites)
  • --type and --auto-detect are mutually exclusive, exactly one must be passed; if neither is passed → the script errors out and prompts the agent to ask the user
  • manual / whitepaper / book only support the full style: the script automatically enables the --full style prompt loading (no need for the user to pass --full; for the full mode contract see references/full-mode-contract.md)
  • manual / whitepaper / book + paper full do not extract original images: automatically enables --no-figures(script INFO prompt)
  • paper quick mode image processing: follows gemini-paper-summary's three-layer localization (Stage 2 visual localization + caption locator + bbox hint); when all fail, delete the whole image + strip the echoing sentence
  • paper quick mode image reference screening: the line text must be in the Figure N[.:] + description form to count as a caption; height sanity check threshold of 250pt; see references/figure-extraction.md

Workflow / Steps

A. Agent calls it in the session (recommended flow)

Step 1 — three-dimensional follow-up on type + split method + output path(Key: the script mandates it):

1. 用户说"总结这个 PDF" / agent 拿到本地 .pdf 文件
2. 如果用户已说明类型("这是产品手册"/"这是白皮书"/"这是论文"/"这是书") → 直接传 --type
3. 如果用户没说 / agent 无法确定 → 反问用户:
     "这份 PDF 属于哪种类型?
      - paper      - 学术论文
      - manual     - 产品手册 / datasheet / 用户手册
      - whitepaper - 行业 / 技术 / vendor 白皮书
      - book       - 书籍 / 长篇技术文档
      或者让我用 --auto-detect 自动识别"
4. 用户回答后传 --type <answer>

Step 1b — split method follow-up(Key: only takes effect in --by-chapter mode):

1. 跑 --by-chapter 前,agent 必须反问拆法(**禁止 agent 拍板粒度**——粒度差异
   直接决定产物文件数 + 后续 ingest 路径):
     "希望按什么粒度拆?
      - L1 (默认): 按 PDF 原生 L1 章 N 次独立调用 + L2 子节合并进 L1。
        产物少、撞 token 限概率近 0、自带 File API 缓存。
        例:98 页白皮书 14 个 L1 章 → 14 个 .md
      - auto: 单次 API 调用,Gemini 自决粒度。仅适用 ≤ 50 页短 PDF。
        例:98 页白皮书 1 次调用 → 35%+ 章节截断(不推荐长 PDF)"
2. 用户回答后传 --granularity <L1|auto>(默认 L1,不传走 L1)
3. **不**反问场景:用户已说"按章节拆"未指定粒度 → agent 仍需反问要 L1 还是 auto
   ("按章节"是模糊诉求;体验教训:98 页白皮书直接拆出 118 个细粒度 .md,
   后续合并丢数据,见 /root/gemini-white-paper-err.md)

Step 2 — output path confirmation(Key: to avoid writing to the wrong location):

1. 如果用户已说明输出位置("落到 raw/manuals/foo/")→ 直接传 --output
2. 如果用户没说 → 反问用户:
     "输出到哪个路径?建议:
      - 落到 llm-wiki 的 raw 端:<wiki-root>/raw/<type>/<slug>/
      - 落到临时目录:~/tmp/<slug>/
      - 打印到 stdout(仅纯文字速读用,不导出图)"
3. 用户回答后传 --output <answer>

Why the agent must ask: the 4 document types correspond to different artifact layouts (raw/papers/ / raw/manuals/ / raw/whitepapers/ / raw/books/) — the agent deciding on the user's behalf easily lands in the wrong directory, and subsequently llm-wiki-management 's ingest_diff.py cannot find the artifact and runs in vain.

Step 3 — call the script:

1. 确认 PDF 存在且可读
2. 确认 GEMINI_API_KEY 已设置;未设置则提示用户去 aistudio.google.com/apikey 申请
3. 确认 google-genai 已安装:python3 -c "import google.genai" 或 pip install -U google-genai
4. 调用 scripts/gemini_pdf_summary.py:
   python3 gemini-pdf-summary/scripts/gemini_pdf_summary.py \
     --pdf <path> \
     --type <paper|manual|whitepaper|book> \
     --output <output-dir>    # 或不传 → stdout
   # paper quick 默认带图 + Stage 2 视觉定位(--refine-figures 默认开),保证图质量;
   # --no-figures 关闭图导出

   # by-chapter 模式(默认 L1,2026-07-06 起):
   python3 gemini-pdf-summary/scripts/gemini_pdf_summary.py \
     --pdf <path> \
     --type <type> \
     --by-chapter \
     --granularity L1         # 默认;可省略;长 PDF 首选
     # --granularity auto     # 单次调用,仅 ≤ 50 页短 PDF
     --output <output-dir>
   # L1 模式产物:<output>/00-index.md + N_L1 个 <NN>-<L1-slug>.md
5. 把生成的 Markdown 总结(含图)呈现给用户
6. 标注所用模型与 PDF 文件名
7. **失败处理(重要)**:若第 4 步脚本抛 RuntimeError(503/429/5xx 重试耗尽),
   agent **不得**自行加 `--model` 换便宜模型重跑——把错误原文 + 三步建议如实
   呈现给用户并停下,换不换模型由用户决定(见 §核心原则 #8 端到端不降级)
8. **by-chapter 失败处理**:L1 模式下若个别 L1 章失败,脚本写 FAILED-<slug>.md
   占位 + 继续后续 L1(不中断);00-index.md 标 ⚠FAILED 指向失败项;agent 可
   单独用 `--pages <失败页范围> --granularity auto` 重跑失败段。

You can also call the SDK directly in the session (for API details see references/api-quickstart.md)。

B. auto-detect (when unsure of the type)

python3 gemini-pdf-summary/scripts/gemini_pdf_summary.py \
  --pdf unknown.pdf \
  --auto-detect \
  --output raw/manuals/foo/    # 类型识别后产物仍落用户指定目录

auto-detect flow(see references/auto-detect.md):

  1. Read PDF metadata (Title / Subject / Keywords / Producer) + first-page text
  2. local heuristic scoring (KEYWORD_HINTS table) → return directly if high confidence; otherwise proceed to 3
  3. render the first 1-3 pages to Gemini for multimodal recognition → return paper / manual / whitepaper / book

on failure (insufficient heuristics + Gemini verification anomaly): error + the 4 candidate types + suggest the user explicitly pass --type。

C. 4 output templates (chapter skeleton SSOT is in assets/template-*.md)

For the complete templates and image reference conventions see assets/template-{paper,manual,whitepaper,book}.md。 any template change only requires editing the corresponding template-<type>.md, SKILL.md does not copy them again to avoid scattering.

The chapter skeleton blocks for the 4 document types and the 5 reference samples have been pushed down to references/output-skeletons-and-examples.md — this section only points out the "consumption object" difference for each type (humans reading vs LLM reading); for the detailed skeletons and samples just read that file.

D. Relay with llm-wiki-management

This skill only produces local files— manual / whitepaper / book never extract original images throughout; paper full / book are self-contained; paper quick includes images (PNG) by default. Uploading to outline-wiki is not handled by this skill。

End-to-end workflow (PDF → wiki accumulation):

1. 本 skill:跑 gemini_pdf_summary.py --type <type> --output <dir>
   产出 <dir>/summary.md(paper quick 同时含 figures/*.png)
2. 把产物复制到 <wiki-root>/raw/<type>/<slug>/(保持 llm-wiki 仓布局)
3. llm-wiki-management:跑 ingest_diff.py 发现 raw 新增
   → 生成 wiki/sources/<slug>.md(含 frontmatter type: source + sources 字段指向 raw 路径)
   → 同步 entity / concept 页(如有)
   → 更新 index.md + log.md

Anti-patterns(Don'tdo this):

  • Writing the PDF summary directly in an outline-wiki document andnotgoing through wiki ingest — losing the source page frontmatter and cross-references
  • landing artifacts in a directory that does not match --type (e.g. --type manual but it lands in raw/papers/) —— ingest_diff cannot find it (Note:raw/papers/ is only a counterexample on this line and does not represent the layout standard; for the 4 layout types, see §Workflow §A Step 2 clarifying prompt)
  • Assume this skill willautomaticallypush to outline-wiki ——it will not, this skill stays local only

E. Troubleshooting

Symptom Cause Resolution
ModuleNotFoundError: google.genai SDK not installed pip install --user --break-system-packages google-genai
import fitz failure / pymupdf missing pymupdf not installed pip install --user --break-system-packages pymupdf
DefaultCredentialsError / api_key not set missing GEMINI_API_KEY export GEMINI_API_KEY=... or .env + direnv
400 INVALID_ARGUMENT + mime type error PDF corrupted / encrypted / not a PDF header verify with file <pdf> ; decrypt or re-download
413 REQUEST_TOO_LARGE PDF over 50 MB upload via File API (see references/api-quickstart.md §Oversized PDF)
必须传 --type 或 --auto-detect 二者之一 Call missing type agent asks the user to confirm the type (see §Workflow §A)
--auto-detect cannot be determined either both heuristics + Gemini have insufficient confidence explicitly pass --type <paper|manual|whitepaper|book>
book 类型仅支持 full 模式 trying --type book without --full add --full, or switch to paper type
manual / whitepaper / book 仅支持 full 风格 trying --type manual etc. then passing --no-figures disable mermaid disable --no-figures; manual / whitepaper / book are full style and do not accept "compressed summary" mode
Model 404 model name misspelled or retired use gemini-api-docs-mcp 's get_current_model to check currently available models
ran with a deprecated model (gemini-2.5-*) successfully but it is about to shut down model still works but is deprecated migrate to gemini-3.1-pro-preview(default) or gemini-3.5-flash / gemini-3.1-flash-lite
the character count produced far exceeds the target declared in the prompt Gemini does not strictly follow the character count constraint in the prompt tune the prompt first (specific values in assets/template-*.md)/ --focus; then post-process trim
output empty / truncated hit the output token limit paper quick → tune the prompt character target (SSOT see assets/template-paper.md)/ --focus; full / book truncated tail → mostly the model failed to transcribe faithfully, switch models and rerun or split the book;--by-chapter last chapter truncated → already the pro-preview default, use --pages to split into segments and rerun the last segment (see details in references/full-mode-contract.md §by-chapter)
--by-chapter and --full are mutually exclusive passed both --by-chapter --full choose one:--full goes paper full single artifact (.full.md);--by-chapter makes N API calls splitting into N .md files by L1 chapter (default L1)
--by-chapter --granularity auto + PDF > 50 pages + no --pages a single API call hits the FULL_MAX_OUTPUT_TOKENS limit → last chapter truncated (measured 35%+) switch to --granularity L1(default): N independent calls by PDF native L1 chapter, each chapter ≤ 50 pages, probability of hitting the limit near 0
--by-chapter --granularity L1 + --pages L1 mode automatically splits pages by chapter,--pages Incompatible Delete --pages; L1 mode automatically splits by the PDF's native L1 chapter boundaries. To split by custom page ranges → switch to --granularity auto
L1 mode: pymupdf missing --granularity L1 requires PyMuPDF to read the TOC + split pages pip install --user --break-system-packages pymupdf; or switch --granularity auto to a single call (no pymupdf needed)
L1 mode: PDF has no TOC PDF has no embedded bookmarks / outline Script automatically falls back --granularity auto(stderr WARN message); to enforce strict L1 splitting → add bookmarks when regenerating the PDF
L1 mode: a certain L1 chapter failed The API call for that L1 page range threw an error (API rate limit / corrupted PDF, etc.) Script writes FAILED-<slug>.md placeholder + continues with subsequent L1 chapters; agent can separately --pages <失败页范围> --granularity auto re-run
L1 mode: File API upload failed For PDFs > 20MB, L1 mode relies on File API caching Script throws an error directly (does not silently fall back to inline—inline cannot be reused across calls); handling: 1) retry 2) --granularity auto use a single call 3) shrink the PDF
by-chapter output contains < 100B empty files Chapters abandoned by the model (truncation / missing content) Script automatically cleans up + stderr WARN count (00-index.md still contains the original references; manually delete or re-run if necessary)
503 UNAVAILABLE / 429 RESOURCE_EXHAUSTED still fails after 3 retries Main model temporarily unavailable / rate limited No end-to-end degradation——Script throws an error directly (including model name + status + three-step suggestion);After receiving this error, the agent must not switch models and re-run on its own, must truthfully report to the user, and the user decides whether to --model explicitly retry
Generated md contains ![图 N](PDF p.X ...) references Non-paper type or paper full mode output Automatic handling: Script strip_pdf_figure_refs cleans up at the end of main; if it appears, the prompt was missed during modification

Reference examples

5 end-to-end examples (single paper / product manual / whitepaper / book / auto-detect) have been moved to references/output-skeletons-and-examples.md §Reference examples ——Each example includes "user's original words → agent clarifying question → final bash call + output description".

Supporting references

  • 4 template skeletons + reference examples:references/output-skeletons-and-examples.md —— the moved-down layer of SKILL.md §C / §Reference examples (chapter skeleton blocks + 5 end-to-end examples)
  • Shared base conventions:assets/_base.md —— API calls / style baseline / character-count discipline / figure handling rules shared by the 4 templates
  • paper quick + full templates:assets/template-paper.md
  • manual template:assets/template-manual.md
  • whitepaper template:assets/template-whitepaper.md
  • book template:assets/template-book.md
  • API quick start:references/api-quickstart.md —— examples for calling the SDK directly + File API approach for very large PDFs
  • auto-detect implementation details:references/auto-detect.md —— heuristic keyword table + Gemini verification flow + failure fallback
  • paper quick figure export:references/figure-extraction.md —— Stage 1/2 + caption locator + bbox sanity check
  • Stage 2 / figure size / thumbnail parameters:references/figure-processing.md —— --refine-figures / --figure-dpi / --thumbnail and other detailed specifications
  • 4-class template quick reference:references/templates.md — dimension comparison table / template change rules / adding new type checklist
  • paper full contract:references/full-mode-contract.md —— --full mode output constraints / integrity validation / token budget

Prerequisites

1. Python ≥ 3.7
2. pip install -U google-genai
3. pip install --user --break-system-packages pymupdf   # paper quick 图导出 / auto-detect 需要
4. export GEMINI_API_KEY="你的 key"   # 在 https://aistudio.google.com/apikey 创建