Prompt 改了,算代码变更吗

传统 CI/CD:改代码 → 跑单测 → 跑集成测试 → 部署。

LLM 应用呢?改一句 system prompt → ?

大多数团队的答案是:直接上线,观察一下用户反馈。

这很危险。Prompt 变更影响模型输出,效果回归是静默的——日志里没有报错,测试没有失败,但用户体验已经变差了。

LLM 应用的 CI/CD 需要额外对待三类变更:

  1. Prompt 模板变更(system prompt、user prompt 结构)
  2. 模型版本变更(claude-3.5 → claude-opus-4)
  3. 工具 / 函数签名变更

CI 里要测什么

1. Lint & Schema 检查

# lint_prompt.py
import yaml, sys, re

def lint_prompt(prompt_file):
    with open(prompt_file) as f:
        config = yaml.safe_load(f)
    
    errors = []
    
    # 必填字段
    for field in ["system_prompt", "version", "model"]:
        if field not in config:
            errors.append(f"Missing required field: {field}")
    
    # prompt 长度检查
    sp = config.get("system_prompt", "")
    token_estimate = len(sp.split()) * 1.3
    if token_estimate > 4000:
        errors.append(f"System prompt too long: ~{int(token_estimate)} tokens")
    
    # 检查 placeholder 一致性
    placeholders = set(re.findall(r'\{(\w+)\}', sp))
    declared = set(config.get("variables", {}).keys())
    undeclared = placeholders - declared
    if undeclared:
        errors.append(f"Undeclared variables: {undeclared}")
    
    return errors

if __name__ == "__main__":
    errors = lint_prompt(sys.argv[1])
    if errors:
        for e in errors:
            print(f"ERROR: {e}")
        sys.exit(1)
    print("Prompt lint passed.")

2. 离线评估(Golden Dataset)

维护一个 golden dataset:固定 input,标注 expected output 或 expected 属性。

# eval_golden.py
import json, asyncio
from anthropic import Anthropic

client = Anthropic()

async def eval_single(case, prompt_config):
    resp = client.messages.create(
        model=prompt_config["model"],
        system=prompt_config["system_prompt"],
        messages=[{"role": "user", "content": case["input"]}],
        max_tokens=1024,
    )
    output = resp.content[0].text
    
    results = {}
    # 硬性断言
    for assertion in case.get("assert_contains", []):
        results[f"contains:{assertion}"] = assertion.lower() in output.lower()
    
    # 硬性排除
    for assertion in case.get("assert_not_contains", []):
        results[f"not_contains:{assertion}"] = assertion.lower() not in output.lower()
    
    return {
        "case_id": case["id"],
        "passed": all(results.values()),
        "details": results,
        "output": output,
    }

async def run_eval(dataset_path, prompt_config_path):
    with open(dataset_path) as f:
        dataset = json.load(f)
    with open(prompt_config_path) as f:
        prompt_config = json.load(f)
    
    tasks = [eval_single(c, prompt_config) for c in dataset["cases"]]
    results = await asyncio.gather(*tasks)
    
    passed = sum(1 for r in results if r["passed"])
    total = len(results)
    pass_rate = passed / total
    
    print(f"Pass rate: {passed}/{total} = {pass_rate:.1%}")
    
    # 打印失败的 case
    for r in results:
        if not r["passed"]:
            print(f"  FAIL [{r['case_id']}]: {r['details']}")
    
    return pass_rate

if __name__ == "__main__":
    import sys
    rate = asyncio.run(run_eval(sys.argv[1], sys.argv[2]))
    if rate < 0.90:  # 90% pass rate gate
        print("Eval failed: pass rate below threshold")
        sys.exit(1)

Golden dataset 示例:

{
  "cases": [
    {
      "id": "tc001",
      "input": "帮我写一首关于春天的诗",
      "assert_contains": ["春"],
      "assert_not_contains": ["秋天", "冬天"]
    },
    {
      "id": "tc002",
      "input": "请提供一个Python排序示例",
      "assert_contains": ["def ", "sort"],
      "assert_not_contains": ["import os", "rm -rf"]
    }
  ]
}

3. 指标对比(Diff Metrics)

新 prompt vs 旧 prompt 在同一 dataset 上跑,对比关键指标:

# metric_diff.py
def compare_evals(baseline_results, candidate_results, threshold=0.02):
    """
    对比两版 prompt 的评估结果。
    threshold: 允许的最大退步幅度(绝对值)
    """
    baseline_pass = sum(1 for r in baseline_results if r["passed"]) / len(baseline_results)
    candidate_pass = sum(1 for r in candidate_results if r["passed"]) / len(candidate_results)
    
    delta = candidate_pass - baseline_pass
    
    print(f"Baseline pass rate: {baseline_pass:.1%}")
    print(f"Candidate pass rate: {candidate_pass:.1%}")
    print(f"Delta: {delta:+.1%}")
    
    if delta < -threshold:
        print(f"REGRESSION: delta {delta:.1%} exceeds threshold -{threshold:.1%}")
        return False
    
    print("No regression detected.")
    return True

4. 安全检查

# safety_check.py
import re

BLOCKED_PATTERNS = [
    r"ignore (all )?previous instructions",
    r"you are now",
    r"act as (a |an )?(?!assistant|AI)",
    r"jailbreak",
]

def check_prompt_safety(prompt_text):
    issues = []
    for pattern in BLOCKED_PATTERNS:
        if re.search(pattern, prompt_text, re.IGNORECASE):
            issues.append(f"Suspicious pattern: {pattern}")
    return issues

完整 GitHub Actions 流水线

# .github/workflows/llm-ci.yml
name: LLM Prompt CI

on:
  pull_request:
    paths:
      - 'prompts/**'
      - 'prompt_config.json'

env:
  ANTHROPIC_API_KEY: $

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - run: pip install pyyaml
      - name: Lint prompt files
        run: |
          for f in prompts/*.yaml; do
            python scripts/lint_prompt.py "$f"
          done

  safety-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - name: Safety check prompts
        run: python scripts/safety_check.py prompts/

  eval-candidate:
    needs: [lint, safety-check]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - run: pip install anthropic
      - name: Run golden dataset eval (candidate)
        run: |
          python scripts/eval_golden.py \
            datasets/golden.json \
            prompt_config.json \
            --output results/candidate.json

  eval-baseline:
    needs: [lint, safety-check]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: main
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - run: pip install anthropic
      - name: Run golden dataset eval (baseline)
        run: |
          python scripts/eval_golden.py \
            datasets/golden.json \
            prompt_config.json \
            --output results/baseline.json

  regression-gate:
    needs: [eval-candidate, eval-baseline]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Compare metrics and gate
        run: |
          python scripts/metric_diff.py \
            results/baseline.json \
            results/candidate.json \
            --threshold 0.02

  report:
    needs: [regression-gate]
    runs-on: ubuntu-latest
    steps:
      - name: Post eval summary to PR
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const candidate = JSON.parse(fs.readFileSync('results/candidate.json'));
            const baseline = JSON.parse(fs.readFileSync('results/baseline.json'));
            const body = `## LLM Eval Results
            | Metric | Baseline | Candidate | Delta |
            |--------|----------|-----------|-------|
            | Pass Rate | ${baseline.pass_rate} | ${candidate.pass_rate} | ${candidate.pass_rate - baseline.pass_rate} |
            | Avg Latency | ${baseline.avg_latency_ms}ms | ${candidate.avg_latency_ms}ms | - |
            `;
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body
            });

部署策略

Shadow Mode(影子模式)

新 prompt 同时接收流量,但结果不返回给用户,只记录对比日志。风险最低。

async def shadow_request(user_input, production_prompt, candidate_prompt):
    # 两个并发请求
    prod_task = call_llm(production_prompt, user_input)
    shadow_task = call_llm(candidate_prompt, user_input)
    
    prod_result, shadow_result = await asyncio.gather(prod_task, shadow_task)
    
    # 只返回 production 结果给用户
    # 记录 shadow 对比供分析
    log_shadow_comparison(prod_result, shadow_result)
    
    return prod_result

Canary 发布

import random

def route_request(user_id, canary_pct=5):
    """5% 流量走新 prompt"""
    if random.randint(1, 100) <= canary_pct:
        return "candidate_prompt"
    return "production_prompt"

快速回滚

Prompt 版本化存储,回滚 = 切指针:

# 回滚到上一版本
./scripts/rollback.sh prompt_config v1.2.3

# rollback.sh 内部:
# git checkout tags/v1.2.3 -- prompt_config.json
# kubectl rollout restart deployment/llm-app

工具选型

工具 用途 特点
LangSmith Trace + Eval 功能全,贵
Braintrust Eval + 版本对比 专注评估,好用
Langfuse Trace(开源可自部署) 性价比高
PromptLayer Prompt 版本管理 轻量
GitHub Actions 流水线 免费额度够用

一个朴素结论

Prompt 是代码,要按代码管。

没有 eval gate 的 prompt 变更 = 生产环境赌博。 建好流水线之后,改 prompt 跟改函数一样有信心——因为你知道测过了。

先把 golden dataset 做到 50 个 case,CI 跑起来,再慢慢扩。别追求完美再动手。