プロンプトのバージョン管理
プロンプトにGit形式のバージョン管理、セマンティックバージョニング、変更履歴管理を適用します。
「プロンプトのバージョン管理」はCoddyKit上の無料AI Prompt Engineeringレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Prompt Engineering学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Prompt Engineeringコースには全4レッスンが含まれています。
なぜプロンプトをバージョン管理するのか
プロンプトは継続的に進化しており、わずかな文言の変更でもモデルの挙動が大きく変わる可能性があります。バージョン管理をしなければ、何を、いつ、なぜ変更したのかをチームで把握できなくなります。プロンプトをコードと同じように扱うことで、履歴、ロールバック、共同作業、変更者の追跡が可能になります。
Gitベースのプロンプトバージョン管理
プロンプトファイルをGitに保存する方法は、最もシンプルなバージョン管理戦略です。各プロンプトはプレーンテキストファイルとして扱い、Gitコミットですべての変更を記録します。ブランチは実験を表し、タグは本番リリースを示します。
# Initialize a prompt repo
git init prompt-library
cd prompt-library
mkdir -p prompts/summarize-article
# First version
cat > prompts/summarize-article/prompt.txt << 'PROMPT'
Summarize the article in {num_sentences} sentences.
Article:
{article_text}
PROMPT
git add prompts/summarize-article/prompt.txt
git commit -m 'feat(summarize-article): initial prompt v1.0.0'
git tag v1.0.0
# Experiment on a branch
git checkout -b experiment/add-focus-area
# ... edit prompt ...
git commit -m 'feat(summarize-article): add focus_area variable'
git tag v1.1.0-rc1プロンプトのセマンティックバージョニング
プロンプトの意味に合わせて調整したセマンティックバージョニング(MAJOR.MINOR.PATCH)を採用します。
- PATCH(1.0.0 → 1.0.1):タイプミスの修正、空白の変更 — 出力は変わりません
- MINOR(1.0.0 → 1.1.0):任意の変数の追加、表現の改善 — 後方互換性があります
- MAJOR(1.0.0 → 2.0.0):必須変数の追加、出力形式の変更、互換性を壊す動作変更
# semver.py — helper to validate version bumps
import re
def parse_semver(v):
m = re.match(r'^(\d+)\.(\d+)\.(\d+)$', v)
if not m:
raise ValueError(f'Invalid semver: {v}')
return tuple(int(x) for x in m.groups())
def classify_bump(old, new):
o = parse_semver(old)
n = parse_semver(new)
if n[0] > o[0]:
return 'MAJOR'
elif n[1] > o[1]:
return 'MINOR'
elif n[2] > o[2]:
return 'PATCH'
else:
raise ValueError('New version must be greater than old')
print(classify_bump('1.0.0', '1.1.0')) # MINOR
print(classify_bump('1.1.0', '2.0.0')) # MAJOR
print(classify_bump('2.0.0', '2.0.1')) # PATCH変更履歴の形式
チームが何をなぜ変更したのかを理解できるように、すべてのプロンプトバージョンに構造化された変更履歴を用意する必要があります。プロンプト向けに調整したKeep a Changelog形式に従います。
# CHANGELOG.md for prompts/summarize-article/
## [2.0.0] - 2024-08-10
### Breaking Changes
- Renamed variable 'text' to 'article_text' (update all call sites)
- Output now always includes a headline sentence before the summary
### Changed
- Improved instruction specificity to reduce hallucination rate by ~12%
## [1.1.0] - 2024-07-01
### Added
- New optional variable 'focus_area' to direct summary emphasis
- Fallback instruction when 'focus_area' is not provided
### Changed
- Reworded opening instruction for clarity
## [1.0.0] - 2024-06-01
### Added
- Initial prompt: basic summarization with 'num_sentences' control本番リリースへのタグ付け
Gitタグによって、本番環境にデプロイされた正確なコミットを示します。注釈付きタグを使用して、リリースノートをタグとともに保存します。これにより、任意の時点でどのプロンプトが稼働していたかを正確に再現できます。
# Annotated git tag with release notes
git tag -a v2.0.0 -m 'Release 2.0.0
Breaking: renamed variable text -> article_text
Improved: reduced hallucination rate by 12%
Author: alice@company.com
Reviewed-by: bob@company.com'
# Push tags to remote
git push origin --tags
# List all tags with dates
git tag -l --sort=version:refname -n9
# v1.0.0 Initial prompt
# v1.1.0 Add focus_area variable
# v2.0.0 Release 2.0.0 — Breaking: renamed variable ...
# View exact prompt at a tag
git show v1.1.0:prompts/summarize-article/prompt.txtロールバック手順
新しいプロンプトバージョンによって品質が低下した場合、ロールバックを迅速に行う必要があります。戦略は2つあります。コードロールバック(古いアーティファクトを再デプロイする)とレジストリロールバック(再デプロイせずにis_activeフラグを切り替える)です。
# Strategy 1: Registry rollback (fastest — no redeploy needed)
def rollback_prompt(registry, prompt_id, target_version):
print(f'Rolling back {prompt_id} to {target_version}...')
registry.activate_version(prompt_id, target_version)
print(f'Rollback complete. {prompt_id} now serving {target_version}')
# Strategy 2: Git-based rollback with audit trail
# Create a revert commit (do NOT force-push, keep history clean)
git revert HEAD --no-commit # stage the revert
git commit -m 'revert(summarize-article): roll back to v1.1.0 due to quality regression'
git tag v2.0.1-hotfix
# Then trigger re-deployment of the reverted artifact
# This preserves full history — nobody loses track of what happenedプロンプトの差分ツール
プロンプトの変更をレビューするには、専用の差分ツールが必要です。通常のテキストにはプレーンなgit diffが使えますが、セマンティック差分ツールを使うと、変数や指示文の構造上の変更を強調表示できます。
# prompt_diff.py — highlight variable changes between versions
import re
def extract_variables(template):
return set(re.findall(r'\{(\w+)\}', template))
def diff_prompts(old_template, new_template):
old_vars = extract_variables(old_template)
new_vars = extract_variables(new_template)
added = new_vars - old_vars
removed = old_vars - new_vars
kept = old_vars & new_vars
print('Variables added:', added or 'none')
print('Variables removed:', removed or 'none')
print('Variables kept:', kept)
old_lines = set(old_template.splitlines())
new_lines = set(new_template.splitlines())
print('New lines:', new_lines - old_lines)
print('Removed lines:', old_lines - new_lines)
old = 'Summarize in {num_sentences} sentences.\n\n{text}'
new = 'Summarize in {num_sentences} sentences focused on {focus_area}.\n\n{article_text}'
diff_prompts(old, new)プロンプト実験のブランチ戦略
プロンプト開発でも、ソフトウェアのブランチ運用規則に合わせます。
main— 本番対応済みのプロンプトのみexperiment/<name>— 開発中のA/Bテスト用バリアントhotfix/<issue>— 本番環境の緊急修正release/<version>— リリース候補のステージング
アプリケーションコードと同じように、プロンプトの変更をmainにマージする前にコードレビュー(Pull Request)を必須にします。
# Typical prompt development workflow
# 1. Create experiment branch
git checkout -b experiment/tone-formal
# 2. Edit and test prompt locally
python test_prompt.py --prompt prompts/summarize-article/prompt.txt \
--eval-set evals/summarize-100.jsonl
# 3. Open PR with eval results in description
gh pr create --title 'experiment: formal tone improves ROUGE by 8%' \
--body 'Eval results attached. ROUGE-L: 0.61 -> 0.66'
# 4. After approval, merge and tag
git checkout main && git merge experiment/tone-formal
git tag v1.2.0 && git push origin main --tags自動バージョン検証CI
プロンプト変更用のCIパイプラインでは、semverの更新が正しいこと、変更履歴が更新されていること、テンプレート内のすべての変数が文書化されていること、評価スコアが低下していないことを自動的に検証します。
# .github/workflows/prompt-ci.yml
# name: Prompt Validation
# on: [pull_request]
# jobs:
# validate:
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v4
# - name: Check semver bump
# run: python scripts/check_semver.py
# - name: Validate template syntax
# run: python scripts/validate_templates.py
# - name: Run eval suite
# run: python scripts/run_evals.py --threshold 0.95
# scripts/validate_templates.py
import glob, json, sys
errors = []
for f in glob.glob('prompts/**/*.yaml', recursive=True):
with open(f) as fh:
data = fh.read()
if '{' not in data:
errors.append(f'{f}: no variables found (may be intentional — double check)')
if errors:
print('Warnings:', errors)
print('Template validation complete')タグ付けされたバージョンの不変性
重要な原則は、タグ付けされたバージョンは不変であるということです。v2.0.0にタグを付けたら、そのテンプレートを変更してはいけません。修正は新しいバージョン(v2.0.1)に反映します。これにより再現性が保証され、タグから本番環境の正確な状態をいつでも再現できます。
# Enforce immutability in the registry
def register(self, prompt_id, version, template, ...):
with self.conn.cursor() as cur:
# Check if version already exists
cur.execute(
'SELECT id FROM prompt_versions '
'WHERE prompt_id=%s AND version=%s',
(prompt_id, version)
)
if cur.fetchone():
raise ValueError(
f'Version {version} of {prompt_id} already exists. '
'Versions are immutable. Create a new version instead.'
)
# Proceed with insertion
cur.execute(
'INSERT INTO prompt_versions '
'(prompt_id, version, template, author, tags, model) '
'VALUES (%s, %s, %s, %s, %s, %s)',
(prompt_id, version, template, author, tags, model)
)
self.conn.commit()プロンプトと評価結果の紐付け
チームがバージョン間の品質を比較できるように、各プロンプトバージョンを評価結果に紐付ける必要があります。評価メタデータはプロンプトアーティファクトと一緒に保存します。
# Attach eval results to a prompt version
ALTER TABLE prompt_versions ADD COLUMN eval_results JSONB;
# Python: record eval scores
def attach_eval_results(self, prompt_id, version, results):
with self.conn.cursor() as cur:
cur.execute(
'UPDATE prompt_versions SET eval_results=%s '
'WHERE prompt_id=%s AND version=%s',
(json.dumps(results), prompt_id, version)
)
self.conn.commit()
# Example eval results structure
eval_results = {
'dataset': 'cnn-dailymail-100',
'date_run': '2024-08-10',
'metrics': {
'rouge_l': 0.66,
'bertscore_f1': 0.89,
'human_quality_avg': 4.2
},
'sample_size': 100,
'runner': 'alice@company.com'
}
registry.attach_eval_results('summarize-article', '1.2.0', eval_results)クイックチェック
プロンプトのMAJORバージョンはいつ上げるべきですか?
バージョン管理のまとめ
プロンプトのバージョン管理は、プロンプト固有の調整を加えながら、ソフトウェアのバージョン管理を踏襲します。
- セマンティックバージョニング:PATCH/MINOR/MAJORで変更の影響度を示す
- Gitタグ:本番リリース用の不変で注釈付きのタグ
- 変更履歴:監査可能性を高める、バージョンごとの構造化された履歴
- ロールバック:レジストリフラグの切り替え(高速)またはgit revert(監査可能)
- CI検証:semverチェック、テンプレート検証、評価の回帰を防ぐ仕組みを自動化
- 不変性:タグ付けされたバージョンは変更せず、修正時は必ず新しいバージョンを作成する
よくある質問
「プロンプトのバージョン管理」レッスンは無料ですか?
はい。「プロンプトのバージョン管理」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Prompt Engineeringコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Prompt Engineeringコースには全4レッスンが含まれています。
「プロンプトのバージョン管理」で何を学びますか?
プロンプトにGit形式のバージョン管理、セマンティックバージョニング、変更履歴管理を適用します。 ブラウザで直接実行するハンズオンコードでAI Prompt Engineeringを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
AI Prompt Engineeringを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのAI Prompt Engineeringは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「プロンプトのバージョン管理」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このAI Prompt Engineeringレッスンでコードを書いて実行できますか?
はい。すべてのAI Prompt Engineeringレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- プロンプトレジストリのアーキテクチャ
- プロンプトのバージョン管理
- デプロイとロールバックの戦略
- 本番環境でのプロンプト性能監視