> ## Documentation Index
> Fetch the complete documentation index at: https://docs.qoder.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 创建 Batch

> 基于 JSONL 输入文件创建异步批量任务。

`POST /api/v1/forward/batches`

Forward 校验输入文件与 JSONL 行格式后，在闲时窗口内自动调度执行，完成后生成 output.jsonl 和 error.jsonl 供下载。

## 请求头

| Header          | 是否必填 | 说明                 |
| --------------- | ---- | ------------------ |
| Authorization   | 是    | `Bearer <PAT>`     |
| Content-Type    | 是    | `application/json` |
| Idempotency-Key | 否    | 有副作用请求可选的幂等键。      |

## 前置准备：上传输入文件

创建 Batch 需要先准备 JSONL 格式的输入文件，然后通过 CAS Files API 上传获得 `file_id`。

**JSONL 格式**：每行一个 JSON 对象，代表一个独立任务：

```jsonl theme={null}
{"custom_id": "task-001", "template_id": "tmpl_example001", "identity_id": "idn_example001", "body": {"input": "你好"}}
{"custom_id": "task-002", "template_id": "tmpl_example001", "identity_id": "idn_example001", "body": {"input": "帮我写一首关于夏天的短诗"}}
```

| 字段            | 类型     | 必填 | 说明                                                            |
| ------------- | ------ | -- | ------------------------------------------------------------- |
| `custom_id`   | string | 是  | 调用方自定义标识，单 Batch 内唯一，用于结果文件行对应。                               |
| `template_id` | string | 是  | Forward Template ID，指定执行模板。                                   |
| `identity_id` | string | 是  | Forward Identity ID，指定执行身份。                                   |
| `body`        | object | 是  | 传给 Session 的请求体，结构取决于 Template 定义。常见格式：`{"input": "用户输入内容"}`。 |

**上传文件**：

```bash theme={null}
curl -X POST 'https://api.qoder.com/api/v1/cloud/files' \
  -H "Authorization: Bearer $QODER_PAT" \
  -F "file=@batch_input.jsonl" \
  -F "purpose=session_resource"
```

<Note>
  `purpose` 必须为 `session_resource`，否则后续下载可能失败。
</Note>

返回的 `id` 即为创建 Batch 请求中的 `input_file_id`。

## 请求体参数

| 参数                 | 类型     | 是否必填 | 说明                                                                                  |
| ------------------ | ------ | ---- | ----------------------------------------------------------------------------------- |
| input\_file\_id    | string | 是    | 通过 Files API 上传的 JSONL 文件 ID。                                                       |
| completion\_window | string | 是    | 完成窗口：`24h`、`48h`、`72h`。超时后 Batch 自动进入 `expired` 状态。                                 |
| metadata           | object | 否    | 调用方业务元数据，最多 16 个 key；value 可为任意 JSON 类型；整体序列化后 ≤ 2KB，key ≤ 64 字符，且不得包含 NUL（U+0000）。 |

## 示例请求

```bash theme={null}
curl -s -X POST 'https://api.qoder.com/api/v1/forward/batches' \
  -H "Authorization: Bearer $QODER_PAT" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: idem_batch_001" \
  -d '{
  "input_file_id": "file_input001",
  "completion_window": "24h",
  "metadata": {
    "source": "data_pipeline",
    "job_id": "12345"
  }
}'
```

## 示例响应

**HTTP 200 OK**

```json theme={null}
{
  "id": "batch_example001",
  "object": "batch",
  "status": "validating",
  "input_file_id": "file_input001",
  "completion_window": "24h",
  "created_at": "2026-07-07T07:25:01Z",
  "expires_at": "2026-07-08T07:25:01Z",
  "request_counts": {
    "total": 0,
    "pending": 0,
    "running": 0,
    "completed": 0,
    "failed": 0,
    "cancelled": 0,
    "expired": 0
  },
  "usage": null
}
```

