Back to Blog

Integrating Clairic and Clairic-Flash into a Game Backend: A Practical Extraction Guide

Published on November 24, 2026
Integrating Clairic and Clairic-Flash into a Game Backend: A Practical Extraction Guide Generated with the help of AI

In a nutshell

Learn how to plan a Clairic-Flash integration for game backends with schema validation, server-side credentials, and real working code examples.

Your game backend is probably full of unstructured text that should be data: support receipts, design-doc tables, playtest notes, patch summaries, and bug-report screenshots. Cloudflare’s updated Clairic and new Clairic-flash are open-weight extraction models aimed squarely at that problem. The catch is that extraction pipelines fail at the edges — malformed JSON, missing dates, merged table rows, hallucinated values — and a sloppy integration turns those failures into bad records at scale.

This guide is a practical integration plan for game developers. It covers what Clairic and Clairic-flash actually do, where they fit in a game backend, how to keep model credentials server-side, and how to validate extracted records before they touch your live systems. The code examples are deliberately boring: a server endpoint, a strict output contract, and a client that never sees a model token.

What Clairic and Clairic-Flash actually are

Cloudflare describes both models as extraction models. They are not general-purpose chat models you should drop into your game loop. The updated Clairic focuses on extracting structured data from complex documents, including images and PDFs, with improved handling of tables, lists, and dates, plus better grounding of answers in the source material.

Clairic-flash is the lighter, faster sibling: a 9-billion-parameter model that Cloudflare positions for strong extraction and prediction performance in a compact package. Both models are hosted on Workers AI, and full open weights are available on Hugging Face. That matters because you can choose the deployment model that fits your volume: hosted inference for low-to-medium throughput, or self-hosted weights when you need tighter control over latency, data residency, or cost.

For game teams, the useful framing is simple: these models turn messy documents into candidate structured records. They do not decide whether those records are correct. That is your backend’s job.

Game workflows that benefit from extraction

The highest-value use cases are the ones where a human is currently copying values from a document into a tool. A few concrete examples:

  • Support receipts and purchase screenshots. Extract vendor, order ID, purchase date, total amount, and issue category from a player-submitted image.
  • Design-doc tables. Pull item stats from a PDF: item_id, rarity, base_damage, cooldown_seconds, drop_rate.
  • Playtest notes. Convert free-text notes into build_number, severity, repro_steps, and affected_map.
  • Patch-note summaries. Extract feature flags, dates, and affected platforms from release announcements.

At 10,000 support tickets per month, a 3% extraction failure rate is 300 bad records. That is enough to poison a refund queue or corrupt a balance spreadsheet. The integration needs to treat extraction as a validation pipeline, not a magic function.

The real pain point: extraction fails silently

Most LLM extraction demos work on one clean document. Production fails on the edges. A receipt is rotated 4 degrees. A PDF table has merged cells. A date is written as “last Tuesday” in a locale you did not expect. The model returns plausible JSON, your parser accepts it, and the bad value lands in your database.

The fix is not a longer prompt. It is a stricter contract. Define the output shape before you tune the prompt. Use closed enums for fields like vendor and issue_category. Require null for missing values instead of letting the model invent placeholders. Add a warnings array so the model can flag ambiguous fields instead of guessing silently. Then validate every field server-side.

That contract-first approach catches more failures than prompt engineering because it moves the failure from “the model said something weird” to “the backend rejected the record.” Rejection is cheap. Bad data is expensive.

Never call the model from a shipped client

This is non-negotiable: do not call Clairic or Clairic-flash directly from a Unity, Unreal, Godot, or web client. Any API token embedded in a build is public. Players can extract it, share it, and burn your quota. Treat model credentials like any other server secret: keep them in your backend, restrict access, and proxy requests through an endpoint you control.

The same principle applies to any backend that handles player data. If a client can call the model directly, it can also bypass your validation. For a deeper postmortem on how backend compromises play out in practice, read The Star Citizen Data Breach Explained: Architecting Game Backends to Survive Compromises. The lesson is the same: assume the client is hostile and keep the sensitive path server-side.

The integration sequence: from document to validated record

A production extraction pipeline has five stages. You can build them in a single Cloudflare Worker or split them across services, but the order matters.

  1. Define the extraction contract. Write a JSON schema with required fields, enums, nullable fields, and a warnings array. Decide how you will represent evidence: a quote, a page number, or both.
  2. Choose the model per document class. Use Clairic for complex PDFs, images, and table-heavy documents. Use Clairic-flash for high-volume text where latency and cost matter more than maximum extraction depth.
  3. Call the model server-side. Put a Worker or backend endpoint in front of Workers AI. The client sends text or an image reference to your endpoint, not to the model.
  4. Validate and ground the output. Parse JSON, check enums, check date formats, check numeric ranges, and verify that every evidence quote actually appears in the source text.
  5. Route warnings to a review queue. Records with warnings should not silently enter production tables. Sample them, review them, and track precision by document type.

