Skip to content

POST /v1/batches 是 Kimi Batch API 的入口接口,用于提交批量推理任务。需先上传 purpose=batch 的 JSONL 文件,再用返回的 file_id 创建批任务,指定处理时间窗口(12h~7d)。本文含完整参数说明和 Python/TS 代码示例。

创建批处理任务

接口信息

POST https://api.moonshot.cn/v1/batches
Authorization: Bearer {MOONSHOT_API_KEY}
Content-Type: application/json

详细使用流程参考 Batch API 完整指南


请求参数

参数类型必填说明
input_file_idstring上传 JSONL 文件后返回的文件 ID
endpointstring目前仅支持 "/v1/chat/completions"
completion_windowstring任务处理时间窗口,支持 12h1d3d,最小 12h,最大 7d
metadataobject自定义键值对,最多 16 个,key ≤ 64 字符,value ≤ 512 字符

请求示例

typescript
const response = await fetch("https://api.moonshot.cn/v1/batches", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MOONSHOT_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    input_file_id: "file-abc123",
    endpoint: "/v1/chat/completions",
    completion_window: "24h",
    metadata: {
      job_name: "daily-analysis",
      environment: "production",
    },
  }),
});

const batch = await response.json();
console.log("批任务 ID:", batch.id);
console.log("状态:", batch.status);
python
import os
import requests

response = requests.post(
    "https://api.moonshot.cn/v1/batches",
    headers={
        "Authorization": f"Bearer {os.environ['MOONSHOT_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "input_file_id": "file-abc123",
        "endpoint": "/v1/chat/completions",
        "completion_window": "24h",
    },
)

batch = response.json()
print(f"批任务 ID: {batch['id']}, 状态: {batch['status']}")

响应(BatchObject)

字段类型说明
idstring批任务唯一 ID
objectstring固定值 "batch"
statusstring任务状态,见下表
input_file_idstring输入文件 ID
output_file_idstring结果文件 ID(完成后可用)
error_file_idstring失败请求的错误文件 ID
request_countsobject{completed, failed, total}
created_atint创建时间(Unix 时间戳)

任务状态

状态说明
validating校验输入文件中
in_progress正在执行
finalizing准备结果中
completed已完成,可下载结果
failed校验失败
expired超出 completion_window 时间
cancelling取消中
cancelled已取消

常见问题

Q: JSONL 输入文件格式是什么?

A: 每行一个 JSON 对象,包含 custom_id(自定义标识)和 body(完整的 chat completions 请求体)。详见 Batch API 指南

Q: completion_window 填写多少合适?

A: 批处理任务使用低优先级队列,通常比在线 API 慢。建议给出至少 2 倍于预估执行时间的余量,常规任务用 24h,大批量任务用 3d

Q: 创建后可以修改 completion_window 吗?

A: 不可以。如需调整,只能取消后重新创建任务。