Skip to content

Kortex — AI Integration

Kortex is the platform's built-in AI assistant. Forge apps interact with it in two directions:

  • Tools let the assistant act on your app. You register what your app can do, the user talks to the assistant, and it calls back into your app to read data, trigger actions, and navigate on the user's behalf.
  • Actions let your app ask the assistant. You call run() from a button handler, describe the job and the shape of the answer you want, and get structured data back. No chat involved.

The rule of thumb: a tool lets the assistant act on the app; an action lets the app ask the assistant. If the user is driving, register a tool. If your UI is driving, run an action.


Setup

Install the @ptkl/components package and import from the forge entry point:

npm install @ptkl/components
import { registerTool, registerContext, showHelper } from '@ptkl/components/forge'

For React apps, hooks are also available:

import { useKortexTool, useKortexContext, useKortexHelper } from '@ptkl/components/forge'

Getting Started

To make your app AI-ready, you only need two things:

  1. Register context — tell the assistant what the user is looking at.
  2. Register tools — tell the assistant what your app can do.
import { registerTool, registerContext } from '@ptkl/components/forge'
import { Platform } from '@ptkl/sdk'

const sdk = new Platform()

// 1. Describe the current page
registerContext(
  'Order #1234',
  'Viewing order details. Status: processing. Customer: John Doe.'
)

// 2. Give the assistant a tool it can call
registerTool(
  'get_order_status',
  'Returns the current status of an order by UUID.',
  {
    type: 'object',
    properties: {
      uuid: { type: 'string', description: 'Order UUID.' }
    },
    required: ['uuid']
  },
  async (args) => {
    const { data: order } = await sdk.component('orders').get(args.uuid)
    return { status: order.status, updated_at: order.updated_at }
  }
)

Now a user can ask "What's the status of this order?" and the assistant will call your tool and answer.


Registering Tools

registerTool

import { registerTool } from '@ptkl/components/forge'

registerTool(name, description, parameters, execute, policy?)
Parameter Type Required Description
name string ✅ Unique tool identifier (e.g. 'get_order_details').
description string ✅ What the tool does — the assistant reads this to decide when to use it.
parameters object ✅ JSON Schema describing the tool's arguments.
execute function ✅ The function that runs when the assistant calls the tool. Receives parsed arguments, returns the result. Can be sync or async.
policy object ❌ Override the default confirmation behavior. See Tool Policies.

unregisterTool

import { unregisterTool } from '@ptkl/components/forge'

unregisterTool('tool_name')

Remove a tool when it's no longer relevant — for example, when the user navigates away from the page.

Registering a tool with the same name replaces the old one

You don't need to call unregisterTool before re-registering. Kortex handles deduplication automatically.


Registering Context

registerContext

import { registerContext } from '@ptkl/components/forge'

registerContext(label, description, icon?)
Parameter Type Required Description
label string ✅ Short label for the current page (e.g. "Order #1234").
description string ✅ Describe what the user is currently seeing or doing.
icon string ❌ Icon identifier for visual representation.

The description is the most important part — it gives the assistant situational awareness. Be specific:

// ❌ Too vague
registerContext('Orders', 'The orders page.')

// ✅ Specific and useful
registerContext(
  'Orders',
  'Browsing the orders list. Filters: status=processing, date=last 7 days. 24 results shown.'
)

unregisterContext

import { unregisterContext } from '@ptkl/components/forge'

unregisterContext()

Clear the context when the user leaves a page.


Tool Policies

Policies control whether the user sees a confirmation prompt before a tool executes. By default, Kortex infers the policy from the tool name:

Name your tool with… What happens
get_*, list_*, find_*, search_* Runs automatically — no confirmation needed.
set_*, save_*, add_*, update_* Asks the user to confirm before running.
create_*, publish_*, delete_*, remove_* Asks to confirm — treated as a higher-risk action.

Name your tools with clear prefixes

A tool named get_order will run without asking. A tool named delete_order will always ask for confirmation. Choose prefixes that match the action's risk level.

Overriding the default policy

If the automatic inference doesn't fit, pass a policy object as the last parameter:

registerTool(
  'export_report',
  'Export the current report as PDF.',
  { type: 'object', properties: {} },
  () => exportToPDF(),
  { risk: 'low', requiresConfirmation: false }
)
Policy field Type Description
risk 'low' \| 'medium' \| 'high' Risk level of the action.
requiresConfirmation boolean Whether the user must approve before the tool runs.
category string Category label (e.g. 'read', 'write', 'destructive').
fullAccessAuto boolean Auto-execute when the user has granted full access.

Helper Visibility

Signal to the user that AI help is available on the current page by activating the Kortex button glow:

import { showHelper, hideHelper } from '@ptkl/components/forge'

