Skip to content

Custom Refiners (JavaScript)

A custom refiner is a condition you write in JavaScript. It reads the OCR text of a page or a document and returns a confidence between 0 and 1. It is best for one job: picking the right subclass when several text signals must be weighed together, for example one vendor's invoice layout among look-alike vendors. If one label on the page decides the match, use a Regex Anchor. If a plain-language description decides it, use a Zero-Shot Classifier hint.

At a glance

  • Runs On the server, on the Intuitive AI worker, while the engine classifies a document
  • Language JavaScript (V8, plain ES5 style recommended)
  • Authored in Intuitive AI app, class builder, Add Refiner: or Add Condition:
  • Can reach OCR text and page dimensions only. No network, no metadata writes.
  • Best for Graded subclass votes from several text signals

There are two kinds:

Kind (UI name) Scope
Custom Condition One page at a time. A page refiner or a condition in a page rule.
Custom Document Condition The whole document, once. A condition in a document rule.

Where it runs

graph TD
  A["Page OCR text"] --> B["Your Custom Condition"]
  B --> C["result.SetResult between 0 and 1"]
  C --> D["And with the other refiners on the page"]
  D --> E["Page score for this subclass"]
  E --> F["Best subclass wins"]
  F --> G["Its rules and actions run"]

Where you author it

  1. Open the Intuitive AI app (permission: Use This App) and open a class or subclass.
  2. For a page condition, use Add Refiner: in First, Middle or Last Page Refiners, or Add Condition: in a page rule. Pick Custom Condition.
  3. For a document condition, use Add Condition: in a document rule. Pick Custom Document Condition.
  4. Open the condition's script editor, write the script, and save the class. The editor offers completion for the objects on the Script Reference.

Runtime contract

Item Value
Engine V8 (Microsoft ClearScript) on the Intuitive AI worker. Server side, not a browser.
Runs when A page condition runs for each page the engine tests against the refiner or rule. A document condition runs once per document for its rule. Script conditions run after the other conditions in the same rule.
Timeout 15 minutes for page and document conditions. At the limit the run fails with "Script execution interrupted by host".
Network access None. No fetch, XMLHttpRequest, require, import or file system.
Objects in scope state, services, result, and the host types Enumerable and EnumerableHelpers. See Script Reference.
Output result.SetResult(confidence), a number from 0 to 1
Logging None. There is no console.

Template