创建成功后 Batch 立即进入 `validating`，校验通过转 `queued`；`output_file_id` / `error_file_id` 在任务终态后才出现，创建响应中省略。

## 响应字段

| 字段                 | 类型          | 说明                                       |
| ------------------ | ----------- | ---------------------------------------- |
| id                 | string      | Batch ID，前缀 `batch_`。                    |
| object             | string      | 固定为 `batch`。                             |
| status             | string      | Batch 状态，见状态说明。                          |
| input\_file\_id    | string      | 输入 JSONL 文件 ID。                          |
| completion\_window | string      | 完成窗口：`24h`、`48h`、`72h`。                  |
| created\_at        | string      | 创建时间，RFC 3339。                           |
| expires\_at        | string      | 过期时间，`created_at` + `completion_window`。 |
| request\_counts    | object      | 任务计数聚合。                                  |
| usage              | object/null | 预留字段，v1 固定为 `null`。                      |
| metadata           | object      | 调用方业务元数据。                                |

### Batch 状态

| 状态           | 说明                      | 类型  |
| ------------ | ----------------------- | --- |
| `validating` | 正在校验输入文件和 JSONL 行格式。    | 非终态 |
| `queued`     | 校验通过，等待闲时窗口激活。          | 非终态 |
| `processing` | 正在执行任务。                 | 非终态 |
| `cancelling` | 取消中，等待 running task 结束。 | 非终态 |
| `expiring`   | 过期中，等待 running task 结束。 | 非终态 |
| `finalizing` | 正在生成输出文件。               | 非终态 |
| `completed`  | 所有任务执行完毕，输出文件已生成。       | 终态  |
| `failed`     | 文件校验失败或不可恢复的系统错误。       | 终态  |
| `cancelled`  | 用户取消完成。                 | 终态  |
| `expired`    | `completion_window` 到期。 | 终态  |

### Request Counts

| 字段        | 类型      | 说明              |
| --------- | ------- | --------------- |
| total     | integer | 总行数（含校验失败行）。    |
| pending   | integer | 等待执行的行数。        |
| running   | integer | 正在执行的行数。        |
| completed | integer | 执行成功的行数。        |
| failed    | integer | 永久失败的行数（含校验失败）。 |
| cancelled | integer | 因取消而终止的行数。      |
| expired   | integer | 因过期而终止的行数。      |

`total = pending + running + completed + failed + cancelled + expired` 始终成立。

## 校验规则

创建 Batch 阶段拦截以下错误，不入队执行：

* JSON 解析失败 → 该行标记 `failed`
* 必填字段缺失 → 该行标记 `failed`
* `custom_id` 重复 → 该行标记 `failed`
* `always_ask`/`always_deny` 工具权限策略 → 该行标记 `failed`（无人值守场景不允许）

校验失败的行不阻塞其他行，统一写入 `error.jsonl`。

## 错误码

| HTTP | Type                    | Code                      | 触发条件                                                     |
| ---- | ----------------------- | ------------------------- | -------------------------------------------------------- |
| 400  | `invalid_request_error` | `invalid_request`         | `input_file_id` 缺失、`completion_window` 非法、`metadata` 超限。 |
| 429  | `rate_limit_error`      | `rate_limit_exceeded`     | 用户未完成 Batch 数量达到上限。                                      |
| 401  | `authentication_error`  | `authentication_required` | PAT 无效或已过期。                                              |

## 注意事项

* 单批次最大 10,000 行 JSONL。
* 全局并发上限 50 个 task。
* 调度在闲时窗口（默认 22:00\~08:00，后台可配）内执行。
* 客户端创建 Batch 后，应通过 `GET /api/v1/forward/batches/{batch_id}` 轮询到终态。

## 相关

<CardGroup cols={2}>
  <Card title="查询 Batch 详情" icon="file-text" href="/zh/cloud-agents/api/forward/batches/get" />

  <Card title="取消 Batch" icon="xmark" href="/zh/cloud-agents/api/forward/batches/cancel" />
</CardGroup>
