Skip to content
Clef Decision Models: Route Support Tickets in Python — ContentBuffer guide

Clef Decision Models: Route Support Tickets in Python

K
Kodetra Technologies··12 min read Intermediate

Summary

Cloudflare's open Clef models return typed probabilities, not text. Build a cheap cascade router.

Most agent code has a quiet weak spot: the moment where an LLM has to decide something small. Is this ticket urgent? Which team owns it? Should the agent continue or stop? We usually answer by prompting a large model, asking for JSON, and parsing whatever comes back. It works, mostly, and it costs a full generation every time.

On October 1, Cloudflare released Clef and Clef-flash, two open-weight decision models hosted on Workers AI. You give them a state and a schema of typed questions. They return a probability for every allowed option, with no free-form text and nothing to parse. Cloudflare reports a median latency of 38.8 ms for Clef-flash and 209.3 ms for Clef, against 524.1 ms for Jev, the model that started this category. Both are Apache 2.0 on Hugging Face.

This guide teaches one concrete thing: how to call Clef, read its typed answers, and build a cascade router that uses the cheap model first, escalates to the bigger one when confidence is low, and hands off to a human when both are unsure. We will write it in Python, test the control flow offline, then cover calibration, images, and running the weights yourself.

A note on what I verified. The request format, model IDs, pricing and benchmark numbers below come from Cloudflare's launch post, the Workers AI model pages and the Hugging Face model card. I could not call the live API from this environment (no Cloudflare credentials), so the control-flow code was tested against a stub that mimics the documented response fields. Where the docs are vague, I say so.

What a decision model actually is

A normal LLM generates tokens one at a time. A decision model does a single prefill pass over your input, then scores every valid answer in parallel. Per the Hugging Face card, Clef returns "a probability for every allowed option of every question in a single forward pass" with "no free-form text generation and no output parsing." The architecture is a frozen Qwen backbone (Qwen3.8-27B for Clef, Qwen3.5-9B for Clef-flash) plus a small joint head that routes evidence from the input to each question.

Two consequences matter for your code. First, the output can only be one of the options you listed, so you never handle a malformed answer. Second, you get calibrated probabilities, so you can set a confidence threshold and send uncertain cases elsewhere. That second point is what makes the cascade in this guide possible.

ClefClef-flash
BackboneQwen3.8-27BQwen3.5-9B
Workers AI model ID@cf/cloudflare/clef@cf/cloudflare/clef-flash
Median latency (Cloudflare eval)209.3 ms38.8 ms
p95 latency238.6 ms122.4 ms
Input price$0.24 / M tokens$0.09 / M tokens
Context window65,536 tokens65,536 tokens
Inputstext, JSON, images, videotext, JSON, images, video

The three question types are noul (true/false, yes the spelling is right: that is the literal type name in the docs), choice (pick one named option) and score (an ordered scale, returned as a probability-weighted expected value starting at 0).

Prerequisites

  • Python 3.10+ and pip install requests
  • A Cloudflare account with Workers AI enabled, your account ID, and an API token with Workers AI permission
  • Two environment variables: CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_AUTH_TOKEN

Step 1: Make your first call

The endpoint is POST https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/@cf/cloudflare/clef. The body takes a model name, a state (any string or JSON value) and a questions map. This is the exact example from Cloudflare's docs:

curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/@cf/cloudflare/clef \
  -X POST \
  -H "Authorization: Bearer $CLOUDFLARE_AUTH_TOKEN" \
  -d '{
    "model": "clef",
    "state": "Checkout has been failing for every customer for the last hour.",
    "questions": {
      "urgent": { "type": "noul", "instructions": "Is this support request urgent?" },
      "team": {
        "type": "choice",
        "instructions": "Which team should handle this request?",
        "criteria": {
          "billing": "Payments, invoices, and refunds",
          "technical": "Outages, errors, and configuration",
          "sales": "Plans and upgrades"
        }
      },
      "severity": {
        "type": "score",
        "instructions": "How severe is the customer impact?",
        "criteria": ["No impact", "Minor", "Major", "Critical"]
      }
    }
  }'

Per the Hugging Face model card, the response mirrors the Jev/SystemOne body: model, answers keyed by your question IDs, and usage. A choice answer has choice, confidence and probabilities. A score answer has the expected score, confidence, legend and probabilities. A noul answer carries the probability of true.

For the checkout example you should expect something shaped like this (values are illustrative, not captured output):

