> For the complete documentation index, see [llms.txt](https://developer.kizen.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.kizen.com/docs/concepts/agentic-workflows/automation-code-steps.md).

# Agentic Workflow Code Steps

Learn how to add custom code steps to Kizen Agentic Workflows to handle complex logic and advanced workflow scenarios.

{% hint style="success" %}
**Audience:** Developers

**Purpose:** Explains how <code class="expression">space.vars.automation</code> Code Steps work in <code class="expression">space.vars.Kizen\_company\_name</code> and provides guidance for writing, executing, and managing custom JavaScript within <code class="expression">space.vars.automations</code>.
{% endhint %}

## Overview

Code steps provide powerful, secure, and flexible scripting to <code class="expression">space.vars.Kizen\_company\_name</code> <code class="expression">space.vars.automations</code> using Python. Code Steps natively integrate with <code class="expression">space.vars.automation</code> variables and field values from your <code class="expression">space.vars.object</code> <code class="expression">space.vars.entities</code>. All code runs in an isolated container.

### Available Runtimes <a href="#available-runtimes" id="available-runtimes"></a>

* Python 3.12
* Python 3.13

In addition to packages included in the Python Standard Library, the following packages come pre-installed:

* `awslambdaric`
* `bcrypt`
* `dateutil`
* `fpdf2`
* `lxml`
* `msgpack`
* `numpy`
* `oracledb`
* `paramiko`
* `psycopg`
* `pyjwt`
* `pypdf`
* `pymysql`
* `pytz`
* `requests`
* `sqlalchemy`
* `tzdata`

{% hint style="info" %}
**Note:** If you have a library you would like for us to consider adding, send us a note at <support@kizen.com>.
{% endhint %}

### Limits <a href="#limits" id="limits"></a>

* 1 GB RAM
* 30 sec execution time

For more information see, [Log Message Limits](#log-message-limits).

***

## Using Inputs and Generating Outputs <a href="#using-inputs-and-generating-outputs" id="using-inputs-and-generating-outputs"></a>

Your python code will access input data in an object named `inputs` and write to an <code class="expression">space.vars.object</code> named `outputs`. The names of the attributes are set when you select inputs and outputs in your <code class="expression">space.vars.Kizen\_company\_name</code> <code class="expression">space.vars.automation</code>.

This example assumes an input called “name” and an output called “greeting”

```python
outputs.greeting = "hello, " + inputs.name + "!"
```

<div data-with-frame="true"><figure><img src="https://3898351136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQd8ufpN7wkdnx7JtgoeZ%2Fuploads%2Fb36Xr0oSCJgwSoza36f4%2FScreenshot-2025-06-26-at-3.23.58%E2%80%AFPM.png?alt=media&amp;token=b3e6d35f-4106-4304-9b63-aa830feda2a1" alt=""><figcaption></figcaption></figure></div>

***

## Logging <a href="#logging" id="logging"></a>

You may write logs using the provided `outputs.log()` function.

Example:

```python
from datetime import datetime
outputs.log(f"Started at: {datetime.now()}")
```

To view these logs:

1\. Open the <code class="expression">space.vars.automation</code> History, for example by navigating to a <code class="expression">space.vars.entity</code> you’ve run this <code class="expression">space.vars.automation</code> on, and clicking the “<code class="expression">space.vars.automation</code> Name” for an execution in the list.

<div data-with-frame="true"><figure><img src="https://3898351136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQd8ufpN7wkdnx7JtgoeZ%2Fuploads%2FbYvj7dmfPnvFeedBGepP%2FScreenshot-2025-06-26-at-3.36.26%E2%80%AFPM.png?alt=media&amp;token=eb117ceb-0cf3-42e5-a2dc-26f720e03e6a" alt="" width="563"><figcaption></figcaption></figure></div>

2. In the <code class="expression">space.vars.automation</code> History view, select the Execution Status in Code Step Action (the word “Completed” in the screenshot):

<div data-with-frame="true"><figure><img src="https://3898351136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQd8ufpN7wkdnx7JtgoeZ%2Fuploads%2FnmAYSyijNmFsVUkS13sk%2FScreenshot-2025-06-26-at-3.31.51%E2%80%AFPM.png?alt=media&amp;token=606a629d-b641-4ce4-903c-a8cc612ed777" alt="" width="281"><figcaption></figcaption></figure></div>

3. You will see your Execution details, including any logs you’ve written:

<div data-with-frame="true"><figure><img src="https://3898351136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQd8ufpN7wkdnx7JtgoeZ%2Fuploads%2Fnb0i6P3Wa6bxIDSzDRbz%2FScreenshot-2025-06-26-at-3.31.59%E2%80%AFPM.png?alt=media&amp;token=37f33700-cedc-4d08-b2e3-c8c1d4a354a2" alt=""><figcaption></figcaption></figure></div>

### Log Message Limits

Each call to `output.logs()` supports a maximum message size of **8 KB**. Messages that exceed this limit are truncated.

In addition, the **combined size of all log messages** generated during a single code step execution is limited to **100 KB**. Once this limit is reached, any additional log messages are discarded.

To avoid losing diagnostic information:

* Keep log messages short and focused
* Avoid logging large data structures or verbose output, especially inside loops
* For larger content, write values to fields or upload files, which support larger data sizes

***

## Validating Inputs and Raising Errors <a href="#validating-inputs-and-raising-errors" id="validating-inputs-and-raising-errors"></a>

You can [raise an Exception](https://docs.python.org/3/library/exceptions.html) to immediately stop execution of your Python code due to invalid data or other unexpected cases.

```python
outputs.log("Checking for Aristotle...")

if inputs.first_name == 'Aristotle':
    raise ValueError("Unexpected Mathematician")
else:
    outputs.greeting = f"Hello, {inputs.first_name}!"
```

This error will be visible in the Execution details:

<div data-with-frame="true"><figure><img src="https://3898351136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQd8ufpN7wkdnx7JtgoeZ%2Fuploads%2Foey9JTaC7Uy778BwJByw%2FScreenshot-2025-06-26-at-4.18.00%E2%80%AFPM.png?alt=media&amp;token=bbc1f73a-526d-4513-904f-af6e6ac063de" alt=""><figcaption></figcaption></figure></div>

A successful execution will show the inputs, outputs, and logs (more detail on the encoding of inputs and outputs later in this document):

<div data-with-frame="true"><figure><img src="https://3898351136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQd8ufpN7wkdnx7JtgoeZ%2Fuploads%2FWRqvGwpl2TIHefbvQHDl%2FScreenshot-2025-06-26-at-4.20.22%E2%80%AFPM.png?alt=media&amp;token=4af91647-bda7-44dc-8e9b-ab11972e418b" alt=""><figcaption></figcaption></figure></div>

***

## Making HTTP Requests <a href="#making-http-requests" id="making-http-requests"></a>

The ability to send HTTP requests enables powerful, flexible integrations.

```python
import requests

resp = requests.post(
  "https://httpbin.org/anything",
  json={"greeting": "Hello, world!"}
)
outputs.log(f"Got {len(resp.content)} bytes")
```

### Integration Secrets <a href="#integration-secrets" id="integration-secrets"></a>

You may also configure your Code Step with access to use Integration Secrets.

<div data-with-frame="true"><figure><img src="https://3898351136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQd8ufpN7wkdnx7JtgoeZ%2Fuploads%2F8fgoXDts95NaWOqdlcOY%2FScreenshot-2025-06-26-at-4.39%E2%80%AFPM.png?alt=media&amp;token=0d4ce5d7-ed08-4c53-ad09-a5fcf655c3b6" alt=""><figcaption></figcaption></figure></div>

```python
import requests

my_secret = secrets["magicword"]

resp = requests.get(
    "https://httpbin.org/anything",
    headers={"Authorization": f"Bearer {my_secret}"}
)
outputs.log(resp.text)
```

### HTTP Request Logs <a href="#http-request-logs" id="http-request-logs"></a>

In addition to messages you log directly in your code, HTTP requests are logged automatically.

In your HTTP request logs you’ll find:

* Total number of HTTP requests sent
* Detailed logs of the first 100 requests sent:
  * HTTP Method
  * URL
  * Request and Response Headers
  * Request Body (truncated to the first 1 kB)
* Number of requests sent without capturing detailed logs (due to exceeding the 100-request threshold)

This info will appear in the Execution Details:

<div data-with-frame="true"><figure><img src="https://3898351136-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQd8ufpN7wkdnx7JtgoeZ%2Fuploads%2Fh48OH4VFzEOsYlfTAWLN%2FScreenshot-2025-06-26-at-3.56.47%E2%80%AFPM.png?alt=media&amp;token=139fd0ff-28c8-4155-bec7-25533f33e807" alt=""><figcaption></figcaption></figure></div>

### Database Connections

Code Steps support direct database connections using `psycopg`, `pymysql`, and `sqlalchemy`. Use Integration Secrets to avoid hardcoding credentials.

#### psycopg (PostgreSQL) Example

```python
import psycopg
from psycopg.rows import dict_row

connection = psycopg.connect(
    host='host_address',
    user='user_name',
    password='password',
    dbname='database_name',
    row_factory=dict_row,
)

with connection.cursor() as cur:
    cur.execute("select * from mydata;")
    result = cur.fetchall()
    outputs.log(result)
```

More details can be found in the [Psycopg documentation](https://www.psycopg.org/).

#### SQLAlchemy (PostgreSQL) Example

```python
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session

engine = create_engine(
    "postgresql+psycopg://DB_USER:DB_PASS@DB_HOST:DB_PORT/DB_NAME"
)

with Session(engine) as session:
    result = session.execute(text("select * from mydata limit 3"))
    for row in result:
        outputs.log(row)
```

More details can be found in the [SQLAlchemy documentation](https://www.sqlalchemy.org/).

#### pymysql (MySQL) Example

```python
import pymysql

connection = pymysql.connect(
    host='host',
    port=DB_PORT,
    user='user',
    password='password',
    database='db_name',
    cursorclass=pymysql.cursors.DictCursor
)

with connection.cursor() as cursor:
    cursor.execute("SELECT * from my_table limit 3")
    result = cursor.fetchall()
    outputs.log(f"Got result: {result}")
```

More details can be found in the [Pymysql documentation.](https://pymysql.readthedocs.io/)

#### SQLAlchemy (MySQL) Example

```python
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session

engine = create_engine(
    "mysql+pymysql://DB_USER:DB_PASS@DB_HOST:DB_PORT/DB_NAME"
)

with Session(engine) as session:
    result = session.execute(text("select * from my_table limit 3"))
    for row in result:
        outputs.log(row)
```

More details can be found in the [SQLAlchemy documentation](https://www.sqlalchemy.org/).

### Other Connections

#### Paramiko Example

```python
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect to a publish SFTP server
ssh.connect(
    "test.rebex.net",
    port=22,
    username="demo",
    password="password",
    allow_agent=False,
    look_for_keys=False,
    disabled_algorithms={"pubkeys": ["rsa-sha2-256", "rsa-sha2-512"]}
)
with ssh.open_sftp() as sftp:
    with sftp.open("readme.txt", "r") as f:
        print(f.read().decode("utf-8"))
```

More details can be found in the [Paramiko documentation](https://docs.paramiko.org/en/stable/).

### Kizen API Access from Code Steps

If you are using a Code Step within an Agentic Workflow, you can call Kizen APIs directly using the preconfigured `kizen.api` client without managing credentials. See **Kizen API Access from Code Steps** in [Service Accounts](https://developer.kizen.com/docs/settings-and-administration/service-accounts.md).

***

## Kizen Data Types and Data Encoding <a href="#kizen-data-types-and-data-encoding" id="kizen-data-types-and-data-encoding"></a>

When you view the <code class="expression">space.vars.automation</code> History for a Code Step, or use the Immediate/sync API for CodeRunner you will see your <code class="expression">space.vars.Kizen\_company\_name</code> values encoded as JSON using the following scheme:

<table data-header-hidden><thead><tr><th>Data Type</th><th>Type Code</th><th>Example</th></tr></thead><tbody><tr><td>Boolean</td><td>b</td><td><pre class="language-json"><code class="lang-json">{"t": "b", "v": "false"}
</code></pre></td></tr><tr><td>Date</td><td>d</td><td><pre class="language-json"><code class="lang-json">{"t": "d", "v": "2024-12-25"}
</code></pre></td></tr><tr><td>DateTime</td><td>dt</td><td><pre class="language-json"><code class="lang-json">{"t": "dt", "v": "2024-03-14T01:59:26.535897+00:00"}
</code></pre></td></tr><tr><td>Number</td><td>n</td><td><pre class="language-json"><code class="lang-json">{"t": "n", "v": "3.14"}
</code></pre></td></tr><tr><td>Phone Number</td><td>p</td><td><pre class="language-json"><code class="lang-json">{"t": "p", "v": "+15125551212"}
</code></pre></td></tr><tr><td>String</td><td>s</td><td><pre class="language-json"><code class="lang-json">{"t": "s", "v": "Hello, World!"}
</code></pre></td></tr><tr><td>UUID</td><td>u</td><td><pre class="language-json"><code class="lang-json">{"t": "u", "v": "c6f9fe22-9d2c-4dca-9380-ab9733c85303"}
</code></pre></td></tr><tr><td>Record</td><td>e&#x3C;uuid></td><td><p>The UUID in the type code indicates which <code class="expression">space.vars.object</code> the <code class="expression">space.vars.entity</code> is part of.<br></p><pre class="language-json"><code class="lang-json">{
  "t": "e&#x3C;06e86916-cc8e-4622-af2f-8e9c08e9225b>",
  "v": "643eb36c-744c-4928-8e21-077acb65eaef"
}
</code></pre></td></tr><tr><td>Field Option</td><td>o&#x3C;uuid,uuid></td><td><p>The first UUID in the type code is the <code class="expression">space.vars.object</code> id, the second UUID is the Field ID.<br></p><pre class="language-json"><code class="lang-json">{
  "t": "o&#x3C;f87c4d49-9de2-4701-a7d1-73eda1783e25,28ca3e62-592e-4036-a7a9-0e2fd500d8f5>",
  "v": "24fb871d-f1df-42a9-8dac-1adb24bb03f6"
}
</code></pre></td></tr><tr><td>Array (typed)</td><td>a[...]</td><td><pre class="language-json"><code class="lang-json">{
  "t": "a[s]",
  "v": ["Einstein", "Newton", "Pythagoras"]
}
</code></pre></td></tr><tr><td>List (untyped)</td><td>l</td><td><p><strong>Note:</strong> Values are individually encoded, may be an empty list, and may be <code>null</code>.<br></p><pre class="language-json"><code class="lang-json">{
  "t": "l",
  "v": [
    {"t": "b", "v": "false"},
    {"t": "d", "v": "2024-12-25"}
  ]
}
</code></pre></td></tr><tr><td>File</td><td>f</td><td><p><strong>Note:</strong> The value will be a valid file ID.</p><pre class="language-json"><code class="lang-json">{"t": "f","v": "c6f9fe22-9d2c-4dca-9380-ab9733c85303"}
</code></pre></td></tr></tbody></table>

***

## Working with Typed Python Objects

Certain field values are automatically converted to strongly-typed Python <code class="expression">space.vars.objects</code> with convenient properties. These <code class="expression">space.vars.objects</code> extend UUID, so they still work anywhere a UUID is expected (comparisons, `str()`, etc.) while providing direct access to metadata.

### KizenFile

File field values are converted to `KizenFile` objects with the following properties:

| Property       | Type  | Description                                                     |
| -------------- | ----- | --------------------------------------------------------------- |
| `url`          | `str` | Presigned S3 URL for downloading the file, valid for 10 minutes |
| `name`         | `str` | Original filename                                               |
| `size`         | `int` | File size in bytes                                              |
| `content_type` | `str` | MIME content type (e.g., "application/pdf")                     |

```python
# Accessing a file field
contract = inputs.contract_file

outputs.log(f"File: {contract.name} ({contract.size} bytes)")

# Download the file content
import requests
response = requests.get(contract.url)
content = response.content
```

### FieldOption

Values from dropdown, radio, checkboxes, tags, and yesnomaybe fields are converted to `FieldOption` <code class="expression">space.vars.objects</code>:

| Property | Type  | Description                |
| -------- | ----- | -------------------------- |
| `name`   | `str` | Display name of the option |
| `order`  | `int` | Sort order                 |
| `code`   | `str` | Option code identifier     |

```python
# Accessing a dropdown field
status = inputs.lead_status

outputs.log(f"Status: {status.name}")  # "Qualified"
outputs.log(f"Code: {status.code}")    # "qualified"

# Still works as UUID for comparisons
outputs.log(str(status))  # "24fb871d-f1df-42a9-8dac-1adb24bb03f6"
```

#### Multi-Select Fields

For multi-select fields (checkboxes, tags), you receive a list of `FieldOption` <code class="expression">space.vars.objects</code>:

```python
# Iterate over selected tags
for tag in inputs.interest_tags:
    outputs.log(f"{tag.name} (code: {tag.code})")
```

### Stage

Pipeline stage field values are converted to `Stage` <code class="expression">space.vars.objects</code> with additional stage-specific properties:

| Property                     | Type  | Description                            |
| ---------------------------- | ----- | -------------------------------------- |
| `name`                       | `str` | Stage name                             |
| `order`                      | `int` | Sort order                             |
| `status`                     | `str` | Stage status: "open", "won", or "lost" |
| `percentage_chance_to_close` | `int` | Win probability (0-100)                |

```python
# Accessing a pipeline stage field
stage = inputs.deal_stage

outputs.log(f"Stage: {stage.name}")           # "Negotiation"
outputs.log(f"Win chance: {stage.percentage_chance_to_close}%")  # 60

# Check deal outcome
if stage.status == "won":
    outputs.result = "Deal closed!"
elif stage.status == "lost":
    outputs.result = "Schedule re-engagement"
```

### Record

<code class="expression">space.vars.entity</code> inputs (type code `e<uuid>`) arrive as `Record` objects. `Record` extends UUID, so existing scripts that compare a <code class="expression">space.vars.entity</code> to a UUID, convert it with `str()`, or pass it anywhere a UUID is accepted keep working.

Identifiers are available immediately. Before a Code Step runs, <code class="expression">space.vars.Kizen\_company\_name</code> loads the identifiers for each single-value <code class="expression">space.vars.entity</code> input and sends them with the inputs, so reading them makes no API call. Every other field loads from the <code class="expression">space.vars.Kizen\_company\_name</code> API the first time you read it, then stays cached for the rest of the run.

| Property                                           | Type   | Description                                                                                                                                                                                                         | API Call                                                                                                                                                                |
| -------------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                                               | `UUID` | The <code class="expression">space.vars.entity</code> itself                                                                                                                                                        | None                                                                                                                                                                    |
| `object_id`                                        | `UUID` | ID of the <code class="expression">space.vars.object</code> the <code class="expression">space.vars.entity</code> belongs to                                                                                        | None                                                                                                                                                                    |
| `object_name`                                      | `str`  | API name of the <code class="expression">space.vars.object</code>, such as `client_client`                                                                                                                          | None for single-value inputs and related <code class="expression">space.vars.entities</code>. Otherwise one call per <code class="expression">space.vars.object</code>. |
| `name`                                             | `str`  | <code class="expression">space.vars.entity</code> name. For Contacts, the first and last name joined                                                                                                                | None for single-value inputs and related <code class="expression">space.vars.entities</code>                                                                            |
| `display_name`                                     | `str`  | Display name of the <code class="expression">space.vars.entity</code>. For Contacts, the value matches the app: First Last (email). With no name, it shows (email). With no name and no email, it shows (No Email). | None for single-value inputs and related <code class="expression">space.vars.entities</code>                                                                            |
| `first_name`, `last_name`, `email`, `mobile_phone` | `str`  | Contact identifiers. `mobile_phone` uses E.164 format                                                                                                                                                               | None for single-value Contact inputs                                                                                                                                    |
| `<field_api_name>`                                 | Varies | Any other field                                                                                                                                                                                                     | One call on first read                                                                                                                                                  |

```python
deal = inputs.deal
contact = inputs.contact

# Available immediately, no API call
outputs.log(f"{deal.display_name} for {contact.display_name} <{contact.email}>")

# Not loaded in advance, one API call on first read
outputs.log(f"Amount: {deal.amount}")
```

Assigning to a `Record` attribute raises `TypeError: Record objects are read-only`. Use `editable()` to change a <code class="expression">space.vars.entity</code>.

Team Member <code class="expression">space.vars.entities</code> (`business_employee`) load only `display_name`, `name`, `first_name`, `last_name`, and `email`. Any other attribute raises `FieldDoesNotExist`. You can't use `load_fields()` on a Team Member, and you can't edit or create Team Members from code.

## Working with Records

Code Steps can read any field on a <code class="expression">space.vars.entity</code>, look up <code class="expression">space.vars.entities</code> that were not passed in as inputs, and update or create <code class="expression">space.vars.entities</code> through the <code class="expression">space.vars.Kizen\_company\_name</code> <code class="expression">space.vars.entities</code> API. Normal <code class="expression">space.vars.entity</code> and field permissions apply to every read and write. Replace placeholder <code class="expression">space.vars.object</code> and field API names, such as `deals` and `lead_score`, with the API names from your business.

### Reading Field Values

Read a field as an attribute, for example `deal.close_date`. For a field API name that is not a valid Python attribute or that starts with an underscore, use `deal["field_api_name"]`. The first read of a field that was not loaded in advance calls the API. <code class="expression">space.vars.Kizen\_company\_name</code> caches the result for the rest of the run.

A field that exists but has no value returns `None`, or `[]` for list fields. A field the <code class="expression">space.vars.object</code> does not have raises `FieldDoesNotExist`.

| Field Type                                     | Python Value                                                              |
| ---------------------------------------------- | ------------------------------------------------------------------------- |
| Single relationship                            | `Record`, or `None` when empty                                            |
| Multi relationship                             | List of `Record` objects, or `[]` when empty                              |
| Dropdown, radio, choices, yes/no/maybe, status | `FieldOption`. Pipeline stages return `Stage`.                            |
| Checkboxes, dynamic tags                       | List of `FieldOption` objects                                             |
| Files                                          | List of `KizenFile` objects                                               |
| Date                                           | `datetime.date`                                                           |
| Date and time                                  | `datetime.datetime`                                                       |
| Timezone                                       | `zoneinfo.ZoneInfo`                                                       |
| Team selector                                  | `dict` with `id`, `first_name`, `last_name`, and `email` (not a `Record`) |
| Money                                          | `float` (the amount)                                                      |
| Phone number                                   | `str` in E.164 format                                                     |
| Text, number, checkbox, and other types        | The value as the Records API returns it                                   |

Related <code class="expression">space.vars.entities</code> returned by a relationship field arrive with their identifiers: `display_name` and `name` for custom <code class="expression">space.vars.objects</code>, and `display_name`, `name`, `email`, `first_name`, and `last_name` for <code class="expression">space.vars.contacts</code>. Looping over a relationship makes no extra API calls unless you read another field on each related <code class="expression">space.vars.entity</code>, which costs one call per <code class="expression">space.vars.entity</code>. A multi relationship with more than 1,000 values raises `TooManyValues`.

```python
company = inputs.company

try:
    contacts = company.contacts
except kizen.errors.TooManyValues:
    outputs.log("More than 1,000 Contacts, skipping")
    contacts = []

# Identifiers arrive with each related Record, so this loop makes no extra API calls
emails = [c.email for c in contacts if c.email]
outputs.contact_count = len(contacts)
outputs.contact_emails = ", ".join(emails)
```

### Loading Several Fields at Once

`load_fields(record, field_names)` fetches several fields in one API call and returns the same <code class="expression">space.vars.entity</code>. Call it before a loop or a block of reads to avoid one request per field. Calling it again re-reads the fields from the API.

```python
load_fields(inputs.deal, ["amount", "close_date", "owner"])

# These reads use the loaded values, with no further API calls
outputs.log(f"{inputs.deal.amount} closes {inputs.deal.close_date}")
```

### Looking Up a Record

`kizen.get_record(identifier, *, custom_object, fields=None)` looks up a <code class="expression">space.vars.entity</code> that was not passed in as an input.

| Parameter       | Description                                                                                                                                                             |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `identifier`    | A <code class="expression">space.vars.entity</code> ID, a <code class="expression">space.vars.entity</code> name, or a Contact email. Name and email matching is exact. |
| `custom_object` | Required keyword argument. The <code class="expression">space.vars.object</code> API name or ID.                                                                        |
| `fields`        | Optional list of field names or field IDs to load in the same call.                                                                                                     |

`kizen.get_record()` raises `RecordDoesNotExist` when nothing matches.

A <code class="expression">space.vars.entity</code> from `kizen.get_record()` is not preloaded. The first read of each field not listed in `fields` costs one API call, then the value is cached for the rest of the run.

*<mark style="color:red;">\[Needs confirmation: whether the lookup call also loads identifiers such as</mark> <mark style="color:red;"></mark><mark style="color:red;">`name`</mark> <mark style="color:red;"></mark><mark style="color:red;">and</mark> <mark style="color:red;"></mark><mark style="color:red;">`display_name`</mark><mark style="color:red;">. The Confluence doc lists Contacts from</mark> <mark style="color:red;"></mark><mark style="color:red;">`kizen.get_record()`</mark> <mark style="color:red;"></mark><mark style="color:red;">as not preloaded, but PR 10835 changed Contact</mark> <mark style="color:red;"></mark><mark style="color:red;">`display_name`</mark><mark style="color:red;">. Ask</mark>* [Rieljun Liguid](mailto:undefined)*<mark style="color:red;">.]</mark>*

```python
company = kizen.get_record("Acme Corp", custom_object="companies", fields=["industry", "employee_count"])
contact = kizen.get_record("amanda@example.com", custom_object="client_client")
```

### Updating a Record

`editable(record)` returns a draft to use in a `with` block. Assign fields as attributes or with `draft["field_api_name"] = value`. <code class="expression">space.vars.Kizen\_company\_name</code> validates each assignment when you make it. When the block exits without an exception, one update request is sent.

* If the block raises an exception, nothing is sent and the original <code class="expression">space.vars.entity</code> is unchanged.
* After a successful block, the <code class="expression">space.vars.entity</code> and any other `Record` with the same ID return the saved values.
* Writing a relationship refreshes the other side. <code class="expression">space.vars.entities</code> already read in the run re-read the inverse field on next access. For `one_to_one` and `primary_for` fields, the <code class="expression">space.vars.entity</code> that previously held the related <code class="expression">space.vars.entity</code> is re-read too.
* A draft works for one `with` block only.

```python
deal = inputs.deal
load_fields(deal, ["amount"])

try:
    with editable(deal) as d:
        d.priority = "High" if float(deal.amount or 0) > 50000 else "Normal"  # Option name
        d.next_step = f"Route to {inputs.region.name} team"
        d.follow_up_date = "2026-11-01"  # ISO string or datetime.date
except kizen.errors.KizenTypeError as err:
    outputs.log(f"Invalid value, nothing was saved: {err}")
    raise

# The Record now returns the saved values
outputs.log(f"{deal.display_name} priority is {deal.priority.name}")
```

### Values You Can Assign

| Field Type                                      | Accepted Values                                                                                                                                            |
| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Text, long text, rich text, email, phone number | `str`                                                                                                                                                      |
| Integer, rating                                 | `int`, or a whole-number `float`                                                                                                                           |
| Decimal, money                                  | `int`, `float`, or `Decimal` (finite)                                                                                                                      |
| Checkbox                                        | `bool`                                                                                                                                                     |
| Date, date and time                             | `date` or `datetime`, or an ISO 8601 string                                                                                                                |
| Timezone                                        | `str` or `ZoneInfo`                                                                                                                                        |
| Dropdown, radio, choices, status, yes/no/maybe  | Option ID, or option name (not case-sensitive)                                                                                                             |
| Checkboxes                                      | List of option IDs or names                                                                                                                                |
| Dynamic tags                                    | List of tag IDs or names. A name that does not exist yet creates the tag.                                                                                  |
| Team selector                                   | Team Member `Record`, ID, or email                                                                                                                         |
| Files                                           | List of file IDs (a `KizenFile` works)                                                                                                                     |
| Relationship                                    | `Record` of the related <code class="expression">space.vars.object</code>, ID, or name (email for Contact relationships). Multi relationships take a list. |
| Any field                                       | `None` clears it (`[]` for list fields)                                                                                                                    |

Read-only fields, and fields of a type not listed, raise `KizenTypeError` on assignment. A field the <code class="expression">space.vars.object</code> does not have raises `FieldDoesNotExist`.

### Creating a Record

`new(custom_object, unarchive="create_new")` returns a draft for a new <code class="expression">space.vars.entity</code>. Pass the <code class="expression">space.vars.object</code> API name or ID. Assign fields the same way as with `editable()`. When the block exits without an exception, one create request is sent.

* After the block, the draft stands in for the created <code class="expression">space.vars.entity</code>. Assign it to an output, read its fields, or use `draft.record`.
* A <code class="expression">space.vars.entity</code> or saved draft assigned to an output is encoded as `e<uuid>`, so a later step can use it.
* `new()` with no field assignments raises `KizenError` instead of creating an empty <code class="expression">space.vars.entity</code>.

The `unarchive` argument controls what happens when an archived <code class="expression">space.vars.entity</code> has the same name or email. Each value maps to a <code class="expression">space.vars.entities</code> API unarchive mode: `create_new` to `overwrite`, `unarchive` to `unarchive_and_update`, and `unarchive_only` to `unarchive`. For details on the modes, see [Add Records API](https://developer.kizen.com/docs/concepts/objects/records/records-apis/add-records-api.md).

| Value                    | Behavior                                                                                                 |
| ------------------------ | -------------------------------------------------------------------------------------------------------- |
| `"create_new"` (default) | Creates a new <code class="expression">space.vars.entity</code> with the submitted fields                |
| `"unarchive"`            | Restores the archived <code class="expression">space.vars.entity</code> and applies the submitted fields |
| `"unarchive_only"`       | Restores the archived <code class="expression">space.vars.entity</code> and ignores the submitted fields |

```python
contact = inputs.contact

with new("support_tickets") as ticket:
    ticket.name = f"Support request from {contact.display_name}"
    ticket.contact = contact  # A Record of the related Object
    ticket.priority = "High"
    ticket.description = inputs.message

outputs.ticket = ticket  # A saved draft encodes as the new Record
outputs.log(f"Created ticket {ticket.record}")
```

To find a <code class="expression">space.vars.contact</code> by email and create one when none exists, restoring an archived match:

```python
try:
    contact = kizen.get_record(inputs.email, custom_object="client_client", fields=["lead_source"])
except kizen.errors.RecordDoesNotExist:
    with new("client_client", unarchive="unarchive") as draft:
        draft.email = inputs.email
        draft.first_name = inputs.first_name
        draft.lead_source = "Webinar"
    contact = draft.record

outputs.contact = contact
```

### Handling Errors

Error classes are not globals. Catch them through `kizen.errors`, for example `except kizen.errors.RecordDoesNotExist:`.

| Error                 | Raised When                                                                                                                                                                                        |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `KizenError`          | Base class. Also raised for a read timeout (30 seconds), a connection failure, or draft misuse.                                                                                                    |
| `KizenAPIError`       | The Records API returns a 4xx or 5xx status. Provides `.status_code` and `.detail`.                                                                                                                |
| `RecordDoesNotExist`  | A <code class="expression">space.vars.entity</code> read, lookup, or update returns 404. Subclass of `KizenAPIError`.                                                                              |
| `FieldDoesNotExist`   | The field is not on the <code class="expression">space.vars.object</code>. Also an `AttributeError`, so `getattr(record, "field", None)` works.                                                    |
| `TooManyValues`       | A relationship has more than 1,000 values.                                                                                                                                                         |
| `WriteOutcomeUnknown` | A write timed out or the connection dropped after the request was sent. The change may have been saved. Fields the write touched are re-read from the API on next access.                          |
| `KizenTypeError`      | An invalid value on assignment, a read-only or unsupported field, or a draft used as a <code class="expression">space.vars.entity</code> before it was saved (for example, assigned to an output). |

Every class except `KizenTypeError` derives from `KizenError`. `KizenTypeError` derives from `ValueError`, so `except kizen.errors.KizenError` does not catch it.

```python
deal = inputs.deal

# Optional field: FieldDoesNotExist is an AttributeError, so getattr() works
if (region := getattr(deal, "legacy_region", None)) is not None:
    outputs.log(f"Legacy region: {region}")

try:
    with editable(deal) as d:
        d.status_note = "Synced from ERP"
except kizen.errors.WriteOutcomeUnknown:
    # The request may have been saved. The next read of status_note fetches it from the API
    if deal.status_note != "Synced from ERP":
        raise
except kizen.errors.KizenAPIError as err:
    outputs.log(f"Update failed with {err.status_code}: {err.detail}")
    raise
```

### Run Identity and Permissions

Reads and writes go through the <code class="expression">space.vars.Kizen\_company\_name</code> <code class="expression">space.vars.entities</code> API, so normal <code class="expression">space.vars.entity</code> and field permissions apply to the identity running the code.

| Run Type                                                             | Identity for API Calls       | Read Check Before the Run | Identifier Fields Filtered by Permission |
| -------------------------------------------------------------------- | ---------------------------- | ------------------------- | ---------------------------------------- |
| Live <code class="expression">space.vars.automation</code> execution | Service account              | No                        | No                                       |
| Test run from the editor                                             | The person who runs the test | Yes                       | Yes                                      |

When the person running a test can't read an input <code class="expression">space.vars.entity</code>, the run fails before the code starts with `Var <name>: You do not have permission to access this record`. Identifier fields the person can't read are left out of the loaded identifiers. For a <code class="expression">space.vars.contact</code> whose email field the running identity can't read, `display_name` shows only the name, or `-` when the <code class="expression">space.vars.contact</code> has no name.

*<mark style="color:red;">\[Needs confirmation: What is the best term for the live identity? The Confluence doc says "Automation service account". DOC-554 says "Agentic Workflow Code Account". Ask</mark>* [Rieljun Liguid](mailto:undefined)*<mark style="color:red;">.]</mark>*

### Limitations

* Inputs typed `a[e<uuid>]` still become `Record` objects, but their identifiers are not loaded in advance. The first read of each element costs one API call. Use `load_fields()` on each element to load several fields at once.
* Team Member <code class="expression">space.vars.entities</code> load only `display_name`, `name`, `first_name`, `last_name`, and `email`. You can't use `load_fields()`, `editable()`, or `new()` on them.
* A multi-value relationship field with more than 1,000 values raises `TooManyValues`.
* A `with editable()` or `with new()` block saves when it exits. If the script fails later, the write is not rolled back.
* Assigning an option name that does not exist on a field raises `KizenTypeError`. Dynamic tags are the exception, because a new tag name creates the tag.
* <code class="expression">space.vars.Kizen\_company\_name</code> fetches each value once per run and reuses it. Writes made by the script refresh what they touch, but changes made by another process during the run are not seen. Call `load_fields()` to re-read a field.
* Code Steps run Python only.


---

# 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://developer.kizen.com/docs/concepts/agentic-workflows/automation-code-steps.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.
