Agentic Pattern Libraryby Vikas Goyal
Patterns / Math models / Conformal prediction
No. M16 Planning Established Decision Verification

Conformal prediction

Prediction sets with a guarantee: \(\Pr\big(Y \in C(X)\big) \ge 1-\alpha\)

Takeaway

With labeled examples and a % target, the agent auto-routes 59% of tickets at 96% accuracy and hands the rest to a person, while the right queue stays in its answer 95% of the time.

Change the blue numbers. Every figure on this page updates with them.

Why care

"Hand off to a human when unsure" needs a definition of unsure that holds up.

Model confidence scores are often miscalibrated: a model can say 90% and be right 70% of the time, and the gap shifts with every model update. Thresholds picked by eye drift with them. Conformal prediction replaces the guess with a guarantee. Using a few hundred labeled examples, it turns any model's scores into a set of plausible answers that contains the right one at least, say, 95% of the time, whatever the model and however badly calibrated it is. When the set has one answer, the agent acts; when it has several, the agent is unsure in a precise sense, and hands off or asks.

The intuition

Take 500 past tickets whose correct queue you know. For each, ask how surprised the model was by the right answer: one minus the probability it gave that queue. Sort the 500 surprise scores. The 95th-percentile surprise is your bar.

For a new ticket, include every queue whose surprise would be below the bar. Because the new ticket is just another draw from the same stream, its right answer clears the bar with the same 95% chance as the past ones did. Nothing about the model needs to be correct for this to hold; a better model just makes the sets smaller.

Model confident: one queue in the set
59%
Torn between two queues
34%
Three or more queues
8%

Share of tickets by set size, at a 95% target with 500 calibration tickets, for a model whose top answer is right 85.5% of the time.

The math

On \(n\) labeled calibration examples, compute a nonconformity score for the true label, here \(s_i = 1 - \hat p(y_i \mid x_i)\). Take the adjusted quantile and build sets:

$$\hat q = s_{(\lceil (n+1)(1-\alpha)\rceil)}, \qquad C(x) = \{\,y : 1 - \hat p(y\mid x) \le \hat q\,\}$$

If calibration and new examples are exchangeable (drawn the same way), then for any model,

$$1-\alpha \;\le\; \Pr\big(Y_{\text{new}} \in C(X_{\text{new}})\big) \;\le\; 1-\alpha + \frac{1}{n+1}$$
\(\alpha\)
allowed miss rate: target coverage is \(1-\alpha\)
\(n\)
number of labeled calibration examples, held out from training
\(s_{(k)}\)
the \(k\)-th smallest calibration score
\(C(x)\)
prediction set: every answer plausible enough to keep
  • The abstention rule: act when \(|C(x)| = 1\); hand off or ask a clarifying question when \(|C(x)| \ge 2\). The set says which options to put in front of the person.
  • The guarantee is on average over calibration sets. For one particular calibration set, coverage varies around the target; more calibration data narrows the spread.
  • Validity is free; efficiency is not. Any model gets the coverage guarantee. A better model gets smaller sets, so more tickets are handled automatically.

Where each of these comes from is worked through in Derivations at the end of the page.

Interactive calculator

A simulated ticket classifier with 8 queues. Each setting is calibrated 200 times on fresh labeled samples, each time tested on 3,000 new tickets; the readouts are averages over those 200 calibrations.

Shown as the accuracy of the model's top answer.
–
Right answer in the set (average)
–
Coverage in the worst 5% of calibrations
–
Handled automatically: one answer in the set
–
Accuracy on those
–
Handed to a person: two or more answers
–
Average set size
One answer: act Two or more: hand off Empty set

Worked example: routing support tickets

An intake agent assigns support tickets to one of 8 queues. Its classifier's top answer is right 85.5% of the time, so routing every ticket automatically sends one in seven to the wrong team. The team labeled 500 recent tickets for calibration and compared three targets. Figures are averages over 300 calibration draws, tested on 20,000 tickets:

Target coverageAchievedAuto-routedAccuracy when auto-routedTwo queuesThree or more
No conformal: route every ticket–100%85.5%––
90%90.3%81%91.4%17%0.4%
95%95.2%59%96.4%34%8%
98%98.0%36%99.3%34%30%

The team chose 95%. Tickets with one queue in the set were routed automatically and were right 96% of the time. Tickets with two queues went to a triage agent who only had to choose between the two shown, which took seconds. Only 8% needed a full manual look. Calibrating on 100 tickets instead of 500 gave the same average coverage, but in the worst 5% of draws coverage fell to 91.5% instead of 93.5%, so the extra labeling bought a steadier guarantee.

Assumptions and where it breaks

  • New data must look like calibration data. The guarantee assumes exchangeability. After a product launch or a model update, recalibrate on fresh labeled examples; under gradual drift, recalibrate on a rolling window.
  • Coverage is on average, not per group. 95% overall can hide 80% on one queue and 99% on another. Mondrian (class-conditional) conformal calibrates each group separately when per-group guarantees matter.
  • It guarantees coverage, not small sets. A weak model gets valid but large sets, and most traffic is handed off. Improving the model is still how you raise automation.
  • Calibration labels must be right. Mislabeled calibration examples shift the threshold. Use carefully labeled data, and check agreement between labelers (M08).
  • Free-text answers need more work. For generated text, sets are built from sampled candidates and a scoring function; conformal methods for language generation exist but are more involved than classification.

How to apply it

  1. Hold out labeled examples that the model was not trained or tuned on, sampled like production traffic: 200 to 1,000 is typical.
  2. Pick the target from the cost of a miss. Higher coverage means more handoffs; the calculator shows the trade-off.
  3. Compute the threshold with the adjusted quantile, and build sets at inference time: every answer whose score clears it.
  4. Act on singletons, route the rest. Show the person only the answers in the set; empty sets are a signal of out-of-distribution input.
  5. Monitor coverage on labeled samples of live traffic, and recalibrate whenever it drifts below target or the model changes.

How to explain it to a stakeholder

"Instead of trusting the model's confidence, we tested it against 500 tickets we know the answers to. Now, when the agent is sure, it routes the ticket itself and is right 96% of the time. When it isn't, it hands the ticket over with the two or three likely queues, and we can guarantee the right one is in its answer 95% of the time."

For coding agents

A machine-readable summary and a reference implementation. The same spec is embedded in this page as <script type="application/json" id="model-spec">, and the whole series is listed in models.json.

Model spec (YAML)
id: conformal-prediction
number: M16
name: Conformal prediction for abstention and handoff
family: planning
answers: "When should the agent act on its own, and when should it hand off?"
formula:
  score: "s_i = 1 - p_hat(y_i | x_i) on calibration data"
  threshold: "q_hat = s_(ceil((n+1)(1-alpha)))"
  prediction_set: "C(x) = {y : 1 - p_hat(y|x) <= q_hat}"
  guarantee: "1 - alpha <= P(Y in C(X)) <= 1 - alpha + 1/(n+1)"
  decision: "act if |C(x)| == 1, otherwise hand off with C(x)"
inputs:
  calibration: {type: list, meaning: held-out labeled examples with model probabilities}
  alpha: {type: float, meaning: allowed miss rate}
assumptions:
  - calibration and live data exchangeable
  - marginal (not per-group) coverage
  - correct calibration labels
use_when:
  - deciding when an agent should act alone versus escalate
  - giving a guaranteed error rate for an automated step
related_patterns: [human-in-the-loop, metacognitive-monitor, fast-slow-escalation, guardrails]
Reference implementation (Python, NumPy)
import math
import numpy as np

