> Canonical URL: https://codingcat.dev/post/gemini-decisions-api-vs-jev-vs-clef

# Gemini Decisions API vs. TypeSafe Jev vs. Cloudflare Clef: System One Routing in Production

✏️ Blog PostNovember 14, 2026[#AI & Agents](/topic/ai)[![](/logos/tags/gemini-symbol-light.svg)![](/logos/tags/gemini-symbol-dark.svg)Google Gemini](/topic/gemini)[![](/logos/tags/cloudflare-symbol-light.svg)![](/logos/tags/cloudflare-symbol-dark.svg)Cloudflare](/topic/cloudflare)[![](/logos/tags/cloudflare-workers-symbol-light.svg)![](/logos/tags/cloudflare-workers-symbol-dark.svg)Cloudflare Workers](/topic/cloudflare-workers)[#Architecture](/topic/architecture)[![](/logos/tags/typescript-symbol-light.svg)![](/logos/tags/typescript-symbol-dark.svg)TypeScript](/topic/typescript)

# Gemini Decisions API vs. TypeSafe Jev vs. Cloudflare Clef: System One Routing in Production

![CodingCat.dev tutorial cover image](https://cdn.sanity.io/images/hfh83o0w/production/ef0168a3852d4ce2eafed69a169efd8006e7f36c-1024x571.jpg?w=1024&q=82&fit=max&auto=format)[![Alex Patterson](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/a606dfaa381aab08ddbe16a33fe1d3e1fb37c927-400x400.jpg?w=96&h=96&q=82&fit=max&auto=format)Alex Patterson](/author/alex-patterson)

If you are still calling a frontier reasoning model with `response_schema` just to check a content guardrail or route a support ticket into one of five queues, you are paying a massive latency and compute tax for work that does not require text generation. Autoregressive decoding was built to write essays and synthesize code token by token, not to flip a boolean switch on your hot path.

With Google's launch of the [**Gemini Decisions API**](https://blog.google/innovation-and-ai/technology/developers-tools/gemini-decisions-api/) (`gemini-decision-1`) alongside [**TypeSafe AI's Jev**](https://typesafe.ai) (`jev-1.14`) and [**Cloudflare's Clef**](https://huggingface.co/Cloudflare/clef) (`@cf/cloudflare/clef`), "System One" discriminative models have officially graduated from a niche startup thesis into a standard layer of the modern AI stack. Instead of generating JSON strings character by character, these models evaluate a shared payload against typed questions in a **single forward pass**, bill **zero output tokens**, and return calibrated probabilities in roughly **100ms to 250ms**.

Let's break down why structured outputs on generative LLMs hit an architectural wall at scale, why all three providers converged on the exact same `noul`, `choice`, and `score` primitives, and how to wire `gemini-decision-1` into a real TypeScript media pipeline.

## Why Structured Outputs Are Overkill for Routing

Over the last two years, constrained decoding (`response_schema`, `response_format`, and tool-forced JSON schemas) became the default hammer for every classification nail in production. Need to check if an incoming prompt violates policy, classify user intent across six product pillars, and rate urgency from 1 to 5? Most teams serialize a JSON schema, call a frontier LLM, and `JSON.parse()` the response.

Under the hood, that workflow is wildly inefficient for closed-set decisions:

- **Sequential Token Decoding Overhead**: Even when constrained by a finite-state grammar, an autoregressive LLM still runs sequential decoding passes to emit `{`, `"`, `r`, `o`, `u`, `t`, `e`, `"`, `:`, `"`, `b`, `i`, `l`, `l`, `i`, `n`, `g`, `"`, `}`. If the model has an active reasoning or "thinking" budget enabled by default, it may burn hundreds of hidden reasoning tokens before emitting that first curly brace.
- **Output Token Billing Multipliers**: Generative APIs charge 3x to 8x more per million output tokens than input tokens. When you evaluate 25 rubric checks against a single document, verbose JSON keys and enum labels compound your bill on every request.
- **Question Cross-Contamination**: When an autoregressive model generates Field B *after* generating Field A in the same JSON object, its own sampled tokens for Field A condition the probability distribution of Field B. Changing the key order in your schema can silently shift your classification accuracy.
- **Uncalibrated Binary Guessing**: Asking a chat model to output `{"is_safe": true}` forces a discrete sample. Unless you manually wrangle raw token `logprobs` across multi-token strings, your application cannot tell the difference between a rock-solid `0.99` certainty and a coin-flip `0.51` guess.

✏️ Autoregressive LLM Decoding vs. System One Forward Pass✓ Good PatternVISUAL DIAGRAM[Diagram Walkthrough]Step 1: Input Payload -> Step 2: Prefill + Thinking -> Step 3: Token-by-Token Decode -> Step 4: Unparsed JSON String -> Step 5: Multimodal Input -> Step 6: Single Prefill Pass -> Step 7: Isolated Schema Head -> Step 8: Calibrated ProbabilitiesAAA Contrast VerifiedArchitectural DimensionGenerative LLM (`response_schema`)System One Decision Model (`noul` / `choice` / `score`)Why It Matters on the Hot Path**Inference Pass** Prefill + `N` sequential decode steps**Single forward pass**  (prefill + parallel scoring head)Latency stays flat whether you ask 1 question or 100 questions.**Typical End-to-End Latency** `600ms to 2,500ms+``100ms to 250ms`Fits comfortably inside synchronous API gateways and edge middleware.**Output Token Cost** `$0.40 to $15.00` / 1M output tokens`$0.00` (zero output tokens generated)Eliminates output token billing completely.**Multi-Question Independence** Later JSON fields attend to earlier generated fields**Strict question isolation**  in a single passReordering questions never mutates individual answers.**Uncertainty Signal** Discrete string (`"true"` or `"billing"`)**Calibrated probabilities (** `0.0`** to ** `1.0`**) + ** `confidence`Enables deterministic threshold routing in TypeScript.

## Shared "System One" Primitives: `noul`, `choice`, and `score`

Borrowing Daniel Kahneman's cognitive framing, **System Two**  models deliberate step by step over open-ended reasoning problems, while **System One**  models make fast, instinctive, bounded judgments over a known state.

**TypeSafe AI**  pioneered this exact API contract with **Jev**  (named after 19th-century economist William Stanley Jevons and the *Jevons Paradox*: when you make machine decisions orders of magnitude faster and cheaper, total demand for automated evaluation explodes rather than shrinks). When Cloudflare launched **Clef**  in October 2026 and Google followed with **Gemini Decision 1**  in November 2026, neither company invented a proprietary wrapper format. Both adopted TypeSafe's three core typed question primitives almost verbatim:

### 1. `noul` (Calibrated Boolean Probability)

Why is a yes/no check called a `noul` instead of a `bool`? TypeSafe named the primitive as a nod to a **Bernoulli trial**  (confirmed by TypeSafe CEO Diogo Almeida): a random experiment with exactly two possible outcomes, parameterized by a continuous probability `p` in `[0.0, 1.0]`.

A `bool` gives you `true` or `false`. A `noul` evaluates a proposition against your input state and returns the calibrated probability that the statement holds (for example, `0.982`), alongside a `confidence` score.

### 2. `choice` (Unordered Categorical Routing)

Used when picking one winner from a closed, unordered set of options (such as intent classification, tool selection, or department routing). You pass a dictionary mapping option keys to plain-English criteria, and the model returns the winning `choice`, a normalized `probabilities` map across every option summing to `1.0`, and a `confidence` metric.

### 3. `score` (Ordered Rubric Evaluation)

Used when grading an input against an ordered scale from lowest to highest (such as incident severity, audio clarity, or lead quality). Unlike `choice`, `score` understands ordinal rank. In `gemini-decision-1`, you define `2` to `255` ordered rubric level descriptions (indexed starting at `0`), and the API returns both per-level `probabilities` and a continuous, probability-weighted expected `score`:

EXPECTED RUBRIC SCORE FORMULAequationE[score] = Σ (i = 0 to K - 1) [ i × P(level = i) ]Copied! 🐾📄 src/lib/expected-rubric-score.tstypescript

```
// Probability-weighted continuous expected score across K ordered rubric levels (0..K-1)
const expectedScore = levelProbabilities.reduce(
  (sum, probability, levelIndex) => sum + levelIndex * probability,
  0,
);
```

That continuous expected value is gold for ranking feeds or sorting queues without ties, because an item with an 80% chance of Level 2 and a 20% chance of Level 3 (`2.20`) cleanly outranks an item with an 80% chance of Level 2 and a 20% chance of Level 1 (`1.80`).

ARCHITECTURE NOTE**Jev's Spatial Fourth Primitive (`box`):**  In `jev-1.14`, TypeSafe also introduced an experimental fourth primitive called `box` for visual inputs. Instead of returning a class label, `box` locates a described target inside a PNG or JPEG image and returns normalized `[top, bottom, left, right]` bounding-box coordinates paired with a confidence score. Neither Cloudflare Clef nor Gemini Decision 1 currently exposes `box`.

### Tuning Thresholds Instead of Trusting Hallucinations

Because System One models are explicitly post-trained for **probability calibration**  (when the model predicts `0.85`, that proposition holds roughly 85% of the time on held-out distributions), your application code regains deterministic control over risk. Instead of praying a prompt tweak stops false positives, you implement explicit three-band routing:

- **Auto-Execute (`noul >= 0.85` and `confidence >= 0.80`)**: Route the ticket, approve the clip, or fire the webhook immediately in ~180ms.
- **Escalate to System Two (`0.20 DimensionGemini Decision 1 (`gemini-decision-1`)TypeSafe Jev (`jev-1.14`)Cloudflare Clef (`@cf/cloudflare/clef`)**Licensing & Hosting** Proprietary managed API (Google AI Studio / Gemini API `v1beta`, includes free prototyping tier)Proprietary managed API (`api.typesafe.ai`)**Apache 2.0 Open Weights**  (`Cloudflare/clef` on Hugging Face) + serverless **Cloudflare Workers AI** **Model Architecture** Native Gemini multimodal discriminative prefill + isolated parallel scoringCustom non-autoregressive System One decision architecture**27B parameters**  post-trained on `Qwen/Qwen3.8-27B` + custom joint schema transformer head (plus 9B `clef-flash` sibling)**Supported Input Modalities** **Text, Images, Raw Audio, Video, and Multi-Page PDFs** Text, structured JSON, and Images (PNG/JPEG) + experimental spatial `box` primitiveText, structured JSON, and Images / sampled video frames (via Qwen3.8 vision encoder)**Context Window** `262,144`** tokens (** `256K`**)**  standard`64,000`** tokens**  per request (`32,768` per question) default; `262,144`** tokens**  opt-in via header`65,536`** tokens (** `65k`**)** **Max Questions per Request** Up to `1,000`** isolated questions** **Token-budget-bound**  (no hard question cap within context limit)Up to `64`** typed questions** **Typical Latency** `150ms to 250ms``70ms to 250ms``120ms to 300ms` (Workers AI edge GPUs)**Pricing per 1M Input Tokens** `$0.10` (`$0` output tokens)`$0.042` (`$0` output tokens)`$0.24` on Workers AI (`$0` output tokens) or **compute-only**  self-hostedAJ PRO-TIP**AJ Pro-Tip on Long Context in Jev:**  By default, TypeSafe Jev caps individual question+state pairs at `32k` tokens and full requests at `64k` tokens. If you need the full `262k` (`262,144` -token) context window in `jev-1.14`, you must explicitly opt in by sending the request header `TypeSafe-Danger-Zone-Long-Context: true`.

## Working TypeScript Example: Multimodal Podcast Clip Triage with `@google/genai`

Let's look at a real production workflow we run into constantly on **CodingCat.dev**: triaging incoming raw **Podcast Episode**  segments and short-form video clips.

Historically, evaluating a 90-second MP4 or MP3 clip required a brittle three-stage chain: upload audio to an object bucket, run speech-to-text transcription (losing vocal tone, crosstalk, and on-screen code context), and finally feed the transcript into an LLM with a JSON schema. Because `gemini-decision-1` is natively multimodal, we can pass the raw audio or video bytes directly alongside episode metadata and evaluate sponsor safety (`noul`), topic pillar routing (`choice`), and viral Shorts potential (`score`) in a single ~200ms forward pass.

IMPORTANT**SDK & Endpoint Gotcha (`decisions.create` vs. `:evaluate`):**  Early previews and community posts speculated that the Decisions API would hang off `models/gemini-decision-1:evaluate`. In the official `@google/genai` SDK (v3.2+, using `apiVersion: "v1beta"`), the canonical method is **`ai.decisions.create(...)`**, backed by the dedicated REST endpoint `POST https://generativelanguage.googleapis.com/v1beta/decisions`. Always pin `apiVersion: "v1beta"` when initializing `GoogleGenAI`.

Install the current Google GenAI SDK:

Copied! 🐾

```
npm install @google/genai@latest
```

Here is the complete, copy-pasteable TypeScript module:

Copied! 🐾📄 src/lib/triage-podcast-clip.tstypescript

```
import { readFile } from "node:fs/promises";
import { GoogleGenAI } from "@google/genai";

// Initialize the official SDK targeting v1beta for the Gemini Decisions API.
// Automatically reads process.env.GEMINI_API_KEY.
const ai = new GoogleGenAI({ apiVersion: "v1beta" });

export interface ClipTriageDecision {
  status: "AUTO_APPROVE" | "ESCALATE_REVIEW" | "REJECT_UNSAFE";
  brandSafeProbability: number;
  brandSafeConfidence: number;
  targetCategory: string;
  categoryProbabilities: Record;
  viralScoreExpected: number; // Continuous 0.00 to 3.00 rubric expectation
  viralScoreConfidence: number;
}

export async function triagePodcastClip(
  audioFilePath: string,
  episodeNotes: string,
): Promise {
  const audioBytes = await readFile(audioFilePath);
  const audioBase64 = audioBytes.toString("base64");

  // Single forward pass: 0 output tokens billed, isolated parallel evaluation
  const result = await ai.decisions.create({
    model: "gemini-decision-1",
    input: [
      {
        type: "audio",
        data: audioBase64,
        mimeType: "audio/mp3",
      },
      {
        type: "text",
        text: `Podcast Episode Context: ${episodeNotes}`,
      },
    ],
    questions: {
      // 1. NOUL: Calibrated Bernoulli probability (0.0 to 1.0)
      brand_safe_for_sponsors: {
        type: "noul",
        instructions:
          "Is this audio clip completely safe to pair with enterprise developer tool sponsor reads?",
        criteria: {
          true: "Clean technical discussion, respectful tone, zero profanity, NDA leaks, or disparagement.",
          false: "Contains profanity, personal attacks, leaked credentials, or unverified security claims.",
        },
      },

      // 2. CHOICE: Closed-set categorical routing across unordered options
      content_category: {
        type: "choice",
        instructions:
          "Which primary CodingCat.dev engineering topic best matches this clip?",
        criteria: {
          edge_and_workers:
            "Cloudflare Workers, Hono, D1, edge caching, or serverless isolates.",
          ai_engineering:
            "LLMs, agentic workflows, MCP servers, RAG, or model routing.",
          frontend_web:
            "Astro, Next.js, React, Tailwind CSS, browser APIs, or accessibility.",
          backend_and_auth:
            "Databases, Better-Auth, Sanity CMS schemas, queues, or distributed systems.",
        },
      },

      // 3. SCORE: Ordered rubric levels (indexed 0 to 3 from lowest to highest)
      viral_clip_potential: {
        type: "score",
        instructions:
          "Rate this clip's standalone hook and retention potential as a 60-second vertical video.",
        criteria: [
          "0 - Low energy, heavy housekeeping banter, or requires missing visual context.",
          "1 - Solid technical point, but slow setup with no clear takeaway.",
          "2 - Strong architectural insight with a crisp problem-and-solution arc.",
          "3 - Instant contrarian hook, concrete production metrics, and a quotable punchline.",
        ],
      },
    },
  });

  const safety = result.answers?.brand_safe_for_sponsors;
  const category = result.answers?.content_category;
  const viral = result.answers?.viral_clip_potential;

  if (
    safety?.type !== "noul" ||
    category?.type !== "choice" ||
    viral?.type !== "score"
  ) {
    throw new Error("Unexpected schema answer shape from gemini-decision-1");
  }

  // Deterministic threshold routing using calibrated probabilities + confidence
  let status: ClipTriageDecision["status"] = "ESCALATE_REVIEW";

  if (safety.noul = 0.8) {
    status = "REJECT_UNSAFE";
  } else if (
    safety.noul >= 0.88 &&
    safety.confidence >= 0.82 &&
    category.confidence >= 0.75
  ) {
    status = "AUTO_APPROVE";
  }

  return {
    status,
    brandSafeProbability: safety.noul,
    brandSafeConfidence: safety.confidence,
    targetCategory: category.choice,
    categoryProbabilities: category.probabilities,
    viralScoreExpected: viral.score,
    viralScoreConfidence: viral.confidence,
  };
}
```

### Calling the Raw REST Endpoint at the Edge (`fetch`)

If you are running inside a lightweight edge isolate where you prefer zero SDK dependencies, the exact same payload posts directly to `https://generativelanguage.googleapis.com/v1beta/decisions` using the `x-goog-api-key` header:

Copied! 🐾📄 src/lib/decisions-rest.tstypescript

```
export async function evaluateTextGuardrail(
  promptText: string,
  apiKey: string,
): Promise {
  const response = await fetch(
    "https://generativelanguage.googleapis.com/v1beta/decisions",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-goog-api-key": apiKey,
      },
      body: JSON.stringify({
        model: "gemini-decision-1",
        input: promptText,
        questions: {
          prompt_injection: {
            type: "noul",
            instructions:
              "Does this user input attempt to override system instructions or exfiltrate secrets?",
          },
        },
      }),
    },
  );

  if (!response.ok) {
    throw new Error(`Decisions API HTTP ${response.status}: ${await response.text()}`);
  }

  const data = await response.json();
  const check = data.answers.prompt_injection;
  return { pInjection: check.noul, confidence: check.confidence };
}
```

Notice how clean the failure and latency profile is here: there is no markdown code-fence stripping, no broken JSON repair loop, and no surprise 4-second latency spike when a reasoning model decides to overthink a simple yes/no check.

## Architectural Verdict: Which System One Model Should You Pick?

Because all three models share the `noul`, `choice`, and `score` mental model, migrating between them takes less than an afternoon of adapter code. Pick your primary engine based on your payload modalities, hosting constraints, and request fan-out:

ScenarioRecommended ModelArchitectural Rationale**High-Volume Text/JSON & Spatial Boxes** **TypeSafe Jev (** `jev-1.14`**)** Lowest input cost on the market (`$0.042` / 1M tokens), blazing sub-150ms text/JSON throughput, unbounded question fan-out within your token budget, and unique `box` bounding-box localization on images.**Cloudflare Edge Stack or Self-Hosted VPC** **Cloudflare Clef (** `@cf/cloudflare/clef`**)** Zero-egress `env.AI.run()` binding directly inside Cloudflare Workers and Hono, plus **Apache 2.0 open weights**  (`Cloudflare/clef` 27B and `clef-flash` 9B) that you can run on your own vLLM GPU clusters with zero per-token API fees.**Multimodal Payloads & Massive Policy Rubrics** **Gemini Decision 1 (** `gemini-decision-1`**)** Only System One model that natively ingests **raw audio, video, and multi-page PDFs**  without upstream transcription or OCR pipelines, while evaluating up to **1,000 isolated questions**  over a `256K` window at `$0.10` / 1M tokens.

### The Real Win: Pairing System One with System Two

The sharpest architectural move in late 2026 is not replacing frontier reasoning models: it is **putting a System One gatekeeper in front of every System Two call**.

When a `$0.042` to `$0.10` per-million-token decision pass absorbs 85% of routine routing, moderation, and rubric scoring in 180ms, and uses calibrated `confidence` thresholds to escalate only genuinely ambiguous 15% edge cases to a heavy reasoning model, your p95 latency drops by an order of magnitude and your monthly inference bill plummets. Stop paying essay writers to flip switches.

✏️ Visual Architecture Diagram

## how this post connects together.

Follow AJ from first principles to production-ready architecture.

Let’s build it!✏️ Visual Diagram: Gemini Decisions API vs. TypeSafe Jev vs. Cloudf…✓ Good PatternVISUAL DIAGRAM[Diagram Walkthrough]Step-by-step diagram breakdown for Gemini Decisions API vs. TypeSafe Jev vs. Cloudflare Clef: System One Routing in Production: start with Gemini Decisions API v, implement Hands-On Implementation, and ship to production.AAA Contrast Verified▶ Watch on @CodingCatDev YouTubeRelated Course & Video

## Watch the Related Video Deep Dive: Cloudflare Agents, Durable Objects & Stateful Workflows in TypeScript

Build stateful, long-running AI agents and resilient multi-step workflows using the Cloudflare Agents SDK, Durable Objects with embedded SQLite, WebSockets hibernation, and Workflows.

[View Full Page →](/course/cloudflare-agents-durable-workflows-typescript)![](https://cdn.sanity.io/images/hfh83o0w/production/d1afde44cc19c93fb4a68cfa428d5ff35009a7ca-1376x768.png?rect=6,0,1365,768&w=1920&h=1080&q=82&fit=max&auto=format)[@CodingCatDev62.5K / 100K Subscribers Goal](https://www.youtube.com/@codingcatdev?sub_confirmation=1)[Subscribe on YouTube→](https://www.youtube.com/@codingcatdev?sub_confirmation=1)[Watch on YouTube App ↗](https://www.youtube.com/watch?v=0GrZo2jxbUo&list=PLR0ZSOt97grA)

## related deep dives.

[All Blog Posts&rarr;](/blog)[![PHP2Shell (CVE-2026-109618): How AI Found a Decade-Old Bug in 70% of the Web](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/e83065d0a4e2f841ce64d3f4aea8ddbbf07e5cb9-1376x768.jpg?w=1376&q=82&fit=max&auto=format)](/post/php2shell-cve-2026-109618-ai-php-security-scramble)October 22, 2026[![](/logos/tags/php-symbol-light.svg)![](/logos/tags/php-symbol-dark.svg)PHP](/topic/php)[#Security](/topic/security)[#AI & Agents](/topic/ai)[+5](/post/php2shell-cve-2026-109618-ai-php-security-scramble)

### [PHP2Shell (CVE-2026-109618): How AI Found a Decade-Old Bug in 70% of the Web](/post/php2shell-cve-2026-109618-ai-php-security-scramble)

Two critical pre-authentication RCE flaws in PHP (CVE-2026-109618 and CVE-2026-109619), uncovered by AI models from OpenAI and Google Gemini, sparked a global patching scramble across 70% of the web. Here is how PHP2Shell works and how to patch your servers.

[![Alex Patterson](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/a606dfaa381aab08ddbe16a33fe1d3e1fb37c927-400x400.jpg?w=96&h=96&q=82&fit=max&auto=format)Alex Patterson](/author/alex-patterson)[![Sanity Knowledge Bases](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/38b0f021c51d97043c8a1ebf31d505a0ea877b7c-2752x1536.jpg?w=1920&q=82&fit=max&auto=format)](/post/sanity-knowledge-bases)October 17, 2026[![](/logos/tags/mcp-symbol-light.svg)![](/logos/tags/mcp-symbol-dark.svg)MCP](/topic/mcp)[#AI & Agents](/topic/ai)[![](/logos/sanity/Sanity-Symbol--black_on_transparent.svg)![](/logos/sanity/Sanity-Symbol--white_on_transparent.svg)Sanity](/topic/sanity)[+5](/post/sanity-knowledge-bases)

### [Sanity Knowledge Bases](/post/sanity-knowledge-bases)

Eliminate query-time guessing in your AI agents. Learn how Sanity Context Knowledge Bases compile structured datasets, crawled documentation websites, and uploaded files ahead of time, resolve conflicting facts, and serve a compact outline over Context MCP.

[![Alex Patterson](https://cdn.sanity.io/media-libraries/mlttp0BZbCpV/images/a606dfaa381aab08ddbe16a33fe1d3e1fb37c927-400x400.jpg?w=96&h=96&q=82&fit=max&auto=format)Alex Patterson](/author/alex-patterson)