# Code in Python

> Execute custom Python code within the workflow.

Source: https://docs.sommatic.ai/en/nodes/code.python/

- Slug: `code.python`
- Family: Code
- Version: 1.0.0
- Status: Available
- Execution: async

Execute custom Python code within the workflow.

Write Python to process data, run ML models, perform OCR, or implement complex logic. The incoming payload is available via the `input` parameter of your `main()` function.

**Convention:** Define a `main(input)` function that receives the node input as a dictionary and returns a dictionary with your results.

**Any pip package, zero setup:** Add the packages you need in the "Pip Packages" field — pandas, scikit-learn, pytesseract, transformers, or any package from PyPI. They are installed automatically before your code runs. No configuration, no Docker, no DevOps required.

**Examples:**
```python
def main(input):
    items = input.get("items", [])
    return {"count": len(items), "urls": [i["url"] for i in items]}
```

```python
import pandas as pd

def main(input):
    df = pd.DataFrame(input.get("records", []))
    summary = df.describe().to_dict()
    return {"summary": summary}
```

```python
from faker import Faker

def main(input):
    fake = Faker(input.get("locale", "en_US"))
    count = input.get("count", 5)
    return {"users": [{"name": fake.name(), "email": fake.email()} for _ in range(count)]}
```

## Configuration

- `code` (string, required): Python code to execute. Define a main(input) function that returns a dict.
- `packages` (array<string>, optional): Python packages to install before execution (e.g., "pandas", "pytesseract", "pdf2image"). A temporary virtual environment is created per execution and cleaned up afterward. Default: `[]`.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `out` (default): Code executed successfully.
- `error`: Syntax error, import error, runtime error, or timeout.

## Input contract

- `payload` (object, optional)

## Output contract

- `result` (object, optional): The dictionary returned by main().
- `logs` (string, optional): Stderr output captured during execution (print statements, warnings).

## In expressions

What a later node can read from this node's output with `$("Code in Python").item.json.<path>` (write your node's label instead of `Code in Python`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `out`, from the output shown in Ports.

- `$("Code in Python").item.json.result` (object) = `{…}`: The dictionary returned by main().
- `$("Code in Python").item.json.logs` (string) = `"loaded 2 items\n"`: Stderr output captured during execution (print statements, warnings).
- `$("Code in Python").item.json.result.count` (number) = `2` (Not suggested by the editor)
- `$("Code in Python").item.json.result.urls` (array) = `[…] (2)` (Not suggested by the editor)


## How it works

Runs your Python 3 code in a separate process, calls `main(input)` with the node input and returns `{ result, logs }`; optional pip packages are installed in a temporary virtual environment for the run.

1. Resolves the config and fails through `error` with `No code provided` when `code` is empty. Reads `execution.timeout_ms` (default 30000 ms) and `packages` (default `[]`).
2. With `packages`, creates a virtual environment (up to 15 s) and runs `pip install --no-cache-dir` for the valid package specs (up to the timeout, at most 120 s).
3. Writes your code into a wrapper that parses the input JSON, redirects `print` to stderr and then calls `main(input)`, where `input` is the previous node's output as a Python value (usually a dict).
4. Runs it with `python3` (or the venv interpreter) and stops it after `execution.timeout_ms`.
5. Serializes the return value of `main` with `json.dumps(..., default=str)` and returns `{ result, logs }` through `out`, where `logs` is the whole stderr text (your `print` output and warnings).
6. Removes the script and the virtual environment after every run.

## In a workflow

### Node

```json
{
  "node_id": "node-extract-urls",
  "label": "Extract URLs",
  "operator_slug": "code.python",
  "operator_version": "1.0.0",
  "config": {
    "code": "def main(input):\n    items = input.get(\"items\", [])\n    print(f\"loaded {len(items)} items\")\n    return {\"count\": len(items), \"urls\": [item[\"url\"] for item in items]}",
    "packages": [],
    "execution": {
      "timeout_ms": 30000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": {
      "count": 2,
      "urls": [
        "https://example.com/a",
        "https://example.com/b"
      ]
    },
    "logs": "loaded 2 items\n"
  },
  "port": "out"
}
```

## Output ports (behaviour in the code)

### `out`

`main` returned without raising. Downstream nodes read the value as `$json.result`. If the script printed to stdout directly and exited with code 0, `result` is that raw stdout text.

```json
{
  "result": {
    "count": 2,
    "urls": [
      "https://example.com/a",
      "https://example.com/b"
    ]
  },
  "logs": "loaded 2 items\n"
}
```

### `error`

`main` raised (data is `{ error, type, logs }` with the exception class name), `main` is missing, the script failed to start or exited non-zero (data is `{ error, exit_code, logs }`), Python is missing (`{ error: "PYTHON_NOT_FOUND" }`), or it timed out (`{ error: "TIMEOUT", logs }`).

```json
{
  "error": "'items'",
  "type": "KeyError",
  "logs": ""
}
```

## Behaviour in the code

