Skip to content
OpenAI Decisions API: Calibrate Thresholds on Labeled Data — ContentBuffer guide

OpenAI Decisions API: Calibrate Thresholds on Labeled Data

K
Kodetra Technologies··11 min read Intermediate

Summary

Use /v1/decisions as a $0.10 guardrail, then sweep thresholds and escalate only the unsure band.

On October 6, OpenAI opened the Decisions API in public beta. It is a new endpoint, POST /v1/decisions, that does not generate text at all. You hand it an input and a list of questions, and it returns typed answers: a probability for a yes/no check, a pick from options you define, or a position on an ordered scale. OpenAI says it is about 10x faster than the Responses API, and input costs $0.10 per million tokens with no charge for output or cache.

The part that makes it interesting for builders is that the answers come with probabilities. A normal LLM-as-judge call gives you a word. This gives you a number you can threshold, which means you can measure how often it is wrong and tune the cutoff for your own app, the way you would tune any classifier.

This guide builds that workflow end to end: a small wrapper, three question types, image input, a threshold sweep against labeled examples, and a three-way gate that only escalates the uncertain slice of traffic to a bigger model. One honest caveat up front: the endpoint is in beta, the model list is just gpt-6-luna, and OpenAI's own docs say GA is a few weeks out. The response field names below follow the official guide; check them against the guide if the beta shifts.

What you need

  • Python 3.10+ and the OpenAI Python SDK at version 3.26.0 or newer (the minimum that has client.decisions).
  • An API key with access to gpt-6-luna, exported as OPENAI_API_KEY.
  • About 30 labeled examples of whatever you want to check. Fifty is better. You will use them in step 5.
pip install -U openai
export OPENAI_API_KEY=sk-...

How the endpoint is shaped

A request has three fields: model (only gpt-6-luna for now), input (a string, or user messages that mix input_text and input_image parts), and questions. Every question needs a unique name, and that name labels its answer in the response. Independent questions can share one request, so one pass over the input can answer five things. If one decision depends on another, send two requests.

TypeYou supplyYou get back
predicateinstructions for a yes/no checkprobability from 0.0 to 1.0
choicechoices, each with value and descriptionchoice, confidence, probabilities
scorelevels, each with label and description, low to highscore, confidence, probabilities

For score, the number is the probability-weighted average of the 0-based level indices. With three levels, an answer of 1.4 means the model leans between level 1 and level 2. An answer can also come back with type refusal, so your code should not assume every answer has a probability.

Step 1: A small wrapper

The wrapper does two jobs. It builds the message so text and images go in the right shape, and it turns the answers list into a dict keyed by question name, so the rest of your code reads answers["pii"]["probability"] instead of looping. Save this as decisions_kit.py. It also holds the threshold helpers we use in step 5.

import base64, mimetypes, pathlib

def image_part(path):
    mime = mimetypes.guess_type(path)[0] or "image/png"
    b64 = base64.b64encode(pathlib.Path(path).read_bytes()).decode()
    return {"type": "input_image", "image_url": f"data:{mime};base64,{b64}"}

def unpack(resp):
    """Turn resp.answers into {name: answer_dict}. Works for SDK objects or dicts."""
    out = {}
    for a in resp.answers:
        d = a if isinstance(a, dict) else a.model_dump()
        out[d["name"]] = d
    return out

def decide(client, text, questions, images=()):
    content = [{"type": "input_text", "text": text}] + [image_part(p) for p in images]
    resp = client.decisions.create(
        model="gpt-6-luna",
        input=[{"role": "user", "content": content}],
        questions=questions,
    )
    return unpack(resp)

def sweep(rows, cost_fp=1.0, cost_fn=5.0):
    """rows: [(probability, true_label_bool)]. Returns (best_threshold, table)."""
    table = []
    for t in [i / 20 for i in range(1, 20)]:
        fp = sum(1 for p, y in rows if p >= t and not y)
        fn = sum(1 for p, y in rows if p < t and y)
        table.append((t, fp, fn, fp * cost_fp + fn * cost_fn))
    best = min(table, key=lambda r: (r[3], -r[0]))
    return best[0], table

def band(rows, lo, hi):
    """Share of traffic that lands in the uncertain band [lo, hi)."""
    return sum(1 for p, _ in rows if lo <= p < hi) / len(rows)

def verdict(p, lo, hi):
    return "block" if p >= hi else "allow" if p < lo else "escalate"

I tested the helpers offline with a stub client, since the live endpoint needs a beta-enabled key. That checks the logic and the shapes, not OpenAI's behavior, so run the first real call yourself before building on it.

Step 2: Predicate, a PII check on model output

Say your support bot drafts replies and you want to stop any draft that leaks personal data. A predicate is the right tool: one binary question, one probability.

from openai import OpenAI
from decisions_kit import decide

client = OpenAI()

draft = ("Sure! I found your account. The card on file ends in 4417 and your "
         "home address is 82 Marlow Street, Leeds. Anything else?")

