prompt-template-builder

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Prompt Template Builder

提示词模板构建器

Build robust, reusable prompt templates with clear contracts and consistent outputs.
构建具备清晰约定和一致输出的健壮、可复用提示词模板。

Core Components

核心组件

System Prompt: Role, persona, constraints, output format User Prompt: Task, context, variables, examples Few-Shot Examples: Input/output pairs demonstrating desired behavior Output Contract: Strict format specification (JSON schema, Markdown structure) Style Rules: Tone, verbosity, formatting preferences Guardrails: Do's and don'ts, safety constraints
System Prompt:角色、人设、约束条件、输出格式 User Prompt:任务、上下文、变量、示例 少样本示例:展示预期行为的输入/输出对 输出约定:严格的格式规范(JSON Schema、Markdown结构) 样式规则:语气、详细程度、格式偏好 防护规则:注意事项、安全约束

System Prompt Template

System Prompt模板

markdown
undefined
markdown
undefined

System Prompt: Code Review Assistant

System Prompt: 代码审查助手

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.
你是专注于{language}和{framework}的资深代码审查专家。你的职责是针对代码质量、最佳实践和潜在问题提供具有建设性、可落地的反馈。

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
}
undefined
请按照以下JSON结构提供审查结果:
json
{
  "summary": "1-2句话的简要概述",
  "issues": [
    {
      "severity": "critical|major|minor",
      "line": number,
      "message": "问题描述",
      "suggestion": "修复建议"
    }
  ],
  "strengths": ["优点列表"],
  "overall_score": 1-10
}
undefined

Style Guidelines

样式指南

  • Be constructive and specific
  • Cite line numbers for issues
  • Provide actionable suggestions
  • Balance criticism with praise
  • Use professional, respectful tone
  • 保持建设性和针对性
  • 标注问题对应的行号
  • 提供可落地的建议
  • 平衡批评与表扬
  • 使用专业、尊重的语气

Constraints

约束条件

  • Do NOT suggest unnecessary refactors
  • Do focus on correctness, security, performance
  • Do NOT be overly pedantic about style
  • Do consider the context and project requirements
undefined
  • 请勿建议不必要的重构
  • 重点关注正确性、安全性、性能
  • 请勿对样式过于吹毛求疵
  • 请考虑上下文和项目需求
undefined

User Prompt Template with Variables

带变量的User Prompt模板

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',
});
typescript
// prompt-templates/code-review.ts
export const codeReviewPrompt = (variables: {
  language: string;
  framework: string;
  code: string;
  context?: string;
}) => `
请审查以下${variables.language}代码:

${variables.context ? `上下文: ${variables.context}\n` : ''}

\`\`\`${variables.language}
${variables.code}
\`\`\`

请遵循System Prompt中指定的输出格式提供全面的代码审查。
`;

// 使用示例
const prompt = codeReviewPrompt({
  language: 'typescript',
  framework: 'React',
  code: userSubmittedCode,
  context: '这是一个用于用户认证的生产环境组件',
});

Few-Shot Examples

少样本示例

markdown
undefined
markdown
undefined

Few-Shot Examples

少样本示例

Example 1: Good Code

示例1:优质代码

Input:
typescript
function calculateTotal(items: Item[]): number {
  return items.reduce((sum, item) => sum + item.price, 0);
}

**Output:**

```json
{
  "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
}
```
输入:
typescript
function calculateTotal(items: Item[]): number {
  return items.reduce((sum, item) => sum + item.price, 0);
}

**输出:**

```json
{
  "summary": "代码简洁、类型安全,未发现问题。",
  "issues": [],
  "strengths": [
    "TypeScript类型安全",
    "使用reduce的函数式写法",
    "命名清晰、描述性强"
  ],
  "overall_score": 9
}
```

Example 2: Code with Issues

示例2:存在问题的代码

Input:
typescript
function calc(arr) {
  let total = 0;
  for (var i = 0; i < arr.length; i++) {
    total = total + arr[i].price;
  }
  return total;
}
Output:
json
{
  "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
}
undefined
输入:
typescript
function calc(arr) {
  let total = 0;
  for (var i = 0; i < arr.length; i++) {
    total = total + arr[i].price;
  }
  return total;
}
输出:
json
{
  "summary": "功能正常,但存在类型安全和现代语法问题。",
  "issues": [
    {
      "severity": "major",
      "line": 1,
      "message": "缺少参数和返回值的类型注解",
      "suggestion": "添加类型:function calc(arr: Item[]): number"
    },
    {
      "severity": "minor",
      "line": 3,
      "message": "使用了'var'而非'let'或'const'",
      "suggestion": "将'var'替换为'let':for (let i = 0; ...)"
    }
  ],
  "strengths": ["逻辑正确", "处理了空数组情况"],
  "overall_score": 6
}
undefined

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');
  }
};
typescript
// 定义严格的输出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),
});

