PromptPrism 2.1
Measure which clauses in your prompt help, which hurt, and which fall within a declared equivalence margin — while quantifying item-sampling noise and gating prompt releases.

PromptPrism is a Python library and CLI (prompt-prism / prism) for prompt diagnostics, clause attribution, coverage-aware token pruning, noise-floor auditing, and fail-closed CI/CD release gating.
Instead of editing one clause at a time or acting on noisy benchmark swings, PromptPrism toggles binary prompt clauses in balanced orthogonal designs over a paired evaluation set and reports which clauses improve scores, which degrade scores, which pass equivalence and coverage checks for pruning, and when sample size N is too small to decide.
What PromptPrism Is — and Isn’t
Built for three production problems
- Attribute harmful clauses & prune redundant prompt bloat with a coverage gate (
prism tests, prism diagnose / exp.diagnose()):
Production prompts accumulate personas, guardrails, formatting contracts, and reasoning cues over time. Even when static system prefixes are discounted by prompt caching, harmful or redundant clauses still introduce instruction interference / attention dilution, extra latency and uncached output tokens, maintenance overhead, and direct token cost on dynamic or uncached prompt sections. With coverage-aware pruning (prism tests + diagnose --tests), PromptPrism blocks SAFE_TO_PRUNE whenever a conditional rule lacks targeted test coverage or fails targeted non-inferiority. Verdicts separate KEEP, KEEP_TARGETED, REMOVE_HARMFUL, CONFLICT_REVIEW, UNTESTED, SAFE_TO_PRUNE, and INCONCLUSIVE_NEED_MORE_ITEMS.
- Separate signal from item-sampling noise:
Small eval sets (50–150 items) exhibit high sampling variance. PromptPrism reports the item-sampling noise floor (
audit.noise_floor) alongside every factor contrast so teams do not ship edits driven by benchmark jitter.
- Gate prompt releases & detect behavioral drift (
prism certify & prism verify-cert):
prism verify-cert (offline CI gate, zero LLM calls): Verifies a saved SHA-256-hashed OperatingEnvelopeSpec certificate against live deployment settings (task_id, model_id, model_version, dataset_partition_hash, parser_hash, prompt_sha256, maximize, decoding_config, algorithm_version, perturbation_env_ids, and optional --max-epsilon). Exits non-zero whenever any declared boundary mismatches or the certificate did not pass.
- Scheduled
prism certify canary runs (behavioral drift check): Providers can update model weights without changing model_version, which offline hash checks cannot observe. Re-running prism certify on a scheduled perturbation/canary wave computes a paired simultaneous 95% upper bootstrap bound (U95_sim) on worst-case oriented drop and fails whenever U95_sim >= epsilon (distinguishing margin-exceeding drops from precision-limited sample sizes).
Why PromptPrism Instead of Black-Box Prompt Search?
No statistically significant peak-accuracy difference vs. equal-budget random or Bayesian clause search — plus clause attribution, baseline TOST equivalence, and noise-floor auditing from the exact same screening matrix. (Generating synthetic test sets with TestSetGenerator, evaluating targeted edge-case items, running untouched confirmation splits, and running multi-environment certify waves require additional LLM calls.)
Across our 1,033-cube retrospective audit (7,006,016 outcomes) and 501,300-call prospective benchmark, PromptPrism’s balanced orthogonal screens showed no statistically significant peak-accuracy difference relative to equal-budget balanced random search (+0.013 pp on MMLU, -0.327 pp on Cohort 2 BBH/LMentry, +0.22 pp on prospective Real-v4, p = 0.161) or Bayesian optimization (+0.14 pp on prospective Real-v4, p = 0.244), while lowering attribution error:
- Prospective 6-factor main-effect RMSE: 35.38% lower (winning
17/18 task–model cells).
- Retrospective main-effect RMSE: 1.01x–1.09x lower on MMLU 5-factor screens and 1.40x lower on Cohort-2 4-factor screens (
177/178 cubes).
- Retrospective 2-factor interaction (2FI) RMSE: 4.11x lower in-sample per task (2.64x held-out) on MMLU 5-factor 2FI models, avoiding the
55.2% rank-deficiency rate of 16-run balanced random screens.
From the screening matrix itself you also get:
- Per-clause causal attribution: identify which clauses help and which hurt, rather than only an opaque winning prompt.
- Calibrated inference & noise-floor diagnostics: contrast-specific item-clustered
t-tests achieve 4.0%–5.1% BH FDR at N >= 100 (vs. 18.4% for pooled fixed-block RCBD ANOVA).
- Coverage-aware pruning & fail-closed gating (with additional testgen/confirmation/perturbation calls): protect rare guardrails (
KEEP_TARGETED, UNTESTED, CONFLICT_REVIEW) and gate production deployments (prism verify-cert / prism certify).
(Scope boundary: PromptPrism audits and optimizes discrete modular binary prompt clauses that you define — it does not synthesize free-form wording rewrites. To optimize wording automatically, pair a prompt compiler such as DSPy MIPROv2 with PromptPrism to audit, prune, and certify the compiled prompt.)
Real Output Example (banking77 on gemini-2.5-flash)
Below is an audit excerpt from a live 1,920-call run on banking77_intent (N = 120 paired eval items × 16 balanced prompt runs on gemini-2.5-flash, equivalence margin |delta| < 0.02, measured input-token deltas), formatted as emitted by v2.1 CalibratedAttributionAudit.to_markdown() including the no-coverage warning and evidence-tier footer:
# PromptPrism Calibrated Attribution & Token-Pruning Audit (`exact_match`)
- **Optimization Direction:** `maximize`
- **Primary Inference:** Contrast-specific item-clustered `t`-test + Benjamini-Hochberg FDR (`alpha=0.05`)
- **Pruning Gate:** TOST practical equivalence (`|delta| < 0.0200`)
- **Paired Benchmark Items (`N`):** `120` across `16` experimental runs
- **Main-Effect Noise Floor:** `RMS_obs=0.0238`, `RMS_noise=0.0088`, `RMS_signal_corr=0.0221` (item noise accounts for **13.7%** of observed variance)
- **Estimated Safe Token Savings (`SAFE_TO_PRUNE`):** `8` tokens/prompt
- **Warning:** No coverage map provided: SAFE_TO_PRUNE does not imply the clause was exercised.
| Factor | Lvl 0 | Lvl 1 | Δ (L1-L0) | SE (Clust.) | 95% Interval | p (Clust.) | q (BH) | p (Flip) | TOST p | Verdict | Tokens |
|:---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---|:---:|
| **self_verification** | 0.9208 | 0.8979 | -0.0229 | 0.0063 | [-0.0353, -0.0105] | 0.0003867 | 0.001904 | 0.0009995 | 0.6786 | `REMOVE_HARMFUL` | 15 |
| **brief_reasoning** | 0.9271 | 0.8917 | -0.0354 | 0.0102 | [-0.0555, -0.0153] | 0.0006889 | 0.001904 | 0.0004998 | 0.9341 | `REMOVE_HARMFUL` | 12 |
| **grounding_guardrail** | 0.9229 | 0.8958 | -0.0271 | 0.0080 | [-0.0429, -0.0113] | 0.0009519 | 0.001904 | 0.001499 | 0.8114 | `REMOVE_HARMFUL` | 19 |
| **strict_output_contract** | 0.8979 | 0.9208 | +0.0229 | 0.0072 | [+0.0086, +0.0373] | 0.00198 | 0.00297 | 0.001999 | 0.656 | `KEEP` | 19 |
| **few_shot_demos** | 0.9000 | 0.9187 | +0.0187 | 0.0123 | [-0.0055, +0.0430] | 0.1287 | 0.1545 | 0.1459 | 0.4595 | `INCONCLUSIVE_NEED_MORE_ITEMS` | 63 |
| **specialist_persona** | 0.9083 | 0.9104 | +0.0021 | 0.0075 | [-0.0128, +0.0170] | 0.7828 | 0.7828 | 0.8841 | 0.009549 | `SAFE_TO_PRUNE` | 8 |
> **Evidence Tier:** `predicted` (attribution diagnostic on evaluated items only; validate any pruned or selected prompt on untouched confirmation items and issue a hashed `OperatingEnvelopeSpec` certificate before claiming perturbation stability).
Reading the audit:
- Three clauses degraded accuracy by
-2.29 to -3.54 pp (brief_reasoning, grounding_guardrail, self_verification; q < 0.002). Removing harmful clauses improves accuracy and cuts uncached output tokens — though for grounding_guardrail, note the no-coverage warning above: verify out-of-scope behavior with targeted tests before deleting a safety guardrail.
specialist_persona passes baseline TOST equivalence within +/-2 pp (TOST p = 0.0095, SAFE_TO_PRUNE).
strict_output_contract has a significant positive effect (+2.29 pp, q = 0.003, KEEP).
few_shot_demos has p = 0.129, but its 95% interval [-0.55 pp, +4.30 pp] crosses the +/-2 pp margin, so it is flagged INCONCLUSIVE_NEED_MORE_ITEMS rather than SAFE_TO_PRUNE.
Installation
PromptPrism requires Python >= 3.11 (ships PEP 561 type metadata via py.typed). It is not yet published on PyPI; install directly from GitHub:
pip install git+https://github.com/robsanmx/prompt_prism.git
# Optional extras
pip install "prompt-prism[viz] @ git+https://github.com/robsanmx/prompt_prism.git" # Matplotlib charts (lazy OO backend)
pip install "prompt-prism[cloud] @ git+https://github.com/robsanmx/prompt_prism.git" # LiteLLM (`LiteLLMClient` & CLI `--model`)
pip install "prompt-prism[deepeval] @ git+https://github.com/robsanmx/prompt_prism.git" # DeepEval >= 4.2.0,<5 LLM-as-a-Judge metrics
pip install "prompt-prism[legacy] @ git+https://github.com/robsanmx/prompt_prism.git" # statsmodels>=0.14.0 for deprecated `exp.analyze()` / `prism analyze`
For local development (includes pytest, black, isort, flake8, pyflakes):
git clone https://github.com/robsanmx/prompt_prism.git
cd prompt_prism
pip install -e ".[dev,viz]"
(Core v2.1 execution, diagnostics, testgen, and certification require zero statsmodels or matplotlib dependencies.)
Quickstart: Diagnose, Prune, and Gate
from pathlib import Path
from prompt_prism import (
CallableLLM,
ExactMatch,
Experiment,
F1Score,
Factor,
OperatingEnvelopeSpec,
evaluate_simultaneous_perturbation_certificate,
)
# 1. Define binary (Level 0 vs. Level 1) modular prompt clauses
factors = [
Factor.binary("specialist_persona", level_0_content="", level_1_content="You are an expert banking intent classifier."),
Factor.binary("brief_reasoning", level_0_content="", level_1_content="Explain briefly before answering."),
Factor.binary("few_shot_demos", level_0_content="", level_1_content="Example: 'lost my card' -> lost_or_stolen_card"),
Factor.binary("strict_output_contract", level_0_content="Answer concisely.", level_1_content="Return only the exact snake_case label."),
Factor.binary("grounding_guardrail", level_0_content="", level_1_content="Never invent unsupported labels."),
]
# 2. Build a balanced 16-run 2^(5-1) Resolution-V screen (omit `design` to auto-select via `recommend_design`)
# Note: supplying `system_prompt` sets `PromptTemplate.resolved_mode == "chat"`, passing
# `List[Dict[str, str]]` messages to `client` (pass `PromptTemplate.from_factors(..., mode="text")` for raw `str`).
exp = Experiment.from_factors(
factors=factors,
design="2(5-1)V",
system_prompt="Classify the customer banking request.",
data_template="Query: {{ query }}",
metrics=[ExactMatch(), F1Score()],
target_metric="exact_match",
title="Banking77 Clause Attribution & Pruning Audit",
)
# screen_dataset: list of dicts with template vars, `target`, and optional `id` (recommended N >= 100)
# Wrap plain callables with `CallableLLM(fn, model_id=...)` so `cache_db` isolates models.
client = CallableLLM(my_chat_llm_fn, model_id="gemini-2.5-flash")
results = exp.run(
dataset=screen_dataset,
client=client,
max_workers=4,
cache_db="prompt_cache.db",
)
# Export tabular screen results for CLI `prism diagnose` or downstream analysis
results.to_csv("screen_results.csv")
# 3. Attribute clauses (exp retains last_results internally; auto-estimates token deltas via chars/4)
audit = exp.diagnose(alpha=0.05, equivalence_margin=0.02, n_sign_flip=2000)
print(audit.to_markdown())
# Compile a deep-copied static pruned PromptTemplate (never mutates exp.template)
# Retains KEEP / KEEP_TARGETED / CONFLICT_REVIEW / UNTESTED / INCONCLUSIVE; prunes REMOVE_HARMFUL & SAFE_TO_PRUNE
pruned = exp.build_prompt_template(audit)
# 4. Evaluate `pruned` externally on untouched confirmation items and your perturbation transforms
# (`fmt_whitespace`, `word_paraphrase_1`, `temporal_wave_2`) in identical item order, then certify:
envelope = OperatingEnvelopeSpec(
task_id="banking77_intent",
model_id="gemini-2.5-flash",
model_version="gemini-2.5-flash",
dataset_partition_hash=confirmation_split_sha256, # e.g. test_set.split_sha256("confirmation")
parser_hash="sha256_exact_label_parser", # SHA-256 of your output parser / metric version
prompt_sha256=pruned.template_sha256(), # Binds certificate to this exact pruned prompt
perturbation_env_ids=["fmt_whitespace", "word_paraphrase_1", "temporal_wave_2"],
decoding_config={"temperature": 0.0, "max_output_tokens": 512, "seed": 42},
)
cert = evaluate_simultaneous_perturbation_certificate(
envelope=envelope,
reference_scores=conf_ref_scores, # Sequence[float], aligned 1:1 with each env below
perturbation_scores_by_env={
"fmt_whitespace": ws_scores,
"word_paraphrase_1": para_scores,
"temporal_wave_2": wave2_scores,
},
epsilon_stability=0.02,
n_bootstrap=2000,
)
print(cert.status, cert.d_stability_upper_95_sim, cert.diagnostic_note)
# Persist certificate JSON for offline CI gating via `prism verify-cert`
Path("stability_cert.json").write_text(cert.model_dump_json(indent=2) + "\n", encoding="utf-8")
(Need an offline runnable script first? See examples/ for end-to-end offline examples.)
1. Python exp.run(dataset=...) Schema
dataset accepts a Sequence[dict], a pandas.DataFrame, or a TestSet. Each row dictionary contains:
- Template variables: Every
{{ var }} referenced in data_template, PromptTemplate.structured_chat(input_fields=...), or master_template (avoid keys in RESERVED_TEST_CASE_KEYS; see Scope, Limitations & Security/Scalability Boundaries).
target (optional, configurable via target_col="target"): Ground-truth reference scored by ExactMatch, F1Score, LevenshteinSimilarity, RegexMatch, or CheckSuiteMetric. Falsy targets (0, 0.0, False) are preserved verbatim.
id (optional, configurable via id_col="id"): Unique item identifier stored as sample_id in ExperimentResults (falls back to row index if omitted).
targets_factors (optional): List or ;/,-separated string of factor IDs or names covered by this item for coverage-gated pruning.
- Automatic metadata passthrough:
env_id, group_id, kind, and split keys are forwarded into Trial.metadata (so exp.diagnose(env_col="env_id", ref_env="ref") works directly after exp.run()).
- Frozen
TestSet splits: exp.run(test_set, ...) evaluates split="discovery" by default (keeping confirmation untouched) and verifies frozen SHA-256 integrity. Pass split="confirmation" explicitly for held-out evaluation and call test_set.split_sha256("confirmation") for OperatingEnvelopeSpec.dataset_partition_hash.
Two Experiment constructors are supported: Experiment.from_factors(factors, design=..., system_prompt=..., data_template=..., metrics=[...], target_metric=...) builds a PromptTemplate automatically, whereas Experiment(factors, template=..., design=..., evaluator=Evaluator([...]), target_metric=...) takes an explicit PromptTemplate (such as PromptTemplate.structured_chat) and Evaluator. Run prism list-metrics to inspect exact target_metric column names (e.g., exact_match, f1_score, check_suite, deepeval_faithfulness).
2. LLM Client, Chat vs. Text Mode & Caching Contract
LLMClient protocol: Subclass prompt_prism.core.llm.LLMClient and implement generate(self, prompt: str | list[dict[str, str]], **kwargs) -> LLMResponse (setting model_id: Optional[str] for cache partitioning).
CallableLLM(fn, model_id=...): Automatically wraps plain callables fn(prompt, ...) -> str | LLMResponse. Inspects fn’s signature once at initialization so extra RunConfig.params kwargs are forwarded only if accepted.
LiteLLMClient(model="gemini/gemini-2.5-flash", temperature=0.0, timeout=60.0): Built-in provider client (from prompt_prism import LiteLLMClient; requires prompt-prism[cloud]) backed by LiteLLM using standard provider API environment variables (GEMINI_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.). Also powers CLI --model and --tagger-model.
- Chat vs. Text rendering (
PromptTemplate.mode): PromptTemplate.mode defaults to "auto". Whenever system_prompt or any section role is set — including Experiment.from_factors(..., system_prompt=...) and PromptTemplate.structured_chat(...) — resolved_mode becomes "chat" and ExperimentRunner passes List[Dict[str, str]] ([{"role": "system", ...}, {"role": "user", ...}]) to client, NOT a raw str. Set mode="text" explicitly (or omit system_prompt/roles) if your callable only accepts str.
- Prompt assembly & output parsing:
PromptTemplate.from_factors() orders optional system_prompt (role="system") first, then each factor in order as a literal (interpolate=False) section (omitting empty level_0_content=""), then data_template (interpolate=True, sandboxed Jinja2) at the end. When prompts emit structured prefixes such as FINAL_ANSWER: <label>, parse the response inside a CustomMetric (or match the prefixed target) and hash your parser code/version into parser_hash.
- Cache-key safety (
ResponseCache): cache_db uses a thread-safe WAL SQLiteKVCache keyed on canonical JSON over (schema=2, prompt_format, prompt_content, model_id, run.params). Always set model_id on CallableLLM (or LiteLLMClient) when sharing a cache across models or decoding settings, and omit cache_db on stochastic repeat perturbation waves so repeat passes invoke the model freshly.
3. CLI Configuration, Data & Client File Schemas
Click to expand exact schemas: factors.yaml, template.yaml, seeds.jsonl, screen_results.csv, stability_wave.csv, review.csv, and CLI --client
factors.yaml (strict Pydantic schema; top-level list or factors: mapping):factors:
- name: specialist_persona
level_0: ""
level_1: "You are a senior banking classifier."
clause_role: global_scaffold # conditional_rule | global_scaffold (optional)
- name: null_date_rule
level_0_content: ""
level_1_content: "If no date is present, set date to null."
clause_role: conditional_rule
template.yaml (strict Pydantic; mutually exclusive shorthand system_prompt/data_template, sections:, or master_template:):system_prompt: "Extract structured JSON from the input."
data_template: "Document: {{ document }}"
mode: chat # auto (default) | text | chat
seeds.jsonl (one JSON object per line; .json, .yaml, .csv also supported):{"document": "Invoice #1042 from Acme Corp for $250.", "target": "{\"vendor\":\"Acme Corp\",\"date\":null}"}
screen_results.csv (exported by results.to_csv("screen_results.csv") for prism diagnose):
Columns: run_id, sample_id, binary {0, 1} or {-1, +1} factor columns, numeric metric column (e.g. exact_match or check_suite), optional targets_factors (JSON list or ;/,-separated factor IDs/names), optional env_id. If --factors is omitted, prism diagnose auto-detects binary numeric columns having exactly 2 distinct values in {0,1} or {-1,1} while excluding known built-in/DeepEval metric and metadata columns.
stability_wave.csv (input to prism certify):
Required columns: sample_id (or --sample-col), env_id (or --env-col, containing ref plus every perturbation env), and numeric --target score column. Optional: group_id (--group-col, paired cluster bootstrap) and returned_model_version (--version-col, fail-closed provider-version auditing; nulls rejected). Strict 1:1 sample_id bijection is enforced between ref and every perturbation environment.
review.csv (exported by prism tests review export, CSV-only):
Columns: id, split, kind, intended_factor, intended_factor_name, tagger_factors, tagger_agrees, inputs, checks, reference_pass, reference_fail, review, accept. Tagger-disagreed and untagged targeted items are sorted first. Edit accept (yes/no) or review (accepted/rejected/pending) and pass the file to prism tests review import.
- CLI
--client module.path:callable contract:
Imports module.path strictly from installed packages or PYTHONPATH (PromptPrism does not add CWD to sys.path). The resolved attribute may be an LLMClient instance, an LLMClient subclass (instantiated with zero args), or a callable fn(prompt, ...) -> str | LLMResponse (wrapped in CallableLLM).
No Eval Set Yet? Generate a Frozen, Coverage-Tagged Test Set
When you lack N >= 100 hand-labelled items — or baseline traffic rarely exercises conditional rules (e.g., “if no date is present, return null” or “if out of scope, reply out_of_scope”) — TestSetGenerator (or prism tests) builds a frozen, scored, split-protected test set:
- Clause-role separation:
conditional_rule clauses receive targeted edge-case checks; global_scaffold clauses (persona, reasoning cue, few-shot demos, self-verification) receive hard/ambiguous inputs scored strictly by the baseline task metric to avoid tautological surface checks. If metadata={"clause_role": ...} is omitted, TestSetGenerator classifies roles automatically (emitting a warning if it falls back to heuristics).
- Deterministic checks first: Prefers
exact, regex, contains, not_contains, and json_schema (filtered by (reference_pass, reference_fail) sanity checks and near-duplicate Jaccard deduplication); llm_judge is a prompt-isolated fallback (judge_fallback=True by default).
- Blind coverage tagging & fail-closed agreement: Pass a separate
temperature=0.0 tagger_client (omitting tagger_client emits a UserWarning and falls back to self-tagging with the generator client). Under require_tag_agreement=True (default), targeted items where tagger_agrees is False or tagger_agrees is None are excluded from coverage unless explicitly accepted in review. Cases are stratified by (intended_factor, tagger_agrees) into discovery / confirmation splits and frozen atomically (cases.jsonl + manifest.json) with canonical-JSON SHA-256 hashes.
from prompt_prism import (
CheckSuiteMetric,
Evaluator,
Experiment,
Factor,
JudgeCache,
PromptTemplate,
TestSetGenerator,
)
factors = [
Factor.binary("specialist_persona", "", "You are a senior extraction specialist.", metadata={"clause_role": "global_scaffold"}),
Factor.binary("brief_reasoning", "", "Explain briefly before outputting JSON.", metadata={"clause_role": "global_scaffold"}),
Factor.binary("null_date_rule", "", "If the input has no date, set date to null.", metadata={"clause_role": "conditional_rule"}),
Factor.binary("strict_json_contract", "Return the fields.", "Return ONLY raw JSON with keys vendor, date, total.", metadata={"clause_role": "conditional_rule"}),
]
template = PromptTemplate.from_factors(
factors,
system_prompt="Extract structured JSON from the input.",
data_template="Document: {{ document }}",
)
# 1. Generate, sanity-filter, blind-tag, split (discovery/confirmation), and freeze
# Set temperature ~0.7 on generator_llm for diversity; keep temperature=0.0 on tagger_llm and model_under_test.
gen = TestSetGenerator(
client=generator_llm, # Prefer a different model than model_under_test
tagger_client=tagger_llm, # Independent blind tagger (temperature=0.0)
n_baseline_discovery=100,
n_per_factor_discovery=35,
)
test_set = gen.generate(factors, template, task_description="Structured invoice extraction", freeze=True)
test_set.save("tests/extraction_suite")
# 2. Evaluate on `discovery` split (default; keeps `confirmation` untouched)
# Pass `judge_client` + `judge_cache` if any generated cases use `llm_judge` checks
# (or omit `judge_client` to fall back to DeepEval GEval with `prompt-prism[deepeval]`).
check_metric = CheckSuiteMetric(
judge_client=judge_llm,
judge_cache=JudgeCache(db_path="judge_cache.db"),
)
exp = Experiment(
factors=factors,
template=template,
design="2(4-1)IV", # 4 binary factors in 8 Resolution-IV runs (or design=None for recommend_design)
evaluator=Evaluator([check_metric]),
target_metric="check_suite",
)
results = exp.run(test_set, client=model_under_test, cache_db="prompt_cache.db")
# 3. Coverage-gated audit (schema_version="2.1.0", evidence_tier="predicted (synthetic tests)")
audit = exp.diagnose(equivalence_margin=0.02)
print(audit.to_markdown())
# 4. Later, confirm the pruned prompt on untouched `confirmation` items and hash the partition:
pruned = exp.build_prompt_template(audit)
conf_results = exp.run(test_set, client=model_under_test, split="confirmation")
conf_partition_hash = test_set.split_sha256("confirmation")
Perturbation-Resilient Prompting & DSPy Audit
Flat single-user prompts with plain-text delimiter headers (e.g., [QUERY]) are more sensitive to formatting and paraphrase shifts than native multi-turn chat templates with structured field tags and in-domain demos. PromptPrism provides four stability primitives that work standalone or to audit compiled DSPy MIPROv2 prompts (unpack a compiled DSPy program’s instruction and bootstrapped demos into Factor.binary + FactorSet.from_candidate_demos, run a 2^(k-p) screen, prune SAFE_TO_PRUNE pieces with exp.build_prompt_template(audit), and certify):
- Multi-turn chat framing (
PromptTemplate.structured_chat): PromptComposer.compose_messages() merges only consecutive same-role sections, preserving alternating user/assistant demo turns and framing inputs with xml (<query>...</query>), brackets ([[ ## query ## ]]), or plain (query: ...) delimiters (mode="chat").
- In-domain demos as binary DOE factors (
Factor.demo / FactorSet.from_candidate_demos): Convert candidate or DSPy-bootstrapped demos into binary factors so TOST keeps only demos that earn their tokens.
- Stability-aware attribution (
diagnose(..., env_col="env_id", ref_env="ref")): Isolates clean main effects on ref_env, aggregates paired perturbation drops (ref - perturbed, oriented by maximize) per environment first with BH FDR, tags clauses STABILIZING / FRAGILE / NEUTRAL, blocks STABILIZING clauses from SAFE_TO_PRUNE, and appends an exploratory warning if a single-environment adverse drop is masked by the cross-environment mean.
- Precision-vs-margin certificate diagnostics (
evaluate_simultaneous_perturbation_certificate / prism certify): Reports worst_env_id, per_env_drops, per_env_se, repeat_noise_se, recommended_min_n, and diagnostic_note separating margin-exceeding drops (max_drop >= epsilon) from precision-limited FAIL results (max_drop < epsilon but U95_sim >= epsilon).
from prompt_prism import (
CustomMetric,
Evaluator,
Experiment,
Factor,
FactorSet,
PromptTemplate,
)
fset = FactorSet.from_candidate_demos(
demos=[
{"query": "My card is stuck in the ATM", "target": "card_swallowed"},
{"query": "Transfer still not showing up", "target": "balance_not_updated_after_bank_transfer"},
],
input_fields=["query"],
output_key="target",
field_style="xml",
output_prefix="FINAL_ANSWER: ",
multi_turn=True,
extra_factors=[
Factor.binary("strict_contract", "Answer briefly.", "Return ONLY FINAL_ANSWER: <label>."),
],
)
template = PromptTemplate.structured_chat(
fset,
system_prompt="Classify the banking support query.",
input_fields=["query"],
field_style="xml",
)
def exact_prefixed_label(pred: str, target: str) -> float:
cleaned = pred.split("FINAL_ANSWER:", 1)[-1].strip()
return float(cleaned.lower() == str(target).strip().lower())
# 3 binary factors -> design=None selects 8-run FullFactorial via recommend_design()
exp = Experiment(
factors=fset,
template=template,
design=None,
evaluator=Evaluator([CustomMetric(exact_prefixed_label, name="label_acc")]),
target_metric="label_acc",
)
# multi_env_dataset includes rows with env_id="ref" and perturbation envs (e.g. "fmt_whitespace", "word_paraphrase_1")
results = exp.run(multi_env_dataset, client=chat_client, cache_db="prompt_cache.db")
audit = exp.diagnose(equivalence_margin=0.02, env_col="env_id", ref_env="ref")
Live Benchmark (gemini-2.5-flash, N = 240 Confirmation)
All live DSPy and PromptPrism-Native results below are scoped to pinned gemini-2.5-flash (temperature=0.0, thinkingBudget=0, N = 240 untouched confirmation items across 5 perturbation environments: repeat_r2, fmt_whitespace, fmt_delimiter, word_paraphrase_1, word_paraphrase_2). Definitions: U95_sim (cert.d_stability_upper_95_sim) is the simultaneous 95% upper bound on worst-case drop (< 0.02 required for PASS); inner-field perturbations modify text inside framed fields (DSPy parity), whereas harsh outer-shell perturbations alter outer prompt delimiters/framing; Pro Proposer Calls counts gemini-2.5-pro compilation calls used by DSPy MIPROv2; Scaffold-held keeps xml_multiturn + strict_contract fixed while pruning optional demos.
| Task |
Variant |
Clean (ref) |
Max Perturb. Drop |
U95_sim (< 0.02) |
Cert |
Prompt / Out Tok |
Pro Proposer Calls |
| Banking77 |
Flat single-user PromptPrism (generic demos) |
95.42% |
2.92 pp (fmt_delimiter) |
0.0542 |
FAIL |
290 / 9.5 |
0 |
| Banking77 |
DSPy MIPROv2 Full (inner-field) |
95.83% |
0.42 pp (fmt_delimiter) |
0.0195 |
PASS |
1,182 / 17.7 |
11 |
| Banking77 |
DSPy → PromptPrism Pruned (TOST 2(5-1)V) |
95.83% |
0.00 pp (repeat_r2) |
0.0083 |
PASS |
719 (-39.2%) / 17.7 |
11 |
| Banking77 |
PromptPrism-Native Stabilized (inner / outer) |
96.25% / 95.42% |
0.00 pp / 0.00 pp |
0.0178 / 0.0018 |
PASS / PASS |
717–729 / 9.5 |
0 |
| SQuAD 2.0 |
DSPy MIPROv2 Full (inner-field) |
95.25% |
0.05 pp |
0.0045 |
PASS |
1,191 / 17.5 |
11 |
| SQuAD 2.0 |
DSPy → PromptPrism Pruned (TOST 2(5-1)V) |
94.77% |
0.39 pp |
0.0116 |
PASS |
512 (-57.0%) / 17.8 |
11 |
| SQuAD 2.0 |
PromptPrism-Native Scaffold-held (inner / outer) |
92.62% / 93.10% |
-0.18 pp / -0.14 pp |
0.0169 / 0.0150 |
PASS / PASS |
308–327 / 9.3–9.8 |
0 |
| GSM8K |
DSPy MIPROv2 Full (inner-field) |
94.58% |
0.42 pp |
0.0193 |
PASS |
317 / 224.8 |
11 |
| GSM8K |
PromptPrism-Native Scaffold-held (inner / outer) |
95.83% / 94.17% |
0.42 pp / -1.25 pp |
0.0242 / 0.0062 |
FAIL(prec.) / PASS |
105–124 / 162.4–177.6 |
0 |
- Tradeoffs across tasks (
gemini-2.5-flash): On Banking77, Native Stabilized ties DSPy Full (+0.42 pp, paired p = 0.656) with -39% prompt tokens and zero proposer calls. On SQuAD 2.0, PromptPrism-Native Scaffold-held cuts -74% prompt tokens and passes both inner and outer stability, but trails DSPy Full on clean reading comprehension (92.62% vs. 95.25%, -2.63 pp, p = 0.0047) — whereas auditing DSPy Full with PromptPrism retains 94.77% (-0.48 pp, p = 0.394) at -57.0% tokens and PASS. On GSM8K, Scaffold-held (0 demos) reaches 95.83% (+1.25 pp, p = 0.258, -67% prompt tokens), passes harsh outer-shell stability (U95_sim = 0.0062), and has 0.42 pp max drop (0.0000 repeat-pass noise) on inner-field with a precision-limited FAIL (U95_sim = 0.0242, recommended_min_n = 383).
- Out-of-scope Banking77 guardrail: On
N = 20 held-out out-of-scope Banking77 queries, both DSPy Full and un-gated PromptPrism scored 0/20 (0%), while enabling the coverage-rescued guardrail (KEEP_TARGETED) passed 17/20 (85%).
CLI Usage (prompt-prism / prism)
There is no prism run command: execute screening and perturbation evaluations in Python (exporting results.to_csv("screen_results.csv") or your own CSV/JSONL harness), then run prism diagnose, prism certify, and prism verify-cert. Both prism --version and prism verify-cert load zero scientific/plotting libraries (pandas, numpy, scipy, matplotlib).
prism --version
# prompt-prism 2.1.0
# 1. Inspect available orthogonal plans, aliasing, design matrices, and metric names
prism list-designs --factors 6 --min-resolution 4
prism alias --plan "2(6-2)IV"
prism design --factors 6 --plan "2(6-2)IV" --output design_matrix.csv
prism list-metrics
# 2. Generate, inspect, CSV-review, freeze, and refresh scored test sets
prism tests generate \
--factors factors.yaml \
--template template.yaml \
--task "Classify banking customer intents" \
--seed-examples seeds.jsonl \
--n-baseline-discovery 100 \
--n-per-factor-discovery 35 \
--temperature 0.7 \
--client mypkg.clients:generator \
--tagger-client mypkg.clients:tagger \
--out tests/banking77/
# Or with optional cloud extra (`pip install "prompt-prism[cloud]"`):
# --model gemini/gemini-2.5-flash --tagger-model gemini/gemini-2.5-flash
prism tests stats tests/banking77/
prism tests review export tests/banking77/ --out review.csv # CSV-only (formula-neutralized)
prism tests review import tests/banking77/ review.csv # updates changed rows & re-freezes
prism tests freeze tests/banking77/ # freeze a --no-freeze draft
# Regenerate ONLY the confirmation split (preserving discovery) after confirmation items are spent:
prism tests generate --factors factors.yaml --template template.yaml \
--client mypkg.clients:generator --refresh-confirmation tests/banking77/
# 3. Calibrated clause attribution, noise-floor audit & coverage-gated pruning verdicts
# Add `--env-col env_id --ref-env ref` for STABILIZING / FRAGILE attribution; add `--minimize` for lower-is-better metrics.
prism diagnose \
--data screen_results.csv \
--target check_suite \
--tests tests/banking77/ \
--sample-col sample_id \
--prune-margin 0.02 \
--token-costs specialist_persona=8,brief_reasoning=12,few_shot_demos=63,strict_output_contract=19 \
--output-report diag.md \
--json-out diag.json
# 4. Issue a stability certificate on untouched confirmation + perturbation/canary wave
# Exit code 2 on FAIL or INVALID/OUT_OF_ENVELOPE when --fail-on-error is set.
# Add `--minimize` for latency/error metrics and `--version-col <col>` for provider version auditing.
# Re-run `prism certify` on scheduled canary batches to catch silent provider weight drift when model_version does not change.
prism certify \
--data stability_wave.csv \
--target score \
--sample-col sample_id \
--env-col env_id \
--ref-env ref \
--task-id banking77_intent \
--model-id gemini-2.5-flash \
--model-version gemini-2.5-flash \
--dataset-hash sha256_conf_split \
--parser-hash sha256_exact_label \
--prompt-sha256 sha256_pruned_prompt \
--decoding-json '{"temperature":0.0,"max_output_tokens":512,"seed":42}' \
--epsilon 0.02 \
--output stability_cert.json \
--fail-on-error
# 5. Offline CI/CD config gate (zero LLM calls) — catches declared config/prompt/model/parser/env changes.
# Exits 0 ONLY when cert status is PASS, epsilon <= --max-epsilon, and every declared envelope field matches (exits 1 otherwise).
prism verify-cert \
--cert stability_cert.json \
--task-id banking77_intent \
--model-id gemini-2.5-flash \
--model-version gemini-2.5-flash \
--dataset-hash sha256_conf_split \
--parser-hash sha256_exact_label \
--prompt-sha256 sha256_pruned_prompt \
--max-epsilon 0.02 \
--decoding-json '{"temperature":0.0,"max_output_tokens":512,"seed":42}' \
--envs fmt_whitespace word_paraphrase_1 temporal_wave_2
7-Verdict Reference & How the Statistics Work
Coverage- and Stability-Aware Pruning Verdicts (schema_version = "2.1.0")
Let F denote the primary baseline evaluation set, T denote the targeted covered subset for clause $j$ (n_T paired items, threshold min_targeted_items = 20), s = +1 for maximize=True (-1 for maximize=False), oriented_delta_F = s * delta_F, and oriented_delta_T = s * delta_T (positive means Level 1 helps). When env_col is provided, a separate BH-corrected paired test on per-environment drops (s * (ref - perturbed)) tags each clause STABILIZING (q_drop < alpha and stability_drop_delta < 0), FRAGILE (q_drop < alpha and stability_drop_delta > 0, emitting an audit warning), or NEUTRAL.
| Priority |
Verdict |
Trigger Condition (F, T, and STABILIZING) |
build_prompt_template() Default |
| 1 |
CONFLICT_REVIEW |
Baseline helps while targeted hurts (f_helps & t_hurts); OR baseline hurts with thin/missing coverage (n_T < min_targeted_items), targeted benefit (t_helps), failed targeted non-inferiority (p_ni_T >= alpha), or STABILIZING; OR targeted hurts while STABILIZING. |
Keep Level 1 (manual review) |
| 2 |
KEEP |
Baseline helps (q_F < alpha, oriented_delta_F > 0, not t_hurts); OR clean-neutral and not targeted-harmful/untested with stability_verdict == "STABILIZING". |
Keep Level 1 |
| 3 |
REMOVE_HARMFUL |
Baseline hurts (q_F < alpha, oriented_delta_F < 0) with adequate coverage & passing targeted NI (p_ni_T < alpha, not STABILIZING); OR targeted hurts (q_T < alpha, oriented_delta_T < 0, not STABILIZING). |
Prune to Level 0 |
| 4 |
UNTESTED |
Coverage map supplied, baseline non-significant, and n_T == 0 (applies to any factor with zero covered items). |
Keep Level 1 |
| 5 |
KEEP_TARGETED |
Baseline non-significant, n_T >= min_targeted_items, and targeted helps (q_T < alpha, oriented_delta_T > 0). |
Keep Level 1 |
| 6 |
SAFE_TO_PRUNE |
Baseline TOST passes (tost_p_value < alpha, |delta_F| < equivalence_margin), not STABILIZING, and (when coverage is present) n_T >= min_targeted_items with targeted non-inferiority p_noninferiority_targeted < alpha (H0: oriented_delta_T >= targeted_margin vs. H1: oriented_delta_T < targeted_margin). |
Prune to Level 0 |
| 7 |
INCONCLUSIVE_NEED_MORE_ITEMS |
Neither significant nor equivalent/non-inferior (including 0 < n_T < min_targeted_items). |
Keep Level 1 |
Statistical Methodology & Notation
- DOE notation (
2^(k-p), Resolution, recommend_design): Testing $k$ binary clauses in full requires $2^k$ runs (FullFactorial). A $2^{k-p}$ fractional factorial runs $2^{k-p}$ balanced combinations: Resolution III (2(5-2)III, PB-12) confounds main effects with 2-factor interactions (2FI, requiring follow-up confirmation); Resolution IV (2(6-2)IV, 2(8-4)IV) keeps main effects clear of 2FIs while 2FIs alias each other; Resolution V+ (2(5-1)V, 2(6-1)VI) keeps main effects and 2FIs unaliased. Use recommend_design(factors, max_runs=..., min_resolution=...) (or pass design=None to Experiment) and inspect confounding with prism alias --plan <ID>.
- Item-clustered
t-tests vs. pooled RCBD ANOVA: Across 1,033 multi-prompt cubes (7,006,016 outcomes), pooled fixed-block Randomized Complete Block Design (RCBD) ANOVA underestimated contrast variance on high-variance formatting factors and inflated global BH FDR to 18.4%. PromptPrism computes contrast-specific per-item paired differences (df = N - 1), achieving 4.0%–5.1% FDR at N >= 100, paired with a 2,000-draw Rademacher sign-flip randomization test for smaller N.
- Noise-floor decomposition (
audit.noise_floor): Across our benchmark suite, 79%–85% of apparent per-task higher-order variance is item-sampling noise. audit.noise_floor exposes rms_observed ($\sqrt{\frac{1}{k}\sum \hat{\Delta}j^2}$, shown as RMS_obs), rms_item_noise ($\sqrt{\frac{1}{k}\sum \mathrm{SE}j^2}$, shown as RMS_noise), rms_signal_corrected ($\sqrt{\max(0, \mathrm{RMS}{\text{obs}}^2 - \mathrm{RMS}{\text{noise}}^2)}$, shown as RMS_signal_corr), and noise_variance_share_pct.
- Zero-variance finite-sample bounds: When paired variance collapses (
se <= 1e-12), PromptPrism never auto-passes TOST, targeted non-inferiority, or stability certification on small N. Bounded [0, 1] scores use exact Clopper-Pearson finite-sample bounds (1 - alpha**(1/n) for TOST/NI and 1 - (alpha / E)**(1/n_g) across $E$ perturbation environments); unbounded metrics (e.g., latency_ms) fail closed to INCONCLUSIVE_NEED_MORE_ITEMS / INVALID/OUT_OF_ENVELOPE.
- Coverage-aware pruning calibration: In Monte Carlo calibration (
2(6-2)IV, N_base = 100, sigma_c in {0.08, 0.11, 0.15}), baseline-only TOST falsely deleted real conditional rules at 18%–95% when trigger frequency p in {0.02, 0.05}. Adding targeted non-inferiority (min_targeted_items = 20, default targeted_margin = max(2 * equivalence_margin, 0.08)) reduced real-rule false prunes to 0.0% across the tested true targeted effect sizes tau_T in {0.15, 0.25} while retaining 94%–100% targeted non-inferiority pruning power on null clauses at n_per_factor_discovery = 35.
- Simultaneous perturbation certificates (
PASS / FAIL / INVALID/OUT_OF_ENVELOPE): evaluate_simultaneous_perturbation_certificate() computes a paired cluster studentized bootstrap-$t$ simultaneous 95% upper bound U95_sim (cert.d_stability_upper_95_sim) across all registered perturbation environments (supporting both maximize=True and maximize=False / --minimize).
PASS: all envelope and pairing checks succeed and U95_sim < epsilon_stability.
FAIL: envelope and pairing checks succeed, but U95_sim >= epsilon_stability — cert.diagnostic_note distinguishes a margin-exceeding drop (d_stability_estimate >= epsilon_stability) from a precision-limited FAIL (d_stability_estimate < epsilon_stability, reporting recommended_min_n).
INVALID/OUT_OF_ENVELOPE: failed closed due to missing or unregistered environments, unpaired or non-finite scores, provider model_version drift, fewer than min_paired_groups (default 20) paired groups, empty perturbation_env_ids, or zero variance on an unbounded metric.
- Evidence tiers (
evidence_tier vs. evidence_state): CalibratedAttributionAudit.evidence_tier reports "predicted" (real/human items) or "predicted (synthetic tests)" (TestSet synthetic/mixed items). EnvelopeValidationResult.evidence_state (and legacy PromptSelectionReport) tracks promotion from "predicted" to "confirmation-validated" to "stability-certified".
Scope, Limitations & Security/Scalability Boundaries
- Binary 2-level factors in
diagnose() & coupled clauses:
2^(k-p) fractional factorial designs, Plackett-Burman designs, and exp.diagnose() / run_calibrated_attribution_audit() / prism diagnose operate strictly on binary 2-level factors ({0, 1} or {-1, +1}); >2-level columns raise ValueError. Independent on/off ablation assumes each clause can be toggled without breaking prompt coherence. For interdependent rules or coupled tool schemas, bundle coupled instructions into an intact Level-0 vs. Level-1 alternative block. Multi-level (>2 levels) exploration requires FullFactorialGenerator paired with the deprecated [legacy] exp.analyze() workflow.
- Simultaneous Multi-Factor Pruning Hazard:
Marginal TOST (
|delta_j| < margin) certifies removing clause $j$ while the remaining prompt scaffolds stay intact — it does not certify deleting all marginally neutral formatting anchors simultaneously onto an unobserved all-off corner. In 2(6-2)IV screening on gemini-2.5-flash, deleting all 6 marginally SAFE_TO_PRUNE anchors at once dropped GSM8K accuracy by -8.33 pp (95.83% -> 87.50%, p = 7.0e-5) and caused SQuAD 2.0 to ramble to 469.2 output tokens (-2.57 pp perturbation drop). Hold structural framing scaffolds (e.g., xml_multiturn and strict output contracts) fixed, prune optional clauses/demos, and always re-confirm on untouched confirmation items after multi-clause deletion.
- Single-turn scope:
Empirical validation covers single-turn tasks (classification, extraction, grounded QA, math, code). Running
N >= 100 paired items × 16 runs × perturbations over end-to-end multi-turn agent trajectories is costly and high-variance; target isolated single-step nodes (intent router, tool selector, RAG groundedness/reranker, output verifier) or replayed state snapshots.
- Security & Scalability Boundaries:
- Design & runtime limits: The built-in catalog provides 27
2^(k-p) designs (k = 3..15, up to 128 runs); Plackett-Burman supports up to k = 23 factors (N <= 24 runs); unconstrained recommend_design(max_runs=None) caps FullFactorial fallback at k <= 10 (1,024 runs). ExperimentRunner schedules R x N trials in-memory via ThreadPoolExecutor backed by WAL-mode SQLiteKVCache (max_memory_entries=10_000).
- Security containment:
PromptSection.interpolate defaults to False (literal text for clauses and error-mined demos), interpolated sections and master_template use ImmutableSandboxedEnvironment(StrictUndefined) (blocking Jinja2 SSTI), CheckSpec(kind="custom") dynamic imports are removed, CSV review exports neutralize leading =+-@\t\r, and CLI --client never mutates sys.path with CWD. See SECURITY.md.
- Reserved input keys (
RESERVED_TEST_CASE_KEYS): Avoid using these names as template data variables in TestSet / TestSetGenerator: id, target, checks, targets_factors, intended_factor, tagger_factors, tagger_agrees, kind, split, source, review, and internal __* keys (__prompt__, __run_id__, __sample_id__, __test_inputs__).
LLM-as-a-Judge & DeepEval Integration
PromptPrism integrates with DeepEval >= 4.2.0, < 5 (enforced at runtime) for reference-based (g_eval, contextual_recall, contextual_precision, json_correctness) and reference-free (answer_relevancy, faithfulness, hallucination, toxicity, bias, contextual_relevancy, summarization) scoring with SQLite JudgeCache.
Configure the judge model via model=... (e.g., "gpt-4o-mini" or a DeepEval DeepEvalBaseLLM) and its provider API key env var (e.g., OPENAI_API_KEY). Dataset keys auto-map to DeepEval fields (input/question/query -> input without ever leaking __prompt__; target/expected_output/ground_truth/gold_answer -> expected_output; context/documents -> context; retrieval_context/context/documents -> retrieval_context, all overridable via *_key kwargs). Note that deepeval_metric("g_eval", ...) accepts either criteria or evaluation_steps (mutually exclusive):
from prompt_prism import deepeval_metric, JudgeCache
judge_cache = JudgeCache(db_path="judge_cache.db")
factual_geval = deepeval_metric(
"g_eval",
name="factual_accuracy",
evaluation_steps=[
"Check that key facts and numbers in actual output match expected output.",
"Penalize fabricated or contradictory claims.",
],
evaluation_params=["INPUT", "ACTUAL_OUTPUT", "EXPECTED_OUTPUT"],
model="gpt-4o-mini",
cache=judge_cache,
)
faithfulness = deepeval_metric("faithfulness", model="gpt-4o-mini", cache=judge_cache)
Score direction (deepeval >= 4.2.0): Under deepeval >= 4.2.0, every metric is higher-is-better (1.0 = pass / no hallucination / no toxicity; 0.0 = fail). deepeval <= 4.1.10 inverted hallucination, toxicity, and bias, so PromptPrism enforces >= 4.2.0 at runtime. Experiment.diagnose() infers direction from Metric.higher_is_better (defaulting latency_ms to maximize=False); pass --minimize in CLI diagnose, certify, and verify-cert for lower-is-better metrics.
Agent Skill (v2.1)
PromptPrism ships with an Agent Skill at .agents/skills/prompt_prism/SKILL.md so coding agents run calibrated clause attribution, noise-floor audits, coverage-aware TOST pruning, and fail-closed certificate verification instead of pooled ANOVA or unconfirmed prompt recipes.
Legacy & Deprecated APIs
- v1.x Pooled-RCBD ANOVA & Reporting (
[legacy] extra, deprecated in v2.1.0, scheduled for removal in v3.0.0): ANOVAEngine, EffectAnalyzer, OptimalPromptFinder, AnalysisReport, exp.analyze(), exp.get_optimal_prompt_template(), and prism analyze require pip install "prompt-prism[legacy]" (statsmodels>=0.14.0). Prefer exp.diagnose() and exp.build_prompt_template(audit).
- Deprecated selection helpers:
ExperimentalTwoStageSelector, exp.experimental_select_two_stage(..., experimental_opt_in=True), PromptSelectionReport, and exp.selection_report() are deprecated in v2.1.0 and scheduled for removal in v3.0.0; call exp.diagnose() and evaluate_simultaneous_perturbation_certificate() directly.
Architecture
prompt_prism/
├── __init__.py # PEP 562 lazy public API exports (zero heavy imports at startup)
├── _version.py # Package version via importlib.metadata ("2.1.0" fallback)
├── py.typed # PEP 561 type-checker marker
├── experiment.py # Top-level Experiment orchestrator (run, diagnose, build_prompt_template, suggest_confirmation_design)
├── core/ # Factor, Level, FactorSet, LLMClient/CallableLLM, DesignMatrix, ExperimentResults, OperatingEnvelopeSpec, PromptStabilityCertificate, CoverageSpec, SQLiteKVCache, retry
├── design/ # 27-plan 2^(k-p) FractionalFactorial catalog, Plackett-Burman (k<=23), FullFactorial, signed/multi-char AliasStructure, recommend_design
├── template/ # Sandboxed Jinja2 PromptTemplate (auto/text/chat, structured_chat), PromptComposer, required_data_variables
├── runner/ # Parallel ExperimentRunner (env/metadata passthrough), ResponseCache, MockLLM, LiteLLMClient
├── evaluation/ # Deterministic metrics, CheckSpec & CheckSuiteMetric, DeepEval (>=4.2.0) adapter, JudgeCache, Evaluator
├── testgen/ # Frozen scored TestSet/TestCase/TestSetManifest, filters, TestSetGenerator, Pydantic YAML loaders, formula-safe CSV review & stats
├── analysis/ # Calibrated 7-verdict diagnostics & coverage/stability gates (diagnostics.py), fail-closed certification (selection.py), deprecated [legacy] ANOVA/effects/optimizer
├── visualization/ # Lazy OO Matplotlib Main Effects, Pareto, Interaction plots (CalibratedAttributionAudit & legacy ANOVAResult) & ASCII Pareto
├── reporting/ # Deprecated [legacy] Markdown & HTML AnalysisReport
└── cli/ # Modular lazy CLI: main, common, client_loader, cmd_design, cmd_diagnose, cmd_certify, cmd_tests, cmd_metrics
Research Paper
- Auditing, Pruning, and Stabilizing Compiled Prompts: Coverage-Aware Equivalence Testing and Perturbation Stability Certification for LLMs (PDF) — full manuscript, LaTeX source, figures, and arXiv bundle in
docs/paper/. All live benchmarks evaluate pinned gemini-2.5-flash (N = 240 held-out confirmation items):
- Post-compilation bloat pruning on DSPy
MIPROv2: Auditing compiled DSPy prompts found that generated instructions fell within the +/-2 pp TOST equivalence margin on Banking77 and SQuAD 2.0, cutting 39.2%–57.0% of prompt tokens at matched accuracy with passing U95_sim certificates.
- Rare guardrail protection: Coverage-aware TOST + targeted non-inferiority lowered simulated false deletions of rare conditional rules (
tau_T in {0.15, 0.25}) from 18%–95% to 0.0% and raised out-of-scope Banking77 pass rate to 17/20 (85%) (vs. 0/20 for DSPy Full and un-gated PromptPrism).
- Compact standalone prompts & scaffold-held pruning: Holding structural scaffolds (
xml_multiturn + strict_contract) fixed while pruning only optional demos matched or numerically edged DSPy on Banking77 (96.25% vs. 95.83%, -39% tokens) and GSM8K (95.83% vs. 94.58%, -67% tokens; outer PASS, inner precision-limited FAIL U95_sim = 0.0242), passed harsh outer-shell stability on 3/3 tasks, and trailed DSPy on SQuAD 2.0 clean reading comprehension (92.62% vs. 95.25%, -2.63 pp, p = 0.0047).
@misc{sanchez2026auditing,
title={Auditing, Pruning, and Stabilizing Compiled Prompts: Coverage-Aware Equivalence Testing and Perturbation Stability Certification for {LLMs}},
author={Sanchez, Roberto},
year={2026},
month={November},
howpublished={PromptPrism Research Group Technical Report},
url={https://github.com/robsanmx/prompt_prism/blob/main/docs/paper/Auditing_Pruning_and_Stabilizing_Compiled_Prompts.pdf}
}
Running Tests
# Core unit & integration tests (fast, offline)
pytest --ignore=tests/research
# Full suite including research replay tests (requires optional [research] extra & local data where applicable)
pytest
Contributing & License
Distributed under the MIT License. See LICENSE for details.
评论