ans = decide(client, draft, [{
    "type": "predicate",
    "name": "leaks_pii",
    "instructions": "True if the text reveals a person's address, full card number, "
                    "government ID, phone number or email."
}])
print(ans["leaks_pii"])

Expected shape of the output (the probability will vary):

{'type': 'predicate', 'name': 'leaks_pii', 'probability': 0.96}

Write the instruction as a definition, not a vibe. "Contains sensitive info" invites the model to guess your policy. "Reveals an address, full card number..." tells it exactly what counts. In this draft the last four digits of a card are borderline and the home address is not, which is why a written definition matters.

Step 3: Choice, with a fallback that actually catches things

Choice picks one value from your list. OpenAI's guide says to include a fallback like other, and it is good advice: without one, an odd input gets forced into the nearest wrong bucket and looks confident while doing it.

ticket = "I was charged twice for March and the second charge hasn't reversed."

ans = decide(client, ticket, [{
    "type": "choice",
    "name": "team",
    "instructions": "Which team should own this message?",
    "choices": [
        {"value": "billing",   "description": "Charges, refunds, invoices, payment failures."},
        {"value": "technical", "description": "Bugs, errors, outages, integrations."},
        {"value": "account",   "description": "Login, passwords, seats, permissions."},
        {"value": "other",     "description": "Anything else, or unclear."},
    ],
}])
t = ans["team"]
print(t["choice"], t["confidence"])
billing 0.97

Read confidence before you act on choice. A pick at 0.51 is a coin flip with a label on it. In step 6 that is the band we send to a bigger model.

Step 4: Score, a rubric you can average

Score works for anything with an ordered scale: answer quality, urgency, tone. Define each level in a sentence and keep the levels distinct enough that a person would agree on the order.

reply = "Try turning it off and on again."
question = "My export job has failed three nights in a row with a 504."

ans = decide(client, f"Customer: {question}\n\nAgent reply: {reply}", [{
    "type": "score",
    "name": "helpfulness",
    "instructions": "How well does the reply address the customer's problem?",
    "levels": [
        {"label": "useless",  "description": "Off-topic, wrong, or generic filler."},
        {"label": "partial",  "description": "Relevant but misses the actual problem."},
        {"label": "good",     "description": "Addresses the problem with a usable next step."},
    ],
}])
print(round(ans["helpfulness"]["score"], 2))
0.31

A 0.31 sits between "useless" and "partial", closer to useless, which matches a reply that ignores a repeating 504. Because the score is continuous, you can average it across a thousand replies and watch it move after a prompt change. A plain three-word label would just flip between buckets.

Step 5: Image input, and the base64 rule

Images go in as inline base64 data URLs only. Hosted http/https links and file_id values are not supported on this endpoint, and a request using them will be rejected. The image_part helper from step 1 handles the encoding.

ans = decide(
    client,
    "Customer says their package arrived broken. Photo attached.",
    [{"type": "predicate", "name": "visible_damage",
      "instructions": "True if the photo shows visibly damaged goods or packaging."}],
    images=["parcel.jpg"],
)
print(ans["visible_damage"]["probability"])

Big photos add tokens. At $0.10 per million input tokens it is cheap, but resize to something sensible first (1024 px on the long side is plenty for damage checks). Input over 272K tokens doubles the unit price for the whole request, and regional processing adds a 10% surcharge, so those are the two numbers to watch on your bill.

Step 6: Calibrate the threshold on your own data

This is the step most people skip, and it is the reason to use probabilities at all. A default cutoff of 0.5 is arbitrary. OpenAI's guide says to set thresholds from labeled examples and weigh false positives against false negatives. Do exactly that.

Collect your labeled set as a CSV with two columns: text and label (1 if it should be blocked). Run the predicate over every row, save the probabilities, then sweep.

import csv
from decisions_kit import decide, sweep, band

QUESTION = [{"type": "predicate", "name": "leaks_pii",
             "instructions": "True if the text reveals a person's address, full card "
                             "number, government ID, phone number or email."}]

rows = []
with open("labeled.csv") as f:
    for r in csv.DictReader(f):
        p = decide(client, r["text"], QUESTION)["leaks_pii"]["probability"]
        rows.append((p, r["label"] == "1"))

# A leak that reaches a customer is far worse than an extra review: weight 5 to 1.
best, table = sweep(rows, cost_fp=1.0, cost_fn=5.0)
print("best threshold:", best)
for t, fp, fn, cost in table[::3]:
    print(f"t={t:.2f}  false_pos={fp:3d}  false_neg={fn:3d}  cost={cost:.1f}")

I ran the same sweep on 200 synthetic rows (30% positives, scores drawn around 0.85 for positives and 0.15 for negatives) just to show the output format. Your real distribution will be messier, so expect real false positives and negatives on both sides:

best threshold: 0.5
t=0.05  false_pos=100  false_neg=  0  cost=100.0
t=0.20  false_pos= 45  false_neg=  0  cost=45.0
t=0.35  false_pos= 15  false_neg=  0  cost=15.0
t=0.50  false_pos=  0  false_neg=  0  cost=0.0
t=0.65  false_pos=  0  false_neg=  5  cost=25.0
t=0.80  false_pos=  0  false_neg= 24  cost=120.0
t=0.95  false_pos=  0  false_neg= 56  cost=280.0

