Format Agent
Automatically reformats messy Word documents (.docx) according to given specifications. The AI understands, the code executes, and JSON connects them.
Capabilities
- Supports two format sources: natural language specification text (.txt) and properly formatted Word templates (.docx)
- Any well-formatted document can serve as a template: committee/board/shareholder meeting materials, contracts, legal opinions, consulting reports, theses, press releases... The Agent reads its font, font size, line spacing, indentation, and numbering conventions and applies them to the target document
- Supports unstructured documents (relying on model semantic judgment for paragraph roles) and numbered documents with manual numbering (1., (1), 1), clause numbering (Chapter 1, Article 1), or Word auto-numbering—deterministic recognition
- Page-level: margins, line grid, headers and footers (including page number fields)
- Paragraph-level: font/font size/bold/alignment/line spacing/first-line indent/numbering
- Table-level: first row header (bold/centered), cell font/size/alignment, borders
- Roles not specified in the template automatically match body text
- Zero changes to body text content: automatic text consistency check after each formatting run (compares original and final texts paragraph by paragraph); any text additions or deletions are explicitly reported
- Table of contents: auto-generated when the template contains a TOC field (updates when opened in Word); multi-column layout: supported (applicable for university double-column theses)
- Current version does not reformat: cover page design; preserves complex merged cell table structures as-is
Environment Requirements
- Python 3.10+, dependencies:
pip install -r requirements.txt(python-docx, requests, PyMuPDF; Windows rendering additionally requires pywin32) - No model configuration needed in Agent environments: understanding is done by the host Agent (see "Usage 1")
- Model configuration is only needed for standalone API mode (without an Agent environment):
Environment variables /
.envfile:LLM_BASE_URL,LLM_API_KEY,LLM_MODEL(optionalLLM_VISION_MODEL,LLM_TIMEOUT,LLM_TEMPERATURE)
Model Selection (Important: Multimodal Recommended)
This skill is not tied to any specific model; any OpenAI-compatible endpoint works. However, a multimodal model is recommended (supports both text and image input, such as GPT-4o, Kimi K3, Qwen-VL, GLM-4V, etc.):
- Main formatting workflow (rule extraction, role labeling) only requires text capabilities
- Visual self-check (--verify) requires passing rendered images to the model for quality inspection – text-only models cannot use this step
Instructions for the calling Agent: Before starting, confirm which model is currently being used and whether it has multimodal (image input) capabilities. If the current model lacks multimodal capabilities, proactively prompt the user: "The current model does not support image input, so visual self-check will be unavailable. It is recommended to switch to a multimodal model (e.g., XXX) for automatic quality inspection after formatting, which yields better results." Proceed only after user confirmation.
Usage
This skill has two usage modes. In an Agent environment, prefer "Built-in Smart Mode" – zero configuration, no API keys needed, understanding done by you (the host Agent).
Usage 1: Agent Built-in Smart Mode (Default Recommended, Zero Configuration)
Your execution flow as the host Agent:
-
Extract target document structure:
python main.py --extract-only --target 待排版.docx --out 输出目录/排版后.docxOutput:
输出目录/排版后_paragraphs.json, each paragraph containsidx/text/size_pt/bold/alignment/style_name/in_tableand numbering metadata. -
You produce the FormatSpec (format rule JSON):
- If the user provides specification text: understand it, write JSON according to the schema below, and save to
输出目录/排版后_formatspec.json; - If the user provides a template docx: run
--extract-onlyon the template first, understand the role of each paragraph (title/body/signature...), write模板_rolemap.json(format{"0": "title", "1": "body", ...}), then use--template 模板.docx --template-rolemap-json 模板_rolemap.jsonto let the code deterministically read template formatting.
FormatSpec schema:
{ "page": {"margin": {"top_mm": 37, "bottom_mm": 35, "left_mm": 28, "right_mm": 26}, "line_grid": {"line_pt": 28}}, "roles": { "body": {"font_eastasia": "仿宋_GB2312", "font_ascii": "Times New Roman", "size_pt": 16, "bold": false, "alignment": "justify", "first_line_indent_chars": 2, "line_spacing": {"type": "exact", "pt": 28}} } }Role enumeration:
title/subtitle/heading_1/heading_2/heading_3/body/signature/date/attachment_label/attachment/other.bodyis required; alignment valuesleft/center/right/justify;size_pt872, margins 550mm. Do not write roles not mentioned in the specification, and do not invent fields not mentioned. - If the user provides specification text: understand it, write JSON according to the schema below, and save to
-
You produce the RoleMap (paragraph role JSON): Read the paragraph list from step 1, assign a role from the enumeration to each paragraph where
in_table=false, and save to输出目录/排版后_rolemap.jsonin format{"0": "title", "1": "body", ...}– must cover all non-table paragraphs. Basis for judgment: text content, position order, current formatting hints; signature at the end has a strong signing feel; date contains year/month/day; title at the beginning and forms a standalone line. -
Execute formatting (deterministic code takes over):
# Specification text source (FormatSpec produced by you in step 2) python main.py --spec-json 输出目录/排版后_formatspec.json \ --rolemap-json 输出目录/排版后_rolemap.json \ --target 待排版.docx --out 输出目录/排版后.docx # Template source python main.py --template 模板.docx --template-rolemap-json 模板_rolemap.json \ --rolemap-json 输出目录/排版后_rolemap.json \ --target 待排版.docx --out 输出目录/排版后.docxThe JSON you produce will be re-validated by the code (role legality, full paragraph coverage, value boundaries); validation failure results in an error with explanation; correct and rerun.
Usage 2: Standalone API Mode (Optional)
Only configure a model in environments without an Agent (server, scheduled tasks, local bare run):
Copy .env.example to .env, fill in LLM_BASE_URL / LLM_API_KEY / LLM_MODEL (multimodal recommended, see above), then:
# Specification text as format source (LLM auto-extracts rules)
python main.py --spec 规范文字.txt --target 待排版.docx --out 输出目录/排版后.docx
# Word template as format source
python main.py --template 模板.docx --target 待排版.docx --out 输出目录/排版后.docx
Any document that has been properly formatted can serve as a template (committee meeting materials, contract templates, legal opinions, consulting reports, sample theses...); no modification or annotation is needed for the template.
Visual Self-Check (Optional, Usage 2 Only + Multimodal Model)
Add --verify: renders the formatted document as images, uses the vision model to check against specifications, detects deviations, fixes them directionally, and reformats once (single pass, no open loop). In Usage 1, if you (the host Agent) have image understanding capabilities, you can also render and inspect: the output directory *_verify_render/ contains page-by-page PNGs.
Output Artifacts
Each run produces (same directory, same filename prefix):
排版后.docx– clean document with named styles排版后_tracked.docx– Track Changes mode: Word review view shows every format change, can be accepted/rejected one by one排版后_report.docx/.md– comparison report (page setup, rules, paragraph details)排版后_formatspec.json/_rolemap.json/_stylemap.json– intermediate artifacts ("evidence of understanding" for review)
Troubleshooting Quick Reference
Missing LLM configuration→ Check .env or environment variables- Role labeling repeatedly fails → Model JSON output unstable; switch to
--rolemap-jsonmanual labeling - Vision review 400 temperature → This model only allows temperature = 1; set
LLM_TEMPERATURE = 1in .env - Vision review reports image error → Endpoint does not support data:base64 inline images, or current model lacks image input capability; switch to multimodal model
- Rendering fails → Windows requires Word installed (via COM), macOS/Linux requires LibreOffice
examples/ Directory
messy.docx: Sample document with messy formatting (a notice)spec.txt: Sample document formatting specification textspec_std.json/rolemap_std.json: Standard answers for the above examples (acceptance benchmark + fallback input)模板-党委会议题样表.docx: Template mode format source example