Condition_RemittanceAdvice.js
(function () {
    var ocr = services.OcrService.GetPageOcr(state);
    var text = (ocr && ocr.Text) ? String(ocr.Text).replace(/\s+/g, " ") : "";

    if (text.length === 0) {
        return; // No text: no opinion (a page refiner ignores this result)
    }

    var hasTitle = /\bremittance\s+advice\b/i.test(text);
    var hasAccount = /\baccount\s+(?:no|number|#)\.?\s*:?\s*[0-9]{6,}\b/i.test(text);

    var score = 0;
    if (hasTitle) { score += 0.6; }
    if (hasAccount) { score += 0.3; }

    result.SetResult(Math.min(score, 1));
})();

What your result means

You return In a page refiner In a rule
SetResult(1) Strong vote for this class or subclass Condition fully true
SetResult(0.5) Weak vote Exactly at the action threshold
SetResult(0) Vote against Condition false; actions do not run
No SetResult call No opinion: the refiner is ignored Counts as 0

A Custom Document Condition result is multiplied by 0.9, so a document condition that returns 1 counts as 0.9, and 0.5 counts as 0.45. See How Classes, Refiners and Actions Fit for every scoring rule.

Rules

  1. Call result.SetResult(confidence) with a number from 0 to 1.
  2. Wrap the script in (function () { ... })();. A top-level return is a syntax error, and one engine runs many scripts, so top-level names can collide.
  3. Treat state as read-only. A condition gets the live state object.
  4. Call each OCR service once and keep the text in a variable.
  5. Return graded confidence. Do not return 1 for a single weak signal.
  6. Return 0 when the evidence is missing. Return nothing only when the page gives no evidence either way (for example, no readable text).
  7. Throw an Error only for a real fault. An uncaught error ends the run for the document.

Gotchas

Mistakes that pick the wrong subclass

  • Substring matching. text.indexOf("Acme") is case-sensitive, matches inside other words, and matches names in the "Bill To" block. Use word-boundary regexes and several signals. See Pick a Vendor Subclass from Page Text.
  • Every subclass returns 1. If two subclasses both return 1, the engine cannot tell them apart. Grade the result.
  • Silence when the signal is absent. A page refiner that never calls SetResult gives no opinion, so it never votes against its subclass. Call SetResult(0).
  • Null KnownSubclass. A class-level page refiner gets no subclass and no model page. Check state.KnownSubclass for null before you read .Name.
  • Slow OCR. GetDocumentOcr with a high page count is the slowest call. Ask for the pages you need.
  • Line breaks. OCR text breaks phrases across lines. Run text.replace(/\s+/g, " ") before you match phrases.

Examples

Copy this into your assistant

Paste the block below into your AI assistant together with the AI Assistant Primer, then describe what you want to build. It is the same contract as this page and Custom Actions, written for a model.

Intuitive AI scripts: context for AI assistants
# Intuitive AI scripts: context for AI assistants

You write JavaScript for KnowledgeLake Intuitive AI, the server engine that classifies documents and extracts Index field values. A script is one of four kinds:

- Custom Condition: page scope. Returns a confidence for one page. Used as a page refiner (First, Middle or Last Page Refiners) or as a condition in a page rule.
- Custom Document Condition: document scope. Returns a confidence for the whole document. Used in a document rule.
- Custom Action: page scope. Runs when its page rule passes. Writes Index values.
- Custom Document Action: document scope. Runs when its document rule passes. Writes Index values.

First decide if a script is needed. One label on the page decides it: suggest a Regex Anchor (a .NET regex, no script). A plain-language description of a class decides it: suggest a Zero-Shot Classifier hint. A field must be found in free text: suggest an Auto Extraction field hint.

## Runtime contract
- Engine: V8 (ClearScript) on the Intuitive AI worker. Not a browser, not Node.js.
- Timeouts: page condition 15 min, document condition 15 min, page action 5 min, document action 15 min. At the limit: "Script execution interrupted by host".
- One engine runs many scripts. Wrap every script in `(function () { ... })();`. No top-level `return`, `let` or `const`.
- No `fetch`, `XMLHttpRequest`, `require`, `import`, `console`, file bytes or page images.
- In scope: `state`, `services`, `result`, host types `Enumerable` and `EnumerableHelpers`. `GlobalVariables`, `batch` and `builder` belong to Custom Step and do not exist here.
- An uncaught error ends the run for the document.

## Objects
`state` in a page script (Custom Condition, Custom Action):
- `DocumentId`, `PageId`: Guids. Use `.ToString()` for text.
- `BatchProjection`: read-only snapshot of the work item: `Id`, `Name`, `Metadata`, `Documents` (each `Id`, `Index`, `Metadata`, `Pages`). Values written in this run are not in it.
- `TemplateZones`: zones of the model page: `Id`, `KnownPageId`, `RectangleCoordinates`. Zones have no names.
- `KnownPage` (`Id`, `Position`, `Width`, `Height`) and `KnownSubclass` (`Id`, `Name`): null in a class-level refiner. Check for null.
- `UserCache`: `Set(key, value)`, `Get(key)`. Shared by the conditions and actions of one rule on one page.
- `OcrCache`: zone OCR stored by OCR actions, keyed by the action's Property name: `ContainsKey(key)`, `Get(key).Text`.
- A page action gets a copy of `state`. Only `UserCache` changes reach later actions.

`state` in a document script: `OriginalDocumentId`, `PageIds` (in order), `BatchProjection`, `KnownClass` (`Id`, `Name`), `KnownSubclass` (can be null), `Classification`. No `TemplateZones`.

`services` (synchronous; results are cached for the run):
- `services.OcrService.GetPageOcr(state)`: page scope.
- `services.OcrService.GetZoneOcr(state, zone)`: page scope; `zone` is an item of `state.TemplateZones`.
- `services.OcrService.GetRegionOcr(state, rectangleCoordinates)`: page scope.
- `services.OcrService.GetDocumentOcr(state, maxPagesToOcr)`: document scope; default 20, cap 100.
- `services.ImageRetriever.GetBatchPageDimensions(state)`: page scope; `{ Width, Height }` in pixels.
- An OCR result has `Text` (with line breaks), `Confidence` (0 to 1), `Bounds` (`X`, `Y`, `Width`, `Height`), `Children`.

`result`:
- Conditions: `result.SetResult(confidence)`, 0 to 1.
- Actions: `result.SetDocumentMetadata(key, value)` writes Index field `key` of the current document (Index bucket only). `result.SetResult(confidence)` sets the action confidence; default 1.

Host collections are .NET objects, not arrays: `x.Length()`, `x[i]`, `x.Where(fn)` (returns a .NET array: use `Length()` and `[i]`, not JS array methods), `d.ContainsKey(k)`, `d.Get(k)`, `d.Set(k, v)`, `d.GetKeys()`.

## Scoring rules
1. Confidence is 0 to 1; values outside are clamped.
2. And takes the minimum; Or takes the maximum. Several page refiners on one page combine with And.
3. A rule runs its actions only when its combined condition confidence is 0.5 or more.
4. A Custom Document Condition result is multiplied by 0.9. Return 0.56 or more for a match.
5. In a page refiner, no `SetResult` call means "no opinion"; `SetResult(0)` means "not this one". In a rule, no call counts as 0.
6. Two actions write the same field: the higher action confidence wins; a tie goes to the custom action.
7. Actions run in the listed order. An OCR action must come before a Custom Action that reads `state.OcrCache`.
8. A page rule runs on every page. The engine keeps the page with the highest average of condition and action confidence.

## Rules
1. Never `text.indexOf("Name")` plus `SetResult(1)`. Use case-insensitive word-boundary regexes, several signals, a penalty for look-alikes, and graded confidence.
2. Collapse whitespace first: `text.replace(/\s+/g, " ")`.
3. Call each OCR service once; keep the text in a variable.
4. Pass strings to `SetDocumentMetadata`: `value.toFixed(2)`, `"true"`. Booleans become "True" and "False".
5. Index field names are exact and case-sensitive. A wrong key fills no field and raises no error.
6. To debug, throw a temporary `new Error("DEBUG ...")` and read it in the class Test results.
7. Plain ES5 style: `var` and `function`.

## Example: page refiner on one vendor subclass
```javascript
(function () {
    var signals = [
        { pattern: /\bharbor\s+point\s+supply\b/i, weight: 0.45 },
        { pattern: /\bremit\s+(?:payment\s+)?to\b.{0,80}?\bharbor\s+point\s+supply\b/i, weight: 0.25 },
        { pattern: /\bHPS-[0-9]{5}\b/, weight: 0.20 }
    ];
    var lookAlikes = [{ pattern: /\bharbor\s+point\s+services\b/i, penalty: 0.40 }];

    var ocr = services.OcrService.GetPageOcr(state);
    var raw = (ocr && ocr.Text) ? String(ocr.Text) : "";
    if (raw.replace(/\s+/g, "").length < 20) { return; } // no readable text: no opinion
    var text = raw.replace(/\s+/g, " ");

    var score = 0, i;
    for (i = 0; i < signals.length; i++) { if (signals[i].pattern.test(text)) { score += signals[i].weight; } }
    for (i = 0; i < lookAlikes.length; i++) { if (lookAlikes[i].pattern.test(text)) { score -= lookAlikes[i].penalty; } }

    if (score < 0.45) { result.SetResult(0); return; } // vote against
    result.SetResult(Math.min(1, score));
})();
```

## Example: Custom Action after an OCR action whose Property is "Invoice Total"
```javascript
(function () {
    if (!state.OcrCache.ContainsKey("Invoice Total")) { result.SetResult(0); return; }
    var raw = String(state.OcrCache.Get("Invoice Total").Text || "");
    var value = parseFloat(raw.replace(/[^0-9.\-]/g, ""));
    if (isNaN(value)) { result.SetResult(0); return; }
    result.SetDocumentMetadata("Invoice Total", value.toFixed(2));
    result.SetResult(1);
})();
```

## Output
Produce one script: `Condition_<Name>.js` or `Action_<Name>.js`. Start it with a comment block: where it goes (class, subclass, section or rule, page or document scope), what it reads, the exact Index field names it writes, and what it returns in each case. Then tell the user how to test it: open the subclass and use Show OCR Data to see the text; open the class, select Test, upload hard documents, select Start Test, and read Condition Confidence, Action Confidence and Extraction Results in Detailed Test Results. If a class, subclass or Index field name is not known, ask the user. Do not invent one.