def calibrate(probs_cal, labels_cal, alpha=0.05):
    """probs_cal: n x K model probabilities; labels_cal: n true labels."""
    n = len(labels_cal)
    scores = 1 - probs_cal[np.arange(n), labels_cal]
    k = math.ceil((n + 1) * (1 - alpha))
    return 1.0 if k > n else float(np.sort(scores)[k - 1])

def prediction_sets(probs, q_hat):
    return (1 - probs) <= q_hat            # boolean mask: n x K

def decide(probs, q_hat):
    sets = prediction_sets(probs, q_hat)
    size = sets.sum(axis=1)
    return np.where(size == 1, "act", np.where(size == 0, "out_of_distribution", "hand_off")), sets

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    def simulate(n, k=8, delta=2.6):
        y = rng.integers(k, size=n)
        logits = rng.normal(size=(n, k))
        logits[np.arange(n), y] += delta
        p = np.exp(logits); p /= p.sum(axis=1, keepdims=True)
        return p, y
    q = calibrate(*simulate(500), alpha=0.05)
    p, y = simulate(5000)
    actions, sets = decide(p, q)
    print("coverage", sets[np.arange(5000), y].mean())          # about 0.95
    print("auto-handled", (actions == "act").mean())            # about 0.6

Derivations

For the math-curious: where each result in The math comes from. Nothing above depends on reading this.

Why the coverage guarantee holds

Put the new example's score \(s_{n+1}\) alongside the \(n\) calibration scores. If all \(n+1\) examples are exchangeable, every ordering of their scores is equally likely, so \(s_{n+1}\) is equally likely to land in any of the \(n+1\) ranks. The new true label is in the set exactly when \(s_{n+1} \le \hat q\), the \(k\)-th smallest calibration score with \(k = \lceil(n+1)(1-\alpha)\rceil\). That happens when \(s_{n+1}\) ranks at most \(k\)-th among the \(n+1\), which has probability \(k/(n+1) \ge 1-\alpha\). With no ties, the probability is also at most \(1-\alpha + 1/(n+1)\).

Why the quantile is adjusted

Using the plain \((1-\alpha)\) quantile of the \(n\) calibration scores would undercover slightly, because the new example adds one more score to the ranking. The \(\lceil (n+1)(1-\alpha)\rceil\) index corrects for that. If \((n+1)(1-\alpha) > n\), for example \(n = 15\) with \(\alpha = 0.05\), there are too few calibration examples for the target, and the only valid set is every possible answer.

How much coverage varies between calibration sets

Given one particular calibration set, the coverage on future data is a random quantity. For continuous scores it follows a Beta distribution, \(\text{Beta}(k,\ n+1-k)\), with mean \(k/(n+1)\) and standard deviation about \(\sqrt{\alpha(1-\alpha)/n}\). At \(n = 500\) and \(\alpha = 0.05\) that is about 1 point; at \(n = 100\), about 2 points. This is what the second calculator view shows, and why larger calibration sets give a steadier guarantee.

Sets as an abstention rule

A set of size one means every alternative was too surprising to keep: the model is confident in a way validated against labeled data. A larger set means at least two answers remain plausible at the chosen coverage. Acting only on singletons gives an error rate on acted-on cases that is typically below \(\alpha\). When you need a guarantee on that error rate directly, conformal risk control extends the same calibration idea to other losses, such as the error rate among accepted cases.

References

  1. Angelopoulos, A. N. and Bates, S. (2021). A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantification. The practical starting point, with code.
  2. Ren, A. Z. et al. (2023). Robots That Ask For Help: Uncertainty Alignment for Large Language Model Planners. Conformal prediction deciding when an LLM agent should ask a person.
  3. Vovk, V., Gammerman, A. and Shafer, G. (2005). Algorithmic Learning in a Random World. Springer. The foundational treatment of conformal prediction.
  4. Angelopoulos, A. N. et al. (2022). Conformal Risk Control. Extending the guarantee to losses beyond coverage.