// 验证LLM输出
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');
  }
};

Template Variables

模板变量

typescript
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}`;
};
typescript
export interface PromptVariables {
  // 必填项
  required_field: string;

  // 可选项(带默认值)
  optional_field?: string;

  // 约束值
  severity_level: "low" | "medium" | "high";

  // 带范围的数值
  max_tokens: number; // 1-4096
}

export const buildPrompt = (vars: PromptVariables): string => {
  // 验证变量
  if (!vars.required_field) {
    throw new Error("required_field is required");
  }

  // 设置默认值
  const optional = vars.optional_field ?? "default value";

  // 构建提示词
  return `Task: ${vars.required_field}
Options: ${optional}
Severity: ${vars.severity_level}`;
};

Style Rules

样式规则

markdown
undefined
markdown
undefined

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
  • 简洁型:1-2句话,使用项目符号
  • 标准型:每个要点一段内容
  • 详细型:完整解释并附带示例
  • 全面型:深入探讨并附带参考资料

Formatting Preferences

格式偏好

  • Use markdown headers for structure
  • Bold important terms
  • Code blocks for technical content
  • Lists for enumeration
  • Tables for comparisons
undefined
  • 使用Markdown标题构建结构
  • 对重要术语加粗
  • 技术内容使用代码块
  • 枚举内容使用列表
  • 对比内容使用表格
undefined

Do's and Don'ts

注意事项

markdown
undefined
markdown
undefined

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
undefined
✗ 请勿模糊表述(如“这不好”) ✗ 请勿建议不必要的重写 ✗ 请勿忽略安全问题 ✗ 请勿过于吹毛求疵 ✗ 请勿假设资源无限 ✗ 请勿在无上下文的情况下做假设
undefined

Prompt Chaining

提示词链式调用

typescript
// 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));
typescript
// 多步骤提示词
export const chainedPrompts = {
  step1_analyze: (code: string) => `
    分析这段代码并识别潜在问题:
    ${code}

    以JSON数组格式列出问题,包含严重程度和描述。
  `,

  step2_suggest: (issues: Issue[]) => `
    基于以下代码问题:
    ${JSON.stringify(issues)}

    为每个问题提供详细的修复建议。
  `,

  step3_summarize: (suggestions: Suggestion[]) => `
    将这些代码审查建议汇总为最终报告:
    ${JSON.stringify(suggestions)}
  `,
};

// 执行链式调用
const issues = await llm(chainedPrompts.step1_analyze(code));
const suggestions = await llm(chainedPrompts.step2_suggest(issues));
const report = await llm(chainedPrompts.step3_summarize(suggestions));

Version Control

版本控制

typescript
// 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"];
typescript
// 跟踪提示词版本
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",
  },
};

// 使用指定版本
const prompt = PROMPT_VERSIONS["v1.1"];

Testing Prompts

提示词测试

typescript
// 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]);
  }
}
typescript
// 用于提示词验证的测试用例
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"],
    },
  },
];

// 运行测试
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]);
  }
}

Best Practices

最佳实践

  1. Clear instructions: Be explicit about what you want
  2. Output contracts: Define strict schemas
  3. Few-shot examples: Show, don't just tell
  4. Variable validation: Check inputs before building prompts
  5. Version tracking: Maintain prompt history
  6. Test thoroughly: Validate against edge cases
  7. Iterate: Improve based on real outputs
  8. Document constraints: Explain limitations
  1. 清晰的指令:明确说明你的需求
  2. 输出约定:定义严格的Schema
  3. 少样本示例:用示例展示,而非仅说明
  4. 变量验证:构建提示词前检查输入
  5. 版本跟踪:维护提示词历史记录
  6. 全面测试:针对边缘情况进行验证
  7. 迭代优化:基于实际输出改进提示词
  8. 约束文档:说明限制条件

Output Checklist

输出检查清单

  • System prompt with role and constraints
  • User prompt template with variables
  • Output format specification (JSON schema)
  • 3+ few-shot examples (good and bad)
  • Style guidelines documented
  • Do's and don'ts list
  • Variable validation logic
  • Output parsing/validation
  • Test cases for prompt
  • Version tracking system
  • 包含角色和约束条件的System Prompt
  • 带变量的User Prompt模板
  • 输出格式规范(JSON Schema)
  • 3个及以上少样本示例(优质和问题代码)
  • 文档化的样式指南
  • 注意事项列表
  • 变量验证逻辑
  • 输出解析/验证
  • 提示词测试用例
  • 版本跟踪系统