---
sidebar_label: "在自己的仓库实现 Recipe"
title: "在自己的仓库里实现 Recipe"
description: "在本地或 GitHub 的 Git 仓库中放置 recipe.toml、entrypoint.sh 与代码，用 el recipe create 发布，并在 Train Job 中运行。"
last_update:
  date: 2026-11-18
---

Recipe 是你自己的训练、数据处理、推理或评测代码，连同它的声明一起发布。它放在你自己的 Git 仓库中：只在本地的仓库，或公开、私有的 GitHub 仓库都可以；用 `el` 发布后，由平台维护的 Runner 在 Job 中运行它。

## Runner 与 Recipe {#runner-and-recipe}

| | Runner | Recipe |
|---|---|---|
| 维护方 | 平台 | 你 |
| 声明文件 | `runner.toml` | `recipe.toml` |
| 入口文件 | `main.sh` | `entrypoint.sh` |
| 决定什么 | 镜像、资源、网络，以及标准参数 `image`、`command`、`timeout_seconds`、`max_retries` | Job 类型、参数、输入槽位和你的代码 |
| 身份 | `NAMESPACE/NAME@FULL_COMMIT` | `envloop://recipes/NAMESPACE/NAME@<recipe-sha256>` |

所有 Recipe 使用同一条调用链：

1. 平台启动 Runner 的 `main.sh`，并准备下表的交接文件。
2. `main.sh` 执行 `bash "$ENVLOOP_RECIPE_ROOT/entrypoint.sh"`，不需要可执行位。
3. 你的 `entrypoint.sh` 调用你的代码。

| 环境变量 | 内容 |
|---|---|
| `ENVLOOP_RECIPE_ROOT` | 只读目录，解开的 Recipe 包 |
| `ENVLOOP_JOB_FILE` | JSON：`job_id`、`trial_id`、`type` 与解析后的 `resources` |
| `ENVLOOP_PARAMS_FILE` | JSON：合并并校验后的 Recipe 参数 |
| `ENVLOOP_INPUTS_FILE` | JSON：每个输入槽位的本地 `path`、`uri` 与 `manifest_sha256` |
| `ENVLOOP_OUTPUT_DIR` | 可写的输出目录 |

退出码 0 表示成功。结果写入 `$ENVLOOP_OUTPUT_DIR/result.json`，格式为 `{"status": "succeeded" | "failed", "metrics": {名称: 数值}}`；`metrics` 可选，取值为有限数值。训练 Recipe 把 checkpoint 写在 `$ENVLOOP_OUTPUT_DIR/checkpoints/` 下。

## 仓库布局 {#repository-layout}

`recipe.toml` 与 `entrypoint.sh` 放在同一目录，可以在仓库根目录：

```text
hello-recipe/
├── recipe.toml
├── entrypoint.sh
├── src/hello/train.py
└── README.md            # not packaged: not under [source].paths
```

也可以在大仓库的子目录中：

```text
ml-monorepo/
├── recipes/hello/recipe.toml
├── recipes/hello/entrypoint.sh
└── training/hello/train.py
```

1. **包内容。** 包根是 `recipe.toml` 与 `entrypoint.sh`；`[source].paths` 选中的文件保持相对仓库根的路径。上面的大仓库写 `paths = ["training/hello"]`，入口从 `$ENVLOOP_RECIPE_ROOT/training/hello/train.py` 运行代码。
2. **选择文件。** `paths` 列出文件或目录；`exclude` 只能列出已选中的确切文件。被 Git 忽略的文件和未选中的文件不会打包。
3. **限制。** 只接受普通文件，不含符号链接或 submodule；最多 1000 个文件，单个文件 512 MiB，总计 1 GiB；路径段只用字母、数字、`_`、`.`、`-`，且不以 `.` 开头。
4. **需要 Git。** CLI 发布的是一个 commit，所以目录必须在至少有一个 commit 的 Git 仓库中。普通目录先 `git init` 并提交一次即可，不需要 remote。

