1 Why Add Summaries to a Blog
After the first five articles in this series, I have already implemented features such as “Series Article Cards”, “Related Articles”, and “Guess What You Want” after the main text of my blog articles. Combined with several “maps” and the “content structure prompts” of each article, my blog content has actually established connections both vertically and horizontally: the vertical connection is the structural link from the knowledge map to specific articles, while the horizontal connection is the thematic relationship between articles.
This means that readers can not only browse related articles along thematic clues, but also quickly locate a specific article through the overall map, or return to the overall map from a specific article. In this way, readers can freely switch between the overall knowledge framework and the content of individual articles, gaining a clearer understanding of the blog's thematic structure and content context.
However, there is still one shortcoming—each article still lacks an independent “summary” section.
Actually, I had considered this issue long ago, but I initially thought that the article's title, table of contents, and the content of the first chapter were enough for readers to understand the main backbone of the article, seemingly serving as a direct substitute for a summary.
However, as the number and length of blog articles increased (especially since I write quite a few long-form articles), I worried that many impatient visitors might give up reading directly when they see how long an article is. For these readers, if the cues from the title and table of contents are not intuitive enough to quickly judge whether a long article is worth reading in depth, it can easily lead to reader drop-off—especially in this era of short videos where people swipe away as soon as they lose interest.
Therefore, I believe it is necessary to introduce “summary” as an independent content layer in the blog system: on one hand, it helps readers quickly grasp the main idea of the article to decide whether to continue reading in depth; on the other hand, it also provides a foundation for the blog's internal semantic system, allowing the core information of each article to exist in a structured, editable, and reconstructible way.
After clarifying the importance of summaries for the reader experience and the blog system, the next question is: how do we actually implement summaries? Should they be completely handwritten? Or automatically generated through off-the-shelf plugins using cloud-based large language models? Or semi-automatically generated via custom scripts using a locally self-hosted large language model? How should the generated summaries be stored to ensure they are editable, reconstructible, and convenient for subsequent use in knowledge maps, recommendation systems, or search functions?
To address these questions, Chapter 2 will start from existing implementation methods and outline the two main paths of summary generation: traditional rule-based or statistical summary technologies, and generative summary solutions based on large language models, which have gradually become mainstream in the past two years. By comparing the basic principles and applicable scenarios of these two approaches, we will first establish an overall cognitive framework of “how summaries are generated.”
2 Existing Blog Summary Solutions
Before officially starting the implementation, we might as well look at several common summary solutions currently used in the blog field.
The earliest blog summaries were actually very simple, written manually by the authors. Many blog systems provide a dedicated summary field where authors can fill in a descriptive summary of the article content. The advantage of this is obvious: the summary content is completely controlled by the author, so it is usually the most accurate. However, the disadvantage is equally obvious—as the number of articles increases, the maintenance cost becomes higher and higher. For a blog that has already accumulated hundreds or even thousands of articles, writing a summary for each article individually is clearly not an easy task.
With the development of blog systems, automatic summaries gradually became popular. Taking WordPress as an example, its built-in Excerpt feature can automatically extract a portion of text from the article content as a summary. Some plugins further enhance this process, such as extracting the first paragraph of the article, truncating a fixed number of words, or filtering out a few key sentences through rule-based algorithms.
Strictly speaking, however, this type of solution is more like “content truncation” rather than “content understanding.” It can solve the automation problem, but it is difficult to truly summarize the core idea of an article. For technical articles with long lengths and multiple logical levels, the summaries generated in this way often only reflect the content at the beginning of the article and may not accurately represent the focus of the entire article.
In the past two or three years, with the development of large language models, AI summaries have gradually become the new mainstream solution. The biggest difference from traditional summaries is that AI no longer simply truncates parts of the article, but can understand the entire article and then reorganize the language to generate a new summary. Therefore, whether in terms of readability or content summarization capability, it usually achieves better results.
For a technical blog like mine, articles are generally long, and much of the content has strong contextual dependencies. The cost of manually maintaining summaries is too high, while traditional automatic summaries struggle to accurately summarize the main idea of the article. Therefore, an AI summary solution based on large language models naturally becomes the most worthwhile direction to try. However, even though they are all AI summaries, there are still significant differences between different implementation schemes.
Most blog AI summary features currently on the market usually exist in the form of plugins. For users, they only need to configure the API Key, and the plugin automatically handles the rest. The biggest advantage of this approach is simplicity and convenience, but at the same time, the summary generation process is often encapsulated inside the plugin. Users usually find it difficult to gain a deep understanding of how the article is processed, what content the model actually sees, what prompts are used, and how the final results are stored.
More importantly, the design goal of such plugins is often just to generate a summary that can be displayed to readers, so the focus is more on “whether it can quickly summarize the article content.” For me, however, this goal is not enough. Because many of my articles are long and often have strong logical relationships throughout, if the article is truncated before being sent to the model, or if the summary generation strategy does not match the article type, the final result may deviate from the focus the article actually wants to express.
At the same time, for a blog that is building a “lightweight knowledge index,” a summary is not just a piece of text displayed to readers. In my view, it is also a reusable data resource in itself. In the future, whether it is semantic search or other AI features, they may all rely on this summary data. Therefore, rather than just getting a summary result directly, I care more about how the summary is generated, whether it can be easily modified after generation, what data was used in the generation process, whether the final result meets my requirements, and whether it can be saved in the format I need.
Therefore, instead of choosing an off-the-shelf black-box solution, I prefer to start from the entire generation workflow and build a fully controllable summary system.
3 Design Ideas for the Blog Summary System
1 Overall Architecture Design
After deciding to add the article summary feature to the blog, I did not rush to study how to write the prompts, nor did I focus my attention on the large model itself at the beginning. Because for the entire system, the large model is just one of the links.
The real priority is: how to make summary generation a system that can be maintained over the long term and run continuously. If it's just about generating a summary for a single article, it is actually very simple. Just send the article content to the large model and save the returned result.
But when the target becomes the entire blog, the situation is completely different, for example:
- The blog has already accumulated hundreds of articles;
- New content will continue to be added in the future;
- Summary generation requires a certain amount of computing resources;
- The model might be replaced or the Prompt adjusted in the future;
- The WordPress front-end needs to read quickly, rather than calling the AI in real-time.
These factors determine that summary generation must adopt an offline pre-computation mode rather than a real-time generation mode.
I ultimately adopted a design idea similar to the previous “lightweight knowledge index”:
WordPress 原始内容
↓
summary-source.json
↓
summary-index.json
↓ summary-source.json; the second stage calls the large model based on this data to generate summaries, and finally outputs the summary-index.json。
From the results, this seems to add an extra step compared to directly generating the final summary file, but the benefit of doing so is that different stages are only responsible for their respective tasks: the data extraction stage is responsible for preparing the input; the AI generation stage is responsible for generating summaries; and the WordPress frontend is responsible for displaying the results. The three are independent of each other and will not be coupled.
For example, when the model needs to be replaced in the future, you only need to regenerate the summary file; when the summary generation strategy needs to be adjusted, there is no need to modify the WordPress frontend code; and if the article content changes, you only need to rebuild the corresponding data source, keeping the data flow of the entire system stable at all times.
In fact, this is also an approach I have increasingly leaned towards in my recent blog feature designs: first build a stable data layer, and then implement specific features based on that data layer.
Although doing so increases some upfront design work, it makes it much easier to expand features, adjust strategies, or maintain the system in the future.
2 summary-source.json: The Data Source for Summary Generation
After the overall architecture is determined, the first problem to solve is: what kind of data should be provided to the large model. Theoretically, you could directly send the article content exported from WordPress to the large model for processing, but after actual testing, I found that this is not an ideal solution.
On one hand, the raw WordPress data contains a large amount of information unrelated to summary generation, such as author, publication date, categories, tags, comment counts, and other content. Although this data is meaningful for the blog system, it is of little help for generating article summaries. On the other hand, if all data is directly handed over to the large model for processing, it will not only increase the context length but also raise the model's comprehension cost, ultimately affecting generation efficiency and stability.
Therefore, I decided to build a data source file specifically for large models before summary generation:summary-source.jsonThe purpose of this file is not for WordPress to use, but to serve as the input layer for the summary generation stage. In other words, it is essentially a preprocessed and filtered article dataset.
For each article, I ultimately retained the following core fields:
{
"id": 14310,
"title": "基于 Cloudflare 的 Emby 影视展示站改造:从公网发布到访问体验优化",
"url": "https://blog.xxx.com/technology/xxxxx/",
"headings": [
"1 问题背景",
"2 方案设计",
"3 访问体验优化"
],
"content": "文章正文内容..."
}
Among them,id is used to establish the correspondence with WordPress articles later;title is used to provide article topic information to the large model;headings is used to help the model understand the article structure; while content provides the actual content source. Among these fields, I believe the title and section structure are particularly important.
For human readers, when reading an article, they usually browse the title and table of contents first before deciding whether to dive into the body text. Large models actually share similar characteristics. When the model can obtain the article title and section structure in advance, it is often easier to understand the organization of the entire article, thereby generating more accurate summary content.
For example, for a Cloudflare tutorial, even if the model has not yet read the full body text, just seeing the title and the names of various sections is enough to roughly determine whether the article discusses cache rules, security protection, or Tunnel deployment. This structural information actually helps the model more quickly establish an overall understanding of the article content.
In addition, I also controlled the length of the input body text. The goal of summary generation is not to have the model reprocess the entire article, but to extract the core semantics of the article within a limited context. If a long article of tens of thousands of words is entirely fed into the model, it will not only significantly increase the generation time but may also introduce a large number of details unrelated to the summary goal, thereby reducing the consistency of the summary output. Therefore, the system will limit the input scale while retaining the title, section structure, and main body content.
Therefore, when building summary-source.json , I only retain the cleaned body content and appropriately limit the input length in the subsequent generation stage. This not only preserves the main information of the article but also keeps the generation time within an acceptable range.
The final formed summary-source.json can be understood as a layer of “summary generation data source” specifically prepared for large models. It does not assume display functions, nor does it participate in frontend logic; instead, it is responsible for converting the originally complex WordPress content into structured input suitable for AI processing.
Through this layer of preprocessing, the subsequent summary generation stage no longer faces cluttered raw article data, but a unified, stable, and controllable input format. This is also an important foundation for the entire summary system to be maintained long-term and continuously expanded.
3 summary-index.json: For Direct Consumption by WordPress
当 summary-source.json After preparation is complete, the second stage of the summary system begins. In this stage, the system will read the data in summary-source.json , call the locally deployed large model to generate article summaries, and write the final results into summary-index.json。
Unlike the previous AI input layer summary-source.json ,summary-index.json already belongs to the data layer facing the WordPress frontend. It no longer cares about the complete content of the article, nor does it need to retain various context information used for summary generation; instead, it only saves the data required for the final display.
Taking the article ”Cloudflare-Based Emby Media Showcase Site Transformation: From Public Release to Access Experience Optimization“ as an example, the currently generated data structure is as follows:
{
"14310": {
"version": "v1",
"source_version": "v1",
"title": "基于 Cloudflare 的 Emby 影视展示站改造:从公网发布到访问体验优化",
"summary": "针对家庭媒体服务器公网展示的挑战,本文通过Cloudflare Tunnel实现无公网IP的稳定发布,并围绕Emby系统进行多维度优化。核心问题包括家庭网络暴露风险、登录流程繁琐及资源加载延迟,解决方案涵盖Guest账号简化访问、Cloudflare缓存加速静态资源、Worker启动页优化首屏体验等。最终实现访问门槛降低、页面响应提速,形成可稳定运行的影视展示站,为个人收藏展示提供可行方案,同时为后续静态化架构演进奠定基础。",
"model": "qwen3:14b",
"updated": "2026-06-18 16:13:33"
}
}
As can be seen, compared to summary-source.json, the data structure here has become very simple: the entire file uses the article ID as the index key, with each article corresponding to an independent data object. This design has the direct benefit of extremely high query efficiency.
When a WordPress article page is opened, you only need to get the Post ID of the current article and then directly look up the corresponding record in the JSON:
当前文章 ID
↓
summary-index.json
↓
读取摘要
↓
页面展示
The entire process does not require database access, AI service calls, or any real-time computation.
For visitors, the summary content is almost indistinguishable from regular article content; for the server, the overhead of reading a local JSON file is almost negligible.
In addition toPost IDand the summary content (summary), I also retained a few auxiliary fields. Among them,version 和 source_version is used to record the data structure version. When adjusting the JSON format or modifying the summary generation strategy in the future, the compatibility relationship between different data can be quickly determined through the version number.model field is used to record the large model used during summary generation. Currently, my system uses the locally deployed Qwen3-14B, so the corresponding record is:
{
"model": "qwen3:14b"
}
This field is not necessary for frontend display, but I ultimately kept it. On one hand, it helps me track the summary source when changing models in the future; on the other hand, it can also directly display summary generation information on the article page, for example:
文章摘要
......
Qwen3-14B · 2026-06-018
This not only clarifies the summary source but also facilitates subsequent quality comparison and system maintenance.
Finally, updated The field records the generation time of the summary. Although it is of little significance to ordinary readers, for system maintenance, it helps determine whether the summary needs to be regenerated and whether the current cached data has expired.
From the perspective of system responsibility division,summary-index.json 's positioning is actually very clear:
- It is not AI input data;
- It is not responsible for summary generation;
- Nor does it participate in any complex calculations;
Its sole responsibility is to provide WordPress with a summary index that can be quickly read.
This design actually shares the same concept as the lightweight knowledge index system introduced earlier: all calculations are completed in the offline phase, while the frontend is only responsible for reading the results. The biggest advantage of this approach is that the computing resources consumed by summary generation are completely decoupled from user visits. Whether the number of articles increases to hundreds or thousands in the future, the frontend display logic will not change, and access performance will not be affected.
For a long-running personal blog, this pre-computation, light-consumption design pattern is often more stable and easier to maintain than real-time generation solutions.
4 Engineering Implementation
1 Data Source Construction: build_summary_source.py
After completing the structural design in the previous chapters, the next practical problem to solve is: how to extract article content from WordPress and generate a unified format of summary-source.json data source.
Although summary generation ultimately relies on large models, the model itself cannot directly read the content in the WordPress database. Therefore, before calling the model, the articles must first be converted into structured data.
To this end, I wrote the build_summary_source.py script, which is responsible for extracting article information from WordPress and generating the data source file required for subsequent processes.
The complete code of the script is as follows:
import requests
import re
import html
import json
import os
from urllib.parse import urlparse
BASE_URL = "http://127.0.0.1:50443"
# -------------------------
# 获取 WordPress 文章
# -------------------------
def fetch_posts(base_url):
posts = []
page = 1
while True:
url = f"{base_url}/wp-json/wp/v2/posts?page={page}&per_page=100"
resp = requests.get(url)
if resp.status_code != 200:
break
data = resp.json()
posts.extend(data)
total_pages = int(resp.headers.get("X-WP-TotalPages", 1))
print(f"Fetched page {page}/{total_pages}")
if page >= total_pages:
break
page += 1
return posts
# -------------------------
# URL -> Path
# -------------------------
def extract_path(url: str) -> str:
if not url:
return ""
return urlparse(url).path
# -------------------------
# 提取 headings
# -------------------------
def extract_headings(html_content):
headings = re.findall(
r"<h[1-6][^>]*>(.*?)</h[1-6]>",
html_content,
flags=re.IGNORECASE | re.DOTALL
)
result = []
for h in headings:
h = re.sub(r"<[^>]+>", "", h)
h = html.unescape(h).strip()
if h:
result.append(h)
return result
# -------------------------
# HTML 清洗
# -------------------------
def clean_html(raw_html):
text = raw_html or ""
# code
text = re.sub(
r"<pre.*?>.*?</pre>",
" ",
text,
flags=re.DOTALL | re.IGNORECASE
)
text = re.sub(
r"<code>.*?</code>",
" ",
text,
flags=re.DOTALL | re.IGNORECASE
)
# script/style
text = re.sub(
r"<script.*?>.*?</script>",
" ",
text,
flags=re.DOTALL | re.IGNORECASE
)
text = re.sub(
r"<style.*?>.*?</style>",
" ",
text,
flags=re.DOTALL | re.IGNORECASE
)
# figure
text = re.sub(
r"<figure.*?>.*?</figure>",
" ",
text,
flags=re.DOTALL | re.IGNORECASE
)
# img
text = re.sub(
r"<img[^>]*>",
" ",
text,
flags=re.IGNORECASE
)
# shortcode
text = re.sub(r"\[/?[^\]]+\]", " ", text)
# headings -> markdown
for level in range(1, 7):
text = re.sub(
rf"<h{level}[^>]*>",
"\n\n# ",
text,
flags=re.IGNORECASE
)
text = re.sub(
rf"</h{level}>",
"\n\n",
text,
flags=re.IGNORECASE
)
# paragraph
text = re.sub(
r"</?p[^>]*>",
"\n",
text,
flags=re.IGNORECASE
)
# br
text = re.sub(
r"<br\s*/?>",
"\n",
text,
flags=re.IGNORECASE
)
# ul / ol
text = re.sub(
r"</?(ul|ol)[^>]*>",
"\n",
text,
flags=re.IGNORECASE
)
# li
text = re.sub(
r"<li[^>]*>",
"\n- ",
text,
flags=re.IGNORECASE
)
text = re.sub(
r"</li>",
"",
text,
flags=re.IGNORECASE
)
# 删除剩余 HTML
text = re.sub(r"<[^>]+>", " ", text)
text = html.unescape(text)
# 删除 URL
text = re.sub(r"https?://\S+", " ", text)
# 特殊符号
text = re.sub(r"[丨||•·■◆►▶●]+", " ", text)
# 压缩空格
text = re.sub(r"[ \t]+", " ", text)
# 压缩空行
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
# -------------------------
# 构建正文
# -------------------------
def build_content(clean_text):
return clean_text.strip()
# -------------------------
# 构建 summary-source
# -------------------------
def build_summary_source(posts):
result = []
for post in posts:
raw_html = post.get("content", {}).get("rendered", "")
title = html.unescape(
post.get("title", {}).get("rendered", "")
)
post_id = str(post.get("id", ""))
url = extract_path(post.get("link", ""))
headings = extract_headings(raw_html)
clean_text = clean_html(raw_html)
article = {
"id": post_id,
"title": title,
"url": url,
"headings": headings,
"content_length": len(clean_text),
"content": build_content(clean_text)
}
result.append(article)
return result
# -------------------------
# 输出 JSON
# -------------------------
def write_json(data, filename="summary-source.json"):
base_dir = os.path.dirname(os.path.abspath(__file__))
output_path = os.path.join(base_dir, filename)
with open(output_path, "w", encoding="utf-8") as f:
json.dump(
data,
f,
ensure_ascii=False,
indent=2
)
print(f"\nSaved: {output_path}")
# -------------------------
# Main
# -------------------------
if __name__ == "__main__":
posts = fetch_posts(BASE_URL)
print(f"\nFetched posts: {len(posts)}")
summary_source = build_summary_source(posts)
print(
f"Built summary source: "
f"{len(summary_source)} articles"
)
write_json(summary_source)
if summary_source:
print("\nSample:\n")
print(
json.dumps(
summary_source[0],
ensure_ascii=False,
indent=2
)[:2000]
)
Functionally, this script mainly accomplishes three tasks: obtaining basic article information; extracting article structural content; and outputting a unified format JSON file.
The most important part is not the data acquisition itself, but the unification of the data format. What is stored in WordPress is content oriented towards page display, whereas the subsequent processing flow requires data oriented towards program consumption. Therefore, during the export process, information such as article titles, body text, and section structures needs to be reorganized into a unified data structure.
In the generated summary-source.json , each article will contain the article ID, title, URL, body content, and section titles mentioned in 3.2. In this way, the article content originally scattered in WordPress is converted into a data source file with a unified structure that is easy to process subsequently.
At this point, the system already has a structured data source that runs independently of the WordPress environment. In the future, whether it is summary generation, keyword extraction, or other AI processing workflows, operations can be performed directly based on this file without needing to access WordPress again.
2 Summary Generation: build_summary_index.py
当 summary-source.json After generation, the system actually already possesses the structured data of all articles. However, this data itself is still just raw content and cannot be directly used for frontend display.
The next problem to solve is: how to generate a summary for each article that can outline the core content, and solidify the results—this is precisely the responsibility of build_summary_index.py .
Unlike the previous build_summary_source.py , this script introduces a large model to participate in the processing: it reads the summary-source.jsongenerated in the previous step, calls the locally deployed Qwen3 model article by article to generate summaries, and then saves the results to /wp-content/themes/theme-directory/cache/summary-index.json .
The complete code of the script is as follows:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
import re
import time
from datetime import datetime
import requests
# 使用你已经验证可用的模型
MODEL = "qwen3:14b"
# 输出路径根据自己实际情况修改,我是以博客正在使用的argon主题为例
OUTPUT_FILE = "/docker/wordpress/html/wp-content/themes/argon-theme-master/cache/summary-index.json"
SOURCE_FILE = "summary-source.json"
# API地址需要根据实际情况修改
OLLAMA_URL = "http://127.0.0.1:11434/api/generate"
# 控制输入长度,避免超长文章拖慢 summary
MAX_CONTENT_LENGTH = 10000
# summary 长度限制
MIN_LEN = 80
MAX_LEN = 300
# 重试控制
MAX_RETRY = 2
REGEN_RETRY = 3
# -------------------------
# 排除“结构型页面 / 地图页”
# -------------------------
EXCLUDE_SLUGS = {
"me",
"map",
"cloudflaremap",
"aimap",
"singingmap",
"roadmap",
}
def is_excluded(article):
url = article.get("url", "")
for slug in EXCLUDE_SLUGS:
if f"/{slug}/" in url:
return True
return False
# -------------------------
# 读取 source
# -------------------------
def load_source():
base_dir = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(base_dir, SOURCE_FILE)
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
# -------------------------
# 加载 cache
# -------------------------
def load_cache():
if not os.path.exists(OUTPUT_FILE):
return {}
with open(OUTPUT_FILE, "r", encoding="utf-8") as f:
return json.load(f)
# -------------------------
# 原子写入
# -------------------------
def save_cache(cache):
# 按 id 从大到小排序
sorted_cache = dict(
sorted(
cache.items(),
key=lambda x: int(x[0]),
reverse=True
)
)
tmp_path = OUTPUT_FILE + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(
sorted_cache,
f,
ensure_ascii=False,
indent=2
)
os.replace(tmp_path, OUTPUT_FILE)
# -------------------------
# 摘要清洗
# -------------------------
def clean_summary(text):
text = text.strip()
text = re.sub(r"\s+", " ", text)
text = text.replace("\n", " ")
return text.strip()
# -------------------------
# Prompt
# -------------------------
def build_prompt(article):
title = article.get("title", "")
headings = "\n".join(article.get("headings", []))
content = article.get("content", "")[:MAX_CONTENT_LENGTH]
prompt = f"""
你是一名中文技术博客编辑。
任务:
阅读文章内容,生成一段面向读者的摘要。
摘要要求:
- 单段输出
- 中文摘要
- 优先控制在150~250字
- 如果原文较短,可低于120字
- 禁止出现“本文”“文章”“作者”“介绍”
- 必须覆盖:问题、方案、结果或收获
- 可以适当体现技术背景或应用场景
- 如果属于系列内容或体系化主题,可简要体现其关联方向
- 如果属于单篇实践内容,重点突出实际问题与解决经验;如果包含架构设计、实践过程或技术演进,应适当体现核心设计思路,而不仅描述操作步骤
- 不要简单复述章节标题
- 不要分析写作过程
- 不要虚构原文未提及的背景、效果或结论
- 不要将实验性探索描述为成熟方案
- 禁止分点
文章标题:
{title}
章节结构:
{headings}
正文:
{content}
只输出摘要:
""".strip()
return prompt
# -------------------------
# 调用 Ollama
# -------------------------
def call_llm(prompt):
payload = {
"model": MODEL,
"prompt": prompt,
"stream": False
}
resp = requests.post(
OLLAMA_URL,
json=payload,
timeout=120
)
resp.raise_for_status()
return clean_summary(
resp.json()["response"]
)
# -------------------------
# 修复生成
# -------------------------
def regenerate(last_summary):
prompt = f"""
以下摘要长度或质量不符合要求:
{last_summary}
请重新生成。
要求:
- 单段中文
- 控制在150~250字
- 覆盖问题、方案、结果或收获
- 可以体现技术背景或应用场景
- 不要简单复述标题
- 不要解释生成过程
- 不要分析写作过程
- 不要虚构原文未提及的信息
- 不要将实验性内容描述为成熟方案
- 不要出现“本文”“文章”“作者”
- 禁止分点
直接输出摘要:
""".strip()
return call_llm(prompt)
# -------------------------
# 校验
# -------------------------
def validate_summary(text):
length = len(text)
return MIN_LEN <= length <= MAX_LEN
# -------------------------
# cache entry
# -------------------------
def build_cache_entry(article, summary):
return {
"version": "v1",
"source_version": "v1",
"title": article.get("title", ""),
"summary": summary,
"model": MODEL,
"updated": datetime.now().strftime(
"%Y-%m-%d %H:%M:%S"
)
}
# -------------------------
# 主逻辑
# -------------------------
def build_cache():
source = load_source()
cache = load_cache()
source = [
article
for article in source
if not is_excluded(article)
]
total = len(source)
print(f"Total articles (after filter): {total}")
saved_count = 0
skipped_count = 0
failed_count = 0
for idx, article in enumerate(source, 1):
post_id = str(article.get("id"))
if post_id in cache:
skipped_count += 1
continue
print(f"[{idx}/{total}] Processing {post_id}...")
try:
prompt = build_prompt(article)
summary = None
for _ in range(MAX_RETRY):
summary = call_llm(prompt)
if validate_summary(summary):
break
if not validate_summary(summary):
success = False
for _ in range(REGEN_RETRY):
summary = regenerate(summary)
if validate_summary(summary):
success = True
break
if not success:
print(
f"Skip {post_id}: "
f"invalid summary length ({len(summary)})"
)
failed_count += 1
continue
cache[post_id] = build_cache_entry(
article,
summary
)
save_cache(cache)
saved_count += 1
print(f"Saved {post_id}")
time.sleep(0.3)
except Exception as e:
failed_count += 1
print(f"Failed {post_id}: {e}")
time.sleep(1)
print("\nFinished")
print(f"Saved: {saved_count}")
print(f"Skipped(existing): {skipped_count}")
print(f"Failed: {failed_count}")
# -------------------------
# main
# -------------------------
if __name__ == "__main__":
build_cache()
From an implementation perspective, the core task of this script is actually not calling the model, but how to make the model stably produce outputs that meet the requirements.
Theoretically, one could just hand the entire article directly to the large model and ask it to generate a summary. However, in actual operation, you will find that the output of large models is not always stable: sometimes the summary is too short, sometimes too long, and there may also be explanatory text, analysis processes, or even additional supplementary content.
Therefore, in the script, instead of directly submitting the raw WordPress text to the model indiscriminately, I added a layer of input control and Prompt constraints. First, the length of the input content is limited to prevent overly long articles from occupying too much of the context window, while reducing the interference of non-core content such as code and logs on summary generation. Second, the Prompt explicitly requires the summary to focus on the article's problems, technical solutions, and final results, and limits the output length range, thereby improving the consistency of summary results across different articles.
Even so, the local model still occasionally generates results that do not meet the requirements. To solve this problem, the script adds a length validation mechanism: when the length of the generated summary exceeds the preset range, it will automatically trigger a regeneration process; if it still fails to meet the requirements after multiple attempts, it will directly skip the current article and wait for the next execution to process it again.
Although this design increases a small amount of computational overhead, the benefit in return is that the quality of the entire summary library can remain relatively stable, without polluting the final results due to individual abnormal outputs.
Another important design is incremental updates. As the number of blog articles continues to grow, if all summaries are regenerated every time the script runs, it will not only waste computing resources but also significantly increase processing time. Therefore, the script will prioritize reading the already existing summary-index.json, directly skipping articles for which summaries have already been generated, and only processing newly added content.
In the finally generated summary-index.json , each article will save the summary content as well as related metadata, such as fields like model name and update time. Once generated, this data will be permanently saved. Subsequent visits to the blog will not need to call the model again, but can instead directly read the results.
At this point, the most computationally expensive part of the summary system is fully complete. What WordPress needs to do next is merely read the corresponding summary based on the article ID and display it on the page, without involving any further AI inference processes.
3 WordPress Summary Display Implementation
当 summary-index.json After the generation is complete, the most complex part of the entire summary system is actually over. At this point, the large model has completed all summary generation work, and WordPress no longer needs to call any AI services or perform additional calculations. For the frontend, what it faces is just an ordinary JSON file.
Therefore, the problem to be solved in the final step becomes very simple: when a user opens an article page, how to find the corresponding summary from the summary-index.json based on the current article ID and display it.
To achieve this goal, I chose to add a custom PHP function to the WordPress theme via a code snippets plugin (or functions.php) to read the summary index file before the article body is output, and insert the corresponding content into the page.
The implementation code is as follows:
add_filter('the_content', 'insert_ai_summary_before_content', 5);
function insert_ai_summary_before_content(content) {
if (!is_single()) {
returncontent;
}
static summary_index = null;
if (summary_index === null) {
file = get_theme_file_path('/cache/summary-index.json');
if (!file_exists(file)) {
return content;
}json = file_get_contents(file);summary_index = json_decode(json, true);
if (!is_array(summary_index)) {
return content;
}
}post_id = get_the_ID();
if (!isset(summary_index[post_id])) {
return content;
}item = summary_index[post_id];
summary =item['summary'] ?? '';
model =item['model'] ?? '';
updated =item['updated'] ?? '';
date = substr(updated, 0, 10);
// 模型显示优化
model_map = [
'qwen3:8b' => 'Qwen3-8B',
'qwen3:14b' => 'Qwen3-14B',
];model_label = model_map[model] ?? model;html = '';
// 外层容器(增强结构隔离)
html .= '<div class="article-summary-wrapper">';
// 上分隔线html .= '<div class="article-summary-divider"></div>';
// 内容主体
html .= '<div class="article-summary">';html .= '<div class="article-summary-title">文章摘要</div>';
html .= '<div class="article-summary-content">'
. nl2br(esc_html(summary)) .
'</div>';
html .= '<div class="article-summary-meta">'
. esc_html(model_label . ' · ' . date) .
'</div>';html .= '</div>';
// 下分隔线
html .= '<div class="article-summary-divider"></div>';html .= '</div>';
return html .content;
}
The entire implementation logic is not complex: first, the code will read thetheme-directory/cache/located in summary-index.json file, and parses it into an array structure. Since the summary data has already been generated during the offline phase, only a standard file read is required here, involving no model calls or network requests. Subsequently, using the current WordPress article ID as the index key, it searches for the corresponding record in the JSON data. Finally, if a match is found, it extracts the saved summary content, model information, generation time, and other fields; if no corresponding record is found, it directly returns the original article content, without affecting normal access.
The benefit of doing this is that even if the summary system stops running in the future or some articles have not yet had summaries generated, it will not affect the normal display logic of the blog itself.
From a system perspective, WordPress's responsibility here is very simple: it is not responsible for generating summaries, but only for displaying them. All complex calculations have already been completed in the offline phase, and frontend access is merely a single JSON query operation. For the server, this overhead is almost negligible.
Of course, simply displaying the summary is not enough. If a block of plain text is output directly, it can easily blend in with the main body content, and readers might not even realize at first glance that it is an independent article overview.
Therefore, in the actual implementation, I added a set of independent styles for the summary area to present it in the form of an information card.
The corresponding CSS is as follows:
.article-summary {
padding: 18px 22px;
background: rgba(0,0,0,0.03);
border: 1px solid rgba(0,0,0,0.08);
border-radius: 10px;
/* 👉 新增:整体阅读节奏 */
line-height: 1.65;
}
/* =========================
外层间距(摘要 vs TOC)
========================= */
.article-summary-wrapper {
margin: 30px 0 40px;
display: flow-root;
}
/* TOC 和摘要之间拉开距离 */
#toc_container {
margin: 40px 0 !important;
}
/* =========================
内部结构节奏(关键优化)
========================= */
.article-summary-title {
font-weight: 600;
margin-bottom: 12px;
}
.article-summary-content {
margin-bottom: 14px;
line-height: 1.7;
}
.article-summary-meta {
margin-top: 10px;
font-size: 12px;
opacity: 0.7;
}
/* =========================
夜间模式
========================= */
body.dark .article-summary,
[data-theme="dark"] .article-summary {
background: rgba(255,255,255,0.07);
border: 1px solid rgba(255,255,255,0.16);
box-shadow: 0 3px 12px rgba(0,0,0,0.28);
}
/* 夜间模式下的节奏保持一致(只微调可读性) */
body.dark .article-summary-title,
[data-theme="dark"] .article-summary-title {
opacity: 0.9;
}
body.dark .article-summary-meta,
[data-theme="dark"] .article-summary-meta {
opacity: 0.65;
}
The final effect is: the summary is located between the article title and the table of contents; it maintains a clear visual separation from the main body; it stays consistent with the overall style of the theme; and it is compatible with both light mode and dark mode.
Compared to inserting the summary directly into the main body content, this card-style display allows readers to quickly understand the general content of the entire article before diving into the main text. This is especially important for long-form technical articles.
Readers can often judge within tens of seconds whether this article meets their needs, thereby deciding whether to continue reading in depth or jump to other content.
The final summary display effect on the page is as follows:

