Code in Python
Execute custom Python code within the workflow.
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:
def main(input):
items = input.get("items", [])
return {"count": len(items), "urls": [i["url"] for i in items]}import pandas as pd
def main(input):
df = pd.DataFrame(input.get("records", []))
summary = df.describe().to_dict()
return {"summary": summary}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
- Resolves the config and fails through
errorwithNo code providedwhencodeis empty. Readsexecution.timeout_ms(default 30000 ms) andpackages(default[]). - With
packages, creates a virtual environment (up to 15 s) and runspip install --no-cache-dirfor the valid package specs (up to the timeout, at most 120 s). - Writes your code into a wrapper that parses the input JSON, redirects
printto stderr and then callsmain(input), whereinputis the previous node's output as a Python value (usually a dict). - Runs it with
python3(or the venv interpreter) and stops it afterexecution.timeout_ms. - Serializes the return value of
mainwithjson.dumps(..., default=str)and returns{ result, logs }throughout, wherelogsis the whole stderr text (yourprintoutput and warnings). - 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
}
}
}{
"ok": true,
"data": {
"result": {
"count": 2,
"urls": [
"https://example.com/a",
"https://example.com/b"
]
},
"logs": "loaded 2 items\n"
},
"port": "out"
}Configuration
-
codestring Required -
Python code to execute. Define a main(input) function that returns a dict.
-
packagesarray<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.
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
pandasorrequests==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.
{
"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 }).
{
"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.
| Expression | Editor | Worker |
|---|---|---|
$("Code in Python").item.json.resultThe dictionary returned by main(). | ||
$("Code in Python").item.json.logsStderr output captured during execution (print statements, warnings). | ||
$("Code in Python").item.json.result.count | — | |
$("Code in Python").item.json.result.urls | — |
— 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
-
payloadobject Optional
Output contract
-
resultobject Optional -
The dictionary returned by main().
-
logsstring 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
}
}
}{
"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"
]
}{
"type": "object",
"description": "Any JSON payload. Passed as the input parameter to your main() function.",
"properties": {
"payload": {
"type": "object"
}
}
}{
"type": "object",
"properties": {
"result": {
"type": "object",
"description": "The dictionary returned by main()."
},
"logs": {
"type": "string",
"description": "Stderr output captured during execution (print statements, warnings)."
}
}
}[
{
"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
- Execution
async- Stateful
- No
- Retries (
retryOnFail) - No
- Capabilities
codepythontransformmlocrdata-science- Tags
codepythontransformscriptmlocr
Notes and limits
- Return JSON-friendly values. Anything
json.dumpscannot encode (dates, decimals, numpy types) is converted withstr(). printgoes tologs; do not write to stdout directly, it is reserved for the result.- The process receives only locale, path and proxy environment variables. Without
packagesonly the standard library and packages already installed for the host'spython3are importable.
Reviewed against the orchestrator code · 31e874b · 2026-11-26