提示词库建设与知识沉淀
High Contrast
Dark Mode
Light Mode
Sepia
Forest
2 min read409 words

提示词库建设与知识沉淀

好的提示词是稀缺资产。把个人摸索出的提示词沉淀成团队知识库,让每个人都站在最高起点上工作。

提示词知识库架构

graph TD SOURCE[提示词来源] --> LIBRARY[团队提示词库] SOURCE --> S1[个人实践发现] SOURCE --> S2[团队分享贡献] SOURCE --> S3[外部优质模板] SOURCE --> S4[AI 自动生成] LIBRARY --> MANAGE[管理机制] MANAGE --> M1[质量评分] MANAGE --> M2[版本控制] MANAGE --> M3[使用统计] MANAGE --> M4[定期淘汰] LIBRARY --> ACCESS[获取方式] ACCESS --> A1[Notion 数据库] ACCESS --> A2[Claude Project KB] ACCESS --> A3[团队 Slack Bot] ACCESS --> A4[命令行工具] style LIBRARY fill:#c8e6c9,stroke:#388e3c,stroke-width:2px style MANAGE fill:#e3f2fd,stroke:#1565c0,stroke-width:2px

提示词库系统实现

"""
团队提示词知识库 — 构建、管理与分发系统
"""
import json
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from pathlib import Path
import re
class PromptCategory(Enum):
CODE = "代码开发"
WRITING = "写作文档"
ANALYSIS = "数据分析"
COMMUNICATION = "沟通邮件"
RESEARCH = "调研学习"
MEETING = "会议管理"
CUSTOMER = "客户服务"
MANAGEMENT = "团队管理"
class PromptQuality(Enum):
DRAFT = "草稿"      # 个人测试中
TESTED = "已验证"   # 多次使用有效
STANDARD = "团队标准"  # 推荐使用
DEPRECATED = "已淘汰"  # 不再推荐
@dataclass
class PromptTemplate:
"""提示词模板"""
id: str
title: str
category: PromptCategory
template: str
variables: list[str]           # 模板中的变量名 {variable}
example_input: dict            # 示例输入
example_output: str            # 预期输出示例
quality: PromptQuality = PromptQuality.DRAFT
author: str = ""
use_count: int = 0
avg_rating: float = 0.0
created_at: str = field(default_factory=lambda: datetime.now().strftime("%Y-%m-%d"))
tags: list[str] = field(default_factory=list)
notes: str = ""                # 使用注意事项
def render(self, **kwargs) -> str:
"""填充变量生成实际提示词"""
result = self.template
for key, value in kwargs.items():
result = result.replace(f"{{{key}}}", str(value))
# 检查未填充的变量
unfilled = re.findall(r'\{(\w+)\}', result)
if unfilled:
raise ValueError(f"未填充的变量: {unfilled}")
return result
def to_markdown(self) -> str:
"""导出为 Markdown 文档"""
vars_str = ", ".join(f"`{{{v}}}`" for v in self.variables)
return f"""## {self.title}
**分类**: {self.category.value} | **质量**: {self.quality.value}
**使用次数**: {self.use_count} | **评分**: {self.avg_rating:.1f}/5.0
**标签**: {', '.join(self.tags)}
### 模板变量
{vars_str if self.variables else '无变量(直接使用)'}
### 提示词

{self.template}


### 使用示例
输入: {json.dumps(self.example_input, ensure_ascii=False)}
输出预览:
> {self.example_output[:200]}{'...' if len(self.example_output) > 200 else ''}
{f'> ⚠️ 注意: {self.notes}' if self.notes else ''}
"""
class PromptLibrary:
"""团队提示词库"""
def __init__(self, library_path: str = "~/.ai-hub/prompts"):
self.library_path = Path(library_path).expanduser()
self.prompts: dict[str, PromptTemplate] = {}
self._load_starter_library()
def _load_starter_library(self):
"""加载入门提示词库"""
starter_prompts = [
PromptTemplate(
id="code-review-001",
title="代码安全审查",
category=PromptCategory.CODE,
template="""作为资深安全工程师,审查以下 {language} 代码的安全问题:
```{language}
{code}

请检查: 1. OWASP Top 10 漏洞(SQL注入/XSS/CSRF等) 2. 敏感数据处理(是否明文存储/传输) 3. 权限验证(是否有认证绕过风险) 4. 依赖库安全(已知 CVE)

输出格式: - [严重] 问题描述 + 修复建议 - [中等] 问题描述 + 修复建议 - [低] 问题描述(可选修复)""", variables=["language", "code"], example_input={"language": "Python", "code": "def get_user(id): return db.query(f'SELECT * FROM users WHERE id={id}')"}, example_output="[严重] SQL 注入漏洞:f-string 直接拼接用户输入。修复:使用参数化查询 db.query('SELECT * FROM users WHERE id=?', (id,))", quality=PromptQuality.STANDARD, use_count=156, avg_rating=4.8, tags=["安全", "代码审查", "OWASP"], notes="对于 LLM 生成的代码尤其有用,但仍需人工二次确认严重问题", ), PromptTemplate( id="email-followup-001", title="跟进邮件生成", category=PromptCategory.COMMUNICATION, template="""写一封专业的跟进邮件:

上次联系时间:{last_contact}({days_ago}天前) 对方姓名:{name} 跟进主题:{topic} 期望结果:{desired_outcome} 语气:{tone}

要求: - 开门见山(第一句话) - 总长度 80-120 字 - 末尾一个明确的 CTA(行动呼吁) - 不要用"希望此邮件找到您一切安好"这类套话""", variables=["last_contact", "days_ago", "name", "topic", "desired_outcome", "tone"], example_input={ "last_contact": "2026-03-10", "days_ago": "13", "name": "David", "topic": "产品演示后续合作", "desired_outcome": "确认下周会议时间", "tone": "友好但明确" }, example_output="David,上周演示后您提到需要时间评估,想确认一下您的时间安排。我们下周二或三是否方便 30 分钟通话讨论具体合作细节?", quality=PromptQuality.STANDARD, use_count=89, avg_rating=4.6, tags=["邮件", "跟进", "销售"], ), PromptTemplate( id="data-analysis-001", title="数据洞察生成", category=PromptCategory.ANALYSIS, template="""分析以下 {data_type} 数据,提供业务洞察:

数据:

业务背景:{context}

请提供: 1. 核心发现(3条,每条用数字支撑) 2. 异常/机会点(如有) 3. 行动建议(2条,具体可执行)

格式:适合在 Slack 发送,用表情符号和简短要点""", variables=["data_type", "data", "context"], example_input={ "data_type": "销售漏斗", "data": "访问:10000, 注册:500(5%), 付费:50(10%), 复购:20(40%)", "context": "SaaS 产品,目标是提升付费转化" }, example_output="📊 核心发现:\n1. 访问→注册转化 5%(行业均值 3%,表现良好)\n2. 注册→付费 10%(可提升空间大,行业标杆 20%)\n3. 复购率 40%(健康)\n\n🎯 建议:\n1. 优化注册后 7 天 Onboarding 流程\n2. 测试免费试用期从 7 天延至 14 天", quality=PromptQuality.STANDARD, use_count=67, avg_rating=4.5, tags=["数据分析", "洞察", "Slack"], ), PromptTemplate( id="meeting-agenda-001", title="会议议程生成", category=PromptCategory.MEETING, template="""为以下会议生成清晰的议程:

会议目的:{purpose} 参会人:{attendees} 时长:{duration} 分钟 需要做决策的事项:{decisions_needed}

生成议程格式: - 每个议题:时间分配 + 负责人 + 预期产出 - 开始5分钟留给 check-in - 结束5分钟留给行动项确认 - 标注哪些是讨论(D)哪些是决策(✓)哪些是告知(I)""", variables=["purpose", "attendees", "duration", "decisions_needed"], example_input={ "purpose": "Q2 产品路线图对齐", "attendees": "PM Alice, Tech Lead Bob, Design Carol", "duration": "60", "decisions_needed": "功能优先级排序,发布时间确认" }, example_output="09:00 Check-in (5min)\n09:05 Q2 目标回顾 (10min) [I] Alice\n09:15 功能优先级讨论 (20min) [D] 全员 → 产出: P0/P1/P2 列表\n09:35 时间线确认 (15min) [✓] Bob → 产出: 发布日期\n09:50 设计资源分配 (5min) [D] Carol\n09:55 行动项 + 下次会议 (5min)", quality=PromptQuality.STANDARD, use_count=43, avg_rating=4.7, tags=["会议", "议程", "效率"], ), PromptTemplate( id="technical-doc-001", title="技术决策记录(ADR)", category=PromptCategory.WRITING, template="""生成一份架构决策记录(ADR):

决策标题:{title} 背景/问题:{context} 考虑过的方案:{options_considered} 最终选择:{decision} 决策理由:{rationale} 影响范围:{consequences}

ADR 格式(Markdown):

ADR-{number}:

状态(草稿/已接受/已废弃)

背景

决策

方案对比

结果与影响

参考""",

            variables=["title", "context", "options_considered", "decision", "rationale", "consequences", "number"],
example_input={
"title": "API 认证方案选择",
"context": "需要为新 API 选择认证方式",
"options_considered": "JWT / Session / API Key",
"decision": "JWT with refresh token",
"rationale": "无状态,支持微服务扩展",
"consequences": "需要实现 Token 刷新逻辑",
"number": "005"
},
example_output="# ADR-005: API 认证方案选择\n## 状态:已接受\n## 背景\n新 API 需要一个安全且可扩展的认证方式...",
quality=PromptQuality.TESTED,
use_count=28, avg_rating=4.4,
tags=["架构", "ADR", "技术文档"],
),
]
for p in starter_prompts:
self.prompts[p.id] = p
def search(self, query: str, category: PromptCategory | None = None) -> list[PromptTemplate]:
"""搜索提示词"""
results = []
query_lower = query.lower()
for prompt in self.prompts.values():
if category and prompt.category != category:
continue
if (query_lower in prompt.title.lower() or
query_lower in prompt.template.lower() or
any(query_lower in tag for tag in prompt.tags)):
results.append(prompt)
return sorted(results, key=lambda p: p.use_count, reverse=True)
def top_prompts(self, n: int = 5) -> list[PromptTemplate]:
"""获取最高分提示词"""
return sorted(
[p for p in self.prompts.values() if p.quality == PromptQuality.STANDARD],
key=lambda p: (p.avg_rating, p.use_count),
reverse=True
)[:n]
def export_markdown(self, output_path: str = "prompt-library.md") -> str:
"""导出完整提示词库为 Markdown"""
lines = ["# 团队提示词库\n", f"共 {len(self.prompts)} 个提示词\n\n"]
by_category: dict[PromptCategory, list[PromptTemplate]] = {}
for p in self.prompts.values():
by_category.setdefault(p.category, []).append(p)
for cat, prompts in sorted(by_category.items(), key=lambda x: x[0].value):
lines.append(f"# {cat.value}\n")
for p in sorted(prompts, key=lambda x: -x.use_count):
lines.append(p.to_markdown())
content = "\n".join(lines)
Path(output_path).write_text(content, encoding="utf-8")
return content