showHelper()   // show the glow indicator
hideHelper()   // hide the glow indicator

React Hooks

For React apps, hooks handle registration and cleanup automatically:

useKortexTool

Registers a tool on mount, unregisters on unmount. Re-registers if the name, description, or parameters change.

import { useKortexTool } from '@ptkl/components/forge'

function OrderDetail({ orderId }) {
  useKortexTool(
    'get_order_status',
    'Returns the current status of this order.',
    {
      type: 'object',
      properties: {
        uuid: { type: 'string', description: 'Order UUID.' }
      },
      required: ['uuid']
    },
    async (args) => {
      const { data: order } = await sdk.component('orders').get(args.uuid)
      return { status: order.status }
    }
  )

  return <div>...</div>
}

useKortexContext

Sets the page context on mount, clears on unmount. Updates when label or description change.

import { useKortexContext } from '@ptkl/components/forge'

function OrderDetail({ order }) {
  useKortexContext(
    `Order #${order.number}`,
    `Viewing order ${order.number}. Status: ${order.status}. Customer: ${order.customer_name}.`
  )

  return <div>...</div>
}

useKortexHelper

Shows the helper glow on mount, hides on unmount.

import { useKortexHelper } from '@ptkl/components/forge'

function ProductCatalog() {
  useKortexHelper()
  return <div>...</div>
}

useIsKortexAvailable

Check whether Kortex is available in the current environment.

import { useIsKortexAvailable } from '@ptkl/components/forge'

function MyApp() {
  const kortexAvailable = useIsKortexAvailable()

  return (
    <div>
      {kortexAvailable && <span>AI assistant is available</span>}
    </div>
  )
}

Examples

Read-only tool — no parameters

registerTool(
  'get_current_page',
  'Returns the current page URL the user is viewing.',
  { type: 'object', properties: {} },
  () => ({
    href: window.location.href,
    path: window.location.pathname
  })
)

Tool with parameters

registerTool(
  'search_orders',
  'Search orders by status and date range.',
  {
    type: 'object',
    properties: {
      status: {
        type: 'string',
        enum: ['pending', 'processing', 'shipped', 'delivered'],
        description: 'Order status to filter by.'
      },
      from_date: {
        type: 'string',
        description: 'Start date in ISO 8601 format.'
      }
    },
    required: ['status']
  },
  async (args) => {
    const orders = await fetchOrders({ status: args.status, from: args.from_date })
    return { count: orders.length, orders }
  }
)

Write tool — creates a record

registerTool(
  'create_invoice',
  'Create a new invoice for a customer.',
  {
    type: 'object',
    properties: {
      customer_uuid: { type: 'string', description: 'Customer UUID.' },
      items: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            product_uuid: { type: 'string' },
            quantity: { type: 'number' }
          }
        },
        description: 'Line items for the invoice.'
      }
    },
    required: ['customer_uuid', 'items']
  },
  async (args) => {
    const invoice = await sdk.component('invoices').create({
      customer_uuid: args.customer_uuid,
      items: args.items
    })
    return { uuid: invoice.uuid, total: invoice.total }
  }
)

Best Practices

  • Write clear descriptions. The assistant chooses which tool to call based on the description. Be specific about what it does, what it returns, and when to use it.
  • Keep tools focused. One tool, one action. Prefer get_order + update_order_status over a single manage_order.
  • Return structured data. Return objects and arrays — the assistant presents structured data better than plain strings.
  • Register and unregister with the page lifecycle. Only expose tools that are relevant to the current page. Clean up on unmount.
  • Throw descriptive errors. If a tool fails, the error message goes to the assistant. Make it helpful: "Order not found: abc-123" is better than "Not found".

Actions — asking the assistant from your app

Some AI work does not belong in a chat. "Generate attributes for this product" is a button next to the attributes field, not a conversation — the user wants suggestions in the form they are already editing, and your app needs the result as data it can apply, not prose it has to parse.

That is what an action is: one bounded operation, triggered by your UI, returning structured data.

useKortexRun

import { useKortexRun } from '@ptkl/components/forge'

function AttributeGenerator({ product, onApply }) {
  const { run, data, isRunning, error } = useKortexRun({
    name: 'generate_product_attributes',
    agent: PRODUCT_AGENT_UUID,
    instructions:
      'Extract product attributes from the supplied title and description. ' +
      'Only emit values directly supported by the copy — never invent specifications.',
    schema: {
      type: 'object',
      required: ['attributes'],
      properties: {
        attributes: {
          type: 'array',
          items: {
            type: 'object',
            required: ['name', 'value', 'confidence'],
            properties: {
              name:       { type: 'string' },
              value:      { type: 'string' },
              confidence: { type: 'number', minimum: 0, maximum: 1 }
            }
          }
        }
      }
    }
  })

  return (
    <>
      <button onClick={() => run({ title: product.title, description: product.description })}
              disabled={isRunning}>
        {isRunning ? 'Generating…' : 'Generate attributes'}
      </button>

      {error?.code === 'no_access' && <p>You do not have access to this feature.</p>}
      {error && error.code !== 'no_access' && <p>Could not generate attributes. Please try again.</p>}

      {data && <AttributeSuggestions items={data.attributes} onApply={onApply} />}
    </>
  )
}