At this point, the data flow of the entire summary system has formed a complete closed loop: from article content extraction and summary generation to the final page display, all work is completed locally, without relying on third-party online services, and without the need to call large models in real-time when users visit.
5 Summary
This article completes the construction of the semantic layer in the “lightweight knowledge index” system: by summary-source.json structurally organizing the original WordPress articles, and then by summary-index.json solidifying the AI-generated results, the blog content has, for the first time, a layer of semantic expression independent of the original articles.
This stage of focus is not simply to add an article summary feature, but to establish a stable data transformation workflow: converting original content into reusable semantic units and reducing frontend runtime complexity through offline generation.
Currently, this semantic layer is mainly used for displaying article summaries, helping readers quickly understand the article content. However, from a system design perspective, the summary itself is not the ultimate goal; more importantly, it establishes a unified semantic data foundation for the blog. In other words, what this article achieves is the conversion from “article content” to “semantic expression,” giving the blog content, for the first time, a semantic description capability that can be further processed.
And when this semantic data is no longer just used for display, but begins to participate in the association and organization between articles, the information structure of the blog will also enter the next stage: evolving from a simple content index into a content space based on semantic relationships.
The next article will continue to build on this semantic foundation, exploring how to use existing article data and summary data to construct a higher-level content organization mechanism.