本页内容
Sommatic 文档
打开控制台

Code in Python

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

以 Markdown 查看
在以下应用中打开
代码 可用 code.python 版本 1.0.0 执行方式: async

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

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

工作原理

  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. 每次运行结束后删除脚本和虚拟环境。

在工作流中

节点在工作流文件(draft_nodes[])中的写法,以及一次成功运行的 envelope。

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

配置

code string 必填

要执行的 Python 代码。定义一个返回 dict 的 main(input) 函数。

packages array<string> 可选

执行前要安装的 Python 包(例如“pandas”“pytesseract”“pdf2image”)。每次执行都会创建临时虚拟环境,并在结束后清理。

默认值: []

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

代码中的行为

除 schema 描述之外,实现代码对这些键的实际处理。

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

输出端口

out 默认

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

数据
{
  "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 })。

数据
{
  "error": "'items'",
  "type": "KeyError",
  "logs": ""
}

在表达式中

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

表达式EditorWorker
$("Code in Python").item.json.resultobject= {…}main() 返回的字典。
$("Code in Python").item.json.logsstring= "loaded 2 items\n"执行期间捕获的 Stderr 输出(print 语句、警告)。
$("Code in Python").item.json.result.countnumber编辑器不提示= 2—
$("Code in Python").item.json.result.urlsarray编辑器不提示= […] (2)—

— Worker: worker 会返回它,但编辑器不会提示:请手动输入。对象内部的键可能取决于你的数据或配置(例如每个标签一个键)。

错误

消息 端口 原因与处理
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 运行。

输入契约

payload object 可选

输出契约

result object 可选

main() 返回的字典。

logs string 可选

执行期间捕获的 Stderr 输出(print 语句、警告)。

契约(JSON Schema)

与编排器声明完全一致的定义。All 是完整的 *.definition.js;可与上方各节对照,找出文档与 schema 之间的差异。发布前可用它校验节点。

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

执行

执行方式
async
有状态
否
重试(retryOnFail)
否
能力
codepythontransformmlocrdata-science
标签
codepythontransformscriptmlocr

说明与限制

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

已对照编排器代码核实 · 31e874b · 2026-11-26

安装智能体工具

为你的编程智能体接入 Sommatic AI 官方文档:技能包、文档 MCP 服务器与 Markdown 页面,无需再抓取网页。

仅安装技能包,不会自动更新;需要时重新运行即可。

npx skills add https://docs.sommatic.ai
智能体如何读取本文档