The code below shows a Cloudflare Worker that implements stages 1, 3, and 4 for a support-receipt extraction use case. It uses Clairic-flash for speed, but the same pattern works with Clairic when you need stronger handling of images or complex PDFs.

// Cloudflare Worker: POST /api/extract
// Requires @cloudflare/workers-types for the Ai binding type.
interface Env {
  AI: Ai;
}

type Extraction = {
  vendor: "steam" | "epic" | "google_play" | "apple" | "unknown";
  order_id: string | null;
  purchase_date: string | null; // ISO 8601 date
  total_usd: number | null;
  issue_category: "refund" | "login" | "crash" | "payment" | "other";
  warnings: string[];
  evidence: { field: string; quote: string; page: number }[];
};

const MODEL = "@cf/cloudflare/clairic-flash";

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    if (request.method !== "POST") {
      return new Response("Method not allowed", { status: 405 });
    }

    const { text, page } = await request.json<{ text: string; page: number }>();
    if (!text || text.length > 20_000) {
      return Response.json({ error: "text must be 1-20000 chars" }, { status: 400 });
    }

    const prompt = `Extract a support receipt. Return JSON only.
Schema:
{
  "vendor": "steam" | "epic" | "google_play" | "apple" | "unknown",
  "order_id": string | null,
  "purchase_date": string | null (ISO 8601),
  "total_usd": number | null,
  "issue_category": "refund" | "login" | "crash" | "payment" | "other",
  "warnings": string[],
  "evidence": [{"field": string, "quote": string, "page": number}]
}
Rules:
- Use null when a field is not present.
- Add a warning for every ambiguous or missing field.
- Every non-null field must have an evidence quote that appears verbatim in the source.
Source page ${page}:
${text}`;

    const ai = await env.AI.run(MODEL, {
      messages: [
        { role: "system", content: "You are a strict extraction engine. Output JSON only." },
        { role: "user", content: prompt },
      ],
      max_tokens: 1024,
      temperature: 0,
    });

    let parsed: Extraction;
    try {
      parsed = JSON.parse(ai.response as string);
    } catch {
      return Response.json(
        { error: "model returned non-JSON", raw: ai.response },
        { status: 502 }
      );
    }

    const errors = validateExtraction(parsed, text);
    if (errors.length > 0) {
      return Response.json({ error: "validation failed", errors, parsed }, { status: 422 });
    }

    return Response.json(parsed);
  },
};

function validateExtraction(x: Extraction, source: string): string[] {
  const errors: string[] = [];
  const vendors = new Set(["steam", "epic", "google_play", "apple", "unknown"]);
  const categories = new Set(["refund", "login", "crash", "payment", "other"]);

  if (!vendors.has(x.vendor)) errors.push("vendor not in enum");
  if (!categories.has(x.issue_category)) errors.push("issue_category not in enum");

  if (x.purchase_date && !/^\d{4}-\d{2}-\d{2}$/.test(x.purchase_date)) {
    errors.push("purchase_date must be YYYY-MM-DD");
  }

  if (x.total_usd !== null && (typeof x.total_usd !== "number" || x.total_usd < 0)) {
    errors.push("total_usd must be a non-negative number or null");
  }

  for (const e of x.evidence) {
    if (!source.includes(e.quote)) {
      errors.push(`evidence quote not found: ${e.field}`);
    }
  }

  if (!Array.isArray(x.warnings)) errors.push("warnings must be an array");
  return errors;
}

The important part is not the specific prompt. It is the validateExtraction function. The model can return a syntactically valid object that still fails the contract. That is exactly what you want: a rejected record is a signal to retry, review, or fall back to manual handling.

The client should only talk to your backend

On the Unity side, the client sends OCR text or an image reference to your endpoint. It does not know the Workers AI model ID, and it does not hold a token. This keeps the credential surface small and lets you change models without shipping a new build.

using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

public class ExtractionClient : MonoBehaviour
{
    [System.Serializable]
    private class ExtractRequest
    {
        public string text;
        public int page;
    }

    private const string BackendUrl = "https://your-game-backend.example.com/api/extract";

    public IEnumerator ExtractReceipt(string ocrText, int page)
    {
        var body = new ExtractRequest { text = ocrText, page = page };
        byte[] payload = Encoding.UTF8.GetBytes(JsonUtility.ToJson(body));

        using (UnityWebRequest req = new UnityWebRequest(BackendUrl, "POST"))
        {
            req.uploadHandler = new UploadHandlerRaw(payload);
            req.downloadHandler = new DownloadHandlerBuffer();
            req.SetRequestHeader("Content-Type", "application/json");

            // No model token here. The backend owns the Workers AI credential.
            yield return req.SendWebRequest();

            if (req.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"Extraction failed: {req.responseCode} {req.error}");
                yield break;
            }

            Debug.Log(req.downloadHandler.text);
        }
    }
}

