Prompt engineering: write a contract, then test it honestly
提示设计
Build an input contract and measure how repeated prompt selection overfits a small validation set.
prompt-engineeringThe best-looking prompt may have won by chance
You try 64 prompt variants on the same eight questions. One scores about 89%, while the average variant scores 50%. That can look like a discovery. In the authored experiment below, every variant has exactly the same true success probability, 50%. Searching more variants makes the best validation score rise; untouched test performance stays near 50%.
Prompt engineering means designing and evaluating the instructions, examples, input arrangement and output contract supplied to a model. It is not a list of magic phrases. Reynolds and McDonell, sections 3.1–3.2, show how formatting changes affected a limited French-to-English translation experiment. Their Table 1 also warns that API conditions and inferred model sizes complicate comparisons. The result motivates testing a prompt; it does not establish a universal winning format.
Zhao and colleagues, section 5, show another reason to measure: the prompt can shift preferences among answer labels. Their contextual calibration uses content-free inputs and changes decision scores. A prompt that sounds clear to its author still needs an evaluation matched to its task.
Turn a request into a measurable contract
Start with the business decision. For sentiment routing, specify what text to classify, which labels are allowed, whether abstention is allowed, and what the caller does with an invalid answer. A non-AI baseline might be a keyword rule or manual routing. Keep it in the comparison: if the task is already a fixed field extraction, ordinary parsing may be enough.
Separate the instruction from the input data in a consistent template. State any examples and the expected response format. A JSON-serialized input field preserves quotes and line breaks as data in the template; it is not a guarantee that a language model will ignore instructions embedded in that field. Authentication and permission decisions belong outside the prompt.
Let s denote one complete prompt specification and c its measured cost in a declared unit, such as seconds or currency. A useful objective can combine end-to-end success and cost:
Theta identifies the fixed model and inference configuration; record the version, sampling settings, parser and timeout policy as well as the prompt text. Lambda converts the chosen cost unit into the score’s units. The experiment below measures accuracy only; it does not fabricate latency or API prices.
Use a development set to inspect failures and propose variants. Use a selection set to compare the resulting candidates. On n labeled selection cases, define:
A parse failure counts as a failed end-to-end prediction. If abstention has a different business value, define that value before comparing candidates. Do not quietly drop inconvenient outputs from the denominator.
Choose a candidate using selection scores, freeze it, then evaluate it on a separate test set:
The test examples and answers must not influence candidate selection. The program rejects overlapping or duplicate case IDs; this catches one simple leakage route, not semantic duplicates, contaminated pretraining or a human repeatedly consulting test results. If you use a test failure to redesign a prompt, it has become development information. Obtain fresh evaluation evidence for the revised choice.
To isolate selection bias, suppose each of m candidates independently gets each of n cases right with the same probability p. Each candidate’s correct count has a binomial distribution:
The probability that every candidate scores at most k is F(k) raised to m. For a nonnegative integer-valued maximum, sum its tail probabilities to obtain:
At p=0.5 and n=8, the expected selected validation accuracy is 0.5 for one candidate, about 0.67889 for four, 0.80171 for 16 and 0.89004 for 64. An independent test set still has expected accuracy 0.5 for the chosen candidate. Real prompts share errors, so these exact numbers do not describe arbitrary prompt searches. The model demonstrates how selecting on noise can create an apparent improvement without any weight updates.
Report output coverage as well as accuracy. When correct outputs are a subset of valid outputs:
The example has three valid outputs out of four and two correct outputs. Coverage is 3/4, accuracy among valid outputs is 2/3, and end-to-end accuracy is 1/2. If no output is valid, conditional accuracy is undefined; the program returns None, not a misleading zero or perfect score.
A local evaluation harness
This complete Python 3.12/NumPy 1.26.4 program serializes a concrete sentiment instruction, calculates coverage, performs split-aware selection and compares simulated selection bias with the exact binomial calculation. It makes no model or network calls. The binary correctness matrices and their probabilities are authored fixtures, not measurements of the displayed prompt.
"""Original prompt-evaluation harness and selection-bias experiment; no LM calls."""
import json,math
import numpy as np
def positive_int(n,maximum):
if isinstance(n,bool) or not isinstance(n,int) or not 1<=n<=maximum:raise ValueError('integer outside declared bounds')
def build_prompt(text):
if not isinstance(text,str) or len(text)>2000:raise ValueError('bounded text required')
data=json.dumps({'text':text},ensure_ascii=False)
return 'Classify the sentiment of the text field. Return only positive, negative, or abstain.\nInput JSON:\n'+data
def metrics(outputs,labels):
if not outputs or len(outputs)!=len(labels):raise ValueError('nonempty aligned records required')
if any(type(y) is not int or y not in [0,1] for y in labels):raise ValueError('labels must be0 or1')
if any(x is not None and (type(x) is not int or x not in [0,1]) for x in outputs):raise ValueError('outputs must be0,1 orNone')
valid=sum(x is not None for x in outputs);correct=sum(x is not None and x==y for x,y in zip(outputs,labels))
return dict(coverage=valid/len(labels),accuracy_on_valid=correct/valid if valid else None,end_to_end_accuracy=correct/len(labels))
def expected_selected_accuracy(candidates,trials,p=.5):
positive_int(candidates,1000);positive_int(trials,100)
if isinstance(p,bool) or not math.isfinite(p) or not 0<=p<=1:raise ValueError('probability required')
probabilities=[math.comb(trials,k)*p**k*(1-p)**(trials-k) for k in range(trials+1)]
cdf=np.cumsum(probabilities)
return float(sum(1-min(1,float(x))**candidates for x in cdf[:-1])/trials)
def select(validation,test,validation_ids,test_ids):
v=np.asarray(validation);t=np.asarray(test)
if v.ndim!=2 or t.ndim!=2 or not v.size or not t.size or v.shape[0]!=t.shape[0]:raise ValueError('nonempty candidate-by-case matrices required')
if v.shape[1]!=len(validation_ids) or t.shape[1]!=len(test_ids):raise ValueError('IDs must match cases')
if len(set(validation_ids))!=len(validation_ids) or len(set(test_ids))!=len(test_ids) or set(validation_ids)&set(test_ids):raise ValueError('separate unique split IDs required')
if not np.isin(v,[0,1]).all() or not np.isin(t,[0,1]).all():raise ValueError('binary correctness required')
chosen=int(np.argmax(v.mean(axis=1)))
return dict(chosen=chosen,validation=float(v[chosen].mean()),test=float(t[chosen].mean()))
def demo():
rng=np.random.default_rng(71);counts=[1,4,16,64];curves=[]
for m in counts:
validation=rng.binomial(8,.5,size=(4000,m));winner=validation.argmax(axis=1)
independent_test=rng.binomial(64,.5,size=(4000,m))
curves.append(dict(candidates=m,exact_validation=expected_selected_accuracy(m,8),simulated_validation=float(np.mean(validation[np.arange(4000),winner])/8),simulated_test=float(np.mean(independent_test[np.arange(4000),winner])/64)))
chosen=select([[1,1,1,1],[1,1,0,1]],[[0,0,1,0],[1,1,1,0]],['v1','v2','v3','v4'],['t1','t2','t3','t4'])
return dict(prompt=build_prompt('Good display.\nThe battery failed.'),metrics=metrics([0,1,None,0],[0,1,1,1]),curves=curves,chosen_fixture=chosen,all_candidates_true_accuracy=.5,simulation_repeats=4000)
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
With seed 71, each curve uses 4,000 synthetic searches. Validation has eight cases and the independent test has 64. The simulation approaches the exact selection curve while the test stays near 0.5. In chosen_fixture, candidate 0 wins the selection set with 1.0 but scores 0.25 on test. Candidate 1 would score 0.75 on that test; the selection procedure does not peek at that result to change its choice.
The exact expectation uses O(n) binomial terms for one candidate count. The simulation stores O(Bm) correct-count arrays for B repetitions and m candidates; it does not allocate every individual Bernoulli trial. An actual model comparison should also log input/output token counts, retries, invalid outputs, latency and error categories, using the same cases and evaluation rules for every variant.
Prompt changes are experiments
The finite experiment assumes independent candidates and cases with equal true quality. Real outputs can be correlated, stochastic and uneven across subgroups. A good average may hide systematic failures on negation, mixed sentiment or a changed input format. Record such slices rather than claiming universal reliability from an aggregate.
Change one meaningful part of the contract at a time when diagnosing a failure. Compare the old prompt, the revised prompt and the non-AI baseline on held-out cases. An elaborate persona or a longer instruction is not evidence of improvement. For stable machine-readable responses, add structured output validation; a textual request alone is not a parser or a factual check.
Check the experiment you are running
- Why can 64 equally good candidates produce a higher winning validation score than one candidate?
Answer: Taking a maximum selects favorable random errors. Under the stated independence model, its expectation is about 0.89004 on eight cases even though every candidate has true accuracy 0.5.
- Four responses contain two correct outputs, one wrong valid output and one invalid output. Report all three metrics.
Answer: Coverage is 3/4, valid-output accuracy is 2/3, and end-to-end accuracy is 2/4. Reporting only 2/3 hides the invalid response.
- A test case has a new ID but is a paraphrase of a development case. Does the ID check establish independence?
Answer: No. The check detects exact ID overlap only. Split by the relevant underlying entity or task and inspect semantic duplication where it affects the claim.
- Does JSON-serializing the input prevent prompt injection?
Answer: No. It makes the input boundary explicit in the string and preserves the data. A language model may still follow embedded instructions; permissions and downstream validation require their own controls.
Compare methods under stated conditions
Read Reynolds and McDonell’s translation setup and Table 1 caveats before reusing their prompt conclusions. Read Zhao’s section 5 and footnote 4 to distinguish label-bias correction from statistical confidence calibration. The selection-bias computation here is an original finite experiment, not a reported result from either paper. Continue to few-shot prompting to study demonstration choice.
Make a prediction, then check
A prompt wins on the same eight cases used to select it. Is that independent evidence of improvement?
Learning objectives
- Separate prompt design, parsing, selection data and final evaluation.
- Run the bounded original example and explain the failure cases.
Prerequisites & connections
Explore related knowledge →References
- Prompt Programming for Large Language Models: Beyond the Few-Shot Paradigm — v1
Laria Reynolds; Kyle McDonell · 2021 - Calibrate Before Use: Improving Few-Shot Performance of Language Models — v1
Tony Z. Zhao; Eric Wallace; Shi Feng; Dan Klein; Sameer Singh · 2021
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Viewed PDF2/3 sections3.1/3.2 and Table1 caption: a limited translation example, prompt formatting and API/model-size uncertainty. Findings are not universal prompt rules. Viewed PDF5 section5 and footnotes: content-free inputs, diagonal probability scaling, softmax versus argmax, and distinction from confidence calibration. Do not implement the suspect zero-W generation footnote. 6 paired equations and four explained exercises. Exact binomial order statistics checked by exhaustive small enumerations and independent seeded test simulation. Split IDs, abstention denominators and serialized input checked; input quoting is not a security guarantee.
- Exact binomial order statistics checked by exhaustive small enumerations and independent seeded test simulation. Split IDs, abstention denominators and serialized input checked; input quoting is not a security guarantee.
- Four computed SVG variants per topic;9 numeric/geometry tests and24 responsive cases passed. Eight selected final captures directly viewed. Full article acceptance recorded separately.
- Final page inspection found missing spaces at English prose number boundaries. Inserted only the explicitly recorded spaces; protected formulas, code, inline literals, links and frontmatter unchanged. Frozen originals retained; exact insertion regression and renewed page checks required.
Source locations checked:
- Prompt Programming for Large Language Models: Beyond the Few-Shot Paradigm — v1 · Viewed PDF2/3 sections3.1/3.2 and Table1 caption: a limited translation example, prompt formatting and API/model-size uncertainty. Findings are not universal prompt rules.
- Calibrate Before Use: Improving Few-Shot Performance of Language Models — v1 · Viewed PDF5 section5 and footnotes: content-free inputs, diagonal probability scaling, softmax versus argmax, and distinction from confidence calibration. Do not implement the suspect zero-W generation footnote.
Related topics