Skip to content

API Reference: The $ai Object

The $ai object is a powerful, secure API available within Record Behaviors that allows you to integrate state-of-the-art AI into your business logic with a single function call.

Security by Design: Permission-Aware Execution

All $ai API calls are secure by default, leveraging the Simple Platform's core security architecture. You do not need to write any extra security or permission-checking code.

  • Secure Sandbox: Your Record Behavior script runs in a secure WASM sandbox, completely isolated from the host system.

  • Platform-Level Permission Enforcement: When you pass a DocumentHandle to an $ai function, the platform's backend services perform an authoritative check. The AI Service re-validates that the current user has read permissions for the specific record and field that the document belongs to. If the user does not have access, the operation will fail with a "Permission Denied" error.

The Simple Advantage

This is a critical security guarantee. On legacy platforms, the burden of checking permissions before calling an external service falls on the developer, creating a massive potential for error and data leaks. On Simple, it is architecturally impossible for a script to trick the AI engine into processing a document the user is not authorized to see. Security is built-in, not bolted on.


await $ai.extract(input, options)

Extracts structured data from a given input, conforming to a JSON schema you provide. This is the cornerstone of AI-powered data entry and document processing.

Parameters

  • input: DocumentHandle | string | object The source data for the extraction. This can be a DocumentHandle from a document field, a long string of text, or any JSON-serializable object.

  • options: object An object to configure the extraction operation.

    • prompt: string (required) A natural language instruction telling the AI what to extract.
    • schema: object (required) A valid JSON Schema object that defines the desired shape of the output. The AI Engine guarantees that the returned data will conform to this schema.
    • model: 'lite' | 'medium' | 'large' | 'xl' (optional) The class of model to use for the operation. If omitted, the platform selects the most cost-effective model suitable for the task. Use larger models for more complex inputs or schemas.
    • systemPrompt: string (optional) A high-level instruction that defines the AI's role, personality, or global constraints (e.g., "You are an expert accounting assistant specialized in parsing invoices.").
    • temperature: number (optional) Controls the creativity of the model. A value from 0.0 (most deterministic) to 1.0 (most creative). If omitted, a sensible default is used.
    • reasoning: boolean (optional, default: false) If true, forces the AI to provide a detailed, step-by-step explanation of its thought process. This is useful for debugging and auditing, and the result is returned in the metadata.reasoning field.
    • regenerate: boolean (optional, default: false) If true, forces the AI to re-process the input, ignoring any previously cached results in the AI Memcache. Use this when you need a fresh result.
    • timeout: number (optional, default: 30000) The maximum time in milliseconds to wait for the AI operation to complete. If the timeout is exceeded, the promise will be rejected.

Returns

A Promise that resolves to an AIExecutionResult object: { data, metadata }.

Example: Extracting Invoice Data from a PDF

javascript
export default async ({ $form, $ai }) => {
  if ($form.updated('invoice_pdf')) {
    const invoiceHandle = $form('invoice_pdf').value();
    if (!invoiceHandle) return;

    const { data, metadata } = await $ai.extract(invoiceHandle, {
      prompt: "Extract the invoice number, total amount, and all line items from this invoice.",
      model: 'large', // Use a larger model for complex document parsing
      reasoning: true, // Ask the AI to explain its work for auditability
      schema: {
        type: "object",
        properties: {
          invoice_number: { type: "string" },
          total_amount: { type: "number" },
          line_items: {
            type: "array",
            items: {
              type: "object",
              properties: {
                description: { type: "string" },
                quantity: { type: "number" },
                unit_price: { type: "number" }
              },
              required: ["description", "quantity", "unit_price"]
            }
          }
        },
        required: ["invoice_number", "total_amount"]
      }
    });
    
    console.log(`AI Reasoning: ${metadata.reasoning}`);

    // Populate form with the guaranteed, structured JSON data
    $form('invoice_number').set(data.invoice_number);
    $form('total_amount').set(data.total_amount);
  }
}

await $ai.summarize(input, options)

Generates a concise, natural-language summary from a given input.

Parameters

  • input: DocumentHandle | string | object The source data to summarize.

  • options: object An object to configure the summarization operation.

    • prompt: string (required) A natural language instruction guiding the summary (e.g., "Summarize this support ticket into one sentence for a manager's dashboard.").
    • All other options from $ai.extract (model, systemPrompt, temperature, reasoning, regenerate, timeout) are also available and behave identically.

Returns

A Promise that resolves to an AIExecutionResult object where data is a string.

Example: Summarizing a Long Description

javascript
export default async ({ $form, $ai }) => {
  // When the detailed description of a support ticket is updated...
  if ($form.updated('long_description')) {
    const description = $form('long_description').value();

    if (description && description.length > 50) {
      // ...generate a short summary for display in list views.
      const { data: summary } = await $ai.summarize(description, {
        prompt: "Summarize this technical issue description into a single, non-technical sentence.",
        model: 'lite' // A small model is perfect for quick summarization tasks.
      });
      
      $form('short_summary').set(summary);
    }
  }
}

The AIExecutionResult Object

Both $ai methods return a consistent result object, providing both the data and valuable metadata about the operation.

PropertyTypeDescription
dataanyThe primary output. For extract, this is the structured object matching your schema. For summarize, this is the summary string.
metadataobjectAn object containing metrics about the AI operation, useful for observability and cost management.
metadata.inputTokens: The number of tokens in the input sent to the model.
metadata.outputTokens: The number of tokens in the generated data output.
metadata.reasoning: A string explaining the AI's thought process. Only present if reasoning: true was set in the options.
metadata.reasoningTokens: The number of tokens used for the reasoning process. Only present if reasoning: true was set.

Next Steps

With the API reference in hand, see how these functions fit into the broader platform.