关于 prompt-template-builder
prompt-template-builder 是用于设计可复用提示词的技能,通过明确变量、输出约定、示例和约束来保持输出一致,适合构建 LLM 任务,并涵盖验证、测试、提示词链和版本管理。
主要功能
- 01系统与用户提示词结构
- 02基于变量的模板
- 03输出约定与架构验证
- 04少样本示例和风格规则
- 05提示词链与版本管理
- 06测试用例和输入验证
适用场景
- 01统一代码审查提示词
- 02要求生成结构化 JSON 输出
- 03通过示例测试提示词行为
- 04维护提示词模板的版本
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ patricio0312rev/ skills --skill prompt-template-builder安装后在 Claude Code 中输入/prompt-template-builder确认已加载。
详细介绍
提示词模板构建器
构建稳健、可复用的提示词模板,明确约定并确保输出一致。
核心组件
系统提示词:角色、人物设定、约束、输出格式 用户提示词:任务、上下文、变量、示例 少样本示例:展示预期行为的输入/输出对 输出约定:严格的格式规范(JSON schema、Markdown 结构) 风格规则:语气、详略程度、格式偏好 防护措施:注意事项、安全约束
系统提示词模板
# System Prompt: Code Review Assistant
You are an expert code reviewer specializing in {language} and {framework}. Your role is to provide constructive, actionable feedback on code quality, best practices, and potential issues.
## Output Format
Provide your review in the following JSON structure:
```json
{
"summary": "Brief 1-2 sentence overview",
"issues": [
{
"severity": "critical|major|minor",
"line": number,
"message": "Description of the issue",
"suggestion": "How to fix it"
}
],
"strengths": ["List of positive aspects"],
"overall_score": 1-10
}
```
风格指南
- 提出有建设性且具体的意见
- 针对问题注明行号
- 提供可执行的建议
- 兼顾批评与肯定
- 语气专业、尊重
约束
- 不要建议不必要的重构
- 要关注正确性、安全性和性能
- 不要过分拘泥于风格细节
- 要考虑上下文和项目需求
## User Prompt Template with Variables
```typescript
// prompt-templates/code-review.ts
export const codeReviewPrompt = (variables: {
language: string;
framework: string;
code: string;
context?: string;
}) => `
Please review the following ${variables.language} code:
${variables.context ? `Context: ${variables.context}\n` : ''}
\`\`\`${variables.language}
${variables.code}
\`\`\`
Provide a thorough code review following the output format specified in the system prompt.
`;
// Usage
const prompt = codeReviewPrompt({
language: 'typescript',
framework: 'React',
code: userSubmittedCode,
context: 'This is a production component for user authentication',
});
少样本示例
# Few-Shot Examples
## Example 1: Good Code
**Input:**
```typescript
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0);
}
```
输出:
{
"summary": "Clean, type-safe implementation with no issues found.",
"issues": [],
"strengths": [
"Type safety with TypeScript",
"Functional approach with reduce",
"Clear, descriptive naming"
],
"overall_score": 9
}
示例 2:存在问题的代码
输入:
function calc(arr) {
let total = 0;
for (var i = 0; i < arr.length; i++) {
total = total + arr[i].price;
}
return total;
}
输出:
{
"summary": "Functional but has type safety and modern syntax issues.",
"issues": [
{
"severity": "major",
"line": 1,
"message": "Missing type annotations for parameters and return value",
"suggestion": "Add types: function calc(arr: Item[]): number"
},
{
"severity": "minor",
"line": 3,
"message": "Using 'var' instead of 'let' or 'const'",
"suggestion": "Replace 'var' with 'let': for (let i = 0; ...)"
}
],
"strengths": ["Logic is correct", "Handles empty array case"],
"overall_score": 6
}
## Output Contracts
```typescript
// Define strict output schema
import { z } from 'zod';
export const codeReviewSchema = z.object({
summary: z.string().min(10).max(200),
issues: z.array(z.object({
severity: z.enum(['critical', 'major', 'minor']),
line: z.number().int().positive(),
message: z.string(),
suggestion: z.string(),
})),
strengths: z.array(z.string()),
overall_score: z.number().int().min(1).max(10),
});
// Validate LLM output
export const parseCodeReview = (output: string) => {
try {
const parsed = JSON.parse(output);
return codeReviewSchema.parse(parsed);
} catch (error) {
throw new Error('Invalid code review output format');
}
};
模板变量
export interface PromptVariables {
// Required
required_field: string;
// Optional with defaults
optional_field?: string;
// Constrained values
severity_level: "low" | "medium" | "high";
// Numeric with ranges
max_tokens: number; // 1-4096
}
export const buildPrompt = (vars: PromptVariables): string => {
// Validate variables
if (!vars.required_field) {
throw new Error("required_field is required");
}
// Set defaults
const optional = vars.optional_field ?? "default value";
// Build prompt
return `Task: ${vars.required_field}
Options: ${optional}
Severity: ${vars.severity_level}`;
};
风格规则
## Tone Guidelines
- **Professional**: Formal language, no slang
- **Friendly**: Conversational but respectful
- **Technical**: Precise terminology, assume expertise
- **Educational**: Explain concepts, teach as you go
## Verbosity Levels
- **Concise**: 1-2 sentences, bullet points
- **Standard**: 1 paragraph per point
- **Detailed**: Full explanations with examples
- **Comprehensive**: Deep dive with references
## Formatting Preferences
- Use markdown headers for structure
- Bold important terms
- Code blocks for technical content
- Lists for enumeration
- Tables for comparisons
注意事项
## Do's
✓ Provide specific, actionable feedback
✓ Include code examples when relevant
✓ Reference line numbers for issues
✓ Suggest concrete improvements
✓ Balance criticism with praise
✓ Consider context and constraints
## Don'ts
✗ Don't be vague ("this is bad")
✗ Don't suggest unnecessary rewrites
✗ Don't ignore security issues
✗ Don't be overly pedantic
✗ Don't assume unlimited resources
✗ Don't make assumptions without context
提示词链式调用
// Multi-step prompts
export const chainedPrompts = {
step1_analyze: (code: string) => `
Analyze this code and identify potential issues:
${code}
List issues in JSON array format with severity and description.
`,
step2_suggest: (issues: Issue[]) => `
Given these code issues:
${JSON.stringify(issues)}
Provide detailed fix suggestions for each issue.
`,
step3_summarize: (suggestions: Suggestion[]) => `
Summarize these code review suggestions into a final report:
${JSON.stringify(suggestions)}
`,
};
// Execute chain
const issues = await llm(chainedPrompts.step1_analyze(code));
const suggestions = await llm(chainedPrompts.step2_suggest(issues));
const report = await llm(chainedPrompts.step3_summarize(suggestions));
版本控制
// Track prompt versions
export const PROMPT_VERSIONS = {
"v1.0": {
system: "Original system prompt...",
user: (vars) => `Original user prompt...`,
deprecated: false,
},
"v1.1": {
system: "Improved system prompt with better constraints...",
user: (vars) => `Updated user prompt...`,
deprecated: false,
changes: "Added JSON schema validation, improved examples",
},
"v1.0-deprecated": {
system: "...",
user: (vars) => `...`,
deprecated: true,
deprecation_reason: "Replaced by v1.1 with better output format",
},
};
// Use specific version
const prompt = PROMPT_VERSIONS["v1.1"];
测试提示词
// Test cases for prompt validation
const testCases = [
{
input: { code: "function test() {}", language: "javascript" },
expected: {
hasIssues: false,
scoreRange: [8, 10],
},
},
{
input: { code: "func test(arr) { return arr[0] }", language: "javascript" },
expected: {
hasIssues: true,
minIssues: 2,
severities: ["major", "minor"],
},
},
];
// Run tests
for (const test of testCases) {
const output = await llm(buildPrompt(test.input));
const parsed = parseCodeReview(output);
if (test.expected.hasIssues) {
assert(parsed.issues.length >= test.expected.minIssues);
}
if (test.expected.scoreRange) {
assert(parsed.overall_score >= test.expected.scoreRange[0]);
assert(parsed.overall_score <= test.expected.scoreRange[1]);
}
}
最佳实践
- 明确指令:清楚说明你的需求
- 输出约定:定义严格的 schema
- 少样本示例:用示例展示,而不只是口头说明
- 变量验证:构建提示词前检查输入
- 版本跟踪:维护提示词历史记录
- 充分测试:针对边界情况进行验证
- 迭代改进:根据实际输出持续优化
- 记录约束:说明限制条件
输出检查清单
- 包含角色和约束的系统提示词
- 包含变量的用户提示词模板
- 输出格式规范(JSON schema)
- 3 个或更多少样本示例(正确和错误示例)
- 已记录风格指南
- 注意事项列表
- 变量验证逻辑
- 输出解析/验证
- 提示词测试用例
- 版本跟踪系统
评论
支持 Markdown