Prompt Baseline Document
【免费下载链接】claude-skills67 Specialized Skills for Full-Stack Developers. Transform Claude Code into your expert pair programmer.项目地址: https://gitcode.com/GitHub_Trending/claud/claude-skills
Prompt Version: v1.0.0
Date: YYYY-MM-DD
Model: claude-opus-4-5-20251101
Task Definition
[What should the prompt accomplish?]
Success Criteria
- Primary metric: [e.g., accuracy >= 95%]
- Secondary metrics: [e.g., latency < 2s, cost < $0.01/request]
Test Set
- Size: [number of test cases]
- Source: [how test cases were collected]
- Categories: [breakdown by type/difficulty]
Baseline Results
| Metric | Value | Target |
|---|---|---|
| Accuracy | 82% | 95% |
| Avg latency | 1.8s | <2s |
| Avg tokens | 450 | <300 |
| Cost/request | $0.015 | <$0.01 |
使用要点: - **主指标**只保留一个(如准确率),它是你迭代的裁判;**次指标**(延迟、Token 数、单次成本)用来约束优化方向,防止"为了准确率无限堆 Token"。 - **模型版本**必须记录。提示词表现与模型强相关,[SKILL.md](https://link.gitcode.com/i/5092e2d29fe1b6bc91141a65e9d8d47d) 明确警告 "Assume prompts transfer perfectly between models" 是禁止行为,换模型前必须重新评估。 - **Test Set 三要素**(规模、来源、类别构成)决定了基线是否可信。 ### 构建有代表性的测试集 参考文档强调,测试集必须覆盖真实输入分布,而不仅是"标准输入"。其示例代码按类别比例生成测试集: ```python def create_test_set(task_type: str, size: int = 100) -> list: """Create a diverse test set for prompt evaluation.""" test_cases = [] # Include different categories categories = { "typical": 0.60, # Common cases (60%) "edge_case": 0.20, # Boundary conditions (20%) "adversarial": 0.10, # Tricky inputs (10%) "malformed": 0.10, # Invalid/unusual inputs (10%) } for category, proportion in categories.items(): count = int(size * proportion) test_cases.extend(generate_cases(task_type, category, count)) return test_cases这是一个 60/20/10/10 的分布建议:六成典型样本保证常规能力,两成边界条件(空输入、超长输入、歧义输入),一成对抗样本(尝试诱导模型出错或越权),一成畸形输入(非法格式)。配套的测试用例结构化描述可以参考 evaluation-frameworks.md 中的 JSON 测试用例格式,其中每条用例包含id、category、input、expected、tags与notes,便于后续按类别做失败归因。
诊断框架:先找根因,再动手修改
提示词表现不佳时,最常见的错误是直接重写。参考文档要求先做失败分类,再对症下药。
失败类别分析
| Failure Type | Symptoms | Common Causes |
|---|---|---|
| Format errors | Wrong structure, missing fields | Unclear format spec, no examples |
| Hallucinations | Made-up facts, wrong answers | Lack of grounding, vague instructions |
| Inconsistency | Same input, different outputs | Ambiguous instructions, high temperature |
| Over-verbosity | Too much explanation | No length constraints, wrong audience |
| Under-performance | Low accuracy across board | Wrong pattern choice, insufficient context |
| Edge case failures | Breaks on unusual inputs | Missing constraint handling |
六类失败对应六种典型根因。值得注意的是,格式错误与幻觉的修复手段截然不同:前者需要补输出脚手架与示例,后者需要加知识锚定与明确指令;如果混淆二者,优化只会南辕北辙。
诊断检查清单
在改动任何内容之前,逐项过一遍清单:
## Prompt Diagnostic Checklist ### 1. Instruction Clarity - [ ] Is the task unambiguously defined? - [ ] Are constraints explicit? - [ ] Is the output format specified? ### 2. Context Sufficiency - [ ] Does the model have all needed information? - [ ] Are examples representative of real inputs? - [ ] Is domain knowledge assumed correctly? ### 3. Edge Case Coverage - [ ] Empty inputs? - [ ] Maximum length inputs? - [ ] Invalid/malformed inputs? - [ ] Ambiguous cases? ### 4. Instruction Conflicts - [ ] Do any instructions contradict each other? - [ ] Do examples match the instructions? - [ ] Are constraints achievable together?第四组"指令冲突"常被忽视:示例与指令矛盾、两个约束互斥,会让模型无所适从。这正对应 SKILL.md 中MUST NOT DO的 "Use few-shot examples that contradict instructions"。
错误分析模板
参考文档提供了一个按类别聚合失败的 Python 模板,保留每类失败的前 3 个样本用于人工核查:
def analyze_failures(results: list) -> dict: """Categorize and analyze prompt failures.""" analysis = { "total": len(results), "passed": 0, "failed": 0, "failure_categories": {}, "examples": [] } for result in results: if result["passed"]: analysis["passed"] += 1 else: analysis["failed"] += 1 category = categorize_failure(result) analysis["failure_categories"][category] = \ analysis["failure_categories"].get(category, 0) + 1 # Keep first 3 examples per category if len([e for e in analysis["examples"] if e["category"] == category]) < 3: analysis["examples"].append({ "category": category, "input": result["input"], "expected": result["expected"], "actual": result["actual"], "hypothesis": generate_hypothesis(result) }) return analysis聚合之后你得到的是一张"失败分布表",而不是一堆零散的错误样本。hypothesis字段强制你在每个失败样本上写下初步归因假设,这正是"Diagnose before changing"的具体化。
四大优化技巧
参考文档给出了四种经过验证的优化技巧,每一类都带完整的 Before/After 对照。
技巧一:指令细化(Instruction Refinement)
问题:指令模糊导致输出不一致。
Before:
Summarize this article. {article}After:
Summarize the following article in exactly 2-3 sentences. Focus on the main conclusion and key supporting evidence. Do not include quotes or specific numbers unless essential. Write for a general audience with no assumed domain knowledge. Article: {article} Summary:改进的四个维度值得逐条拆解:量化约束(exactly 2-3 sentences)、内容聚焦(main conclusion + key supporting evidence)、显式排除(Do not include...)、受众定义(general audience)。与 SKILL.md 中 before/after 示例的"3 个要点 + 动词开头 + 不加观点"约束思路完全同构——好的指令 = 任务 + 数量限定 + 排除项 + 受众。
技巧二:约束收紧(Constraint Tightening)
问题:输出技术上正确,但不符合工程使用需求。
Before:
Extract the email addresses from this text. {text}After:
Extract all valid email addresses from the following text. Requirements: - Return as a JSON array of strings - Return empty array [] if no emails found - Only include properly formatted emails (user@domain.tld) - Deduplicate - each email appears once - Sort alphabetically Text: {text} Emails:这一技巧的精华是把"需求"翻译成"可校验的输出契约":返回值类型、空值语义、合法性判定、去重、排序。这些约束让下游代码可以无脑json.loads后直接使用,无需容错。更复杂的输出契约设计(JSON Schema、function calling)可进一步参考 structured-outputs.md,其中包含枚举约束、嵌套对象、条件字段等 Schema 设计模式。
技巧三:示例校准(Example Calibration)
问题:Few-shot 示例与真实输入分布不匹配。
def calibrate_examples(example_pool: list, real_inputs: list, k: int = 5) -> list: """Select examples that match the distribution of real inputs.""" # Cluster real inputs real_clusters = cluster_by_embedding(real_inputs, n_clusters=k) # For each cluster, find best matching example calibrated = [] for cluster_center in real_clusters: best_match = max( example_pool, key=lambda ex: cosine_similarity(embed(ex["input"]), cluster_center) ) calibrated.append(best_match) return calibrated思路是:先把真实输入按语义聚类成 k 个簇,再从示例池中为每个簇挑选最相似的示例,从而保证选出的 k 个示例覆盖真实输入的多样性。这与 prompt-patterns.md 中"Match the distribution"和"3-5 examples typically optimal"的选择准则互相印证。相关指标(如每类准确率、各类别的 F1)可以参考 evaluation-frameworks.md 的分类评估代码,用classification_report检查示例校准是否真正改善了长尾类别。
技巧四:输出脚手架(Output Scaffolding)
问题:模型内容正确,但结构不符合预期。
Before:
Analyze this code for security issues.After:
Analyze this code for security issues using the following structure: ## Summary [One sentence overview] ## Issues Found For each issue: - **Severity:** [Critical/High/Medium/Low] - **Location:** [file:line or function name] - **Description:** [What's wrong] - **Fix:** [How to remediate] ## Recommendation [Overall assessment and priority order for fixes] Code: {code}输出脚手架把"自由发挥"变成"填空"。模型只需按给定骨架填充,天然规避了结构漂移。参考文档指出,如果连"填充"都不稳定,可以叠加 structured-outputs.md 中的输出包裹技术(<analysis>...</analysis>标签包裹 JSON)配合正则解析,可靠性更高。
Token 优化:让每一个 Token 都有价值
Token 即成本,也影响延迟与上下文质量。参考文档提供了不同策略的量化预期:
| Strategy | Savings | Risk | When to Use |
|---|---|---|---|
| Remove redundant instructions | 10-20% | Low | Always |
| Shorten examples | 20-40% | Medium | Token-constrained |
| Use abbreviations/symbols | 5-15% | Medium | Technical audiences |
| Compress context | 30-50% | High | Very long inputs |
| Switch to zero-shot | 40-60% | High | Simple tasks |
注意风险与收益成正比:压缩上下文和切换 zero-shot 收益最大,但信息丢失风险也最高,适合在简单任务上使用。
一个 180 → 45 Token 的经典案例
Before(180 tokens):
You are a helpful assistant that specializes in analyzing customer feedback and extracting sentiment information. Your task is to read the customer review provided below and determine whether the overall sentiment expressed in the review is positive, negative, or neutral. Please respond with exactly one word: either "positive", "negative", or "neutral". Do not include any other text, explanations, or formatting in your response. Customer Review: {review} Sentiment:After(45 tokens):
Classify sentiment as: positive, negative, or neutral. Reply with one word only. Review: {review} Sentiment:削减了约 75% 的 Token:长句身份设定压缩为一句祈使句,"one word only"同时完成了"只输出一个词 + 禁止多余解释"两件事。这份精简后的提示词与 SKILL.md 中的 zero-shot 示例风格一致。但要注意:精简是有边界的——prompt-patterns.md 指出简单任务适合 zero-shot,而需要格式引导的任务仍应保留示例,否则会出现格式错误。
量化 Token 影响
参考文档用tiktoken提供跨版本对比工具:
import tiktoken def compare_token_usage(prompt_v1: str, prompt_v2: str, model: str = "gpt-4") -> dict: """Compare token usage between two prompt versions.""" enc = tiktoken.encoding_for_model(model) v1_tokens = len(enc.encode(prompt_v1)) v2_tokens = len(enc.encode(prompt_v2)) return { "v1_tokens": v1_tokens, "v2_tokens": v2_tokens, "difference": v1_tokens - v2_tokens, "reduction_pct": ((v1_tokens - v2_tokens) / v1_tokens) * 100, "cost_impact": estimate_cost_savings(v1_tokens, v2_tokens, model) }需要留意:tiktoken是 OpenAI 系的编码工具,用于Claude 或其他模型时只能作为近似估算,实际以目标模型的 tokenizer 为准。estimate_cost_savings在参考文档中未给出实现,你需要按目标模型的实际单价补全。
上下文压缩技术
当输入过长时,参考文档提供了三级压缩管线:
def compress_context(text: str, target_ratio: float = 0.5) -> str: """Compress context while preserving key information.""" # Strategy 1: Extractive summarization key_sentences = extract_key_sentences(text, ratio=target_ratio) # Strategy 2: Remove redundancy deduplicated = remove_redundant_info(key_sentences) # Strategy 3: Use LLM for compression compressed = llm.complete(f""" Compress the following text to {int(target_ratio * 100)}% of its length. Preserve all facts, numbers, and key details. Remove only redundant or low-information content. Text: {deduplicated} Compressed: """) return compressed从抽取式压缩、去冗余到 LLM 生成式压缩,逐级提升压缩质量。这与 context-management.md 的上下文压缩策略表一致(抽取式摘要可省 30-50%,但存在信息损失风险),其 "Four-Bucket Approach"(关键指令常驻、近 3-5 轮对话原样保留、相关历史检索注入、其余历史摘要化)可以作为长期会话中 Token 治理的系统性方案。
A/B 测试框架:用统计替代感觉
"感觉新提示词更好"不是证据。参考文档提供了一个完整的 A/B 测试框架。
测试设计与随机化
class PromptABTest: """Framework for A/B testing prompt variants.""" def __init__(self, prompt_a: str, prompt_b: str, test_cases: list): self.prompt_a = prompt_a self.prompt_b = prompt_b self.test_cases = test_cases self.results = {"a": [], "b": []} def run(self, sample_size: int = 100) -> dict: """Run A/B test with randomized assignment.""" import random for test_case in random.sample(self.test_cases, sample_size): # Randomize order to avoid position bias if random.random() < 0.5: result_a = self.evaluate(self.prompt_a, test_case) result_b = self.evaluate(self.prompt_b, test_case) else: result_b = self.evaluate(self.prompt_b, test_case) result_a = self.evaluate(self.prompt_a, test_case) self.results["a"].append(result_a) self.results["b"].append(result_b) return self.analyze_results() def analyze_results(self) -> dict: """Statistical analysis of A/B test results.""" from scipy import stats scores_a = [r["score"] for r in self.results["a"]] scores_b = [r["score"] for r in self.results["b"]] t_stat, p_value = stats.ttest_ind(scores_a, scores_b) return { "prompt_a_mean": sum(scores_a) / len(scores_a), "prompt_b_mean": sum(scores_b) / len(scores_b), "p_value": p_value, "significant": p_value < 0.05, "winner": "a" if sum(scores_a) > sum(scores_b) else "b", "confidence": 1 - p_value }两个关键设计:
- 随机交换执行顺序(
random.random() < 0.5决定谁先跑)消除位置偏差——这与 evaluation-frameworks.md 中 LLM-as-Judge 的"双向对比消除位置偏差"是同一思想。 - 用 t 检验与 p 值判断差异是否显著,避免"均值高一点就认为赢"。
最小样本量计算
样本太少会得出无意义的结论。参考文档给出了基于 Cohen's h 的样本量公式:
def calculate_sample_size( baseline_rate: float, minimum_detectable_effect: float, significance_level: float = 0.05, power: float = 0.80 ) -> int: """Calculate required sample size for detecting a given effect.""" from scipy import stats # Effect size (Cohen's h for proportions) p1 = baseline_rate p2 = baseline_rate + minimum_detectable_effect h = 2 * (math.asin(math.sqrt(p1)) - math.asin(math.sqrt(p2))) # Required sample size per group z_alpha = stats.norm.ppf(1 - significance_level / 2) z_beta = stats.norm.ppf(power) n = 2 * ((z_alpha + z_beta) / h) ** 2 return math.ceil(n) # Example: Detect 5% improvement from 80% baseline # sample_size = calculate_sample_size(0.80, 0.05) # ~783 per group从注释示例可见:要在 80% 基线上检测 5% 的提升(显著性 0.05、统计功效 0.80),每组大约需要 783 个样本。想检测的效应越小,所需样本量越大——这解释了为什么"改了几个示例就宣布胜利"是不可靠的。
当 A/B 测试的评分本身依赖 LLM 评判时,可复用 evaluation-frameworks.md 的LLMJudge类(含 accuracy/relevance/clarity/completeness 四维评分与 pairwise 对比),并将其偏置缓解策略(位置、冗长、自偏好、锚定)纳入测试设计。
提示词版本控制:可回滚的演进
提示词是持续演进的生产资产,必须有版本管理。
版本注册表 Schema
参考文档给出 YAML 版注册表:
# prompt_registry.yaml prompts: sentiment_classifier: current: v2.1.0 versions: v1.0.0: file: prompts/sentiment/v1.0.0.txt date: 2024-01-15 metrics: accuracy: 0.82 latency_p50: 1.2s status: deprecated v2.0.0: file: prompts/sentiment/v2.0.0.txt date: 2024-02-01 metrics: accuracy: 0.89 latency_p50: 1.1s changes: - Added few-shot examples - Tightened output format status: deprecated v2.1.0: file: prompts/sentiment/v2.1.0.txt date: 2024-02-15 metrics: accuracy: 0.94 latency_p50: 1.0s changes: - Optimized examples for edge cases - Reduced token count by 30% status: production每个版本记录四类信息:文件位置(prompt 正文)、日期与作者、指标(accuracy、latency 等)、变更说明与状态(deprecated/production)。这让你随时可以回答三个问题:现在线上跑的是哪个版本?它比上一个版本改了什么?指标如何?
变更记录模板
配合注册表,每次发版填写一份变更记录:
## Prompt Change Record ### Version: v2.0.0 -> v2.1.0 ### Date: 2024-02-15 ### Author: [name] ### Problem Statement Accuracy dropped to 85% on sarcastic reviews (edge case category). ### Hypothesis Current examples don't include sarcastic tone, causing misclassification. ### Changes Made 1. Added 2 sarcastic review examples 2. Added instruction: "Consider tone and context, not just words" 3. Removed verbose instruction paragraph (token optimization) ### Test Results | Metric | v2.0.0 | v2.1.0 | Change | |--------|--------|--------|--------| | Overall accuracy | 89% | 94% | +5% | | Sarcasm accuracy | 62% | 91% | +29% | | Tokens | 156 | 109 | -30% | ### Rollback Plan Revert to v2.0.0 if accuracy drops below 90% in production.注意这个模板强制写Problem Statement(问题)→ Hypothesis(假设)→ Changes Made(改动)→ Test Results(结果)→ Rollback Plan(回滚),与优化循环一一对应。尤其"回滚计划"体现了生产意识:线上指标跌破阈值立即回退,而不是当场改提示词。
版本化的提示词还可以接入持续评估。参考 evaluation-frameworks.md 的测试套件目录结构(evaluation/test_cases/、evaluation/prompts/v1.0.0/、evaluation/results/{timestamp}_{prompt_version}/),以及其中的RegressionDetector——它对比新版本与基线的分套件准确率,一旦下降超过阈值就给出BLOCK建议,可与上述Rollback Plan机制联动。
常见优化误区
| Mistake | Why It's Wrong | Better Approach |
|---|---|---|
| Multiple changes at once | Can't identify what worked | One change per iteration |
| Testing on training examples | Overfitting to test set | Hold out validation set |
| Optimizing for edge cases first | May hurt common case | Fix common cases first |
| Ignoring latency/cost | Production constraints matter | Track all metrics |
| No baseline measurement | Can't prove improvement | Always measure first |
| Skipping failure analysis | Symptoms vs. root cause | Diagnose before changing |
六个误区中,前两个(同时改多个变量、用训练样本测试)本质上是把统计思维丢掉了——无法归因与过拟合会让所有后续迭代失去意义。中间两个是优先级错误:边界用例应当优化,但永远排在常见用例之后;延迟与成本与准确率同等重要,忽略它们会导致"实验室满分、生产不可用"。最后两个是纪律缺失:没有基线就无法证明改进,跳过失败分析就只能治标不治本。这些误区也对应 SKILL.md 的 Constraints 清单:必须量化测量、必须系统性版本管理、必须用匹配分布的 few-shot 示例、必须考虑 Token 成本与延迟。
优化决策树:按失败模式选择手段
面对表现不佳的提示词,参考文档给出了一棵快速决策树:
┌──────────────────────────┐ │ Prompt Underperforms │ └────────────┬─────────────┘ │ ┌────────────▼─────────────┐ │ What's the failure mode? │ └────────────┬─────────────┘ │ ┌────────────────────────┼────────────────────────┐ │ │ │ Format Issues Wrong Content Inconsistent │ │ │ ▼ ▼ ▼ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │ Add output │ │ Improve │ │ Add examples │ │ scaffolding │ │ instructions │ │ Lower temp │ │ Add examples │ │ Add context │ │ Add constraints│ └───────────────┘ │ Use CoT │ └───────────────┘ └───────────────┘【免费下载链接】claude-skills67 Specialized Skills for Full-Stack Developers. Transform Claude Code into your expert pair programmer.项目地址: https://gitcode.com/GitHub_Trending/claud/claude-skills
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考