mcpField
P
prompt-template-builder

prompt-template-builder

github.com/patricio0312revエージェントワークフロー63277 回インストール41 週間前に更新
リポジトリ

prompt-template-builder について

prompt-template-builderは、変数、出力契約、例、ガードレールを明示した再利用可能なプロンプトを設計するスキルです。LLMタスクの出力を統一したいチーム向けに、検証、テスト、プロンプトチェーン、バージョン管理も扱います。

主な機能

  1. 01システム・ユーザープロンプトの構成
  2. 02変数を使うテンプレート
  3. 03出力契約とスキーマ検証
  4. 04Few-shot例とスタイル規則
  5. 05プロンプトチェーンとバージョン管理
  6. 06テストケースと入力検証

活用シーン

  1. 01コードレビュー用プロンプトの標準化
  2. 02構造化JSON出力の指定
  3. 03例を使ったプロンプト動作のテスト
  4. 04プロンプトテンプレートの改訂管理

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/patricio0312rev/skills --skill prompt-template-builder

インストール後、Claude Code で/prompt-template-builderを入力して読み込まれたか確認します。

詳細

プロンプトテンプレートビルダー

明確な契約と一貫した出力を備えた、堅牢で再利用可能なプロンプトテンプレートを作成します。

コアコンポーネント

システムプロンプト:役割、ペルソナ、制約、出力形式 ユーザープロンプト:タスク、コンテキスト、変数、例 フューショット例:望ましい動作を示す入力と出力のペア 出力契約:厳密な形式仕様(JSON スキーマ、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]);
  }
}

ベストプラクティス

  1. 明確な指示:求める内容を明示します
  2. 出力契約:厳密なスキーマを定義します
  3. フューショット例:説明するだけでなく、実例を示します
  4. 変数の検証:プロンプトを作成する前に入力を確認します
  5. バージョンの追跡:プロンプトの履歴を維持します
  6. 十分にテスト:エッジケースに対して検証します
  7. 反復:実際の出力に基づいて改善します
  8. 制約の文書化:制限事項を説明します

出力チェックリスト

  • 役割と制約を含むシステムプロンプト
  • 変数を含むユーザープロンプトテンプレート
  • 出力形式の仕様(JSON スキーマ)
  • 3 つ以上のフューショット例(良い例と悪い例)
  • スタイルガイドラインの文書化
  • すべきこと、すべきでないことのリスト
  • 変数の検証ロジック
  • 出力の解析/検証
  • プロンプトのテストケース
  • バージョン追跡システム

コメント