- `packages`: pip specs such as `pandas` or `requests==2.32.3`. Entries with characters outside letters, digits and `-_.[]<>=!,` are skipped silently. Packages are installed on every run, which adds their download and install time to the run.
- `execution.timeout_ms`: Default 30000 ms in the code. The schema shows 300000 because the generic execution settings override the field's default; the code does not apply that value. It bounds the script run; package installation has its own limit.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `No main(input) function defined. Define a main(input) function that returns a dict.` | `error` | The code defines no callable `main`. Top-level code runs, but only `main(input)` produces the result. `data.type` is `RuntimeError`. |
| `Python script timed out after <timeout_ms>ms` | `error` | The script ran longer than `execution.timeout_ms`. Raise it for heavy work such as OCR or model inference. |
| `Failed to install packages [<packages>]: <detail>` | `error` | pip could not install a package (unknown name, no network, build failure). This error is thrown, so the engine fails the node and the run unless a `flow.try` scope catches it. `Failed to create virtual environment: <detail>` behaves the same. |
| `Python 3 is not available. Ensure python3 is installed in the runtime environment.` | `error` | `python3` is not installed on the host that runs the worker. |
| `Failed to parse input payload: <detail>` | `error` | The input could not be decoded as JSON; `data.type` is `InputPayloadError`. The code never runs on an empty payload in that case. |

## Notes and limits

- Return JSON-friendly values. Anything `json.dumps` cannot encode (dates, decimals, numpy types) is converted with `str()`.
- `print` goes to `logs`; do not write to stdout directly, it is reserved for the result.
- The process receives only locale, path and proxy environment variables. Without `packages` only the standard library and packages already installed for the host's `python3` are importable.


## Contracts (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "code.python",
  "name": "Code in Python",
  "category": "code",
  "version": "1.0.0",
  "description": "Execute custom Python code within the workflow.\n\n  Write Python to process data, run ML models, perform OCR, or implement complex logic. The incoming payload is available via the `input` parameter of your `main()` function.\n\n  **Convention:** Define a `main(input)` function that receives the node input as a dictionary and returns a dictionary with your results.\n\n  **Any pip package, zero setup:** Add the packages you need in the \"Pip Packages\" field — pandas, scikit-learn, pytesseract, transformers, or any package from PyPI. They are installed automatically before your code runs. No configuration, no Docker, no DevOps required.\n\n  **Examples:**\n  ```python\n  def main(input):\n      items = input.get(\"items\", [])\n      return {\"count\": len(items), \"urls\": [i[\"url\"] for i in items]}\n  ```\n\n  ```python\n  import pandas as pd\n\n  def main(input):\n      df = pd.DataFrame(input.get(\"records\", []))\n      summary = df.describe().to_dict()\n      return {\"summary\": summary}\n  ```\n\n  ```python\n  from faker import Faker\n\n  def main(input):\n      fake = Faker(input.get(\"locale\", \"en_US\"))\n      count = input.get(\"count\", 5)\n      return {\"users\": [{\"name\": fake.name(), \"email\": fake.email()} for _ in range(count)]}\n  ```",
  "capabilities": [
    "code",
    "python",
    "transform",
    "ml",
    "ocr",
    "data-science"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "code": {
        "type": "string",
        "title": "Code",
        "description": "Python code to execute. Define a main(input) function that returns a dict.",
        "ui_widget": "code_editor",
        "ui_options": {
          "language": "python"
        }
      },
      "packages": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "title": "Pip Packages",
        "description": "Python packages to install before execution (e.g., \"pandas\", \"pytesseract\", \"pdf2image\"). A temporary virtual environment is created per execution and cleaned up afterward.",
        "default": []
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          },
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          }
        }
      }
    },
    "required": [
      "code"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "description": "Any JSON payload. Passed as the input parameter to your main() function.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "object",
        "description": "The dictionary returned by main()."
      },
      "logs": {
        "type": "string",
        "description": "Stderr output captured during execution (print statements, warnings)."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Result",
      "description": "Code executed successfully.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Syntax error, import error, runtime error, or timeout."
    }
  ],
  "execution_mode": "async",
  "tags": [
    "code",
    "python",
    "transform",
    "script",
    "ml",
    "ocr"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "code": {
      "type": "string",
      "title": "Code",
      "description": "Python code to execute. Define a main(input) function that returns a dict.",
      "ui_widget": "code_editor",
      "ui_options": {
        "language": "python"
      }
    },
    "packages": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "title": "Pip Packages",
      "description": "Python packages to install before execution (e.g., \"pandas\", \"pytesseract\", \"pdf2image\"). A temporary virtual environment is created per execution and cleaned up afterward.",
      "default": []
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        },
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        }
      }
    }
  },
  "required": [
    "code"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "description": "Any JSON payload. Passed as the input parameter to your main() function.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": "object",
      "description": "The dictionary returned by main()."
    },
    "logs": {
      "type": "string",
      "description": "Stderr output captured during execution (print statements, warnings)."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Result",
    "description": "Code executed successfully.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Syntax error, import error, runtime error, or timeout."
  }
]
```