演示

library = PromptLibrary()

print("=== 团队提示词库 ===\n") print(f"总提示词数: {len(library.prompts)}\n")

print("Top 5 最高评分提示词:") for p in library.top_prompts(5): print(f" ★ {p.avg_rating:.1f} [{p.use_count}次] {p.title} ({p.category.value})")

print("\n搜索示例: '安全'") results = library.search("安全") for p in results: print(f" → {p.title}")

print("\n渲染示例(跟进邮件):") followup = library.prompts["email-followup-001"] try: rendered = followup.render( last_contact="2026-03-10", days_ago="13", name="David", topic="产品合作", desired_outcome="确认会议时间", tone="友好", ) print(rendered[:300] + "...") except ValueError as e: print(f"错误: {e}") ```

提示词库管理规范

质量等级 标准 维护要求
草稿 个人测试中 每月评估升级或删除
已验证 >5 次使用,效果稳定 季度复查
团队标准 评分 >4.0,使用 >20 次 每半年重新验证
已淘汰 模型升级后失效 标注原因,保留参考

行动清单

本书完:你已经掌握了从 Claude Chat 到 Claude Code、从个人使用到团队协作、从桌面到移动端的完整 AI 工作流。 继续探索 claude-skills-guide 深入学习 Skills 开发,或 mcp-guide 构建自己的 MCP 工具。