Skip to content

Custom Actions (JavaScript)

A custom action is an action you write in JavaScript. It runs when its rule passes, reads OCR text, and writes Index values to the document. It is best for one job: cleaning or deriving a value that the built-in actions cannot produce, for example normalizing an amount that an OCR action read from a zone. If the value only needs to be found, use an OCR action (with its regex refiner) or Auto Extraction instead.

At a glance

  • Runs On the server, on the Intuitive AI worker, after its rule's conditions reach 0.5
  • Language JavaScript (V8, plain ES5 style recommended)
  • Authored in Intuitive AI app, class builder, Add Action: in a rule
  • Can reach OCR text, zone OCR from earlier OCR actions, and the Index bucket of the current document (write only)
  • Best for Normalizing, combining or deriving Index values during capture

There are two kinds:

Kind (UI name) Scope
Custom Action The page where its page rule passed
Custom Document Action The whole document, in a document rule

Where it runs

graph TD
  A["Rule conditions reach 0.5"] --> B["OCR action stores zone text"]
  B --> C["Your Custom Action"]
  C --> D["result.SetDocumentMetadata"]
  D --> E["Engine resolves conflicts by confidence"]
  E --> F["Index fields on the document"]

Your writes are queued. The engine collects the results of every rule, resolves fields that two actions wrote, and then applies them.

Where you author it

  1. Open the Intuitive AI app (permission: Use This App) and open a class or subclass.
  2. In a rule, select Add Action:. Pick Custom Action in a page rule or Custom Document Action in a document rule.
  3. Open the action's script editor, write the script, and save the class.
  4. Put the action after any OCR action whose result it reads.

Runtime contract

Item Value
Engine V8 (Microsoft ClearScript) on the Intuitive AI worker. Server side, not a browser.
Runs when After the rule's conditions reach 0.5 or more. Actions run in the order listed in the rule. A page rule's actions run on each page where the rule passes.
Timeout Page action: 5 minutes. Document action: 15 minutes.
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.SetDocumentMetadata(key, value) to the Index bucket of the current document, and result.SetResult(confidence) (default 1)
Logging None. There is no console.

Template

Action_PaymentStatus.js
(function () {
    var ocr = services.OcrService.GetPageOcr(state);
    var text = (ocr && ocr.Text) ? String(ocr.Text) : "";

    if (/\bPAID\b/.test(text)) {
        result.SetDocumentMetadata("Payment Status", "Paid");
        result.SetResult(1);
    } else {
        result.SetResult(0);
    }
})();

Read the zone text an OCR action found

An OCR action ("Extract from OCR Snippet") stores its zone OCR in state.OcrCache, keyed by the field you picked in Property:. A Custom Action listed after it in the same rule can read it:

Action_TrimInvoiceTotal.js
(function () {
    var key = "Invoice Total";
    if (!state.OcrCache.ContainsKey(key)) {
        result.SetResult(0);
        return;
    }
    var raw = String(state.OcrCache.Get(key).Text || "");
    result.SetDocumentMetadata(key, raw.replace(/\s+/g, " ").trim());
    result.SetResult(1);
})();

The cache belongs to one rule on one page. A Custom Action in a different rule does not see it.

How the engine uses your result

  • Same field, two actions. The value from the action with the higher confidence wins. On a tie, the custom action wins. A Custom Action that calls SetResult(1) replaces the value an OCR action wrote to the same field.
  • Page rules run on every page. The engine keeps the results from the page with the highest average of condition and action confidence, and drops the others.
  • Only the Index bucket. SetDocumentMetadata writes only the Index bucket. To write work item metadata, use a later Custom Step in the workflow.
  • No reads of this run's writes. state.BatchProjection is a snapshot taken before the run. A Custom Action cannot read a value that Auto Extraction or another action writes in the same run. It can read zone OCR through state.OcrCache.

Page action and document action

Item Page action Document action
state A copy of the page state. Changes are not seen by later actions, except state.UserCache. The live document state
OCR GetPageOcr, GetZoneOcr, GetRegionOcr GetDocumentOcr(state, maxPagesToOcr) (default 20, cap 100)
Zone OCR from an OCR action state.OcrCache.Get("<Property name>") Not available
Timeout 5 minutes 15 minutes

Rules

  1. Write values with result.SetDocumentMetadata(key, value). The key is the Index field name, exact and case-sensitive.
  2. Pass strings that you formatted yourself (see Gotchas).
  3. Wrap the script in (function () { ... })();.
  4. List the action after the actions it depends on.
  5. Leave the confidence at 1 when you wrote a good value. Lower it, or return 0, when the value is a guess.

Gotchas

Mistakes that write the wrong value, or nothing

  • Booleans become "True" and "False". The server formats a boolean with .NET rules. Pass "true" or "false" as strings if you need lowercase.
  • Numbers use server formatting. 1234.5 is written as 1234.5, not 1234.50. Format with toFixed(2) and pass the string.
  • Wrong order. If the Custom Action is listed before the OCR action, state.OcrCache is empty. Reorder the actions.
  • Field name typos. A key that does not match an Index field fills no field, and there is no error. Copy the field name from the content type.
  • Page action timeout is shorter. Long loops over OCR children can hit 5 minutes. Move heavy work to a document action.

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 Refiners, 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.