{
  "result": {
    "model": "clef",
    "answers": {
      "urgent":   0.97,
      "team":     {"choice": "technical", "confidence": 0.95,
                   "probabilities": {"billing": 0.03, "technical": 0.95, "sales": 0.02}},
      "severity": {"score": 2.8, "confidence": 0.8,
                   "legend": ["No impact", "Minor", "Major", "Critical"],
                   "probabilities": [0.01, 0.04, 0.2, 0.75]}
    }
  },
  "success": true
}

The docs do not spell out the exact JSON shape of a noul answer or whether the Workers AI REST route wraps the body in result. The client below tolerates both, so print a real response once and tighten it.

Step 2: A small typed client

Keep the HTTP code in one place. Note the timeout: you are putting this on a hot path, so fail fast.

import os
import requests

ACCOUNT_ID = os.environ["CLOUDFLARE_ACCOUNT_ID"]
TOKEN = os.environ["CLOUDFLARE_AUTH_TOKEN"]
BASE = f"https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/@cf/cloudflare"


def decide(model: str, state, questions: dict, timeout: int = 15) -> dict:
    """Call clef or clef-flash and return the `answers` dict."""
    r = requests.post(
        f"{BASE}/{model}",
        headers={"Authorization": f"Bearer {TOKEN}"},
        json={"model": model, "state": state, "questions": questions},
        timeout=timeout,
    )
    r.raise_for_status()
    body = r.json()
    # The REST API wraps model output in {"result": ...}; the Jev-style body
    # has "answers" at the top level. Accept both.
    body = body.get("result", body)
    return body["answers"]


def p_true(answer) -> float:
    """Normalise a noul answer to a float in [0, 1]."""
    if isinstance(answer, (int, float)):
        return float(answer)
    for key in ("probability", "true", "p_true"):
        if key in answer:
            return float(answer[key])
    raise KeyError(f"unrecognised noul answer shape: {answer!r}")


TICKET_QUESTIONS = {
    "urgent": {"type": "noul", "instructions": "Is this support request urgent?"},
    "team": {
        "type": "choice",
        "instructions": "Which team should handle this request?",
        "criteria": {
            "billing": "Payments, invoices, and refunds",
            "technical": "Outages, errors, and configuration",
            "sales": "Plans and upgrades",
        },
    },
    "severity": {
        "type": "score",
        "instructions": "How severe is the customer impact?",
        "criteria": ["No impact", "Minor", "Major", "Critical"],
    },
}

Step 3: Build the cascade

Here is the idea. Clef-flash costs about a third of Clef per token and answers in tens of milliseconds, so let it take every ticket first. If its top-choice confidence is under 0.85, re-ask Clef. If Clef is under 0.70, stop guessing and send the ticket to a person. Everything above those lines is handled automatically.

from clef_router import decide, p_true, TICKET_QUESTIONS

FLASH_MIN_CONF = 0.85   # accept the cheap model above this
CLEF_MIN_CONF = 0.70    # below this after escalation, hand to a human


def route(ticket: str) -> dict:
    answers = decide("clef-flash", ticket, TICKET_QUESTIONS)
    used = "clef-flash"

    if answers["team"]["confidence"] < FLASH_MIN_CONF:
        answers = decide("clef", ticket, TICKET_QUESTIONS)
        used = "clef"

    team = answers["team"]
    if team["confidence"] < CLEF_MIN_CONF:
        return {"action": "human_review", "model": used,
                "reason": f"team confidence {team['confidence']:.2f}"}

    urgent = p_true(answers["urgent"])
    severity = answers["severity"]["score"]   # expected value, 0..3
    action = "page_oncall" if urgent > 0.8 and severity >= 2.0 else "enqueue"
    return {"action": action, "team": team["choice"], "model": used,
            "urgent": round(urgent, 3), "severity": round(severity, 2)}

Two details worth noticing. The paging rule combines two answers (urgent above 0.8 and expected severity at least 2.0), because a single probability is a thin basis for waking someone up. And the human_review branch is a first-class result, not an error. That is the whole payoff of getting probabilities back.

Test the control flow offline

Before spending tokens, stub requests.post and check that each branch fires. The stub below imitates the documented fields, so the printed lines prove the routing logic, not model quality.

import os, json
os.environ.update(CLOUDFLARE_ACCOUNT_ID="acct", CLOUDFLARE_AUTH_TOKEN="tok")
from unittest import mock
import cascade

def fake(url, headers=None, json=None, timeout=None):
    model = url.rsplit("/", 1)[1]
    text = json["state"]
    conf = 0.95 if "checkout" in text.lower() else (0.60 if model == "clef-flash" else 0.78)
    if "weird" in text: conf = 0.4
    class R:
        def raise_for_status(self): pass
        def json(self_):
            return {"success": True, "result": {"model": model, "answers": {
                "urgent": {"probability": 0.97 if "checkout" in text.lower() else 0.1},
                "team": {"choice": "technical", "confidence": conf, "probabilities": {"technical": conf}},
                "severity": {"score": 2.8 if "checkout" in text.lower() else 0.4, "confidence": 0.8, "legend": [], "probabilities": []}}}}
    return R()

