# Code in Python

> 在工作流中执行自定义 Python 代码。

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

- 标识: `code.python`
- 类别: 代码
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

在工作流中执行自定义 Python 代码。

编写 Python 来处理数据、运行机器学习模型、执行 OCR 或实现复杂逻辑。传入的载荷通过 `main()` 函数的 `input` 参数提供。

**约定：** 定义一个 `main(input)` 函数，它以字典形式接收节点输入，并返回包含结果的字典。

**任意 pip 包，零配置：** 在“Pip Packages”字段中添加所需的包，如 pandas、scikit-learn、pytesseract、transformers 或 PyPI 上的任何包。它们会在代码运行前自动安装。无需配置、无需 Docker、无需 DevOps。

**示例：**
```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)]}
```

## 配置

- `code` (string, 必填): 要执行的 Python 代码。定义一个返回 dict 的 main(input) 函数。
- `packages` (array<string>, 可选): 执行前要安装的 Python 包（例如“pandas”“pytesseract”“pdf2image”）。每次执行都会创建临时虚拟环境，并在结束后清理。 默认值: `[]`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `out` (默认): 代码执行成功。
- `error`: 语法错误、导入错误、运行时错误或超时。

## 输入契约

- `payload` (object, 可选)

## 输出契约

- `result` (object, 可选): main() 返回的字典。
- `logs` (string, 可选): 执行期间捕获的 Stderr 输出（print 语句、警告）。

## 在表达式中

后续节点可通过 `$("Code in Python").item.json.<路径>` 读取此节点输出中的内容（请把 `Code in Python` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Code in Python").item.json.result` (object) = `{…}`: main() 返回的字典。
- `$("Code in Python").item.json.logs` (string) = `"loaded 2 items\n"`: 执行期间捕获的 Stderr 输出（print 语句、警告）。
- `$("Code in Python").item.json.result.count` (number) = `2` (编辑器不提示)
- `$("Code in Python").item.json.result.urls` (array) = `[…] (2)` (编辑器不提示)


## 工作原理

在独立进程中运行你的 Python 3 代码，以节点输入调用 `main(input)` 并返回 `{ result, logs }`；可选的 pip 包会安装到本次运行专用的临时虚拟环境中。

1. 解析配置；`code` 为空时以 `No code provided` 从 `error` 失败输出。读取 `execution.timeout_ms`（默认 30000 毫秒）和 `packages`（默认 `[]`）。
2. 设置 `packages` 时，创建虚拟环境（最多 15 秒），并对有效的包规格执行 `pip install --no-cache-dir`（不超过时限，最长 120 秒）。
3. 将你的代码写入包装脚本：解析输入 JSON，把 `print` 重定向到 stderr，然后调用 `main(input)`，其中 `input` 为上一个节点输出对应的 Python 值（通常是 dict）。
4. 使用 `python3`（或虚拟环境中的解释器）运行，超过 `execution.timeout_ms` 后终止。
5. 使用 `json.dumps(..., default=str)` 序列化 `main` 的返回值，并从 `out` 返回 `{ result, logs }`，其中 `logs` 为完整的 stderr 文本（你的 `print` 输出和警告）。
6. 每次运行结束后删除脚本和虚拟环境。

## 在工作流中

### 节点

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

## 输出端口 (代码中的行为)

### `out`

`main` 正常返回且未抛出异常。下游节点通过 `$json.result` 读取返回值。若脚本直接写入 stdout 且以退出码 0 结束，`result` 即为该原始 stdout 文本。

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

### `error`

`main` 抛出异常（数据为 `{ error, type, logs }`，含异常类名）；缺少 `main`；脚本无法启动或以非零码退出（数据为 `{ error, exit_code, logs }`）；缺少 Python（`{ error: "PYTHON_NOT_FOUND" }`）；或超时（`{ error: "TIMEOUT", logs }`）。

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

## 代码中的行为

- `packages`: pip 规格，例如 `pandas` 或 `requests==2.32.3`。包含字母、数字及 `-_.[]<>=!,` 以外字符的条目会被静默跳过。每次运行都会重新安装依赖包，下载和安装时间会计入运行时长。
- `execution.timeout_ms`: 代码中默认为 30000 毫秒。schema 显示 300000，是因为通用执行设置覆盖了该字段的默认值；代码不会采用该值。该值限制脚本运行时长，依赖包安装另有独立时限。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `No main(input) function defined. Define a main(input) function that returns a dict.` | `error` | 代码中没有可调用的 `main`。顶层代码会执行，但只有 `main(input)` 会产生结果。`data.type` 为 `RuntimeError`。 |
| `Python script timed out after <timeout_ms>ms` | `error` | 脚本运行时间超过 `execution.timeout_ms`。对于 OCR 或模型推理等重负载任务，请调高该值。 |
| `Failed to install packages [<packages>]: <detail>` | `error` | pip 无法安装某个包（名称未知、无网络或构建失败）。该错误会被抛出，因此若无 `flow.try` 作用域捕获，引擎会将节点和运行判定为失败。`Failed to create virtual environment: <detail>` 的行为相同。 |
| `Python 3 is not available. Ensure python3 is installed in the runtime environment.` | `error` | 运行 worker 的主机未安装 `python3`。 |
| `Failed to parse input payload: <detail>` | `error` | 输入无法解码为 JSON，`data.type` 为 `InputPayloadError`。这种情况下代码不会以空 payload 运行。 |

## 说明与限制

- 请返回适合 JSON 的值。`json.dumps` 无法编码的值（日期、Decimal、numpy 类型等）会通过 `str()` 转换。
- `print` 的输出进入 `logs`；请勿直接写入 stdout，它专用于返回结果。
- 进程只接收语言区域、路径和代理相关的环境变量。未设置 `packages` 时，只能导入标准库以及主机 `python3` 已安装的包。


## 契约（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."
  }
]
```