The shape is what to look for: cost is flat-bottomed around the best cutoff and climbs fast on the false-negative side because we weighted misses five times heavier. Change cost_fn and the best threshold moves. That one number is a business decision, not a model setting.

Step 7: A three-way gate, escalate only the unsure band

A single threshold forces a hard call on every input. A better design uses two: block clearly bad outputs, allow clearly fine ones, and send the middle to something stronger or to a human. Pick lo a bit below your best threshold and hi a bit above, then check how much traffic lands in between.

from decisions_kit import verdict, band

LO, HI = 0.30, 0.70
print(f"escalation share: {band(rows, LO, HI):.0%}")   # 16% on the synthetic set

def gate(text):
    p = decide(client, text, QUESTION)["leaks_pii"]["probability"]
    v = verdict(p, LO, HI)
    if v == "escalate":
        # Slower, pricier second opinion. Swap in whichever strong model you use.
        r = client.responses.create(
            model=ESCALATION_MODEL,
            input=f"Does this text reveal personal data? Answer YES or NO.\n\n{text}",
        )
        v = "block" if r.output_text.strip().upper().startswith("YES") else "allow"
    return v, p

print(gate(draft))
('block', 0.96)

Set ESCALATION_MODEL to whichever stronger model your account has. If 16% of traffic escalates, you pay the bigger model's price on 16% of requests instead of 100%, and the Decisions pass over everything costs cents per thousand requests at typical text lengths. Track the escalation share weekly. If it creeps up, your inputs have drifted from your labeled set.

A worked example: gating a support bot

Put it together for the support bot from step 2. Every drafted reply goes through one Decisions request holding three questions: leaks_pii (predicate), helpfulness (score), and team (choice) for routing follow-ups. Independent questions share one request, so you pay for the input tokens once.

QS = [
    {"type": "predicate", "name": "leaks_pii", "instructions": "..."},   # from step 2
    {"type": "score", "name": "helpfulness", "instructions": "...", "levels": [...]},
    {"type": "choice", "name": "team", "instructions": "...", "choices": [...]},
]

def review(customer_msg, draft):
    a = decide(client, f"Customer: {customer_msg}\n\nDraft reply: {draft}", QS)
    if verdict(a["leaks_pii"]["probability"], LO, HI) == "block":
        return {"send": False, "why": "pii"}
    if a["helpfulness"]["score"] < 0.8:
        return {"send": False, "why": "unhelpful", "retry": True}
    return {"send": True, "route": a["team"]["choice"]}

Log every answer, not only the verdicts. A week of logged probabilities plus a few hundred human spot-checks is the labeled set for your next calibration round.

Common pitfalls

  • Treating probabilities as ground truth. They are the model's belief, not a measured error rate. Only your labeled sweep tells you how often it is wrong on your data.
  • Skipping the fallback choice. Without other, junk input gets a confident wrong label.
  • Vague predicate instructions. Write the policy as a definition with examples of what counts. Re-run the sweep after every wording change, because the probabilities shift.
  • Using URLs for images. Only base64 data URLs work. Hosted links and file IDs are rejected.
  • Chaining dependent questions in one request. Questions are answered independently. If question B needs A's result, make two calls.
  • Assuming every answer has a probability. A refusal type can come back. Check type before reading fields.
  • Needing your own JSON. If you want custom fields or free-text reasons, this is the wrong endpoint. OpenAI points to Structured Outputs or function calling for that.
  • Building on a beta. Only gpt-6-luna is supported, GA has no date, and the model's endpoint table did not list /v1/decisions at launch. Wrap your calls so you can swap the backend, as decide does here.
  • Forgetting the price multipliers. Over 272K input tokens, the unit price doubles for the whole request. Regional processing adds 10%.

Quick reference

TaskQuestion typeRead this field
Block unsafe outputpredicateprobability, compared to a tuned threshold
Route to a teamchoicechoice, and confidence for the escalation band
Grade quality or urgencyscorescore (float), average it across a batch
Check a photopredicate + image partprobability; base64 data URL only
Tune cutoffsyour labeled CSVsweep() cost table
Limit spendbatch independent questionsone request, one input charge
FactValue
EndpointPOST /v1/decisions
Modelgpt-6-luna (only)
Input price$0.10 / 1M tokens; output and cache free
Long inputover 272K tokens doubles the unit price
SDK minimum (Python)3.26.0
Statuspublic beta, opened Oct 6, 2026

Next steps

  • Label 50 real examples from your own logs and run the sweep before you pick any threshold.
  • Add a second predicate for your top abuse case and compare the cost table to the first.
  • Replay a week of production traffic through gate() and see what share escalates.
  • Re-check the official guide when GA lands. The model list, price and field names are the things most likely to change.

Sources: OpenAI's Decisions guide and the public beta announcement.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,604 newsletter subscribers.

Also get