with mock.patch("clef_router.requests.post", fake):
    for t in ["Checkout has been failing for every customer for the last hour.",
              "Can I move to the annual plan?", "weird message"]:
        print(t[:40], "->", cascade.route(t))
Checkout has been failing for every cust -> {'action': 'page_oncall', 'team': 'technical', 'model': 'clef-flash', 'urgent': 0.97, 'severity': 2.8}
Can I move to the annual plan? -> {'action': 'enqueue', 'team': 'technical', 'model': 'clef', 'urgent': 0.1, 'severity': 0.4}
weird message -> {'action': 'human_review', 'model': 'clef', 'reason': 'team confidence 0.40'}

The three lines show the three paths: handled by Clef-flash, escalated to Clef, and deferred to a human.

Step 4: Pick thresholds from data, not vibes

The 0.85 and 0.70 above are starting points. Because Clef was trained with a Brier-loss calibration objective, its confidence should track accuracy better than a typical LLM's self-reported certainty, but "should" is not a measurement. Label 100 to 200 real tickets, run them through both models, and sweep the threshold.

def sweep(rows, model="clef-flash"):
    # rows: list of (ticket_text, true_team)
    scored = []
    for text, truth in rows:
        a = decide(model, text, {"team": TICKET_QUESTIONS["team"]})["team"]
        scored.append((a["confidence"], a["choice"] == truth))
    for thr in (0.5, 0.6, 0.7, 0.8, 0.9, 0.95):
        kept = [ok for conf, ok in scored if conf >= thr]
        if kept:
            print(f"thr={thr:.2f} coverage={len(kept)/len(scored):.0%} "
                  f"accuracy={sum(kept)/len(kept):.1%}")

Read the output as a coverage versus accuracy curve. Pick the lowest threshold where accuracy on the kept tickets meets your bar, and accept that the rest go up a tier. Run this separately for each model, because Clef-flash and Clef are not calibrated identically.

Note that this call asks only the team question. You can drop questions you do not need, which keeps the input small.

Step 5: Decisions over images

Both models have a vision encoder, which Jev lacks. On the hosted API, the Hugging Face card says images and videos may be added to the request. It does not document how images are encoded over REST (base64, URL or byte array), so check the Workers AI model page before relying on it. Locally, you pass PIL images:

from PIL import Image

record = {
    "state": {"task": "Review the attached receipt."},
    "images": [Image.open("receipt.jpg")],
    "questions": {
        "legible": {"type": "noul", "instructions": "Is the receipt total legible?"},
    },
}
encoded = encode_record(processor.tokenizer, record, processor=processor)

Use cases that fit: is this screenshot a login page, does this upload contain a face, is this receipt readable enough to OCR. Cloudflare's Threat Intelligence team pairs Clef with Browser Run to categorise domains. Their reported number is 2.2 seconds for fetch, render and classify, versus 4.7 seconds with gpt-oss-120b, with more categories returned.

Step 6: Run the weights yourself

The weights are on Hugging Face as Cloudflare/clef and Cloudflare/clef-flash. The card was tested with torch 2.11 and transformers 5.10.2 on a single H200, so plan for a serious GPU for the 27B model. Clef-flash at 9B is the realistic one for smaller cards. The repo ships a joint_schema_model.py with a systemone helper that accepts the same request body as the hosted API:

import sys, torch
from huggingface_hub import snapshot_download

path = snapshot_download("Cloudflare/clef-flash")
sys.path.insert(0, path)
from joint_schema_model import load_release_model, systemone

model, processor = load_release_model(path, device="cuda")

response = systemone(model, processor, {
    "model": "clef-flash",
    "state": "Our checkout started returning errors and orders are blocked.",
    "questions": {
        "department": {
            "type": "choice",
            "instructions": "Which team should handle the message?",
            "criteria": {"billing": "Payments or invoices", "technical": "Bugs or outages"},
        },
        "urgency": {"type": "score", "criteria": ["Can wait", "This week", "Today"]},
        "outage": {"type": "noul", "instructions": "Is a service down?"},
    },
})
print(response["answers"])

Because the local helper takes the hosted request body unchanged, your decide() function can switch between local and hosted with one flag. Note that instructions is optional: when omitted, the question ID is used, so name your IDs clearly if you skip it. The card's own score example does exactly that.

A worked example: invoice triage