### Python 依赖 {#dependencies}

包里只有你的文件。代码可以通过两种方式使用第三方包。

1. **使用 Runner 镜像中的包。** `envloop/train` 运行在公开的 PyTorch CUDA runtime 镜像中，带 Python、PyTorch 和 pip；[dry run](#run) 的 `params.image` 显示确切镜像。要使用已装好所需包的其他公开镜像，设置 `params.image`。
2. **在 `entrypoint.sh` 中安装。** 把固定版本的 requirements 文件提交在 `[source].paths` 下，启动代码前安装：

```bash
python3 -m pip install --user --no-cache-dir -r "$ENVLOOP_RECIPE_ROOT/src/requirements.txt"
```

1. **网络。** 安装需要出站访问，由 Runner 决定；`envloop/train` 允许（`[sandbox] allow_internet = true`）。Runner 不允许联网时安装会失败。
2. **安装位置。** `--user` 安装到 `$HOME`，每个 Trial 中 `$HOME` 都可写；镜像自带的 site-packages 可能只读，Trial 也不一定以 root 运行。镜像的 Python 拒绝用户安装时，改在 `$HOME` 下创建虚拟环境。
3. **时间。** 安装时间计入 Trial 的 `params.timeout_seconds`。
4. **没有缓存。** Trial 之间、Job 之间都不保留安装结果，每个 Trial 都会重新安装；用 `==` 固定版本，保证每个 Trial 得到相同的包。

## 完整示例 {#example}

这个示例用一个 Dataset 输入训练一个替身模型，只使用 Python 标准库。

```toml title="recipe.toml"
schema_version = "envloop.recipe/v3"

[recipe]
name = "example-org/hello-recipe"
types = ["train"]

[runner]
name = "envloop/train"
abi = "envloop.recipe/1"

[source]
paths = ["src"]

[inputs.train_dataset]
kind = "dataset"
required = true

[params]
run_name = { type = "string", required = true, description = "Label written to result.json" }
max_steps = { type = "integer", default = 10, minimum = 1, maximum = 1000 }
seed = { type = "integer", default = 42, locked = true }

[params.optimizer]
type = "object"

[params.optimizer.properties.learning_rate]
type = "number"
default = 0.01
minimum = 0
maximum = 1

[params.optimizer.properties.warmup_steps]
type = "integer"
default = 0
minimum = 0
```

1. **`[recipe]`。** `name` 是 Recipe URI 的 `NAMESPACE/NAME`；`types` 列出支持的 Job 类型：`bench`、`sandbox`、`train`、`inference`。
2. **`[runner]`。** 适配的 Runner 与 Recipe ABI；`abi` 固定为 `envloop.recipe/1`。
3. **`[source]`。** `paths` 选择打包的代码。`repository` 可选：只在本地的仓库省略它（如本例），GitHub 仓库写 `repository = "https://github.com/OWNER/REPO"`。它只作为来源记录，平台不会访问。commit 来自发布时选定的 revision，不写在这个文件里。
4. **`[inputs.SLOT]`。** `kind` 为 `dataset`、`checkpoint` 或 `artifact`；`train_dataset`、`eval_dataset` 是 Dataset，`checkpoint`、`resume_from_checkpoint` 是 Checkpoint。
5. **`[params]`。** 每个参数写 `type`，可选 `default`、`required`、`description`、`enum`、`minimum`、`maximum`、`locked`。`required = true` 的参数没有默认值，每个 Job 都必须给出；`locked` 的参数保持默认值。`object` 参数在 `properties` 下列出字段，除非写 `additional_properties = true`，否则不接受其他字段。
6. **保留名称。** 标准参数 `image`、`command`、`timeout_seconds`、`max_retries` 归平台，不能声明。Runner 也声明了同名参数时，Recipe 只能收窄：类型相同、范围更紧、`enum` 为子集，并保留 Runner 的锁定与必填；否则返回 `RECIPE_PARAM_CONFLICT`。`envloop/train` 只声明标准参数。
7. **可选表。** `[outputs] files` 列出 Recipe 在 `$ENVLOOP_OUTPUT_DIR` 下写的其他文件；`[dependencies.SLOT]` 用 `uri` 与 `manifest_sha256` 固定另一个已发布的 Recipe。

```bash title="entrypoint.sh"
#!/usr/bin/env bash
# The Runner's main.sh runs this file as: bash "$ENVLOOP_RECIPE_ROOT/entrypoint.sh"
set -euo pipefail

for name in ENVLOOP_JOB_FILE ENVLOOP_PARAMS_FILE ENVLOOP_INPUTS_FILE; do
  [[ -r "${!name:-}" ]] || { echo "missing handoff file $name" >&2; exit 64; }
done
[[ -d "${ENVLOOP_OUTPUT_DIR:-}" ]] || { echo "missing ENVLOOP_OUTPUT_DIR" >&2; exit 64; }

# The package is read-only; put the packaged src/ directory on the import path.
export PYTHONPATH="$ENVLOOP_RECIPE_ROOT/src${PYTHONPATH:+:$PYTHONPATH}"
exec python3 -m hello.train
```

```python title="src/hello/train.py"
"""A minimal training loop: read the EnvLoop handoff files, train, write result.json."""
import json
import os
import random
from pathlib import Path


def read(variable):
    return json.loads(Path(os.environ[variable]).read_text())


def main():
    job = read("ENVLOOP_JOB_FILE")
    params = read("ENVLOOP_PARAMS_FILE")
    inputs = read("ENVLOOP_INPUTS_FILE")
    output = Path(os.environ["ENVLOOP_OUTPUT_DIR"])

    dataset = Path(inputs["train_dataset"]["path"])
    examples = sum(1 for path in dataset.rglob("*") if path.is_file())
    print(f"{job['type']} trial {job['trial_id']}: {examples} dataset files", flush=True)

    random.seed(params["seed"])
    optimizer = params["optimizer"]
    loss = 1.0
    for step in range(1, params["max_steps"] + 1):
        rate = optimizer["learning_rate"] * min(1.0, step / max(1, optimizer["warmup_steps"]))
        loss *= 1 - rate * random.random()  # stand-in for a real training step
        print(f"step {step} loss {loss:.6f}", flush=True)

    result = {"status": "succeeded", "metrics": {"loss": loss, "steps": params["max_steps"]}}
    (output / "result.json").write_text(json.dumps(result))
    print(f"{params['run_name']}: done", flush=True)


if __name__ == "__main__":
    main()
```

## 发布 {#publish}

先提交文件，预览后再发布：

```bash
git add recipe.toml entrypoint.sh src
git commit -m "Add the hello Recipe"
el recipe create --directory . --revision FULL_COMMIT --wait --json
```

命令返回 `{asset, operation}`。加 `--wait` 后从就绪投影读取 `asset.uri`、`asset.manifest_sha256`；不等待时保留 `operation.operation_id` 观察同一次发布。`--revision` 必须是完整不可变源码 commit。Recipe 内容摘要与源码 commit 不同，内容变化产生新的不可变身份。客户端只从本地仓库打包已提交的 `recipe.toml`、`entrypoint.sh` 和声明源码，平台不克隆私有来源。

SDK 使用 `client.recipes.create(directory=".", revision="FULL_COMMIT", wait=True)`。新名称默认 private，`--visibility internal` 共享到工作空间，public 变更需要平台管理员。见 [Recipes](recipes.md#visibility)。

## 在 Train Job 中运行 {#run}

把 Job spec 保存为 `job.json`，把占位符换成 Runner 的完整 commit、已发布 Recipe 的摘要和你自己的 Dataset：

```json
{
  "schema": "envloop.job/v2",
  "type": "train",
  "runner": "envloop/train@<runner-commit>",
  "recipe": "example-org/hello-recipe@<recipe-sha256>",
  "inputs": {
    "train_dataset": {"uri": "envloop://datasets/example-org/messages@1", "config": "default", "split": "train"}
  },
  "params": {"run_name": "first-run", "max_steps": 20, "optimizer": {"learning_rate": 0.05}},
  "resources": {"gpus": 1, "gpu_type": "H100"}
}
```

1. **`runner`。** `NAMESPACE/NAME@REVISION`；分支或 tag 会冻结为完整 commit。该 Runner Revision 必须声明 `[recipe] abi = "envloop.recipe/1"`，且 types 包含 `train`；可以用 `el runner list --json` 查找。
2. **`recipe`。** `NAMESPACE/NAME@<recipe-sha256>`，摘要即回执中的 `manifest_sha256`；只接受摘要。
3. **`params`。** Runner 与 Recipe 的参数共用一个命名空间，每个键必须由 Runner 或 Recipe 声明。对象参数按字段合并，所以这里 `optimizer.warmup_steps` 保留 Recipe 的默认值。标准参数 `image`、`command`、`timeout_seconds`、`max_retries` 也写在这里。Trial 从 `ENVLOOP_PARAMS_FILE` 读取合并后的非标准参数。
4. **`inputs`。** Dataset 槽位写 `{uri, config, split}`。平台解析内容摘要并检查你是否可读；Trial 从 `ENVLOOP_INPUTS_FILE` 读取该槽位。
5. **`resources`。** 每个 Trial 的需求：`cpus`、`memory_mb`、`storage_mb`、`gpus`、`gpu_type`、`shm_mb`；未写的取 Runner 的值。

### 预览解析结果

`POST /v1/jobs/resolve` 合并请求但不创建 Job。`overrides` 是可选的部分 spec，用于单次改动，不能包含 `schema`、`type` 或 `profile`。

```bash
jq -n --slurpfile spec job.json '{spec: $spec[0], overrides: {params: {max_steps: 50}}}' |
  curl --fail-with-body --silent --show-error https://api.envloop.ai/v1/jobs/resolve \
    -H "Authorization: Bearer $ENVLOOP_API_KEY" \
    -H "X-Workspace-ID: $ENVLOOP_WORKSPACE_ID" -H "X-Project-ID: $ENVLOOP_PROJECT_ID" \
    -H "Content-Type: application/json" --data @-
```

响应（节选）列出每个合并后的值及其来源层：

```json
{
  "schema": "envloop.resolved-job/v1",
  "spec": {
    "runner": "envloop/train@<runner-commit>",
    "recipe": "example-org/hello-recipe@<recipe-sha256>",
    "params": {
      "run_name": "first-run", "max_steps": 50, "seed": 42,
      "optimizer": {"learning_rate": 0.05, "warmup_steps": 0},
      "image": "<runner-image>", "command": "bash main.sh", "timeout_seconds": 3600, "max_retries": 0
    },
    "repeat": 1
  },
  "field_sources": {
    "params.run_name": "spec",
    "params.max_steps": "overrides",
    "params.seed": "recipe",
    "params.optimizer.learning_rate": "spec",
    "params.optimizer.warmup_steps": "recipe",
    "params.image": "runner",
    "params.max_retries": "platform"
  },
  "warnings": []
}
```

各层优先级从高到低：`overrides`、`profile`（spec 引用的 named Profile）、`spec`、`recipe`（`recipe.toml` 的默认值）、`runner`（Runner 的默认值）、`platform`（其他层都没有设置的兜底值，如 `repeat = 1`）。任何层都没有给出的必填参数返回 `RECIPE_PARAM_REQUIRED` 或 `RUNNER_PARAM_REQUIRED`，不会被补上默认值。

### 提交

把同样的内容加上 `request_id` 发送到 `POST /v1/jobs`：

```bash
jq -n --slurpfile spec job.json '{request_id: "hello-recipe-1", spec: $spec[0]}' |
  curl --fail-with-body --silent --show-error https://api.envloop.ai/v1/jobs \
    -H "Authorization: Bearer $ENVLOOP_API_KEY" \
    -H "X-Workspace-ID: $ENVLOOP_WORKSPACE_ID" -H "X-Project-ID: $ENVLOOP_PROJECT_ID" \
    -H "Content-Type: application/json" --data @-
```

`el job submit` 与 SDK 目前还不发送 `envloop.job/v2` 请求，请使用 HTTP API。用 `el job get JOB_ID`、`el job log JOB_ID --follow` 与 `el job result JOB_ID` 查看 Job。提交结果不确定时，用相同的 `request_id` 和相同内容重试。

## 常见错误 {#errors}

| 错误码 | 原因 | 处理 |
|---|---|---|
| `RECIPE_DECLARATION_NOT_FOUND` | 该 revision 的 `--directory` 中没有 `recipe.toml` | 提交它，或让 `--directory` 指向它所在的目录 |
| `RECIPE_ENTRYPOINT_NOT_FOUND` | `recipe.toml` 旁边没有 `entrypoint.sh` | 在同一目录提交 `entrypoint.sh` |
| `RECIPE_PACKAGE_UNCOMMITTED` | 打包路径与分支或 tag 不一致 | 提交或移除改动，或传完整 commit |
| `RECIPE_REVISION_UNRESOLVED` | 目录不在有 commit 的 Git 仓库中，或 `--revision` 不是本地分支、tag 或 commit | `git init` 并提交，fetch 或创建该 revision，或传完整 commit |
| `RECIPE_PACKAGE_SCHEMA_RETIRED` | `recipe.toml` 使用已停用的 `envloop.recipe-publication/v3` | 改写为 `envloop.recipe/v3` 并增加 `entrypoint.sh` |
| `RECIPE_SCHEMA_UNSUPPORTED` | 缺少 `schema_version` 或取值不同 | 写 `schema_version = "envloop.recipe/v3"` |
| `RECIPE_ABI_UNSUPPORTED` | `[runner] abi` 不是 `envloop.recipe/1` | 写 `abi = "envloop.recipe/1"` |
| `RECIPE_DECLARATION_INVALID` | 未知的表或键，或 `source.repository` 不是 `https://github.com/OWNER/REPO` | 只使用上文的表；省略 `repository` 或使用 GitHub 仓库地址 |
| `RECIPE_PARAMS_INVALID` | 参数声明无效或使用了保留名称 | 修正声明；与标准参数同名的参数改名 |
| `RECIPE_PATH_NOT_FOUND` | `paths` 某项没有匹配的文件，或 `exclude` 列出了未选中的文件 | 修正路径 |
| `RECIPE_DECLARATION_CONFLICT` | `paths` 会把另一个文件放到包根的 `recipe.toml` 或 `entrypoint.sh` | 缩小 `paths` 或排除该文件 |
| `RECIPE_FILE_UNSUPPORTED` | 选中的路径是符号链接或 submodule | 从 `paths` 中移除或排除 |
| `RECIPE_PACKAGE_TOO_LARGE` | 超过 1000 个文件、单个文件 512 MiB 或总计 1 GiB | 缩小 `paths` |
| `RECIPE_NAME_MISMATCH` | 上传的 URI 名称与 `[recipe] name` 不同 | 用 `--directory` 发布，让 URI 由 `recipe.toml` 推出 |
| `RECIPE_INDEX_INVALID` | 上传的文件与 content index 不一致 | 用 `--directory` 发布，不要手写 manifest |
| `RECIPE_READBACK_MISMATCH` | 目录没有把刚发布的 Recipe 返回为 ready | 重试前用 `el recipe get URI` 查看 |
| `RECIPE_ABI_MISMATCH` | Runner Revision 没有实现 `envloop.recipe/1` | 固定一个实现了它的 Runner Revision |
| `RECIPE_TYPE_UNSUPPORTED` | Job 类型不同时在 Runner 与 Recipe 的 types 中 | 提交支持的类型，或在 `[recipe] types` 中加入 |
| `RECIPE_PARAM_REQUIRED` | 必填的 Recipe 参数在所有层中都没有值 | 在 `params` 中给出 |
