# Schematron (https://inference.net/docs/api/models/schematron)

Schematron is a family of long-context models trained to extract clean, typed
JSON from messy HTML. They're built for web scraping, product data ingestion,
and converting arbitrary pages into structured data: you pass a schema, and the
model returns conforming JSON.

Schematron V2 Small delivers the highest extraction quality, approaching
frontier-model accuracy on complex schemas. Schematron V2 Turbo is optimized for
throughput and cost, processing pages significantly faster while still exceeding
the quality of the previous-generation Schematron 3B. Both models handle long
HTML inputs with strict schema adherence.

To learn how Schematron was trained and what it can do, see the
[announcement blog post](/blog/schematron/?utm_source=docs).

<Callout tone="success">

For best results, pre-clean HTML with `lxml` to remove scripts, styles, and
boilerplate before sending it to the model. See
[Preprocess HTML](#preprocess-html).

Alternatives like [Readability](https://github.com/mozilla/readability) or regex
can work; `lxml` is recommended for this model because it matches how the
training data was preprocessed. When preprocessing, err on the side of removing
less content; the model can still extract the information you need.

</Callout>

## Quickstart

<CardGroup>
  <Card title="Schematron V2 Small" href="/models/inference-net-schematron-v2-small/">
    Highest extraction quality for complex schemas and long pages.
  </Card>
  <Card title="Schematron V2 Turbo" href="/models/inference-net-schematron-v2-turbo/">
    Optimized for maximum throughput and lowest cost at scale.
  </Card>
  <Card
    title="Notebook example"
    href="https://github.com/context-labs/inference-samples/blob/main/examples/schematron-scrape-companies/schematron-scrape-companies.ipynb"
  >
    End-to-end company scraping walkthrough using Schematron.
  </Card>
</CardGroup>

<Callout tone="info">

You need an Inference.net account, an API key, and the OpenAI SDK configured
with `base_url="https://api.inference.net/v1"`. See the
[quickstart](/docs/api/quickstart/) for setup details.

</Callout>

<Callout tone="info" title="TypeScript users">

The examples below use OpenAI SDK v6 and Zod v3. Install the compatible Zod
version with:

```bash
npm install zod@^3
```

</Callout>

## Extract from HTML into a typed model

Define your schema with a typed model (for example Pydantic or Zod). Pass the
model's JSON Schema and the raw HTML to the model, enable JSON mode, and
validate the response.

<Callout tone="info">

This model does not use user or system prompts. It uses only the schema to
extract the data.

</Callout>

<CodeTabs>

```typescript
import OpenAI from "openai";
import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";

const openai = new OpenAI({
  baseURL: "https://api.inference.net/v1",
  apiKey: process.env.INFERENCE_API_KEY,
});

// 1) Define your schema (nested data and lists are supported)
const Product = z.object({
  name: z.string(),
  price: z.number().describe("Primary price of the product."),
  specs: z.record(z.string()).describe("Specs of the product."),
  tags: z.array(z.string()).describe("Tags assigned of the product."),
});

// 2) Messy HTML (could be the full page; trim to the relevant region when possible)
const html = `
<div id="item">
  <h2 class="title">MacBook Pro M3</h2>
  <p>Price: <b>$2,499.99</b> USD</p>
  <ul info>
    <li>RAM: 16GB</li>
    <li>Storage: 512GB SSD</li>
  </ul>
  <span class="tag">laptop</span>
  <span class="tag">professional</span>
  <span class="tag">macbook</span>
  <span class="tag">apple</span>
</div>
`;

// 3) Chat Completions extraction (typed validation)
const resp = await openai.chat.completions.parse({
  model: "inference-net/schematron-v2-small",
  messages: [{ role: "user", content: html }],
  response_format: zodResponseFormat(Product, "product"),
});

console.log(resp.choices[0].message.content);
```

```python
import os
from pydantic import BaseModel, Field
from openai import OpenAI

# 1) Define your schema (nested data and lists are supported)

class Product(BaseModel):
    name: str
    price: float = Field(
        ...,
        description="Primary price of the product.",
    )
    specs: dict[str, str] = Field(
        default_factory=dict,
        description="Specs of the product.",
    )
    tags: list[str] = Field(
        default_factory=list,
        description="Tags assigned of the product.",
    )

# 2) Messy HTML (could be the full page; trim to the relevant region when possible)

html = """
<div id="item">
  <h2 class="title">MacBook Pro M3</h2>
  <p>Price: <b>$2,499.99</b> USD</p>
  <ul info>
    <li>RAM: 16GB</li>
    <li>Storage: 512GB SSD</li>
  </ul>
  <span class="tag">laptop</span>
  <span class="tag">professional</span>
  <span class="tag">macbook</span>
  <span class="tag">apple</span>
</div>
"""

# 3) Client setup

client = OpenAI(
    base_url="https://api.inference.net/v1",
    api_key=os.environ.get("INFERENCE_API_KEY"),
)

resp = client.beta.chat.completions.parse(
    model="inference-net/schematron-v2-small",
    messages=[
        {"role": "user", "content": html},
    ],
    response_format=Product,
)

print(resp.choices[0].message.parsed.model_dump_json(indent=2))
```

```bash
curl https://api.inference.net/v1/chat/completions \
  -H "Authorization: Bearer $INFERENCE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "inference-net/schematron-v2-small",
    "messages": [
      { "role": "user", "content": "<div id=\"item\">\n    <h2 class=\"title\">MacBook Pro M3</h2>\n    <p>Price: <b>$2,499.99</b> USD</p>\n    <ul info>\n    <li>RAM: 16GB</li>\n    <li>Storage: 512GB SSD</li>\n    </ul>\n    <span class=\"tag\">laptop</span>\n    <span class=\"tag\">professional</span>\n    <span class=\"tag\">macbook</span>\n    <span class=\"tag\">apple</span>\n</div>" }
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "product",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "name": { "type": "string" },
            "price": { "type": "number", "description": "Primary price of the product." },
            "specs": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Specs of the product." },
            "tags": { "type": "array", "items": { "type": "string" }, "description": "Tags assigned of the product." }
          },
          "required": ["name", "price", "specs", "tags"],
          "additionalProperties": false
        }
      }
    }
  }'
```

</CodeTabs>

## Output

For the HTML above, Schematron produces strictly valid JSON that conforms to
your schema. A representative output:

```json
{
  "name": "MacBook Pro M3",
  "price": 2499.99,
  "specs": {
    "RAM": "16GB",
    "Storage": "512GB SSD"
  },
  "tags": ["laptop", "professional", "macbook", "apple"]
}
```

## Best practices

1. **Keep temperature at zero.** The model is trained to perform best at
   temperature 0.
2. **Provide a clear schema.** Pass a JSON Schema or typed model (for example
   `Product.model_json_schema()`). Include required fields and types, and
   optionally describe them directly in the schema (supported by Pydantic and
   Zod). For example:

<CodeTabs>

```typescript
const Product = z.object({
  name: z.string().describe("Exact product name as shown in the title or primary heading."),
  price: z.number().describe("Primary price of the product."),
  specs: z
    .object({
      ram: z.string().describe("RAM capacity."),
      storage: z.string().describe("Storage capacity and type."),
    })
    .describe("Key attributes describing the product."),
});
```

```python
from pydantic import BaseModel, Field

class Specs(BaseModel):
    ram: str = Field(..., description="RAM capacity.")
    storage: str = Field(..., description="Storage capacity and type.")

class Product(BaseModel):
    name: str = Field(
        ...,
        description=(
            "Exact product name as shown in the title or primary heading."
        ),
    )
    price: float = Field(
        ...,
        description="Primary price of the product.",
    )
    specs: Specs = Field(
        ...,
        description="Key attributes describing the product.",
    )
```

</CodeTabs>

3. **Pre-clean HTML (recommended).** Remove scripts, styles, and boilerplate to
   improve accuracy and reduce tokens. See [Preprocess HTML](#preprocess-html).
   Alternatives (Readability, Trafilatura, BeautifulSoup, regex) are fine;
   `lxml` aligns with training.
4. **Validate on ingest.** Parse with Pydantic (or your validator) and handle
   validation errors explicitly. Schematron should always return valid JSON
   matching your schema, but validating the response is still a good idea.

## Preprocess HTML

Schematron models were trained on HTML pre-cleaned with
`lxml.html.clean.Cleaner` to strip scripts, styles, and inline JavaScript.
Matching your preprocessing to training typically improves extraction quality
and consistency.

```python
import lxml.html as LH
from lxml.html.clean import Cleaner

HTML_CLEANER = Cleaner(
    scripts=True,
    javascript=True,
    style=True,
    inline_style=True,
    safe_attrs_only=False,
)

def strip_noise(html: str) -> str:
    """Remove scripts, styles, and JavaScript from HTML using lxml."""
    if not html or not html.strip():
        return ""
    try:
        doc = LH.fromstring(html)
        cleaned = HTML_CLEANER.clean_html(doc)
        return LH.tostring(cleaned, encoding="unicode")
    except Exception:
        return ""
```

Notes:

- You don't have to use `lxml`. Alternatives like Readability (often more
  aggressive), Trafilatura, BeautifulSoup, or targeted regex can be acceptable.
- Use whichever tool fits your content; `lxml` is recommended for this model
  because it matches how the training data was preprocessed.

## Capabilities

### Key features

- **Schema-first extraction:** drive output with your own JSON Schema or a typed
  model (for example Pydantic) and get strictly formatted JSON back.
- **Long-context HTML:** trained for long documents with up to 128K-token
  context, and robust to noisy markup.
- **Strict JSON mode:** 100% schema adherence.
- **Cost-efficient quality:** matches the quality of frontier models at a
  significantly lower cost.

### Models

| Model ID                            | Best for                                       |
| ----------------------------------- | ---------------------------------------------- |
| `inference-net/schematron-v2-small` | Best quality for complex schemas or long pages |
| `inference-net/schematron-v2-turbo` | Maximum throughput and lowest cost at scale    |

See pricing and limits on the
[Schematron V2 Small](/models/inference-net-schematron-v2-small/) and
[Schematron V2 Turbo](/models/inference-net-schematron-v2-turbo/) model pages.

## Process at scale

For large-scale extraction, use the asynchronous APIs:

<CardGroup>
  <Card title="Batch API" href="/docs/api/async/batch/">
    Submit up to 1,000,000 extraction requests in one JSONL file, track their
    status asynchronously, and get an optional webhook within a 24-hour window.
  </Card>
  <Card title="Group API" href="/docs/api/async/group/">
    Send smaller groups (up to 50 requests) in one JSON payload, follow the
    group as a single job, and get one callback when everything is done.
  </Card>
</CardGroup>

## Limitations

- **Context window:** up to 128K tokens per request. Truncate or chunk very
  large pages.
- **Ambiguous fields:** if a field requires summarization or synthesis, make
  your schema and field descriptions explicit about what you expect. Schematron
  does not take a prompt or directions; all information goes through the
  schema.

## Legacy models

<Callout tone="warning">

The first-generation **Schematron 3B** (`inference-net/schematron-3b`) and
**Schematron 8B** (`inference-net/schematron-8b`) models are retired. Requests
to these identifiers are routed to their V2 successors so existing code keeps
working:

- Calls to `inference-net/schematron-3b` are served by
  `inference-net/schematron-v2-turbo`.
- Calls to `inference-net/schematron-8b` are served by
  `inference-net/schematron-v2-small`.

V2 pricing applies to these requests; see the
[Schematron V2 Turbo](/models/inference-net-schematron-v2-turbo/) and
[Schematron V2 Small](/models/inference-net-schematron-v2-small/) model pages for
current per-token rates. Update your model identifiers explicitly so your code,
dashboards, and receipts all reflect the model you intend to call.

The original open-source weights remain available on Hugging Face for
self-hosting:

- [Schematron-8B on Hugging Face](https://huggingface.co/inference-net/Schematron-8B)
- [Schematron-3B on Hugging Face](https://huggingface.co/inference-net/Schematron-3B)

</Callout>

## Support

For technical support, email
[support@inference.net](mailto:support@inference.net) or
[schedule a call](/meet-with-us/).