Decision models are not only for support. The model card's own example passes structured JSON as the state. Try the same pattern for accounts payable: feed the parsed invoice and ask three questions.

state = {"invoice": {"vendor": "Acme", "total": 1250.0, "currency": "USD",
                     "status": "overdue", "days_late": 41}}
questions = {
    "action": {"type": "choice",
               "instructions": "What should accounts payable do next?",
               "criteria": {"pay": "Approve payment now",
                            "chase": "Contact the vendor or requester",
                            "escalate": "Needs finance manager review"}},
    "large": {"type": "noul", "instructions": "Is the total above 1000 USD?"},
    "risk": {"type": "score", "instructions": "Late-payment risk?",
             "criteria": ["Low", "Medium", "High"]},
}
print(decide("clef", state, questions))

The large question is deliberately trivial. It is a good canary: a decision model should get it right nearly every time, so if it does not, your state formatting is probably wrong. For actual arithmetic, do not ask the model. Compute total > 1000 in code and keep Clef for judgement calls.

Common pitfalls

  • Treating it as an LLM. It does not follow open-ended instructions or write explanations. Every question needs a closed set of options. If you need reasoning, call a generative model after the decision.
  • Vague option descriptions. The criteria text is the only thing distinguishing options. "technical" versus "engineering" with no descriptions gives the model nothing. Write one clear sentence per option, and make them mutually exclusive.
  • Forgetting the score offset. The docs say a score is a probability-weighted value where 0 is the lowest level. A 4-item scale returns values between 0 and 3, not 1 and 4.
  • Trusting benchmarks over your data. Clef-flash beats Clef on some rows (BFCL, MMLU) and loses badly on others (CLINC150+OOS: 66.8 vs 97.4 macro-F1). On the Decision Index, GPQA Diamond and BBH, Jev scores far higher than Clef (78.3 vs 48.0 on GPQA). Measure on your own labels.
  • Benchmark source bias. The Decision Index is Jev's own benchmark and the numbers are Cloudflare's internal run. Treat the leaderboard as a vendor claim until you reproduce it.
  • Using it for open-ended arithmetic or lookup. It decides, it does not compute. Keep deterministic checks in code.
  • Skipping the human branch. A cascade that always returns an answer will be confidently wrong on out-of-distribution input. CLINC150+OOS exists precisely to test out-of-scope detection, and Clef-flash is the weaker model there.
  • Long inputs. The context is 65,536 tokens, but encode_record defaults to 16,384 tokens locally. Set max_length and max_state_tokens if you feed long documents.
  • Privacy assumptions. Cloudflare states it does not read, store or train on Workers AI requests and responses unless you opt into fine-tuning. That is a vendor statement; read the data usage page for your compliance needs.

Where this fits in an agent

The pattern generalises well beyond tickets. Put a decision model at any branch point that currently costs you a full LLM call: tool selection among a fixed set, whether a draft needs another revision, whether a retrieved passage is relevant, whether a user message is a follow-up or a new task. Then spend your generative tokens only where text is actually needed.

Cloudflare also announced an RL fine-tuning service for Clef built on AI Gateway, Workers AI, Containers and a new trainer. For now it is a hands-on engagement with their forward-deployed engineers, with a self-serve platform promised later. Until then, the AI Gateway logging part is something you can use today: route your decision calls through it so you accumulate the labelled data a fine-tune would need.

Quick reference

ItemValue
Hosted models@cf/cloudflare/clef, @cf/cloudflare/clef-flash
Open weightsCloudflare/clef, Cloudflare/clef-flash (Apache 2.0)
EndpointPOST /accounts/{id}/ai/run/@cf/cloudflare/{model}
Bodymodel, state, questions (+ images, videos locally)
noultrue/false, returns probability of true
choiceone of named options: choice, confidence, probabilities
scoreordered scale: score, confidence, legend, probabilities
Price per M input tokensClef $0.24, Clef-flash $0.09
Context65,536 tokens
Compatible withJev / SystemOne request and response bodies

Next steps

  • Print one real response and tighten p_true() to the exact shape you get.
  • Label 150 of your own decisions and run sweep() for both models.
  • Log every decision call through AI Gateway so you build a fine-tuning dataset.
  • Add a second decision point: let Clef choose which tool your agent should call next, then compare with your current LLM router on cost and latency.
  • Read Cloudflare's launch post and the Hugging Face model card for the training details, including the RLCD objective.

Sources: Cloudflare blog, "Introducing Clef: our open-source decision models, and new RL fine-tuning platform"; Workers AI model pages for clef and clef-flash; Hugging Face model card Cloudflare/clef.

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,605 newsletter subscribers.

Also get