Programming Agent Skills: A Practical Guide with Token Optimization

    This guide explains how to turn long technical documents into structured, on-demand skill packages for programming agents. It covers layered skill design, the conversion pipeline from raw material to skill package, token budgeting, parsing strategies by document type, quality checks, versioning, and common anti-patterns, helping you reduce context usage, improve retrieval accuracy, and lower hallucination and rework rates.

    1. Why Pasting an Entire Book into the Model Fails

    As programming agents become part of everyday development workflows, a recurring problem appears: models are familiar with common frameworks and standard algorithms, but they produce plausible-sounding yet unreliable answers when the topic involves internal team conventions, domain-specific terminology, or configuration details tied to a particular version. The traditional fix is to paste an entire technical manual or a full set of specification documents into the context at once, which usually backfires.

    There are three reasons. First, the context window is a finite resource. A full book can easily reach hundreds of thousands of tokens, leaving little room for the actual code, logs, and error messages. Second, attention dilution: when relevant content is surrounded by large amounts of unrelated text, the model’s accuracy in locating the key rules drops. Third, cost and latency grow roughly linearly with input length, and long contexts also slow down the first-token response.

    The industry has therefore converged on one approach: preprocess long documents into structured skill packages, and load only the fragments relevant to the current task at runtime. This is essentially a classic engineering tradeoff of space for time, and preprocessing for runtime work.

    2. Core Skill Package Design: Layering and On-Demand Loading

    A usable skill package is not a single large file but a collection of files with clear responsibilities. A typical layering looks like this:

    • Entry file: holds the overall mental model, scope, and section index, kept to a few thousand tokens, and serves as the minimal always-resident context.
    • Chapter files: one file per chapter, each self-contained and read on demand, typically around a thousand tokens each.
    • Glossary: key concepts sorted alphabetically or by pinyin, used for disambiguation and consistent wording.
    • Pattern library: reusable techniques, algorithms, and design patterns, describing which approach to use under which conditions.
    • Cheatsheet: decision rules compressed into tables or decision trees for frequent lookup.

    The key constraints are that the entry file must stay small and chapter files must stay independent. Once the entry file bloats, the always-resident cost spirals out of control. If chapter files contain many cross-references, on-demand loading degrades into chained loading, which cancels out the token savings.

    An illustrative directory and entry structure:

    1. skills/
    2. SKILL.md # mental model + section index (always resident)
    3. chapters/
    4. ch01-*.md # loaded on demand
    5. ch02-*.md
    6. glossary.md # term disambiguation
    7. patterns.md # solutions and anti-patterns
    8. cheatsheet.md # decision tables

    The entry file should keep only three kinds of information: what problem this skill solves and what it does not; a mapping of section titles to one-line summaries; and loading conventions covering when to read a chapter and when to check the glossary.

    1. # Skill: Engineering Practices for a Specific Domain
    2. ## Applicable Scenarios
    3. - Configuration and coding decisions that must follow specific version constraints
    4. ## Not Applicable
    5. - Latest features unrelated to the version covered here
    6. ## Section Index
    7. - ch01 Core Model and Boundaries | Keywords: constraints, prerequisites
    8. - ch02 Configuration and Deployment | Keywords: parameters, rollback
    9. ## Loading Conventions
    10. Read this file first to locate a section, then read only the matching chapter file

    3. Conversion Pipeline: From Raw Material to Skill Package

    The overall flow breaks into four steps. The first three are offline preprocessing; the fourth is runtime behavior.

    1. Collection and normalization. Unify encoding, strip headers, footers, and table-of-contents noise, and preserve heading levels, since heading hierarchy is the main basis for later splitting.
    2. Structure extraction. Identify three kinds of elements: frameworks, decision rules, and anti-patterns. A framework describes what parts the whole consists of; a decision rule describes choosing approach B when condition A is met; an anti-pattern describes a practice that looks reasonable but should be avoided.
    3. Splitting and indexing. Split along chapter boundaries, generate a summary and keywords for each chapter, and write them back into the entry file index. Consolidate terminology into the glossary so one concept does not end up with several names.
    4. On-demand reading at runtime. The user references a chapter with an explicit instruction, or the agent matches index keywords and then reads the corresponding file. Answers cite their source, which lowers the probability of hallucination.

    The engineering property of traceability deserves emphasis: every conclusion should point back to a specific chapter. This is both a means of reducing hallucination and an entry point for later human review.

    4. Token Budget: Making Savings a Measurable Metric

    Token optimization should not stay a slogan. Build a budget table and observe it continuously.

    • Resident budget: the sum of the entry file, glossary, and cheatsheet, with a cap, for example no more than 10% of the total budget.
    • Per-task budget: the resident part plus the number of matched chapters times the average chapter size. Matched chapters should be limited to 1 to 3.
    • Metrics to observe: average chapters loaded, input tokens per task, hit rate (matched chapters divided by loaded chapters), and answer rework rate.

    A simplified estimate:

    1. Input per request ≈ resident tokens + Σ(matched chapter tokens) + conversation and code context
    2. With 6000 resident, 1000 per chapter, and 2 matched chapters, the skill part is about 8000 tokens
    3. Compared with directly pasting a 300000-token book, the difference in scale is obvious

    If the hit rate stays low over time, the index keywords are not good enough. Go back to step 3 and redo the summaries and keywords instead of compressing chapter content further.

    5. Format and Parsing: Choosing a Strategy by Material Type

    Materials differ greatly in parsing difficulty and need to be handled by category.

    • Plain text (mostly prose and explanations, few tables): a general text extraction method is enough; the focus is preserving paragraph and heading structure.
    • Technical material (code blocks, tables, formulas): requires a parsing approach with stronger layout understanding, processed page by page. It is slower but preserves structure with higher fidelity. After parsing, verify that code blocks are complete and tables are not misaligned into wrong columns.
    • Image-based scans: optical character recognition must run before extraction, otherwise the result is empty text. After recognition, manually spot-check key tables and numbers.
    • Web pages and multi-source material: save them as local files first, then process them uniformly, which makes version tracking and rerunning after failure easier.

    The engineering recommendation is to make parsing a re-entrant pipeline: each step writes its output to disk with a checksum and retry on failure, so one failed parse does not force the whole flow to restart. With large data volumes, raw material and outputs can sit in object storage, parsing tasks can be driven by a message queue, a container platform can host the parsing and indexing services, and logs plus monitoring alerts can track failure rates and elapsed time.

    6. Quality Checks and Version Management

    Skill packages drift as material is updated, so they must be placed under version control.

    • Checklist: whether all chapters are covered, whether the index maps one-to-one to files, whether terminology is consistent, whether decision tables match the body text, and whether code examples run.
    • Regression testing: prepare a set of typical questions with key points for their standard answers, run them after each rebuild of the skill package, and watch for changes in hit rate and rework rate.
    • Version strategy: bind the skill package to the version of the source material, and record the source version and generation time in the entry file. When material is updated, incrementally rebuild only the affected chapters instead of rerunning everything.
    • Permissions and compliance: internal material still follows its original classification after conversion, and the skill package should not contain sensitive fragments unrelated to the task.

    7. Common Anti-Patterns

    • Writing the entry file as a long, directory-style document, so the resident cost spirals out of control.
    • Splitting chapters too finely, so one task triggers chained loading of a dozen or more files.
    • Extracting conclusions without keeping the applicable conditions, so the model applies rules under premises that do not hold.
    • Missing glossary, so one concept has several expressions and retrieval hit rate drops.
    • No source citations, so answers cannot be verified and the rework rate rises.

    8. Implementation Advice

    Start with a small-scale validation on a single domain and a single material set. Compress the entry file to under a few thousand tokens and keep chapters around a thousand tokens, then use hit rate and rework rate to judge whether it is worth expanding. After validation passes, chain parsing, indexing, checking, and publishing into a pipeline and plug it into the team’s continuous integration process, so skill packages are reviewed, tested, and rolled back like code. With general capabilities from cloud platforms such as Baidu AI Cloud, this architecture of separating offline preprocessing from runtime loading is relatively easy to scale elastically and observe, but the architectural gains still depend on splitting quality and index quality rather than the platform itself.