Build a drawing game · Exercise 02

Add a decision model

Write your word list, send each drawing to Clef on Workers AI, and show a probability for every word.

Add a decision model

Your canvas works. Now it needs someone to guess. In this exercise you’ll write the list of words players can draw, send each drawing to a model, and show its answer as a bar for every word.

What’s a decision model?

Most AI models you’ve used write text: you ask, they answer in words. A decision model doesn’t write anything. You give it some input and a question with the answers you allow, and it returns a probability for each answer. It’s fast, and there’s nothing to parse: the answer is already in the shape your code needs.

Clef is a family of decision models made by Cloudflare that run on Workers AI. It can look at images, and it has three kinds of question:

  • choice: pick one option from a list you define. That’s your game’s guess.
  • noul: yes or no, returned as the probability of yes.
  • score: a rating on a scale you write.

You’ll use Clef-flash, the fastest and cheapest of them. If you took Build a guestbook, you’ve already used it to catch spam with a noul question.

Your word list

Your word list is the whole game. Each word has a short description, and Clef reads it to decide what each option means:

src/words.tsexport const WORDS = {
  cow: "A cow",
  duck: "A duck",
  tractor: "A tractor",
  barn: "A red barn",
  // ...
} satisfies Record<string, string>;

export type Word = keyof typeof WORDS;

Words that look alike when drawn compete with each other. When we drew a circle with “sun” as the target, Clef said circle with 95% and sun with 2%. Both were on the list, and a plain circle looks more like a circle. Pick words that look different, or describe them so they do: “The sun, with rays around it”.

Asking for a guess

Your Worker sends the drawing and the word list to Clef, and passes the answer back to the page:

src/index.tsimport { env } from "cloudflare:workers";
import { WORDS } from "./words.ts";

export default {
  async fetch(request) {
    const url = new URL(request.url);
    if (url.pathname !== "/api/guess" || request.method !== "POST") {
      return new Response("Not found", { status: 404 });
    }

    const { image } = await request.json<{ image: unknown }>();
    if (typeof image !== "string" || !image.startsWith("data:image/png;base64,")) {
      return Response.json({ error: "Send a PNG data URL" }, { status: 400 });
    }

    const started = Date.now();
    const result = await env.AI.run("@cf/cloudflare/clef-flash", {
      model: "clef-flash",
      images: [image],
      state: "A hand-drawn sketch on a white canvas. It may still be in progress.",
      questions: {
        guess: { type: "choice", instructions: "Which word is the player drawing?", criteria: WORDS },
      },
    });
    return Response.json({ ...result, ms: Date.now() - started });
  },
} satisfies ExportedHandler;

The answer has a probability for every word, adding up to 1, and choice is the highest one. Here’s a real answer for a drawing of a house, with an eight-word list:

{
  "answers": {
    "guess": {
      "type": "choice",
      "choice": "house",
      "probabilities": {
        "circle": 0.0077,
        "triangle": 0.0084,
        "square": 0.0086,
        "house": 0.9456,
        "person": 0.0086,
        "sun": 0.0065,
        "tree": 0.0073,
        "fish": 0.0073
      },
      "confidence": 0.8794
    }
  },
  "usage": { "input_tokens": 408, "output_tokens": 0 },
  "ms": 386
}

The drawing never goes from the browser to the model directly. The page talks to your Worker, and only your Worker can call Workers AI through its binding, so there’s no API key in the page for anyone to copy.

Prerequisites

  • You’ve completed Build a canvas and still have that project on disk.
  • The cf CLI logged in to your Cloudflare account (cf auth whoami).