Image-Text-to-Text
Transformers
Safetensors
qwen3_5
clairic
cloudflare
systemone
multimodal
structured-output
information-extraction
custom-code
conversational
Instructions to use Cloudflare/clairic-flash with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Cloudflare/clairic-flash with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="Cloudflare/clairic-flash") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("Cloudflare/clairic-flash") model = AutoModelForMultimodalLM.from_pretrained("Cloudflare/clairic-flash", device_map="auto") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Cloudflare/clairic-flash with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Cloudflare/clairic-flash" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Cloudflare/clairic-flash", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker
docker model run hf.co/Cloudflare/clairic-flash
- SGLang
How to use Cloudflare/clairic-flash with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Cloudflare/clairic-flash" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Cloudflare/clairic-flash", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Cloudflare/clairic-flash" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Cloudflare/clairic-flash", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }' - Docker Model Runner
How to use Cloudflare/clairic-flash with Docker Model Runner:
docker model run hf.co/Cloudflare/clairic-flash
File size: 10,386 Bytes
dc7d8aa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | from __future__ import annotations
import json
import math
from decimal import ROUND_HALF_UP, Decimal, DecimalException, localcontext
from typing import Any
from . import image_rows
VERSION = "parallel-ar-json-scalar-v1"
EOS = "<|im_end|>"
EXTRACTION_INSTRUCTION = "Extract the requested value from the supplied input, following the field instructions and scope."
MEDIA_EVIDENCE_INSTRUCTION = "The attached images are the document pages and contain extraction evidence. Use all attached pages together with the accompanying text, following the field instructions and requested scope."
COMPUTATION_INSTRUCTION = "Answer the requested field using the supplied input and field instructions. Perform any required arithmetic, reasoning, normalization, or unit conversion. A computable answer is available even when it is not written literally in the source."
KNOWLEDGE_INSTRUCTION = "Answer the requested field using reliable prior knowledge and any relevant supplied input. This field explicitly permits knowledge: true. The answer does not need to appear in the document. Missing source evidence does not make a known factual answer unavailable. Return null only when neither reliable prior knowledge nor the input determines the answer. Follow the field instructions and scope."
RECOVERY_INSTRUCTION = "Answer the requested field using the supplied input and field instructions. Copy the matching source value exactly. Check labels, surrounding context and requested entity. Do not calculate, convert units, complete a name, or substitute a related field. Return the value if it is explicitly present; return null if it is absent."
BOOLEAN_INSTRUCTION = " This field is a Boolean statement about the input. Evaluate its condition using the supplied evidence: return true when the condition is affirmed, false when the condition is explicitly negated, and null only when evidence does not determine whether it holds. The literal words true and false do not need to be printed."
def normalize_number(value: Any, spec: dict[str, Any]) -> Any:
decimals = 0 if spec.get("integer") else spec.get("decimals")
if value is None or spec["type"] != "number":
return value
if isinstance(value, bool):
raise TypeError("A boolean is not a numeric answer")
if decimals is None:
if isinstance(value, Decimal):
if not value.is_finite():
raise ValueError("Nonfinite number")
value = int(value) if value == value.to_integral_value() else float(value)
if isinstance(value, float) and (not math.isfinite(value)):
raise ValueError("Nonfinite number")
return value
number = value if isinstance(value, Decimal) else Decimal(str(value))
if not number.is_finite():
raise ValueError("Nonfinite number")
try:
with localcontext() as context:
context.prec = max(context.prec, number.adjusted() + decimals + 2)
number = number.quantize(
Decimal(1).scaleb(-decimals), rounding=ROUND_HALF_UP
)
except DecimalException as error:
raise ValueError(
"Cannot represent numeric answer at the requested precision"
) from error
return int(number) if decimals == 0 else float(number)
def names(record: dict[str, Any]) -> list[str]:
return [
n
for (n, s) in record["fields"].items()
if s["type"] in ("text", "number", "boolean", "enum", "object")
or image_rows.is_inventory(s)
]
def schema(spec: dict[str, Any]) -> dict[str, Any]:
if image_rows.is_inventory(spec):
return image_rows.inventory_schema(spec)
if spec["type"] == "object":
return {
"type": ["object", "null"] if spec.get("nullable", True) else "object",
"properties": {
name: schema(child) for (name, child) in spec["properties"].items()
},
"required": list(spec["properties"]),
"additionalProperties": False,
}
if spec["type"] == "boolean":
return {
"type": ["boolean", "null"] if spec.get("nullable", True) else "boolean"
}
if spec["type"] == "enum":
values = list(spec["enum"])
if spec.get("nullable", True) and None not in values:
values.append(None)
return {"enum": values}
kind = (
"string"
if spec["type"] == "text"
else "integer"
if spec.get("integer")
else "number"
)
result = {"type": [kind, "null"] if spec.get("nullable", True) else kind}
if kind == "string":
for key in ["minLength", "maxLength", "pattern", "enum"]:
if key in spec:
result[key] = spec[key]
elif kind in ("number", "integer"):
for key in [
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"enum",
]:
if key in spec:
result[key] = spec[key]
return result
def complete_spec(record: dict[str, Any], name: str) -> dict[str, Any]:
spec = dict(record["fields"][name])
annotation = (
record.get("_meta", {})
.get("extraction_contract", {})
.get("fields", {})
.get(name, {})
)
parent = annotation.get("parent")
if parent:
parent_spec = record["fields"].get(parent)
if not parent_spec or parent_spec["type"] != "list":
raise ValueError("Missing parent list definition: " + name)
spec["instructions"] = (
"Parent list "
+ parent
+ ": "
+ parent_spec.get("instructions", "")
+ "\nRequested element: "
+ spec.get("instructions", "")
)
return spec
def instruction(
record: dict[str, Any], name: str, *, compact_lists: bool = True
) -> str:
image_instruction = image_rows.instruction(record, name, schema)
if image_instruction is not None:
return image_instruction
spec = complete_spec(record, name)
annotation = (
record.get("_meta", {})
.get("extraction_contract", {})
.get("fields", {})
.get(name, {})
)
if (
spec["type"] == "boolean"
and (not annotation.get("parent"))
and (not spec.get("_physical_row_scope"))
and (name not in record.get("_source_row_gates", ()))
):
spec["instructions"] = spec.get("instructions", "") + BOOLEAN_INSTRUCTION
numeric_instructions = ""
if spec["type"] == "number":
if spec.get("unit"):
numeric_instructions += " Return the value in " + str(spec["unit"]) + "."
intro = (
(KNOWLEDGE_INSTRUCTION if spec.get("knowledge") else EXTRACTION_INSTRUCTION)
+ " Return exactly one JSON scalar matching the field schema: quote and escape strings, write numbers without digit-group separators, and use null only when the value is unavailable and null is allowed. Zero is a present number. Preserve repeated source words and list entries. End immediately after the value."
)
parent = annotation.get("parent")
source_bound = spec.get("_physical_row_scope") or (
parent
and name
in record.get("_meta", {})
.get("extraction_contract", {})
.get("fields", {})
.get(parent, {})
.get("source_fields", [])
)
if parent and compact_lists and (spec["type"] != "object") and (not source_bound):
return (
intro
+ "\nSchema: "
+ json.dumps(schema(spec), ensure_ascii=False, separators=(",", ":"))
+ "\nInstructions: "
+ record["fields"][parent].get("instructions", "")
+ numeric_instructions
+ f"\nList: {parent}\nRequested element: Item {annotation['index']} of {parent}, "
+ "following requested order and duplicate policy. Return null if this item does not exist.\nField: "
+ name
)
if spec["type"] == "object":
row_instruction = (
"Check whether this exact physical source row satisfies the requested row scope and exclusions. Return null if this physical row does not match the requested scope, even though it exists. If it qualifies, return one JSON object matching the schema, using only this row's cells. "
if source_bound
else "Extract one complete requested row from the supplied document. Return one JSON object matching the schema, or null only if that row does not exist. Keep all properties on the same physical row. "
)
return (
row_instruction
+ "Use null for a missing cell in an existing row. Preserve distinct rows with identical values. Follow the requested row scope and exclusions. End immediately after the object or null."
+ "\nField: "
+ name
+ "\nSchema: "
+ json.dumps(schema(spec), ensure_ascii=False, separators=(",", ":"))
+ "\nInstructions: "
+ spec.get("instructions", "")
+ "\nProperty instructions: "
+ json.dumps(spec["properties"], ensure_ascii=False)
)
return (
intro
+ "\nField: "
+ record.get("_source_row_names", {}).get(name, name)
+ "\nSchema: "
+ json.dumps(schema(spec), ensure_ascii=False, separators=(",", ":"))
+ "\nInstructions: "
+ spec.get("instructions", "")
+ numeric_instructions
)
def typed_record(record: dict[str, Any]) -> dict[str, Any] | None:
active = set(names(record))
annotations = (
record.get("_meta", {}).get("extraction_contract", {}).get("fields", {})
)
omitted = set(active)
for name, spec in record["fields"].items():
annotation = annotations.get(name, {})
queries = annotation.get("query_fields", annotation.get("source_fields", []))
if spec["type"] == "list" and queries and all((n in active for n in queries)):
omitted.add(name)
fields = {
n: {**s, "type": "number"} if s["type"] == "compute" else s
for (n, s) in record["fields"].items()
if n not in omitted
}
if not fields:
return None
result = {**record, "fields": fields}
if "answers" in record:
result["answers"] = {n: record["answers"][n] for n in fields}
return result
|