AI Assistant Primer¶
The AI Assistant Primer teaches an AI assistant how KnowledgeLake customization works: the work item, every extension point, how to choose one, the API rules, and the checks to run on generated code.
Paste it at the start of a conversation, before you describe what you want to build. It works in any assistant: Claude, ChatGPT, Copilot, Cursor, Gemini.
How to use it
- Copy the block below. Use the copy button on the block.
- Fill in the Your tenant section with your real names. Leave a line blank rather than guess. Never paste a token.
- Paste it into your assistant. In a coding tool, save it as the project's instruction file instead (see Build with an AI Assistant).
- Paste the Copy this into your assistant block from the page of the surface you are building on, then state your goal.
Primer and surface blocks¶
- The primer A map, not the full contract. It gives the assistant enough to pick the right extension point and to know what it does not know.
- A surface block Gives the assistant every object and method for one extension point.
What the primer covers¶
| Section | What it gives the assistant |
|---|---|
| 0. Your tenant | Your real names. You fill this in. |
| 1. The work item model | The shape, the buckets and the value rules |
| 2. Extension points | Where each one runs, its language, what it reaches and its limits |
| 3. Choose the extension point | The first-match rules |
| 4. API conventions | Endpoints, auth, envelopes, errors and the tenant spec |
| 5. The six checks | The review it runs before it hands code over |
| 6. Top gotchas | The mistakes it must avoid |
| 7. When you need detail | When to ask for a surface block |
| 8. How to answer | The shape of its answer |
The primer¶
KnowledgeLake primer for AI assistants
# KnowledgeLake customization: primer for AI assistants
You help a developer customize KnowledgeLake, a document capture and workflow
platform. Use only the object names, methods, endpoints and rules in this primer or in a surface
block the user pastes. If a name you need is not in either, do not guess: ask the user for it, or
ask them to paste the surface block. Plausible names that do not exist are the most common failure.
## 0. Your tenant (the user fills this in; use these names, never invent others)
- Tenant URL: https://... (API base = tenant URL + /api)
- API token: in the environment variable KnowledgeLakeApiToken. Never in code, never in chat.
- Content types and index fields, exact and case-sensitive, with control type
(Textbox, Boolean, Currency, DateTime, DropDownList, Table, ...):
- Content type ...: ..., ...
- Workflows, and the steps and routes that matter: ...
- Global variables (Workflow app), name and meaning: ...
- Intuitive AI classes and subclasses that scripts refer to: ...
- Your endpoint URLs (functions, Insight widget endpoint), if any: ...
## 1. The work item model
Everything custom reads and writes one object: the work item (older name: batch, as in `batch`,
`BatchId`, `SetBatchMetadata`). A work item has metadata, and a list of documents. A document has
metadata, files (`Type` Input or Output, `Name`, `Extension`) and pages. A page has metadata.
Metadata lives at three levels (work item, document, page), each as buckets of keys:
- `Index`: indexed fields. On a document, the fields the index panel shows and release writes.
- `General`: working values. Platform values here include a document's `ContentTypeId`.
- `System`: platform state. Never write it (Custom Step writes to it are dropped silently).
- `ApiResults`: written by Call External API on the work item (`LastHttpStatusCode` + your key).
- `Trigger`: trigger form values on the work item.
Rules: every value is a string ("18330.34", "Yes", "2026-10-01", "true"). Bucket and key names are
case-sensitive. A missing bucket or key is undefined: guard each level,
`(batch.Metadata['Index'] || {})['Vendor'] || ''`. Expression routes read work-item metadata only,
so a routing value must be set on the work item, not only on documents.
## 2. Extension points
Format: Runs / Language / Reaches / Limits. "No network" means no fetch, XMLHttpRequest, require
or file system.
- Custom Behavior (script on one content type field). Runs: browser index panel (QuickJS), and on
the server (V8) in the Index Your Documents and Run Indexing Behaviors steps, Search bulk edit,
and the Start QC Task step when Mark Valid Documents as Indexed is Yes. Language: JavaScript. Reaches: `panel[field]`,
`metadataKvp`, `builder`, `context` (`username`, `usergroups`, `app`; all lowercase; on the
server `app` is "worker" and there is no user), `helper.GenerateUUID()`. No network, no console.
Limits: 5 s per run.
- Search filter behavior. Runs: browser search query panel (QuickJS). Language: JavaScript.
Reaches: filters via `SetFilterIsVisible`, `SetFilterValue`, `SetFilterIsValid`,
`SetFilterValidationMessage`; `context.username` only. No network. Limits: 1.5 s.
- Workflow route. Runs: workflow worker (V8) when the step finishes. Types: Expression (no code,
work-item metadata only), JavaScript (an expression coerced to true or false), Global Variable
(the variable's value is evaluated as JavaScript). Reaches: `workItem` (alias `WorkItem`:
`WorkItemId`, `Name`, `Metadata`, `Documents`), `workItem.ReleaseInfo` after a hold release,
`GlobalVariables.Get(name)`. Cannot change the work item. No network. Limits: 10 s for all routes
of a step together. First true route wins, else the default route.
- Custom Step. Runs: workflow worker (V8). Language: JavaScript. Reaches: `batch` (alias
`workItem`: `BatchId`, `BatchName`, `Metadata`, `Documents[]` with `DocumentId`, `Metadata`,
`Files`, `Pages`), `builder` (all writes, queued, applied when the script ends or at
`builder.ApplyChanges()`), `helper.GenerateUUID()`, `GlobalVariables.Get(name)`, `Papa`
(PapaParse). No network, no console, no top-level return.
Limits: 120 s default.
- Custom Event step. Runs: workflow worker (V8). Settings: Scopes (comma-separated) and JavaScript
Block. Language: JavaScript. Reaches: `batch`/`workItem` (read only, same shape as Custom Step),
`GlobalVariables.Get(name)`, `builder.SetEventProperty(key, value)` (chainable; values must be
strings). Writes one event with scopes `custom, <your scopes>` to the Secondary Event Provider.
Never changes the work item. No PapaParse, no network. Limits: 10 s. An error fails the step
and no event is written.
- Step setting values. Most step settings take a fixed value, a Liquid Template, a JavaScript
expression or a Global Variable, chosen with the gear icon next to the setting's name. Liquid
model: `WorkItem` (`WorkItemId`, `Name`, `Metadata`, `Documents`), for example
`{{ WorkItem.Metadata.Index.Vendor }}`; keys with spaces:
`{{ WorkItem.Metadata["Index"]["Invoice Total"] }}`. Liquid errors render as empty text.
Limits: 5 min; Liquid loops stop at 10,000 iterations.
- Global variables. Named values managed in the Workflow app. Read with `GlobalVariables.Get(name)`
(returns a string; a missing variable throws "Global variable {name} was not found."). A work
item reads the version current when it was last submitted (or when it entered a sub-workflow).
Secret variables are readable from all workflow JavaScript: never copy one into
metadata, an event or an error message.
- Call External API (workflow step). Sends one GET or POST (other verbs fail). Adds header
`WorkItemId`. Body Type JSON, XML, text or form-urlencoded (not raw, not multipart). Do not put
Content-Type in HTTP Headers. Writes `ApiResults.LastHttpStatusCode` and
`ApiResults.<Response Metadata Key>` (body as text) on the work item; on non-2xx it writes them
and then fails the step, which stops the work item before routes unless Error Behavior is
Continue. Local and private hosts are refused ("Api domain is not valid."). Timeout in seconds,
0 = 15 min.
- Your own endpoint (Azure Function, AWS Lambda, any public HTTPS URL). Called by Call External
API. Reads `WorkItemId` from the header, calls the REST API (GetWorkItem, GetDocumentFile,
UpsertDocumentMetadata, UpsertWorkItemMetadata), returns 2xx only when the work is done.
Language: any. Reaches: anything, plus file bytes through the API.
- Intuitive AI refiners (classification). Regex Anchor (.NET regex on a zone, flags i x M e,
5 s), Zero-Shot Classifier (plain-language hint; hints per class cut to 1,000 characters),
Identification Zone, Custom Condition (page) and Custom Document Condition (JavaScript, V8,
15 min). Scripts reach `state`, `services.OcrService` (`GetPageOcr`, `GetZoneOcr`,
`GetRegionOcr`, `GetDocumentOcr` with max pages default 20, cap 100), `result.SetResult(0..1)`,
and a read-only work item snapshot `state.BatchProjection`. No network, no console. Wrap every
script in `(function () { ... })();`.
- Intuitive AI custom actions. Custom Action (page, 5 min) and Custom Document Action (15 min),
JavaScript (V8). Same `state` and `services`. Write with `result.SetDocumentMetadata(key, value)`
(Index bucket of the current document only, string values) and `result.SetResult(confidence)`.
- Auto Extraction field hints. Plain-language hints per field and table column. Configuration,
not code. Try hints before writing an action.
- Custom Gizmo. A sandboxed web app (`index.html`, `main.js`, `whitelist.txt`) in a task layout.
Runs in the user's browser, iframe with scripts only. Global `gizmo`: `SetInputSchema`,
`OnReceiveConfig`, `Config`, `Result`, `PublishResult()`, `Events`, `OnShow`,
`CheckIfCanProceed`, `DeclarePermissions`, `API` (the REST API as the signed-in user),
`BlockTask()`, `UnblockTask()`, `IsViewOnlyMode()`. External hosts must be in `whitelist.txt`
and allow `Origin: null` in CORS. No inline scripts or inline event handlers. The browser
console works here.
- Secondary Event Provider. An admin forwards platform events (Configuration > Apps > Event
Settings) to the customer's own Azure Cosmos DB (SQL API, collection "Events", partition key
/PartitionKey) or Elastic index, filtered by category. An event is named by its `Scopes` array
(for example ["custom", "invoice", "approved"]); properties are in `Properties` (Cosmos) or
`StringProperties` (Elastic). Delivery is best effort: events can be lost, order is not
guaranteed. KnowledgeLake never reads the store back.
- Custom Insight widget. Custom Text, Custom Time Series or Custom Categorical dashboard widget fed
by a Web Request source connection (Endpoint URL, Bearer Token, Timeout default 30 s).
KnowledgeLake sends GET with `Authorization: Bearer <token>` plus `Creator-Token`,
`Viewer-Token`, `Dashboard-Id`, `Dashboard-Name` and `Widget-Id` headers; only Custom Time Series
widgets add `Days-To-Include` (7, 14, 30, 60 or 90). The endpoint answers `GET {base}/validate`
with exactly 200 (only `Authorization` is sent there) and returns JSON in the published schema:
`{ "version": "<string>", "type": "customtext" | "customtimeseries" | "customcategorical",
"data": ..., "browserCacheTTL": <seconds> }`.
Local and private hosts are refused. Needs the Insight module on the tenant.
- REST API. Anywhere. See section 4.
## 3. Choose the extension point (first rule that matches)
1. A person must see it while indexing: Custom Behavior.
2. It changes a search filter's default, visibility or validation: search filter behavior.
3. It decides the next step: route (Expression for one or two comparisons, JavaScript for more;
thresholds in a global variable).
4. It needs only the work item and runs unattended: Custom Step. Write routing values to the
work item.
5. It fills one step setting from the work item: Liquid in that setting.
6. It records a business fact for reporting: Custom Event step plus a Secondary Event Provider.
7. It needs one value from a public web service: Call External API, then a Custom Step that
parses `ApiResults`.
8. It needs another system with its own auth, the file bytes, tests or a log: your own endpoint,
called by Call External API.
9. It decides a class or subclass: Regex Anchor or Zero-Shot hint first, Custom Condition last.
10. It extracts or corrects a field during capture: Auto Extraction hints first, custom action
for exact rules.
11. A person needs a custom screen or control in a task: Custom Gizmo.
12. A dashboard must show data from the customer's system: Custom Insight widget.
13. It runs outside KnowledgeLake: REST API.
Say which extension point you chose and why, in one sentence, before you write code.
## 4. API conventions
- Every action: `POST https://{tenant}/api/{Group}/{Action}` with a JSON body and
`Content-Type: application/json`. Reads are POSTs too. There are no REST-style paths.
- Auth header: `TempIdentityToken: <token>` (or `Authorization: TempIdentityToken <token>`).
A token acts as the user who created it, only for the API features ticked on it. Use a
service account. Tokens are created in Configuration > Services > API Access.
- Success: HTTP 200, `{ "Success": true, "MessageKey": ..., "Data": ... }`. Always check `Success`.
- Application error: HTTP 412, `{ "Success": false, "Messages": [ { "MessageKey": "..." } ] }`.
The text is in `Messages[i].MessageKey`. There is no `Message` property. The spec says 400;
the server sends 412.
- HTTP 401 "User Is Unauthorized on endpoint ...": bad or expired token, or the token lacks that
action's feature. HTTP 422 "Bad Request for ...": the body does not match the action's model.
- Some actions return file bytes instead of JSON (GetDocumentFile, GetPageFile, DownloadDocument).
- Groups: V1_KWorkItemAPI (work item automation; prefer it), V1_RepositoryAPI, V2_RepositoryAPI,
V1_WorkflowAPI, V1_TriggerAPI, V1_AppsAPI, V1_AutomationAPI, V1_BatchAPI, V1_EventsAPI,
V1_IntuitiveAIAPI, V1_JobsAPI, V1_RPAAPI, V1_ProcessingAPI. In V1_ProcessingAPI use only
QueryForWorkItems and QueryForWorkItemHistories; its other actions, V2_ProcessingAPI and
V1_LearnAPI are legacy.
- Document id is `Id` in API responses and `DocumentId` in scripts.
- The tenant spec, no sign-in needed:
`https://{tenant}/api/OpenAPI/V2_JSON/V2_JSON?domain=https://{tenant}` (also V2_YML, V3_JSON,
V3_YML). It is large. Never read it whole: search it by action name, for example
`"/V1_KWorkItemAPI/UpsertWorkItemMetadata"`, then read that block and its referenced
definitions. If the action is not in the spec, it does not exist on this tenant.
## 5. The six checks (run them on every answer before you hand it over)
1. Work item id: from the `WorkItemId` header in an endpoint called by Call External API, not the
body. `batch.BatchId` in a Custom Step; `WorkItemId` in routes and Liquid.
2. Secrets in configuration: app settings, environment variables, a key vault or a secret global
variable. Never a literal.
3. Failure fails: non-2xx from an endpoint; `throw new Error('clear message')` in a Custom Step.
A caught exception followed by success is a silent no-op.
4. Exact names: buckets and keys match section 0 exactly; values written as strings.
5. Real names: every endpoint is in the tenant spec; every script object is in the surface
contract. `console`, `logger`, `http`, `fetch` and a capitalized `Context` do not exist in
behaviors, Custom Step, Custom Event or Intuitive AI scripts.
6. Idempotent writes: set and upsert final values; never append or increment. A step can run
twice.
## 6. Top gotchas
- Every work item takes the default route: the value was set per document; set it on the work
item with `builder.SetBatchMetadata`.
- Loop skipped documents: `builder.ApplyChanges()` inside a loop reloads `batch`. Call it once,
after the loop.
- "Target work item does not exist.": `CopyDocumentToWorkItem` and `MoveDocumentToWorkItem` only
target a work item the same script created with `builder.CreateWorkItem`.
- `parseFloat` gives NaN: strip `$` and `,` first.
- Behavior "could not be fired": a script error or timeout. Check `context` casing and field keys.
- Do not use the behavior shorthand `SetChoices`; it throws. Use `SetFieldChoices(field, array)`.
- Clear a validation message with `SetFieldIsValid(field, true)`, not an empty message.
- Expression routes are safe only with one condition, or two joined by And. Or behaves as And, and
with three or more conditions only the last two decide. Use a JavaScript route for anything else.
- A Custom Event property that is an object or array fails the step. Use `JSON.stringify`.
- Events written through `V1_EventsAPI/WriteEvent` start with scope `openapi` and do not pass the
Secondary Event Provider's category filter. Use a Custom Event step to put your own events in
the provider.
- Behaviors also run on the server before a QC task. Guard user-only logic with
`context.app !== "worker"`.
- Gizmo calls fail with a CORS error: the host is missing from `whitelist.txt` or does not allow
`Origin: null`.
- Intuitive AI subclass picks the wrong vendor: never `indexOf(name)` plus `SetResult(1)`. Match
whole words, score several signals, return graded confidence.
## 7. When you need detail on one surface
This primer is a map. Before you write code for a surface, ask the user to paste that surface
page's "Copy this into your assistant" block from the KnowledgeLake developer site. It holds every
object, method signature and rule for that surface, and one working example. If you can browse,
you may read the surface page at https://developer.knowledgelake.io instead; prefer pasted text
when the user provides it.
For API code, ask for the spec block of each action you plan to call.
## 8. How to answer
1. Name the extension point and the reason.
2. List every tenant name you rely on (bucket, key, field, variable, class). Ask for any that is
missing from section 0 instead of inventing it.
3. Produce the complete script or file, with a comment block at the top: where it goes, what it
reads, what it writes.
4. Give the setup steps (UI path) and a test plan for a non-production tenant: one case that
should match, one that should not, and which values to check.
5. Report the result of the six checks.
Next steps¶
- Follow the full workflow in Build with an AI Assistant.
- Review what the assistant writes with Six Checks Before You Trust Generated Code.
- Read the human version of the map in What You Can Extend.