On this page
Sommatic Docs
Open portal

Code in Python

Execute custom Python code within the workflow.

View as Markdown
Open in
Code Available code.python Version 1.0.0 Execution: async

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.

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)]}

How it works

  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

The node as it appears in a workflow file (draft_nodes[]), and the envelope of a successful run.

{
  "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
    }
  }
}

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.

Behaviour in the code

What the implementation does with these keys beyond what the schema says.

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.

Output ports

out default

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.

Data
{
  "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 }).

Data
{
  "error": "'items'",
  "type": "KeyError",
  "logs": ""
}

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.

ExpressionEditorWorker
$("Code in Python").item.json.resultobject= {…}The dictionary returned by main().
$("Code in Python").item.json.logsstring= "loaded 2 items\n"Stderr output captured during execution (print statements, warnings).
$("Code in Python").item.json.result.countnumberNot suggested by the editor= 2—
$("Code in Python").item.json.result.urlsarrayNot suggested by the editor= […] (2)—

— Worker: The worker returns it but the editor does not suggest it: write it by hand. Keys inside objects can depend on your data or configuration (for example one key per label).

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.

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).

Contracts (JSON Schema)

The definition exactly as the orchestrator declares it. All is the whole *.definition.js; compare it with the sections above to spot differences between the documentation and the schema. Use it to validate a node before you publish.

{
  "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
    }
  }
}

Execution

Execution
async
Stateful
No
Retries (retryOnFail)
No
Capabilities
codepythontransformmlocrdata-science
Tags
codepythontransformscriptmlocr

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.

Reviewed against the orchestrator code · 31e874b · 2026-11-26

Install agent tools

Give your coding agent the official Sommatic AI docs: skills, the docs MCP server and Markdown pages, so it never has to scrape the site.

Skills only. They do not update by themselves; run it again to refresh.

npx skills add https://docs.sommatic.ai
How agents read these docs