Image-Text-to-Text
MLX
Safetensors
qwen3_5
clairic
cloudflare
systemone
structured-output
information-extraction
multimodal
custom-code
conversational
4-bit precision
Instructions to use mlx-community/clairic-flash-4bit with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use mlx-community/clairic-flash-4bit with MLX:
# Make sure mlx-vlm is installed # pip install --upgrade mlx-vlm from mlx_vlm import load, generate from mlx_vlm.prompt_utils import apply_chat_template from mlx_vlm.utils import load_config # Load the model model, processor = load("mlx-community/clairic-flash-4bit") config = load_config("mlx-community/clairic-flash-4bit") # Prepare input image = ["http://images.cocodataset.org/val2017/000000039769.jpg"] prompt = "Describe this image." # Apply chat template formatted_prompt = apply_chat_template( processor, config, prompt, num_images=1 ) # Generate output output = generate(model, processor, formatted_prompt, image) print(output) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Pi
How to use mlx-community/clairic-flash-4bit with Pi:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "mlx-community/clairic-flash-4bit"
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "mlx-lm": { "baseUrl": "http://localhost:8080/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "mlx-community/clairic-flash-4bit" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Hermes Agent
How to use mlx-community/clairic-flash-4bit with Hermes Agent:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "mlx-community/clairic-flash-4bit"
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:8080/v1 hermes config set model.default mlx-community/clairic-flash-4bit
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use mlx-community/clairic-flash-4bit with OpenClaw:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "mlx-community/clairic-flash-4bit"
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:8080/v1 \ --custom-model-id "mlx-community/clairic-flash-4bit" \ --custom-provider-id mlx-lm \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Download clairic_runtime/table_rows.py from mlx-community/clairic-flash-4bit: direct link, hf CLI and curl.
- Browser
- Download file 20 kB
-
https://huggingface.co/mlx-community/clairic-flash-4bit/resolve/main/clairic_runtime/table_rows.py
- Command line
-
hf download hf://mlx-community/clairic-flash-4bit/clairic_runtime/table_rows.py
-
curl -L -o table_rows.py https://huggingface.co/mlx-community/clairic-flash-4bit/resolve/main/clairic_runtime/table_rows.py
20 kB
| from __future__ import annotations | |
| import csv | |
| import json | |
| import math | |
| import re | |
| from collections.abc import Mapping, Sequence | |
| from typing import Any | |
| from jsonschema import Draft202012Validator, ValidationError | |
| from . import ar, html_rows, printed_numbers | |
| LOCAL_SCOPE_INPUT = ( | |
| "The row to classify is provided in the requested field instructions." | |
| ) | |
| def _column(value: str) -> str: | |
| return re.sub("[\\W_]+", "", value.casefold()) | |
| def _header_keys(cells: Sequence[str], names: Mapping[str, str]) -> list[str]: | |
| keys = [_column(cell) for cell in cells] | |
| return [ | |
| "quantity" | |
| if key == "qty" and "qty" not in names and ("quantity" in names) | |
| else key | |
| for key in keys | |
| ] | |
| def join_wrapped_descriptions(instructions: str) -> bool: | |
| positive = False | |
| for clause in re.split("[.;\\n]", instructions): | |
| wrapped = re.search( | |
| "\\b(?:wrapped|multiline|multi-line|continuation)\\b", clause, re.IGNORECASE | |
| ) | |
| joining = re.search("\\b(?:join|combine|merge)\\b", clause, re.IGNORECASE) | |
| negative = re.search( | |
| "\\b(?:not|no|never|without|separate\\w*|independent\\w*)\\b|\\b\\w+n['’]t\\b", | |
| clause, | |
| re.IGNORECASE, | |
| ) | |
| if negative and (wrapped or joining): | |
| return False | |
| positive |= bool( | |
| re.search( | |
| "\\b(?:join|combine)\\b[^.;\\n]*\\b(?:wrapped|multiline|multi-line|continuation)\\b[^.;\\n]*\\b(?:descriptions?|lines?|text)\\b", | |
| clause, | |
| re.IGNORECASE, | |
| ) | |
| ) | |
| return positive | |
| def _wrapped_rows( | |
| rows: list[dict[str, Any]], properties: dict[str, dict[str, Any]] | |
| ) -> list[dict[str, Any]] | None: | |
| texts = [name for (name, spec) in properties.items() if spec["type"] == "text"] | |
| numbers = [name for (name, spec) in properties.items() if spec["type"] == "number"] | |
| if len(texts) != 1 or not numbers: | |
| return rows | |
| text = texts[0] | |
| joined: list[dict[str, Any]] = [] | |
| for row in rows: | |
| previous = joined[-1] if joined else None | |
| if ( | |
| previous | |
| and previous["values"][text] | |
| and row["values"][text] | |
| and (previous["spans"][text] is not None) | |
| and (row["spans"][text] is not None) | |
| and all((previous["values"][key] is None for key in numbers)) | |
| and any((row["values"][key] is not None for key in numbers)) | |
| and ( | |
| row["line"].find(row["values"][text]) | |
| >= previous["line"].find(previous["values"][text]) + 2 | |
| ) | |
| ): | |
| value = previous["values"][text] + " " + row["values"][text] | |
| if not Draft202012Validator(ar.schema(properties[text])).is_valid(value): | |
| return None | |
| joined[-1] = { | |
| "line": previous["line"] + "\n" + row["line"], | |
| "values": {**row["values"], text: value}, | |
| "spans": {**row["spans"], text: None}, | |
| } | |
| else: | |
| joined.append(row) | |
| return joined | |
| def _source_row( | |
| cells: Sequence[str], | |
| keys: Sequence[str], | |
| line: str, | |
| offset: int, | |
| properties: dict[str, dict[str, Any]], | |
| names: Mapping[str, str], | |
| ) -> dict[str, Any] | None: | |
| value: str | int | float | None | |
| (values, spans) = ({}, {}) | |
| for key, cell in zip(keys, cells, strict=True): | |
| name = names[key] | |
| spec = properties[name] | |
| if not cell: | |
| value = None | |
| elif spec["type"] == "number": | |
| try: | |
| value = printed_numbers.normalize(cell, spec) | |
| except (ValueError, TypeError, OverflowError, ValidationError): | |
| return None | |
| else: | |
| value = cell | |
| if not Draft202012Validator(ar.schema(spec)).is_valid(value): | |
| return None | |
| values[name] = value | |
| start = line.find(cell) if cell and line.count(cell) == 1 else -1 | |
| spans[name] = ( | |
| [offset + start, offset + start + len(cell)] if start >= 0 else None | |
| ) | |
| for name, spec in properties.items(): | |
| if name not in values: | |
| if not Draft202012Validator(ar.schema(spec)).is_valid(None): | |
| return None | |
| (values[name], spans[name]) = (None, None) | |
| return {"line": line.rstrip("\r\n"), "values": values, "spans": spans} | |
| def _html_candidates( | |
| source: str, properties: dict[str, dict[str, Any]], names: Mapping[str, str] | |
| ) -> list[dict[str, Any]] | None: | |
| tables = html_rows.tables(source) | |
| if tables is None or len(tables) != 1 or len(tables[0]) < 2: | |
| return None | |
| (header, *body) = tables[0] | |
| keys = [_column(cell) for cell in header["cells"]] | |
| if ( | |
| len(keys) < 2 | |
| or len(set(keys)) != len(keys) | |
| or any((key not in names for key in keys)) | |
| ): | |
| return None | |
| rows = [] | |
| for row in body: | |
| if len(row["cells"]) != len(keys) or not any(row["cells"]): | |
| return None | |
| parsed = _source_row( | |
| row["cells"], keys, row["line"], row["offset"], properties, names | |
| ) | |
| if parsed is None: | |
| return None | |
| for key, span in zip(keys, row["spans"], strict=True): | |
| parsed["spans"][names[key]] = span | |
| rows.append(parsed) | |
| return rows | |
| def candidates( | |
| source: str, properties: dict[str, dict[str, Any]], *, wrapped: bool = False | |
| ) -> list[dict[str, Any]] | None: | |
| if any( | |
| ( | |
| spec["type"] not in ("text", "number") or spec.get("knowledge") | |
| for spec in properties.values() | |
| ) | |
| ): | |
| return None | |
| names = {_column(name): name for name in properties} | |
| if len(names) != len(properties): | |
| return None | |
| if re.search("<table\\b", source, re.IGNORECASE): | |
| return _html_candidates(source, properties, names) | |
| lines = source.splitlines(keepends=True) | |
| (offsets, offset) = ([], 0) | |
| for line in lines: | |
| offsets.append(offset) | |
| offset += len(line) | |
| tables = [] | |
| for delimiter in ("|", "\t", ",", ";"): | |
| for index, line in enumerate(lines): | |
| if delimiter not in line: | |
| continue | |
| try: | |
| header = next(csv.reader([line], delimiter=delimiter, strict=True)) | |
| except csv.Error: | |
| continue | |
| header = [cell.strip() for cell in header] | |
| leading = delimiter == "|" and len(header) > 2 and (not header[0]) | |
| trailing = delimiter == "|" and len(header) > 2 and (not header[-1]) | |
| if trailing: | |
| header = header[:-1] | |
| if leading: | |
| header = header[1:] | |
| keys = _header_keys(header, names) | |
| if ( | |
| len(keys) < 2 | |
| or len(set(keys)) != len(keys) | |
| or any((key not in names for key in keys)) | |
| ): | |
| continue | |
| rows: list[dict[str, Any]] = [] | |
| for row_index in range(index + 1, len(lines)): | |
| text = lines[row_index] | |
| if delimiter not in text: | |
| break | |
| try: | |
| cells = next(csv.reader([text], delimiter=delimiter, strict=True)) | |
| except csv.Error: | |
| return None | |
| cells = [cell.strip() for cell in cells] | |
| if trailing and cells and (not cells[-1]): | |
| cells = cells[:-1] | |
| if leading and cells and (not cells[0]): | |
| cells = cells[1:] | |
| if len(cells) != len(keys): | |
| return None | |
| if not rows and all( | |
| (re.fullmatch(":?-{3,}:?", cell) for cell in cells) | |
| ): | |
| continue | |
| if not any(cells): | |
| return None | |
| row = _source_row( | |
| cells, keys, text, offsets[row_index], properties, names | |
| ) | |
| if row is None: | |
| return None | |
| rows.append(row) | |
| tables.append(_wrapped_rows(rows, properties) if wrapped else rows) | |
| return tables[0] if len(tables) == 1 else None | |
| def _scope_instruction(instructions: str) -> str | None: | |
| requested = re.split( | |
| "[.\\n]|\\bExclude\\b", instructions, maxsplit=1, flags=re.IGNORECASE | |
| )[0] | |
| roles = [ | |
| bool(re.search(pattern, requested, re.IGNORECASE)) | |
| for pattern in ( | |
| "\\bfees?\\b", | |
| "\\btax(?:es)?\\b", | |
| "\\b(?:charges?|goods|products?|services?)\\b", | |
| ) | |
| ] | |
| if sum(roles) != 1: | |
| return None | |
| priority = "Evaluate exclusions first for this exact row; an exclusion overrides a general category match. " | |
| if roles[0]: | |
| return ( | |
| priority | |
| + "Include only a separately printed fee or surcharge. A billed product or service charge, tax, total or payment is not a fee merely because it has a monetary amount. The row label must explicitly establish that it is a fee or surcharge. " | |
| ) | |
| if roles[1]: | |
| return ( | |
| priority | |
| + "Include only an explicitly identified tax, such as sales tax, VAT or GST. A product, service charge, fee, total or payment is not a tax merely because it has an amount. " | |
| ) | |
| if roles[2]: | |
| return ( | |
| priority | |
| + "Include only billed goods or service charges. A separately identified tax, fee, surcharge, payment, subtotal or total is excluded, even though it is a monetary charge. " | |
| ) | |
| return None | |
| def scoped_pairs(source: str, spec: dict[str, Any]) -> list[dict[str, Any]] | None: | |
| instructions = spec.get("instructions", "") | |
| scope_instruction = _scope_instruction(instructions) | |
| properties = spec["items"]["properties"] | |
| if ( | |
| len(properties) != 2 | |
| or scope_instruction is None | |
| or (not re.match("\\s*Only\\b[^.\\n]*\\brows\\b", instructions, re.IGNORECASE)) | |
| or re.search( | |
| "\\b(?:summar\\w*|calculat\\w*|combin\\w*|group\\w*|aggregat\\w*|deduplicat\\w*)\\b|\\buse\\b[^.\\n]*\\bas\\b", | |
| instructions, | |
| re.IGNORECASE, | |
| ) | |
| ): | |
| return None | |
| texts = [ | |
| name for (name, child) in properties.items() if child.get("type") == "text" | |
| ] | |
| numbers = [ | |
| name for (name, child) in properties.items() if child.get("type") == "number" | |
| ] | |
| if ( | |
| len(texts) != 1 | |
| or len(numbers) != 1 | |
| or any((child.get("knowledge") for child in properties.values())) | |
| ): | |
| return None | |
| if not re.search( | |
| "\\b(?:exact|verbatim)\\b[^.\\n]*\\b(?:printed|row)\\b[^.\\n]*\\blabel\\b", | |
| properties[texts[0]].get("instructions", ""), | |
| re.IGNORECASE, | |
| ): | |
| return None | |
| names = {_column(name): name for name in properties} | |
| if len(names) != len(properties): | |
| return None | |
| keys = [_column(texts[0]), _column(numbers[0])] | |
| tables = [] | |
| for delimiter in ("|", "\t", ";"): | |
| (rows, offset) = ([], 0) | |
| for line in source.splitlines(keepends=True): | |
| if delimiter in line: | |
| try: | |
| cells = [ | |
| cell.strip() | |
| for cell in next( | |
| csv.reader([line], delimiter=delimiter, strict=True) | |
| ) | |
| ] | |
| except csv.Error: | |
| return None | |
| if len(cells) != 2 or not all(cells): | |
| return None | |
| row = _source_row(cells, keys, line, offset, properties, names) | |
| if row is None: | |
| return None | |
| row["eligibility_only"] = True | |
| row["scope_instruction"] = scope_instruction | |
| rows.append(row) | |
| offset += len(line) | |
| if len(rows) >= 2: | |
| tables.append(rows) | |
| return tables[0] if len(tables) == 1 else None | |
| def prepare( | |
| source: str, | |
| fields: dict[str, dict[str, Any]], | |
| *, | |
| has_media: bool = False, | |
| allow_scoped_pairs: bool = False, | |
| ) -> dict[str, list[dict[str, Any]]]: | |
| if has_media: | |
| return {} | |
| result = {} | |
| for name, spec in fields.items(): | |
| item = spec.get("items") | |
| if ( | |
| spec.get("type") != "list" | |
| or not isinstance(item, dict) | |
| or item.get("type") != "object" | |
| ): | |
| continue | |
| explicit_rows = re.search( | |
| "\\bone\\s+(?:object|entry|record)\\s+(?:per|for\\s+each)\\b[^.\\n]*\\brow\\b", | |
| spec.get("instructions", ""), | |
| re.IGNORECASE, | |
| ) | |
| wrapped = join_wrapped_descriptions(spec.get("instructions", "")) | |
| rows = ( | |
| candidates(source, item["properties"], wrapped=wrapped) | |
| if explicit_rows | |
| else scoped_pairs(source, spec) | |
| if allow_scoped_pairs | |
| else None | |
| ) | |
| if rows and len(rows) <= spec.get("max_items", 32): | |
| missing_columns = [ | |
| key | |
| for (key, child) in item["properties"].items() | |
| if child.get("type") == "number" | |
| and all((row["values"][key] is None for row in rows)) | |
| ] | |
| if missing_columns: | |
| for row in rows: | |
| row["eligibility_only"] = True | |
| result[name] = rows | |
| return result | |
| def membership_instructions(instructions: str) -> str: | |
| if re.search( | |
| "[\\r\\n`\\\"“”]|(?<!\\w)'[^'\\r\\n]+'(?!\\w)|‘[^’]+’|\\b(?:literal|verbatim|quoted|quote|quotation|code|snippet|block|note|label|phrase)\\b", | |
| instructions, | |
| re.IGNORECASE, | |
| ): | |
| return instructions | |
| target = "(?:(?:wrapped|multiline|multi-line|continuation)\\s+)?(?:descriptions?(?:\\s+lines?)?|lines?|(?:distinct|separate|duplicate|repeated|physical)\\s+rows?)" | |
| negative_join = re.compile( | |
| "\\s*(?:do\\s+not|don't|never)\\s+(?:join|combine|merge)\\s+" | |
| + target | |
| + "(?:\\s+or\\s+(?:join|combine|merge)\\s+" | |
| + target | |
| + ")*\\s*[.;]?\\s*", | |
| re.IGNORECASE, | |
| ) | |
| clauses = re.split("(?<=[.;])(?=\\s|$)|(?<=\\n)", instructions) | |
| if not any((negative_join.fullmatch(clause) for clause in clauses)): | |
| return instructions | |
| return "".join( | |
| (clause for clause in clauses if not negative_join.fullmatch(clause)) | |
| ).strip() | |
| def row_spec( | |
| spec: dict[str, Any], row: dict[str, Any], *, eligibility: bool = False | |
| ) -> dict[str, Any]: | |
| missing = [name for (name, value) in row["values"].items() if value is None] | |
| missing_instruction = ( | |
| "Missing cells or entire columns do not exclude an otherwise matching row. These source cells are missing and must remain null: " | |
| + ", ".join(missing) | |
| + ". " | |
| if missing | |
| else "" | |
| ) | |
| scope = membership_instructions(spec.get("instructions", "")) | |
| if eligibility: | |
| return { | |
| "type": "boolean", | |
| "nullable": False, | |
| "instructions": "Classify exactly this physical source row for inclusion in the requested list. Return true if and only if this row satisfies the requested list instructions. Return false if the row is excluded, unrelated, or does not belong to the requested list, even though it exists. This is an eligibility decision, not a request to copy its cells. " | |
| + missing_instruction | |
| + row.get("scope_instruction", "") | |
| + "Requested list instructions: " | |
| + scope | |
| + "\nExact physical source row: " | |
| + row["line"], | |
| } | |
| properties = {} | |
| for name, child in spec["items"]["properties"].items(): | |
| value = row["values"][name] | |
| properties[name] = {**child, "nullable": value is None, "enum": [value]} | |
| return { | |
| **spec["items"], | |
| "properties": properties, | |
| "nullable": True, | |
| "instructions": scope | |
| + "\nRead only this exact physical source row: " | |
| + json.dumps(row["line"], ensure_ascii=False) | |
| + "\nReturn null if this row does not satisfy the requested scope. Otherwise copy its cells together. " | |
| + missing_instruction | |
| + "Do not substitute a different row. Missing cells are null. This query has no list ordinal to count.", | |
| } | |
| def local_scope_context( | |
| rows: Sequence[dict[str, Any]], queries: Sequence[str], *, offset: int = 0 | |
| ) -> tuple[dict[str, str], dict[str, str]]: | |
| if not rows or not all((row.get("scope_instruction") for row in rows)): | |
| return ({}, {}) | |
| pairs = list(zip(queries, rows, strict=True)) | |
| inputs = dict.fromkeys(queries, LOCAL_SCOPE_INPUT) | |
| names = { | |
| query: f"source_scope_{offset + index}" | |
| for (index, (query, _)) in enumerate(pairs, 1) | |
| } | |
| return (inputs, names) | |
| def assemble( | |
| predictions: dict[str, dict[str, Any]], | |
| rows: Sequence[dict[str, Any]], | |
| queries: Sequence[str], | |
| *, | |
| eligibility: bool = False, | |
| ) -> dict[str, Any]: | |
| checks = [predictions[name] for name in queries] | |
| selected = [ | |
| (row, answer) | |
| for (row, answer) in zip(rows, checks, strict=True) | |
| if ( | |
| answer.get("value") is True | |
| if eligibility | |
| else answer.get("value") is not None | |
| ) | |
| ] | |
| valid = all( | |
| ( | |
| answer.get("valid", False) and answer.get("complete", False) | |
| for answer in checks | |
| ) | |
| ) | |
| scored = True | |
| if eligibility: | |
| valid &= all((type(answer.get("value")) is bool for answer in checks)) | |
| scored = all( | |
| ( | |
| isinstance((score := answer.get("p_excluded")), (int, float)) | |
| and (not isinstance(score, bool)) | |
| and math.isfinite(score) | |
| and (0 <= score <= 1) | |
| for answer in checks | |
| ) | |
| ) | |
| valid &= scored | |
| p_null = ( | |
| math.exp(sum((math.log(answer["p_excluded"]) for answer in checks))) | |
| if scored and all((answer["p_excluded"] > 0 for answer in checks)) | |
| else 0.0 | |
| ) | |
| p_null_method = ( | |
| "product_source_row_exclusion_probabilities" | |
| if scored | |
| else "unavailable_source_row_exclusion_probability" | |
| ) | |
| else: | |
| p_null = min((answer.get("p_null", 0.0) for answer in checks)) | |
| p_null_method = "minimum_source_row_null_probability" | |
| log_probability = sum( | |
| (answer.get("log_probability", -math.inf) for answer in checks) | |
| ) | |
| if not math.isfinite(log_probability): | |
| log_probability = None | |
| result = { | |
| "value": [ | |
| dict(row["values"]) if eligibility else answer["value"] | |
| for (row, answer) in selected | |
| ], | |
| "valid": valid, | |
| "complete": valid, | |
| "confidence": math.exp(min(0, log_probability)) | |
| if valid and log_probability is not None | |
| else 0.0, | |
| "confidence_method": "ar_source_row_eligibility_probability" | |
| if eligibility | |
| else "ar_source_row_sequence_probability", | |
| "p_null": p_null, | |
| "p_null_method": p_null_method, | |
| "confidences": [answer.get("confidence", 0.0) for (row, answer) in selected], | |
| "p_nulls": [ | |
| answer.get("p_excluded" if eligibility else "p_null", 0.0) | |
| for (row, answer) in selected | |
| ], | |
| "spans": [None] * len(selected), | |
| "property_spans": [row["spans"] for (row, answer) in selected], | |
| } | |
| if log_probability is not None: | |
| result["log_probability"] = log_probability | |
| if eligibility and (not scored): | |
| result.pop("p_nulls") | |
| if not valid: | |
| result["failure_reason"] = ( | |
| "source_row_eligibility_unscored" | |
| if eligibility and (not scored) | |
| else "source_row_read_incomplete" | |
| ) | |
| return result | |