This is the minimum viable security boundary. If you later add image uploads, keep the same pattern: the client uploads to your backend, your backend calls the model, and your backend returns only validated records.

Edge cases that break extraction pipelines

The model is only one part of the system. Most production failures come from document handling and validation gaps. These are the ones game teams hit most often.

Multi-page tables and merged cells

PDF tables often split across pages or use merged cells that flatten into ambiguous text. If you extract the whole PDF in one call, the model may merge rows or drop headers. A more reliable pattern is page-level extraction: send one page at a time, require source_page in every record, then merge records by a stable key such as item_id or order_id. If the key is missing, route the record to review instead of guessing.

Dates and locales

Dates are a classic hallucination target. “Last Tuesday” is not a date. “03/04/2025” is ambiguous between March 4 and April 3. Require ISO 8601 in the schema, and add a date_confidence warning when the source is relative or locale-ambiguous. Validate the format server-side and reject anything that does not match YYYY-MM-DD.

Low-quality images and OCR noise

Receipts and screenshots are often rotated, cropped, or compressed. Preprocess before extraction: deskew, crop to the receipt boundary, and increase contrast. If you cannot improve the image, add an image_quality warning and lower the confidence threshold. Do not let a blurry image produce a high-confidence total_usd value.

Hallucinated evidence

Grounding is the strongest defense against invented values. Require the model to return an evidence quote for every non-null field, then verify that the quote appears verbatim in the source text. If the quote is missing, reject the record. This one check catches many hallucinations because the model cannot quote text that is not there.

Rate limits and retries

Extraction is often bursty. A support backlog or a playtest upload can produce hundreds of documents at once. Use a queue, not a synchronous request in your game loop. Retry failed calls with exponential backoff and jitter, and cap retries at three. For Clairic-flash, a 9-billion-parameter model at 4-bit quantization is roughly 5–6 GB of weights, which leaves headroom on a 24 GB GPU for batching and KV cache. Measure tokens per second on your own documents before committing to a self-hosted GPU plan.

Best practices you can apply immediately

  1. Contract first, prompt second. Define enums, required fields, nullable fields, and a warnings array before you tune the prompt. Validate every field server-side. A rejected record is cheaper than a bad record.
  2. Keep model credentials server-side. Never ship a Workers AI token in a client build. Proxy requests through your backend, restrict access, and log every extraction request with an idempotency key.
  3. Ground every non-null field. Require an evidence quote and source page. Reject records where the quote does not appear in the source. This is the highest-leverage validation check you can add.
  4. Route by document complexity. Use Clairic for images, PDFs, and table-heavy documents. Use Clairic-flash for high-volume text where speed matters. Do not use one model for every document class just because it is simpler.
  5. Review warnings, not everything. Send records with warnings to a human review queue and sample 1–5% of clean records. Track precision by document type so you know which extraction jobs are actually safe to automate.

Where horizOn fits in the surrounding backend

Clairic and Clairic-flash solve the extraction problem. They do not solve the rest of your game backend. You still need authentication, account-bound storage, leaderboards, remote configuration, crash reports, and player communication. That is where horizOn fits: it provides end-user authentication and account-bound sessions, account-bound Cloud Save with revision-aware reads and writes, leaderboards, remote configuration, multilingual in-game news and localization, crash reports, user feedback, user logs, transactional email, and gift codes.

Keep model inference in Workers AI or your own GPU worker. Use horizOn for the verified backend services around it, and keep the extraction pipeline’s validation logic in your own code where you can test it. If you are architecting the broader backend, the same discipline in Mastering the Craft: Why Modern Game Architecture Demands More Than Just a Great Engine applies: separate concerns, validate at the boundary, and make failures observable.

The takeaway

Clairic and Clairic-flash are useful because they turn messy documents into candidate structured records. They are dangerous when you treat that output as truth. The integration that works is the boring one: a strict schema, server-side credentials, evidence grounding, validation, and a review queue for warnings.

Start with one document type — support receipts are a good first target because the schema is small and the failure cost is easy to measure. Build the contract, run 100 real documents through Clairic-flash, and count how many records pass validation without warnings. If that number is below 90%, fix the contract and preprocessing before you scale. If you need authentication, account-bound Cloud Save, leaderboards, or remote config for the backend that consumes those records, try horizOn free.


Source: An updated Clairic and Clairic-flash are now open-weight, from the new Workers AI Superintelligence team