> For the complete documentation index, see [llms.txt](https://docs.ninox.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.ninox.com/ninox-scripting/automate-your-workflows/work-with-functions/system-flow-control-and-ai.md).

# System, flow control, and AI

Learn how to pause scripts, inspect the app execution context.

System and flow control functions help you manage timing, sync, caching, and environment-specific behavior. You can pause a script, inspect raw values, and detect app context.

In this chapter, you will learn how to:

* Control timing in a running script.
* Inspect the current app environment and database status.

<table><thead><tr><th width="233.96484375">Function (A-Z)</th><th>Task</th></tr></thead><tbody><tr><td><code>eval()</code></td><td>Execute text as a script</td></tr><tr><td><code>generateObject()</code></td><td>Get JSON object data from Ninox AI</td></tr><tr><td><code>generateText()</code></td><td>Get text data from Ninox AI</td></tr><tr><td><code>ninoxApp()</code></td><td>Return the current client or app context</td></tr><tr><td><code>raw()</code></td><td>Return the internal text representation</td></tr><tr><td><code>sleep()</code></td><td>Pause a script briefly</td></tr></tbody></table>

## Control timing and execution order

Use these functions when one action should happen only after another has completed.

### Pause a script briefly

Use `sleep()` to force Ninox to wait for a given number of milliseconds before the script continues.

Use it when you want to:

* Add a short delay before a follow-up action.
* Avoid timing issues in a UI flow.
* Wait briefly for another process to settle.
* Show a note or warning before the next step runs.

`sleep(number)`

* `number` the delay in milliseconds

`sleep()` returns no value.

#### Let’s take a look at some examples:

```ninox
sleep(2000)
```

Pauses the script for 2 seconds.

Tips:

* Keep delays as short as possible.
* Use a delay only when the flow really needs it.

## Inspect raw values and range boundaries

Use these functions when you need the underlying value or the start boundary of a duration or range context.

### Inspect the raw value

Use `raw()` to return the internal raw text representation of a value.

Use it when you want to:

* Convert formatted text into its raw text form.
* Read the internal value behind a color field.
* Reuse formatted content in dialogs or emails.
* Compare the raw form with the displayed form.

`raw(any)`

* `any` the value you want in raw form

`raw()` returns a string.

#### Let’s take a look at some examples:

```ninox
raw('My sample text')
```

Returns the content of a formatted text value as unformatted text with HTML tags.

```ninox
dialog("Hello", raw('Dialog text'), ["Yes", "No"])
```

Displays a dialog with the contents of the formatted text field `Dialog text`.

```ninox
raw(Color)
```

Returns the internal color value, for example `#EC87E2`.

Tips:

* Use `raw()` when you need the system's internal text representation.
* This is useful for formatted text fields, dialogs, and emails.
* You can format the result again later with `html()`.

### Execute strings as formulas and inspect data with `eval()`

Use `eval()` to execute text as a script.

This lets you create dynamic expressions. For example, use table, field, and variable names that change at runtime.

`eval(string, nid)`

* `string` text containing calculations or a Ninox script
* `nid` the record to which the script applies

#### Let’s take a look at some examples:

```
eval(manual_formula, this) 
```

Returns `20` if the current record's "Manual formula" field contains "14 + 6 \* 0.5 \* 2".

<pre><code><strong>let myTable := "invoices"; 
</strong>eval("sum((select " + myTable + ").amount)", this)
</code></pre>

Returns the sum of all amounts in the "Invoices" table.

```
let myText := "alert(""This is a test"")"; 
eval(myText,this)
```

Shows an alert with the message "This is a test".

```
let myField := "full_name"
eval(myField, this) 
```

Returns the value "Toni Kim" from the "Full name" field. For a choice field, it returns the value's index.

```
let myChoice := "choice_field";
eval("text(" + myChoice + ")", this)
```

Returns the text value of a choice field.

```
let myTable := "contacts";
let myField := text(my_choice);
let myCurrentName := eval("text(" + myField + ")", this);
cnt(eval("select " + myTable + " where " + myField + " = " + myCurrentName, this))
```

Returns the number of records in the "Contacts" table whose "Full name" field matches the selected field value in the current record. Use this approach for dynamic duplicate searches when `myField` is selected from a choice field.

## Detect app context and database state

Use these functions when your script should react to the current client or the protection status of the database.

### Detect the current app with `ninoxApp()`

Use `ninoxApp()` to check where your script is executed.

Use it when you want to:

* Adjust behavior by client.
* Diagnose client-specific workflows.

`ninoxApp()`

`ninoxApp()` returns a string that identifies the current environment.

Possible return values include:

* `client`
* `server`

#### Let’s take a look at some examples:

```ninox
ninoxApp() = "client"
```

Returns a string that identifies where the script is running.

Tips:

* Use `ninoxApp()` to check if your UI-based functions can be executed, which is not the case if the result is "server".

## Let Ninox AI execute tasks with `generateObject()` and `generateText()`

Use these two functions to send data and instructions to Ninox AI and get text or a JSON object. Use them to classify text, extract values, or fill fields automatically.

`generateObject(prompt, format)`, returns a JSON object with the fields `format` asks for.\
`generateObject(prompt, format, model)`\
`generateText(prompt)`, returns text.\
`generateText(prompt, model)`

* `prompt` is a text value or an array of texts. It contains the data Ninox AI should inspect and the instruction for Ninox AI.
* `format` JSON values to define the returned fields and their types: `"string"`, `"number"`, `"boolean"`, `"date"`, or a list of text values when Ninox AI must select one option. Provide them in curly braces.
* `model` is a JSON value to choose an AI model: `"haiku"` (default), `"sonnet"` , `"opus"`, or `"luna"`. Provide it in curly braces.

{% hint style="info" %}
Find more information about the AI models used by Ninox AI [here](https://docs.ninox.com/builder-hub/ninox-ai/ninox-ai.md).
{% endhint %}

If you refer to Ninox fields, their raw values are taken, for example, a choice's option ID instead of its label. Use the `text()` function to get the text value instead.

Read the result in `format` with `r.field`, `item(r, "field")`, or `for key, value in r do … end`.

A date returns text in `YYYY-MM-DD` format. Use `date()` to convert it to a date value.

Note the following limits:

* `format` fields: maximum 20. Use 1-7 where possible.
* Choices per list: 2-50. Use up to 10 where possible.
* Field names: letters, digits, and `_` only. Start with a letter. `error` is reserved.
* `prompt` size: maximum 20,000 characters
* Timeout: 25 seconds
* AI calls per script run: maximum 50
* Up to four calls can run at once per workspace.

{% hint style="info" %}
In triggers, use `generateObject()` and `generateText()` inside `do as deferred`. They are not available in Logic fields or `do as transaction`.
{% endhint %}

#### Let’s take a look at some examples:

```ninox
let r := generateObject(
    [message, "Pick a category and priority."], {
    category: ["Bug", "Question"],
    priority: ["High", "Medium", "Low"]
    });
if r.error then
    alert(r.error)
else
    category := r.category;
    priority := r.priority
end
```

Classifies a support ticket and fills the category and priority fields.

```ninox
let r := generateObject(
    text(email_text) + " Extract the number of licenses and the start date.", {
    licenses: "number",
    startDate: "date"}, {
    model: "sonnet"});
if not r.error then
    licenses := r.licenses;
    start_date := date(r.startDate);
    total_price := r.licenses * price_per_license
end
```

Extracts a number and date from an email. The returned number can be used in calculations.

```ninox
let t := generateText(["Subj: " + email_subject + "Msg: " + text(email_body), 
                       "Summarize the request!"]);
if not t.error then
    alert(t)
end
```

Displays a short summary of the received email in a pop-up message, using its subject and body.

### Process many records

You can call the functions once for each record or once for a group of records. Choose the approach based on the result you need.

Use an AI call for each record when you need to fill a field for every record. This example classifies each record in the "Tickets" table:

```ninox
for t in select Tickets do
    let r := generateObject([t.message, "Classify the ticket."], {
        category: ["Bug", "Question", "Feature request"]}
    });
    if not r.error then
        t.category := r.category
    end
end
```

Five records result in five AI calls. Each record receives its own category.

Use one AI call for all records when you need an overview or report for multiple records. This example sends all ticket titles and messages in one AI call:

```ninox
let myData := for t in select Tickets do
   "Title: " + t.title + ", Message: " + t.message
end;
let r := generateText(myData + " What is the most common problem in the messages?", {
                        model: "opus"});
if not r.error then
    alert(r)
end
```

Five records result in one AI call. This approach is faster and uses fewer AI credits.

{% hint style="info" %}
Call the function once for each record when every record needs its own result. This approach fills fields, but five records require five AI calls.\
\
Call the function once for all records when you need one shared result. This approach suits overviews and reports. Five records require one AI call.
{% endhint %}

Tips:

* Each AI call uses AI credits.
* Send only necessary data to the Ninox AI.
* No prompt, message or answer content is logged.
* The result contains the fields defined in `format`. Unknown values are `null`.
* On failure, both functions return `{error: "message"}`. Check `r.error` before using the result.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.ninox.com/ninox-scripting/automate-your-workflows/work-with-functions/system-flow-control-and-ai.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