Kortex renders nothing except a small progress pill while the action runs. The result is yours to present — a diff, a checklist, a preview. Never apply model output silently; let the user see and accept it.

Request fields

Field Required Notes
name yes Stable id. Shown on the progress pill, used for telemetry.
agent yes Which agent runs the action. See below — this is a real decision.
instructions yes What the model should do.
input no Serialised into the message. Pass the data the action works on.
schema no JSON Schema. When present, data is parsed and validated against it.
tools no true exposes every registered tool; an array names a subset.
onProgress no Content deltas. Not called when schema is set — partial JSON is useless.
signal no Cancel the run. useKortexRun also gives you cancel().

Choosing the agent

agent has no default, deliberately. It selects the system prompt, the model tier, the knowledge bases and the generation settings — including temperature. An action that extracts facts wants a low-temperature agent; one that writes marketing copy does not. There is no correct default, so there isn't one.

If your action needs a project-specific agent, take the uuid from app configuration rather than hard-coding it — a constant only works for platform-wide agents.

Schemas are a contract

Supply a schema whenever you intend to use the result programmatically. Kortex validates the model's output against it and retries once with the validation errors before giving up, so data either matches your schema or you get a schema_invalid error. Without a schema you get text and nothing more.

Keep schemas tight. confidence: { type: 'number', minimum: 0, maximum: 1 } is more useful than confidence: { type: 'number' }, both as a constraint and as a hint to the model.

Using your tools from an action

Pass tools: true and the action can call any tool your page has registered — useful when the model needs to look something up mid-task rather than being handed everything up front.

Tool approval works exactly as it does in chat: a tool that requires confirmation still prompts the user. An action is not a way around the policy layer. Actions are capped at 5 tool rounds.

Errors

error.code is one of:

Code Meaning
no_access The user cannot use Kortex, or cannot use this agent.
quota_exceeded Project daily limit or the user's credit limit is reached.
schema_invalid Output did not match the schema after one repair attempt. details has the validation errors.
tool_denied The user declined a tool the action needed.
aborted Cancelled via cancel() or the signal.
agent_not_found The agent uuid does not resolve.
input_too_large A message exceeded the 32,000-byte limit.
not_ready Called before the Kortex runtime finished mounting.
upstream Anything else.

no_access deserves its own branch in your UI. It fires per user, not per app — the same action can work for one user and be refused for another, depending on their Kortex access and agent allowlist. Render it as "you do not have access to this feature", not as a failure.

Feature detection

Actions need a host that supports them. Older hosts expose the registration surface only:

import { hasKortexCapability } from '@ptkl/components/forge'

if (hasKortexCapability('run')) {
  // safe to offer the action
}

Testing Kortex locally

ptkl forge dev provides a working window.kortex and a DevTools panel, so tools and actions can be developed without deploying.

Open the 🛠 Kortex button in the corner of your dev server.

Tools tab

Every registered tool with its schema, resolved policy, and page context, updating live. Invoke a tool directly with your own JSON arguments to check execute() in isolation.

Runs tab

This is where you check the part that actually goes wrong. Registering a tool is easy; getting the model to choose it, with the right arguments, is not.

Every action run records:

  • the tool calls the model made, with the arguments it invented
  • what each tool returned, and the policy that applied
  • the final data, or the error with validation detail

The prompt box drives a real round-trip through the same run() your app uses. Type something a user might say, tick expose registered tools, and watch whether your tool gets called. If it does not, the problem is almost always the tool's description — the model chooses from that text.

What is faithful, and what is not

Dev mode drives the same endpoint, the same tool loop, the same policy resolution and the same schema validation as production. Two differences to keep in mind:

  • Approval prompts do not appear. Production raises an approval card for a tool that requires confirmation; dev auto-runs it and logs a warning to the console naming the policy that would have applied. Verify approval flows in a deployed app.
  • run() needs a session. It uses your CLI profile token, so a run costs real tokens against your project's budget. If you are not logged in it fails with no_access — run ptkl login and restart the dev server.

There is no offline or mock mode. A run either reaches Kortex or it does not, and only one of those tells you anything: the questions worth answering — does the model choose my tool, do my instructions produce valid output — can only be answered by a real round-trip.